@webjsdev/mcp 0.1.6 → 0.1.8

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (33) hide show
  1. package/README.md +1 -1
  2. package/package.json +1 -1
  3. package/resources/AGENTS.md +169 -77
  4. package/resources/SKILL.md +226 -0
  5. package/resources/references/auth-and-sessions.md +220 -0
  6. package/resources/references/built-ins.md +200 -0
  7. package/resources/references/client-router-and-streaming.md +204 -0
  8. package/resources/references/components.md +167 -0
  9. package/resources/references/data-and-actions.md +187 -0
  10. package/resources/references/muscle-memory-gotchas.md +170 -0
  11. package/resources/references/optimistic-ui.md +128 -0
  12. package/resources/references/routing-and-pages.md +158 -0
  13. package/resources/references/runtime.md +80 -0
  14. package/resources/references/service-worker.md +78 -0
  15. package/resources/references/styling.md +123 -0
  16. package/resources/references/testing.md +125 -0
  17. package/resources/references/typescript.md +148 -0
  18. package/src/mcp-docs.js +27 -14
  19. package/src/mcp-source.js +12 -2
  20. package/src/mcp.js +4 -3
  21. package/resources/agent-docs/advanced.md +0 -1251
  22. package/resources/agent-docs/built-ins.md +0 -379
  23. package/resources/agent-docs/components.md +0 -712
  24. package/resources/agent-docs/configuration.md +0 -284
  25. package/resources/agent-docs/framework-dev.md +0 -65
  26. package/resources/agent-docs/lit-muscle-memory-gotchas.md +0 -470
  27. package/resources/agent-docs/metadata.md +0 -334
  28. package/resources/agent-docs/recipes.md +0 -528
  29. package/resources/agent-docs/runtime.md +0 -65
  30. package/resources/agent-docs/service-worker.md +0 -100
  31. package/resources/agent-docs/styling.md +0 -279
  32. package/resources/agent-docs/testing.md +0 -438
  33. package/resources/agent-docs/typescript.md +0 -402
