@nifrajs/cli 5.5.0 → 5.6.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +172 -0
- package/dist/cdn-check.d.ts +7 -6
- package/dist/cdn-check.d.ts.map +1 -1
- package/dist/cdn-check.js +13 -1
- package/dist/cdn-check.js.map +1 -1
- package/dist/check-diagnostics.d.ts.map +1 -1
- package/dist/check-diagnostics.js +5 -3
- package/dist/check-diagnostics.js.map +1 -1
- package/dist/check-scan.d.ts.map +1 -1
- package/dist/check-scan.js +29 -2
- package/dist/check-scan.js.map +1 -1
- package/dist/cli.d.ts.map +1 -1
- package/dist/cli.js +14 -5
- package/dist/cli.js.map +1 -1
- package/dist/command-catalog.d.ts +14 -1
- package/dist/command-catalog.d.ts.map +1 -1
- package/dist/command-catalog.js +93 -0
- package/dist/command-catalog.js.map +1 -1
- package/dist/doctor.d.ts +9 -1
- package/dist/doctor.d.ts.map +1 -1
- package/dist/doctor.js +52 -0
- package/dist/doctor.js.map +1 -1
- package/dist/fix-recipes.d.ts.map +1 -1
- package/dist/fix-recipes.js +27 -0
- package/dist/fix-recipes.js.map +1 -1
- package/dist/frontend-guidance.d.ts +1 -1
- package/dist/frontend-guidance.d.ts.map +1 -1
- package/dist/frontend-guidance.js +17 -8
- package/dist/frontend-guidance.js.map +1 -1
- package/dist/internal/source-facts.d.ts +2 -1
- package/dist/internal/source-facts.d.ts.map +1 -1
- package/dist/internal/source-facts.js +17 -11
- package/dist/internal/source-facts.js.map +1 -1
- package/dist/introspect.js +1 -1
- package/dist/introspect.js.map +1 -1
- package/dist/load.d.ts +4 -1
- package/dist/load.d.ts.map +1 -1
- package/dist/load.js +8 -0
- package/dist/load.js.map +1 -1
- package/dist/mcp-exec.d.ts.map +1 -1
- package/dist/mcp-exec.js +57 -3
- package/dist/mcp-exec.js.map +1 -1
- package/dist/mcp-http.d.ts +2 -1
- package/dist/mcp-http.d.ts.map +1 -1
- package/dist/mcp-http.js +3 -2
- package/dist/mcp-http.js.map +1 -1
- package/dist/mcp-tool-meta.d.ts +21 -0
- package/dist/mcp-tool-meta.d.ts.map +1 -0
- package/dist/mcp-tool-meta.js +246 -0
- package/dist/mcp-tool-meta.js.map +1 -0
- package/dist/mcp.d.ts +3 -2
- package/dist/mcp.d.ts.map +1 -1
- package/dist/mcp.js +36 -98
- package/dist/mcp.js.map +1 -1
- package/dist/output-schemas.d.ts +8 -0
- package/dist/output-schemas.d.ts.map +1 -1
- package/dist/output-schemas.js +14 -0
- package/dist/output-schemas.js.map +1 -1
- package/dist/ppr-read-fix.d.ts +8 -0
- package/dist/ppr-read-fix.d.ts.map +1 -0
- package/dist/ppr-read-fix.js +356 -0
- package/dist/ppr-read-fix.js.map +1 -0
- package/dist/recipes/5.6.0.d.ts +10 -0
- package/dist/recipes/5.6.0.d.ts.map +1 -0
- package/dist/recipes/5.6.0.js +68 -0
- package/dist/recipes/5.6.0.js.map +1 -0
- package/dist/recipes/index.d.ts.map +1 -1
- package/dist/recipes/index.js +2 -0
- package/dist/recipes/index.js.map +1 -1
- package/dist/review.d.ts.map +1 -1
- package/dist/review.js +7 -2
- package/dist/review.js.map +1 -1
- package/dist/rules/codes.d.ts +8 -3
- package/dist/rules/codes.d.ts.map +1 -1
- package/dist/rules/codes.js +9 -4
- package/dist/rules/codes.js.map +1 -1
- package/dist/rules/explanations.d.ts.map +1 -1
- package/dist/rules/explanations.js +39 -13
- package/dist/rules/explanations.js.map +1 -1
- package/dist/rules/islands.d.ts +91 -0
- package/dist/rules/islands.d.ts.map +1 -1
- package/dist/rules/islands.js +757 -3
- package/dist/rules/islands.js.map +1 -1
- package/dist/rules/ppr.d.ts +16 -0
- package/dist/rules/ppr.d.ts.map +1 -0
- package/dist/rules/ppr.js +114 -0
- package/dist/rules/ppr.js.map +1 -0
- package/dist/rules/swap.d.ts +7 -0
- package/dist/rules/swap.d.ts.map +1 -0
- package/dist/rules/swap.js +338 -0
- package/dist/rules/swap.js.map +1 -0
- package/dist/scaffold-hole.d.ts +105 -0
- package/dist/scaffold-hole.d.ts.map +1 -0
- package/dist/scaffold-hole.js +688 -0
- package/dist/scaffold-hole.js.map +1 -0
- package/dist/scaffold.d.ts +5 -3
- package/dist/scaffold.d.ts.map +1 -1
- package/dist/scaffold.js +56 -46
- package/dist/scaffold.js.map +1 -1
- package/dist/verification-plan.d.ts.map +1 -1
- package/dist/verification-plan.js +12 -1
- package/dist/verification-plan.js.map +1 -1
- package/dist/web-app-options.d.ts +1 -1
- package/dist/web-app-options.d.ts.map +1 -1
- package/dist/web-app-options.js.map +1 -1
- package/docs/examples.json +63 -9
- package/docs/llms-full.txt +2070 -437
- package/docs/types.json +1300 -270
- package/package.json +11 -11
- package/src/cdn-check.ts +21 -7
- package/src/check-diagnostics.ts +5 -3
- package/src/check-scan.ts +34 -3
- package/src/cli.ts +14 -5
- package/src/command-catalog.ts +126 -0
- package/src/doctor.ts +44 -1
- package/src/fix-recipes.ts +28 -0
- package/src/frontend-guidance.ts +20 -8
- package/src/internal/source-facts.ts +27 -13
- package/src/introspect.ts +1 -1
- package/src/load.ts +13 -0
- package/src/mcp-exec.ts +74 -3
- package/src/mcp-http.ts +3 -2
- package/src/mcp-tool-meta.ts +268 -0
- package/src/mcp.ts +35 -99
- package/src/output-schemas.ts +28 -0
- package/src/ppr-read-fix.ts +426 -0
- package/src/recipes/5.6.0.ts +69 -0
- package/src/recipes/index.ts +2 -0
- package/src/review.ts +7 -2
- package/src/rules/codes.ts +9 -4
- package/src/rules/explanations.ts +39 -13
- package/src/rules/islands.ts +875 -3
- package/src/rules/ppr.ts +143 -0
- package/src/rules/swap.ts +402 -0
- package/src/scaffold-hole.ts +880 -0
- package/src/scaffold.ts +60 -49
- package/src/verification-plan.ts +20 -1
- package/src/web-app-options.ts +1 -0
- package/dist/rules/nano.d.ts +0 -6
- package/dist/rules/nano.d.ts.map +0 -1
- package/dist/rules/nano.js +0 -273
- package/dist/rules/nano.js.map +0 -1
- package/src/rules/nano.ts +0 -307
package/docs/llms-full.txt
CHANGED
|
@@ -221,10 +221,9 @@ implementation, secrets and database handles off the browser and use the same va
|
|
|
221
221
|
mutation API across the supported UI libraries.
|
|
222
222
|
|
|
223
223
|
The optional [server-components pipeline](/docs/server-components) adds
|
|
224
|
-
server-only views and state-preserving refresh. React uses native RSC/Flight; Vue, Svelte
|
|
225
|
-
and
|
|
226
|
-
|
|
227
|
-
Server functions remain the mutation API; native React `"use server"` actions
|
|
224
|
+
server-only views and state-preserving refresh. React uses native RSC/Flight; Vue, Svelte,
|
|
225
|
+
Solid and Preact use their native islands in validated server-rendered ranges. It shipped in
|
|
226
|
+
5.0.0, and all five adapters pass the same certification. Server functions remain the mutation API; native React `"use server"` actions
|
|
228
227
|
are unsupported.
|
|
229
228
|
|
|
230
229
|
### Also a standalone backend (vs. Hono & Elysia)
|
|
@@ -236,14 +235,14 @@ to full-stack later without a rewrite.
|
|
|
236
235
|
**Throughput - the realistic case.** Router micro-benchmarks flatter Hono (a single compiled
|
|
237
236
|
regex), but a real request also pays for middleware and validation,
|
|
238
237
|
context, and serialization. In the current matrix Nifra runs **level with Elysia on Bun** -
|
|
239
|
-
|
|
240
|
-
|
|
241
|
-
**level with Fastify on Node** (
|
|
242
|
-
|
|
243
|
-
and Express behind. On **Deno** it runs at
|
|
244
|
-
GET and
|
|
238
|
+
100% of Elysia on `GET /users/:id` and
|
|
239
|
+
102% on the validated `POST` - and
|
|
240
|
+
**level with Fastify on Node** (102% of Fastify on GET,
|
|
241
|
+
99% on the validated `POST`), with Elysia, Hono,
|
|
242
|
+
and Express behind. On **Deno** it runs at 98% of Elysia on
|
|
243
|
+
GET and 118% on the validated `POST`. In the realistic shape (security headers + CORS +
|
|
245
244
|
bearer auth + cookies + validated query/body + a ~2.4 KB JSON response, measured with
|
|
246
|
-
`oha`) Nifra runs at **
|
|
245
|
+
`oha`) Nifra runs at **104% of Elysia on GET and 104% on POST**. Treat benchmark
|
|
247
246
|
rows as same-run evidence, not a permanent law of nature.
|
|
248
247
|
|
|
249
248
|
-
|
|
@@ -727,6 +726,117 @@ an `_error` page the server renders reports an empty list.
|
|
|
727
726
|
`@nifrajs/web-<framework>/router`, as an array on React/Preact, a
|
|
728
727
|
`Ref` on Vue, and an accessor on Solid/Svelte.
|
|
729
728
|
|
|
729
|
+
### Opening a route in a modal
|
|
730
|
+
|
|
731
|
+
A photo grid can open `/photos/7` over the grid, while a shared link or a reload of
|
|
732
|
+
that URL shows the photo as its own page. A layout or page declares this with a boundary whose
|
|
733
|
+
mode is `{ intercept: "/photos/:id" }`, in its `boundaries` export.
|
|
734
|
+
On a client navigation from a page under that layout (or from that page) to a matching URL,
|
|
735
|
+
nifra fetches the target route's data with the usual request, so its middleware, gates
|
|
736
|
+
and loader all run. The current page stays mounted, the address bar shows the new URL, and the
|
|
737
|
+
target's loader data arrives as `boundaries.photo` with
|
|
738
|
+
`status: "ready"`. Until then the boundary's status is
|
|
739
|
+
`"unresolved"`.
|
|
740
|
+
|
|
741
|
+
```tsx
|
|
742
|
+
// routes/_layout.tsx - a link to /photos/:id from any page opens the photo over that page
|
|
743
|
+
import type { Boundary, BoundaryStates } from "@nifrajs/web"
|
|
744
|
+
// /client, not the root: the root carries the server, which a browser bundle must not load.
|
|
745
|
+
import { closeBoundary } from "@nifrajs/web/client"
|
|
746
|
+
import type { ReactNode } from "react"
|
|
747
|
+
import type { Route as Photo } from "./photos/+types/[id]"
|
|
748
|
+
|
|
749
|
+
// No load of its own: the modal shows the target page's loader data.
|
|
750
|
+
const photo: Boundary<Photo.LoaderData, ReactNode> = {
|
|
751
|
+
name: "photo",
|
|
752
|
+
mode: { intercept: "/photos/:id" },
|
|
753
|
+
render: (data) => <h2>{data.title}</h2>,
|
|
754
|
+
}
|
|
755
|
+
|
|
756
|
+
export const boundaries = [photo]
|
|
757
|
+
|
|
758
|
+
export default function Layout(props: { children?: ReactNode; boundaries?: BoundaryStates }) {
|
|
759
|
+
const open = props.boundaries?.photo
|
|
760
|
+
return (
|
|
761
|
+
<>
|
|
762
|
+
{props.children}
|
|
763
|
+
{open?.status === "ready" || open?.status === "error" ? (
|
|
764
|
+
// A form in here with no action posts to the photo's route, not the page's.
|
|
765
|
+
<dialog open data-nifra-boundary="photo">
|
|
766
|
+
{open.status === "ready" ? photo.render(open.data as Photo.LoaderData) : <p>Could not load.</p>}
|
|
767
|
+
<button type="button" onClick={() => closeBoundary("photo")}>
|
|
768
|
+
Close
|
|
769
|
+
</button>
|
|
770
|
+
</dialog>
|
|
771
|
+
) : null}
|
|
772
|
+
</>
|
|
773
|
+
)
|
|
774
|
+
}
|
|
775
|
+
```
|
|
776
|
+
|
|
777
|
+
-
|
|
778
|
+
The boundary has no `load`: its data is the target page's loader data, so
|
|
779
|
+
type it with that route's `LoaderData`. `routes/photos/[id].tsx`
|
|
780
|
+
stays an ordinary page.
|
|
781
|
+
|
|
782
|
+
-
|
|
783
|
+
Back closes the modal and forward reopens it. A link inside the modal to another matching
|
|
784
|
+
URL replaces its content, and back steps through each one. Navigating anywhere else closes
|
|
785
|
+
it.
|
|
786
|
+
|
|
787
|
+
-
|
|
788
|
+
A reload, a shared link, or a navigation from a page outside the declaring layout or page
|
|
789
|
+
renders the target as a full page. That includes coming back to the modal's URL from a
|
|
790
|
+
page that does not intercept it.
|
|
791
|
+
|
|
792
|
+
-
|
|
793
|
+
A target that answers with its own status, such as a `404` or
|
|
794
|
+
`401`, or that throws, never opens in the modal: the browser loads that URL as a
|
|
795
|
+
full page and gets that answer. A redirect is followed first, and opens in the modal only
|
|
796
|
+
when it lands on another matching URL.
|
|
797
|
+
|
|
798
|
+
-
|
|
799
|
+
`closeBoundary("photo")` from `@nifrajs/web/client` closes it: it
|
|
800
|
+
goes back through the entries the modal added, or replaces the modal's URL with the
|
|
801
|
+
page's when those entries are not in this tab's history (the modal was opened with
|
|
802
|
+
a replace navigation). It does nothing when that boundary holds no target.
|
|
803
|
+
|
|
804
|
+
-
|
|
805
|
+
While the modal is open, the route props and hooks describe the page underneath:
|
|
806
|
+
`useLocation`, `useSearch`, `useParams` and
|
|
807
|
+
`useMatches` report the page's path, query and params, while the address bar
|
|
808
|
+
shows the modal's URL.
|
|
809
|
+
|
|
810
|
+
-
|
|
811
|
+
Opening the modal keeps the page's scroll position and its
|
|
812
|
+
`actionData`, and closing it restores the
|
|
813
|
+
page's entry with its scroll. A link to the page's own URL is a normal navigation,
|
|
814
|
+
never an interception, and only one intercept boundary is open at a time: opening another
|
|
815
|
+
closes the first.
|
|
816
|
+
|
|
817
|
+
-
|
|
818
|
+
An action submitted while the modal is open revalidates both routes: the page reloads
|
|
819
|
+
under its own URL and the target under the modal's, each with its own cache entry.
|
|
820
|
+
With `revalidate: false`, only the paths the server names as changed reload.
|
|
821
|
+
`invalidate()` reloads both, and `invalidate(paths)` reloads the ones
|
|
822
|
+
listed. If the target answers a reload with a status or throws, the modal stays open and
|
|
823
|
+
the boundary's status becomes `"error"` with a generic error, so
|
|
824
|
+
none of that answer reaches the page.
|
|
825
|
+
|
|
826
|
+
-
|
|
827
|
+
A form with no `action` (or a submitter with no `formaction`), POST
|
|
828
|
+
or GET, submits to the route that owns it: the target's URL when the form sits inside an element with
|
|
829
|
+
`data-nifra-boundary="photo"`, otherwise the page's URL. A form
|
|
830
|
+
with an explicit action posts where it says. The result of an action posted to the
|
|
831
|
+
target arrives as `boundaries.photo.actionData`, and the page's own
|
|
832
|
+
`actionData` stays the page's. An action that redirects renders the
|
|
833
|
+
redirect's target as a full page, never in the modal.
|
|
834
|
+
|
|
835
|
+
-
|
|
836
|
+
The component renders the boundary itself: it reads `boundaries.<name>`
|
|
837
|
+
from its props and calls the boundary's `render` with the data. Every
|
|
838
|
+
adapter passes `boundaries` to the layouts and the page.
|
|
839
|
+
|
|
730
840
|
### Guarding navigation
|
|
731
841
|
|
|
732
842
|
A page with unsaved work shouldn't lose it to a stray click or the back button.
|
|
@@ -1499,6 +1609,19 @@ loader **revalidates** (no full reload); with JS disabled the native form POST r
|
|
|
1499
1609
|
- progressive enhancement, same code. What the action returns reaches the page as
|
|
1500
1610
|
`actionData`, bounded by `actionOutput`.
|
|
1501
1611
|
|
|
1612
|
+
A reload of the page on screen (an action's revalidation, `invalidate()`, a live
|
|
1613
|
+
refresh, a fetcher loading its path again) keeps every part of `data` and the
|
|
1614
|
+
layouts' data that it did not change as the same object, with one bound: an array none of
|
|
1615
|
+
whose first 32 elements is unchanged is replaced whole, so a reload that changed every row
|
|
1616
|
+
stops comparing early. A row kept this way keeps its DOM and component state: a Solid
|
|
1617
|
+
`<For>` keeps the row, a memoized React or Preact row
|
|
1618
|
+
and a Vue child component skip their render, and a Svelte or Solid effect on `data`
|
|
1619
|
+
runs again only when the reload changed it. Dates compare by time, rows with an
|
|
1620
|
+
`id` pair by it, and the built-in transport does not parse again a plain JSON
|
|
1621
|
+
response with the same text as the one on screen (a response with deferred parts is always
|
|
1622
|
+
parsed). A page whose code compares `data` with its value from before a reload exports
|
|
1623
|
+
`shareData = false` and gets fresh data on every reload.
|
|
1624
|
+
|
|
1502
1625
|
```ts
|
|
1503
1626
|
// routes/users/new.backend.ts - an action handles the route's POST.
|
|
1504
1627
|
import { t } from "@nifrajs/schema"
|
|
@@ -1613,7 +1736,8 @@ export async function loader() {
|
|
|
1613
1736
|
```
|
|
1614
1737
|
|
|
1615
1738
|
For optimistic UI, concurrent fetchers, and a keyed query cache, the same primitives compose
|
|
1616
|
-
on
|
|
1739
|
+
on all five adapters: see [fetchers](/docs/mutations) and
|
|
1740
|
+
[the query cache](/docs/query).
|
|
1617
1741
|
|
|
1618
1742
|
## Nifra - Server functions
|
|
1619
1743
|
|
|
@@ -1695,7 +1819,11 @@ in the module that is not a server function is ignored rather than mounted.
|
|
|
1695
1819
|
|
|
1696
1820
|
One thing worth knowing: the namespace you pass here and the `*.fn.ts` filename are
|
|
1697
1821
|
not statically checked against each other. If they disagree the call 404s, and the generated
|
|
1698
|
-
stub names the mismatch - but the compiler will not catch it for you.
|
|
1822
|
+
stub names the mismatch - but the compiler will not catch it for you. The build fails on a
|
|
1823
|
+
filename that is not a valid namespace (`todoItems.fn.ts`; use
|
|
1824
|
+
`todo-items.fn.ts`). Two files with one basename (`admin/todos.fn.ts`
|
|
1825
|
+
and `user/todos.fn.ts`) share the namespace: both mount, and an export name they
|
|
1826
|
+
both use fails at boot as a duplicate route.
|
|
1699
1827
|
|
|
1700
1828
|
### Calling it
|
|
1701
1829
|
|
|
@@ -1838,7 +1966,8 @@ function toggle() {
|
|
|
1838
1966
|
|
|
1839
1967
|
### Concurrent fetchers
|
|
1840
1968
|
|
|
1841
|
-
`useFetcher(key)` (React) / `createFetcher(key)`
|
|
1969
|
+
`useFetcher(key)` (React, Preact, Vue, Svelte) / `createFetcher(key)`
|
|
1970
|
+
(Solid), from each adapter's `/fetcher` entry, is an
|
|
1842
1971
|
independent submission state machine - perfect for row-level actions or side-channel loads
|
|
1843
1972
|
that shouldn't block navigation. `useFetchers()` exposes the live collection for
|
|
1844
1973
|
global pending indicators. After a mutation, targeted revalidation refreshes just the
|
|
@@ -1987,10 +2116,10 @@ On a server you run yourself, `nifra build --target bun` or `node`
|
|
|
1987
2116
|
prerenders the same routes into `_prerendered/` beside `server.js`, and
|
|
1988
2117
|
the server answers each from its file instead of rendering it. The file is served from the
|
|
1989
2118
|
page route, so `use` middleware still runs first and a gate in front of the page
|
|
1990
|
-
still applies. A request with a query string, a navigation data request, or a
|
|
1991
|
-
visitor renders on demand. So does a page whose build-time render set a cookie, was private or
|
|
1992
|
-
`no-store`, or varied on a request header
|
|
1993
|
-
`nonce`. The Vite pipeline and the edge targets render every page on demand.
|
|
2119
|
+
still applies. A request with a query string, a navigation data request, a slot swap, or a
|
|
2120
|
+
draft-mode visitor renders on demand. So does a page whose build-time render set a cookie, was private or
|
|
2121
|
+
`no-store`, or varied on a request header other than `Accept-Encoding`
|
|
2122
|
+
and nifra's own data and slot-swap headers, and every page of an app with a `nonce`. The Vite pipeline and the edge targets render every page on demand.
|
|
1994
2123
|
|
|
1995
2124
|
### ISR - cache with stale-while-revalidate
|
|
1996
2125
|
|
|
@@ -2045,6 +2174,26 @@ broken. A store that also implements `fence()` keeps a purge that lands while a
|
|
|
2045
2174
|
page renders from being undone when that render stores the page it built from the old data;
|
|
2046
2175
|
both built-in stores do.
|
|
2047
2176
|
|
|
2177
|
+
Workers KV is eventually consistent: a purge is usually seen at once where it was made and
|
|
2178
|
+
reaches other locations as their copies expire, which Cloudflare puts at up to 60 seconds or
|
|
2179
|
+
more. Until then those locations serve the old page. A page one of them rebuilt from the old
|
|
2180
|
+
data in that time reads as a miss once the purge arrives, so a purge by path or by tag is
|
|
2181
|
+
delayed by propagation, never lost. For a purge that every location honors at the same
|
|
2182
|
+
moment, use a store with a strongly consistent backend, such as a Durable Object.
|
|
2183
|
+
|
|
2184
|
+
Anything else that can write a shared store - another service on the same KV namespace, a
|
|
2185
|
+
leaked token - could put a page with its own script in front of every visitor. So over any
|
|
2186
|
+
store but `MemoryCacheStore`, `withISR` needs a
|
|
2187
|
+
`storeSecret` (the same in every process, at least 32 characters, and generated
|
|
2188
|
+
at random - `openssl rand -hex 32` - since a guessable one can be found from any
|
|
2189
|
+
signed page) and refuses to
|
|
2190
|
+
start without one. Each page is stored with an HMAC-SHA-256 over its key, body, status,
|
|
2191
|
+
headers, tags and freshness, and a page whose signature is missing or wrong is a miss: it
|
|
2192
|
+
renders again and the signed render replaces it. A new secret only empties the cache. The
|
|
2193
|
+
signature cannot stop a store writer from deleting pages or putting back an older page the
|
|
2194
|
+
app stored for the same URL. That page keeps its age: still within its freshness window, it
|
|
2195
|
+
is a hit until the window ends; past it, it serves stale and regenerates.
|
|
2196
|
+
|
|
2048
2197
|
```ts
|
|
2049
2198
|
// doc-check: skip - Workers entry: `Env`/`ExecutionContext` globals + your `app` from server.ts.
|
|
2050
2199
|
// worker.ts - production uses a SHARED store so the cache + purges hold across instances.
|
|
@@ -2056,7 +2205,10 @@ export default {
|
|
|
2056
2205
|
if (new URL(req.url).pathname === "/__nifra/revalidate") {
|
|
2057
2206
|
return revalidateEndpoint({ store, secret: env.REVALIDATE_SECRET })(req)
|
|
2058
2207
|
}
|
|
2059
|
-
|
|
2208
|
+
// Signs every page it stores and serves only pages that verify. Generate the secret:
|
|
2209
|
+
// `openssl rand -hex 32 | wrangler secret put ISR_STORE_SECRET`
|
|
2210
|
+
const storeSecret = env.ISR_STORE_SECRET
|
|
2211
|
+
const isr = withISR(app, { store, storeSecret, revalidate: 60, now: () => Date.now() })
|
|
2060
2212
|
// waitUntil keeps the worker alive while a stale page regenerates behind the response.
|
|
2061
2213
|
return isr(req, { env, waitUntil: (p) => ctx.waitUntil(p) })
|
|
2062
2214
|
},
|
|
@@ -2067,7 +2219,8 @@ A store outage never fails a page. A read that throws, rejects, or outlives
|
|
|
2067
2219
|
`storeTimeoutMs` is a miss and the page renders; a failed write still returns the
|
|
2068
2220
|
rendered page; a failed background regeneration keeps the stale entry. Each failure goes to
|
|
2069
2221
|
`onStoreError(error, { op })`, which by default logs one line per operation
|
|
2070
|
-
per minute without the cache key
|
|
2222
|
+
per minute without the cache key; a page that fails its signature check is reported with op
|
|
2223
|
+
`"verify"`. Set `storeTimeoutMs` for a network store, so a
|
|
2071
2224
|
hung connection costs a miss rather than the request.
|
|
2072
2225
|
|
|
2073
2226
|
### On-demand revalidation
|
|
@@ -2084,6 +2237,17 @@ curl -X POST 'https://example.com/__nifra/revalidate?path=/posts/hello' \
|
|
|
2084
2237
|
# → { "revalidated": "/posts/hello" } (the token is checked in constant time)
|
|
2085
2238
|
```
|
|
2086
2239
|
|
|
2240
|
+
An action's `revalidate(paths, data, { tags })` purges the same way
|
|
2241
|
+
before it answers, so a reload, a new tab or a redirect after the post renders the write: data
|
|
2242
|
+
caches (`withISR({ dataCaches })`), then the page store, then live pages,
|
|
2243
|
+
then `cdn`. A path purge drops the entry the key function gives that URL with the
|
|
2244
|
+
action request's own headers and cookies, so the client that wrote reads its write. Entries a
|
|
2245
|
+
custom `key` builds from other header or cookie values, and those for query
|
|
2246
|
+
parameters `query` keeps, stay until they expire: tag those pages and name the tag.
|
|
2247
|
+
Each store call is bounded by `storeTimeoutMs`. A failed purge is retried
|
|
2248
|
+
behind the response under `waitUntil`, else for up to 2 s before the action answers,
|
|
2249
|
+
and is reported once to `onInvalidationError`.
|
|
2250
|
+
|
|
2087
2251
|
A per-request CSP nonce makes a page uncacheable. For a strict policy under ISR, give
|
|
2088
2252
|
`createWebApp` a `csp` from `createCspPolicy` instead of a
|
|
2089
2253
|
`nonce`: constant scripts are allowed by hash, so only a page that needs a nonce
|
|
@@ -2129,7 +2293,10 @@ import { revalidateEndpoint } from "@nifrajs/web"
|
|
|
2129
2293
|
|
|
2130
2294
|
const cdn = cloudflareZone({ zoneId: env.CF_ZONE_ID, apiToken: env.CF_PURGE_TOKEN })
|
|
2131
2295
|
// The CDN stores the pages ISR would, tagged, for the route's `revalidate`; browsers revalidate.
|
|
2132
|
-
const
|
|
2296
|
+
const storeSecret = env.ISR_STORE_SECRET // signs the pages a shared store keeps
|
|
2297
|
+
const handler = withCdn(withISR(app, { store, storeSecret, revalidate: 60, now: () => Date.now() }), {
|
|
2298
|
+
provider: cdn,
|
|
2299
|
+
})
|
|
2133
2300
|
// One purge reaches the origin store first, then the CDN: 200 done, 202 queued, 502 refused.
|
|
2134
2301
|
const revalidate = revalidateEndpoint({ store, secret: env.REVALIDATE_SECRET, cdn })
|
|
2135
2302
|
```
|
|
@@ -2137,8 +2304,8 @@ const revalidate = revalidateEndpoint({ store, secret: env.REVALIDATE_SECRET, cd
|
|
|
2137
2304
|
-
|
|
2138
2305
|
**Cloudflare zone** (`cloudflareZone`): needs a Cache Rule that makes HTML
|
|
2139
2306
|
eligible for cache, and, because the zone cache ignores `Vary`, that bypasses the
|
|
2140
|
-
cache when the request has an `x-nifra-data`
|
|
2141
|
-
page URL with
|
|
2307
|
+
cache when the request has an `x-nifra-data` or `x-nifra-swap` header
|
|
2308
|
+
(soft navigations and slot swaps fetch the page URL with them). The Free plan allows 5 purge calls a minute; purges arriving together go
|
|
2142
2309
|
out as one call.
|
|
2143
2310
|
|
|
2144
2311
|
-
|
|
@@ -2205,7 +2372,13 @@ export async function loader({ api, draft, params }: Route.LoaderArgs) {
|
|
|
2205
2372
|
|
|
2206
2373
|
// 3. Wire the SAME secret so loaders see ctx.draft + editors bypass the ISR cache.
|
|
2207
2374
|
createWebApp({ adapter, manifest, clientEntry, api, draftSecret: env.DRAFT_SECRET })
|
|
2208
|
-
withISR(app, {
|
|
2375
|
+
withISR(app, {
|
|
2376
|
+
store,
|
|
2377
|
+
storeSecret: env.ISR_STORE_SECRET, // a shared store's page-signing secret
|
|
2378
|
+
revalidate: 60,
|
|
2379
|
+
now: () => Date.now(),
|
|
2380
|
+
draftSecret: env.DRAFT_SECRET,
|
|
2381
|
+
})
|
|
2209
2382
|
```
|
|
2210
2383
|
|
|
2211
2384
|
### Fonts
|
|
@@ -2337,46 +2510,52 @@ if (document.documentElement.hasAttribute("data-nifra-hydrated")) start()
|
|
|
2337
2510
|
else document.addEventListener("nifra:hydrated", start, { once: true })
|
|
2338
2511
|
```
|
|
2339
2512
|
|
|
2340
|
-
## Nifra - Islands:
|
|
2513
|
+
## Nifra - Islands: interactivity without hydration
|
|
2341
2514
|
|
|
2342
|
-
> Add interactivity to a zero-runtime vanilla page with islands
|
|
2515
|
+
> Add interactivity to a zero-runtime vanilla page with islands: an imperative DOM enhancer, or signals bound to server-rendered markup by name. No framework runtime, no hydration, and nifra check matches the markup against the code that mounts it.
|
|
2343
2516
|
|
|
2344
2517
|
A `@nifrajs/web-vanilla` page ships zero framework runtime. When one corner needs
|
|
2345
|
-
to be interactive, you don't turn on hydration - you mount an **island
|
|
2346
|
-
|
|
2347
|
-
|
|
2518
|
+
to be interactive, you don't turn on hydration - you mount an **island**
|
|
2519
|
+
over a server-rendered element. Write it as plain DOM code, or bind signals to the markup by
|
|
2520
|
+
name. Either way `nifra check` reads the island and the markup together.
|
|
2348
2521
|
|
|
2349
2522
|
### Why islands, not hydration
|
|
2350
2523
|
|
|
2351
2524
|
Vanilla routes set `export const hydrate = false` in their
|
|
2352
|
-
`.backend.ts` half - there is no client framework
|
|
2353
|
-
|
|
2354
|
-
|
|
2355
|
-
|
|
2356
|
-
|
|
2357
|
-
|
|
2358
|
-
islands for widgets on an otherwise-static page.
|
|
2525
|
+
`.backend.ts` half - there is no client framework to hydrate with, and that is
|
|
2526
|
+
the point. The five framework adapters give you a component runtime and pay for it in client
|
|
2527
|
+
JS and in failure modes (stale closures, hydration mismatch, what-re-runs-when) that trip up
|
|
2528
|
+
generated code. Islands keep the HTML the server sent and attach behavior to it. Reach for a
|
|
2529
|
+
framework adapter when you need client routing or nested views; reach for islands for
|
|
2530
|
+
widgets and small apps on an otherwise-static page.
|
|
2359
2531
|
|
|
2360
2532
|
### Mount an island
|
|
2361
2533
|
|
|
2362
|
-
|
|
2363
|
-
|
|
2364
|
-
|
|
2534
|
+
Any element with `data-island="id"` is a host; its props are inline
|
|
2535
|
+
JSON in `data-island-props`. Bundle one entry (in `frontend/`) that
|
|
2536
|
+
calls `mountIslands` with an enhancer per id, and load it with the
|
|
2537
|
+
`islandScripts` export of the route's `.backend.ts` half. Calling
|
|
2538
|
+
`mountIslands` again after a soft navigation mounts only new hosts, and the
|
|
2539
|
+
disposer it returns tears down every island it mounted.
|
|
2365
2540
|
|
|
2366
2541
|
```ts
|
|
2367
|
-
// doc-check: skip - server-rendered island
|
|
2368
|
-
// In your @nifrajs/web-vanilla page,
|
|
2369
|
-
html`<
|
|
2542
|
+
// doc-check: skip - server-rendered island host (HTML, not a checkable module).
|
|
2543
|
+
// In your @nifrajs/web-vanilla page, mark any element as a host and give it inline JSON props:
|
|
2544
|
+
html`<div data-island="counter" data-island-props="${JSON.stringify({ start: 0 })}">
|
|
2370
2545
|
<output>0</output>
|
|
2371
2546
|
<button type="button">+1</button>
|
|
2372
|
-
</
|
|
2547
|
+
</div>`
|
|
2373
2548
|
```
|
|
2374
2549
|
|
|
2550
|
+
There are two ways to write the enhancer, and one page can mix both.
|
|
2551
|
+
|
|
2552
|
+
### Imperative islands: defineIsland
|
|
2553
|
+
|
|
2375
2554
|
```ts
|
|
2376
2555
|
// doc-check: skip - browser DOM enhancer, typechecked in @nifrajs/web under its DOM lib.
|
|
2377
2556
|
import { defineIsland, mountIslands } from "@nifrajs/web/islands"
|
|
2378
2557
|
|
|
2379
|
-
// defineIsland pins the data-props type; the body is plain imperative DOM. ALWAYS return the
|
|
2558
|
+
// defineIsland pins the data-island-props type; the body is plain imperative DOM. ALWAYS return the
|
|
2380
2559
|
// teardown for anything you wire - mountIslands calls it on soft-nav (NF-C020 warns if you forget).
|
|
2381
2560
|
const counter = defineIsland<{ start: number }>((el, props) => {
|
|
2382
2561
|
let n = props.start
|
|
@@ -2391,10 +2570,157 @@ mountIslands({ counter })
|
|
|
2391
2570
|
```
|
|
2392
2571
|
|
|
2393
2572
|
`defineIsland<Props>` is a zero-cost identity helper - its only job is to
|
|
2394
|
-
type `props` and `el` so the body needs no cast.
|
|
2395
|
-
|
|
2396
|
-
|
|
2397
|
-
|
|
2573
|
+
type `props` and `el` so the body needs no cast. Read the DOM, add
|
|
2574
|
+
listeners, **return the cleanup**. The returned function runs on teardown;
|
|
2575
|
+
forget it and every navigation leaks the listener - `nifra check` flags exactly
|
|
2576
|
+
that as `NF-C020`.
|
|
2577
|
+
|
|
2578
|
+
### Reactive islands: bindIsland
|
|
2579
|
+
|
|
2580
|
+
For local state, mount the host with `bindIsland`. The setup declares named
|
|
2581
|
+
state with `state(key, fallback)` - seeded from the island's props when they
|
|
2582
|
+
carry the key - and returns its event handlers. The markup then binds them by name:
|
|
2583
|
+
|
|
2584
|
+
```ts
|
|
2585
|
+
// doc-check: skip - server-rendered island host (HTML, not a checkable module).
|
|
2586
|
+
html`<form data-island="search" data-island-props="${JSON.stringify({ query: "" })}"
|
|
2587
|
+
data-bind-on="submit:go">
|
|
2588
|
+
<input name="q" data-bind-value="query" />
|
|
2589
|
+
<button data-bind-attr="disabled:busy">Search</button>
|
|
2590
|
+
<p data-bind-show="busy">Searching...</p>
|
|
2591
|
+
<p><span data-bind-text="count">0</span> results</p>
|
|
2592
|
+
</form>`
|
|
2593
|
+
```
|
|
2594
|
+
|
|
2595
|
+
```ts
|
|
2596
|
+
// doc-check: skip - browser DOM enhancer, typechecked in @nifrajs/web under its DOM lib.
|
|
2597
|
+
import { bindIsland, mountIslands } from "@nifrajs/web/islands"
|
|
2598
|
+
|
|
2599
|
+
const search = bindIsland(({ state, onDispose }) => {
|
|
2600
|
+
// Every data-bind-* name in the markup is a state key here, seeded from data-island-props.
|
|
2601
|
+
const query = state("query", "")
|
|
2602
|
+
const busy = state("busy", false)
|
|
2603
|
+
const count = state("count", 0)
|
|
2604
|
+
const timer = setInterval(() => console.log("still searching for", query()), 5000)
|
|
2605
|
+
onDispose(() => clearInterval(timer))
|
|
2606
|
+
|
|
2607
|
+
// The returned handlers are what data-bind-on names.
|
|
2608
|
+
return {
|
|
2609
|
+
go: async (event) => {
|
|
2610
|
+
event.preventDefault()
|
|
2611
|
+
busy.set(true)
|
|
2612
|
+
try {
|
|
2613
|
+
const hits: unknown[] = await fetch("/api/search?q=" + encodeURIComponent(query())).then((r) => r.json())
|
|
2614
|
+
count.set(hits.length)
|
|
2615
|
+
} finally {
|
|
2616
|
+
busy.set(false)
|
|
2617
|
+
}
|
|
2618
|
+
},
|
|
2619
|
+
}
|
|
2620
|
+
})
|
|
2621
|
+
|
|
2622
|
+
mountIslands({ search })
|
|
2623
|
+
```
|
|
2624
|
+
|
|
2625
|
+
Attribute
|
|
2626
|
+
Effect
|
|
2627
|
+
|
|
2628
|
+
`data-bind-text="count"`
|
|
2629
|
+
|
|
2630
|
+
Sets the element's text to the signal's value.
|
|
2631
|
+
|
|
2632
|
+
`data-bind-show="open"`
|
|
2633
|
+
|
|
2634
|
+
Hides the element while the signal is falsy.
|
|
2635
|
+
|
|
2636
|
+
`data-bind-class="active:open"`
|
|
2637
|
+
|
|
2638
|
+
Toggles a class per pair.
|
|
2639
|
+
|
|
2640
|
+
`data-bind-attr="aria-expanded:open"`
|
|
2641
|
+
|
|
2642
|
+
Sets an attribute per pair, removing it for `false` or
|
|
2643
|
+
`null`. Never an `on*` attribute or `srcdoc`, and a
|
|
2644
|
+
URL attribute takes only an http(s), mailto, tel or relative URL.
|
|
2645
|
+
|
|
2646
|
+
`data-bind-value="query"`
|
|
2647
|
+
|
|
2648
|
+
Two-way: an input, select or textarea writes the signal back.
|
|
2649
|
+
|
|
2650
|
+
`data-bind-on="click:add"`
|
|
2651
|
+
|
|
2652
|
+
Adds a returned handler as an event listener per pair.
|
|
2653
|
+
|
|
2654
|
+
Values are names, never code, so markup cannot inject behavior. A binding belongs to its
|
|
2655
|
+
nearest island, and nothing inside a `data-island-ignore` element binds or mounts
|
|
2656
|
+
- render user HTML there. Because both sides are literal, `nifra check` matches
|
|
2657
|
+
them: `NF-C047` warns when a name has no `state("...")` key
|
|
2658
|
+
or returned handler, and `NF-C048` when a binding sits where no
|
|
2659
|
+
`bindIsland` host will ever walk it.
|
|
2660
|
+
|
|
2661
|
+
### Signals
|
|
2662
|
+
|
|
2663
|
+
The reactive core is exported for code that needs more than markup bindings. A read inside
|
|
2664
|
+
an `effect` or `computed` subscribes; `batch` runs the
|
|
2665
|
+
effects once after several writes, and `untrack` reads without subscribing.
|
|
2666
|
+
Effects run after every computed they read has settled, so they never see a half-updated
|
|
2667
|
+
value.
|
|
2668
|
+
|
|
2669
|
+
```ts
|
|
2670
|
+
import { batch, computed, effect, signal, untrack } from "@nifrajs/web/islands"
|
|
2671
|
+
|
|
2672
|
+
// A signal is read by calling it and written with .set. Reads inside an effect or computed subscribe.
|
|
2673
|
+
const price = signal(20)
|
|
2674
|
+
const quantity = signal(1)
|
|
2675
|
+
const total = computed(() => price() * quantity())
|
|
2676
|
+
|
|
2677
|
+
const stop = effect(() => console.log("total", total(), "at", untrack(price)))
|
|
2678
|
+
batch(() => {
|
|
2679
|
+
price.set(25)
|
|
2680
|
+
quantity.set((n) => n + 1)
|
|
2681
|
+
}) // the effect runs once, after both writes: logs "total 50 at 25"
|
|
2682
|
+
stop()
|
|
2683
|
+
```
|
|
2684
|
+
|
|
2685
|
+
Everything an enhancer creates while it sets up - effects, computeds, lists, resources - is
|
|
2686
|
+
owned by its island and stops when the island unmounts. `onDispose(fn)` covers
|
|
2687
|
+
timers and requests the setup starts itself. An effect created later, inside an event
|
|
2688
|
+
handler, is not owned: create it during setup.
|
|
2689
|
+
|
|
2690
|
+
### Keyed lists and async state
|
|
2691
|
+
|
|
2692
|
+
`bindList(source, container, { key, create, update })` renders a list
|
|
2693
|
+
signal into a container. A surviving item keeps its node, so focus and input state survive a
|
|
2694
|
+
reorder, and only the nodes out of order move. `resource(source, fetcher)` keeps
|
|
2695
|
+
an async value with a `pending`, `ready` or `error` state;
|
|
2696
|
+
a newer key aborts the older request, and an unmounted island drops a late result.
|
|
2697
|
+
|
|
2698
|
+
```ts
|
|
2699
|
+
// doc-check: skip - browser DOM enhancer, typechecked in @nifrajs/web under its DOM lib.
|
|
2700
|
+
import { bindIsland, bindList, mountIslands, resource } from "@nifrajs/web/islands"
|
|
2701
|
+
|
|
2702
|
+
type Hotel = { id: string; name: string }
|
|
2703
|
+
|
|
2704
|
+
const hotels = bindIsland(({ root, state }) => {
|
|
2705
|
+
const city = state("city", "paris")
|
|
2706
|
+
// A newer city aborts the older request; only the newest result lands.
|
|
2707
|
+
const found = resource(city, (c, abort) =>
|
|
2708
|
+
fetch("/api/hotels?city=" + encodeURIComponent(c), { signal: abort }).then((r): Promise<Hotel[]> => r.json()),
|
|
2709
|
+
)
|
|
2710
|
+
const list = root.querySelector("ul")
|
|
2711
|
+
if (list)
|
|
2712
|
+
bindList(() => found().value ?? [], list, {
|
|
2713
|
+
key: (h) => h.id, // a stable id, never a position (NF-C022)
|
|
2714
|
+
create: () => document.createElement("li"),
|
|
2715
|
+
update: (li, h) => {
|
|
2716
|
+
li.textContent = h.name
|
|
2717
|
+
},
|
|
2718
|
+
})
|
|
2719
|
+
// A <select data-bind-value="city"> in the markup writes city; nothing else to return.
|
|
2720
|
+
})
|
|
2721
|
+
|
|
2722
|
+
mountIslands({ hotels })
|
|
2723
|
+
```
|
|
2398
2724
|
|
|
2399
2725
|
### Coordinate islands with a typed bus
|
|
2400
2726
|
|
|
@@ -2479,232 +2805,93 @@ const results = defineIsland((el) =>
|
|
|
2479
2805
|
mountIslands({ filter, results })
|
|
2480
2806
|
```
|
|
2481
2807
|
|
|
2482
|
-
###
|
|
2483
|
-
|
|
2484
|
-
A marker's `data-strategy` defers its enhancer: `load` (default),
|
|
2485
|
-
`idle`, `visible` (mount when it scrolls into view), or a
|
|
2486
|
-
`media` query. An island with no matching enhancer, or an invalid strategy, stays
|
|
2487
|
-
inert server-rendered HTML - forward-compatible, never a runtime error.
|
|
2488
|
-
|
|
2489
|
-
## Nifra - nano: explicit reactivity for small apps
|
|
2490
|
-
|
|
2491
|
-
> nano is the AI-safe small-app lane: signal + computed(fn, [deps]) + keyed bindList, no VDOM, no auto-tracking. Every reactive edge is a visible call, so its three mistakes are static lints (NF-C021/C022/C023) with a fix recipe - the same closed loop that makes the backend AI-safe, now on the frontend.
|
|
2492
|
-
|
|
2493
|
-
`@nifrajs/web/nano` is the middle lane between a static
|
|
2494
|
-
[island](/docs/islands) and a full framework adapter. It gives you a signal, a
|
|
2495
|
-
derived `computed`, and a keyed list - enough to build a small app with local
|
|
2496
|
-
state a human edits - and nothing else. No virtual DOM, no template compiler, no
|
|
2497
|
-
auto-tracking. Every reactive edge is a call you write, which is exactly what lets a tool
|
|
2498
|
-
catch the mistakes before runtime.
|
|
2499
|
-
|
|
2500
|
-
### Why a fourth lane
|
|
2501
|
-
|
|
2502
|
-
A framework fails generated code not because it is unfamiliar but because its reactivity is
|
|
2503
|
-
_implicit_: an effect silently tracks what it read, a stale closure captures the wrong
|
|
2504
|
-
value, a render mismatches hydration - all silent, all runtime. Preact fixes the
|
|
2505
|
-
**size** of that model (3 KB) but copies its footguns faithfully. nano
|
|
2506
|
-
fixes the **failure model** for the small-app band: dependencies are an explicit
|
|
2507
|
-
array, list keys are a required argument, cleanups are a returned value. Each of those is a
|
|
2508
|
-
thing a static check can see. Reach for nano when a page needs local state and a keyed list;
|
|
2509
|
-
reach for a [framework adapter](/docs/frameworks) the moment you need client
|
|
2510
|
-
routing, nested view state, or suspense.
|
|
2511
|
-
|
|
2512
|
-
### Signals and computed
|
|
2513
|
-
|
|
2514
|
-
A `signal` holds a value; `.get()` reads it and `.set(...)`
|
|
2515
|
-
replaces it (deduped with `Object.is`). A `computed` derives a value and
|
|
2516
|
-
declares its sources as an explicit deps array - it recomputes when a listed source changes,
|
|
2517
|
-
never by magic. Both are synchronous and framework-free.
|
|
2518
|
-
|
|
2519
|
-
```ts
|
|
2520
|
-
import { signal, computed } from "@nifrajs/web/nano"
|
|
2521
|
-
|
|
2522
|
-
// State is a signal: reads are .get(), writes are .set(...). Every edge is a call you can see.
|
|
2523
|
-
const count = signal(0)
|
|
2524
|
-
|
|
2525
|
-
// Derived state declares its dependencies EXPLICITLY - the array is the whole contract. It
|
|
2526
|
-
// recomputes when (and only when) a listed source changes. Object.is-deduped, like signal.
|
|
2527
|
-
const doubled = computed(() => count.get() * 2, [count])
|
|
2528
|
-
|
|
2529
|
-
const off = doubled.subscribe((v) => console.log("doubled is now", v))
|
|
2530
|
-
count.set(5) // logs: doubled is now 10
|
|
2531
|
-
off() // unsubscribe
|
|
2532
|
-
```
|
|
2533
|
-
|
|
2534
|
-
The deps array is the whole contract, and its one failure mode is catchable: a
|
|
2535
|
-
`computed` whose body reads a signal the array omits will never recompute when that
|
|
2536
|
-
signal changes. `nifra check` flags exactly that as `NF-C023` - the
|
|
2537
|
-
check reads which signals the body calls `.get()` on and compares them to the
|
|
2538
|
-
array. A framework's auto-tracked effect gives a tool nothing to compare, which is why
|
|
2539
|
-
the equivalent lint elsewhere is a best-effort warning, not a gate.
|
|
2540
|
-
|
|
2541
|
-
### Bind a signal to the DOM
|
|
2542
|
-
|
|
2543
|
-
`bind` is the one-value edge: it applies your function immediately and on every
|
|
2544
|
-
change, and returns a disposer. **Collect the disposer.** A bare
|
|
2545
|
-
`bind(...)` whose return value is discarded leaks its subscription on soft-nav -
|
|
2546
|
-
`nifra check` flags it as `NF-C021`.
|
|
2547
|
-
|
|
2548
|
-
```ts
|
|
2549
|
-
// doc-check: skip - browser DOM enhancer, typechecked in @nifrajs/web under its DOM lib.
|
|
2550
|
-
import { signal, bind } from "@nifrajs/web/nano"
|
|
2551
|
-
|
|
2552
|
-
const label = signal("hello")
|
|
2553
|
-
|
|
2554
|
-
// bind applies immediately AND on every change; it returns the disposer. COLLECT it - a bare
|
|
2555
|
-
// bind(...) that drops its return leaks the subscription on soft-nav (nifra check flags NF-C021).
|
|
2556
|
-
const off = bind(document.querySelector("h1")!, label, (el, v) => { el.textContent = v })
|
|
2557
|
-
label.set("world") // the <h1> updates synchronously
|
|
2558
|
-
// ...on teardown: off()
|
|
2559
|
-
```
|
|
2560
|
-
|
|
2561
|
-
### Keyed lists with bindList
|
|
2562
|
-
|
|
2563
|
-
`bindList` keeps a container's children in sync with an array by key - a keyed
|
|
2564
|
-
reconcile like a framework's list diff, but you spell the key out. Add, remove, and
|
|
2565
|
-
reorder reuse the matching node (preserving focus and scroll) instead of rebuilding the list.
|
|
2566
|
-
Key by a **stable id** on the item; keying by the array index reuses the wrong
|
|
2567
|
-
node on reorder, and `nifra check` flags it as `NF-C022`.
|
|
2568
|
-
|
|
2569
|
-
```ts
|
|
2570
|
-
// doc-check: skip - browser DOM enhancer, typechecked in @nifrajs/web under its DOM lib.
|
|
2571
|
-
import { signal, bindList } from "@nifrajs/web/nano"
|
|
2572
|
-
|
|
2573
|
-
interface Todo { id: string; text: string; done: boolean }
|
|
2574
|
-
const todos = signal<Todo[]>([])
|
|
2575
|
-
|
|
2576
|
-
// bindList keeps a container's children in sync with an array by KEY - a keyed reconcile, like a
|
|
2577
|
-
// framework's list diff, but explicit. Add/remove/reorder reuse the right node instead of rebuilding.
|
|
2578
|
-
const off = bindList(todos, document.querySelector("ul")!, {
|
|
2579
|
-
key: (t) => t.id, // a STABLE id on the item. Keying by the array index is NF-C022 - reorder breaks.
|
|
2580
|
-
create: (t) => { const li = document.createElement("li"); li.dataset.id = t.id; return li },
|
|
2581
|
-
update: (li, t) => { li.textContent = t.text; li.classList.toggle("done", t.done) },
|
|
2582
|
-
})
|
|
2583
|
-
|
|
2584
|
-
todos.set([...todos.get(), { id: crypto.randomUUID(), text: "buy milk", done: false }])
|
|
2585
|
-
// ...on teardown: off()
|
|
2586
|
-
```
|
|
2587
|
-
|
|
2588
|
-
### Async state with resource
|
|
2808
|
+
### Refresh part of the page: swap
|
|
2589
2809
|
|
|
2590
|
-
|
|
2591
|
-
|
|
2592
|
-
|
|
2593
|
-
|
|
2594
|
-
|
|
2595
|
-
no stale-response flicker. There is no thrown promise and no magic boundary; it is a value you
|
|
2596
|
-
read or bind like any other.
|
|
2810
|
+
A search form or a "more" link on a vanilla page reloads the whole document.
|
|
2811
|
+
To refresh one region instead, mark it with `data-swap-slot`, render its content
|
|
2812
|
+
with `slot()` from `@nifrajs/web-vanilla`, and point the link or form
|
|
2813
|
+
at it with `data-swap="replace:<slot>"` or
|
|
2814
|
+
`data-swap="append:<slot>"`:
|
|
2597
2815
|
|
|
2598
2816
|
```ts
|
|
2599
|
-
|
|
2600
|
-
|
|
2601
|
-
const userId = signal(1)
|
|
2602
|
-
|
|
2603
|
-
// resource(fetcher, [deps]) is an async cell: it fetches immediately and again whenever a declared
|
|
2604
|
-
// dep changes. The fetcher gets an AbortSignal; a superseded fetch is aborted and its late result
|
|
2605
|
-
// dropped, so the newest request always wins - no stale-response flicker to hand-guard.
|
|
2606
|
-
const user = resource(async (sig) => {
|
|
2607
|
-
const res = await fetch(`/api/users/${userId.get()}`, { signal: sig })
|
|
2608
|
-
return (await res.json()) as { name: string }
|
|
2609
|
-
}, [userId])
|
|
2817
|
+
// doc-check: skip - html template markup, which the sample check cannot tell from JSX.
|
|
2818
|
+
import { html, slot } from "@nifrajs/web-vanilla"
|
|
2610
2819
|
|
|
2611
|
-
|
|
2612
|
-
const off = user.subscribe((s) => {
|
|
2613
|
-
if (s.status === "ready") console.log("got", s.value.name)
|
|
2614
|
-
})
|
|
2615
|
-
userId.set(2) // refetches; the deps array is what NF-C023 checks against the fetcher's .get() reads
|
|
2616
|
-
// ...on teardown: off()
|
|
2617
|
-
```
|
|
2820
|
+
type Books = { q: string; page: number; titles: string[]; more: boolean }
|
|
2618
2821
|
|
|
2619
|
-
|
|
2620
|
-
|
|
2621
|
-
|
|
2622
|
-
|
|
2623
|
-
|
|
2624
|
-
|
|
2625
|
-
|
|
2626
|
-
|
|
2627
|
-
|
|
2628
|
-
|
|
2629
|
-
|
|
2630
|
-
const userId = signal(1)
|
|
2631
|
-
const user = resource(async (sig) => {
|
|
2632
|
-
const res = await fetch(`/api/users/${userId.get()}`, { signal: sig })
|
|
2633
|
-
return (await res.json()) as { name: string }
|
|
2634
|
-
}, [userId])
|
|
2635
|
-
|
|
2636
|
-
// bindResource dispatches on status - one handler per state, ready required. Like bind it returns a
|
|
2637
|
-
// disposer (a bare bindResource(...) that drops it is NF-C021).
|
|
2638
|
-
const off = bindResource(document.querySelector("[data-user]")!, user, {
|
|
2639
|
-
pending: (el) => { el.textContent = "Loading…" },
|
|
2640
|
-
ready: (el, u) => { el.textContent = u.name },
|
|
2641
|
-
error: (el) => { el.textContent = "Could not load user" },
|
|
2642
|
-
})
|
|
2643
|
-
// ...on teardown: off()
|
|
2822
|
+
export default ({ data }: { data: Books }) => html`
|
|
2823
|
+
<form action="/books" data-swap="replace:results">
|
|
2824
|
+
<input name="q" value="${data.q}" />
|
|
2825
|
+
<button>Search</button>
|
|
2826
|
+
</form>
|
|
2827
|
+
<ul data-swap-slot="results">${slot("results", [
|
|
2828
|
+
...data.titles.map((title) => html`<li data-island="book">${title}</li>`),
|
|
2829
|
+
data.more
|
|
2830
|
+
? html`<li><a href="/books?q=${encodeURIComponent(data.q)}&page=${data.page + 1}" data-swap="append:results">More</a></li>`
|
|
2831
|
+
: "",
|
|
2832
|
+
])}</ul>`
|
|
2644
2833
|
```
|
|
2645
2834
|
|
|
2646
|
-
|
|
2647
|
-
|
|
2648
|
-
nano owns state and DOM edges; an [island](/docs/islands) owns mount and teardown.
|
|
2649
|
-
Put the signals in the enhancer, collect every disposer, and return one cleanup that calls
|
|
2650
|
-
them all. Scaffold this shape with
|
|
2651
|
-
`nifra_scaffold { path, variant: "stateful" }` on a vanilla
|
|
2652
|
-
project - it emits the golden pattern below.
|
|
2835
|
+
Then call `enableSwap` from `@nifrajs/web/islands/swap` in place of
|
|
2836
|
+
`mountIslands` in the island entry. A page that does not import it pays nothing.
|
|
2653
2837
|
|
|
2654
2838
|
```ts
|
|
2655
|
-
// doc-check: skip - browser DOM
|
|
2656
|
-
import { defineIsland
|
|
2657
|
-
import {
|
|
2658
|
-
|
|
2659
|
-
interface Todo { id: string; text: string; done: boolean }
|
|
2660
|
-
|
|
2661
|
-
// nano lives INSIDE an island - the island owns mount/teardown, nano owns the state and the DOM edges.
|
|
2662
|
-
const todos = defineIsland<{ items: Todo[] }>((el, props) => {
|
|
2663
|
-
const items = signal<Todo[]>(props.items)
|
|
2664
|
-
const remaining = computed(() => items.get().filter((t) => !t.done).length, [items])
|
|
2665
|
-
|
|
2666
|
-
// Collect every disposer; the island's cleanup calls them all (this is what NF-C021 protects).
|
|
2667
|
-
const cleanups: Array<() => void> = []
|
|
2668
|
-
cleanups.push(bind(el.querySelector("[data-count]")!, remaining, (n, v) => {
|
|
2669
|
-
n.textContent = String(v) + " left"
|
|
2670
|
-
}))
|
|
2671
|
-
cleanups.push(bindList(items, el.querySelector("[data-list]")!, {
|
|
2672
|
-
key: (t) => t.id,
|
|
2673
|
-
create: (t) => { const li = document.createElement("li"); li.dataset.id = t.id; return li },
|
|
2674
|
-
update: (li, t) => { li.textContent = t.text; li.classList.toggle("done", t.done) },
|
|
2675
|
-
}))
|
|
2839
|
+
// doc-check: skip - browser DOM entry, typechecked in @nifrajs/web under its DOM lib.
|
|
2840
|
+
import { defineIsland } from "@nifrajs/web/islands"
|
|
2841
|
+
import { enableSwap } from "@nifrajs/web/islands/swap"
|
|
2676
2842
|
|
|
2677
|
-
|
|
2678
|
-
|
|
2679
|
-
|
|
2680
|
-
|
|
2681
|
-
return () => { for (const off of cleanups) off() }
|
|
2843
|
+
const book = defineIsland((el) => {
|
|
2844
|
+
const onClick = () => el.classList.toggle("picked")
|
|
2845
|
+
el.addEventListener("click", onClick)
|
|
2846
|
+
return () => el.removeEventListener("click", onClick)
|
|
2682
2847
|
})
|
|
2683
2848
|
|
|
2684
|
-
mountIslands
|
|
2685
|
-
|
|
2686
|
-
|
|
2687
|
-
|
|
2688
|
-
|
|
2689
|
-
|
|
2690
|
-
|
|
2691
|
-
|
|
2692
|
-
|
|
2693
|
-
|
|
2694
|
-
|
|
2695
|
-
|
|
2696
|
-
|
|
2697
|
-
|
|
2698
|
-
-
|
|
2699
|
-
|
|
2849
|
+
// In place of mountIslands: mounts the islands, then refreshes slots from data-swap links and forms.
|
|
2850
|
+
enableSwap({ book })
|
|
2851
|
+
```
|
|
2852
|
+
|
|
2853
|
+
The link or GET form makes its usual request with an `x-nifra-swap` header. The
|
|
2854
|
+
server runs the page as usual - middleware and loaders - and answers with that
|
|
2855
|
+
slot's HTML alone, so the fragment is a slice of the real page, never a second
|
|
2856
|
+
template. `replace` swaps the slot's content and, for a GET, pushes the
|
|
2857
|
+
URL, so a filtered list survives a reload and back and forward work. `append`
|
|
2858
|
+
adds to it, and a link or form inside the slot is spent: the slot's child that holds it
|
|
2859
|
+
is removed when the next page arrives.
|
|
2860
|
+
|
|
2861
|
+
Any other answer - a redirect, another origin, a page without that slot, an error - loads
|
|
2862
|
+
the URL normally, as does a page whose Trusted Types policy refuses the HTML. A swapped
|
|
2863
|
+
slot joins the current page, so that page's Content-Security-Policy governs it. POST
|
|
2864
|
+
forms submit natively, so the browser applies the response's security policy, starts
|
|
2865
|
+
its scripts and shows the action result. A form POST is sent once. Without the script,
|
|
2866
|
+
links and forms work as plain HTML.
|
|
2867
|
+
A loading slot carries
|
|
2868
|
+
`aria-busy="true"`, a newer swap of the same slot cancels the older
|
|
2869
|
+
one, and a failed request leaves the page as it is and sets `data-swap-error` on
|
|
2870
|
+
the link or form. Islands inside a slot
|
|
2871
|
+
mount with it and unmount when it is replaced, so interactivity inside a slot comes from
|
|
2872
|
+
islands in it, not from bindings of an island around it. Only
|
|
2873
|
+
`@nifrajs/web-vanilla` pages answer a swap.
|
|
2874
|
+
|
|
2875
|
+
A swap fetch bypasses the browser cache. Documents and fragments vary on
|
|
2876
|
+
`x-nifra-swap`; fragments are `private, no-store`, and
|
|
2877
|
+
ISR never serves or stores one. A CDN that ignores `Vary`, such as a Cloudflare
|
|
2878
|
+
zone, needs its cache rule to bypass requests carrying `x-nifra-swap`;
|
|
2879
|
+
`nifra cdn-check` tests that. `nifra check` reads both sides:
|
|
2880
|
+
`NF-C049` flags `data-swap` on anything but a link or form, or a mode
|
|
2881
|
+
other than `replace` and `append`; `NF-C050` a slot name
|
|
2882
|
+
nothing declares; `NF-C051` a slot whose content is not its `slot()`
|
|
2883
|
+
alone; `NF-C052` a URL whose page renders no such slot; and `NF-C048`
|
|
2884
|
+
a binding inside a slot that belongs to an island outside it.
|
|
2700
2885
|
|
|
2701
|
-
|
|
2702
|
-
`NF-C023` - a `computed` that reads a signal its deps omit. Add it to
|
|
2703
|
-
the deps array.
|
|
2886
|
+
### Load strategies
|
|
2704
2887
|
|
|
2705
|
-
|
|
2706
|
-
|
|
2707
|
-
|
|
2888
|
+
A host's `data-island-strategy` defers its enhancer: `load`
|
|
2889
|
+
(default), `idle`, `visible` (mount when it scrolls into view), or
|
|
2890
|
+
`media` with the query in `data-island-media`. A host with no matching
|
|
2891
|
+
enhancer, or an invalid strategy, stays inert server-rendered HTML - forward-compatible,
|
|
2892
|
+
never a runtime error. The scheduling itself is `@nifrajs/island-trigger`'s
|
|
2893
|
+
`scheduleTrigger`, which has no DOM or framework dependency, for a runtime of
|
|
2894
|
+
your own.
|
|
2708
2895
|
|
|
2709
2896
|
## Nifra - Streaming
|
|
2710
2897
|
|
|
@@ -2801,7 +2988,8 @@ A client that stops reading is dropped once it has `maxBufferedBytes` (default 1
|
|
|
2801
2988
|
MiB) of events unread: `stream.signal` aborts with `sse_client_too_slow`,
|
|
2802
2989
|
the queued frames are released, and later sends do nothing, so one stalled reader cannot hold
|
|
2803
2990
|
server memory without limit. Raise it for a burst larger than that sent before the client can
|
|
2804
|
-
read, or pass `Infinity` to turn the limit off.
|
|
2991
|
+
read, or pass `Infinity` to turn the limit off. A single frame over the cap is refused
|
|
2992
|
+
immediately, even if no further frame is sent.
|
|
2805
2993
|
|
|
2806
2994
|
### Typed SSE routes
|
|
2807
2995
|
|
|
@@ -2811,7 +2999,8 @@ read, or pass `Infinity` to turn the limit off.
|
|
|
2811
2999
|
`body` is a POST stream: the body validates as on any POST, and
|
|
2812
3000
|
`.subscribe(onEvent, { body })` sends it. A GET stream reconnects after a
|
|
2813
3001
|
drop and resumes with `Last-Event-ID`; a POST stream does not reconnect unless you
|
|
2814
|
-
pass `reconnect: true`, since a reconnect sends the body again.
|
|
3002
|
+
pass `reconnect: true`, since a reconnect sends the body again. A
|
|
3003
|
+
`204` answer closes the stream for good. The client's
|
|
2815
3004
|
`onRequest` hook runs before each connect, so a refreshed token reaches the stream.
|
|
2816
3005
|
|
|
2817
3006
|
```ts
|
|
@@ -2850,14 +3039,16 @@ feed.close()
|
|
|
2850
3039
|
> Nifra's keyed query cache: useQuery / createQuery, dedup, staleness, invalidation.
|
|
2851
3040
|
|
|
2852
3041
|
For client-side data that isn't a route loader - lists, widgets, anything refetchable -
|
|
2853
|
-
Nifra ships a keyed query cache (TanStack-Query-style), agnostic across
|
|
3042
|
+
Nifra ships a keyed query cache (TanStack-Query-style), agnostic across all five adapters.
|
|
2854
3043
|
|
|
2855
3044
|
### useQuery / createQuery
|
|
2856
3045
|
|
|
2857
|
-
`useQuery(key, fn)` (React
|
|
2858
|
-
|
|
2859
|
-
|
|
2860
|
-
|
|
3046
|
+
`useQuery(key, fn)` (React, Preact, Vue and Svelte) and
|
|
3047
|
+
`createQuery(key, fn)` (Solid), each from the adapter's `/query`
|
|
3048
|
+
entry, subscribe a component to a cached, keyed query. Concurrent reads of the same key
|
|
3049
|
+
**dedup** into one in-flight fetch; results are cached with a `staleTime` (the
|
|
3050
|
+
third argument's option), a background refetch, and bounded GC. React also has
|
|
3051
|
+
`useMutation`, `useInfiniteQuery` and `HydrationBoundary`.
|
|
2861
3052
|
|
|
2862
3053
|
```ts
|
|
2863
3054
|
import { useQuery, useQueryClient } from "@nifrajs/web-react/query"
|
|
@@ -2885,9 +3076,13 @@ After a mutation, `useQueryClient().invalidateQueries(key)` marks matching entri
|
|
|
2885
3076
|
stale (by exact key or array **prefix**) and refetches the mounted ones - no manual cache
|
|
2886
3077
|
surgery.
|
|
2887
3078
|
|
|
2888
|
-
|
|
2889
|
-
|
|
2890
|
-
|
|
3079
|
+
In an app with [live refresh](/docs/live), a query can name the live keys its data
|
|
3080
|
+
depends on: `useQuery(key, fn, { live: [`post:${id}`] })` refetches whenever
|
|
3081
|
+
the server publishes one of them.
|
|
3082
|
+
|
|
3083
|
+
It's the same agnostic core under every adapter: the cache, dedup, and invalidation logic
|
|
3084
|
+
live in `@nifrajs/web`; each binding is a thin wrapper in its framework's own
|
|
3085
|
+
reactivity (`useSyncExternalStore`, a signal, a `shallowRef`, a store).
|
|
2891
3086
|
|
|
2892
3087
|
## Nifra - Frameworks
|
|
2893
3088
|
|
|
@@ -2936,7 +3131,8 @@ import { html, vanillaAdapter } from "@nifrajs/web-vanilla"
|
|
|
2936
3131
|
|
|
2937
3132
|
// routes/hotels.tsx - a page keeps a route extension even with no JSX in it.
|
|
2938
3133
|
export default function Hotels({ data }: { data: { hotels: Array<{ name: string }> } }) {
|
|
2939
|
-
// Interpolated values are escaped
|
|
3134
|
+
// Interpolated values are escaped for where they land (text, attribute, URL); a string as a tag
|
|
3135
|
+
// name or inside <script> throws. Wrap trusted markup in raw() to opt out deliberately.
|
|
2940
3136
|
return html`<ul>${data.hotels.map((h) => html`<li>${h.name}</li>`)}</ul>`
|
|
2941
3137
|
}
|
|
2942
3138
|
|
|
@@ -3045,7 +3241,7 @@ const fetcher = useFetcher("save") // fetcher.submit(...), fetcher.pend
|
|
|
3045
3241
|
const q = useQuery(["todos"], loadTodos) // q.data, q.isFetching, q.refetch()
|
|
3046
3242
|
|
|
3047
3243
|
// Vue - composables (refs): const f = useFetcher("save"); f.state.value.pending
|
|
3048
|
-
// Solid - signals: const q =
|
|
3244
|
+
// Solid - signals: const q = createQuery(...); q.state().data
|
|
3049
3245
|
// Svelte - stores (read with $): const f = useFetcher("save"); $f.pending
|
|
3050
3246
|
```
|
|
3051
3247
|
|
|
@@ -3078,6 +3274,52 @@ framework's Vite plugin. React, Preact, and Vue preserve edited component state.
|
|
|
3078
3274
|
and Svelte update live without a full page reload, and the edited component may remount. Full
|
|
3079
3275
|
matrix in [Dev & HMR](/docs/dev).
|
|
3080
3276
|
|
|
3277
|
+
### React Compiler
|
|
3278
|
+
|
|
3279
|
+
The React Compiler is a Babel plugin, and nifra builds with Bun, so it runs as a small Bun
|
|
3280
|
+
plugin over your own `.tsx` and `.jsx` files. Listed in
|
|
3281
|
+
`clientPlugins`, it compiles the client bundle for `nifra build` and for
|
|
3282
|
+
`nifra dev`. With `--vite`, both commands take it from
|
|
3283
|
+
`vitePlugins` instead: `@vitejs/plugin-react` 6 hands its
|
|
3284
|
+
`reactCompilerPreset()` to `@rolldown/plugin-babel`, which skips
|
|
3285
|
+
`node_modules` on its own. That pair needs Vite 8. The server bundle stays as
|
|
3286
|
+
written: a compiled component renders the same markup, so pages hydrate as before. Needs React
|
|
3287
|
+
19.
|
|
3288
|
+
|
|
3289
|
+
```ts
|
|
3290
|
+
// doc-check: skip - needs @babel/core, babel-plugin-react-compiler, @rolldown/plugin-babel and @vitejs/plugin-react 6 installed.
|
|
3291
|
+
// nifra.config.ts - the React Compiler for nifra build and nifra dev, with or without --vite.
|
|
3292
|
+
import type { BunPlugin } from "bun"
|
|
3293
|
+
import { transformAsync } from "@babel/core"
|
|
3294
|
+
import babel from "@rolldown/plugin-babel"
|
|
3295
|
+
import react, { reactCompilerPreset } from "@vitejs/plugin-react"
|
|
3296
|
+
|
|
3297
|
+
export { adapter } from "./backend/framework"
|
|
3298
|
+
export const clientModule = "@nifrajs/web-react/client"
|
|
3299
|
+
|
|
3300
|
+
// Your own components only; packages ship compiled or plain already.
|
|
3301
|
+
const reactCompiler: BunPlugin = {
|
|
3302
|
+
name: "react-compiler",
|
|
3303
|
+
setup(build) {
|
|
3304
|
+
build.onLoad({ filter: /\.[jt]sx$/ }, async ({ path }) => {
|
|
3305
|
+
if (/[\\/]node_modules[\\/]/.test(path)) return undefined
|
|
3306
|
+
const source = await Bun.file(path).text()
|
|
3307
|
+
const out = await transformAsync(source, {
|
|
3308
|
+
filename: path,
|
|
3309
|
+
babelrc: false,
|
|
3310
|
+
configFile: false,
|
|
3311
|
+
parserOpts: { plugins: path.endsWith(".tsx") ? ["jsx", "typescript"] : ["jsx"] },
|
|
3312
|
+
plugins: ["babel-plugin-react-compiler"],
|
|
3313
|
+
})
|
|
3314
|
+
return { contents: out?.code ?? source, loader: path.endsWith(".tsx") ? "tsx" : "jsx" }
|
|
3315
|
+
})
|
|
3316
|
+
},
|
|
3317
|
+
}
|
|
3318
|
+
|
|
3319
|
+
export const clientPlugins = [reactCompiler]
|
|
3320
|
+
export const vitePlugins = [react(), babel({ presets: [reactCompilerPreset()] })]
|
|
3321
|
+
```
|
|
3322
|
+
|
|
3081
3323
|
## Nifra - Plugins & middleware
|
|
3082
3324
|
|
|
3083
3325
|
> Extend Nifra with definePlugin (typed context, idempotent) + hook-bundle middleware. Official middleware: requestId, logger, etag, bearer, apiKey, basicAuth, jwt/jwks, csrf, ipRestriction, bodyLimit, cors, securityHeaders, rateLimit, compression, cacheControl, cache, prettyJson, timing, methodOverride, trailingSlash, language, poweredBy, combine, openapi, healthcheck, idempotency.
|
|
@@ -3253,6 +3495,13 @@ hooks.
|
|
|
3253
3495
|
`around`, `derive`, and `beforeHandle` apply only to
|
|
3254
3496
|
routes declared after them.
|
|
3255
3497
|
|
|
3498
|
+
-
|
|
3499
|
+
An `authenticate()` stage, and a required auth plugin built on one (
|
|
3500
|
+
`bearer()`, `jwt()`, `basicAuth()`,
|
|
3501
|
+
`apiKey()`), guards the routes **and** the `mount()` and
|
|
3502
|
+
`mountFetch()` handlers declared after it. A mount declared before it stays
|
|
3503
|
+
public.
|
|
3504
|
+
|
|
3256
3505
|
-
|
|
3257
3506
|
A **WebSocket** route, listed as `WS /path`, runs the request hooks, then the
|
|
3258
3507
|
authentication stages, `derive`s, `beforeHandle`s and
|
|
@@ -3602,6 +3851,67 @@ const app = server().use(
|
|
|
3602
3851
|
)
|
|
3603
3852
|
```
|
|
3604
3853
|
|
|
3854
|
+
### A shared store in production
|
|
3855
|
+
|
|
3856
|
+
`MemoryStore` counts per instance, so it refuses to start under
|
|
3857
|
+
`NODE_ENV=production`: behind a load balancer each instance would allow the full
|
|
3858
|
+
limit. A shared store implements `RateLimitStore`, one method that records a hit
|
|
3859
|
+
and returns the window's count and reset time. Over Redis it is one atomic script per
|
|
3860
|
+
request, so instances never race, and a key that lost its expiry is given one back instead
|
|
3861
|
+
of locking a client out. Both limiters take it, and tiers share it.
|
|
3862
|
+
|
|
3863
|
+
```ts
|
|
3864
|
+
import { RedisClient } from "bun"
|
|
3865
|
+
import { server } from "@nifrajs/core/server"
|
|
3866
|
+
import { rateLimit, type RateLimitResult, type RateLimitStore } from "@nifrajs/middleware"
|
|
3867
|
+
|
|
3868
|
+
/** The one call the store makes; Bun's RedisClient has it as send(). */
|
|
3869
|
+
interface RedisCommands {
|
|
3870
|
+
send(command: string, args: string[]): Promise<unknown>
|
|
3871
|
+
}
|
|
3872
|
+
|
|
3873
|
+
// One atomic round trip: count the hit, start the window on the first one, and report when it ends.
|
|
3874
|
+
// A key left without an expiry gets one here, so it can never lock a client out for good.
|
|
3875
|
+
const HIT = [
|
|
3876
|
+
'local count = redis.call("INCR", KEYS[1])',
|
|
3877
|
+
'local ttl = redis.call("PTTL", KEYS[1])',
|
|
3878
|
+
"if ttl < 0 then",
|
|
3879
|
+
' redis.call("PEXPIRE", KEYS[1], ARGV[1])',
|
|
3880
|
+
" ttl = tonumber(ARGV[1])",
|
|
3881
|
+
"end",
|
|
3882
|
+
"return { count, ttl }",
|
|
3883
|
+
].join("\n")
|
|
3884
|
+
|
|
3885
|
+
class RedisRateLimitStore implements RateLimitStore {
|
|
3886
|
+
readonly #redis: RedisCommands
|
|
3887
|
+
readonly #prefix: string
|
|
3888
|
+
|
|
3889
|
+
constructor(redis: RedisCommands, prefix = "ratelimit:") {
|
|
3890
|
+
this.#redis = redis
|
|
3891
|
+
this.#prefix = prefix
|
|
3892
|
+
}
|
|
3893
|
+
|
|
3894
|
+
async hit(key: string, windowMs: number): Promise<RateLimitResult> {
|
|
3895
|
+
const reply = await this.#redis.send("EVAL", [HIT, "1", this.#prefix + key, String(windowMs)])
|
|
3896
|
+
const [count, ttl] = reply as [number, number]
|
|
3897
|
+
return { count, resetAt: Date.now() + ttl }
|
|
3898
|
+
}
|
|
3899
|
+
}
|
|
3900
|
+
|
|
3901
|
+
// Bun's client fits as it is. Others take one line:
|
|
3902
|
+
// ioredis: { send: (command, args) => redis.call(command, ...args) }
|
|
3903
|
+
// node-redis: { send: (command, args) => client.sendCommand([command, ...args]) }
|
|
3904
|
+
const redis = new RedisClient(process.env.REDIS_URL)
|
|
3905
|
+
const app = server().use(
|
|
3906
|
+
rateLimit({ store: new RedisRateLimitStore(redis), max: 100, windowMs: 60_000 }),
|
|
3907
|
+
)
|
|
3908
|
+
```
|
|
3909
|
+
|
|
3910
|
+
If Redis cannot be reached, `hit()` rejects and the request fails rather than
|
|
3911
|
+
going unlimited. To fail open instead, catch inside `hit()` and return
|
|
3912
|
+
`{ count: 0, resetAt: Date.now() + windowMs }`. On Redis Cluster the script
|
|
3913
|
+
touches one key, so it runs on whichever node owns it.
|
|
3914
|
+
|
|
3605
3915
|
### Security middleware
|
|
3606
3916
|
|
|
3607
3917
|
The security set - `csrf` (signed double-submit + Origin/Referer), `jwt`,
|
|
@@ -3943,8 +4253,8 @@ never build a path from the name.
|
|
|
3943
4253
|
**
|
|
3944
4254
|
Without `accept`, `file.type` is the client's too.
|
|
3945
4255
|
**
|
|
3946
|
-
|
|
3947
|
-
one the bytes proved.
|
|
4256
|
+
It is the part's `Content-Type`, lower-cased, or `text/plain` when
|
|
4257
|
+
the part names none. Only a type that `accept` matched is one the bytes proved.
|
|
3948
4258
|
|
|
3949
4259
|
-
|
|
3950
4260
|
**Serve uploads as downloads.** Send `content-disposition: attachment` and
|
|
@@ -4042,7 +4352,7 @@ the route still reads; send another format with `fetch`.
|
|
|
4042
4352
|
|
|
4043
4353
|
### File uploads - `@nifrajs/uploads`
|
|
4044
4354
|
|
|
4045
|
-
A
|
|
4355
|
+
A small package for the upload-hardening basics. `validateUpload` enforces a
|
|
4046
4356
|
size cap and sniffs the **real** type from magic bytes - never the client-set
|
|
4047
4357
|
`Content-Type`, which is trivially forged - against an optional allow-list. An oversized
|
|
4048
4358
|
`Blob` is rejected by its `.size` before it's ever buffered.
|
|
@@ -4075,8 +4385,9 @@ app.post("/avatar", async (c) => {
|
|
|
4075
4385
|
```
|
|
4076
4386
|
|
|
4077
4387
|
Pair it with `c.boundedBody` to also bound the _read_: cap the read, then validate
|
|
4078
|
-
the buffered bytes. `detectFileType(bytes)`
|
|
4079
|
-
`{ mime, ext }` or `null`),
|
|
4388
|
+
the buffered bytes. The detection alone is `detectFileType(bytes)` from
|
|
4389
|
+
`@nifrajs/core/file-type` (returns `{ mime, ext }` or `null`),
|
|
4390
|
+
covering common image / A-V / archive types.
|
|
4080
4391
|
|
|
4081
4392
|
`signDownloadUrl` / `verifyDownloadUrl` mint short-TTL, tamper-evident
|
|
4082
4393
|
download links (HMAC-SHA256 over the path + expiry, constant-time verify). And
|
|
@@ -4139,11 +4450,13 @@ accept either during a key rotation.
|
|
|
4139
4450
|
A dropped connection or an impatient double-tap shouldn't double-charge a card. With an
|
|
4140
4451
|
`Idempotency-Key` header, a retried unsafe request replays the first response instead of
|
|
4141
4452
|
re-running the side effect. The key is claimed in `onRequest`, so a concurrent retry gets
|
|
4142
|
-
a `409`; the stored response is replayed
|
|
4143
|
-
route's authentication
|
|
4144
|
-
|
|
4145
|
-
|
|
4146
|
-
|
|
4453
|
+
a `409`; the stored response is replayed just before the handler, _after_ the
|
|
4454
|
+
route's authentication, validation and every guard accept the retry - a guard registered before
|
|
4455
|
+
or after the middleware alike - so a credential revoked since the first request gets the
|
|
4456
|
+
route's current answer. Install it before every route that uses a covered method, public or
|
|
4457
|
+
protected; installing it after one throws. A
|
|
4458
|
+
request no covered route handles, such as one a mounted app or an earlier hook answers, is not
|
|
4459
|
+
deduplicated. Older stored records without an admission marker are refused.
|
|
4147
4460
|
|
|
4148
4461
|
```ts
|
|
4149
4462
|
// doc-check: skip - fragment: `app`, `chargeCard`, and `id` are your application's.
|
|
@@ -4180,11 +4493,26 @@ braces - the constraint is the belt.
|
|
|
4180
4493
|
replaying it to a second caller (key collision or abuse) would leak/fixate a session. The first
|
|
4181
4494
|
caller still gets their cookie - replays just don't carry it.
|
|
4182
4495
|
|
|
4496
|
+
-
|
|
4497
|
+
Stores can implement `renew(key, reservation, lockTtlMs)` to keep active work's lease
|
|
4498
|
+
alive, for up to `ttlMs`. Without renewal, pending reservations last at least `ttlMs`. A lost lease or
|
|
4499
|
+
failed completion returns `503 idempotency_reservation_lost`; external effects still
|
|
4500
|
+
need their own durable deduplication or fencing.
|
|
4501
|
+
|
|
4502
|
+
-
|
|
4503
|
+
A cacheable response over `maxBytes` reaches its first caller intact, while its key
|
|
4504
|
+
retains a terminal record. Retries receive `507 idempotency_response_too_large` and
|
|
4505
|
+
never repeat the operation. A response-body capture failure also retains a terminal outcome. A
|
|
4506
|
+
response `shouldCache` declines, such as a `5xx`, releases its key at any
|
|
4507
|
+
size, so a retry runs again.
|
|
4508
|
+
|
|
4183
4509
|
-
|
|
4184
4510
|
Caching buffers the response body, so apply it to JSON/API routes, not streaming SSR responses.
|
|
4185
4511
|
Transient `5xx` aren't cached, and neither are `401`, `403`,
|
|
4186
4512
|
`408`, `409`, `425`, or `429`: each says the call
|
|
4187
|
-
|
|
4513
|
+
stays retryable under the same key by default. A handler can fail after an effect: use the
|
|
4514
|
+
core route-level idempotency lane or an appropriate `shouldCache` policy for those
|
|
4515
|
+
operations.
|
|
4188
4516
|
|
|
4189
4517
|
-
|
|
4190
4518
|
The key is not bound to the body: a key reused with a different body replays the first answer. A
|
|
@@ -4961,8 +5289,11 @@ app.post("/api/logout", async (c) => {
|
|
|
4961
5289
|
### Guard a route
|
|
4962
5290
|
|
|
4963
5291
|
`requireSession` / `requireUser` throw a `status(...)` render
|
|
4964
|
-
(a 302 to `redirectTo`, or a 401) when the session is
|
|
4965
|
-
thrown control-flow value as-is, so the guard
|
|
5292
|
+
(a 302 to `redirectTo`, or a 401) when the session is empty, or when it lacks the
|
|
5293
|
+
key a login sets - Nifra renders a thrown control-flow value as-is, so the guard
|
|
5294
|
+
short-circuits the loader. A session can hold data before anyone signs in (a cart, a return
|
|
5295
|
+
path), and `requireSession` passes it, so guard a signed-in page with
|
|
5296
|
+
`requireUser`. It is plain data, not
|
|
4966
5297
|
a `Response`: same bytes on the wire, on the lane an ordinary return takes. To guard
|
|
4967
5298
|
every page under a directory, run the same check in the `middleware` export of that
|
|
4968
5299
|
directory's `_layout.backend.ts` - see [Route middleware](/docs/routing#middleware).
|
|
@@ -5977,8 +6308,9 @@ Size is the other edge axis. `t` is TypeBox-backed - it carries the whole JSON
|
|
|
5977
6308
|
Schema type system - so a validated app on `t` is heavier than one on a lean
|
|
5978
6309
|
validator. Validation is per route, so reach for `t` where you want the contract
|
|
5979
6310
|
(OpenAPI/MCP for free) and Valibot where the Workers cold-start bundle is what matters: a
|
|
5980
|
-
Valibot-validated Nifra app measures
|
|
5981
|
-
|
|
6311
|
+
minimal Valibot-validated Nifra app measures **about 38 KB gzipped**, against about 62 KB
|
|
6312
|
+
on `t` (`bun run bench:size`). Both are first-class, and you can mix
|
|
6313
|
+
them in one app.
|
|
5982
6314
|
|
|
5983
6315
|
### Scheduled (cron)
|
|
5984
6316
|
|
|
@@ -6098,7 +6430,7 @@ text (`string`) or binary (`ArrayBuffer`/typed-array)
|
|
|
6098
6430
|
|
|
6099
6431
|
`close(code?, reason?)`
|
|
6100
6432
|
|
|
6101
|
-
close the connection
|
|
6433
|
+
close the connection; with no code it sends 1000, on every runtime
|
|
6102
6434
|
|
|
6103
6435
|
`readyState`
|
|
6104
6436
|
|
|
@@ -6349,9 +6681,19 @@ it). Install it when you use `app.ws()`; without it a WS upgrade gets a clean
|
|
|
6349
6681
|
npm i ws
|
|
6350
6682
|
```
|
|
6351
6683
|
|
|
6684
|
+
`nifra dev` serves `app.ws()` routes too, on the Bun pipeline and under
|
|
6685
|
+
Vite, through each route's own `upgrade()` guard and `Origin`
|
|
6686
|
+
check. Under Vite the upgrade goes through Node's `upgrade` event, so it
|
|
6687
|
+
needs `ws` as well; without it a WS upgrade gets a `501` naming the
|
|
6688
|
+
package, and a path no WebSocket route takes stays with Vite's HMR.
|
|
6689
|
+
|
|
6352
6690
|
`server({ wsMaxPayloadBytes })` caps one inbound message (default
|
|
6353
6691
|
`maxBodyBytes`, 1 MB): a socket that sends more is closed with `1009`
|
|
6354
|
-
and the message never reaches your handler. Bun and Node refuse it while it arrives.
|
|
6692
|
+
and the message never reaches your handler. Bun and Node refuse it while it arrives. When a
|
|
6693
|
+
message passes Bun's own frame limit (the largest cap on the listener, below), Bun up to 1.4.3
|
|
6694
|
+
drops the connection without a close frame, so the client sees `1006`, and Bun
|
|
6695
|
+
1.4.4 sends `1009`; your `close` handler gets `1009` either
|
|
6696
|
+
way, as on every other runtime. Deno's
|
|
6355
6697
|
`Deno.upgradeWebSocket` takes no size limit, so Deno receives each message whole
|
|
6356
6698
|
(up to its own limit, 64 MiB on Deno 2.9) before nifra can check it: the cap still keeps the
|
|
6357
6699
|
message from your handler, but it does not bound the memory Deno spent receiving it. Where that
|
|
@@ -6844,7 +7186,7 @@ The declared production smoke checks: SSR, the mounted API, 404s, headers, auth,
|
|
|
6844
7186
|
|
|
6845
7187
|
`nifra cdn-check <url>`
|
|
6846
7188
|
|
|
6847
|
-
Check a deployed page behind a CDN: served from cache, no internal headers reaching visitors, and soft navigations getting
|
|
7189
|
+
Check a deployed page behind a CDN: served from cache, no internal headers reaching visitors, and soft navigations and slot swaps getting their own answer rather than the cached document.
|
|
6848
7190
|
|
|
6849
7191
|
`nifra i18n check [entry] [--strict]`
|
|
6850
7192
|
|
|
@@ -6924,6 +7266,10 @@ Regenerate `nifra-routes.d.ts` so `navigate({ to, search })` is typed by each ro
|
|
|
6924
7266
|
|
|
6925
7267
|
Regenerate a committed `server-manifest.ts` from `routes/` without a full build.
|
|
6926
7268
|
|
|
7269
|
+
`nifra scaffold hole <route> <name> [--shared] [--interactive] [--timeout <ms>] [--server]`
|
|
7270
|
+
|
|
7271
|
+
Experimental. Add a hole to a [partially prerendered](/docs/partial-prerendering) route: its definition, `boundaries` entry and `Hole` in a JSX page, and a loader with its output schema in the backend half. A Vue or Svelte page gets the code to paste.
|
|
7272
|
+
|
|
6927
7273
|
`nifra openapi [--format json | yaml] [--path <prefix>]`
|
|
6928
7274
|
|
|
6929
7275
|
The backend's OpenAPI document, including response types inferred at build time.
|
|
@@ -7209,6 +7555,10 @@ nifra init-agents --sync-mcp
|
|
|
7209
7555
|
The generated files are additive and the command will not overwrite an existing one, so it is
|
|
7210
7556
|
safe to re-run after a Nifra upgrade.
|
|
7211
7557
|
|
|
7558
|
+
For an agent that loads skills from a `skills/` directory,
|
|
7559
|
+
`@nifrajs/skills` packages Nifra's contracts, boundaries and gates as
|
|
7560
|
+
`SKILL.md` bundles, each read only when it applies.
|
|
7561
|
+
|
|
7212
7562
|
### The loop
|
|
7213
7563
|
|
|
7214
7564
|
```bash
|
|
@@ -7241,6 +7591,22 @@ nifra_assure # every route's required evidence, and what is missing
|
|
|
7241
7591
|
nifra_levels # { achieved, levels[] } - the ladder
|
|
7242
7592
|
```
|
|
7243
7593
|
|
|
7594
|
+
### Every tool
|
|
7595
|
+
|
|
7596
|
+
Each tool's MCP annotations say which of these it is, so a client can ask before a call that
|
|
7597
|
+
writes a file or runs project code. A tool that writes only under a flag counts as writing,
|
|
7598
|
+
and one that imports the project's config or backend, which runs its top-level code, counts
|
|
7599
|
+
as running project code.
|
|
7600
|
+
|
|
7601
|
+
Tool
|
|
7602
|
+
May
|
|
7603
|
+
What it does
|
|
7604
|
+
|
|
7605
|
+
`{name}`
|
|
7606
|
+
|
|
7607
|
+
{effect}
|
|
7608
|
+
{what}
|
|
7609
|
+
|
|
7244
7610
|
### What the running app saw
|
|
7245
7611
|
|
|
7246
7612
|
`nifra dev` keeps a feed of what happened while it ran, and the project tools read it
|
|
@@ -7319,7 +7685,10 @@ served, and every answer says so, so an agent treats a log line that reads like
|
|
|
7319
7685
|
as the data it is.
|
|
7320
7686
|
|
|
7321
7687
|
`nifra_run` returns the same evidence for the requests it makes: each result carries the
|
|
7322
|
-
console output and the structured errors that request produced.
|
|
7688
|
+
console output and the structured errors that request produced. Its engine is
|
|
7689
|
+
`@nifrajs/runner`: `runApp(app, requests)` runs requests through any
|
|
7690
|
+
app's `fetch` and never throws, in the browser (it backs the playground), Bun,
|
|
7691
|
+
Node, Deno or the edge.
|
|
7323
7692
|
|
|
7324
7693
|
### The development database
|
|
7325
7694
|
|
|
@@ -7442,10 +7811,11 @@ untrusted language is refused too, unless `allowExtensions` names it.
|
|
|
7442
7811
|
-
|
|
7443
7812
|
**Secret columns refused.** A query that reads a column whose name says
|
|
7444
7813
|
credential (`password`, `token`, `secret`,
|
|
7445
|
-
`api_key`, ...) or one in `redactColumns` is refused
|
|
7446
|
-
selected under another name, inside an expression, in a filter,
|
|
7447
|
-
|
|
7448
|
-
|
|
7814
|
+
`api_key`, ...) or one in `redactColumns` is refused wherever the
|
|
7815
|
+
query plan uses it: selected under another name, inside an expression, in a filter, through
|
|
7816
|
+
a view, or renamed by a table's column alias list. Functions that run SQL from a string,
|
|
7817
|
+
which the plan cannot see, are refused outright. Every other value goes through the same
|
|
7818
|
+
redactor as the dev feed: keys, tokens, JWTs and the project's environment values.
|
|
7449
7819
|
|
|
7450
7820
|
-
|
|
7451
7821
|
**Data, not instructions.** Rows, and names from the schema, are marked
|
|
@@ -7528,8 +7898,8 @@ does not exist. `nifra_db_schema` lists what is exposed.
|
|
|
7528
7898
|
|
|
7529
7899
|
#### NIFRA_DB_COLUMN_REFUSED
|
|
7530
7900
|
|
|
7531
|
-
The query reads a masked column: a credential name, or one in `redactColumns`.
|
|
7532
|
-
|
|
7901
|
+
The query reads a masked column: a credential name, or one in `redactColumns`. A
|
|
7902
|
+
query is refused wherever its plan reads one, so select the other columns by name (`SELECT *` on that
|
|
7533
7903
|
table is refused too), or list the column in `revealColumns` if it holds no secret.
|
|
7534
7904
|
|
|
7535
7905
|
#### NIFRA_DB_TIMEOUT
|
|
@@ -7663,6 +8033,13 @@ serves a SQLite database as its own MCP server, fail-closed: allowlisted schema
|
|
|
7663
8033
|
default, and read-only queries only when you opt in, with plan verification. Handing a model a
|
|
7664
8034
|
database connection is not the same as handing it a query tool, and this is the second one.
|
|
7665
8035
|
|
|
8036
|
+
**
|
|
8037
|
+
`@nifrajs/agent-review`
|
|
8038
|
+
**
|
|
8039
|
+
is the bounded review-report contract `nifra review` emits: scope, checks,
|
|
8040
|
+
findings and a digest, with no source content. A tool of your own can compose and parse the
|
|
8041
|
+
same report.
|
|
8042
|
+
|
|
7666
8043
|
### Run a coding agent
|
|
7667
8044
|
|
|
7668
8045
|
`@nifrajs/agent-protocol` is the small versioned session and event contract.
|
|
@@ -8105,7 +8482,8 @@ export function Counter(props: { message: string }) {
|
|
|
8105
8482
|
|
|
8106
8483
|
`@nifrajs/devtools` is a plugin that streams what each request actually did - loader
|
|
8107
8484
|
traces, ISR status, route metadata - over a secured SSE endpoint, with an overlay to read it
|
|
8108
|
-
in the browser.
|
|
8485
|
+
in the browser. In an app with [keep-alive](/docs/keep-alive) routes, the overlay
|
|
8486
|
+
also lists the pages kept hidden.
|
|
8109
8487
|
|
|
8110
8488
|
```ts
|
|
8111
8489
|
import { server } from "@nifrajs/core/server"
|
|
@@ -9379,6 +9757,79 @@ connection strings, tokens, and payload fragments, and evidence is meant to be s
|
|
|
9379
9757
|
never becomes a place credentials leak. Cleanup errors cannot turn a failed functional check
|
|
9380
9758
|
into a pass.
|
|
9381
9759
|
|
|
9760
|
+
## Nifra - Content & MDX
|
|
9761
|
+
|
|
9762
|
+
> Typed content collections + MDX - author docs and blogs in Markdown with embedded components.
|
|
9763
|
+
|
|
9764
|
+
Nifra ships **typed content collections** and **MDX** - the backbone of a docs site, blog, or changelog,
|
|
9765
|
+
without hand-rolling `readdir` and a frontmatter parser.
|
|
9766
|
+
|
|
9767
|
+
> **This very page is written in MDX.** The note you're reading is a real `<Callout>` React component
|
|
9768
|
+
> embedded directly in the Markdown prose and server-rendered by nifra.
|
|
9769
|
+
|
|
9770
|
+
### Content collections
|
|
9771
|
+
|
|
9772
|
+
`defineCollection` turns a folder of Markdown into a typed, schema-validated source. The frontmatter is
|
|
9773
|
+
validated against a `t` schema, so a typo'd or missing field fails the build - not production - and the
|
|
9774
|
+
entries are fully typed into your loaders:
|
|
9775
|
+
|
|
9776
|
+
```ts
|
|
9777
|
+
import { defineCollection } from "@nifrajs/content/fs"
|
|
9778
|
+
import { t } from "@nifrajs/schema"
|
|
9779
|
+
|
|
9780
|
+
export const blog = defineCollection({
|
|
9781
|
+
dir: "content/blog",
|
|
9782
|
+
schema: t.object({ title: t.string(), date: t.string(), draft: t.boolean() }),
|
|
9783
|
+
})
|
|
9784
|
+
|
|
9785
|
+
// in a loader - typed + validated entries (a typo'd field fails the build, not production):
|
|
9786
|
+
const posts = (await blog.all()).filter((p) => !p.frontmatter.draft)
|
|
9787
|
+
```
|
|
9788
|
+
|
|
9789
|
+
`all()` lists the folder and checks each file for changes on every call, so an edit shows without a
|
|
9790
|
+
restart. When the content ships with the build, pass `watch: false` to read it once and reuse that
|
|
9791
|
+
snapshot; `get(slug)` still checks its one file.
|
|
9792
|
+
|
|
9793
|
+
### MDX routes
|
|
9794
|
+
|
|
9795
|
+
Add the MDX plugin to your build and any `routes/**/*.mdx` file becomes a page - Markdown that can
|
|
9796
|
+
`import` and render components inline, and `export const meta`, exactly like a `.tsx` route:
|
|
9797
|
+
|
|
9798
|
+
```ts
|
|
9799
|
+
import { mdxBunPlugin } from "@nifrajs/content/mdx"
|
|
9800
|
+
|
|
9801
|
+
// build.ts - every routes/**/*.mdx file compiles to a component for your framework
|
|
9802
|
+
await buildClient({
|
|
9803
|
+
routesDir: "./routes",
|
|
9804
|
+
clientModule: "@nifrajs/web-react/client",
|
|
9805
|
+
plugins: [mdxBunPlugin({ jsxImportSource: "react" })],
|
|
9806
|
+
})
|
|
9807
|
+
```
|
|
9808
|
+
|
|
9809
|
+
### MDX on all five frameworks
|
|
9810
|
+
|
|
9811
|
+
MDX is framework-agnostic in Nifra - same as everything else. Each framework gets a build plugin that
|
|
9812
|
+
compiles `.mdx` to *its* component model:
|
|
9813
|
+
|
|
9814
|
+
```ts
|
|
9815
|
+
// React / Preact / Vue - one plugin, pick the JSX runtime:
|
|
9816
|
+
import { mdxBunPlugin } from "@nifrajs/content/mdx"
|
|
9817
|
+
mdxBunPlugin({ jsxImportSource: "react" }) // or "preact" | "vue"
|
|
9818
|
+
|
|
9819
|
+
// Solid - compile-time transform + an intrinsics runtime:
|
|
9820
|
+
import { solidMdxBunPlugin } from "@nifrajs/web-solid/mdx"
|
|
9821
|
+
solidMdxBunPlugin("ssr") // "dom" for the client build
|
|
9822
|
+
|
|
9823
|
+
// Svelte - through mdsvex (Svelte's own Markdown compiler):
|
|
9824
|
+
import { svelteMdxBunPlugin } from "@nifrajs/web-svelte/mdx"
|
|
9825
|
+
svelteMdxBunPlugin("ssr")
|
|
9826
|
+
```
|
|
9827
|
+
|
|
9828
|
+
React, Preact, and Vue share one plugin (their JSX runtimes differ only by `jsxImportSource`). Solid
|
|
9829
|
+
needs its compile-time transform, so `@nifrajs/web-solid/mdx` runs `babel-preset-solid` over the MDX and
|
|
9830
|
+
maps intrinsic tags through `<Dynamic>`. Svelte has no JSX, so `@nifrajs/web-svelte/mdx` routes MDX through
|
|
9831
|
+
`mdsvex` - Svelte's own Markdown compiler. All five server-render and hydrate.
|
|
9832
|
+
|
|
9382
9833
|
## Nifra - Framework contract
|
|
9383
9834
|
|
|
9384
9835
|
> The one-page contract: LoaderContext shape, loader/action/meta/head signatures, the client↔server boundary, and the build-output contract - every signature verified against the source.
|
|
@@ -9547,8 +9998,9 @@ response carrying `Set-Cookie`).
|
|
|
9547
9998
|
URL as the document with an `x-nifra-data` request header, so its response is
|
|
9548
9999
|
always `cache-control: private, no-store` with `vary: x-nifra-data`,
|
|
9549
10000
|
and a document that carries loader headers gets `x-nifra-data` added to its
|
|
9550
|
-
`vary`. A
|
|
9551
|
-
|
|
10001
|
+
`vary`. A slot swap's response (`x-nifra-swap`) is
|
|
10002
|
+
`private, no-store` with `vary: x-nifra-swap` too. A CDN that ignores
|
|
10003
|
+
`Vary` must bypass its cache for both headers when it caches documents.
|
|
9552
10004
|
|
|
9553
10005
|
-
|
|
9554
10006
|
**Write before you return.** The controls close when the loader or action
|
|
@@ -10950,13 +11402,42 @@ serving the old page until its freshness runs out. The revalidate endpoint answe
|
|
|
10950
11402
|
permission for this zone, project or service; a 5xx or `network_error` is retried on
|
|
10951
11403
|
its own.
|
|
10952
11404
|
|
|
10953
|
-
###
|
|
11405
|
+
### Keep-alive
|
|
10954
11406
|
|
|
10955
|
-
|
|
10956
|
-
|
|
10957
|
-
|
|
10958
|
-
|
|
10959
|
-
|
|
11407
|
+
#### NIFRA_KEEPALIVE_IDENTITY_COOKIE
|
|
11408
|
+
|
|
11409
|
+
The app keeps pages alive, and a response changed or deleted an `HttpOnly` cookie
|
|
11410
|
+
Nifra does not know as a sign-in cookie. If that cookie says who is signed in, a sign-in or
|
|
11411
|
+
sign-out through it leaves the previous visitor's kept pages in every tab, and back shows
|
|
11412
|
+
them. Development reports each cookie name once.
|
|
11413
|
+
|
|
11414
|
+
**Fix:** name the cookie in
|
|
11415
|
+
`createWebApp({ keepAlive: { identityCookies } })` if it
|
|
11416
|
+
carries the session, or in `keepAlive.ignoreCookies` if it does not. When the
|
|
11417
|
+
session is a token in client storage, call `identityChanged()` from
|
|
11418
|
+
`@nifrajs/web/client` at sign-in and sign-out. See
|
|
11419
|
+
[keep-alive and sign-in](/docs/keep-alive#sign-in).
|
|
11420
|
+
|
|
11421
|
+
#### NIFRA_KEEPALIVE_DIRECT_CHILD_CSS
|
|
11422
|
+
|
|
11423
|
+
A `keepAlive` page renders inside two `display:contents` wrappers, so a
|
|
11424
|
+
selector that reached its root element as a direct child of the layout (
|
|
11425
|
+
`main > section`), by its position among siblings (`:first-child`,
|
|
11426
|
+
`:nth-child()`), or through `:has(> ...)` on the layout no longer
|
|
11427
|
+
matches it. Development checks the page's same-origin stylesheets the first time it is shown
|
|
11428
|
+
and reports each selector once.
|
|
11429
|
+
|
|
11430
|
+
**Fix:** use a descendant combinator (`main section`), target the
|
|
11431
|
+
wrapper (`[data-nifra-page] > section`), or give the page's root element a class
|
|
11432
|
+
and select that.
|
|
11433
|
+
|
|
11434
|
+
### Silencing a nifra check finding
|
|
11435
|
+
|
|
11436
|
+
`nifra check` names each finding with an `NF-` code;
|
|
11437
|
+
`nifra explain NF-C007` (or `nifra_explain` with the code as its
|
|
11438
|
+
`error`) says what the rule reports, why it matters, how to fix it and where it is
|
|
11439
|
+
documented. Where a finding is reviewed and intended, a comment on the flagged line, or anywhere
|
|
11440
|
+
in the comment block directly above it, says so and why:
|
|
10960
11441
|
|
|
10961
11442
|
```ts
|
|
10962
11443
|
// nifra-expect NF-S002: compares the challenge the sender echoes back, not a secret
|
|
@@ -11267,6 +11748,515 @@ session, a tenant), mount routes of its own, or hook the request lifecycle. That
|
|
|
11267
11748
|
`definePlugin` - a few lines, typed end-to-end. For everything else, an import
|
|
11268
11749
|
at the top of the file is the whole integration.
|
|
11269
11750
|
|
|
11751
|
+
### GraphQL
|
|
11752
|
+
|
|
11753
|
+
`@nifrajs/graphql` mounts a GraphQL-over-HTTP endpoint with
|
|
11754
|
+
`mountGraphql`, executed by the `graphql` package's own parser and
|
|
11755
|
+
executor, with your typed nifra context passed to the resolvers. Subscriptions run over
|
|
11756
|
+
nifra's WebSocket lane with `graphql-ws`. The request body goes through the same
|
|
11757
|
+
bounded parser as every other route, and the query text is never logged.
|
|
11758
|
+
|
|
11759
|
+
## Nifra - Keep-alive
|
|
11760
|
+
|
|
11761
|
+
> Pages that stay mounted after the visitor leaves them: back and forward bring back the same page, with its scroll, form input and component state, and a sign-out drops them in every tab.
|
|
11762
|
+
|
|
11763
|
+
A route that exports `keepAlive` stays mounted after the visitor leaves it. Back
|
|
11764
|
+
and forward bring back the same page, not a new render of it: its scroll positions, form
|
|
11765
|
+
input, open `<details>`, focus and component state are where the visitor
|
|
11766
|
+
left them.
|
|
11767
|
+
|
|
11768
|
+
### Keep a page
|
|
11769
|
+
|
|
11770
|
+
```tsx
|
|
11771
|
+
// doc-check: skip - a route module; the page component is the app's own.
|
|
11772
|
+
// routes/orders/[id].tsx
|
|
11773
|
+
export const keepAlive = true
|
|
11774
|
+
|
|
11775
|
+
export default function Order({ data }: { data: OrderData }) {
|
|
11776
|
+
// ...
|
|
11777
|
+
}
|
|
11778
|
+
```
|
|
11779
|
+
|
|
11780
|
+
Pass options instead of `true` to change how the page comes back:
|
|
11781
|
+
|
|
11782
|
+
```ts
|
|
11783
|
+
import type { KeepAliveOptions } from "@nifrajs/web"
|
|
11784
|
+
|
|
11785
|
+
// Show the kept page as it was, without reloading its data; drop it after a minute hidden.
|
|
11786
|
+
export const keepAlive: KeepAliveOptions = { revalidate: false, maxAge: 60_000 }
|
|
11787
|
+
```
|
|
11788
|
+
|
|
11789
|
+
`keepAlive` works with the React (19.2 or later, for
|
|
11790
|
+
`<Activity>`), Preact, Solid, Svelte and Vue adapters. A build with another
|
|
11791
|
+
adapter fails and names the routes that export it.
|
|
11792
|
+
|
|
11793
|
+
### When a page is kept, and when it comes back
|
|
11794
|
+
|
|
11795
|
+
-
|
|
11796
|
+
A page is kept when the visitor leaves it by a link, a form or back and forward. A redirect
|
|
11797
|
+
or a `replace` navigation discards it, since its history entry is gone.
|
|
11798
|
+
|
|
11799
|
+
-
|
|
11800
|
+
Only back or forward to the page's own history entry brings it back. A link to the same
|
|
11801
|
+
path renders a fresh page.
|
|
11802
|
+
|
|
11803
|
+
-
|
|
11804
|
+
A new path on the same route is a new page: `/orders/1` and
|
|
11805
|
+
`/orders/2` are kept apart. A change of the query string alone keeps the page.
|
|
11806
|
+
|
|
11807
|
+
-
|
|
11808
|
+
A tab keeps at most three pages, dropping the one shown longest ago, and none hidden
|
|
11809
|
+
longer than ten minutes, or the route's `maxAge`.
|
|
11810
|
+
|
|
11811
|
+
-
|
|
11812
|
+
Going back and then following a link drops the pages ahead of it, as the browser drops
|
|
11813
|
+
those history entries.
|
|
11814
|
+
|
|
11815
|
+
-
|
|
11816
|
+
A page left with a [route open in a modal](/docs/routing#modal-routes) over
|
|
11817
|
+
it is kept with the modal. Back to that entry shows the page and opens the modal over it
|
|
11818
|
+
again.
|
|
11819
|
+
|
|
11820
|
+
### What changes when a page stays mounted
|
|
11821
|
+
|
|
11822
|
+
-
|
|
11823
|
+
Code that runs when a page mounts runs once for that page, not on every visit. Back to a
|
|
11824
|
+
kept page does not mount it again; work that belongs to each visit goes in
|
|
11825
|
+
`onPageShow`. React is the exception: `<Activity>` runs the
|
|
11826
|
+
page's effects again each time it is shown.
|
|
11827
|
+
|
|
11828
|
+
-
|
|
11829
|
+
In Preact, Solid, Svelte and Vue a hidden page keeps running: its timers fire, its
|
|
11830
|
+
subscriptions deliver, its stores update. Pause what should not run unseen with
|
|
11831
|
+
`onPageHide`.
|
|
11832
|
+
|
|
11833
|
+
-
|
|
11834
|
+
State outlives the visit. Form input, a filter, an open panel are where the visitor left
|
|
11835
|
+
them; reset in `onPageShow` what must start fresh.
|
|
11836
|
+
|
|
11837
|
+
-
|
|
11838
|
+
Each kept page holds its DOM and its components' memory, at most three per tab. In
|
|
11839
|
+
development, the [devtools overlay](/docs/dev#devtools) lists them with their
|
|
11840
|
+
path, how long each has been hidden and how many elements it renders.
|
|
11841
|
+
|
|
11842
|
+
### Fresh data
|
|
11843
|
+
|
|
11844
|
+
A page comes back at once, as it was left, and reloads its data behind it. The reload is
|
|
11845
|
+
shared onto the data the page already holds: what did not change keeps its identity, so
|
|
11846
|
+
nothing below an unchanged value renders again, and form input in a list survives. Set
|
|
11847
|
+
`revalidate: false` to skip the reload; an action submitted while the page was
|
|
11848
|
+
hidden still reloads it.
|
|
11849
|
+
|
|
11850
|
+
A [partially prerendered](/docs/partial-prerendering) page that is kept stops its
|
|
11851
|
+
holes while it is hidden: a hole still loading is cancelled on the server, and a reload on its
|
|
11852
|
+
way is dropped. When the page comes back each hole reloads in place, its old content marked
|
|
11853
|
+
`aria-busy="true"` until the new arrives, with `revalidate: false` too.
|
|
11854
|
+
An interactive hole keeps its state through it, in React as well, where
|
|
11855
|
+
`<Activity>` cleans the page's effects up while it is hidden.
|
|
11856
|
+
|
|
11857
|
+
With [live refresh](/docs/live), a hidden page is not watched. When it comes back,
|
|
11858
|
+
what changed while it was hidden reloads, whatever `revalidate` says, and a grant
|
|
11859
|
+
that expired in the meantime is loaded again.
|
|
11860
|
+
|
|
11861
|
+
### While a page is hidden
|
|
11862
|
+
|
|
11863
|
+
A kept page is taken out of the document. It is absent from the accessibility tree, its
|
|
11864
|
+
media stops, and its ids never collide with the page on screen. It renders from its own
|
|
11865
|
+
route state, so it never sees another page's params.
|
|
11866
|
+
|
|
11867
|
+
In React, `<Activity>` cleans up the page's effects while it is hidden and
|
|
11868
|
+
runs them again when it is shown. `usePageVisibility()` reads which it is:
|
|
11869
|
+
|
|
11870
|
+
```tsx
|
|
11871
|
+
// doc-check: skip - a page component; Chart is the app's own.
|
|
11872
|
+
import { usePageVisibility } from "@nifrajs/web-react/router"
|
|
11873
|
+
|
|
11874
|
+
export default function Dashboard() {
|
|
11875
|
+
const visible = usePageVisibility()
|
|
11876
|
+
return <Chart animate={visible} />
|
|
11877
|
+
}
|
|
11878
|
+
```
|
|
11879
|
+
|
|
11880
|
+
A Preact, Solid, Svelte or Vue page keeps running while it is hidden. Pause timers, sockets
|
|
11881
|
+
and media with `onPageHide` and resume them with `onPageShow`, from
|
|
11882
|
+
each adapter's `/router`:
|
|
11883
|
+
|
|
11884
|
+
```svelte
|
|
11885
|
+
<script>
|
|
11886
|
+
import { onMount } from "svelte"
|
|
11887
|
+
import { onPageHide, onPageShow } from "@nifrajs/web-svelte/router"
|
|
11888
|
+
let timer
|
|
11889
|
+
const start = () => (timer = setInterval(refresh, 5000))
|
|
11890
|
+
const stop = () => clearInterval(timer)
|
|
11891
|
+
const offHide = onPageHide(stop)
|
|
11892
|
+
const offShow = onPageShow(start)
|
|
11893
|
+
// onMount runs in the browser only, so the server starts no timer.
|
|
11894
|
+
onMount(() => {
|
|
11895
|
+
start()
|
|
11896
|
+
return () => {
|
|
11897
|
+
stop()
|
|
11898
|
+
offHide()
|
|
11899
|
+
offShow()
|
|
11900
|
+
}
|
|
11901
|
+
})
|
|
11902
|
+
</script>
|
|
11903
|
+
```
|
|
11904
|
+
|
|
11905
|
+
```vue
|
|
11906
|
+
<script setup lang="ts">
|
|
11907
|
+
import { onPageHide, onPageShow } from "@nifrajs/web-vue/router"
|
|
11908
|
+
import { onMounted, onUnmounted } from "vue"
|
|
11909
|
+
let socket: Socket | undefined
|
|
11910
|
+
onMounted(() => {
|
|
11911
|
+
socket = connect()
|
|
11912
|
+
})
|
|
11913
|
+
onUnmounted(() => socket?.close())
|
|
11914
|
+
onPageHide(() => socket?.pause())
|
|
11915
|
+
onPageShow(() => socket?.resume())
|
|
11916
|
+
</script>
|
|
11917
|
+
```
|
|
11918
|
+
|
|
11919
|
+
Adapter
|
|
11920
|
+
|
|
11921
|
+
`usePageVisibility()`
|
|
11922
|
+
|
|
11923
|
+
`onPageHide` / `onPageShow`
|
|
11924
|
+
|
|
11925
|
+
React
|
|
11926
|
+
a boolean
|
|
11927
|
+
effects, which hiding cleans up
|
|
11928
|
+
|
|
11929
|
+
Preact
|
|
11930
|
+
a boolean
|
|
11931
|
+
hooks
|
|
11932
|
+
|
|
11933
|
+
Solid
|
|
11934
|
+
an accessor
|
|
11935
|
+
run in a component, removed with it
|
|
11936
|
+
|
|
11937
|
+
Svelte
|
|
11938
|
+
a getter
|
|
11939
|
+
run as the component initializes, return their removal
|
|
11940
|
+
|
|
11941
|
+
Vue
|
|
11942
|
+
a ref
|
|
11943
|
+
|
|
11944
|
+
run in `setup`; `onActivated` / `onDeactivated` also
|
|
11945
|
+
run
|
|
11946
|
+
|
|
11947
|
+
A `useBlocker` in a hidden page blocks nothing. Any code can listen for the
|
|
11948
|
+
`nifra:pagehide` and `nifra:pageshow` events, which bubble from the
|
|
11949
|
+
page. An island inside a kept page stays mounted with it; its enhancer pauses with
|
|
11950
|
+
`onPageHide` and `onPageShow` from `@nifrajs/web/islands`:
|
|
11951
|
+
|
|
11952
|
+
```ts
|
|
11953
|
+
import { defineIsland, onPageHide, onPageShow } from "@nifrajs/web/islands"
|
|
11954
|
+
|
|
11955
|
+
export const clock = defineIsland((el) => {
|
|
11956
|
+
const tick = () => {
|
|
11957
|
+
el.textContent = new Date().toLocaleTimeString()
|
|
11958
|
+
}
|
|
11959
|
+
let timer = setInterval(tick, 1000)
|
|
11960
|
+
const hide = onPageHide(el, () => clearInterval(timer))
|
|
11961
|
+
const show = onPageShow(el, () => {
|
|
11962
|
+
timer = setInterval(tick, 1000)
|
|
11963
|
+
})
|
|
11964
|
+
return () => {
|
|
11965
|
+
hide()
|
|
11966
|
+
show()
|
|
11967
|
+
clearInterval(timer)
|
|
11968
|
+
}
|
|
11969
|
+
})
|
|
11970
|
+
```
|
|
11971
|
+
|
|
11972
|
+
The [server components](/docs/server-components) of a kept page stay mounted too.
|
|
11973
|
+
With `bindComponentRouter` installed, navigation leaves them alone while the page
|
|
11974
|
+
is hidden, and the reload of a page that comes back updates them.
|
|
11975
|
+
|
|
11976
|
+
### CSS around a kept page
|
|
11977
|
+
|
|
11978
|
+
A kept page renders inside two `<slot>` elements,
|
|
11979
|
+
`[data-nifra-entry]` and `[data-nifra-page]`; so does a layout below
|
|
11980
|
+
which the routes' layouts differ. Browsers lay a `<slot>` out as
|
|
11981
|
+
`display: contents`, and the wrappers carry no inline style, so a strict
|
|
11982
|
+
`style-src` needs nothing for them. Vue, whose `<KeepAlive>`
|
|
11983
|
+
moves the page itself, renders neither. They take no box, but a selector that reached the
|
|
11984
|
+
page's root as a direct child, or by its position among siblings, stops matching:
|
|
11985
|
+
|
|
11986
|
+
```text
|
|
11987
|
+
/* Stops matching: the wrappers sit between main and the page's root */
|
|
11988
|
+
main > section { padding: 2rem; }
|
|
11989
|
+
|
|
11990
|
+
/* Matches, kept or not */
|
|
11991
|
+
main section { padding: 2rem; }
|
|
11992
|
+
[data-nifra-page] > section { padding: 2rem; }
|
|
11993
|
+
```
|
|
11994
|
+
|
|
11995
|
+
In development, the first time a kept page is shown the client reads the page's
|
|
11996
|
+
same-origin stylesheets and reports each such selector once, as
|
|
11997
|
+
[NIFRA_KEEPALIVE_DIRECT_CHILD_CSS](/docs/errors#keepalive-direct-child-css).
|
|
11998
|
+
|
|
11999
|
+
### Keep-alive and sign-in
|
|
12000
|
+
|
|
12001
|
+
A page kept for one visitor must never come back for the next. When a response signs a
|
|
12002
|
+
visitor in or out, the server also rotates a readable epoch cookie (
|
|
12003
|
+
`__Host-nifra-epoch`, or `nifra-epoch` on local `http:`)
|
|
12004
|
+
with the session cookie's lifetime. A tab that reads a new epoch drops every page it kept and
|
|
12005
|
+
tells the other tabs of the origin to do the same. A sign-out by a native form post, or a
|
|
12006
|
+
session that expires while the visitor is away, is covered the same way: back compares the
|
|
12007
|
+
epoch before it shows a kept page.
|
|
12008
|
+
|
|
12009
|
+
The session cookies of `@nifrajs/auth`, Better Auth and Auth.js count under their
|
|
12010
|
+
default names. Name any other in `identityCookies`:
|
|
12011
|
+
|
|
12012
|
+
```ts
|
|
12013
|
+
// doc-check: skip - adapter, manifest and clientEntry are the app's own.
|
|
12014
|
+
const app = createWebApp({
|
|
12015
|
+
adapter,
|
|
12016
|
+
manifest,
|
|
12017
|
+
clientEntry,
|
|
12018
|
+
keepAlive: {
|
|
12019
|
+
identityCookies: ["sid"], // your own session cookie
|
|
12020
|
+
ignoreCookies: ["cart"], // HttpOnly, but says nothing about who is signed in
|
|
12021
|
+
},
|
|
12022
|
+
})
|
|
12023
|
+
```
|
|
12024
|
+
|
|
12025
|
+
In development, an `HttpOnly` cookie that changes and is in neither list is
|
|
12026
|
+
reported once, as
|
|
12027
|
+
[NIFRA_KEEPALIVE_IDENTITY_COOKIE](/docs/errors#keepalive-identity-cookie). A flow
|
|
12028
|
+
that changes who is signed in without changing a cookie rotates the epoch itself:
|
|
12029
|
+
|
|
12030
|
+
```ts
|
|
12031
|
+
import { server } from "@nifrajs/core/server"
|
|
12032
|
+
import { rotateIdentityEpoch } from "@nifrajs/web"
|
|
12033
|
+
|
|
12034
|
+
// A flow that changes who is signed in without changing a watched cookie.
|
|
12035
|
+
export const api = server().post("/switch-account", (c) => {
|
|
12036
|
+
rotateIdentityEpoch(c)
|
|
12037
|
+
return { ok: true }
|
|
12038
|
+
})
|
|
12039
|
+
```
|
|
12040
|
+
|
|
12041
|
+
When identity lives in client storage, as a bearer token, call `identityChanged()`
|
|
12042
|
+
at sign-in and sign-out:
|
|
12043
|
+
|
|
12044
|
+
```ts
|
|
12045
|
+
import { identityChanged } from "@nifrajs/web/client"
|
|
12046
|
+
|
|
12047
|
+
// Identity in client storage: say so at sign-in and sign-out.
|
|
12048
|
+
export function signOut(): void {
|
|
12049
|
+
localStorage.removeItem("token")
|
|
12050
|
+
identityChanged()
|
|
12051
|
+
}
|
|
12052
|
+
```
|
|
12053
|
+
|
|
12054
|
+
A document the browser puts in its back/forward cache drops its kept pages first, so a
|
|
12055
|
+
cached document never carries them.
|
|
12056
|
+
|
|
12057
|
+
### Limits
|
|
12058
|
+
|
|
12059
|
+
-
|
|
12060
|
+
A route with a `clientLoader` runs it again when the page comes back, even with
|
|
12061
|
+
`revalidate: false`.
|
|
12062
|
+
|
|
12063
|
+
- A hot update of a route module drops every kept page.
|
|
12064
|
+
|
|
12065
|
+
## Nifra - Live refresh
|
|
12066
|
+
|
|
12067
|
+
> Pages that stay fresh on their own: loaders declare live keys, a publish reloads only what read them, through the same authorized path a navigation takes.
|
|
12068
|
+
|
|
12069
|
+
Pages stay fresh on their own. A loader declares the keys its data depends on; when one
|
|
12070
|
+
changes, every open page that read it reloads just the loaders that read it, through the
|
|
12071
|
+
same authorized path a navigation takes. A change notice never carries data.
|
|
12072
|
+
|
|
12073
|
+
### Set up
|
|
12074
|
+
|
|
12075
|
+
Create one live runtime. `subject` names the viewer: a grant is only honored for
|
|
12076
|
+
the viewer it was issued to, and a different viewer on the same tab clears every cache the
|
|
12077
|
+
page holds.
|
|
12078
|
+
|
|
12079
|
+
```ts
|
|
12080
|
+
import { live } from "@nifrajs/web/live"
|
|
12081
|
+
|
|
12082
|
+
// Your session lookup: a stable user id, or null for an anonymous viewer.
|
|
12083
|
+
declare function sessionUserId(request: Request): Promise<string | null>
|
|
12084
|
+
|
|
12085
|
+
export const liveRuntime = live({
|
|
12086
|
+
secret: process.env.LIVE_SECRET, // openssl rand -base64 32; required in production
|
|
12087
|
+
subject: (ctx) => sessionUserId(ctx.request),
|
|
12088
|
+
})
|
|
12089
|
+
```
|
|
12090
|
+
|
|
12091
|
+
Hand it to `createWebApp`, and give the client build its endpoints. With the CLI,
|
|
12092
|
+
export it as `live` from `backend/framework.ts` instead:
|
|
12093
|
+
`nifra dev` serves its socket, and `nifra build` does both.
|
|
12094
|
+
|
|
12095
|
+
```ts
|
|
12096
|
+
// doc-check: skip - adapter, manifest and the build are the app's own, as on the custom-server page.
|
|
12097
|
+
const app = createWebApp({ adapter, manifest, clientEntry: build.entry, live: liveRuntime })
|
|
12098
|
+
|
|
12099
|
+
// The client build sends route loads through the live endpoints.
|
|
12100
|
+
await buildClient({ routesDir, outDir, clientModule, live: liveRuntime.clientEntry })
|
|
12101
|
+
```
|
|
12102
|
+
|
|
12103
|
+
### Declare keys
|
|
12104
|
+
|
|
12105
|
+
`live(...keys)` in any loader, page or layout, names what its data reads. A key
|
|
12106
|
+
is your own name for a piece of data, such as `post:42`: a letter, then up to
|
|
12107
|
+
127 of `A-Z a-z 0-9 . _ : / -`. A frame holds at most 64. A live load returns
|
|
12108
|
+
an encrypted grant for its keys beside the data. A hole of a
|
|
12109
|
+
[partially prerendered page](/docs/partial-prerendering) declares its own the
|
|
12110
|
+
same way, and a change reloads that hole alone.
|
|
12111
|
+
|
|
12112
|
+
```ts
|
|
12113
|
+
// doc-check: skip - a route's backend half; db is the app's own.
|
|
12114
|
+
export async function loader({ params, live }: Route.LoaderArgs) {
|
|
12115
|
+
live(`post:${params.id}`, `comments:${params.id}`)
|
|
12116
|
+
return { post: await db.post(params.id), comments: await db.comments(params.id) }
|
|
12117
|
+
}
|
|
12118
|
+
```
|
|
12119
|
+
|
|
12120
|
+
### Publish changes
|
|
12121
|
+
|
|
12122
|
+
Call `publish(...keys)` once the write is readable by loaders. With read
|
|
12123
|
+
replicas, pass `live({ visible })`, a function that resolves once loaders can
|
|
12124
|
+
read the write; every publish waits for it. An action can name the keys it changed in
|
|
12125
|
+
`revalidate()`, which publishes them after the caches it clears.
|
|
12126
|
+
|
|
12127
|
+
```ts
|
|
12128
|
+
// doc-check: skip - db and the action's input are the app's own.
|
|
12129
|
+
// After the write is readable by loaders:
|
|
12130
|
+
await db.updatePost(id, input)
|
|
12131
|
+
await liveRuntime.publish(`post:${id}`)
|
|
12132
|
+
|
|
12133
|
+
// Or from an action, beside the paths and cache tags the write made stale:
|
|
12134
|
+
return revalidate([`/posts/${id}`], result, { keys: [`post:${id}`] })
|
|
12135
|
+
```
|
|
12136
|
+
|
|
12137
|
+
Each tab holds one WebSocket. A change reaches it as an opaque tag: no data, key text,
|
|
12138
|
+
subject or sequence number is on the wire. The tab reloads only the loaders whose keys
|
|
12139
|
+
changed, keeps the rest as shown, and spreads reloads over up to five seconds when many tabs
|
|
12140
|
+
watch one key. Live loads are capped per process (`maxConcurrentLoads`, default
|
|
12141
|
+
64) and answered 503 past it, so a hot key cannot overload your database. In a load test of
|
|
12142
|
+
10,000 tabs on one key across two Bun processes, no process ran more than 64 loaders at
|
|
12143
|
+
once, and with `reloadRate: 5000` every tab had the new data within 2.1 seconds.
|
|
12144
|
+
|
|
12145
|
+
### Revoke access
|
|
12146
|
+
|
|
12147
|
+
```ts
|
|
12148
|
+
// doc-check: skip - userId and projectId are the app's own.
|
|
12149
|
+
await liveRuntime.revoke(userId) // every grant issued to them, and their sockets
|
|
12150
|
+
await liveRuntime.revokeKey(`project:${projectId}`, userId) // one key, for one viewer
|
|
12151
|
+
await liveRuntime.revokeAll() // every grant issued before now
|
|
12152
|
+
```
|
|
12153
|
+
|
|
12154
|
+
A revoked key sends one last change to every affected socket, and no grant issued before the
|
|
12155
|
+
revocation keeps or re-signs it, so the next load runs that loader, which decides again.
|
|
12156
|
+
|
|
12157
|
+
### Many processes
|
|
12158
|
+
|
|
12159
|
+
The default bus serves one process. Behind a load balancer, give every process the same
|
|
12160
|
+
Redis Streams log. A reader that falls behind the stream's trim, or whose connection stops
|
|
12161
|
+
answering (`readTimeoutMs`), resyncs its sockets rather than miss a change.
|
|
12162
|
+
|
|
12163
|
+
```ts
|
|
12164
|
+
import { live } from "@nifrajs/web/live"
|
|
12165
|
+
import { redisLiveBus } from "@nifrajs/web/live-redis"
|
|
12166
|
+
|
|
12167
|
+
const url = process.env.REDIS_URL ?? "redis://127.0.0.1:6379"
|
|
12168
|
+
const send = new Bun.RedisClient(url)
|
|
12169
|
+
const read = new Bun.RedisClient(url) // its own connection: XREAD blocks it
|
|
12170
|
+
|
|
12171
|
+
export const liveRuntime = live({
|
|
12172
|
+
secret: process.env.LIVE_SECRET,
|
|
12173
|
+
subject: () => null,
|
|
12174
|
+
bus: redisLiveBus({
|
|
12175
|
+
send: (command, args) => send.send(command, [...args]),
|
|
12176
|
+
read: (command, args) => read.send(command, [...args]),
|
|
12177
|
+
}),
|
|
12178
|
+
instances: 4, // processes serving the app, for spreading reloads
|
|
12179
|
+
})
|
|
12180
|
+
```
|
|
12181
|
+
|
|
12182
|
+
### Cloudflare Workers
|
|
12183
|
+
|
|
12184
|
+
On Workers, one hibernating Durable Object per app owns the log and holds every socket.
|
|
12185
|
+
Request isolates run live loads themselves and forward only the socket handshake to it. The
|
|
12186
|
+
hub answers heartbeats without waking, keeps revocations and socket membership in storage,
|
|
12187
|
+
and refuses calls from an app whose `secret`, `appId` or
|
|
12188
|
+
`grantTtl` differ from its own. It holds 5,000 sockets and 150,000 socket-tag
|
|
12189
|
+
subscriptions by default (`maxSockets`, `maxMemberships`).
|
|
12190
|
+
|
|
12191
|
+
```ts
|
|
12192
|
+
// doc-check: skip - Env, adapter, manifest and the client entry are the worker's own.
|
|
12193
|
+
import { live } from "@nifrajs/web/live"
|
|
12194
|
+
import { liveHub } from "@nifrajs/web/live-hub"
|
|
12195
|
+
|
|
12196
|
+
// The hub: a SQLite-backed Durable Object class, bound as LIVE_HUB.
|
|
12197
|
+
export class LiveHub extends liveHub((env: Env) => ({ secret: env.LIVE_SECRET })) {}
|
|
12198
|
+
|
|
12199
|
+
// Each isolate: the same secret, and the hub's namespace.
|
|
12200
|
+
const runtime = live({ secret: env.LIVE_SECRET, subject, hub: env.LIVE_HUB })
|
|
12201
|
+
const app = createWebApp({ adapter, manifest, clientEntry, live: runtime })
|
|
12202
|
+
```
|
|
12203
|
+
|
|
12204
|
+
```ts
|
|
12205
|
+
[durable_objects]
|
|
12206
|
+
bindings = [{ name = "LIVE_HUB", class_name = "LiveHub" }]
|
|
12207
|
+
|
|
12208
|
+
[[migrations]]
|
|
12209
|
+
tag = "v1"
|
|
12210
|
+
new_sqlite_classes = ["LiveHub"]
|
|
12211
|
+
```
|
|
12212
|
+
|
|
12213
|
+
### Query hooks
|
|
12214
|
+
|
|
12215
|
+
A `useQuery` can name the live keys its data depends on. With
|
|
12216
|
+
`queryKeys: true`, each live load also carries a salted digest of every key it
|
|
12217
|
+
grants; the page matches its queries' keys against them, and a change to one refetches the
|
|
12218
|
+
query. In development, a query key no loader on the page grants logs a warning: nothing
|
|
12219
|
+
would refresh it.
|
|
12220
|
+
|
|
12221
|
+
```ts
|
|
12222
|
+
// doc-check: skip - id and fetchComments are the component's own.
|
|
12223
|
+
// Server: live({ secret, subject, queryKeys: true })
|
|
12224
|
+
|
|
12225
|
+
// Client: refetch this query when comments:<id> changes.
|
|
12226
|
+
const comments = useQuery(["comments", id], () => fetchComments(id), {
|
|
12227
|
+
live: [`comments:${id}`],
|
|
12228
|
+
})
|
|
12229
|
+
```
|
|
12230
|
+
|
|
12231
|
+
The digests let page code confirm a guess at a key its loaders read. Leave
|
|
12232
|
+
`queryKeys` off if your key names hold anything the viewer should not see.
|
|
12233
|
+
|
|
12234
|
+
### Rotate the secret
|
|
12235
|
+
|
|
12236
|
+
Put the new secret first and keep the old one listed: `secret: [next, current]`.
|
|
12237
|
+
Grants sealed under either keep working, and a viewer stays the same viewer whichever
|
|
12238
|
+
process serves the load. Remove the old secret once every process runs the new list and
|
|
12239
|
+
another `grantTtl` plus a minute has passed.
|
|
12240
|
+
|
|
12241
|
+
### Security
|
|
12242
|
+
|
|
12243
|
+
-
|
|
12244
|
+
Grants are sealed with AES-256-GCM and bound to one socket, path, frame and viewer. They
|
|
12245
|
+
expire (`grantTtl`, default 10 minutes, at most an hour); tabs renew them.
|
|
12246
|
+
|
|
12247
|
+
-
|
|
12248
|
+
The load endpoint and the socket check `Origin`; allow other origins with
|
|
12249
|
+
`trustedOrigins`.
|
|
12250
|
+
|
|
12251
|
+
-
|
|
12252
|
+
Every reload runs your hooks, middleware, gates and loaders exactly as a navigation does.
|
|
12253
|
+
|
|
12254
|
+
-
|
|
12255
|
+
Sockets, watches and outbound buffers are bounded per socket and per process (
|
|
12256
|
+
`maxSockets`, `maxRssBytes`). A socket that holds no key for a
|
|
12257
|
+
minute is closed, so holding one costs a live load. Limit connections per client at your
|
|
12258
|
+
proxy as well: the socket cap is shared by every visitor.
|
|
12259
|
+
|
|
11270
12260
|
## Nifra 2.0 migration guide - upgrade from 1.x
|
|
11271
12261
|
|
|
11272
12262
|
> Upgrade a Nifra 1.x application to 2.0: automated package and import moves, opt-in runtime plugins, client and web changes, external auth mounts, and release verification.
|
|
@@ -11977,8 +12967,8 @@ app.
|
|
|
11977
12967
|
|
|
11978
12968
|
-
|
|
11979
12969
|
**Much faster SSR** - the current dynamic-page snapshot reports Nifra at
|
|
11980
|
-
|
|
11981
|
-
3.
|
|
12970
|
+
15× the throughput of Next.js, 7.2× Nuxt, and
|
|
12971
|
+
3.9× SvelteKit / 2.2× SolidStart, with a fraction
|
|
11982
12972
|
of the client JavaScript. See [benchmarks](/benchmarks).
|
|
11983
12973
|
|
|
11984
12974
|
-
|
|
@@ -12007,6 +12997,10 @@ mount small and temporary, and use typed routes for every migrated endpoint.
|
|
|
12007
12997
|
`stripPrefix: true` when the legacy app declares paths relative to its mount point.
|
|
12008
12998
|
The platform object is forwarded as the second argument when the runtime supplies one.
|
|
12009
12999
|
|
|
13000
|
+
An auth plugin used before the mount, such as `bearer()` or
|
|
13001
|
+
`jwt()`, guards it like a route: a request it refuses never reaches the legacy
|
|
13002
|
+
app. Mount before the plugin when the legacy app keeps its own auth.
|
|
13003
|
+
|
|
12010
13004
|
A mounted fetch handler carries HTTP only. A WebSocket upgrade under the mount reaches it as
|
|
12011
13005
|
an ordinary request and never becomes a socket, so keep the legacy app's sockets on its own
|
|
12012
13006
|
server until they move to `app.ws()` routes (see
|
|
@@ -12221,6 +13215,627 @@ No span carries a request body, a job payload, an event payload, a raw cache key
|
|
|
12221
13215
|
Without a tracer configured, the cache and the queue run the code they ran before: no clock
|
|
12222
13216
|
reads, no events, no extra frames.
|
|
12223
13217
|
|
|
13218
|
+
## Nifra - Partial prerendering (experimental)
|
|
13219
|
+
|
|
13220
|
+
> Serve a page's shared frame from a cached shell at once, then stream each per-visitor part as its own loader settles. Shared holes, server components in holes, a store shared by processes, Deno and Workers, eligibility rules, the no-JavaScript limit, proxies and connection limits.
|
|
13221
|
+
|
|
13222
|
+
Most of a product page is the same for everyone: the title, the description, the layout. A
|
|
13223
|
+
partially prerendered route serves that part from a cached shell at once, then streams each
|
|
13224
|
+
per-visitor part, a hole, into it as its own loader settles.
|
|
13225
|
+
|
|
13226
|
+
[!WARNING] Experimental. It is enabled through `experimental.ppr`, and its API may
|
|
13227
|
+
change in any release.
|
|
13228
|
+
|
|
13229
|
+
### Set it up
|
|
13230
|
+
|
|
13231
|
+
`compileShells` bundles each route's shell and refuses one whose emitted code
|
|
13232
|
+
reaches a module that reads the visitor. The shell is the page's and its layouts' whole
|
|
13233
|
+
modules, `meta` included, and the backend half's `shellLoader`. A route missing from its record, or from a record
|
|
13234
|
+
made for another deployment, renders whole. Run it in your build (Bun), and pass the record
|
|
13235
|
+
to `partialPrerendering`. A Svelte, Vue or Solid app passes its server plugin, such
|
|
13236
|
+
as `plugins: [svelteBunPlugin("ssr")]`.
|
|
13237
|
+
|
|
13238
|
+
```ts
|
|
13239
|
+
import { createCspPolicy, createWebApp } from "@nifrajs/web"
|
|
13240
|
+
import { discoverRoutes } from "@nifrajs/web/fs"
|
|
13241
|
+
import { compileShells, partialPrerendering } from "@nifrajs/web/ppr"
|
|
13242
|
+
import { reactAdapter } from "@nifrajs/web-react"
|
|
13243
|
+
|
|
13244
|
+
const routesDir = "./routes"
|
|
13245
|
+
const manifest = discoverRoutes(routesDir)
|
|
13246
|
+
// The content-hashed client entry from your build; a shell check record is valid for it only.
|
|
13247
|
+
const clientEntry = "/assets/entry-4c5ndncr.js"
|
|
13248
|
+
|
|
13249
|
+
// Fails a route whose shell reaches a module that reads the visitor. That route renders whole.
|
|
13250
|
+
const shellChecks = await compileShells({
|
|
13251
|
+
routesDir,
|
|
13252
|
+
manifest,
|
|
13253
|
+
deployment: clientEntry,
|
|
13254
|
+
requestScoped: (file) => file.endsWith("/lib/session.ts"),
|
|
13255
|
+
onFailure: (routeId, error) => console.warn(routeId, error),
|
|
13256
|
+
})
|
|
13257
|
+
|
|
13258
|
+
export const app = createWebApp({
|
|
13259
|
+
adapter: reactAdapter,
|
|
13260
|
+
manifest,
|
|
13261
|
+
clientEntry,
|
|
13262
|
+
// Hashes, not a nonce: a shell is one document for every visitor.
|
|
13263
|
+
csp: createCspPolicy({
|
|
13264
|
+
header: ({ sources }) => `script-src 'self' ${sources}; object-src 'none'; base-uri 'none'`,
|
|
13265
|
+
}),
|
|
13266
|
+
experimental: {
|
|
13267
|
+
ppr: partialPrerendering({ shellChecks, origin: "https://shop.example" }),
|
|
13268
|
+
},
|
|
13269
|
+
})
|
|
13270
|
+
```
|
|
13271
|
+
|
|
13272
|
+
The route's backend half exports the shell loader and one loader per hole. The shell loader
|
|
13273
|
+
gets params, locale, the declared variations, `origin` from config and the
|
|
13274
|
+
in-process `api`, never the request. With
|
|
13275
|
+
`satisfies Route.BoundaryLoaders`, a misspelt or missing hole is a type error
|
|
13276
|
+
when the page is a `.tsx` file whose boundary names are literal types; the
|
|
13277
|
+
manifest refuses an unknown key at startup either way.
|
|
13278
|
+
|
|
13279
|
+
```ts
|
|
13280
|
+
import { t } from "@nifrajs/schema"
|
|
13281
|
+
import type { BoundaryRequestCtx } from "@nifrajs/web"
|
|
13282
|
+
import { defineShellLoader } from "@nifrajs/web/ppr"
|
|
13283
|
+
import type { Route } from "./+types/[id]"
|
|
13284
|
+
|
|
13285
|
+
const titles: Readonly<Record<string, string>> = { "1": "Sencha", "2": "Hojicha" }
|
|
13286
|
+
const cartCount = (request: Request): number => (request.headers.has("cookie") ? 2 : 0)
|
|
13287
|
+
|
|
13288
|
+
// The shell: no request, no cookies. It is built once and shared by every visitor.
|
|
13289
|
+
export const shellLoader = defineShellLoader(async ({ params }) => ({
|
|
13290
|
+
title: titles[params.id ?? ""] ?? "Tea",
|
|
13291
|
+
}))
|
|
13292
|
+
export const shellOutput = t.object({ title: t.string() })
|
|
13293
|
+
export const revalidate = 60
|
|
13294
|
+
export const revalidateTags = ["catalog"]
|
|
13295
|
+
export const shellVariations = { search: { size: ["50g", "100g"] } }
|
|
13296
|
+
|
|
13297
|
+
// The holes: each runs per request, under its own deadline.
|
|
13298
|
+
export const boundaryLoaders = {
|
|
13299
|
+
cart: {
|
|
13300
|
+
load: (ctx: BoundaryRequestCtx) => ({ count: cartCount(ctx.request) }),
|
|
13301
|
+
output: t.object({ count: t.number() }),
|
|
13302
|
+
},
|
|
13303
|
+
} satisfies Route.BoundaryLoaders
|
|
13304
|
+
```
|
|
13305
|
+
|
|
13306
|
+
The page places each hole with the adapter's hole component.
|
|
13307
|
+
|
|
13308
|
+
```tsx
|
|
13309
|
+
// routes/tea/[id].tsx
|
|
13310
|
+
import type { BoundaryStates } from "@nifrajs/web"
|
|
13311
|
+
import { Hole } from "@nifrajs/web-react/ppr"
|
|
13312
|
+
import { Cart } from "../../frontend/cart"
|
|
13313
|
+
|
|
13314
|
+
// `as const` keeps the name literal, so Route.BoundaryLoaders can check the backend half's keys.
|
|
13315
|
+
const cart = {
|
|
13316
|
+
name: "cart",
|
|
13317
|
+
mode: "dynamic",
|
|
13318
|
+
interactive: true, // ships its props and hydrates as its own root
|
|
13319
|
+
render: (data: { readonly count: number }) => <Cart count={data.count} />,
|
|
13320
|
+
fallback: <p>Loading your cart</p>,
|
|
13321
|
+
} as const
|
|
13322
|
+
export const boundaries = [cart]
|
|
13323
|
+
|
|
13324
|
+
export default function Tea(props: { data: { title: string }; boundaries?: BoundaryStates }) {
|
|
13325
|
+
return (
|
|
13326
|
+
<main>
|
|
13327
|
+
<h1>{props.data.title}</h1>
|
|
13328
|
+
<Hole of={cart} state={props.boundaries?.cart} />
|
|
13329
|
+
</main>
|
|
13330
|
+
)
|
|
13331
|
+
}
|
|
13332
|
+
```
|
|
13333
|
+
|
|
13334
|
+
A Preact page is the same, with `/** @jsxImportSource preact */` at the top and
|
|
13335
|
+
`Hole` from `@nifrajs/web-preact/ppr`. Svelte places a hole with its
|
|
13336
|
+
own component and wraps each render in `ui(Component, props)`.
|
|
13337
|
+
|
|
13338
|
+
```svelte
|
|
13339
|
+
<!-- routes/tea/[id].svelte -->
|
|
13340
|
+
<script module>
|
|
13341
|
+
import Hole from "@nifrajs/web-svelte/hole"
|
|
13342
|
+
import { ui } from "@nifrajs/web-svelte/ppr"
|
|
13343
|
+
import Cart from "../../frontend/Cart.svelte"
|
|
13344
|
+
import Loading from "../../frontend/Loading.svelte"
|
|
13345
|
+
|
|
13346
|
+
const cart = {
|
|
13347
|
+
name: "cart",
|
|
13348
|
+
mode: "dynamic",
|
|
13349
|
+
interactive: true,
|
|
13350
|
+
render: (data) => ui(Cart, { count: data.count }),
|
|
13351
|
+
fallback: ui(Loading, { text: "Loading your cart" }),
|
|
13352
|
+
}
|
|
13353
|
+
export const boundaries = [cart]
|
|
13354
|
+
</script>
|
|
13355
|
+
|
|
13356
|
+
<script>
|
|
13357
|
+
let { data, boundaries: states } = $props()
|
|
13358
|
+
</script>
|
|
13359
|
+
|
|
13360
|
+
<main>
|
|
13361
|
+
<h1>{data.title}</h1>
|
|
13362
|
+
<Hole of={cart} state={states?.cart} />
|
|
13363
|
+
</main>
|
|
13364
|
+
```
|
|
13365
|
+
|
|
13366
|
+
A Vue page builds its holes with `h()` and places them in its template; the
|
|
13367
|
+
hole's `error` slot shows when its loader failed.
|
|
13368
|
+
|
|
13369
|
+
```vue
|
|
13370
|
+
<!-- routes/tea/[id].vue -->
|
|
13371
|
+
<script lang="ts">
|
|
13372
|
+
import { Hole } from "@nifrajs/web-vue/ppr"
|
|
13373
|
+
import { h } from "vue"
|
|
13374
|
+
import Cart from "../../frontend/Cart.vue"
|
|
13375
|
+
|
|
13376
|
+
// A hole renders h() output; the page around it is an ordinary template.
|
|
13377
|
+
const cart = {
|
|
13378
|
+
name: "cart",
|
|
13379
|
+
mode: "dynamic",
|
|
13380
|
+
interactive: true,
|
|
13381
|
+
render: (data: { readonly count: number }) => h(Cart, { count: data.count }),
|
|
13382
|
+
fallback: h("p", "Loading your cart"),
|
|
13383
|
+
} as const
|
|
13384
|
+
export const boundaries = [cart]
|
|
13385
|
+
</script>
|
|
13386
|
+
|
|
13387
|
+
<script setup lang="ts">
|
|
13388
|
+
const props = defineProps(["data", "boundaries"])
|
|
13389
|
+
</script>
|
|
13390
|
+
|
|
13391
|
+
<template>
|
|
13392
|
+
<main>
|
|
13393
|
+
<h1>{{ props.data.title }}</h1>
|
|
13394
|
+
<Hole :of="cart" :state="props.boundaries?.cart" />
|
|
13395
|
+
</main>
|
|
13396
|
+
</template>
|
|
13397
|
+
```
|
|
13398
|
+
|
|
13399
|
+
A Solid page's `fallback` is a function returning JSX, so each place that shows
|
|
13400
|
+
it gets its own nodes.
|
|
13401
|
+
|
|
13402
|
+
```tsx
|
|
13403
|
+
// routes/tea/[id].tsx
|
|
13404
|
+
import type { BoundaryStates } from "@nifrajs/web"
|
|
13405
|
+
import { Hole } from "@nifrajs/web-solid/ppr"
|
|
13406
|
+
import { Cart } from "../../frontend/cart"
|
|
13407
|
+
|
|
13408
|
+
const cart = {
|
|
13409
|
+
name: "cart",
|
|
13410
|
+
mode: "dynamic",
|
|
13411
|
+
interactive: true,
|
|
13412
|
+
render: (data: { readonly count: number }) => <Cart count={data.count} />,
|
|
13413
|
+
// A function: JSX evaluated at import would be one DOM node every page shares.
|
|
13414
|
+
fallback: () => <p>Loading your cart</p>,
|
|
13415
|
+
} as const
|
|
13416
|
+
export const boundaries = [cart]
|
|
13417
|
+
|
|
13418
|
+
export default function Tea(props: { data: { title: string }; boundaries?: BoundaryStates }) {
|
|
13419
|
+
return (
|
|
13420
|
+
<main>
|
|
13421
|
+
<h1>{props.data.title}</h1>
|
|
13422
|
+
<Hole of={cart} state={props.boundaries?.cart} />
|
|
13423
|
+
</main>
|
|
13424
|
+
)
|
|
13425
|
+
}
|
|
13426
|
+
```
|
|
13427
|
+
|
|
13428
|
+
`nifra scaffold hole <route> <name>` writes a hole into both halves:
|
|
13429
|
+
its definition, its `boundaries` entry and the `Hole` in a JSX page,
|
|
13430
|
+
and a loader with its output schema in the backend half. `--shared`,
|
|
13431
|
+
`--interactive` and `--timeout <ms>` shape it, and
|
|
13432
|
+
`--server` makes it show a new React server component. A Vue or Svelte page gets
|
|
13433
|
+
the code to paste. `nifra check` reports a page that calls
|
|
13434
|
+
`getContext()` or `tryGetContext()` (NF-C053), and
|
|
13435
|
+
`nifra fix --code NF-C053` moves a read held in one `const`, with the
|
|
13436
|
+
one element that uses it, into a new dynamic hole whose loader makes the read.
|
|
13437
|
+
|
|
13438
|
+
The import check cannot see visitor data an app keeps in module state, such as a variable
|
|
13439
|
+
middleware writes. `checkShellCanaries` requests each path once with unique values
|
|
13440
|
+
in a cookie, `Authorization`, a header and the query, and reports each value found
|
|
13441
|
+
in the shared shell or in a shared hole's frame (the finding names the hole).
|
|
13442
|
+
|
|
13443
|
+
```ts
|
|
13444
|
+
// doc-check: skip - continues the server snippet above (`app`).
|
|
13445
|
+
import { checkShellCanaries } from "@nifrajs/web/ppr"
|
|
13446
|
+
|
|
13447
|
+
// Run before the app serves traffic: a shell already cached was built without the canaries.
|
|
13448
|
+
const leaks = await checkShellCanaries(app, ["/tea/1", "/tea/2"])
|
|
13449
|
+
if (leaks.length > 0) throw new Error(`visitor data in a shared shell: ${JSON.stringify(leaks)}`)
|
|
13450
|
+
```
|
|
13451
|
+
|
|
13452
|
+
### Which routes qualify
|
|
13453
|
+
|
|
13454
|
+
-
|
|
13455
|
+
The backend half exports `shellLoader`, and not `loader` or
|
|
13456
|
+
`prerender = true`.
|
|
13457
|
+
|
|
13458
|
+
-
|
|
13459
|
+
It declares 1 to 32 `dynamic` or `shared` boundaries, each with a
|
|
13460
|
+
`boundaryLoaders` entry. Names are 1-32 lowercase letters, digits and single
|
|
13461
|
+
hyphens, start with a letter and do not end with a hyphen.
|
|
13462
|
+
|
|
13463
|
+
-
|
|
13464
|
+
A hole's `timeout` is 1 to 30000 ms (default 5000). The response ends by the
|
|
13465
|
+
largest timeout plus one second, at most 30 seconds.
|
|
13466
|
+
|
|
13467
|
+
-
|
|
13468
|
+
A layout above it may have a loader only as a `gate`: the gate runs to redirect
|
|
13469
|
+
or refuse, and its data reaches no response. Intercepting boundaries are not supported.
|
|
13470
|
+
|
|
13471
|
+
-
|
|
13472
|
+
`shellVariations` lists closed sets of query values that each select their own
|
|
13473
|
+
shell. Any other parameter or value shares the default shell.
|
|
13474
|
+
|
|
13475
|
+
-
|
|
13476
|
+
The app uses `csp: createCspPolicy(...)`, not `nonce`. Under enforced
|
|
13477
|
+
Trusted Types, its `trusted-types` directive lists `nifra-ppr`,
|
|
13478
|
+
beside any policy the UI framework creates (Svelte's is `svelte-trusted-html`,
|
|
13479
|
+
Vue's `vue`). Solid's client renders new DOM from plain strings under no policy,
|
|
13480
|
+
so a Solid app cannot enforce Trusted Types.
|
|
13481
|
+
|
|
13482
|
+
### What each request gets
|
|
13483
|
+
|
|
13484
|
+
Request
|
|
13485
|
+
Response
|
|
13486
|
+
|
|
13487
|
+
A browser's first load
|
|
13488
|
+
The shell at once, each hole's fallback in place, then each hole as it settles
|
|
13489
|
+
|
|
13490
|
+
A client navigation
|
|
13491
|
+
The shell data, then each hole as a streamed value; leaving cancels the rest
|
|
13492
|
+
|
|
13493
|
+
A hover prefetch
|
|
13494
|
+
The shell data only; no hole loader starts
|
|
13495
|
+
|
|
13496
|
+
A listed bot (`blockingFor`), a draft, or a route whose shell is unchecked
|
|
13497
|
+
or at its build limit
|
|
13498
|
+
|
|
13499
|
+
The whole page, every hole rendered in place
|
|
13500
|
+
|
|
13501
|
+
Once the shell store is full, a page whose shell key has had fewer requests than
|
|
13502
|
+
`shellAfterRequests` (default 2)
|
|
13503
|
+
|
|
13504
|
+
The whole page streamed, each hole as it settles; no shell is built
|
|
13505
|
+
|
|
13506
|
+
A hole cannot redirect or set a status: the shell's status and headers are already sent, so a
|
|
13507
|
+
hole whose loader returns or throws a redirect or a status renders its error state. A page
|
|
13508
|
+
cache such as `withISR` never stores the route's response, however it rendered.
|
|
13509
|
+
|
|
13510
|
+
Before a hole's HTML is framed, the server checks the markup a component may have inserted
|
|
13511
|
+
unescaped (`dangerouslySetInnerHTML`, `{@html}`,
|
|
13512
|
+
`v-html`): no `script`, `iframe`, `object`,
|
|
13513
|
+
`embed`, `style`, `link`, `meta`,
|
|
13514
|
+
`base` or `template` element, no `on*` handler or
|
|
13515
|
+
`srcdoc`, and no `javascript:`, `vbscript:` or
|
|
13516
|
+
`data:` URL. A hole that fails it renders its error state, and the failure is
|
|
13517
|
+
logged with the route and hole names only. The check costs about 20 us per KB of hole HTML.
|
|
13518
|
+
`holeHtmlValidation: "development"` skips it in production for per-visitor holes;
|
|
13519
|
+
set that only when the app's CSP already blocks inline scripts and handlers, since without
|
|
13520
|
+
the check only the CSP stops unescaped markup from running as script. Shared holes and
|
|
13521
|
+
server components are always checked.
|
|
13522
|
+
|
|
13523
|
+
A shell older than `revalidate` is served while one rebuild runs; a failing
|
|
13524
|
+
rebuild keeps the old one for up to ten times `revalidate`, at most a day. A shell
|
|
13525
|
+
loader's `notFound()` is remembered for 60 seconds. A shell or shared hole build
|
|
13526
|
+
that runs past `maxHoleTimeoutMs` fails every request waiting on it and keeps
|
|
13527
|
+
nothing it returns later; until its loader does end, it still counts against the route's
|
|
13528
|
+
`shellBuildConcurrency`.
|
|
13529
|
+
|
|
13530
|
+
### Shared holes
|
|
13531
|
+
|
|
13532
|
+
A part that is the same for every visitor but changes faster than the shell, such as a price
|
|
13533
|
+
or a stock level, is a `shared` hole. Its loader gets the shell's context, never
|
|
13534
|
+
the request, so a hole that should have been per visitor shows generic content, never one
|
|
13535
|
+
visitor's data to another. It is built once per route, params, locale and variations, and
|
|
13536
|
+
kept on its own `revalidate` (required, in seconds) and
|
|
13537
|
+
`revalidateTags`, apart from the shell.
|
|
13538
|
+
|
|
13539
|
+
```tsx
|
|
13540
|
+
// doc-check: skip - an excerpt of the React page above, beside its cart hole.
|
|
13541
|
+
const price = {
|
|
13542
|
+
name: "price",
|
|
13543
|
+
mode: "shared", // the same for every visitor: built once, cached on its own
|
|
13544
|
+
render: (data: { readonly amount: string }) => <p>{data.amount}</p>,
|
|
13545
|
+
fallback: <p>Loading the price</p>,
|
|
13546
|
+
} as const
|
|
13547
|
+
export const boundaries = [cart, price]
|
|
13548
|
+
```
|
|
13549
|
+
|
|
13550
|
+
```ts
|
|
13551
|
+
import { t } from "@nifrajs/schema"
|
|
13552
|
+
import type { ShellCtx } from "@nifrajs/web"
|
|
13553
|
+
import type { Route } from "./+types/[id]"
|
|
13554
|
+
|
|
13555
|
+
const prices: Readonly<Record<string, string>> = { "1": "$12.00", "2": "$9.50" }
|
|
13556
|
+
|
|
13557
|
+
export const boundaryLoaders = {
|
|
13558
|
+
// Inline, with revalidate: the build checks this loader with the shell, so its frame is stored.
|
|
13559
|
+
price: {
|
|
13560
|
+
load: async ({ params }: ShellCtx) => ({ amount: prices[params.id ?? ""] ?? "-" }),
|
|
13561
|
+
output: t.object({ amount: t.string() }),
|
|
13562
|
+
revalidate: 10,
|
|
13563
|
+
revalidateTags: ({ params }) => [`price:${params.id}`],
|
|
13564
|
+
},
|
|
13565
|
+
} satisfies Route.BoundaryLoaders
|
|
13566
|
+
```
|
|
13567
|
+
|
|
13568
|
+
-
|
|
13569
|
+
A frame this process holds goes out with the shell, in its first write. On a miss the
|
|
13570
|
+
visitor waits up to the hole's `timeout`, then gets the error slot while the
|
|
13571
|
+
build finishes for the next visitor.
|
|
13572
|
+
|
|
13573
|
+
-
|
|
13574
|
+
An older frame is served while one rebuild runs. A failed build is never stored: the old
|
|
13575
|
+
frame stays for up to ten times `revalidate`, at most a day.
|
|
13576
|
+
|
|
13577
|
+
-
|
|
13578
|
+
Builds count against the route's `shellBuildConcurrency`; past it, a missing
|
|
13579
|
+
frame is built anyway as hole work under `maxHoleWork`, and stored.
|
|
13580
|
+
|
|
13581
|
+
-
|
|
13582
|
+
`compileShells` bundles each shared loader with the shell and refuses the route
|
|
13583
|
+
if it reaches a module that reads the visitor. It finds an entry written inline in
|
|
13584
|
+
`boundaryLoaders` with `revalidate`; any other shared hole loads for
|
|
13585
|
+
every visitor and warns once in development.
|
|
13586
|
+
|
|
13587
|
+
- A draft loads it fresh and never reads or fills the cache.
|
|
13588
|
+
|
|
13589
|
+
### When the page reloads
|
|
13590
|
+
|
|
13591
|
+
After an action posted from the page, and when a live key its holes read changes (
|
|
13592
|
+
`createWebApp({ live })`), the router reloads the page on screen. A page
|
|
13593
|
+
the partially prerendered document filled keeps its holes where they are: each hole's new
|
|
13594
|
+
HTML, with props for an interactive one, goes into its host in place.
|
|
13595
|
+
|
|
13596
|
+
-
|
|
13597
|
+
An interactive hole's own root renders the new props and keeps its state. A Solid root gets
|
|
13598
|
+
object props through a store, so a component that reads them in JSX updates; Svelte keeps
|
|
13599
|
+
the root while the render picks the same component.
|
|
13600
|
+
|
|
13601
|
+
-
|
|
13602
|
+
The old content stays until the new arrives. A hole whose reload fails shows its error
|
|
13603
|
+
slot, never content from before the action. A reload overtaken by a newer one is dropped,
|
|
13604
|
+
and leaving the page aborts its hole loaders on the server.
|
|
13605
|
+
|
|
13606
|
+
-
|
|
13607
|
+
After a client navigation the holes render as streamed boundaries, and reload as they do.
|
|
13608
|
+
|
|
13609
|
+
A hole loader declares its live keys with `ctx.live(...)`, as a page loader does.
|
|
13610
|
+
A change reloads only the holes whose keys changed; the live load keeps the rest. The page's
|
|
13611
|
+
grant comes after its holes, in one trailing frame of the reload, and holds each hole that
|
|
13612
|
+
loaded: a hole that failed or timed out is not watched until it loads again. The shell and
|
|
13613
|
+
the first document carry no grant. A shared hole's keys are kept with its stored entry, and
|
|
13614
|
+
the entry answers the reload until it is dropped, so publish a shared hole's key together
|
|
13615
|
+
with a purge of its tag.
|
|
13616
|
+
|
|
13617
|
+
```ts
|
|
13618
|
+
// doc-check: skip - an excerpt of a backend half, on an app created with `live`.
|
|
13619
|
+
export const boundaryLoaders = {
|
|
13620
|
+
cart: {
|
|
13621
|
+
load: async ({ api, params, live }: BoundaryRequestCtx) => {
|
|
13622
|
+
live(`cart:${params.id}`)
|
|
13623
|
+
return api.cart.get({ id: params.id })
|
|
13624
|
+
},
|
|
13625
|
+
output: t.object({ count: t.number() }),
|
|
13626
|
+
},
|
|
13627
|
+
price: {
|
|
13628
|
+
// Kept with the stored entry: publish this key with a purge of the price tag.
|
|
13629
|
+
load: async ({ params, live }: SharedHoleCtx) => {
|
|
13630
|
+
live(`price:${params.id}`)
|
|
13631
|
+
return { amount: await priceOf(params.id) }
|
|
13632
|
+
},
|
|
13633
|
+
output: t.object({ amount: t.string() }),
|
|
13634
|
+
revalidate: 10,
|
|
13635
|
+
revalidateTags: ({ params }) => [`price:${params.id}`],
|
|
13636
|
+
},
|
|
13637
|
+
} satisfies Route.BoundaryLoaders
|
|
13638
|
+
```
|
|
13639
|
+
|
|
13640
|
+
### Server components in holes
|
|
13641
|
+
|
|
13642
|
+
A `dynamic` hole can show a server component: `serverHole(Basket)`, from
|
|
13643
|
+
`@nifrajs/web/server-components/hole`, is its `render`. The hole's loader
|
|
13644
|
+
returns the component's input; the component authorizes, loads and renders on the server for
|
|
13645
|
+
each request. The browser gets its HTML and the code of its client islands, never its view or
|
|
13646
|
+
anything its loader returned beyond its props. Like every server component, it needs the
|
|
13647
|
+
coordinated compiler (`buildServerComponents`).
|
|
13648
|
+
|
|
13649
|
+
```tsx
|
|
13650
|
+
// doc-check: skip - excerpts of a component file, a page, its backend half and both entries.
|
|
13651
|
+
// Basket.component.server.tsx
|
|
13652
|
+
export const Basket = defineServerComponent({
|
|
13653
|
+
input: t.object({ id: t.string() }),
|
|
13654
|
+
props: t.object({ title: t.string(), count: t.number() }),
|
|
13655
|
+
authorize: ({ request }) => requireVisitor(request),
|
|
13656
|
+
load: async ({ request }, input) => basketOf(request, input.id),
|
|
13657
|
+
view: ({ props }) => (
|
|
13658
|
+
<section>
|
|
13659
|
+
<h2>{props.title}</h2>
|
|
13660
|
+
<AddButton count={props.count} /> {/* a "use client" island */}
|
|
13661
|
+
</section>
|
|
13662
|
+
),
|
|
13663
|
+
})
|
|
13664
|
+
|
|
13665
|
+
// routes/tea/[id].tsx
|
|
13666
|
+
const basket = { name: "basket", mode: "dynamic", render: serverHole(Basket) } as const
|
|
13667
|
+
export const boundaries = [cart, basket]
|
|
13668
|
+
|
|
13669
|
+
// routes/tea/[id].backend.ts: the hole's loader returns the component's input
|
|
13670
|
+
export const boundaryLoaders = {
|
|
13671
|
+
basket: {
|
|
13672
|
+
load: ({ params }: BoundaryRequestCtx) => ({ id: params.id ?? "" }),
|
|
13673
|
+
output: t.object({ id: t.string() }),
|
|
13674
|
+
},
|
|
13675
|
+
} satisfies Route.BoundaryLoaders
|
|
13676
|
+
|
|
13677
|
+
// The server entry: the components each route's holes may show.
|
|
13678
|
+
createServerComponents({ build, adapter, owners: {}, holes: { "tea/[id]": { components: [Basket] } } })
|
|
13679
|
+
|
|
13680
|
+
// The client entry, before the router mounts.
|
|
13681
|
+
holeComponents(reactComponentClient())
|
|
13682
|
+
```
|
|
13683
|
+
|
|
13684
|
+
-
|
|
13685
|
+
List each route's hole components in `createServerComponents({ holes })`.
|
|
13686
|
+
A route that shows a server component the list leaves out fails, and a route either owns
|
|
13687
|
+
server components or shows them in holes, never both.
|
|
13688
|
+
|
|
13689
|
+
-
|
|
13690
|
+
The hole is not interactive. Its loader declares an `output` like any hole's: its
|
|
13691
|
+
value reaches the browser as the component's input.
|
|
13692
|
+
|
|
13693
|
+
-
|
|
13694
|
+
The component reads the visitor's request, under the hole's timeout and admission. It cannot
|
|
13695
|
+
set a cookie or a header, since the shell sent them already: a component that tries shows
|
|
13696
|
+
the error slot, as does an input or authorization it refuses.
|
|
13697
|
+
|
|
13698
|
+
-
|
|
13699
|
+
Call `holeComponents` in the client entry before the router mounts, with the
|
|
13700
|
+
adapter's component client, such as `reactComponentClient()` or
|
|
13701
|
+
`vueComponentClient({ islands })`. Without it the hole shows its error
|
|
13702
|
+
slot.
|
|
13703
|
+
|
|
13704
|
+
-
|
|
13705
|
+
The hole is a host on every load: a client navigation mounts it from its fill, and a
|
|
13706
|
+
crawler's blocking render has its HTML in the host. A reload puts the new HTML in and mounts
|
|
13707
|
+
its islands afresh, so they do not keep their state.
|
|
13708
|
+
|
|
13709
|
+
### Across processes
|
|
13710
|
+
|
|
13711
|
+
Each process keeps its own shells and shared frames. Give `partialPrerendering` a
|
|
13712
|
+
`store` the processes share, such as Workers KV, and a process that has not built
|
|
13713
|
+
an entry reads it from there. Every entry is signed with `storeSecret` over its key,
|
|
13714
|
+
deployment and contents, so a store other services can write cannot hand visitors a page this
|
|
13715
|
+
app did not build; one that fails the check is a miss. Entries are kept apart per deployment:
|
|
13716
|
+
the client build, each route's checked shell code and the optional `deployment`
|
|
13717
|
+
name all go into the key. A route whose tags the store cannot drop keeps its entries in the
|
|
13718
|
+
process, with one warning. A process reads an entry it holds from the store again once
|
|
13719
|
+
`sharedRecheckMs` (default 1000) has passed, so a purge made on another process
|
|
13720
|
+
reaches it within that time; a store that does not answer within `holeTimeoutMs`
|
|
13721
|
+
counts as a miss.
|
|
13722
|
+
|
|
13723
|
+
```ts
|
|
13724
|
+
// doc-check: skip - a Worker's partialPrerendering call, with the server snippet's records.
|
|
13725
|
+
import { KVCacheStore } from "@nifrajs/web"
|
|
13726
|
+
|
|
13727
|
+
partialPrerendering({
|
|
13728
|
+
shellChecks,
|
|
13729
|
+
store: new KVCacheStore(env.SHELLS),
|
|
13730
|
+
storeSecret: env.PPR_STORE_SECRET, // at least 32 characters, the same in every process
|
|
13731
|
+
deployment: env.CF_VERSION_METADATA.id,
|
|
13732
|
+
})
|
|
13733
|
+
```
|
|
13734
|
+
|
|
13735
|
+
### Runtimes
|
|
13736
|
+
|
|
13737
|
+
- Bun and Node serve it as they serve any nifra app.
|
|
13738
|
+
|
|
13739
|
+
-
|
|
13740
|
+
Deno serves it through `@nifrajs/deno`; a hang-up aborts the holes still
|
|
13741
|
+
running.
|
|
13742
|
+
|
|
13743
|
+
-
|
|
13744
|
+
On Cloudflare Workers, the shell store defaults to 8 MB and the cancel beacon is off, since
|
|
13745
|
+
it would reach another isolate: a hole the visitor left stops at its deadline. Rebuilds and
|
|
13746
|
+
store writes run through `waitUntil`. Workers compress responses themselves, so
|
|
13747
|
+
`compression()` leaves them alone there. A shell that imports
|
|
13748
|
+
`cloudflare:workers` fails its check: that module hands any code the Worker's
|
|
13749
|
+
`env`.
|
|
13750
|
+
|
|
13751
|
+
```ts
|
|
13752
|
+
// doc-check: skip - continues the server snippet above (`app`) on Deno.
|
|
13753
|
+
import { serve } from "@nifrajs/deno"
|
|
13754
|
+
|
|
13755
|
+
await serve(app, { port: 8000 })
|
|
13756
|
+
```
|
|
13757
|
+
|
|
13758
|
+
### Without JavaScript
|
|
13759
|
+
|
|
13760
|
+
A hole's HTML arrives as inert data that the inline runtime inserts, so a browser with
|
|
13761
|
+
scripts off sees the shell and each hole's fallback, never the hole. Nothing in a single
|
|
13762
|
+
streamed response can fill a hole without script. Listed bots get the whole page instead. If
|
|
13763
|
+
a route's per-visitor part must work without JavaScript, do not partially prerender it. In
|
|
13764
|
+
development, a hole whose fallback renders empty warns once per route.
|
|
13765
|
+
|
|
13766
|
+
### Behind a proxy
|
|
13767
|
+
|
|
13768
|
+
-
|
|
13769
|
+
The stream must reach the browser as it is written. Responses carry
|
|
13770
|
+
`X-Accel-Buffering: no`, which nginx honors; turn response buffering off for
|
|
13771
|
+
other proxies.
|
|
13772
|
+
|
|
13773
|
+
-
|
|
13774
|
+
Compression in front of the app must flush after every write, or the holes arrive with the
|
|
13775
|
+
last one. `compression()` from `@nifrajs/middleware` does.
|
|
13776
|
+
|
|
13777
|
+
-
|
|
13778
|
+
Responses are `Cache-Control: private, no-store`: the holes are per visitor. The
|
|
13779
|
+
shell is cached in the server process, keyed by deployment, route, locale, path and
|
|
13780
|
+
declared variations.
|
|
13781
|
+
|
|
13782
|
+
-
|
|
13783
|
+
Leaving a page posts a cancel beacon to `/__nifra/ppr/cancel`; forward it.
|
|
13784
|
+
|
|
13785
|
+
-
|
|
13786
|
+
Set `origin`: the shell and its `meta` never read the Host header.
|
|
13787
|
+
|
|
13788
|
+
-
|
|
13789
|
+
A proxy's read timeout must exceed the response deadline: the largest hole timeout plus
|
|
13790
|
+
one second, plus `writeGraceMs` (5 s) for a slow reader.
|
|
13791
|
+
|
|
13792
|
+
### Connection limits are yours to set
|
|
13793
|
+
|
|
13794
|
+
Each document holds its connection open until its slowest hole ends. nifra bounds the work
|
|
13795
|
+
behind those connections: `maxHoleWork` responses with hole loaders running per
|
|
13796
|
+
process; a loader that ignores its abort stops being admitted; a response whose client stops
|
|
13797
|
+
reading sends its later holes as errors once 1 MB is unsent, and the slowest readers are cut
|
|
13798
|
+
off when the process's unsent bytes pass 64 MB. It does not bound the number of open
|
|
13799
|
+
sockets. Set a connection limit at the proxy or load balancer, or
|
|
13800
|
+
in the runtime where it offers one (Node's `server.maxConnections`).
|
|
13801
|
+
|
|
13802
|
+
### Limits and defaults
|
|
13803
|
+
|
|
13804
|
+
Every number above is a default in `PPR_DEFAULTS`, overridden per app through
|
|
13805
|
+
`options`; contradicting limits throw at startup.
|
|
13806
|
+
|
|
13807
|
+
```ts
|
|
13808
|
+
// doc-check: skip - an excerpt of the server snippet's partialPrerendering call.
|
|
13809
|
+
partialPrerendering({
|
|
13810
|
+
shellChecks,
|
|
13811
|
+
options: { holeTimeoutMs: 3_000, maxHoleWork: 256, holeHtmlValidation: "always" },
|
|
13812
|
+
})
|
|
13813
|
+
```
|
|
13814
|
+
|
|
13815
|
+
### Invalidation and metrics
|
|
13816
|
+
|
|
13817
|
+
`pprShells(app)` is the app's shell cache. Give it to
|
|
13818
|
+
`createInvalidator` as a data cache, so a purge by tag also drops the shells and
|
|
13819
|
+
shared hole frames built from the purged data; a shell or shared hole build already running
|
|
13820
|
+
when the purge lands is not kept.
|
|
13821
|
+
|
|
13822
|
+
A `revalidateTags` function on the route or on a shared hole is given the shell's
|
|
13823
|
+
URL, not the visitor's: the configured `origin` (`http://shell.invalid`
|
|
13824
|
+
without one), the path and the declared variations, and no other query. Tags are read once
|
|
13825
|
+
per build and kept with the entry, so they can only follow what keys it.
|
|
13826
|
+
|
|
13827
|
+
```ts
|
|
13828
|
+
// doc-check: skip - continues the server snippet above (`app`) with an app-owned `store`.
|
|
13829
|
+
import { createInvalidator } from "@nifrajs/web/cdn"
|
|
13830
|
+
import { pprShells } from "@nifrajs/web/ppr"
|
|
13831
|
+
|
|
13832
|
+
const shells = pprShells(app)
|
|
13833
|
+
const { invalidate } = createInvalidator({ store, origin: "https://shop.example", dataCaches: [shells] })
|
|
13834
|
+
|
|
13835
|
+
await invalidate({ tags: ["catalog"] }) // shells listing "catalog" are rebuilt on their next request
|
|
13836
|
+
console.log(shells.stats()) // admitted, denied and shed holes, aborted slow readers, unsent bytes
|
|
13837
|
+
```
|
|
13838
|
+
|
|
12224
13839
|
## Nifra security posture vs Hono, Fastify, Express, Elysia
|
|
12225
13840
|
|
|
12226
13841
|
> A dimension-by-dimension security comparison of Nifra against the current releases of Hono, Fastify, Express, and Elysia - which hardening each framework ships by default, which is opt-in, and which is left to third-party packages.
|
|
@@ -13316,6 +14931,14 @@ $ nifra context # the same contract as compact text - pipe into any agent
|
|
|
13316
14931
|
$ nifra mcp # the same data over an MCP server - Claude Code & Cursor read it
|
|
13317
14932
|
```
|
|
13318
14933
|
|
|
14934
|
+
### In the editor
|
|
14935
|
+
|
|
14936
|
+
`@nifrajs/ts-plugin` is a TypeScript language-service plugin. Add
|
|
14937
|
+
`{ "name": "@nifrajs/ts-plugin" }` to `compilerOptions.plugins` and
|
|
14938
|
+
go-to-definition on a route path such as `"/orders"` opens the
|
|
14939
|
+
`routes/` file that serves it. It also marks, as you type, an import the build
|
|
14940
|
+
would refuse: backend code in a page, or a server package in browser code.
|
|
14941
|
+
|
|
13319
14942
|
### Known limitations
|
|
13320
14943
|
|
|
13321
14944
|
-
|
|
@@ -14996,6 +16619,21 @@ Part of the **[nifra](https://nifra.dev)** full-stack TypeScript framework - one
|
|
|
14996
16619
|
bun add @nifrajs/content
|
|
14997
16620
|
```
|
|
14998
16621
|
|
|
16622
|
+
## Rendering an entry
|
|
16623
|
+
|
|
16624
|
+
`entry.html` is `marked` output, unsanitized: raw HTML and `javascript:` links in the Markdown pass
|
|
16625
|
+
through. That is right for content you author. Mark it trusted for an adapter's `<Content>`:
|
|
16626
|
+
|
|
16627
|
+
```tsx
|
|
16628
|
+
import { trustHtml } from "@nifrajs/web"
|
|
16629
|
+
import { Content } from "@nifrajs/web-react/content"
|
|
16630
|
+
|
|
16631
|
+
<Content html={trustHtml(entry.html)} />
|
|
16632
|
+
```
|
|
16633
|
+
|
|
16634
|
+
For a collection that contributors or a CMS write, pass `sanitizeHtml(entry.html, sanitizer)` with an
|
|
16635
|
+
allowlist sanitizer you choose instead.
|
|
16636
|
+
|
|
14999
16637
|
## Docs
|
|
15000
16638
|
|
|
15001
16639
|
- Reference: <https://nifra.dev/docs>
|
|
@@ -15314,6 +16952,19 @@ await serve(app, { port: 3000, signals: true }) // SIGTERM/SIGINT → graceful s
|
|
|
15314
16952
|
await serve(app, { port: 3000, signals: { drainMs: 8_000 } }) // the same, with an 8 s drain window
|
|
15315
16953
|
```
|
|
15316
16954
|
|
|
16955
|
+
## Client disconnect and `c.req.signal`
|
|
16956
|
+
|
|
16957
|
+
`Deno.serve` aborts a request's `signal` when the client goes away and, by default, also once a
|
|
16958
|
+
response has been sent in full. Deno prints a one-time notice about that default when it finishes
|
|
16959
|
+
the response to a request whose `signal` was read. nifra reads it when it rebuilds a request (a
|
|
16960
|
+
mounted app, a path with `.` or `..` segments, an idempotent route), so `c.req.signal` and
|
|
16961
|
+
`fetch(c.req)` still follow a client that hangs up. To have the signal abort only on a disconnect,
|
|
16962
|
+
and no notice, run Deno with `--unstable-no-legacy-abort`:
|
|
16963
|
+
|
|
16964
|
+
```sh
|
|
16965
|
+
deno run --allow-net --unstable-no-legacy-abort main.ts
|
|
16966
|
+
```
|
|
16967
|
+
|
|
15317
16968
|
## What you get for free
|
|
15318
16969
|
|
|
15319
16970
|
The request timeout (`server({ requestTimeoutMs })` → `503 request_timeout`) and body-size
|
|
@@ -15355,6 +17006,10 @@ The plugin is enabled by default only when `NODE_ENV=development`. It records a
|
|
|
15355
17006
|
and serves the overlay stream at `/_nifra/devtools`; remote hosts and cross-origin access stay denied
|
|
15356
17007
|
unless explicitly allowed. Leave it unregistered in production for zero request-path overhead.
|
|
15357
17008
|
|
|
17009
|
+
In an app with [`keepAlive`](https://nifra.dev/docs/keep-alive) routes, the overlay also lists the
|
|
17010
|
+
kept pages under its request log: each one's path and instance, how long it has been hidden and how
|
|
17011
|
+
many elements it renders.
|
|
17012
|
+
|
|
15358
17013
|
Each SSE connection also has a finite pending-byte budget (`maxPendingBytes`, default 64 KiB),
|
|
15359
17014
|
including keep-alive frames. A slow reader that fills that budget is closed and releases its
|
|
15360
17015
|
connection slot. Already queued frames drain before EOF; the overflow frame is dropped. Browser
|
|
@@ -15525,9 +17180,9 @@ Every value in `process.env` is a `string | undefined`; these turn it into the v
|
|
|
15525
17180
|
| helper | type | notes |
|
|
15526
17181
|
| --- | --- | --- |
|
|
15527
17182
|
| `env.string({ default?, optional? })` | `string` | empty string counts as unset |
|
|
15528
|
-
| `env.number({ default?, optional? })` | `number` |
|
|
15529
|
-
| `env.port({ default? })` | `number` | integer 1-65535 |
|
|
15530
|
-
| `env.boolean({ default? })` | `boolean` | `true`/`1`/`yes`/`on` vs `false`/`0`/`no`/`off
|
|
17183
|
+
| `env.number({ default?, optional? })` | `number` | plain decimal (`42`, `-3.5`; not `0x10` or `1e3`); blank counts as unset |
|
|
17184
|
+
| `env.port({ default? })` | `number` | decimal integer 1-65535; blank counts as unset |
|
|
17185
|
+
| `env.boolean({ default? })` | `boolean` | `true`/`1`/`yes`/`on` vs `false`/`0`/`no`/`off`; empty is `default`, else `false` |
|
|
15531
17186
|
| `env.enum([...], { default? })` | union | one of the listed values |
|
|
15532
17187
|
| `env.url({ default?, optional? })` | `string` | parses with WHATWG `URL`, returns the normalized href |
|
|
15533
17188
|
|
|
@@ -15905,8 +17560,8 @@ done-gate, or `nifra mcp` to give the agent live project tools.
|
|
|
15905
17560
|
|
|
15906
17561
|
## @nifrajs/island-trigger
|
|
15907
17562
|
|
|
15908
|
-
Framework-neutral, browser-side trigger scheduling
|
|
15909
|
-
`@nifrajs/web/islands
|
|
17563
|
+
Framework-neutral, browser-side trigger scheduling for Nifra’s island runtime,
|
|
17564
|
+
`@nifrajs/web/islands`.
|
|
15910
17565
|
|
|
15911
17566
|
It has no DOM or UI-framework dependency. The public contract is the small `scheduleTrigger`
|
|
15912
17567
|
primitive with these strategies:
|
|
@@ -15929,96 +17584,6 @@ registry, signals, and framework integration.
|
|
|
15929
17584
|
For AI agents, see [`LLM.md`](./LLM.md). The wider reference is in
|
|
15930
17585
|
[`llms-full.txt`](../../llms-full.txt).
|
|
15931
17586
|
|
|
15932
|
-
## @nifrajs/islets
|
|
15933
|
-
|
|
15934
|
-
Fine-grained signals + declarative DOM bindings for islands - **interactivity in ~2 KB gz**, no
|
|
15935
|
-
framework runtime. The client companion to `@nifrajs/web-vanilla`: the server renders real HTML
|
|
15936
|
-
(zero framework JS); islands attach behavior to it in place. No VDOM, no hydration re-render -
|
|
15937
|
-
the markup the server sent IS the initial state.
|
|
15938
|
-
|
|
15939
|
-
The full island bundle is about 2 KB gzipped (2,080 B at most), and a size test keeps it there. Use
|
|
15940
|
-
it for small interactive widgets where a full framework runtime would be overkill.
|
|
15941
|
-
|
|
15942
|
-
## Server side (any adapter - `@nifrajs/web-vanilla` shown)
|
|
15943
|
-
|
|
15944
|
-
```ts
|
|
15945
|
-
import { html } from "@nifrajs/web-vanilla"
|
|
15946
|
-
import { islandState } from "@nifrajs/islets" // safe to import server-side: it's just JSON.stringify
|
|
15947
|
-
|
|
15948
|
-
html`<section data-island="compare" data-island-state="${islandState({ count: hotels.length })}">
|
|
15949
|
-
<span data-bind-text="count">${hotels.length}</span>
|
|
15950
|
-
<button data-bind-on="click:add" type="button">Compare</button>
|
|
15951
|
-
</section>`
|
|
15952
|
-
```
|
|
15953
|
-
|
|
15954
|
-
The state attribute is the loader-data → client-signal seam: emit it through an escaping renderer
|
|
15955
|
-
(vanilla's `html` escapes attribute quotes) and the island reads it back with `state()` - no
|
|
15956
|
-
separate hydration payload, no data globals.
|
|
15957
|
-
|
|
15958
|
-
## Client side (an `islandScripts` entry)
|
|
15959
|
-
|
|
15960
|
-
```ts
|
|
15961
|
-
import { island, mountIslands } from "@nifrajs/islets"
|
|
15962
|
-
|
|
15963
|
-
island("compare", ({ state }) => {
|
|
15964
|
-
const count = state("count", 0) // seeded from data-island-state, falls back to 0
|
|
15965
|
-
return { add: () => count.set((n) => n + 1) }
|
|
15966
|
-
})
|
|
15967
|
-
|
|
15968
|
-
mountIslands() // idempotent - safe to call again after soft navigation
|
|
15969
|
-
```
|
|
15970
|
-
|
|
15971
|
-
## The binding set (closed - six bindings, no expression language)
|
|
15972
|
-
|
|
15973
|
-
| Attribute | Effect |
|
|
15974
|
-
| --- | --- |
|
|
15975
|
-
| `data-bind-text="sig"` | `textContent ← String(sig())` |
|
|
15976
|
-
| `data-bind-show="sig"` | `hidden ← !sig()` |
|
|
15977
|
-
| `data-bind-class="active:isOpen,b:sigB"` | `classList.toggle` per pair |
|
|
15978
|
-
| `data-bind-attr="aria-expanded:isOpen"` | `setAttribute`; `false`/`null`/`undefined` removes. Never an `on*` handler or `srcdoc`; `href`/`src`/`action` and other URL attributes take only http(s), mailto, tel or relative URLs |
|
|
15979
|
-
| `data-bind-value="query"` | two-way `<input>`/`<select>`/`<textarea>` (`input` event) |
|
|
15980
|
-
| `data-bind-on="click:inc,submit:save"` | `addEventListener` per pair |
|
|
15981
|
-
|
|
15982
|
-
Values are signal/handler **names** resolved in the island's scope - never evaluated code, so
|
|
15983
|
-
markup cannot inject behavior. Unknown names warn once and skip; the server-rendered content
|
|
15984
|
-
stays as-is (progressive enhancement never throws).
|
|
15985
|
-
|
|
15986
|
-
Render user-supplied HTML (comments, rich text) inside an element marked `data-island-ignore`.
|
|
15987
|
-
Nothing in it binds or mounts: a sanitizer that keeps `data-*` attributes cannot let that markup
|
|
15988
|
-
reach the island's handlers or signals, or mount an island of its own.
|
|
15989
|
-
|
|
15990
|
-
```html
|
|
15991
|
-
<section data-island="comments">
|
|
15992
|
-
<button data-bind-on="click:save">Save</button>
|
|
15993
|
-
<div data-island-ignore>${sanitizedCommentHtml}</div>
|
|
15994
|
-
</section>
|
|
15995
|
-
```
|
|
15996
|
-
|
|
15997
|
-
Islands may nest. A binding belongs to its nearest island, so an outer island never binds inside a
|
|
15998
|
-
nested island. The nested host element itself is the outer island's markup: the outer island may
|
|
15999
|
-
bind it, for example to show or hide the nested island.
|
|
16000
|
-
|
|
16001
|
-
## Signals
|
|
16002
|
-
|
|
16003
|
-
`signal(initial)` / `computed(fn)` / `effect(fn) → dispose` / `batch(fn)` - auto-tracking with
|
|
16004
|
-
per-run re-tracking, `Object.is` skips, synchronous updates; `batch` coalesces multiple writes
|
|
16005
|
-
into one flush. Computeds settle before any effect runs, so an effect never sees one that lags its
|
|
16006
|
-
inputs. A write or batch runs each affected effect once; an effect runs again only when another
|
|
16007
|
-
effect writes one of its inputs during that flush, and its last run sees the settled values. A `computed` runs on first read and stops by itself once nothing reads it: the
|
|
16008
|
-
next change to its inputs stops it instead of recomputing, and reading it again computes it afresh.
|
|
16009
|
-
Every effect an island's setup creates stops when `mountIslands`' disposer unmounts it; one created
|
|
16010
|
-
outside an island runs until its disposer is called. Island-scale by design: if a widget outgrows this (lists, ownership trees,
|
|
16011
|
-
async orchestration), that's the signal to use the Solid adapter for that page - both tiers are
|
|
16012
|
-
first-class.
|
|
16013
|
-
|
|
16014
|
-
## For AI agents
|
|
16015
|
-
|
|
16016
|
-
Start with [`LLM.md`](./LLM.md) - this package's contract card (the exports you call + its footguns),
|
|
16017
|
-
one cheap read instead of the whole corpus. For the wider framework: the repo's
|
|
16018
|
-
[`AGENTS.md`](../../AGENTS.md) is the copy-paste quick reference, and
|
|
16019
|
-
[`llms-full.txt`](../../llms-full.txt) is the full machine-readable corpus. Run `nifra check` as the
|
|
16020
|
-
done-gate, or `nifra mcp` to give the agent live project tools.
|
|
16021
|
-
|
|
16022
17587
|
## @nifrajs/jobs
|
|
16023
17588
|
|
|
16024
17589
|
Typed background jobs for nifra - enqueue work off the request path, run it with **retries + exponential
|
|
@@ -16202,7 +17767,17 @@ const mcp = createMcpServer({
|
|
|
16202
17767
|
})
|
|
16203
17768
|
```
|
|
16204
17769
|
|
|
16205
|
-
Mount `mcp.fetch` at `
|
|
17770
|
+
Mount `mcp.fetch` at `/mcp` for `GET`, `POST` and `OPTIONS`:
|
|
17771
|
+
|
|
17772
|
+
```ts
|
|
17773
|
+
import { method } from "@nifrajs/core/methods"
|
|
17774
|
+
import { server } from "@nifrajs/core/server"
|
|
17775
|
+
|
|
17776
|
+
const app = server().use(method(["GET", "POST", "OPTIONS"], "/mcp", (c) => mcp.fetch(c.req)))
|
|
17777
|
+
```
|
|
17778
|
+
|
|
17779
|
+
`OPTIONS` carries a cross-origin browser client's CORS preflight to the server's own origin policy;
|
|
17780
|
+
without it the preflight gets a 405. The package also exposes the JSON-RPC protocol and Streamable HTTP
|
|
16206
17781
|
layers directly, plus `defineMcpWidget` and the React adapter for tool results that render UI in MCP
|
|
16207
17782
|
hosts.
|
|
16208
17783
|
|
|
@@ -16219,6 +17794,28 @@ Clients that include `text/event-stream` in `Accept` receive progress notificati
|
|
|
16219
17794
|
followed by the final JSON-RPC response in the same stream. An SSE `GET /mcp` opens a cancellable
|
|
16220
17795
|
server-message connection; a plain `GET /mcp` remains a health page.
|
|
16221
17796
|
|
|
17797
|
+
## stdio
|
|
17798
|
+
|
|
17799
|
+
A command an agent launches (`"command": "my-server"` in its MCP config) talks over stdin and stdout
|
|
17800
|
+
instead. `serveStdio` runs the same server that way, on Bun, Node or Deno:
|
|
17801
|
+
|
|
17802
|
+
```ts
|
|
17803
|
+
import { serveStdio } from "@nifrajs/mcp/stdio"
|
|
17804
|
+
|
|
17805
|
+
await serveStdio(mcp)
|
|
17806
|
+
```
|
|
17807
|
+
|
|
17808
|
+
It resolves when stdin ends and every pending request has answered. Whoever can write to the process's
|
|
17809
|
+
stdin can call every tool, so the HTTP origin, host and `authorizeMessage` options do not apply. Write
|
|
17810
|
+
logs to stderr: anything else on stdout corrupts the stream. `runStdioTransport` is the framing layer
|
|
17811
|
+
underneath, for a host that dispatches messages itself.
|
|
17812
|
+
|
|
17813
|
+
## Widgets on Node and Deno
|
|
17814
|
+
|
|
17815
|
+
A React widget from `@nifrajs/mcp/react` is bundled with `Bun.build`. For a server that runs on Node
|
|
17816
|
+
or Deno, bundle it at build time with `bundleReactWidget({ component })`, ship the returned body as a
|
|
17817
|
+
file, and pass that file's text to `defineMcpWidget({ uri, name, html })` at run time.
|
|
17818
|
+
|
|
16222
17819
|
## For AI agents
|
|
16223
17820
|
|
|
16224
17821
|
Start with [`LLM.md`](./LLM.md) - this package's contract card (the exports you call + its footguns),
|
|
@@ -16247,8 +17844,10 @@ const mcp = serveDatabaseAsMcp(new Database("app.db"), {
|
|
|
16247
17844
|
```
|
|
16248
17845
|
|
|
16249
17846
|
Only `list_tables` and `describe_table` are exposed by default, restricted to the explicit table
|
|
16250
|
-
allowlist. `
|
|
16251
|
-
|
|
17847
|
+
allowlist. `list_tables` counts rows in the same lane as `run_query`, within its time limit, and
|
|
17848
|
+
reuses the counts for 10 seconds. `run_query` requires an authorization hook and is guarded by SQLite
|
|
17849
|
+
query-only mode, single-statement/read-only checks, verification of the compiled statement, and
|
|
17850
|
+
bounded output. D1 is not supported
|
|
16252
17851
|
because it cannot provide the same engine-level read-only guarantee.
|
|
16253
17852
|
|
|
16254
17853
|
## The engine: `@nifrajs/mcp-db/engine`
|
|
@@ -16307,8 +17906,9 @@ Each layer refuses on its own, in this order:
|
|
|
16307
17906
|
1. **Host.** Only loopback, `*.localhost` and unix sockets connect unless `allowHosts` names the host.
|
|
16308
17907
|
URL parameters other than host, port, user, password, database and `sslmode` are ignored.
|
|
16309
17908
|
2. **Tokenizer.** One SELECT, WITH, VALUES or TABLE statement; row-locking clauses, unicode-escaped
|
|
16310
|
-
identifiers
|
|
16311
|
-
|
|
17909
|
+
identifiers, functions that reach outside a query (server files, `dblink`, `set_config`, advisory
|
|
17910
|
+
locks, `pg_notify`, `nextval`, backend signals) and functions that run SQL from a string the plan
|
|
17911
|
+
check cannot see (`query_to_xml`, `ts_stat`, `ts_rewrite`, `crosstab`, `connectby`) are refused.
|
|
16312
17912
|
3. **Read-only transaction.** `BEGIN READ ONLY` with `statement_timeout`, `lock_timeout` and
|
|
16313
17913
|
`idle_in_transaction_session_timeout` set to `timeoutMs`, always rolled back. Sessions also start
|
|
16314
17914
|
with `default_transaction_read_only = on`.
|
|
@@ -16323,7 +17923,9 @@ Each layer refuses on its own, in this order:
|
|
|
16323
17923
|
every `pg_catalog` function scanned in FROM must sit in `schemas` (default `public`) and outside
|
|
16324
17924
|
`exclude`. With `redaction`, a column `redaction.column` matches that any plan expression uses
|
|
16325
17925
|
(output, filter, join, sort or index condition), or a whole row holding one, is refused
|
|
16326
|
-
(`NIFRA_DB_COLUMN_REFUSED`).
|
|
17926
|
+
(`NIFRA_DB_COLUMN_REFUSED`). A plan names a scan's columns by the table's column alias list
|
|
17927
|
+
(`FROM users AS t(a, b)`), so while any relation the query reads holds a matching column, a query
|
|
17928
|
+
that gives a table one is refused as well.
|
|
16327
17929
|
|
|
16328
17930
|
`explainPostgres` returns the plan (with `analyze`, executed inside the same transaction),
|
|
16329
17931
|
`readPostgresSchema` reads tables, columns, keys and indexes from `pg_catalog`, and `postgresRoleSql`
|
|
@@ -16367,12 +17969,9 @@ const app = server()
|
|
|
16367
17969
|
.use(problemDetails())
|
|
16368
17970
|
.use(cors({ origin: ["https://app.example.com"], credentials: true }))
|
|
16369
17971
|
.use(bodyLimit({ maxBytes: 1_000_000 }))
|
|
16370
|
-
.
|
|
16371
|
-
|
|
16372
|
-
|
|
16373
|
-
windowMs: 60_000,
|
|
16374
|
-
key: (req) => req.headers.get("x-user-id") ?? "anonymous",
|
|
16375
|
-
}))
|
|
17972
|
+
// Keyed by the caller IP the server resolved. MemoryStore refuses production unless given
|
|
17973
|
+
// { allowInProduction: true } for a single instance; several instances need one shared store.
|
|
17974
|
+
.use(rateLimit({ store: new MemoryStore(), max: 100, windowMs: 60_000 }))
|
|
16376
17975
|
.use(timing())
|
|
16377
17976
|
.get("/", () => ({ ok: true }))
|
|
16378
17977
|
```
|
|
@@ -16911,7 +18510,7 @@ const upstream = createProxy({ upstream: "http://127.0.0.1:8081" })
|
|
|
16911
18510
|
const app = server().mountFetch("/api", upstream, { stripPrefix: true })
|
|
16912
18511
|
```
|
|
16913
18512
|
|
|
16914
|
-
The upstream is a **bare origin** fixed at construction - the forwarded URL is built by mutating a clone of that origin, never by resolving request-derived strings, so no request input can change which host is dialed. Hop-by-hop and `Connection`-nominated headers are stripped in both directions. Every inbound `Forwarded` and `X-Forwarded-*` header is dropped; caller IP/protocol metadata is re-added only under `forwardClientIp: true`, and any other forwarding header only as a fixed `headers` entry. The inbound Host is never trusted, and `X-Forwarded-Host` is emitted only from a fixed `forwardedHost`. Upstream redirects are never followed, and TLS verification has no off switch. Unreachable upstreams answer a flat `502`; the deadline (`timeoutMs`, default 30s) answers `504`.
|
|
18513
|
+
The upstream is a **bare origin** fixed at construction - the forwarded URL is built by mutating a clone of that origin, never by resolving request-derived strings, so no request input can change which host is dialed. Hop-by-hop and `Connection`-nominated headers are stripped in both directions. Every inbound `Forwarded` and `X-Forwarded-*` header is dropped; caller IP/protocol metadata is re-added only under `forwardClientIp: true`, and any other forwarding header only as a fixed `headers` entry. The one exception is `trustForwardedFor: true` (with `forwardClientIp`), which keeps the inbound `X-Forwarded-For` chain and appends the caller: set it only behind a proxy you control, since any caller that reaches this one directly can forge the leading entries. The inbound Host is never trusted, and `X-Forwarded-Host` is emitted only from a fixed `forwardedHost`. Upstream redirects are never followed, and TLS verification has no off switch. Unreachable upstreams answer a flat `502`; the deadline (`timeoutMs`, default 30s) answers `504`.
|
|
16915
18514
|
|
|
16916
18515
|
## Docs
|
|
16917
18516
|
|
|
@@ -16994,8 +18593,9 @@ const openapi = toOpenAPI(app) // OpenAPI 3.1
|
|
|
16994
18593
|
- **Validating string formats** - `email`/`uuid`/`date-time`/`date`/`time`/`uri`/`ipv4`
|
|
16995
18594
|
validate *and* annotate; register more with `registerFormat`.
|
|
16996
18595
|
- **`toOpenAPI`** - richest from a contract (it carries `response` schemas + op names →
|
|
16997
|
-
`operationId`s); also works on a live app.
|
|
16998
|
-
|
|
18596
|
+
`operationId`s); also works on a live app. A Standard Schema that also implements Standard JSON
|
|
18597
|
+
Schema (zod 4 does) is described like `t`; one that exposes no JSON Schema is emitted without a
|
|
18598
|
+
detailed schema.
|
|
16999
18599
|
|
|
17000
18600
|
### Static validators for edge runtimes
|
|
17001
18601
|
|
|
@@ -17087,9 +18687,11 @@ cost - TypeBox carries the whole JSON Schema type system, so `t` adds meaningful
|
|
|
17087
18687
|
|
|
17088
18688
|
nifra validates through **Standard Schema**, so any Standard-Schema validator works on a route with
|
|
17089
18689
|
no adapter - `{ body: v.object({ ... }) }` with valibot, for instance. A validated app built on a
|
|
17090
|
-
lean validator like valibot is a
|
|
17091
|
-
edge/Workers cold-starts. The trade is
|
|
17092
|
-
JSON Schema
|
|
18690
|
+
lean validator like valibot is lighter (a minimal app measures about 38 KB gzipped on valibot and
|
|
18691
|
+
about 62 KB on `t`, `bun run bench:size`), which matters for edge/Workers cold-starts. The trade is
|
|
18692
|
+
the one noted above: a validator that exposes no JSON Schema (valibot without a Standard JSON Schema
|
|
18693
|
+
wrapper) gives those routes no OpenAPI/MCP detail. One that implements Standard JSON Schema
|
|
18694
|
+
(`~standard.jsonSchema`, as zod 4 does) is described from it.
|
|
17093
18695
|
|
|
17094
18696
|
Rule of thumb: reach for `t` when you want the contract (OpenAPI/MCP) for free; bring valibot (or any
|
|
17095
18697
|
Standard-Schema validator) when bundle size on the edge is the priority. Both are first-class - the
|
|
@@ -17105,13 +18707,22 @@ It emits `paths`, `parameters` (path + object query), `requestBody`, and `respon
|
|
|
17105
18707
|
- **Non-200 responses** and **non-JSON content** - a contract op's `responses` map declares extra status
|
|
17106
18708
|
codes; `requestContentType` / `responseContentType` set media types other than `application/json`.
|
|
17107
18709
|
- **`$ref` reuse** - a schema with a `$id` (`t.object({…}, { $id: "User" })`) is hoisted into
|
|
17108
|
-
`components.schemas` once and referenced by `$ref` everywhere it's used.
|
|
18710
|
+
`components.schemas` once and referenced by `$ref` everywhere it's used. A Standard JSON Schema's
|
|
18711
|
+
`$defs` are hoisted the same way, so its refs resolve inside the document.
|
|
18712
|
+
- **Framework errors** - the responses the server answers before a handler runs, as the shared
|
|
18713
|
+
`NifraError` (`{ ok: false, error }`) and `NifraValidationError` (`{ ok: false, error: "validation",
|
|
18714
|
+
issues }`) components: `400`, `413` and `415` on a route with a body, `422` on any route with a request
|
|
18715
|
+
schema (left out when an `onValidationError` hook writes that body). A declared response wins.
|
|
18716
|
+
- **Tagged unions** - a union whose members all pin one required property to distinct values is
|
|
18717
|
+
emitted as a `oneOf`. When every member is a component (a `$id`) it also gets a `discriminator`
|
|
18718
|
+
with a `mapping`, so a client generator can build a tagged union; OpenAPI discriminators never
|
|
18719
|
+
consider inline members.
|
|
17109
18720
|
- Per-operation **`summary`**, **`description`**, **`tags`**, **`deprecated`** - declared on the contract op.
|
|
17110
18721
|
|
|
17111
18722
|
A **contract** is richest (its ops carry all of the above); in **app** mode a route's response is a
|
|
17112
18723
|
generic `200` with no schema - declare a `defineContract` with `response` schemas, or pass
|
|
17113
|
-
`options.operations` (keyed by `"METHOD /path"`) to enrich app routes. Routes using a
|
|
17114
|
-
are still emitted without body/response detail
|
|
18724
|
+
`options.operations` (keyed by `"METHOD /path"`) to enrich app routes. Routes using a schema that
|
|
18725
|
+
exposes no JSON Schema are still emitted without body/response detail.
|
|
17115
18726
|
|
|
17116
18727
|
`@nifrajs/core` is a peer dependency. ESM-only. MIT.
|
|
17117
18728
|
|
|
@@ -17553,7 +19164,7 @@ MIT
|
|
|
17553
19164
|
|
|
17554
19165
|
## @nifrajs/uploads
|
|
17555
19166
|
|
|
17556
|
-
File-upload hardening for nifra - magic-byte
|
|
19167
|
+
File-upload hardening for nifra - size + magic-byte type validation, short-TTL signed download URLs, and EXIF/metadata stripping. Edge-safe.
|
|
17557
19168
|
|
|
17558
19169
|
Part of the **[nifra](https://nifra.dev)** full-stack TypeScript framework - one core, five UI libraries, every runtime. Scaffold a new app with `bun create nifra`.
|
|
17559
19170
|
|
|
@@ -17569,8 +19180,9 @@ bun add @nifrajs/uploads
|
|
|
17569
19180
|
body schema instead - validated before the handler runs, typed in `c.body` - use `t.file` and
|
|
17570
19181
|
`t.form` from `@nifrajs/schema/form`, which run the same signature detection.
|
|
17571
19182
|
|
|
17572
|
-
|
|
17573
|
-
`FILE_TYPE_PREFIX_BYTES`
|
|
19183
|
+
For code that needs file-type detection and nothing else, import `detectFileType`,
|
|
19184
|
+
`DETECTABLE_MIME_TYPES`, `FILE_TYPE_PREFIX_BYTES` and the `FileType` type from
|
|
19185
|
+
`@nifrajs/core/file-type`.
|
|
17574
19186
|
|
|
17575
19187
|
## Docs
|
|
17576
19188
|
|
|
@@ -17753,6 +19365,17 @@ Vanilla is the render adapter an agent gets right on the first try. It ships no
|
|
|
17753
19365
|
|
|
17754
19366
|
Interactivity is added with **islands**, not hydration: small imperative DOM enhancers over server-rendered elements. `defineIsland` types the props, `createIslandBus` coordinates islands over a typed channel, and every enhancer returns its cleanup - the one rule `nifra check` enforces (`NF-C020`). See the [islands cookbook](https://nifra.dev/docs/islands) for the counter, cart-badge, and filter patterns, or run `nifra scaffold` on a vanilla route for the golden stub.
|
|
17755
19367
|
|
|
19368
|
+
To refresh one region from a link or GET form without a full reload, render it with `slot(name, content)` inside a `data-swap-slot="<name>"` element and mark the link or form `data-swap="replace:<name>"` or `"append:<name>"`; the page then answers a swap request with that slot alone, and `enableSwap` from `@nifrajs/web/islands/swap` puts it in place. POST forms submit natively, and a swapped slot runs under the current page's Content-Security-Policy. See [Refresh part of the page](https://nifra.dev/docs/islands).
|
|
19369
|
+
|
|
19370
|
+
## Escaping
|
|
19371
|
+
|
|
19372
|
+
`html` writes each interpolated value for the place it lands, read from the template's own text:
|
|
19373
|
+
|
|
19374
|
+
- In text and in a quoted attribute value, it is HTML-escaped.
|
|
19375
|
+
- An unquoted attribute value (`class=${name}`) is quoted for you, so a space in the value cannot start another attribute.
|
|
19376
|
+
- A `javascript:` or `vbscript:` URL that begins an `href`, `src`, `action` or other URL attribute is written as `about:invalid`.
|
|
19377
|
+
- No escaping makes a string safe as a tag name, inside `<script>` or `<style>`, or in an `on*` handler or `srcdoc` value, so a string or nested template throws there. An attribute name takes only a plain name with no value (`<input ${checked ? "checked" : ""}>`), or a suffix after `data-` or `aria-`. Numbers and booleans fill any of these, and `raw()` is the explicit opt-out for trusted text.
|
|
19378
|
+
|
|
17756
19379
|
Need a stateful app UI with reactive components? That is what the five framework adapters are for - reach for `@nifrajs/web-preact` or `@nifrajs/web-solid` when you want a small reactive runtime.
|
|
17757
19380
|
|
|
17758
19381
|
## Install
|
|
@@ -17911,7 +19534,7 @@ open page.
|
|
|
17911
19534
|
- WebMCP registration is not authorization. Enforce authorization again at the server boundary.
|
|
17912
19535
|
- Keep inputs narrow and annotations honest. A safety hint is not a permission.
|
|
17913
19536
|
- Predictions are pure local transforms and cannot grant capability or bypass core policy.
|
|
17914
|
-
- Receipts contain status, bounded evidence, and error codes
|
|
19537
|
+
- Receipts contain status, bounded evidence, and error codes - not credentials, request bodies, secrets, or
|
|
17915
19538
|
stack traces.
|
|
17916
19539
|
- Normal browsers and non-WebMCP hosts receive a safe unsupported report.
|
|
17917
19540
|
|
|
@@ -17996,6 +19619,20 @@ bun install
|
|
|
17996
19619
|
bun run dev
|
|
17997
19620
|
```
|
|
17998
19621
|
|
|
19622
|
+
## As a library
|
|
19623
|
+
|
|
19624
|
+
A tool that generates a nifra app can write the same starter without shelling out to the CLI.
|
|
19625
|
+
`create-nifra/scaffold` runs on Bun, Node and Deno, and importing it never starts the CLI:
|
|
19626
|
+
|
|
19627
|
+
```ts
|
|
19628
|
+
import { scaffold } from "create-nifra/scaffold"
|
|
19629
|
+
|
|
19630
|
+
const result = await scaffold({ target: "./my-api", template: "api" })
|
|
19631
|
+
```
|
|
19632
|
+
|
|
19633
|
+
It takes the CLI's options (`template`, `framework`, `deployTarget`, `docker`, `ci`, `db`, `auth`,
|
|
19634
|
+
`force`, `link`) and refuses a non-empty directory unless `force` is set.
|
|
19635
|
+
|
|
17999
19636
|
MIT.
|
|
18000
19637
|
|
|
18001
19638
|
## For AI agents
|
|
@@ -18103,7 +19740,7 @@ done-gate, or `nifra mcp` to give the agent live project tools.
|
|
|
18103
19740
|
|
|
18104
19741
|
## @nifrajs/coding-agent
|
|
18105
19742
|
|
|
18106
|
-
`AGENT_CAPABILITY_MANIFEST_VERSION`, `AGENT_PRESETS`, `APPROVAL_NEVER_EXPIRES_AT`, `AgentCapability`, `AgentCapabilityManifest`, `AgentPlan`, `AgentPreset`, `AgentPresetName`, `ApprovalDecision`, `ApprovalManager`, `ApprovalManagerOptions`, `ApprovalMatchRejection`, `ApprovalMatchResult`, `ApprovalRequest`, `ApprovalTimeout`, `BoundedSubagentRunner`, `BoundedText`, `CapabilityDescriptor`, `CiDeploymentAdapter`, `CodingAgentExtension`, `CodingAgentHost`, `CodingAgentHostOptions`, `CodingAgentRpcServer`, `CodingAgentRpcServerHandle`, `CodingAgentRpcServerOptions`, `CompactionReport`, `ContextRecord`, `ContextWindow`, `ContextWindowOptions`, `DEPLOYMENT_REFERENCE_PROFILES`, `ExtensionCommand`, `ExtensionContext`, `ExtensionDescriptorOptions`, `ExtensionDescriptorSource`, `ExtensionEventHandler`, `ExtensionHost`, `ExtensionHostOptions`, `ExtensionProvider`, `ExtensionReloadResult`, `ExtensionSubagent`, `ExtensionTool`, `FileSessionStore`, `FileSessionStoreOptions`, `HandoffCoordinator`, `HandoffCoordinatorOptions`, `HandoffDecision`, `HandoffError`, `HandoffRejection`, `HandoffView`, `HealingEvent`, `HealingOptions`, `HealingResult`, `IsolatedExtensionSnapshot`, `IsolatedExtensionTool`, `IsolatedExtensionWorker`, `IsolatedExtensionWorkerOptions`, `LocalProcessDeploymentAdapter`, `MigrateLegacySessionOptions`, `NIFRA_AGENT_INSTRUCTIONS`, `NativeApprovalPort`, `NativeGatewayModelPortOptions`, `NativeMessage`, `NativeModelChunk`, `NativeModelPort`, `NativeModelRequest`, `NativeModelResponse`, `NativeTool`, `NifraAgentTool`, `NifraBackend`, `NifraBackendOptions`, `NifraContextOptions`, `NifraContextResult`, `OpenHandoffInput`, `PiBackend`, `PiBackendOptions`, `PlanEvent`, `PlanPhase`, `PlanResult`, `PlanRunner`, `PlanRunnerOptions`, `ProjectDiffOptions`, `ProjectDiffResult`, `RepairProposal`, `ReplayBackend`, `ReplayBackendOptions`, `ReplayDeploymentAdapter`, `ReviewExecutionErrorCode`, `ReviewExecutionResult`, `ReviewOptions`, `SESSION_EVIDENCE_VERSION`, `SelfHealingController`, `SessionEvidenceRecord`, `SessionLogEntry`, `SessionMigrationError`, `SessionMigrationReport`, `SessionStore`, `SubagentAbandonment`, `SubagentAbandonmentLedger`, `SubagentExecutor`, `SubagentResult`, `SubagentRunnerOptions`, `SubagentSpec`, `UiExtensionHost`, `UiExtensionHostOptions`, `UiExtensionManifest`, `UiExtensionSlot`, `UiReloadResult`, `UiStatusWidget`, `UiThemeDescriptor`, `VerificationOptions`, `VerificationRepairTask`, `VerificationResult`, `WorkflowContext`, `WorkflowEvent`, `WorkflowResult`, `WorkflowRunner`, `WorkflowRunnerOptions`, `WorkflowStep`, `approvalRequestFromEvent`, `approvalResolvedEvent`, `createCapabilityManifest`, `createCiDeploymentAdapter`, `createLocalProcessDeploymentAdapter`, `createNativeGatewayModelPort`, `createNifraTools`, `createPresetSpec`, `createReplayDeploymentAdapter`, `createVerificationRepairTask`, `deniedCapabilities`, `discoverExtensions`, `extensionDescriptor`, `extensionDescriptors`, `getAgentPreset`, `isSafeReviewDiff`, `isVerificationAvailable`, `migrateLegacySession`, `parseCapabilityManifest`, `parseSessionEvidenceRecord`, `readBoundedText`, `readProjectDiff`, `readReplayEvents`, `runNifraContext`, `runNifraReview`, `runNifraVerification`, `stableSessionEventCode`, `validateExtensionModule`
|
|
19743
|
+
`AGENT_CAPABILITY_MANIFEST_VERSION`, `AGENT_PRESETS`, `APPROVAL_NEVER_EXPIRES_AT`, `AgentCapability`, `AgentCapabilityManifest`, `AgentPlan`, `AgentPreset`, `AgentPresetName`, `ApprovalDecision`, `ApprovalManager`, `ApprovalManagerOptions`, `ApprovalMatchRejection`, `ApprovalMatchResult`, `ApprovalRequest`, `ApprovalTimeout`, `BoundedSubagentRunner`, `BoundedText`, `CapabilityDescriptor`, `CiDeploymentAdapter`, `CodingAgentExtension`, `CodingAgentHost`, `CodingAgentHostOptions`, `CodingAgentRpcServer`, `CodingAgentRpcServerHandle`, `CodingAgentRpcServerOptions`, `CompactionReport`, `ContextRecord`, `ContextWindow`, `ContextWindowOptions`, `DEPLOYMENT_REFERENCE_PROFILES`, `ExtensionCommand`, `ExtensionContext`, `ExtensionDescriptorOptions`, `ExtensionDescriptorSource`, `ExtensionEventHandler`, `ExtensionHost`, `ExtensionHostOptions`, `ExtensionProvider`, `ExtensionReloadResult`, `ExtensionSubagent`, `ExtensionTool`, `FileSessionStore`, `FileSessionStoreOptions`, `HandoffCoordinator`, `HandoffCoordinatorOptions`, `HandoffDecision`, `HandoffError`, `HandoffRejection`, `HandoffView`, `HealingEvent`, `HealingOptions`, `HealingResult`, `IsolatedExtensionSnapshot`, `IsolatedExtensionTool`, `IsolatedExtensionWorker`, `IsolatedExtensionWorkerOptions`, `LocalProcessDeploymentAdapter`, `MigrateLegacySessionOptions`, `NIFRA_AGENT_INSTRUCTIONS`, `NativeApprovalPort`, `NativeGatewayModelPortOptions`, `NativeMessage`, `NativeModelChunk`, `NativeModelPort`, `NativeModelRequest`, `NativeModelResponse`, `NativeTool`, `NifraAgentTool`, `NifraBackend`, `NifraBackendOptions`, `NifraContextOptions`, `NifraContextResult`, `OpenHandoffInput`, `PiBackend`, `PiBackendOptions`, `PlanEvent`, `PlanPhase`, `PlanResult`, `PlanRunner`, `PlanRunnerOptions`, `ProjectDiffOptions`, `ProjectDiffResult`, `RepairProposal`, `ReplayBackend`, `ReplayBackendOptions`, `ReplayDeploymentAdapter`, `ReviewExecutionErrorCode`, `ReviewExecutionResult`, `ReviewOptions`, `SESSION_EVIDENCE_VERSION`, `SelfHealingController`, `SessionEvidenceRecord`, `SessionLogEntry`, `SessionMigrationError`, `SessionMigrationReport`, `SessionStore`, `SubagentAbandonment`, `SubagentAbandonmentLedger`, `SubagentChildLedger`, `SubagentExecutor`, `SubagentResult`, `SubagentRunnerOptions`, `SubagentSpec`, `UiExtensionHost`, `UiExtensionHostOptions`, `UiExtensionManifest`, `UiExtensionSlot`, `UiReloadResult`, `UiStatusWidget`, `UiThemeDescriptor`, `VerificationOptions`, `VerificationRepairTask`, `VerificationResult`, `WorkflowContext`, `WorkflowEvent`, `WorkflowResult`, `WorkflowRunner`, `WorkflowRunnerOptions`, `WorkflowStep`, `approvalRequestFromEvent`, `approvalResolvedEvent`, `createCapabilityManifest`, `createCiDeploymentAdapter`, `createLocalProcessDeploymentAdapter`, `createNativeGatewayModelPort`, `createNifraTools`, `createPresetSpec`, `createReplayDeploymentAdapter`, `createVerificationRepairTask`, `deniedCapabilities`, `discoverExtensions`, `extensionDescriptor`, `extensionDescriptors`, `getAgentPreset`, `isSafeReviewDiff`, `isVerificationAvailable`, `migrateLegacySession`, `parseCapabilityManifest`, `parseSessionEvidenceRecord`, `readBoundedText`, `readProjectDiff`, `readReplayEvents`, `runNifraContext`, `runNifraReview`, `runNifraVerification`, `stableSessionEventCode`, `validateExtensionModule`
|
|
18107
19744
|
|
|
18108
19745
|
## @nifrajs/content
|
|
18109
19746
|
|
|
@@ -18111,7 +19748,7 @@ done-gate, or `nifra mcp` to give the agent live project tools.
|
|
|
18111
19748
|
|
|
18112
19749
|
## @nifrajs/core
|
|
18113
19750
|
|
|
18114
|
-
`AdmissionController`, `AdmissionDecision`, `AnyServer`, `AuthHeaders`, `AuthMaybePromise`, `AuthenticationFailure`, `AuthenticationFailureReason`, `AuthenticationInput`, `AuthenticationResult`, `AuthenticationStage`, `AuthenticationSuccess`, `Context`, `ContextPlugin`, `CookieOptions`, `CookieSecret`, `DeclaredMountRoute`, `DefinePluginResult`, `DurableObjectNamespaceLike`, `ExecutionContext`, `FRAMEWORK_NAME`, `FetchApp`, `FrameworkError`, `FrameworkName`, `Handler`, `IdentityPlugin`, `InferInput`, `InferOutput`, `JoinRoutePath`, `LambdaEvent`, `LambdaHandler`, `LambdaResponse`, `LambdaV1Event`, `LambdaV2Event`, `ListenTlsOptions`, `LogFields`, `Logger`, `METHODS`, `McpPromptDescriptor`, `McpResourceDescriptor`, `Method`, `Middleware`, `MountFetchOptions`, `MountOptions`, `MountableApp`, `NetlifyEvent`, `NetlifyHandler`, `NifraFeatureVersion`, `NifraPlugin`, `NifraWebSocket`, `NodeRequestContext`, `NodeRequestHook`, `NodeResponseBodyHook`, `NodeResponseContext`, `NodeResponseHook`, `NodeServeOutcome`, `OnRequestResult`, `OpaqueMountDeclaration`, `Params`, `PlainRender`, `Platform`, `PlatformResponse`, `PluginTypeCollapsed`, `PrefixRegistry`, `Prettify`, `PromptArgument`, `PromptMessage`, `ROUTE_PATTERN_OVERLAP_MAX_STATES`, `RedactOptions`, `Registry`, `RequestPath`, `ResponseBodyHook`, `ResponseBodyReplacement`, `ResponseControls`, `ResponseFinalization`, `ResponseHeadersHook`, `ResponseHeadersView`, `ResponseMapFor`, `ResponseResult`, `RouteConfigError`, `RouteConfigErrorCode`, `RouteDescriptor`, `RouteInfo`, `RouteInfoFor`, `RouteMethod`, `RoutePatternOverlapLimitError`, `RouteSchema`, `Router`, `RouterMatch`, `RunningServer`, `SSEContext`, `SSEInit`, `SSEMessage`, `SSEStream`, `ScheduledController`, `ScheduledHandler`, `Server`, `ServerOptions`, `StandardIssue`, `StandardResult`, `StandardSchemaV1`, `StandardTypes`, `StandardWebSocket`, `StatusResponse`, `ToolAnnotations`, `TypedSSEStream`, `UrlParts`, `VERSION`, `ValidationOutcome`, `VercelHandler`, `Version`, `WebSocketContext`, `WebSocketData`, `WebSocketHandler`, `WebSocketUpgradeOutcome`, `authenticated`, `commonSecretPatterns`, `cookieNamePrefix`, `defineContextPlugin`, `defineIdentityPlugin`, `definePlugin`, `defineRouterPlugin`, `hasDuplicateCookie`, `isAuthenticatedRequest`, `isSameOriginForm`, `isSameOriginPath`, `isSameOriginRequest`, `jsonLogger`, `markAuthenticatedRequest`, `parseCookies`, `pathnameOf`, `redactLogFields`, `rejected`, `replacedRequestOf`, `routePatternOverlap`, `serializeCookie`, `server`, `signValue`, `silentLogger`, `status`, `toFetchHandler`, `toLambdaHandler`, `toNetlifyHandler`, `toVercelHandler`, `unsignValue`, `urlPartsOf`, `writableResponse`
|
|
19751
|
+
`AdmissionController`, `AdmissionDecision`, `AnyServer`, `AuthHeaders`, `AuthMaybePromise`, `AuthenticationFailure`, `AuthenticationFailureReason`, `AuthenticationInput`, `AuthenticationResult`, `AuthenticationStage`, `AuthenticationSuccess`, `Context`, `ContextPlugin`, `CookieOptions`, `CookieSecret`, `DeclaredMountRoute`, `DefinePluginResult`, `DurableObjectNamespaceLike`, `ExecutionContext`, `FRAMEWORK_NAME`, `FetchApp`, `FrameworkError`, `FrameworkName`, `Handler`, `IdentityPlugin`, `InferInput`, `InferOutput`, `JoinRoutePath`, `LambdaEvent`, `LambdaHandler`, `LambdaResponse`, `LambdaV1Event`, `LambdaV2Event`, `ListenTlsOptions`, `LogFields`, `Logger`, `METHODS`, `McpPromptDescriptor`, `McpResourceDescriptor`, `Method`, `Middleware`, `MountFetchOptions`, `MountOptions`, `MountableApp`, `NetlifyEvent`, `NetlifyHandler`, `NifraFeatureVersion`, `NifraPlugin`, `NifraWebSocket`, `NodeRequestContext`, `NodeRequestHook`, `NodeResponseBodyHook`, `NodeResponseContext`, `NodeResponseHook`, `NodeServeOutcome`, `OnRequestResult`, `OpaqueMountDeclaration`, `Params`, `PlainRender`, `Platform`, `PlatformResponse`, `PluginTypeCollapsed`, `PrefixRegistry`, `Prettify`, `PromptArgument`, `PromptMessage`, `ROUTE_PATTERN_OVERLAP_MAX_STATES`, `RedactOptions`, `Registry`, `RequestPath`, `ResponseBodyHook`, `ResponseBodyReplacement`, `ResponseControls`, `ResponseFinalization`, `ResponseHeadersHook`, `ResponseHeadersView`, `ResponseMapFor`, `ResponseResult`, `RouteConfigError`, `RouteConfigErrorCode`, `RouteDescriptor`, `RouteInfo`, `RouteInfoFor`, `RouteMethod`, `RoutePatternOverlapLimitError`, `RouteSchema`, `Router`, `RouterMatch`, `RunningServer`, `SSEContext`, `SSEInit`, `SSEMessage`, `SSEStream`, `ScheduledController`, `ScheduledHandler`, `Server`, `ServerOptions`, `StandardIssue`, `StandardResult`, `StandardSchemaV1`, `StandardTypes`, `StandardWebSocket`, `StatusResponse`, `ToolAnnotations`, `TypedSSEStream`, `UrlParts`, `VERSION`, `ValidationOutcome`, `VercelHandler`, `Version`, `WebSocketContext`, `WebSocketData`, `WebSocketHandler`, `WebSocketUpgradeOutcome`, `authenticated`, `beforeHandler`, `commonSecretPatterns`, `cookieNamePrefix`, `defineContextPlugin`, `defineIdentityPlugin`, `definePlugin`, `defineRouterPlugin`, `hasDuplicateCookie`, `isAuthenticatedRequest`, `isSameOriginForm`, `isSameOriginPath`, `isSameOriginRequest`, `jsonLogger`, `markAuthenticatedRequest`, `parseCookies`, `pathnameOf`, `redactLogFields`, `rejected`, `replacedRequestOf`, `routePatternOverlap`, `serializeCookie`, `server`, `signValue`, `silentLogger`, `status`, `toFetchHandler`, `toLambdaHandler`, `toNetlifyHandler`, `toVercelHandler`, `unsignValue`, `urlPartsOf`, `writableResponse`
|
|
18115
19752
|
|
|
18116
19753
|
## @nifrajs/cron
|
|
18117
19754
|
|
|
@@ -18153,10 +19790,6 @@ done-gate, or `nifra mcp` to give the agent live project tools.
|
|
|
18153
19790
|
|
|
18154
19791
|
`IslandStrategy`, `MAX_MEDIA_QUERY_LENGTH`, `TriggerOptions`, `scheduleTrigger`
|
|
18155
19792
|
|
|
18156
|
-
## @nifrajs/islets
|
|
18157
|
-
|
|
18158
|
-
`BindableElement`, `BindableRoot`, `Computed`, `IslandContext`, `IslandHost`, `IslandScope`, `IslandSetup`, `IslandStrategy`, `MountIslandOptions`, `Signal`, `batch`, `bindScope`, `computed`, `effect`, `island`, `islandState`, `mountIslands`, `signal`
|
|
18159
|
-
|
|
18160
19793
|
## @nifrajs/jobs
|
|
18161
19794
|
|
|
18162
19795
|
`Backoff`, `CapabilityBeacon`, `DeadLetterRecord`, `DeadLetterView`, `EnqueueOptions`, `ExponentialOptions`, `JobContext`, `JobCounts`, `JobDefinition`, `JobEnqueueInfo`, `JobError`, `JobHandle`, `JobHandler`, `JobRunInfo`, `JobRunOutcome`, `JobStore`, `JobTimeoutError`, `JobTraceContext`, `JobValidationError`, `MemoryJobStore`, `Queue`, `QueueHealth`, `QueueInstrument`, `QueueOptions`, `RetryPolicy`, `StandardResult`, `StandardSchemaV1`, `StoredJob`, `Worker`, `WorkerOptions`, `createQueue`, `exponentialBackoff`, `fixedBackoff`, `noBackoff`, `toDeadLetterView`, `toQueueHealth`
|
|
@@ -18219,11 +19852,11 @@ done-gate, or `nifra mcp` to give the agent live project tools.
|
|
|
18219
19852
|
|
|
18220
19853
|
## @nifrajs/uploads
|
|
18221
19854
|
|
|
18222
|
-
`
|
|
19855
|
+
`ImagePixelLimitError`, `ImageReencoder`, `SignDownloadUrlOptions`, `StripImageMetadataOptions`, `UploadResult`, `ValidateUploadOptions`, `signDownloadUrl`, `stripImageMetadata`, `validateUpload`, `verifyDownloadUrl`
|
|
18223
19856
|
|
|
18224
19857
|
## @nifrajs/web
|
|
18225
19858
|
|
|
18226
|
-
`ACTION_GLOBAL`, `Action`, `BOUNDARY_GLOBAL`, `BackendOnly`, `Blocker`, `BlockerController`, `BlockerFunction`, `BlockerLocation`, `BlockerState`, `Boundary`, `BoundaryDescriptor`, `BoundaryError`, `BoundaryMode`, `BoundaryRegistration`, `BoundaryRequestCtx`, `BoundaryState`, `BoundaryStates`, `BoundaryStatus`, `BrowserNavigate`, `BuildAssetSet`, `CacheStore`, `CachedResponse`, `CdnPurgeOutcome`, `CdnPurgeTarget`, `ClientAction`, `ClientActionArgs`, `ClientActionResult`, `ClientLoader`, `ClientLoaderArgs`, `ClientRequestBody`, `ClientRouteHooks`, `ClientRouter`, `ClientRouterOptions`, `CreateCspPolicyOptions`, `CreateNonceResolverOptions`, `CreateWebAppOptions`, `CspHeaderContext`, `CspPolicy`, `CssLoadingMode`, `DATA_GLOBAL`, `DATA_HEADER`, `DEFAULT_CSS_LOADING`, `DEFAULT_DEV_PORT`, `DRAFT_COOKIE`, `Deferred`, `DehydratedState`, `DocumentParts`, `DraftCookieControls`, `DynamicBoundary`, `DynamicBoundaryBatch`, `EnableDraftOptions`, `FetchRouteData`, `Fetcher`, `FetcherState`, `FontDisplay`, `FontFace`, `FontPreloadInput`, `FontSource`, `GenerateClientEntryOptions`, `GenerateRouteSearchTypesOptions`, `GenerateServerManifestOptions`, `GetStaticPaths`, `HANDOVER_ID`, `HostPolicy`, `HostPolicyOptions`, `HostPolicyRule`, `HtmlSanitizer`, `IDLE_BLOCKER`, `ISRApp`, `ISROptions`, `ISRPlatform`, `ISRQuery`, `ISRStoreOp`, `ISR_REVALIDATE_HEADER`, `ISR_REVALIDATE_TAGS_HEADER`, `ISR_STATUS_HEADER`, `InertScriptType`, `InfiniteData`, `InfiniteQueryHandle`, `InfiniteQueryOptions`, `InterceptBoundary`, `KVCacheStore`, `KVCacheStoreOptions`, `KVNamespaceLike`, `LAYOUT_DATA_GLOBAL`, `LOCALES_GLOBAL`, `LayoutEntry`, `LinkDescriptor`, `Loader`, `LoaderContext`, `LoaderResponseControls`, `LoadingEntry`, `Manifest`, `MatchChain`, `MemoryCacheStore`, `MemoryCacheStoreOptions`, `MemoryStaticBoundaryCache`, `Meta`, `MetaArgs`, `MetaDescriptor`, `MetaInput`, `MiddlewareOutcome`, `MountRouterOptions`, `MutationCallbacks`, `MutationHandle`, `MutationState`, `MutationStatus`, `NAV_FROM_HEADER`, `NavigateFunction`, `NavigateOptions`, `NavigateSearchOf`, `NavigateTargetInput`, `NonceContext`, `NonceGenerator`, `NonceHeader`, `NonceHeaderContext`, `NonceResolver`, `NotFoundEntry`, `NotFoundScope`, `OpenGraphInput`, `PRE_HYDRATION_GUARD`, `PageLocale`, `PageLocales`, `PendingBoundary`, `PrefetchMode`, `PrerenderedPageReaderOptions`, `PrerenderedPages`, `PreviewEndpointOptions`, `PublicDirCache`, `QueryClient`, `QueryClientOptions`, `QueryHandle`, `QueryOptions`, `QueryState`, `QueryStatus`, `REDIRECT_HEADER`, `RETAIN_HEADER`, `REVALIDATE_HEADER`, `ROOT_ATTRIBUTE`, `ROUTE_GLOBAL`, `RedirectOptions`, `RenderAdapter`, `RenderAdapterConformanceError`, `RenderAdapterConformanceFixture`, `RenderAssemblyCache`, `RenderPageInput`, `RenderPageOptions`, `RenderProps`, `RenderStreamOptions`, `RenderedPage`, `RevalidateEndpointOptions`, `RevalidateResult`, `RevalidateTags`, `RevalidateTagsInput`, `RouteEntry`, `RouteMatch`, `RouteMiddleware`, `RouteModule`, `RoutePattern`, `RouteSearch`, `RouterState`, `SERVER_FN_MODULE`, `STATUS_HEADER`, `SanitizedHtml`, `ScriptDescriptor`, `SearchOf`, `ServePublicDirOptions`, `ShouldRevalidate`, `ShouldRevalidateArgs`, `SsrModuleLoader`, `StaticBoundary`, `StaticBoundaryCache`, `StaticBoundaryImportEdge`, `StaticBoundaryRoot`, `StaticCtx`, `StaticPath`, `StaticPaths`, `StaticRoutes`, `StatusPageOptions`, `Submission`, `SubmitOptions`, `TrustedHtml`, `UIMatch`, `UnsafeScriptDescriptor`, `WebAppI18n`, `assertCssLoadingCompatible`, `assertRenderAdapterConformance`, `assertStaticBoundaryImports`, `boundaryDescriptors`, `boundaryModeKey`, `buildManifest`, `canonical`, `createClientRouter`, `createCspPolicy`, `createHostPolicy`, `createMatcher`, `createMutation`, `createNonceResolver`, `createQueryClient`, `createWebApp`, `defer`, `disableDraft`, `enableDraft`, `enumerateStaticRoutes`, `filePathToPattern`, `filePathToPatterns`, `fontFace`, `fontPreload`, `generateClientEntry`, `generateRouteSearchTypes`, `generateServerManifest`, `getBrowserNavigate`, `gone`, `hashQueryKey`, `isCacheablePage`, `isDraftEnabled`, `isHostPolicy`, `jsonLd`, `localeOfProps`, `mergeHeads`, `nifraScriptHashes`, `normalizeCssLoading`, `notFound`, `openGraph`, `pageLocaleIn`, `prerenderedPageReader`, `previewEndpoint`, `redirect`, `registerBlocker`, `renderPage`, `renderPageResult`, `resolveChainMeta`, `resolveDynamicBoundaries`, `resolveMeta`, `resolveNavigate`, `resolvePublicPath`, `resolveStaticBoundaries`, `revalidate`, `revalidateEndpoint`, `sanitizeHtml`, `sanitizedHtml`, `searchOf`, `searchOfChain`, `serializeData`, `serializeSearch`, `servePublicDir`, `setBlockerController`, `setBrowserNavigate`, `setSsrModuleLoader`, `ssrModuleLoader`, `startDynamicBoundaries`, `statusPage`, `trustHtml`, `unsafeInlineScript`, `webProjectEvidence`, `withISR`
|
|
19859
|
+
`ACTION_GLOBAL`, `Action`, `BOUNDARY_GLOBAL`, `BackendOnly`, `Blocker`, `BlockerController`, `BlockerFunction`, `BlockerLocation`, `BlockerState`, `Boundary`, `BoundaryDescriptor`, `BoundaryError`, `BoundaryLoaderEntry`, `BoundaryLoadersOf`, `BoundaryMode`, `BoundaryRegistration`, `BoundaryRequestCtx`, `BoundaryState`, `BoundaryStates`, `BoundaryStatus`, `BrowserNavigate`, `BuildAssetSet`, `CacheStore`, `CachedResponse`, `CdnPurgeOutcome`, `CdnPurgeTarget`, `ClientAction`, `ClientActionArgs`, `ClientActionResult`, `ClientLoader`, `ClientLoaderArgs`, `ClientRequestBody`, `ClientRouteHooks`, `ClientRouter`, `ClientRouterOptions`, `CreateCspPolicyOptions`, `CreateNonceResolverOptions`, `CreateWebAppOptions`, `CspHeaderContext`, `CspPolicy`, `CssLoadingMode`, `DATA_GLOBAL`, `DATA_HEADER`, `DEFAULT_CSS_LOADING`, `DEFAULT_DEV_PORT`, `DRAFT_COOKIE`, `DataText`, `Deferred`, `DehydratedState`, `DocumentParts`, `DraftCookieControls`, `DynamicBoundary`, `DynamicBoundaryBatch`, `EnableDraftOptions`, `FetchRouteData`, `Fetcher`, `FetcherState`, `FontDisplay`, `FontFace`, `FontPreloadInput`, `FontSource`, `GenerateClientEntryOptions`, `GenerateRouteSearchTypesOptions`, `GenerateServerManifestOptions`, `GetStaticPaths`, `HANDOVER_ID`, `HostPolicy`, `HostPolicyOptions`, `HostPolicyRule`, `HtmlSanitizer`, `IDLE_BLOCKER`, `ISRApp`, `ISROptions`, `ISRPlatform`, `ISRQuery`, `ISRStoreOp`, `ISR_REVALIDATE_HEADER`, `ISR_REVALIDATE_TAGS_HEADER`, `ISR_STATUS_HEADER`, `IdentityEpochContext`, `InertScriptType`, `InfiniteData`, `InfiniteQueryHandle`, `InfiniteQueryOptions`, `InterceptBoundary`, `Intercepted`, `KVCacheStore`, `KVCacheStoreOptions`, `KVNamespaceLike`, `KeepAliveOptions`, `KeepAliveServerOptions`, `KeptPage`, `LAYOUT_DATA_GLOBAL`, `LOCALES_GLOBAL`, `LayoutEntry`, `LinkDescriptor`, `LiveClientEntry`, `Loader`, `LoaderContext`, `LoaderResponseControls`, `LoadingEntry`, `Manifest`, `MatchChain`, `MemoryCacheStore`, `MemoryCacheStoreOptions`, `MemoryStaticBoundaryCache`, `Meta`, `MetaArgs`, `MetaDescriptor`, `MetaInput`, `MiddlewareOutcome`, `MountRouterOptions`, `MutationCallbacks`, `MutationHandle`, `MutationState`, `MutationStatus`, `NAV_FROM_HEADER`, `NavigateFunction`, `NavigateOptions`, `NavigateSearchOf`, `NavigateTargetInput`, `NonceContext`, `NonceGenerator`, `NonceHeader`, `NonceHeaderContext`, `NonceResolver`, `NotFoundEntry`, `NotFoundScope`, `OpenGraphInput`, `PREFETCH_HEADER`, `PRE_HYDRATION_GUARD`, `PageLocale`, `PageLocales`, `PendingBoundary`, `PrefetchMode`, `PrerenderedPageReaderOptions`, `PrerenderedPages`, `PreviewEndpointOptions`, `PublicDirCache`, `QueryClient`, `QueryClientOptions`, `QueryHandle`, `QueryOptions`, `QueryState`, `QueryStatus`, `REDIRECT_HEADER`, `RETAIN_HEADER`, `REVALIDATE_HEADER`, `ROOT_ATTRIBUTE`, `ROUTE_GLOBAL`, `RedirectOptions`, `RenderAdapter`, `RenderAdapterConformanceError`, `RenderAdapterConformanceFixture`, `RenderAssemblyCache`, `RenderPageInput`, `RenderPageOptions`, `RenderProps`, `RenderStreamOptions`, `RenderedPage`, `RevalidateEndpointOptions`, `RevalidateOptions`, `RevalidateResult`, `RevalidateTags`, `RevalidateTagsInput`, `RouteEntry`, `RouteMatch`, `RouteMiddleware`, `RouteModule`, `RoutePattern`, `RouteSearch`, `RouterState`, `SERVER_FN_MODULE`, `STATUS_HEADER`, `SanitizedHtml`, `ScriptDescriptor`, `SearchOf`, `ServePublicDirOptions`, `SharedBoundary`, `SharedHoleCtx`, `ShellCtx`, `ShouldRevalidate`, `ShouldRevalidateArgs`, `SsrModuleLoader`, `StaticBoundary`, `StaticBoundaryCache`, `StaticBoundaryImportEdge`, `StaticBoundaryRoot`, `StaticCtx`, `StaticPath`, `StaticPaths`, `StaticRoutes`, `StatusPageOptions`, `Submission`, `SubmitOptions`, `TrustedHtml`, `UIMatch`, `UnsafeScriptDescriptor`, `WebAppI18n`, `assertCssLoadingCompatible`, `assertRenderAdapterConformance`, `assertStaticBoundaryImports`, `boundaryDescriptors`, `boundaryModeKey`, `buildManifest`, `canonical`, `closeBoundary`, `createClientRouter`, `createCspPolicy`, `createHostPolicy`, `createMatcher`, `createMutation`, `createNonceResolver`, `createQueryClient`, `createWebApp`, `defer`, `disableDraft`, `enableDraft`, `enumerateStaticRoutes`, `filePathToPattern`, `filePathToPatterns`, `fontFace`, `fontPreload`, `generateClientEntry`, `generateRouteSearchTypes`, `generateServerManifest`, `getBrowserNavigate`, `gone`, `hashQueryKey`, `isCacheablePage`, `isDraftEnabled`, `isHostPolicy`, `jsonLd`, `localeOfProps`, `mergeHeads`, `nifraScriptHashes`, `normalizeCssLoading`, `notFound`, `openGraph`, `pageLocaleIn`, `prerenderedPageReader`, `previewEndpoint`, `redirect`, `registerBlocker`, `renderPage`, `renderPageResult`, `resolveChainMeta`, `resolveDynamicBoundaries`, `resolveMeta`, `resolveNavigate`, `resolvePublicPath`, `resolveStaticBoundaries`, `revalidate`, `revalidateEndpoint`, `rotateIdentityEpoch`, `sanitizeHtml`, `sanitizedHtml`, `searchOf`, `searchOfChain`, `serializeData`, `serializeSearch`, `servePublicDir`, `setBlockerController`, `setBrowserNavigate`, `setSsrModuleLoader`, `ssrModuleLoader`, `startDynamicBoundaries`, `statusPage`, `trustHtml`, `unsafeInlineScript`, `webProjectEvidence`, `withISR`
|
|
18227
19860
|
|
|
18228
19861
|
## @nifrajs/web-preact
|
|
18229
19862
|
|
|
@@ -18243,7 +19876,7 @@ done-gate, or `nifra mcp` to give the agent live project tools.
|
|
|
18243
19876
|
|
|
18244
19877
|
## @nifrajs/web-vanilla
|
|
18245
19878
|
|
|
18246
|
-
`HtmlValue`, `RawHtml`, `Template`, `VanillaComponent`, `compose`, `html`, `hydrate`, `raw`, `vanillaAdapter`
|
|
19879
|
+
`HtmlValue`, `RawHtml`, `Template`, `VanillaComponent`, `compose`, `html`, `hydrate`, `raw`, `slot`, `vanillaAdapter`
|
|
18247
19880
|
|
|
18248
19881
|
## @nifrajs/web-vue
|
|
18249
19882
|
|