@rangojs/router 0.0.0-experimental.b02a2fec → 0.0.0-experimental.bf1b128c
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/README.md +50 -20
- package/dist/vite/index.js +1338 -462
- package/dist/vite/plugins/cloudflare-protocol-loader-hook.mjs +76 -0
- package/package.json +7 -5
- package/skills/breadcrumbs/SKILL.md +3 -1
- package/skills/handler-use/SKILL.md +362 -0
- package/skills/hooks/SKILL.md +28 -20
- package/skills/intercept/SKILL.md +20 -0
- package/skills/layout/SKILL.md +22 -0
- package/skills/links/SKILL.md +88 -16
- package/skills/loader/SKILL.md +66 -2
- package/skills/middleware/SKILL.md +32 -3
- package/skills/migrate-nextjs/SKILL.md +560 -0
- package/skills/migrate-react-router/SKILL.md +765 -0
- package/skills/parallel/SKILL.md +66 -0
- package/skills/rango/SKILL.md +24 -22
- package/skills/response-routes/SKILL.md +8 -0
- package/skills/route/SKILL.md +24 -0
- package/skills/streams-and-websockets/SKILL.md +283 -0
- package/skills/typesafety/SKILL.md +3 -1
- package/src/browser/app-shell.ts +52 -0
- package/src/browser/navigation-bridge.ts +71 -5
- package/src/browser/navigation-client.ts +64 -13
- package/src/browser/navigation-store.ts +25 -1
- package/src/browser/partial-update.ts +34 -3
- package/src/browser/prefetch/cache.ts +129 -21
- package/src/browser/prefetch/fetch.ts +148 -16
- package/src/browser/prefetch/queue.ts +36 -5
- package/src/browser/rango-state.ts +53 -13
- package/src/browser/react/Link.tsx +30 -2
- package/src/browser/react/NavigationProvider.tsx +50 -11
- package/src/browser/react/use-navigation.ts +22 -2
- package/src/browser/react/use-params.ts +11 -1
- package/src/browser/react/use-router.ts +8 -1
- package/src/browser/rsc-router.tsx +34 -6
- package/src/browser/segment-reconciler.ts +36 -14
- package/src/browser/types.ts +13 -0
- package/src/build/route-trie.ts +50 -24
- package/src/cache/cf/cf-cache-store.ts +5 -7
- package/src/client.tsx +82 -174
- package/src/index.rsc.ts +3 -0
- package/src/index.ts +40 -9
- package/src/outlet-context.ts +1 -1
- package/src/response-utils.ts +28 -0
- package/src/reverse.ts +7 -3
- package/src/route-definition/dsl-helpers.ts +175 -23
- package/src/route-definition/helpers-types.ts +63 -14
- package/src/route-definition/resolve-handler-use.ts +6 -0
- package/src/route-types.ts +7 -0
- package/src/router/handler-context.ts +24 -4
- package/src/router/lazy-includes.ts +6 -6
- package/src/router/loader-resolution.ts +3 -0
- package/src/router/manifest.ts +22 -13
- package/src/router/match-api.ts +3 -3
- package/src/router/middleware-types.ts +2 -22
- package/src/router/middleware.ts +54 -7
- package/src/router/pattern-matching.ts +60 -9
- package/src/router/revalidation.ts +15 -1
- package/src/router/segment-resolution/revalidation.ts +63 -58
- package/src/router/trie-matching.ts +10 -4
- package/src/router/url-params.ts +49 -0
- package/src/router.ts +1 -2
- package/src/rsc/handler.ts +8 -4
- package/src/rsc/helpers.ts +69 -41
- package/src/rsc/progressive-enhancement.ts +2 -0
- package/src/rsc/response-route-handler.ts +14 -1
- package/src/rsc/rsc-rendering.ts +7 -0
- package/src/rsc/server-action.ts +2 -0
- package/src/segment-content-promise.ts +67 -0
- package/src/segment-loader-promise.ts +122 -0
- package/src/segment-system.tsx +11 -61
- package/src/server/context.ts +26 -3
- package/src/server/request-context.ts +10 -42
- package/src/types/handler-context.ts +12 -39
- package/src/types/loader-types.ts +5 -6
- package/src/types/request-scope.ts +126 -0
- package/src/types/route-entry.ts +11 -0
- package/src/types/segments.ts +0 -1
- package/src/urls/include-helper.ts +24 -14
- package/src/urls/path-helper-types.ts +30 -4
- package/src/urls/response-types.ts +2 -10
- package/src/vite/debug.ts +184 -0
- package/src/vite/discovery/discover-routers.ts +31 -3
- package/src/vite/discovery/gate-state.ts +171 -0
- package/src/vite/discovery/prerender-collection.ts +48 -1
- package/src/vite/discovery/self-gen-tracking.ts +27 -1
- package/src/vite/plugins/cjs-to-esm.ts +5 -0
- package/src/vite/plugins/client-ref-dedup.ts +16 -0
- package/src/vite/plugins/client-ref-hashing.ts +16 -4
- package/src/vite/plugins/cloudflare-protocol-loader-hook.d.mts +23 -0
- package/src/vite/plugins/cloudflare-protocol-loader-hook.mjs +76 -0
- package/src/vite/plugins/cloudflare-protocol-stub.ts +214 -0
- package/src/vite/plugins/expose-action-id.ts +52 -28
- package/src/vite/plugins/expose-ids/router-transform.ts +20 -3
- package/src/vite/plugins/expose-internal-ids.ts +516 -486
- package/src/vite/plugins/performance-tracks.ts +17 -9
- package/src/vite/plugins/use-cache-transform.ts +56 -43
- package/src/vite/plugins/version-injector.ts +37 -11
- package/src/vite/rango.ts +49 -14
- package/src/vite/router-discovery.ts +558 -53
- package/src/vite/utils/banner.ts +1 -1
- package/src/vite/utils/package-resolution.ts +41 -1
- package/src/vite/utils/prerender-utils.ts +20 -6
package/skills/parallel/SKILL.md
CHANGED
|
@@ -206,6 +206,65 @@ parallel(
|
|
|
206
206
|
)
|
|
207
207
|
```
|
|
208
208
|
|
|
209
|
+
## Composable Slots via `handler.use`
|
|
210
|
+
|
|
211
|
+
Slot handlers can carry their own loader, loading, error/notFound boundaries, revalidation, and transition defaults via `.use`. The mount site then declares **just the slot names** — no per-call data wiring.
|
|
212
|
+
|
|
213
|
+
```typescript
|
|
214
|
+
const CartSummary: Handler = async (ctx) => {
|
|
215
|
+
const cart = await ctx.use(CartLoader);
|
|
216
|
+
return <CartSummaryView cart={cart} />;
|
|
217
|
+
};
|
|
218
|
+
CartSummary.use = () => [
|
|
219
|
+
loader(CartLoader),
|
|
220
|
+
loading(<CartSkeleton />),
|
|
221
|
+
revalidate(revalidateCartData),
|
|
222
|
+
];
|
|
223
|
+
|
|
224
|
+
// Same slot, no copy-pasted plumbing across layouts.
|
|
225
|
+
layout(<DashboardLayout />, () => [
|
|
226
|
+
parallel({ "@cart": CartSummary }),
|
|
227
|
+
path("/dashboard", DashboardIndex, { name: "dashboard.index" }),
|
|
228
|
+
]);
|
|
229
|
+
|
|
230
|
+
layout(<AccountLayout />, () => [
|
|
231
|
+
parallel({ "@cart": CartSummary }),
|
|
232
|
+
path("/account", AccountIndex, { name: "account.index" }),
|
|
233
|
+
]);
|
|
234
|
+
```
|
|
235
|
+
|
|
236
|
+
A slot's `loading()` (whether from `handler.use` or explicit) makes that slot an independent streaming unit, exactly as in the **Streaming Behavior** section above.
|
|
237
|
+
|
|
238
|
+
The `parallel` mount site has the narrowest allow-list for `handler.use` items — slots cannot bring their own middleware or layout, only `revalidate`, `loader`, `loading`, `errorBoundary`, `notFoundBoundary`, and `transition`. See [skills/handler-use](../handler-use/SKILL.md) for the full table and merge rules.
|
|
239
|
+
|
|
240
|
+
### Two scopes for explicit `use`: shared (broadcast) and slot-local
|
|
241
|
+
|
|
242
|
+
`parallel({...slots}, () => [...use])` runs the shared `use()` callback **once per slot** ([dsl-helpers.ts](../../src/route-definition/dsl-helpers.ts)) — items in that callback land on every slot's entry. That's the right behavior for the items the parallel allow-list permits and that accumulate (`loader`, `revalidate`, `errorBoundary`, `notFoundBoundary`, `transition`). (Slots cannot bring `middleware` or `layout` — see the allowed-types note above.)
|
|
243
|
+
|
|
244
|
+
For single-assignment items like `loading()`, broadcasting overwrites every slot's `handler.use` default. Pass a **slot descriptor** `{ handler, use }` instead — items in the descriptor's `use` apply only to that slot:
|
|
245
|
+
|
|
246
|
+
```typescript
|
|
247
|
+
// @cart gets a custom skeleton; @notifs keeps its handler.use default.
|
|
248
|
+
parallel({
|
|
249
|
+
"@cart": {
|
|
250
|
+
handler: Cart,
|
|
251
|
+
use: () => [loading(<CustomCartSkeleton />)],
|
|
252
|
+
},
|
|
253
|
+
"@notifs": Notifs,
|
|
254
|
+
});
|
|
255
|
+
|
|
256
|
+
// Opt one slot out of streaming while siblings still stream the broadcast.
|
|
257
|
+
parallel(
|
|
258
|
+
{
|
|
259
|
+
"@cart": { handler: Cart, use: () => [loading(false)] },
|
|
260
|
+
"@notifs": Notifs,
|
|
261
|
+
},
|
|
262
|
+
() => [loading(<BroadcastSkeleton />)],
|
|
263
|
+
);
|
|
264
|
+
```
|
|
265
|
+
|
|
266
|
+
Per-slot merge order is **handler.use → shared use → slot-local use**. Slot-local is the narrowest scope, so it wins for last-write-wins items. See [skills/handler-use § `loading()` is a single-assignment item — scope it correctly](../handler-use/SKILL.md#loading-is-a-single-assignment-item--scope-it-correctly) for the full reasoning.
|
|
267
|
+
|
|
209
268
|
## Slot Override Semantics
|
|
210
269
|
|
|
211
270
|
When multiple `parallel()` calls define the same slot name, **the last
|
|
@@ -288,6 +347,13 @@ Revalidating only the parallel does not re-run outer handlers/layouts.
|
|
|
288
347
|
If the slot reads `ctx.get()` data established above it, opt the outer
|
|
289
348
|
segment into revalidation as well.
|
|
290
349
|
|
|
350
|
+
A `revalidate()` callback may return a hard `boolean`, a soft
|
|
351
|
+
`{ defaultShouldRevalidate }` object, or nothing (`void` / `null` /
|
|
352
|
+
`undefined`) to defer to the next revalidator. See
|
|
353
|
+
[loader/SKILL.md#revalidate-return-shapes](../loader/SKILL.md#revalidate-return-shapes)
|
|
354
|
+
for the full contract — it's the same across `loader()`, `path()`,
|
|
355
|
+
`layout()`, `parallel()`, and `intercept()`.
|
|
356
|
+
|
|
291
357
|
### Revalidation Contracts for Parallel Dependencies
|
|
292
358
|
|
|
293
359
|
Prefer named revalidation contracts shared by both the upstream producer and
|
package/skills/rango/SKILL.md
CHANGED
|
@@ -10,28 +10,30 @@ Django-inspired RSC router with composable URL patterns, type-safe href, and ser
|
|
|
10
10
|
|
|
11
11
|
## Skills
|
|
12
12
|
|
|
13
|
-
| Skill
|
|
14
|
-
|
|
|
15
|
-
| `/router-setup`
|
|
16
|
-
| `/route`
|
|
17
|
-
| `/layout`
|
|
18
|
-
| `/loader`
|
|
19
|
-
| `/middleware`
|
|
20
|
-
| `/intercept`
|
|
21
|
-
| `/parallel`
|
|
22
|
-
| `/caching`
|
|
23
|
-
| `/use-cache`
|
|
24
|
-
| `/cache-guide`
|
|
25
|
-
| `/document-cache`
|
|
26
|
-
| `/theme`
|
|
27
|
-
| `/links`
|
|
28
|
-
| `/hooks`
|
|
29
|
-
| `/typesafety`
|
|
30
|
-
| `/host-router`
|
|
31
|
-
| `/tailwind`
|
|
32
|
-
| `/response-routes`
|
|
33
|
-
| `/mime-routes`
|
|
34
|
-
| `/fonts`
|
|
13
|
+
| Skill | Description |
|
|
14
|
+
| ----------------------- | -------------------------------------------------------------------------- |
|
|
15
|
+
| `/router-setup` | Create and configure the RSC router |
|
|
16
|
+
| `/route` | Define routes with `urls()` and `path()` |
|
|
17
|
+
| `/layout` | Layouts that wrap child routes |
|
|
18
|
+
| `/loader` | Data loaders with `createLoader()` |
|
|
19
|
+
| `/middleware` | Request processing and authentication |
|
|
20
|
+
| `/intercept` | Modal/slide-over patterns for soft navigation |
|
|
21
|
+
| `/parallel` | Multi-column layouts and sidebars |
|
|
22
|
+
| `/caching` | Segment caching with memory or KV stores |
|
|
23
|
+
| `/use-cache` | Function-level caching with `"use cache"` directive |
|
|
24
|
+
| `/cache-guide` | When to use `cache()` vs `"use cache"` — differences and decision guide |
|
|
25
|
+
| `/document-cache` | Edge caching with Cache-Control headers |
|
|
26
|
+
| `/theme` | Light/dark mode with FOUC prevention |
|
|
27
|
+
| `/links` | URL generation: ctx.reverse, href, useHref, useMount, scopedReverse |
|
|
28
|
+
| `/hooks` | Client-side React hooks |
|
|
29
|
+
| `/typesafety` | Type-safe routes, params, href, and environment |
|
|
30
|
+
| `/host-router` | Multi-app host routing with domain/subdomain patterns |
|
|
31
|
+
| `/tailwind` | Set up Tailwind CSS v4 with `?url` imports |
|
|
32
|
+
| `/response-routes` | JSON/text/HTML/XML/stream endpoints with `path.json()`, `path.text()` |
|
|
33
|
+
| `/mime-routes` | Content negotiation — same URL, different response types via Accept header |
|
|
34
|
+
| `/fonts` | Load web fonts with preload hints |
|
|
35
|
+
| `/migrate-nextjs` | Migrate a Next.js App Router project to Rango |
|
|
36
|
+
| `/migrate-react-router` | Migrate a React Router / Remix project to Rango |
|
|
35
37
|
|
|
36
38
|
## Quick Start
|
|
37
39
|
|
|
@@ -400,6 +400,14 @@ path(
|
|
|
400
400
|
Multiple response types can share the same URL pattern. See `/mime-routes` for the
|
|
401
401
|
full content negotiation API (Accept header matching, Vary: Accept, multi-variant routes).
|
|
402
402
|
|
|
403
|
+
## Long-Lived Responses (SSE / WebSocket)
|
|
404
|
+
|
|
405
|
+
For Server-Sent Events (`path.stream`) and WebSocket upgrades (`path.any`
|
|
406
|
+
returning a 101 / `webSocket` Response), see `/streams-and-websockets`.
|
|
407
|
+
Upgrade responses flow through without reconstruction; `Vary` and
|
|
408
|
+
`Server-Timing` are skipped, and stub headers are applied in place on a
|
|
409
|
+
best-effort basis.
|
|
410
|
+
|
|
403
411
|
## How It Works
|
|
404
412
|
|
|
405
413
|
1. `path.json()` tags the route at the trie level with a MIME type
|
package/skills/route/SKILL.md
CHANGED
|
@@ -383,6 +383,30 @@ urls(({ path, layout }) => [
|
|
|
383
383
|
])
|
|
384
384
|
```
|
|
385
385
|
|
|
386
|
+
## Handler-attached `.use`
|
|
387
|
+
|
|
388
|
+
Page handlers can carry their own loader, middleware, error boundaries, parallels, and other defaults via a `.use` callback — so the page is self-contained and reusable across mount sites without re-wiring the same items.
|
|
389
|
+
|
|
390
|
+
```typescript
|
|
391
|
+
const ProductPage: Handler<"/product/:slug"> = async (ctx) => {
|
|
392
|
+
const product = await ctx.use(ProductLoader);
|
|
393
|
+
return <ProductView product={product} />;
|
|
394
|
+
};
|
|
395
|
+
ProductPage.use = () => [
|
|
396
|
+
loader(ProductLoader),
|
|
397
|
+
loading(<ProductSkeleton />),
|
|
398
|
+
middleware(async (ctx, next) => {
|
|
399
|
+
await next();
|
|
400
|
+
ctx.header("Cache-Control", "private, max-age=60");
|
|
401
|
+
}),
|
|
402
|
+
];
|
|
403
|
+
|
|
404
|
+
// Mount site has no per-page wiring — defaults travel with the handler.
|
|
405
|
+
path("/product/:slug", ProductPage, { name: "product" });
|
|
406
|
+
```
|
|
407
|
+
|
|
408
|
+
Explicit `use()` at the mount site merges with `handler.use` (handler defaults first, explicit second). See [skills/handler-use](../handler-use/SKILL.md) for the merge order, allowed item types per mount site, and override semantics.
|
|
409
|
+
|
|
386
410
|
## Complete Example
|
|
387
411
|
|
|
388
412
|
```typescript
|
|
@@ -0,0 +1,283 @@
|
|
|
1
|
+
---
|
|
2
|
+
name: streams-and-websockets
|
|
3
|
+
description: Long-lived Response handlers — Server-Sent Events (SSE) via path.stream and WebSocket upgrades via path.any on Cloudflare Workers, including middleware interaction and runtime caveats.
|
|
4
|
+
argument-hint: "[sse | websocket | agents]"
|
|
5
|
+
---
|
|
6
|
+
|
|
7
|
+
# Streams and WebSockets
|
|
8
|
+
|
|
9
|
+
Response routes can return long-lived responses — SSE streams and WebSocket
|
|
10
|
+
upgrades. Both require a `Response` that the router must forward through the
|
|
11
|
+
middleware chain without reconstruction.
|
|
12
|
+
|
|
13
|
+
## When each fits
|
|
14
|
+
|
|
15
|
+
| Shape | Tag | Status | Body | Runtime |
|
|
16
|
+
| ----------- | --------------- | ------ | ------------------------------- | -------------------------------- |
|
|
17
|
+
| Server-Sent | `path.stream()` | 200 | `ReadableStream` (event-stream) | any runtime (Node, workerd, bun) |
|
|
18
|
+
| WebSocket | `path.any()` | 101 | `null` + `webSocket` property | Cloudflare Workers (workerd) |
|
|
19
|
+
|
|
20
|
+
- **SSE** is a regular 200 response with `content-type: text/event-stream`
|
|
21
|
+
and a `ReadableStream` body. Works everywhere, flows through middleware
|
|
22
|
+
normally.
|
|
23
|
+
- **WebSocket upgrades** produce a status-101 response with a non-standard
|
|
24
|
+
`webSocket` property (Cloudflare). The router detects these and forwards
|
|
25
|
+
them without reconstruction; `Vary` and `Server-Timing` are skipped, and
|
|
26
|
+
stub headers are merged in place on a best-effort basis.
|
|
27
|
+
|
|
28
|
+
## Server-Sent Events (SSE)
|
|
29
|
+
|
|
30
|
+
Use `path.stream()` (or `path.any()` if you need full control) to return a
|
|
31
|
+
`ReadableStream`. Each chunk is an `event-stream` frame:
|
|
32
|
+
|
|
33
|
+
```typescript
|
|
34
|
+
import { urls } from "@rangojs/router";
|
|
35
|
+
|
|
36
|
+
export const urlpatterns = urls(({ path }) => [
|
|
37
|
+
path.stream(
|
|
38
|
+
"/events/ticks",
|
|
39
|
+
(ctx) => {
|
|
40
|
+
const encoder = new TextEncoder();
|
|
41
|
+
|
|
42
|
+
const stream = new ReadableStream({
|
|
43
|
+
async start(controller) {
|
|
44
|
+
let count = 0;
|
|
45
|
+
const interval = setInterval(() => {
|
|
46
|
+
controller.enqueue(
|
|
47
|
+
encoder.encode(`event: tick\ndata: ${++count}\n\n`),
|
|
48
|
+
);
|
|
49
|
+
}, 1000);
|
|
50
|
+
|
|
51
|
+
// Honor client disconnect — signal comes from ctx.request.signal
|
|
52
|
+
ctx.request.signal.addEventListener("abort", () => {
|
|
53
|
+
clearInterval(interval);
|
|
54
|
+
controller.close();
|
|
55
|
+
});
|
|
56
|
+
},
|
|
57
|
+
});
|
|
58
|
+
|
|
59
|
+
return new Response(stream, {
|
|
60
|
+
headers: {
|
|
61
|
+
"content-type": "text/event-stream",
|
|
62
|
+
"cache-control": "no-store",
|
|
63
|
+
// Disable proxy buffering on Nginx/Traefik deployments
|
|
64
|
+
"x-accel-buffering": "no",
|
|
65
|
+
},
|
|
66
|
+
});
|
|
67
|
+
},
|
|
68
|
+
{ name: "ticks" },
|
|
69
|
+
),
|
|
70
|
+
]);
|
|
71
|
+
```
|
|
72
|
+
|
|
73
|
+
### Client
|
|
74
|
+
|
|
75
|
+
```typescript
|
|
76
|
+
"use client";
|
|
77
|
+
const source = new EventSource("/events/ticks");
|
|
78
|
+
source.addEventListener("tick", (e) => console.log("tick", e.data));
|
|
79
|
+
```
|
|
80
|
+
|
|
81
|
+
### SSE caveats
|
|
82
|
+
|
|
83
|
+
- **Never wrap SSE routes in `cache()`** — a cached `ReadableStream` is read
|
|
84
|
+
once and would replay an empty body on the next hit. `path.stream` is
|
|
85
|
+
already excluded from response-route caching, but don't layer a custom
|
|
86
|
+
cache() middleware on top.
|
|
87
|
+
- **Middleware is fine.** Global/route middleware rewraps the SSE `Response`
|
|
88
|
+
as `new Response(response.body, { status, headers })` to merge stub headers.
|
|
89
|
+
The `ReadableStream` body is passed by reference, not consumed, so the
|
|
90
|
+
client sees the stream unchanged. (WebSocket upgrades are the exception —
|
|
91
|
+
those bypass rewrap entirely; see below.)
|
|
92
|
+
- **Honor `ctx.request.signal`.** Without wiring abort to your source
|
|
93
|
+
(timer, DB cursor, upstream fetch), the stream leaks when the client
|
|
94
|
+
disconnects.
|
|
95
|
+
- **Disable Nginx/CDN buffering** via `x-accel-buffering: no` and ensure
|
|
96
|
+
no intermediate proxy rebuffers. On Cloudflare Workers this is a non-issue.
|
|
97
|
+
|
|
98
|
+
## WebSockets (Cloudflare Workers)
|
|
99
|
+
|
|
100
|
+
WebSocket upgrades on workerd produce a response with `status: 101` and a
|
|
101
|
+
non-standard `webSocket` property. The router detects this shape and forwards
|
|
102
|
+
the `Response` without reconstruction — the 101 status and the `webSocket`
|
|
103
|
+
property are preserved. `Vary` and `Server-Timing` writes are skipped, and
|
|
104
|
+
stub-header merging (cookies/custom headers set via `ctx.header()` or
|
|
105
|
+
`cookies().set()`) is best-effort: the router attempts to apply them in
|
|
106
|
+
place, but silently skips any write rejected by a runtime that exposes
|
|
107
|
+
immutable upgrade headers.
|
|
108
|
+
|
|
109
|
+
### Minimal upgrade handler
|
|
110
|
+
|
|
111
|
+
```typescript
|
|
112
|
+
import { urls } from "@rangojs/router";
|
|
113
|
+
|
|
114
|
+
export const urlpatterns = urls(({ path }) => [
|
|
115
|
+
path.any(
|
|
116
|
+
"/ws",
|
|
117
|
+
(ctx) => {
|
|
118
|
+
// Manual WebSocketPair on workerd
|
|
119
|
+
const upgrade = ctx.request.headers.get("upgrade");
|
|
120
|
+
if (upgrade !== "websocket") {
|
|
121
|
+
return new Response("expected upgrade: websocket", { status: 426 });
|
|
122
|
+
}
|
|
123
|
+
|
|
124
|
+
const { 0: client, 1: server } = new WebSocketPair();
|
|
125
|
+
server.accept();
|
|
126
|
+
server.addEventListener("message", (e) => {
|
|
127
|
+
server.send(`echo: ${e.data}`);
|
|
128
|
+
});
|
|
129
|
+
|
|
130
|
+
return new Response(null, {
|
|
131
|
+
status: 101,
|
|
132
|
+
webSocket: client,
|
|
133
|
+
} as ResponseInit);
|
|
134
|
+
},
|
|
135
|
+
{ name: "ws" },
|
|
136
|
+
),
|
|
137
|
+
]);
|
|
138
|
+
```
|
|
139
|
+
|
|
140
|
+
### Durable Object pattern
|
|
141
|
+
|
|
142
|
+
Route into a Durable Object that owns the connection:
|
|
143
|
+
|
|
144
|
+
```typescript
|
|
145
|
+
export const urlpatterns = urls(({ path }) => [
|
|
146
|
+
path.any(
|
|
147
|
+
"/rooms/:roomId",
|
|
148
|
+
async (ctx) => {
|
|
149
|
+
const id = ctx.env.ROOMS.idFromName(ctx.params.roomId);
|
|
150
|
+
const stub = ctx.env.ROOMS.get(id);
|
|
151
|
+
// The DO's fetch handler calls handleWebSocketUpgrade(request)
|
|
152
|
+
// and returns the 101 Response. We forward it unchanged.
|
|
153
|
+
return stub.fetch(ctx.request);
|
|
154
|
+
},
|
|
155
|
+
{ name: "room" },
|
|
156
|
+
),
|
|
157
|
+
]);
|
|
158
|
+
```
|
|
159
|
+
|
|
160
|
+
### Using the `agents` library
|
|
161
|
+
|
|
162
|
+
`routeAgentRequest` from `agents` returns a 101 `Response` targeted at a
|
|
163
|
+
Durable Object. Return it directly from `path.any()`:
|
|
164
|
+
|
|
165
|
+
```typescript
|
|
166
|
+
import { routeAgentRequest } from "agents";
|
|
167
|
+
import { urls } from "@rangojs/router";
|
|
168
|
+
|
|
169
|
+
export const urlpatterns = urls(({ path }) => [
|
|
170
|
+
path.any("/agents/*", async (ctx) => {
|
|
171
|
+
const response = await routeAgentRequest(ctx.request, ctx.env);
|
|
172
|
+
if (!response) {
|
|
173
|
+
return new Response("not found", { status: 404 });
|
|
174
|
+
}
|
|
175
|
+
return response;
|
|
176
|
+
}),
|
|
177
|
+
]);
|
|
178
|
+
```
|
|
179
|
+
|
|
180
|
+
## Middleware interaction
|
|
181
|
+
|
|
182
|
+
### Forwarded, not reconstructed
|
|
183
|
+
|
|
184
|
+
When a middleware is matched for the upgrade URL, the middleware still runs
|
|
185
|
+
**before** `next()` — but the Response from `next()` is forwarded as-is
|
|
186
|
+
rather than re-wrapped. This preserves:
|
|
187
|
+
|
|
188
|
+
- The 101 status (which would otherwise throw `RangeError: Responses may
|
|
189
|
+
only be constructed with status codes in the range 200 to 599, inclusive`
|
|
190
|
+
on standards-compliant runtimes).
|
|
191
|
+
- The Cloudflare `webSocket` property (which would otherwise be silently
|
|
192
|
+
dropped by `new Response(body, ...)` on workerd).
|
|
193
|
+
|
|
194
|
+
```typescript
|
|
195
|
+
// This works — logger runs, but the 101 flows through unchanged.
|
|
196
|
+
router.use(async (ctx, next) => {
|
|
197
|
+
console.log("ws request", ctx.url.pathname);
|
|
198
|
+
return next();
|
|
199
|
+
});
|
|
200
|
+
```
|
|
201
|
+
|
|
202
|
+
### Don't try to set cookies on an upgrade
|
|
203
|
+
|
|
204
|
+
Stub cookie/header writes made before `await next()` are applied to the
|
|
205
|
+
upgrade response on a best-effort basis — the router attempts an in-place
|
|
206
|
+
merge and skips any write rejected by runtimes that expose immutable 101
|
|
207
|
+
headers. Either way, a browser completing a WS handshake never reads them.
|
|
208
|
+
Do not rely on this for auth or state propagation: set cookies via a prior
|
|
209
|
+
HTTP request instead (e.g. during login), then read them at upgrade time
|
|
210
|
+
via `ctx.request.headers.get("cookie")`.
|
|
211
|
+
|
|
212
|
+
```typescript
|
|
213
|
+
// Avoid: this cookie may not land on the upgrade response, and the client
|
|
214
|
+
// never reads it during the handshake regardless.
|
|
215
|
+
router.use(async (ctx, next) => {
|
|
216
|
+
cookies().set("last-ws-at", Date.now().toString());
|
|
217
|
+
return next();
|
|
218
|
+
});
|
|
219
|
+
|
|
220
|
+
// Prefer: authenticate by reading a cookie set on a prior HTTP request.
|
|
221
|
+
path.any("/ws", (ctx) => {
|
|
222
|
+
const session = parseCookie(ctx.request.headers.get("cookie"))?.session;
|
|
223
|
+
if (!verify(session)) return new Response("unauthorized", { status: 401 });
|
|
224
|
+
// ...upgrade
|
|
225
|
+
});
|
|
226
|
+
```
|
|
227
|
+
|
|
228
|
+
### Short-circuit before upgrade
|
|
229
|
+
|
|
230
|
+
Middleware can return a non-101 Response to deny the upgrade outright:
|
|
231
|
+
|
|
232
|
+
```typescript
|
|
233
|
+
router.use(async (ctx, next) => {
|
|
234
|
+
if (!isAllowed(ctx.request)) {
|
|
235
|
+
return new Response("forbidden", { status: 403 });
|
|
236
|
+
}
|
|
237
|
+
return next();
|
|
238
|
+
});
|
|
239
|
+
```
|
|
240
|
+
|
|
241
|
+
## Caching
|
|
242
|
+
|
|
243
|
+
- **SSE** — do not combine with `cache()` (streams can't be replayed).
|
|
244
|
+
- **WebSocket** — `cache()` is inert because only `status === 200` is cacheable.
|
|
245
|
+
|
|
246
|
+
## Runtime caveats
|
|
247
|
+
|
|
248
|
+
| Runtime | SSE | WebSocket upgrade (101) |
|
|
249
|
+
| -------------------------------------- | --- | ---------------------------------------------------- |
|
|
250
|
+
| Cloudflare Workers (workerd) | OK | OK (native `WebSocketPair`, DO, `agents`) |
|
|
251
|
+
| Node (undici fetch) | OK | N/A — Node's HTTP server must upgrade |
|
|
252
|
+
| Bun | OK | Bun's native `upgrade()` — not a Response-based path |
|
|
253
|
+
| Dev (Vite + `@cloudflare/vite-plugin`) | OK | OK via workerd emulation |
|
|
254
|
+
|
|
255
|
+
When running in pure Node without workerd, a `status: 101` Response cannot
|
|
256
|
+
even be constructed (`new Response(null, { status: 101 })` throws). For
|
|
257
|
+
tests, fabricate upgrade-style responses by overriding `.status` on a real
|
|
258
|
+
Response instance:
|
|
259
|
+
|
|
260
|
+
```typescript
|
|
261
|
+
const upgrade = new Response(null, { status: 200 });
|
|
262
|
+
Object.defineProperty(upgrade, "status", { value: 101, configurable: true });
|
|
263
|
+
// optional: attach a webSocket stub
|
|
264
|
+
Object.defineProperty(upgrade, "webSocket", {
|
|
265
|
+
value: { stub: "ws" },
|
|
266
|
+
configurable: true,
|
|
267
|
+
enumerable: true,
|
|
268
|
+
});
|
|
269
|
+
```
|
|
270
|
+
|
|
271
|
+
## Testing
|
|
272
|
+
|
|
273
|
+
- Unit tests: `isWebSocketUpgradeResponse` and `executeMiddleware` passthrough
|
|
274
|
+
cases live in `src/rsc/__tests__/helpers.test.ts` and
|
|
275
|
+
`src/router/middleware.test.ts`.
|
|
276
|
+
- E2E: cover both dev and production modes against a workerd target. SSE
|
|
277
|
+
can be tested on any runtime; WS upgrades need workerd (use
|
|
278
|
+
`@cloudflare/vite-plugin` or `wrangler dev`).
|
|
279
|
+
|
|
280
|
+
## See also
|
|
281
|
+
|
|
282
|
+
- `response-routes` — the parent skill for `path.json/text/html/stream/any`.
|
|
283
|
+
- `middleware` — how global and route-level middleware compose with handlers.
|
|
@@ -462,9 +462,11 @@ export const ProductLoader = createLoader(async (ctx) => {
|
|
|
462
462
|
});
|
|
463
463
|
|
|
464
464
|
// Built-in Breadcrumbs — or any custom handle created with createHandle()
|
|
465
|
+
```
|
|
465
466
|
|
|
467
|
+
```tsx
|
|
466
468
|
// Client component — typeof infers all generics
|
|
467
|
-
|
|
469
|
+
"use client";
|
|
468
470
|
import { useLoader, useHandle, type Breadcrumbs } from "@rangojs/router/client";
|
|
469
471
|
import type { ProductLoader } from "../loaders";
|
|
470
472
|
|
|
@@ -0,0 +1,52 @@
|
|
|
1
|
+
import type { ComponentType, ReactNode } from "react";
|
|
2
|
+
|
|
3
|
+
/**
|
|
4
|
+
* App-shell metadata: the set of per-router fields that describe the
|
|
5
|
+
* "envelope" around the current app's segment tree. These fields are set
|
|
6
|
+
* from the initial RSC payload and must be replaced atomically when the
|
|
7
|
+
* client navigates into a different router (app switch).
|
|
8
|
+
*
|
|
9
|
+
* Intentionally NOT part of the shell (all document-lifetime):
|
|
10
|
+
* - themeConfig / initialTheme: ThemeProvider is mounted above the segment
|
|
11
|
+
* tree and must not remount on smooth transitions.
|
|
12
|
+
* - warmupEnabled: attached to the NavigationProvider's lifetime effect;
|
|
13
|
+
* toggling it mid-session would tear down and restart idle listeners.
|
|
14
|
+
* Also not serialized on every full-render path (e.g. the not-found
|
|
15
|
+
* fallback), so carrying it here would be unreliable.
|
|
16
|
+
* - prefetchCacheTTL: the not-found full-render payload does not serialize
|
|
17
|
+
* it, so a cross-app nav into a 404 would silently erase the setting.
|
|
18
|
+
* Mutable shell fields must be serialized on EVERY full-render path,
|
|
19
|
+
* otherwise absent fields are indistinguishable from "new app has no
|
|
20
|
+
* value" and the old app's value is dropped.
|
|
21
|
+
*
|
|
22
|
+
* A new document navigation (hard reload) applies these fields from the
|
|
23
|
+
* target app's initial payload.
|
|
24
|
+
*/
|
|
25
|
+
export interface AppShell {
|
|
26
|
+
/** Router identity. Used to namespace per-app client state (e.g. the
|
|
27
|
+
* rango-state localStorage key) so sibling apps on the same origin
|
|
28
|
+
* cannot observe each other's cache invalidations. */
|
|
29
|
+
routerId?: string;
|
|
30
|
+
rootLayout?: ComponentType<{ children: ReactNode }>;
|
|
31
|
+
basename?: string;
|
|
32
|
+
version?: string;
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
/**
|
|
36
|
+
* Mutable container for the active app shell. Read-through via `get()` so
|
|
37
|
+
* closures capture the ref, not the shell, and pick up updates at call time.
|
|
38
|
+
*/
|
|
39
|
+
export interface AppShellRef {
|
|
40
|
+
get(): AppShell;
|
|
41
|
+
update(next: AppShell): void;
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
export function createAppShellRef(initial: AppShell): AppShellRef {
|
|
45
|
+
let current = initial;
|
|
46
|
+
return {
|
|
47
|
+
get: () => current,
|
|
48
|
+
update: (next) => {
|
|
49
|
+
current = next;
|
|
50
|
+
},
|
|
51
|
+
};
|
|
52
|
+
}
|
|
@@ -5,6 +5,8 @@ import type {
|
|
|
5
5
|
ResolvedSegment,
|
|
6
6
|
} from "./types.js";
|
|
7
7
|
import { setAppVersion } from "./app-version.js";
|
|
8
|
+
import { setRangoStateLocal } from "./rango-state.js";
|
|
9
|
+
import type { AppShell, AppShellRef } from "./app-shell.js";
|
|
8
10
|
import * as React from "react";
|
|
9
11
|
import { startTransition } from "react";
|
|
10
12
|
import {
|
|
@@ -48,8 +50,13 @@ export { createNavigationTransaction };
|
|
|
48
50
|
*/
|
|
49
51
|
export interface NavigationBridgeConfigWithController extends NavigationBridgeConfig {
|
|
50
52
|
eventController: EventController;
|
|
51
|
-
/** RSC version from initial payload metadata */
|
|
53
|
+
/** RSC version from initial payload metadata (fallback when appShellRef is not provided) */
|
|
52
54
|
version?: string;
|
|
55
|
+
/**
|
|
56
|
+
* Live app-shell ref. When supplied, the bridge reads version/basename
|
|
57
|
+
* from this ref so cross-app navigations propagate correctly.
|
|
58
|
+
*/
|
|
59
|
+
appShellRef?: AppShellRef;
|
|
53
60
|
}
|
|
54
61
|
|
|
55
62
|
/**
|
|
@@ -68,9 +75,46 @@ export interface NavigationBridgeConfigWithController extends NavigationBridgeCo
|
|
|
68
75
|
export function createNavigationBridge(
|
|
69
76
|
config: NavigationBridgeConfigWithController,
|
|
70
77
|
): NavigationBridge {
|
|
71
|
-
const {
|
|
78
|
+
const {
|
|
79
|
+
store,
|
|
80
|
+
client,
|
|
81
|
+
eventController,
|
|
82
|
+
onUpdate,
|
|
83
|
+
renderSegments,
|
|
84
|
+
appShellRef,
|
|
85
|
+
} = config;
|
|
72
86
|
let version = config.version;
|
|
73
87
|
|
|
88
|
+
/**
|
|
89
|
+
* Replace the active app-shell snapshot atomically. Called by the partial
|
|
90
|
+
* updater when a response's routerId indicates the navigation crossed
|
|
91
|
+
* into a different app. Runs the local-only side-effects tied to
|
|
92
|
+
* app-shell fields (app version, rango-state namespace) so the new app
|
|
93
|
+
* owns them after the swap. Theme, warmup, and prefetch TTL are
|
|
94
|
+
* document-lifetime and are NOT touched here.
|
|
95
|
+
*/
|
|
96
|
+
function applyAppShell(next: AppShell): void {
|
|
97
|
+
if (appShellRef) {
|
|
98
|
+
appShellRef.update(next);
|
|
99
|
+
}
|
|
100
|
+
if (next.version !== undefined) {
|
|
101
|
+
version = next.version;
|
|
102
|
+
setAppVersion(next.version);
|
|
103
|
+
// Use the local-only setter — initRangoState writes the shared
|
|
104
|
+
// localStorage key and fires a storage event in other tabs still in
|
|
105
|
+
// the old app. setRangoStateLocal only mutates this tab's in-memory
|
|
106
|
+
// cache and rebinds it to the target app's routerId-scoped key,
|
|
107
|
+
// preserving the "local-only, no broadcast/rotation" contract for
|
|
108
|
+
// smooth app-switch transitions.
|
|
109
|
+
setRangoStateLocal(next.version, next.routerId);
|
|
110
|
+
}
|
|
111
|
+
// Cross-app: prior cache entries belong to a different app's segments.
|
|
112
|
+
// Drop them locally only — do NOT broadcast invalidation or rotate the
|
|
113
|
+
// shared X-Rango-State token, since other tabs still in the old app are
|
|
114
|
+
// unaffected by this tab's transition.
|
|
115
|
+
store.clearHistoryCacheLocal();
|
|
116
|
+
}
|
|
117
|
+
|
|
74
118
|
// Create shared partial updater
|
|
75
119
|
const fetchPartialUpdate = createPartialUpdater({
|
|
76
120
|
store,
|
|
@@ -78,6 +122,7 @@ export function createNavigationBridge(
|
|
|
78
122
|
onUpdate,
|
|
79
123
|
renderSegments,
|
|
80
124
|
getVersion: () => version,
|
|
125
|
+
applyAppShell,
|
|
81
126
|
});
|
|
82
127
|
|
|
83
128
|
return {
|
|
@@ -271,10 +316,14 @@ export function createNavigationBridge(
|
|
|
271
316
|
!cached?.stale &&
|
|
272
317
|
!options?._skipCache;
|
|
273
318
|
|
|
319
|
+
// Forward navigations always await fetchPartialUpdate before rendering,
|
|
320
|
+
// so useNavigation should always report "loading". skipLoadingState is
|
|
321
|
+
// only used for popstate background revalidation (line ~526) where
|
|
322
|
+
// cached content renders instantly without a network wait.
|
|
274
323
|
const tx = createNavigationTransaction(store, eventController, url, {
|
|
275
324
|
...options,
|
|
276
325
|
state: resolvedState,
|
|
277
|
-
skipLoadingState:
|
|
326
|
+
skipLoadingState: false,
|
|
278
327
|
});
|
|
279
328
|
|
|
280
329
|
// REVALIDATE: Fetch fresh data from server
|
|
@@ -286,7 +335,7 @@ export function createNavigationBridge(
|
|
|
286
335
|
: options?._skipCache
|
|
287
336
|
? [] // Action redirect: send no segments so server renders everything fresh
|
|
288
337
|
: undefined,
|
|
289
|
-
|
|
338
|
+
false,
|
|
290
339
|
tx.handle.signal,
|
|
291
340
|
tx.with({
|
|
292
341
|
url,
|
|
@@ -414,6 +463,15 @@ export function createNavigationBridge(
|
|
|
414
463
|
eventController.abortAllActions();
|
|
415
464
|
}
|
|
416
465
|
|
|
466
|
+
// Popstate that exits an intercept to a non-intercept destination. The
|
|
467
|
+
// fallback fetch path below needs `leave-intercept` mode so it filters
|
|
468
|
+
// the cached @modal segment from the request and forces a re-render —
|
|
469
|
+
// otherwise a cache-miss popstate whose server response has an empty
|
|
470
|
+
// diff hits the "no changes" branch in partial-update and the modal
|
|
471
|
+
// stays on screen.
|
|
472
|
+
const isLeavingIntercept =
|
|
473
|
+
!isIntercept && currentInterceptSource !== null;
|
|
474
|
+
|
|
417
475
|
// Compute history key from URL (with intercept suffix if applicable)
|
|
418
476
|
const historyKey = generateHistoryKey(url, { intercept: isIntercept });
|
|
419
477
|
|
|
@@ -564,7 +622,11 @@ export function createNavigationBridge(
|
|
|
564
622
|
intercept: isIntercept,
|
|
565
623
|
interceptSourceUrl,
|
|
566
624
|
}),
|
|
567
|
-
isIntercept
|
|
625
|
+
isIntercept
|
|
626
|
+
? { type: "navigate", interceptSourceUrl }
|
|
627
|
+
: isLeavingIntercept
|
|
628
|
+
? { type: "leave-intercept" }
|
|
629
|
+
: undefined,
|
|
568
630
|
);
|
|
569
631
|
// Restore scroll position after fetch completes
|
|
570
632
|
handleNavigationEnd({ restore: true, isStreaming });
|
|
@@ -647,6 +709,10 @@ export function createNavigationBridge(
|
|
|
647
709
|
setAppVersion(newVersion);
|
|
648
710
|
store.clearHistoryCache();
|
|
649
711
|
},
|
|
712
|
+
|
|
713
|
+
updateAppShell(next: AppShell): void {
|
|
714
|
+
applyAppShell(next);
|
|
715
|
+
},
|
|
650
716
|
};
|
|
651
717
|
}
|
|
652
718
|
|