@@ -1,1251 +0,0 @@
1
- # Advanced features
2
-
3
- ## Streaming SSR / Suspense
4
-
5
- ```js
6
- import { html, Suspense } from '@webjsdev/core';
7
-
8
- export default function Page() {
9
- return html`
10
- <h1>Catalogue</h1>
11
- ${Suspense({ fallback: html`<p>Loading…</p>`, children: fetchExpensive() })}
12
- `;
13
- }
14
- ```
15
-
16
- TTFB = time to render everything *outside* the Suspense boundary. The
17
- fallback flushes immediately, and the resolved content streams in as a
18
- `<template>` + inline `__webjsResolve('id')` script when the promise
19
- lands. Nested Suspense supported.
20
-
21
- ### Component-level streaming: `<webjs-suspense>` (#471)
22
-
23
- `Suspense({ fallback, children })` above is the page/region-level primitive (a promise passed as `children`). With **async render** (`agent-docs/components.md`), a COMPONENT is the suspending unit: a component doing `async render() { const u = await getUser(this.uid); … }` BLOCKS the first byte by default (real data in the first paint). To STREAM a slow component, wrap it in the renderer-recognized `<webjs-suspense>` element:
24
-
25
- ```js
26
- html`
27
- <webjs-suspense .fallback=${html`<p>Loading section…</p>`}>
28
- <user-profile uid="42"></user-profile>
29
- <user-activity uid="42"></user-activity>
30
- </webjs-suspense>
31
- `;
32
- ```
33
-
34
- `.fallback` is read at SSR as the inline placeholder (`render-server.js`'s `processSuspenseElements` carries it via `data-webjs-fallback`, since a `TemplateResult` is not serializer-safe) and flushed on the first byte; the children push to `ctx.pending` and stream in via the same `<template data-webjs-resolve>` engine. Multiple boundaries resolve via `Promise.all`, so they fetch concurrently (no server waterfall). One boundary groups several components under one fallback (the boundary `.fallback` wins over a contained component's `renderFallback()`), and a throwing component inside is isolated to its own error state while siblings stream. Without a streaming context (`renderToString`) the children render inline (blocking).
35
-
36
- ### Progressive soft-nav streaming (#473)
37
-
38
- On a client-router navigation to a streamed page, the router applies the response PROGRESSIVELY: the SSR stream flushes the shell (with fallbacks) plus a `<!--wj-stream-shell-->` sentinel, the router's `readStreamedShell` swaps the shell in immediately and advances the URL, then `streamBoundariesProgressively` applies each resolved boundary into the live DOM as it streams (fast-before-slow), upgrading the custom elements inside. So a soft nav matches the initial-load experience instead of buffering the whole response. A non-streaming page is read to completion and applied once; a navigation superseded mid-stream stops and cancels the reader; a mid-stream transport failure leaves the applied boundaries in place (non-destructive).
39
-
40
- ## First-paint performance without a build step
41
-
42
- Five stacked zero-build optimizations:
43
-
44
- 1. **`<link rel="modulepreload">` per used component + transitive deps.**
45
- The SSR pass knows every custom element in the final HTML. A startup
46
- module-graph scan adds their transitive import dependencies too. All
47
- preload hints are deduplicated and emitted in `<head>`.
48
- 2. **HTTP/2 multiplex at the edge.** The production server (`npm run start`) speaks plain
49
- HTTP/1.1. PaaS edges (Railway, Fly, Render, Vercel, Cloudflare Pages,
50
- Heroku) and reverse proxies (nginx, Caddy, Traefik) speak
51
- HTTP/2 to the browser and proxy 1.1 to the container, fetching many module
52
- fetches in parallel over one TCP+TLS connection.
53
- 3. **103 Early Hints.** Before SSR starts computing the response, the
54
- server sends `103 Interim Response` with the page's module URLs as
55
- `rel=modulepreload`. Chrome/Edge and edge proxies (Cloudflare, fly-proxy,
56
- Fastly) forward these.
57
- 4. **Lazy component loading (opt-in).** Components with `static lazy = true`
58
- are excluded from modulepreload and loaded on-demand via
59
- `IntersectionObserver` (200px root margin). The SSR-rendered DSD content
60
- is visible immediately. `static hydrate = 'visible'` further defers
61
- `connectedCallback` activation. Ideal for below-the-fold widgets.
62
- 5. **Auto-vendor via jspm.io (Rails 7 + importmap-rails posture).** At
63
- startup the server scans client-reachable source for bare npm import
64
- specifiers. The WHOLE scanned set is resolved in ONE
65
- `api.jspm.io/generate` call (a single `install[]` array) so jspm
66
- computes one mutually-consistent dependency graph: a directly-imported
67
- package and a transitive that needs a newer version of the same package
68
- agree on one CDN URL, instead of skewing (a direct dep pinned to its
69
- local version while a transitive floats to jspm-latest, which crashed
70
- the browser with a missing export). Each resolved entry is a CDN URL
71
- (`https://ga.jspm.io/npm:<pkg>@<version>/...`) added to the import map;
72
- the browser fetches each package directly from the CDN. If the unified
73
- call fails because some install is unresolvable (a 401 for a private or
74
- server-only dep), the resolver falls back to per-package isolation for
75
- the offending install(s) and re-resolves the resolvable survivors as one
76
- graph, so one bad dep can never collapse the whole map.
77
- **SRI integrity (SHA-384) is computed on BOTH paths.** A
78
- live-resolved (unpinned) app hashes each cross-origin bundle at warmup
79
- and emits `integrity` + `crossorigin` on the importmap and modulepreload
80
- tags, so a swapped or compromised CDN response is rejected by the browser
81
- even with no pin file (#235). The hashing is bounded (parallel fetches
82
- with a small concurrency cap and a per-fetch timeout) and FAIL-OPEN: a
83
- bundle fetch failure skips that one URL's integrity (it loads without SRI,
84
- the same as before) and emits a one-time warning, so a CDN hiccup never
85
- takes the app down. Added warmup cost is one HEAD-like GET per distinct
86
- cross-origin bundle, cached per process by URL so a re-resolve does not
87
- re-fetch. `webjs vendor pin` still commits the resolved URLs + integrity
88
- hashes to `.webjs/vendor/importmap.json` for reproducible deploys (and a
89
- stable boot-time build id with no warmup fetch); `webjs vendor pin
90
- --download` also caches the bundle bytes locally under
91
- `.webjs/vendor/<pkg>@<version>.js` for air-gapped / strict-CSP
92
- deployments. No bundler runs at any point. **`webjs doctor` validates
93
- importmap coherence** (#450): for each resolved package it checks that the
94
- version pinned for every OTHER resolved package it depends on satisfies the
95
- declared dependency / peer range, and WARNS naming both packages, the range,
96
- and the pinned version when they skew (the class of bug where a pinned
97
- package needs a newer minor of another pinned package than is pinned, so a
98
- symbol it expects is missing at runtime). It is a validation over the
99
- produced importmap, not a re-resolution and not bundling, and it runs the
100
- SAME check with the SAME verdict over the live importmap and the vendored
101
- `.webjs/vendor/importmap.json` (vendoring freezes the runtime-resolved
102
- graph, so a coherent live graph stays coherent vendored). It reads
103
- dependency metadata from the installed `node_modules` (no network of its
104
- own) and degrades to "could not verify" when a manifest is unavailable.
105
-
106
- ## No-build production model
107
-
108
- webjs has no bundler and no `webjs build` step. The same `.js` / `.ts`
109
- source files that run in dev are served as-is to the browser in
110
- production. The Rails 7+ / Hotwire pattern:
111
-
112
- - **Importmap-driven**: bare-specifier imports (`from "react"`) are
113
- resolved via `<script type="importmap">` emitted into the document
114
- head. By default the whole scanned set resolves through one
115
- `api.jspm.io/generate` call (one consistent graph, see point 5 above)
116
- to `https://ga.jspm.io/npm:<pkg>@<version>/...` URLs and the browser
117
- fetches them from the CDN directly, with an `integrity` SRI hash on every
118
- cross-origin entry (computed live at warmup for an unpinned app, or read
119
- from the pin file for a pinned one). `webjs vendor pin` commits the
120
- resolved URLs + SHA-384 integrity hashes to `.webjs/vendor/importmap.json`
121
- for reproducible deploys; `webjs vendor pin --download` additionally
122
- caches each bundle to `.webjs/vendor/<pkg>@<version>.js` and rewrites
123
- the importmap to `/__webjs/vendor/<pkg>@<version>.js` so the server
124
- serves the bytes from disk (air-gapped / strict-CSP path). No bundler
125
- runs at any point. Because the pins are meant to be committed,
126
- `webjs vendor pin` makes its output committable: the scaffold already
127
- un-ignores `.webjs/vendor/`, and if a `.gitignore` would swallow the
128
- pins it heals it (or prints how to commit them when the ignore is not
129
- in the app's own `.gitignore`). A no-vendor app, which never pins, is
130
- unaffected.
131
- - **Per-file ESM serving**: every app `.js` / `.ts` becomes its own HTTP
132
- resource. The browser walks the import graph and fetches each module
133
- on demand.
134
- - **`<link rel="modulepreload">` hints at SSR time**: for every component
135
- the route uses + its transitive deps from the module graph. The
136
- browser parallelizes fetches instead of waterfalling through nested
137
- imports. This is what eliminates the perceived gap vs a bundle.
138
- - **HTTP/2 multiplex** is what makes per-file serving competitive: one
139
- TCP+TLS handshake, many module fetches in parallel over the same
140
- connection. The production server (`npm run start`) speaks plain HTTP/1.1.
141
- TLS + HTTP/2 is the proxy's job. PaaS edges (Railway, Fly, Render, Vercel,
142
- Cloudflare Pages, Heroku) do this automatically. For bare-VM
143
- deploys, put nginx, Caddy, or Traefik in front.
144
-
145
- Content-hashed cache-busting and granular cache invalidation come from
146
- the same per-file model: edit one file, only that file's URL hash
147
- changes, only that one re-downloads.
148
-
149
- ## Content-hash asset caching: `?v=<digest>` immutable URLs (prod) (#243)
150
-
151
- In PRODUCTION the framework appends a per-file content hash to every
152
- SAME-ORIGIN asset URL it emits (the importmap targets, the
153
- `<link rel="modulepreload">` hrefs, the boot script's module specifiers).
154
- The hash is a short prefix of a sha-256 over the file's BYTES, computed at
155
- serve time (no build step) and memoized. A request whose URL carries that
156
- `?v=<digest>` query is served `Cache-Control: public, max-age=31536000,
157
- immutable` instead of the 1-hour fallback, so a browser / CDN holds it for
158
- a year without revalidating.
159
-
160
- This is safe precisely because the hash IS the version: a deploy that
161
- changes a module's bytes changes its hash, so its emitted URL changes, so a
162
- returning client fetches the NEW URL rather than serving a stale immutable
163
- copy. The framework's own `@webjsdev/core` runtime (`/__webjs/core/*`) is
164
- fingerprinted too, which fixes the exact regression an un-versioned
165
- `immutable` would otherwise cause (a year-pinned old core renderer running
166
- against a server emitting the new SSR shape after a version bump).
167
-
168
- - **Per-file digest, not the build id.** The importmap build id
169
- (`data-webjs-build`) does not change on an app-module byte change, so it
170
- cannot be the per-asset fingerprint; each file carries its own hash.
171
- - **Cross-origin URLs are NEVER fingerprinted.** A `https://ga.jspm.io/...`
172
- vendor target keeps its exact URL: jspm already versions it, and #235's
173
- SRI integrity is keyed by the un-hashed cross-origin URL. A downloaded
174
- `/__webjs/vendor/<pkg>@<ver>.js` bundle is already version-named, so it is
175
- left unchanged too.
176
- - **Composes with `webjs.basePath` (#256).** A sub-path deploy emits
177
- `<basePath>/app/foo.js?v=<digest>`: the base path is prefixed first, the
178
- `?v` query appended after, and the ingress base-path strip never touches a
179
- query.
180
- - **DEV is byte-identical to before.** Fingerprinting is enabled only in
181
- `webjs start` (prod). `webjs dev` emits no `?v` and serves every module
182
- `no-cache`, so the dev wire is unchanged.
183
- - **Un-fingerprinted requests keep the 1-hour fallback.** Only the presence
184
- of a `?v` query flips the cache header; a hand-typed bare URL still
185
- resolves and serves `public, max-age=3600`.
186
-
187
- ## Connection-warming hints: `preconnect` / `dnsPrefetch` + auto vendor preconnect (#243)
188
-
189
- A page can warm a cross-origin connection it is about to use (an API host,
190
- a font / image CDN) by declaring it in `metadata`:
191
-
192
- ```ts
193
- export const metadata = {
194
- preconnect: ['https://api.example.com', { url: 'https://fonts.gstatic.com', crossorigin: true }],
195
- dnsPrefetch: 'https://analytics.example.com',
196
- };
197
- ```
198
-
199
- Each emits a head hint: `<link rel="preconnect" href="..." [crossorigin]>`
200
- (warms DNS + TLS + TCP) and `<link rel="dns-prefetch" href="...">` (DNS
201
- only). Each field takes a URL string, `{ url, crossorigin? }`, or an array;
202
- hrefs are HTML-escaped. See `agent-docs/metadata.md`.
203
-
204
- **Auto vendor preconnect.** For an UNPINNED app resolving vendors live from
205
- a cross-origin CDN, the framework auto-emits ONE
206
- `<link rel="preconnect" href="<cdn-origin>" crossorigin>` (the resolved
207
- vendor CDN origin, e.g. `https://ga.jspm.io`, derived from the importmap, so
208
- a `--from jsdelivr` app preconnects to jsdelivr) so the browser warms that
209
- connection before the importmap resolves. It is DEDUPED against an
210
- author-declared preconnect to the same origin, and emits NOTHING for a
211
- same-origin pinned app (vendors served from the app's own origin) or an app
212
- with no cross-origin vendors.
213
-
214
-
215
- ## Rate limiting via `rateLimit()`
216
-
217
- Fixed-window limiter shaped as middleware. Place in `middleware.ts` at
218
- whatever level you want to protect:
219
-
220
- ```js
221
- // app/api/auth/middleware.ts: protect login/signup from brute force
222
- import { rateLimit } from '@webjsdev/server';
223
- export default rateLimit({ window: '10s', max: 5 });
224
-
225
- // Custom key: rate limit per authenticated user instead of IP
226
- export default rateLimit({
227
- window: '1m', max: 30,
228
- key: async (req) => {
229
- const session = await auth(req);
230
- return session?.user?.id ?? 'anon';
231
- },
232
- });
233
- ```
234
-
235
- **Options:** `window` (`'10s'`, `'1m'`, `'1h'`, ms), `max` (default 60),
236
- `key` (string prefix or `(req) => string`, defaulting to the
237
- framework-stamped client IP from the TCP socket), `message`, `store`,
238
- `trustProxy` (default `false`).
239
-
240
- **`trustProxy`** controls how the default key is derived:
241
-
242
- - **`false` (default, safe):** key on the framework-stamped
243
- `x-webjs-remote-ip` header, which `startServer` sets from the
244
- underlying TCP socket on every request (and strips any inbound
245
- copy of, so clients cannot spoof it). Forwarded-IP headers like
246
- `x-forwarded-for`, `cf-connecting-ip`, `x-real-ip` are ignored.
247
- Correct for direct deployments (bare Node, no proxy in front).
248
- - **`true`:** honour forwarded-IP headers, preferring the leftmost
249
- entry of `x-forwarded-for`, then `cf-connecting-ip`, then
250
- `x-real-ip`. Production deploys MUST run behind a reverse proxy
251
- (nginx, Caddy, Cloudflare, Fly, Railway, Render edge) that STRIPS
252
- inbound `x-forwarded-for` before adding its own. If the proxy
253
- doesn't strip, the option reintroduces the per-request bucket
254
- rotation it exists to defend against.
255
-
256
- ```js
257
- // Direct deploy (default): safe, ignores spoofable forwarded headers.
258
- export default rateLimit({ window: '10s', max: 5 });
259
-
260
- // Behind a trusted reverse proxy: opt in, MUST strip inbound XFF.
261
- export default rateLimit({ window: '10s', max: 5, trustProxy: true });
262
- ```
263
-
264
- The `clientIp(req, { trustProxy })` helper is exported separately so
265
- custom `key` functions can reuse the same resolution:
266
-
267
- ```js
268
- import { rateLimit, clientIp } from '@webjsdev/server';
269
- export default rateLimit({
270
- window: '1m', max: 30,
271
- key: (req) => `${req.headers.get('x-tenant') || 'global'}:${clientIp(req, { trustProxy: true })}`,
272
- });
273
- ```
274
-
275
- **Embedded use** (`createRequestHandler` running under Express / Bun /
276
- Deno / edge adapters): the host adapter is responsible for stripping
277
- any inbound `x-webjs-remote-ip` from the wire AND stamping its own
278
- from the trusted socket address, otherwise a malicious client forges
279
- the header and the framework trusts it. Call the exported helper:
280
-
281
- ```js
282
- import { createRequestHandler, stampRemoteIp } from '@webjsdev/server';
283
- const handler = await createRequestHandler({ appDir });
284
-
285
- // Inside the host adapter's per-request callback. `nodeReq` is the
286
- // host's request object (Express req, Node IncomingMessage, etc.).
287
- // `webReq` is whatever Request you constructed from the wire (URL,
288
- // method, headers, body); building that is host-specific. The
289
- // security-relevant line is the one that wraps it in stampRemoteIp:
290
- const safe = stampRemoteIp(webReq, nodeReq.socket.remoteAddress);
291
- const webRes = await handler.handle(safe);
292
- // Pipe webRes back through the host's response API.
293
- ```
294
-
295
- The host-specific Request construction has its own gotchas (Node `Readable` to WHATWG `ReadableStream` for bodies; coalescing array-valued raw headers into comma-joined strings; URL synthesis from host + path). The `stampRemoteIp` line is what makes the result safe to hand off to webjs's rate limit; it MUST come after the inbound headers land in `webReq` and before `handler.handle(safe)` is called.
296
-
297
- If the adapter cannot expose a trusted socket address, pass a custom
298
- `key` function to `rateLimit()` that reads whatever client identifier
299
- the host actually provides. The default rate-limit collapsing to
300
- `_anon_` is preferable to silently trusting wire-set headers.
301
-
302
- **Exceeded:** returns `429 Too Many Requests` with JSON `{ error: "Too Many Requests" }` and headers `x-ratelimit-limit`, `x-ratelimit-remaining`, `x-ratelimit-reset`, `retry-after`.
303
-
304
- **Scaling:** in-memory by default. `setStore(redisStore({ url: process.env.REDIS_URL }))` shares limits across instances.
305
-
306
- ## Sub-path deployment: `webjs.basePath` (#256)
307
-
308
- An app served under a sub-path (`example.com/app/`) behind a proxy that does NOT strip the prefix needs every framework-emitted absolute URL to carry that prefix, or module resolution 404s and the page never hydrates. Set the prefix in `package.json`:
309
-
310
- ```jsonc
311
- { "webjs": { "basePath": "/app" } }
312
- ```
313
-
314
- `'app'`, `'/app'`, and `'/app/'` all normalize to `'/app'`; a nested `'/foo/bar'` is allowed; the empty default (or absence) is a root mount and a pure no-op (an unconfigured app is byte-identical to before this feature). An unsafe value (a `..`, a protocol, a `//host` network-path reference, whitespace, a backslash) is rejected to the empty default so a typo fails safe.
315
-
316
- **The model is strip-at-ingress + prefix-on-emit, two seams only.** At the very start of request handling, when the request path is under the base path, the framework STRIPS the prefix and rewrites the request, so all downstream logic (route matching, the `/__webjs/*` checks, the source-file gate, redirects, trailing-slash, the `webjs.headers` path config, the HTML cache key) sees a root-relative path and works unchanged. A request whose path is NOT under the base path is not for this mounted app, so it 404s. On the way out, every framework-emitted same-origin absolute URL gets the prefix prepended: the importmap targets (the `/__webjs/core/*` runtime entries and any same-origin `/__webjs/vendor/*` local target; a cross-origin `https://` CDN vendor URL is left untouched), the `<link rel="modulepreload">` hrefs, the boot script's per-route module specifiers and lazy-loader entries, the dev reload `src`, and the 103 Early Hints preloads. So a sub-path deploy serves `<basePath>/__webjs/core/*` and resolves every module under the prefix.
317
-
318
- The whole config surface (`webjs.redirects` / `webjs.trailingSlash` / `webjs.headers` `source` patterns) is authored app-root-relative, exactly as without a base path, because the ingress strip runs first.
319
-
320
- **OUT OF SCOPE (a documented follow-up).** Author-written `<a href="/about">` links and client-router navigation are NOT auto-prefixed under a base path. This is the same boundary Next draws between basePath auto-prefixing its `<Link>` component and a raw `<a href>`: webjs links are plain `<a href>`, so an author targeting a sub-path deploy writes the prefix into their own hrefs (or a future helper does) until client-side prefixing lands. The acceptance for #256 covers the server-emitted-URL + matching surface only.
321
-
322
- ## CORS via `cors()`
323
-
324
- `cors()` is a middleware factory (same `(req, next) => Response` contract as `rateLimit()`), usable in `middleware.js` (root or per-segment) or wrapped around a `route.js` handler. It handles origin reflection, the `OPTIONS` preflight, `Vary: Origin`, and the credentials rule, so route handlers do not hand-roll any of it. The `--template api` scaffold ships a root `middleware.ts` demonstrating it.
325
-
326
- ```js
327
- // middleware.js (applies to every request)
328
- import { cors } from '@webjsdev/server';
329
- export default cors({
330
- origin: ['https://app.example.com', 'http://localhost:3000'],
331
- credentials: true,
332
- methods: ['GET', 'POST', 'PUT', 'PATCH', 'DELETE'],
333
- allowedHeaders: ['content-type', 'authorization'],
334
- maxAge: 86400,
335
- });
336
- ```
337
-
338
- Wrap a single handler instead of going app-wide:
339
-
340
- ```js
341
- // app/api/widgets/route.js
342
- import { cors } from '@webjsdev/server';
343
- const corsMw = cors({ origin: '*' });
344
- export async function GET(req) {
345
- return corsMw(req, async () => Response.json({ widgets: [] }));
346
- }
347
- ```
348
-
349
- ### Options
350
-
351
- | Option | Meaning |
352
- |---|---|
353
- | `origin` | A string (exact), `string[]` allow-list, a `RegExp`, a function `(origin) => boolean`, or `'*'` / `true` (any). Entries in an array may mix strings and RegExps. Defaults to `'*'`. |
354
- | `credentials` | Sets `Access-Control-Allow-Credentials: true` for an allowed specific origin. |
355
- | `methods` | Advertised on a preflight (`Access-Control-Allow-Methods`). |
356
- | `allowedHeaders` | Advertised on a preflight; defaults to reflecting `Access-Control-Request-Headers`. |
357
- | `exposedHeaders` | `Access-Control-Expose-Headers` on the actual response. |
358
- | `maxAge` | Preflight cache lifetime in seconds. |
359
-
360
- ### Behavior
361
-
362
- - **Preflight.** An `OPTIONS` request carrying `Access-Control-Request-Method` short-circuits with a `204` carrying the Allow-Methods / Allow-Headers / Max-Age headers. `next()` is NOT called. A disallowed-origin preflight returns a bare `204` with no CORS headers, so the browser blocks the follow-up.
363
- - **Actual request.** `next()` runs, then `Access-Control-Allow-Origin` (plus credentials / exposed headers) is attached. A disallowed origin gets NO `Access-Control-Allow-Origin`, and the browser blocks the cross-origin read, but the server still serves the response (CORS is browser-enforced, not a server gate, so a mismatched actual request is never 403'd server-side).
364
- - **`Vary: Origin`.** Appended (never clobbering an existing `Vary`) whenever the allowed origin is dynamic (a reflected, per-origin value), so a shared cache keys on `Origin` and cannot poison one origin's response onto another. A constant `*` (no credentials) does not vary, so no `Vary` is added.
365
-
366
- ### `credentials: true` requires an explicit origin allowlist (spec, enforced, warned)
367
-
368
- **For any credentialed endpoint, pass an explicit `origin` allowlist (string / array / RegExp / function). Never combine `credentials: true` with a wildcard `origin` (`'*'` / `true`).**
369
-
370
- `Access-Control-Allow-Origin: *` is INVALID together with `Access-Control-Allow-Credentials: true`, and the browser rejects the pair. Worse, the usual workaround (reflecting the request origin) under credentials effectively grants credentialed access (cookies, `Authorization`) to EVERY origin, a real footgun.
371
-
372
- `cors()` keeps the request working rather than failing it: when `credentials: true` meets a wildcard `origin` it NARROWS to the reflected request origin instead of sending `*` (and appends `Vary: Origin`). With no `Origin` header under that combination it refuses entirely (no ACAO). Because that reflects any origin with credentials, it ALSO emits a one-time `console.warn` (deduped, not per-request):
373
-
374
- ```
375
- cors(): credentials with a wildcard origin reflects ANY origin with credentials.
376
- Use an explicit origin allowlist for credentialed requests.
377
- ```
378
-
379
- The warning is informational; the request still proceeds. Treat it as a prompt to replace the wildcard with a real allowlist. An explicit allowlist with `credentials: true` is the safe, silent path.
380
-
381
- ## Client router: nested-layout-aware partial swap
382
-
383
- The client router auto-enables when `@webjsdev/core` loads in the browser (any page that ships a component), no import needed (#620). It gives SPA-style navigation that
384
- preserves outer-layout DOM identity at any depth. Intercepts same-origin
385
- `<a>` clicks (incl. inside shadow DOM via `composedPath()`), fetches the
386
- target HTML, and replaces only the inside of the deepest shared layout.
387
- Outer header / sidenav / footer DOM nodes are never re-rendered, so
388
- scroll positions, input values, and `<details>` open state survive
389
- navigation automatically.
390
-
391
- ### How it works
392
-
393
- 1. SSR injects `<!--wj:children:<segment-path>-->...<!--/wj:children-->`
394
- comment markers around each layout's `${children}` interpolation,
395
- one pair per layout in the chain. Auto-derived from folder
396
- structure. Layout authors write nothing extra.
397
- 2. On click, the router walks both the live DOM and the incoming HTML
398
- for these markers and builds `Map<path, {start, end}>`.
399
- 3. Picks the **longest shared path**, the deepest layout boundary
400
- both pages have in common.
401
- 4. Replaces nodes between that marker pair using a keyed `data-key`
402
- reconciler. Elements with matching tag + matching key are reused
403
- with in-place attribute diffing. **Live attributes** (`value`,
404
- `checked`, `selected`, `indeterminate`, `disabled`, `open`,
405
- `popover`) are NEVER overwritten by the server HTML.
406
- 5. Merges `<head>` (add-only on partial swaps so runtime-injected
407
- styles like Tailwind survive, with a full merge on the
408
- root-layout-change fallback), re-runs `<script>` elements,
409
- `customElements.upgrade()`s the swapped subtree, `pushState`s the
410
- URL, scrolls.
411
- 6. Dispatches `webjs:navigate` event on `document`.
412
-
413
- ### In-place navigation-error recovery (`webjs:navigation-error`)
414
-
415
- A successful swap (2xx/3xx) applies in place, and an HTML error body of any
416
- status (a 4xx/5xx page, e.g. a `422` re-rendered form) is ALSO applied in
417
- place. The remaining failure cases are a **non-HTML error response** (a
418
- `500` carrying a JSON body) and a **transport/parse failure** (the `fetch`
419
- rejected, or the body claimed HTML but did not parse). For those the router
420
- no longer abandons the SPA with a destructive full `location.href` reload
421
- (which would discard the partial-swap shell, scroll, focus, and in-flight
422
- client state, and eat a second round-trip that may itself fail to the
423
- browser's default error page).
424
-
425
- Instead the router dispatches a cancelable, bubbling
426
- `webjs:navigation-error` CustomEvent on `document`, with detail
427
- `{ url, status, error }`: `status` is the HTTP status when a response
428
- arrived (else `null`), and `error` is the `Error` for a transport/parse
429
- failure (else `null`).
430
-
431
- - **`preventDefault()` hands recovery to the app.** The router does NOTHING
432
- further: the current page is left exactly as it is (shell, scroll, focus,
433
- and client state all preserved), so the app can show its own toast, retry,
434
- or navigate elsewhere.
435
- - **Not cancelled (the default)** renders a MINIMAL in-place error surface,
436
- a `<div role="alert" data-webjs-nav-error>` carrying a generic message
437
- plus the status, into the deepest layout children slot (the same target a
438
- normal partial swap writes to, so outer chrome and nav are preserved). No
439
- full reload, the shell survives, and the user sees the failure.
440
- - **Last-resort hard load** happens only when there is NO shared layout
441
- marker to render into (a genuine cross-document nav), and only after the
442
- event was not cancelled, so a truly unrecoverable case is not a silent
443
- dead-end. This is the exception, not the default.
444
-
445
- An **AbortError** (a newer navigation superseding this one) is a normal
446
- supersede, NOT an error, and never dispatches `webjs:navigation-error`.
447
-
448
- ```ts
449
- document.addEventListener('webjs:navigation-error', (e) => {
450
- // e.detail = { url, status, error }
451
- e.preventDefault(); // app handles recovery; page left intact
452
- showToast(`Could not load ${e.detail.url} (status ${e.detail.status})`);
453
- });
454
- ```
455
-
456
- ### Form submission state (`webjs:submit-start` / `webjs:submit-end` + `aria-busy`)
457
-
458
- When a `<form>` submits through the JS-enhanced router, the form gets a
459
- submission lifecycle a component can read to disable the submit button, show a
460
- spinner, or set a pending style:
461
-
462
- - The router sets the native `aria-busy="true"` on the form for the in-flight
463
- duration (cleared on settle). This IS the readable "is this form submitting"
464
- primitive: any component can poll `form.getAttribute('aria-busy')` or style
465
- `form[aria-busy="true"]` in CSS.
466
- - It dispatches a bubbling `webjs:submit-start` (detail `{ form, url }`) when the
467
- submission fetch starts, and `webjs:submit-end` (detail `{ form, url, ok }`,
468
- `ok` is whether the submission settled as a success) on EVERY settle (success,
469
- a 4xx/5xx validation re-render, a navigation error, or an abort by a
470
- superseding submit). The pair is balanced even under a rapid re-submit (a
471
- nav-token guard keeps a superseded submit's teardown from clearing the busy
472
- state a newer submit set, the same guard `<webjs-frame>` uses).
473
-
474
- ```ts
475
- // A submit button that disables itself while its form is submitting.
476
- form.addEventListener('webjs:submit-start', () => { button.disabled = true; });
477
- form.addEventListener('webjs:submit-end', (e) => {
478
- button.disabled = false; // e.detail = { form, url, ok }
479
- });
480
- /* or purely in CSS, no JS: */
481
- /* form[aria-busy="true"] button[type="submit"] { opacity: .5; pointer-events: none; } */
482
- ```
483
-
484
- Progressive enhancement is unaffected: with JS off the form is a normal POST;
485
- the events + `aria-busy` are a client-only enhancement.
486
-
487
- ### Optimistic mutations (`optimistic()`)
488
-
489
- `optimistic(signal, value, action)` from `@webjsdev/core` shows a mutation's
490
- expected result IMMEDIATELY (the UI feels instant), runs the real server action,
491
- and ROLLS BACK on failure. It is a thin wrapper over the signal primitive, no
492
- state machine.
493
-
494
- ```ts
495
- import { signal, optimistic } from '@webjsdev/core';
496
- import { likePost } from '../actions/like-post.server.js';
497
-
498
- const liked = signal(false);
499
- // in an @click handler:
500
- const result = await optimistic(liked, true, () => likePost(postId));
501
- // `liked` flips to true instantly. If likePost THROWS or returns
502
- // { success: false }, `liked` rolls back to its prior value; the throw
503
- // re-throws and the { success: false } result is returned (read its
504
- // error / fieldErrors). On success the optimistic value stays; reconcile
505
- // to the authoritative value from `result` if you need it.
506
- ```
507
-
508
- It rolls back on a thrown error OR an `ActionResult` `{ success: false }`
509
- envelope, and never on success. Client-only (it mutates a signal), so a
510
- component importing it is never elided as display-only.
511
-
512
- ### Wire-byte optimization
513
-
514
- The router sends `X-Webjs-Have: <paths>` listing the marker paths it
515
- already has rendered. The server walks the target route's layout chain
516
- innermost → outermost and **short-circuits at the first match**. The
517
- inner tree is wrapped in that layout's marker pair and returned. Outer
518
- layouts are not loaded, not rendered, not re-serialized. Real savings
519
- on every same-shell navigation.
520
-
521
- ### Cross-deploy hard-reload signals
522
-
523
- Two complementary mechanisms tell the client when a partial swap is
524
- unsafe and a hard reload is required:
525
-
526
- 1. **Importmap drift** (the common case after a vendor pin change).
527
- Server stamps the PUBLISHED build id on `<script type="importmap"
528
- data-webjs-build="…">` AND emits the same value as `X-Webjs-Build`
529
- on every response, including X-Webjs-Have partial responses with no
530
- head. The published id is the importmap hash, but advertised only
531
- once the importmap is authoritatively final (at boot for a pinned
532
- app, after the first successful vendor resolve otherwise); while the
533
- map is still warming it stays empty. Client compares the response
534
- header against the live document's `data-webjs-build`. A hard reload
535
- (`location.href = target`) fires only when both ids are present and
536
- differ (a real cross-deploy). An empty id on either side means
537
- "version unknown" (a warming runtime-first-boot server) and never
538
- reloads, so the warmup window cannot hard-reload and wipe a
539
- half-filled form. Works for every nav, including partial-response navs.
540
-
541
- 2. **Generic `data-webjs-track="reload"`** (for non-importmap concerns,
542
- e.g. a CSS bundle hash, a build-id meta tag). Any head element with
543
- the attribute joins a signature computed from concatenated outerHTML.
544
- On nav, mismatched signatures trigger reload. Mirrors hotwired/turbo's
545
- `data-turbo-track="reload"`.
546
-
547
- ```html
548
- <link rel="stylesheet" href="/build/main-abc123.css" data-webjs-track="reload">
549
- <meta name="build-id" content="rev-42" data-webjs-track="reload">
550
- ```
551
-
552
- Both paths share a one-shot `sessionStorage` reload guard so a
553
- genuinely-churning resource doesn't loop reloads.
554
-
555
- ### Snapshot cache + revalidation
556
-
557
- URL-keyed `Map<url, snapshot>` (LRU, cap 16). Back/forward via
558
- popstate restores from cache instantly, then refetches in the
559
- background.
560
-
561
- ```js
562
- import { revalidate } from '@webjsdev/core';
563
- revalidate('/products/123'); // evict one URL
564
- revalidate(); // clear the entire cache
565
- ```
566
-
567
- Call `revalidate(path)` after a server action mutates data that
568
- affects a cached page.
569
-
570
- ### Link prefetch
571
-
572
- Same-origin in-app links are prefetched speculatively so a click
573
- resolves from a warm cache with no round-trip. On by default (no per-link
574
- opt-in needed), the way Next / Nuxt / SvelteKit ship auto-prefetch. The
575
- prefetch request carries the same `X-Webjs-Have` header a real navigation
576
- sends, so the server returns the same divergent fragment; that fragment
577
- lands in a dedicated prefetch cache (separate from the back/forward
578
- snapshot cache) and `fetchAndApply` consumes it via `prefetchTake` before
579
- falling back to the network.
580
-
581
- The default strategy is DEVICE-ADAPTIVE, because one strategy cannot serve
582
- both input modalities. On a hover-capable fine pointer (mouse / trackpad)
583
- the default is `intent` (warm on hover / focus, a real head-start before
584
- the click). On touch the default is `viewport` (warm as links settle
585
- on-screen), because a touch device has no hover and `touchstart` fires at
586
- tap time, too late to front-run the navigation. The modality is detected
587
- with `matchMedia('(hover: hover) and (pointer: fine)')`, not a user-agent
588
- sniff. A per-link `data-prefetch` always overrides the adaptive default.
589
-
590
- Per link, set `data-prefetch` (a valid-HTML `data-*` attribute, the shape
591
- SvelteKit and Astro use; Next / Nuxt / Remix use a component prop, which
592
- webjs has no equivalent for since links are plain `<a href>`):
593
-
594
- ```html
595
- <a href="/dashboard">adaptive: intent on pointer, viewport on touch (default)</a>
596
- <a href="/dashboard" data-prefetch="intent">hover / focus / touch</a>
597
- <a href="/dashboard" data-prefetch="render">eager on insert</a>
598
- <a href="/dashboard" data-prefetch="viewport">on scroll-into-view</a>
599
- <a href="/dashboard" data-prefetch="none">never</a>
600
- ```
601
-
602
- Next-style aliases are accepted: `true` = `render`, `auto` = `viewport`,
603
- `false` = `none`. `intent` waits a short dwell (~100ms) after hover/focus
604
- so a pointer passing over a link does not fetch it. `viewport` uses an
605
- IntersectionObserver at threshold 0.5 and waits a ~250ms dwell, cancelled
606
- the instant the link scrolls back out, so a fast scroll through a long
607
- list spends no requests (the same gate Astro / Next / Nuxt / Remix /
608
- TanStack / Turbo apply). On touch, `touchstart` additionally warms the
609
- tapped link itself (a single request for a link about to be navigated).
610
- `render` and `viewport` are applied by a document scan on enable and after
611
- each navigation.
612
-
613
- Only internal links qualify, using the same eligibility as a click:
614
- cross-origin, `download`, `target` other than `_self`, non-HTML
615
- extensions, `data-no-router`, and pure same-page hash jumps are skipped.
616
- Opt out with `data-prefetch="none"`, `data-no-prefetch`, or
617
- `rel="external"`. Speculation is bounded by a concurrency cap (excess
618
- requests queue and drain as slots free, rather than being dropped),
619
- in-flight de-dupe, and an LRU + TTL cache, and is disabled entirely under
620
- `Save-Data`, `prefers-reduced-data`, or a 2g `effectiveType` connection.
621
- The guiding rule: snappy, but never at the cost of bloating the client
622
- network tab; when the two conflict, the gate under-fetches. A mutating form submission and
623
- `revalidate(url)` both evict the prefetch cache alongside the snapshot
624
- cache, so a fragment prefetched before a mutation is never served stale.
625
-
626
- There is no logout-style safeguard, matching every framework that
627
- auto-prefetches: a prefetch issues a real GET, so a `/logout` or any
628
- mutating endpoint MUST be a POST or a `<form>` submission (which the
629
- router never prefetches), not a GET link. A native `<link rel="prefetch">`
630
- in the document head is the browser's own mechanism and is left untouched.
631
-
632
- The router dispatches a `webjs:prefetch` event on `document` the instant a
633
- speculative fragment lands in the cache and becomes consumable (which is
634
- strictly later than the request going out, since the entry is stored only
635
- after the response body is read). The detail is `{ url, key, from: 'prefetch' }`,
636
- mirroring `webjs:navigate` so one listener can split the two by `detail.from`.
637
- Listen to instrument prefetch hit rate, or to gate work on a warm cache:
638
-
639
- ```ts
640
- document.addEventListener('webjs:prefetch', (e) => {
641
- console.log('prefetched', e.detail.url); // fragment is now cached
642
- });
643
- ```
644
-
645
- ### View Transitions (opt-in, all three swap paths)
646
-
647
- The router can wrap a client navigation's DOM mutation in the native
648
- [View Transitions API](https://developer.mozilla.org/en-US/docs/Web/API/View_Transitions_API)
649
- (`document.startViewTransition`), so a same-shell partial swap cross-fades
650
- (or runs your `::view-transition-*` CSS) instead of snapping. It is OFF by
651
- default and purely OPT-IN, so an unconfigured app behaves exactly as
652
- before (no animation surprise, no regression in a browser without the
653
- API). Opt in by adding a meta to the page head, mirroring Turbo's
654
- `<meta name="view-transition">` convention:
655
-
656
- ```html
657
- <!-- in the root layout's <head>, or any page's head -->
658
- <meta name="view-transition" content="same-origin">
659
- ```
660
-
661
- The accepted opt-in value is `same-origin` (every client-router swap is
662
- same-origin by construction, so it reads as "animate these in-app
663
- navigations"); any other value, or the meta being absent, keeps
664
- transitions off. The meta is re-read PER navigation, so a page can turn
665
- transitions on or off as the user moves through the app (the head merge
666
- brings in the new page's head).
667
-
668
- When enabled and supported, the transition wraps ALL THREE swap paths,
669
- the deepest-marker layout swap, the `<webjs-frame>` swap, AND the
670
- full-body fallback, not just the full-body case (the inverse of what an
671
- author expects, since the marker + frame swaps are the common
672
- designed-for paths). The transition wraps the DOM MUTATION ONLY, never
673
- the fetch (which already happened); the browser captures the
674
- before/after around the synchronous swap. When `startViewTransition` is
675
- unavailable (Firefox / older Safari), the swap runs synchronously,
676
- byte-identical to the no-transition path, with no flash and no throw.
677
-
678
- ### Persisting elements across a swap (`data-webjs-permanent`)
679
-
680
- An element marked `data-webjs-permanent` (it MUST also carry an `id`)
681
- survives a navigation as the SAME live DOM node, by node identity, so a
682
- playing `<audio>` / `<video>`, a live widget, an open menu, or any element
683
- with accumulated JS state keeps running across the swap instead of being
684
- destroyed and re-created from the incoming HTML. Mirrors Turbo's
685
- permanent-element behaviour.
686
-
687
- ```html
688
- <audio id="player" data-webjs-permanent controls src="/track.mp3"></audio>
689
- ```
690
-
691
- Mechanism: before the destructive swap, for each `[data-webjs-permanent]
692
- [id]` in the CURRENT DOM the router looks for a matching `#id` in the
693
- INCOMING document; when BOTH exist, the LIVE node is moved into the
694
- incoming tree's position (replacing the incoming placeholder), so the swap
695
- adopts the live node rather than recreating it. It works for the
696
- full-body path AND the in-region (marker / frame) paths, and is a STRONGER
697
- guarantee than the keyed reconciler (which preserves identity for matched
698
- keyed children): a permanent node keeps EXACT identity even where the
699
- reconciler would otherwise recreate it. Rules:
700
-
701
- - The element must have an `id` (the match key) and the attribute on BOTH
702
- the current and incoming render of the page.
703
- - An id present in the current but ABSENT from the incoming doc is NOT
704
- force-persisted (it is being removed; the swap removes it as usual).
705
- - Only a CURRENT node actually carrying `data-webjs-permanent` is moved
706
- (an incoming `#id` that resolves to a non-permanent current element is
707
- left untouched).
708
- - The node is placed exactly where the incoming document puts it, so it
709
- never escapes a frame / region boundary.
710
-
711
- Progressive enhancement: with JS off, `data-webjs-permanent` is an inert
712
- attribute and the navigation is a normal full-page load.
713
-
714
- ### Per-segment loading skeletons
715
-
716
- Each `loading.{js,ts}` in the route chain is rendered into a hidden
717
- `<template id="wj-loading:<segment-path>">`. On nav-start, the client
718
- clones the deepest matching template into the swap slot. Users see
719
- an instant per-segment skeleton during the fetch.
720
-
721
- ### Programmatic navigation
722
-
723
- ```js
724
- import { navigate } from '@webjsdev/core';
725
- await navigate('/about'); // push history
726
- await navigate('/login', { replace: true }); // replace
727
- ```
728
-
729
- ### Form submissions
730
-
731
- `<form action="..." method="...">` submissions are intercepted alongside
732
- link clicks and routed through the same partial-swap pipeline.
733
- Submitter attributes (`formmethod` / `formaction` / `formenctype` on a
734
- clicked `<button>`) take precedence over the form's own, per the HTML5
735
- form-submission algorithm.
736
-
737
- - **GET**: `FormData` is promoted to the URL query string (replacing
738
- any existing `?...` on `action`), then the URL is fetched and applied
739
- exactly like a link click.
740
- - **POST / PUT / PATCH / DELETE**: `FormData` is sent as the request
741
- body. After a successful response the snapshot cache is cleared (the
742
- submission may have mutated server state that other cached URLs
743
- depend on, so back/forward must refetch instead of restoring stale).
744
-
745
- Forms calling a server action via `@submit=${e => this.handleSubmit(e)}`
746
- + `e.preventDefault()` are unaffected: the router only intercepts when
747
- `event.defaultPrevented` is false. Opt out per form or per submitter
748
- with `data-no-router`:
749
-
750
- ```html
751
- <form action="/legacy" data-no-router>...</form>
752
- <form action="/x"><button data-no-router>Full reload</button></form>
753
- ```
754
-
755
- Auto-skipped (no `data-no-router` needed):
756
- - `method="dialog"` (browser-native dialog dismissal)
757
- - `target` / `formtarget` ≠ `_self` (iframe / popup)
758
- - Cross-origin `action`
759
- - Non-HTML extensions on `action` (`.pdf`, etc.)
760
-
761
- ### Non-2xx HTML responses are rendered in place
762
-
763
- A response with a `text/html` body is applied to the DOM regardless of
764
- status code:
765
-
766
- - **2xx**: normal navigation.
767
- - **4xx (e.g. 422)**: server-rendered validation errors. The form is
768
- re-rendered with `value` attributes preserving what the user typed,
769
- inline error messages visible, no full-page reload. Standard Rails /
770
- Django / Laravel / Phoenix pattern.
771
- - **5xx with HTML**: error page rendered in place (not a flash of
772
- blank then reload).
773
-
774
- Non-HTML responses (JSON error envelopes, downloads, opaque) fall back
775
- to `location.href = url` and let the browser handle them.
776
-
777
- **204 No Content** = "stay on current page" (autosave-style
778
- submissions). DOM is untouched. History records the requested URL.
779
-
780
- **Server-side redirects** (3xx that `fetch()` follows automatically)
781
- record the **final** URL in history, not the originally-requested one.
782
- The Post-Redirect-Get pattern works correctly.
783
-
784
- ### Page server actions (a `<form>` that re-renders with errors)
785
-
786
- The server side of the no-JS validation pattern is a page `action`
787
- export. A `page.{js,ts}` may export an `action` alongside its default
788
- render function. A non-GET/HEAD submission to that page's own URL runs
789
- the action (inside the page's segment middleware), so a plain
790
- `<form method="POST">` works with JS disabled AND through the client
791
- router, same UI either way.
792
-
793
- ```ts
794
- // app/signup/page.ts
795
- import { html } from '@webjsdev/core';
796
- import { signup } from '../../modules/auth/actions/signup.server.ts';
797
-
798
- export async function action({ formData }: { formData: FormData }) {
799
- const email = String(formData.get('email') || '').trim();
800
- const values = { email };
801
- if (!email.includes('@')) {
802
- return { success: false, fieldErrors: { email: 'Enter a valid email' }, values, status: 422 };
803
- }
804
- const r = await signup({ email });
805
- if (!r.success) return { success: false, fieldErrors: { email: r.error }, values, status: r.status };
806
- return { success: true, redirect: '/login' };
807
- }
808
-
809
- export default function Signup({ actionData }: { actionData?: { fieldErrors?: Record<string, string>; values?: Record<string, string> } }) {
810
- const errors = actionData?.fieldErrors || {};
811
- const values = actionData?.values || {};
812
- return html`
813
- <form method="POST">
814
- <input name="email" type="email" value=${values.email || ''} required>
815
- ${errors.email ? html`<p class="error">${errors.email}</p>` : ''}
816
- <button>Sign up</button>
817
- </form>
818
- `;
819
- }
820
- ```
821
-
822
- The action receives `{ request, params, searchParams, url, formData }`
823
- (`formData` is the already-parsed body, `request` is the raw Request)
824
- and returns an `ActionResult`. The server interprets the result:
825
-
826
- - **Success** (`{ success: true, redirect? }`, or any non-`false`
827
- result): a `303 See Other` to `result.redirect` if present, else the
828
- page's own path (Post/Redirect/Get, so a reload does not resubmit).
829
- This 303 is the success-result path only; a `redirect()` *thrown* from
830
- the action is a separate case (see below).
831
- - **Failure** (`{ success: false, fieldErrors?, values?, status? }`):
832
- re-SSR the SAME page with `status` (default `422`) and the result on
833
- `ctx.actionData`. The page reads `actionData.fieldErrors.<field>` for
834
- messages and `actionData.values.<field>` to repopulate native
835
- `<input value=...>`, so the user's typed input survives.
836
- - A thrown `notFound()` yields a 404. A thrown `redirect()` carries no
837
- baked-in status; the catching site picks the convention: thrown from an
838
- action (a POST) it defaults to `307 Temporary Redirect`
839
- (method-preserving, so the bounce keeps the POST's intent), thrown
840
- during a GET page/layout render or gate it defaults to `302 Found` (the
841
- code an auth bounce conventionally wants). An explicit status overrides
842
- either default, in both the positional `redirect(url, 308)` and the
843
- options `redirect(url, { status })` forms. PRG's 303 (above) is only
844
- the success-result path, distinct from these thrown defaults.
845
-
846
- A page WITHOUT an `action` export keeps the old behavior, a non-GET to
847
- it 404s. There is no form library: native input repopulation plus the
848
- browser's Constraint Validation API (`required`, `type="email"`,
849
- `minlength`) cover the rest. Field-level errors come from the server
850
- action result. See `agent-docs/recipes.md` for the full recipe and the
851
- `ActionResult` shape.
852
-
853
- ### Concurrent navigations + cancellation
854
-
855
- Each navigation/submission `abort()`s any in-flight fetch from the prior
856
- one (Turbo Drive's `navigator.stop()` pattern). Rapid clicks won't
857
- produce N parallel requests competing to be applied last. A monotonic
858
- nav-token additionally short-circuits any response that arrives after a
859
- newer navigation has settled, so a slow first request that races past
860
- its abort cannot revert the newer page.
861
-
862
- ### Scroll restoration on back/forward
863
-
864
- On snapshot, the router records `{ window.scrollX, window.scrollY }`
865
- alongside the HTML. On popstate cache-hit, the cached DOM is applied
866
- and scroll is restored to where the user left it. The background
867
- revalidation fetch that follows does **not** scroll, so the restored
868
- position survives the refresh. Cache miss → browser-native scroll
869
- restoration takes over.
870
-
871
- Every programmatic nav scroll (the popstate restore and the
872
- scroll-to-top on a forward nav) is issued with `behavior: 'instant'`, so
873
- an app-level `html { scroll-behavior: smooth }` does not animate it. The
874
- restore matches a native page load (an instant jump), not a visible
875
- slide. The one nav scroll left smooth is a hash-anchor (`#section`)
876
- target, where smooth scrolling is the intent. So `scroll-behavior:
877
- smooth` on `<html>` only affects in-page anchors, not route
878
- transitions. In development the router logs a one-time console hint when
879
- it detects that setting (and notes that pairing it with a sticky
880
- `backdrop-filter` header can flash on iOS during navigation).
881
-
882
- Inner scroll containers (e.g. `.docs-sidenav`) are preserved
883
- automatically by the outer-layout-DOM-identity invariant. They stay
884
- mounted across nav and keep their `scrollTop` natively.
885
-
886
- ### `<webjs-frame>` escape hatch
887
-
888
- `<webjs-frame>` is webjs's take on **Turbo Frames** (Hotwire Turbo), so the
889
- mental model and most `<turbo-frame>` muscle memory transfer directly: a lazy,
890
- URL-addressable region that swaps on its own, driven by a link or form
891
- targeting its id. It is the unit for a region that loads or refreshes
892
- INDEPENDENTLY of a full-page navigation (something a page/layout, which
893
- re-renders only at the route level, cannot express), and it ships zero
894
- component JS. A frame's route can itself use `<webjs-suspense>`, so a deferred
895
- (`loading="lazy"`) frame whose data is slow streams that data behind a fallback
896
- inside the frame (one caveat: a streamed framed route skips the byte-saving
897
- subtree extraction, so the full page renders and the client slices out the
898
- region). See the data-fetching doc page (`docs/app/docs/data-fetching/page.ts`)
899
- for the async-render vs `<webjs-suspense>` vs `<webjs-frame>` vs `<webjs-stream>`
900
- decision boundary.
901
-
902
- For partial-swap regions NOT tied to a folder layout (a marketing-page
903
- widget, tabbed UI, etc.), wrap the region in a frame:
904
-
905
- ```ts
906
- html`<webjs-frame id="activity">…contents…</webjs-frame>`
907
- ```
908
-
909
- On click, the router walks `closest('webjs-frame')` from the click
910
- target. If a frame is found AND the response contains a matching
911
- `<webjs-frame id="...">`, the swap is scoped to that frame's children,
912
- which takes precedence over the layout-marker mechanism.
913
-
914
- #### External targeting (`data-webjs-frame`) and `_top` breakout
915
-
916
- A trigger does NOT have to be nested inside the frame it drives. Mirroring
917
- Turbo's `data-turbo-frame`, an `<a>` or `<form>` (or any ancestor of it)
918
- carrying `data-webjs-frame="<id>"` drives the frame with that id, resolved
919
- via `getElementById` in the current document. So an external nav/sidebar
920
- link or a filter form can drive a content frame it does not enclose:
921
-
922
- ```ts
923
- html`
924
- <nav data-webjs-frame="results">
925
- <a href="/products?sort=new">Newest</a>
926
- <a href="/products?sort=top">Top rated</a>
927
- </nav>
928
- <form action="/products" data-webjs-frame="results">…filters…</form>
929
-
930
- <webjs-frame id="results">…current results…</webjs-frame>
931
- `
932
- ```
933
-
934
- Resolution precedence: an explicit `data-webjs-frame` WINS over the
935
- closest-enclosing-frame default. So a link physically inside frame A that
936
- carries `data-webjs-frame="b"` drives frame B.
937
-
938
- - **`data-webjs-frame="_top"`** is a reserved token: it forces a full-page
939
- navigation (the normal layout/marker swap or a full nav), breaking OUT of
940
- the enclosing frame. Put it on a link inside a frame that should escape it.
941
- - **An id that does not resolve** to a live `<webjs-frame>` emits a one-time
942
- `console.warn` and falls back to a normal navigation (fail-safe; the
943
- router never throws and never swaps the wrong region).
944
- - **With JS disabled** a `data-webjs-frame` link is an inert attribute on a
945
- plain `<a href>`, so the click is a normal full-page navigation, the
946
- correct progressive-enhancement fallback.
947
-
948
- #### Busy state (`aria-busy` + `webjs:frame-busy`)
949
-
950
- While a frame's navigation is in flight the router sets the native
951
- `aria-busy="true"` on the frame element and clears it (to `"false"`) on
952
- completion, on EVERY exit (a successful swap, a frame-missing response, an
953
- HTTP/transport error, or an abort by a newer nav). So assistive tech
954
- announces the loading state for free, and CSS can style the busy region:
955
-
956
- ```css
957
- webjs-frame[aria-busy="true"] { opacity: 0.6; }
958
- ```
959
-
960
- The router also dispatches a bubbling `webjs:frame-busy` event on the frame
961
- at both edges, so app code can hook the start and finish:
962
-
963
- ```ts
964
- document.addEventListener('webjs:frame-busy', (e) => {
965
- const { frameId, busy } = e.detail; // busy: true at start, false at finish
966
- spinner.toggle(frameId, busy);
967
- });
968
- ```
969
-
970
- #### `webjs:frame-missing` (response lacks the requested frame)
971
-
972
- When a frame-scoped navigation's response does NOT carry a matching
973
- `<webjs-frame id="...">` (e.g. an auth gate returns a login page without
974
- the frame), the router does NOT fall through to a full-page swap, because
975
- that would silently destroy the page. Instead it dispatches a cancelable,
976
- bubbling `webjs:frame-missing` CustomEvent on the frame element (so a
977
- document-level listener catches it) and returns.
978
-
979
- - **Default (not prevented):** the router emits a one-line `console.warn`
980
- and leaves the frame UNCHANGED (its current content stays, now stale).
981
- No full-page swap ever happens.
982
- - **Calling `preventDefault()`** keeps the framework silent and doing nothing
983
- further. The listener owns the outcome, e.g. it may call `navigate(url)`
984
- for a deliberate full swap, or `location.assign(url)` for a hard load.
985
-
986
- `event.detail` is `{ frameId, url, document }`, where `frameId` is the
987
- requested frame id, `url` is the navigation target, and `document` is the
988
- parsed response document (so a listener can inspect what came back).
989
-
990
- ```ts
991
- document.addEventListener('webjs:frame-missing', (e) => {
992
- // The frame wasn't in the response (auth redirect, say). Take over
993
- // with a deliberate full navigation to the URL the server returned.
994
- e.preventDefault();
995
- location.assign(e.detail.url);
996
- });
997
- ```
998
-
999
- #### Self-loading frames (`src` + `loading`, #253)
1000
-
1001
- A `<webjs-frame>` can fetch its OWN content instead of waiting for a click
1002
- or a form. Give it a `src` and it self-fetches that URL as a frame nav and
1003
- applies the matching `<webjs-frame id>` subtree from the response into itself,
1004
- through the SAME frame-swap path a click-driven frame nav uses (so the busy
1005
- lifecycle, the navigation-error recovery, the keyed reconciler, and the
1006
- frame-missing fallback all apply for free).
1007
-
1008
- ```html
1009
- <!-- Eager (default): fetches on connect. -->
1010
- <webjs-frame id="rail" src="/widgets/rail"></webjs-frame>
1011
-
1012
- <!-- Lazy: fetches when the frame first scrolls into view. -->
1013
- <webjs-frame id="comments" src="/posts/42/comments" loading="lazy">
1014
- <p>Loading comments...</p>
1015
- </webjs-frame>
1016
- ```
1017
-
1018
- The `loading` attribute picks WHEN:
1019
-
1020
- - **`loading="eager"`** (or absent, the default) fetches on `connectedCallback`.
1021
- - **`loading="lazy"`** fetches when the frame first enters the viewport, reusing
1022
- the same IntersectionObserver budget (`rootMargin: '200px'`) as a
1023
- `static lazy = true` component.
1024
-
1025
- A `src` change after connect re-loads. Eager connect, the lazy observer, and a
1026
- `src` mutation never double-fetch the same URL (a per-element loaded/loading
1027
- guard keyed on the resolved URL coalesces them). The request carries the same
1028
- `x-webjs-frame: <id>` header a click-driven frame nav sends, so a `src` self-load
1029
- and a click that targets the same frame produce identical DOM.
1030
-
1031
- **The server returns ONLY the requested subtree.** When a request carries
1032
- `x-webjs-frame: <id>` and the route renders a `<webjs-frame id>` with that id,
1033
- the server returns JUST that frame subtree (extracted from the full render, so
1034
- byte-equivalent to what the client would slice from a full-page response) rather
1035
- than the whole page. So a region swap pays only for the region, not the full
1036
- document shell and every other region, the same spirit as the `X-Webjs-Have`
1037
- partial-nav optimization. When the requested frame is NOT in the rendered output
1038
- (an auth redirect to a login page, a route that dropped the frame), the server
1039
- falls back to the full page and the client handles the absence via
1040
- `webjs:frame-missing`. A request with no `x-webjs-frame` header is unaffected
1041
- (byte-identical full-page render).
1042
-
1043
- **PROGRESSIVE ENHANCEMENT CAVEAT: a `src`-driven frame is JS-DEPENDENT.** The
1044
- browser does NOT natively fetch `<webjs-frame src>` (unlike `<iframe>`), so with
1045
- JS off the frame shows only whatever children were server-rendered into it. Use
1046
- `src`/`loading` for DEFERRED content (comments, a recommendations rail, an
1047
- expensive card) where a JS-off placeholder / empty state is acceptable, exactly
1048
- the lazy-content use case. For content that MUST exist without JS, render it
1049
- server-side into the frame instead of using `src` (the self-load then replaces
1050
- those fallback children).
1051
-
1052
- ### Stream actions: surgical element-level updates (#248)
1053
-
1054
- `<webjs-stream>` is webjs's take on **Turbo Streams** (Hotwire Turbo); the
1055
- action set (`append` / `prepend` / `before` / `after` / `replace` / `update` /
1056
- `remove`) mirrors `<turbo-stream>`, so that muscle memory transfers directly. It
1057
- is the ONLY surgical single-element update primitive (and the live-channel
1058
- applier); a region swap or a `<webjs-frame>` reload redraws a whole region, and
1059
- `<webjs-suspense>` is for streaming, so none of them cover "append one row".
1060
-
1061
- A region swap (a layout marker or a `<webjs-frame>`) is the right tool for "this
1062
- part of the page changed". It is too coarse for "append ONE comment", "remove
1063
- ONE row", "bump a count", or "insert a toast". For those, a server response can
1064
- declare per-element actions, carried as plain HTML, a `<webjs-stream action
1065
- target>` wrapping one `<template>`:
1066
-
1067
- ```html
1068
- <webjs-stream action="append" target="comments">
1069
- <template><li>Nice post!</li></template>
1070
- </webjs-stream>
1071
- ```
1072
-
1073
- The `<webjs-stream>` element clones its `<template>` content on connect, applies
1074
- the action against the target by native DOM, then removes itself. Actions
1075
- (Turbo's set): `append` / `prepend` (last / first child of the target id),
1076
- `before` / `after` (sibling of the target), `replace` (the target element
1077
- itself), `update` (the target's children), `remove` (delete the target, no
1078
- template). A `targets="<css-selector>"` applies to every match instead of a
1079
- single `target` id.
1080
-
1081
- **One applier, two delivery paths.**
1082
-
1083
- 1. **HTTP (content-negotiated form).** A `<form>` submission rides the client
1084
- router, which adds `Accept: text/vnd.webjs-stream.html`. The server returns a
1085
- stream ONLY when that Accept is present; the router then applies the
1086
- `<webjs-stream>` body surgically (no region swap). With JS OFF the browser
1087
- sends no such Accept, so the SAME endpoint returns a normal render/redirect
1088
- and the form is a plain full-page POST. The grammar is additive and
1089
- progressive-enhancement-safe.
1090
-
1091
- 2. **Live channel (`broadcast()` / `connectWS`).** `renderStream(message)` parses
1092
- a server-pushed payload and inserts the `<webjs-stream>` elements (which
1093
- self-apply), so chat / notifications / presence reuse the SAME applier:
1094
-
1095
- ```js
1096
- import { connectWS, renderStream } from '@webjsdev/core';
1097
- connectWS('/feed', { onMessage: (m) => renderStream(m) });
1098
- ```
1099
-
1100
- **Server-side, build the payload with the `@webjsdev/server` helpers:**
1101
-
1102
- ```ts
1103
- // app/post/[id]/route.ts (or a page `action`)
1104
- import { stream, streamResponse, acceptsStream } from '@webjsdev/server';
1105
- import { broadcast } from '@webjsdev/server';
1106
-
1107
- export async function POST(req: Request, { params }) {
1108
- const comment = await addComment(params.id, await req.formData());
1109
- const html = stream.append('comments', `<li>${escapeHtml(comment.text)}</li>`);
1110
- // Fan the SAME action out to every other connected viewer.
1111
- broadcast(`post:${params.id}`, html);
1112
- // Negotiate: a stream for the JS client, a redirect for the no-JS form.
1113
- if (acceptsStream(req)) return streamResponse(html);
1114
- return Response.redirect(`/post/${params.id}`, 303);
1115
- }
1116
- ```
1117
-
1118
- `stream.*` returns the `<webjs-stream>` string (the target id is
1119
- attribute-escaped; the CONTENT is server-authored and NOT escaped, so escape any
1120
- user substring yourself, like an `html` hole). `streamResponse(...)` wraps one or
1121
- more parts in a `Response` with the stream content type. A page `action` may
1122
- return `streamResponse(...)` directly (it is honored verbatim); on the no-JS
1123
- branch return a normal `ActionResult` instead. `renderStream` is auto-registered
1124
- by the client router, so it (and the `<webjs-stream>` element) is available
1125
- on any page that loads `@webjsdev/core` (the router auto-enables there).
1126
-
1127
- ### Streaming RPC results: an action returns a stream (#489)
1128
-
1129
- `<webjs-stream>` above is the SERVER-PUSHED render-side primitive (the server
1130
- decides what changes and ships HTML actions). Streaming RPC is the complementary
1131
- PULL-side primitive: a `'use server'` action that RETURNS a `ReadableStream`, an
1132
- async iterable, or an async generator streams its chunks over the single RPC
1133
- response, and the client gets back an async iterable to `for await`. This is the
1134
- token-stream / progress / incremental-result case a component consumes
1135
- imperatively after an interaction.
1136
-
1137
- ```ts
1138
- // modules/ai/actions/stream-answer.server.ts
1139
- 'use server';
1140
- export async function* streamAnswer(prompt: string) {
1141
- for await (const token of llm.complete(prompt)) yield token;
1142
- }
1143
- ```
1144
-
1145
- ```ts
1146
- // inside a component
1147
- for await (const token of await streamAnswer(q)) {
1148
- this.text.set(this.text.get() + token); // renders incrementally
1149
- }
1150
- ```
1151
-
1152
- The wire is a sequence of length-prefixed frames (`application/vnd.webjs+stream`):
1153
- each chunk is rich-serialized (a `Date` / `Map` / `BigInt` round-trips), then a
1154
- terminal frame closes the stream. Detection is purely on the RETURN value, so any
1155
- verb (#488) can stream and there is no config export to declare. Back-pressure is
1156
- respected (a slow consumer throttles a fast producer), and the request
1157
- `AbortSignal` (#492) cancels the source generator on a client disconnect or a
1158
- superseded `async render()`. A streamed result is never cached, ETagged, or
1159
- seeded (#472); a mutation that streams still emits its `X-Webjs-Invalidate`
1160
- header. A mid-stream throw surfaces as an error from the iterable (the HTTP status
1161
- is already 200, so wrap the `for await` in `try/catch`), the author message in
1162
- prod. A truncated stream (a server crash, a dropped connection) also throws
1163
- rather than completing silently: a healthy stream always ends in an explicit
1164
- terminal frame, so a missing one is an error. For a slow region you want behind a fallback on the FIRST paint, use
1165
- `<webjs-suspense>` instead; streaming RPC is for an imperative stream consumed
1166
- after an interaction. Full reference: the [Data fetching](https://docs.webjs.com/docs/data-fetching) page.
1167
-
1168
- ### Opt out per link
1169
-
1170
- ```html
1171
- <a href="/legacy" data-no-router>Full reload</a>
1172
- ```
1173
-
1174
- Use `data-no-router` for:
1175
- - **Auth flows**: `/logout`, OAuth redirects. Full reload wipes in-memory module state.
1176
- - **Print views / embed pages.**
1177
- - **Experimental routes** with a different client runtime.
1178
-
1179
- ### Auto-skipped (no `data-no-router` needed)
1180
-
1181
- - `download`, non-`_self` target, modifier-key click.
1182
- - Cross-origin hrefs.
1183
- - Pure hash fragments on same page.
1184
- - Non-HTML extensions (`.pdf`, `.zip`, `.json`, images, media): browser handles.
1185
- - Response `Content-Type` not `text/html`: falls back to full nav.
1186
-
1187
- ### Loading indicator
1188
-
1189
- **When to use it.** You want a CSS-only progress affordance (a top bar, a `cursor: progress`) while a client navigation is in flight, with no JavaScript. For a JS-driven indicator, skip this and listen for the `webjs:navigate` event (and `webjs:submit-start` for forms) instead, which always fires.
1190
-
1191
- **How to use it.** It is OPT-IN. Add `data-webjs-nav-progress` to your `<html>` element (once, in the root layout), and the router then sets a `data-navigating` attribute on `<html>` while a nav is in flight (deferred 150ms, so quick sub-150ms navs never trigger it). Style off that attribute:
1192
-
1193
- ```html
1194
- <html data-webjs-nav-progress> <!-- opt in once -->
1195
- ```
1196
-
1197
- ```css
1198
- html[data-navigating] { cursor: progress; }
1199
- html[data-navigating]::after {
1200
- content: ''; position: fixed; top: 0; left: 0; right: 0; height: 2px;
1201
- background: var(--accent); animation: progress 1s ease-in-out infinite;
1202
- }
1203
- ```
1204
-
1205
- **Why it is opt-in, not default (#610).** Toggling an attribute on `<html>` re-runs global style resolution, and on WebKit (so every iOS browser) that re-resolves the page's `oklch()` / `color-mix()` design tokens to an equivalent oklab representation and repaints them for one frame. On a token-driven theme that is a visible background flash, worst on a slow mobile forward nav (which exceeds the 150ms defer). So without the opt-in the attribute is never written and the flash cannot happen. Enable it only when your theme does not lean on wide-gamut color tokens, or use the event-based path above.
1206
-
1207
- ## WebSockets
1208
-
1209
- ### Server: `WS` export in `route.{js,ts}`
1210
-
1211
- ```js
1212
- export function WS(ws, req, { params }) {
1213
- ws.on('message', (data) => ws.send('echo:' + data));
1214
- ws.on('close', () => { /* cleanup */ });
1215
- }
1216
- ```
1217
-
1218
- In **dev mode** the module re-imports per connection to pick up edits.
1219
- Store shared state on `globalThis`:
1220
-
1221
- ```js
1222
- const clients = globalThis.__my_clients ?? (globalThis.__my_clients = new Set());
1223
- ```
1224
-
1225
- ### Client: `connectWS`
1226
-
1227
- `connectWS(url, { onOpen, onMessage, onClose, onError, reconnect })` from `@webjsdev/core`. Auto-reconnects with exponential backoff, JSON parse/stringify, queues sends while disconnected.
1228
-
1229
- ### Broadcast (single-instance)
1230
-
1231
- ```js
1232
- import { broadcast } from '@webjsdev/server';
1233
-
1234
- export function WS(ws, req) {
1235
- ws.on('message', (data) => {
1236
- broadcast('/api/chat', data); // → all connected clients on this path
1237
- });
1238
- }
1239
- ```
1240
-
1241
- For multi-instance, the user adds Redis pub/sub themselves. No framework magic.
1242
-
1243
- ## Per-segment middleware
1244
-
1245
- `middleware.js` can live at any level under `app/` and only applies to
1246
- its subtree. Chain runs outermost → innermost, root-sibling → app-root
1247
- first, then segment-scoped files.
1248
-
1249
- ## Raw-text templates
1250
-
1251
- `<script>` and `<style>` are parsed as raw-text. `<` and `>` inside them aren't tag starts. Holes interpolate verbatim (no HTML escaping).