@uniflowed/router 0.0.0-alpha.8 → 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (49) hide show
  1. package/action.js +324 -0
  2. package/client.js +261 -7
  3. package/handler.js +113 -99
  4. package/http-client.js +104 -0
  5. package/index.js +49 -6
  6. package/instrumentation.js +92 -0
  7. package/internal/action-endpoint.js +438 -0
  8. package/internal/action-wire.js +608 -0
  9. package/internal/base-path.js +175 -0
  10. package/internal/boundaries.js +481 -0
  11. package/internal/boundary-data.js +88 -0
  12. package/internal/compose.js +490 -0
  13. package/internal/deployment.js +160 -0
  14. package/internal/devtools.js +131 -0
  15. package/internal/diagnostics.js +169 -0
  16. package/internal/error-view.js +193 -0
  17. package/internal/flight-browser.js +242 -0
  18. package/internal/flight-chunks.js +205 -0
  19. package/internal/flight-rows.js +135 -0
  20. package/internal/flight-ssr.js +91 -0
  21. package/internal/flight.js +192 -0
  22. package/internal/head.js +219 -0
  23. package/internal/hydration.js +1085 -0
  24. package/internal/inspector.js +626 -0
  25. package/internal/native-links.js +67 -0
  26. package/internal/native-tree.js +89 -0
  27. package/internal/navigation-cache.js +181 -0
  28. package/internal/payload-rows.js +270 -0
  29. package/internal/payload.js +685 -0
  30. package/internal/prepare-document.js +54 -0
  31. package/internal/react-version.js +77 -0
  32. package/internal/resolve.js +1617 -0
  33. package/internal/resolved-summary.js +199 -0
  34. package/internal/routing.js +478 -0
  35. package/internal/runtime.js +1597 -1329
  36. package/internal/server-instrumentation.js +12 -0
  37. package/internal/server-route.js +58 -0
  38. package/internal/shell.js +125 -0
  39. package/internal/stream.js +754 -21
  40. package/middleware.js +161 -22
  41. package/native-navigation.js +217 -0
  42. package/native.js +416 -0
  43. package/package.json +48 -7
  44. package/routing.js +51 -0
  45. package/rsc-client.js +120 -0
  46. package/rsc-ssr.js +637 -0
  47. package/rsc.js +402 -0
  48. package/server-components.js +159 -0
  49. package/server.js +254 -106
package/middleware.js CHANGED
@@ -2,13 +2,13 @@
2
2
  //
3
3
  // Middleware: what runs before a path answers, whatever answers it.
4
4
  //
5
- // `app/dashboard/_uf.middleware.js` guards `/dashboard` and everything under
5
+ // `app/dashboard/$middleware.js` guards `/dashboard` and everything under
6
6
  // it — the pages, the route handlers, and the paths under it that match
7
7
  // nothing at all. There is no `matcher` to write because the directory the
8
8
  // file sits in *is* the matcher, which is the same composition rule layouts
9
9
  // already use and the reason uf does not inherit Next's regular expressions.
10
10
  //
11
- // // app/dashboard/_uf.middleware.js
11
+ // // app/dashboard/$middleware.js
12
12
  // // @flow
13
13
  // import { cookies } from "@uniflowed/server";
14
14
  //
@@ -27,10 +27,38 @@
27
27
  // that could only observe would not be able to reject, and one that had to
28
28
  // answer could not be a logger.
29
29
  //
30
- // There is no `next()` and no way to rewrite the request. Rewriting needs a
31
- // spelling — a returned `Request`, or a `next(request)` argument — and picking
32
- // one badly is harder to undo than not having it, so it is not spelled here
33
- // yet. What exists answers or continues, and says so.
30
+ // There is no `next()`. A third answer is `rewrite(destination)`: serve another
31
+ // route of this application at the address the visitor asked for.
32
+ //
33
+ // // app/$middleware.js
34
+ // import { rewrite } from "@uniflowed/router/middleware";
35
+ //
36
+ // export default function middleware(request: Request) {
37
+ // if (cookies().get("beta") != null) return rewrite("/beta" + new URL(request.url).pathname);
38
+ // }
39
+ //
40
+ // A returned value rather than a returned `Request`, which was the other
41
+ // spelling on the table. A `Request` could change the method and the headers
42
+ // too, and `headers()` reads the request the host began — so a middleware that
43
+ // added a header would have handed the page one set of headers and `headers()`
44
+ // another. A rewrite changes the path, the query when it names one, and
45
+ // nothing else.
46
+ //
47
+ // # A rewrite runs the destination's middleware
48
+ //
49
+ // The chain starts again from the root over the middleware that has not run
50
+ // yet, against the new path. So a rewrite into `/admin` passes the guard on
51
+ // `/admin` exactly as a request for it would, and is never an unguarded way to
52
+ // a guarded page; a middleware that already ran for this request does not run
53
+ // a second time, which is also what makes the loop finite.
54
+ //
55
+ // # A payload request is its document
56
+ //
57
+ // A browser navigating a React Server Components application asks for
58
+ // `/pricing/__uf.flight` rather than `/pricing`. The chain is matched against,
59
+ // and every middleware is handed, the document's URL — so the check a
60
+ // middleware writes against `/pricing` holds for a client navigation too, and
61
+ // a rewrite of the document becomes a rewrite of its payload.
34
62
  //
35
63
  // # The request it runs inside
36
64
  //
@@ -38,9 +66,18 @@
38
66
  // `@uniflowed/server/host`, once per request, around everything that answers
39
67
  // it — and the guard, the handler or page underneath it, and the render all
40
68
  // see that one context. So `cookies()` in a guard and `cookies()` in the page
41
- // it guards are the same cookies, `draftMode().enable()` in a guard is visible
42
- // to what it guards, and every `after()` on the request is one ordered list
43
- // the host drains after the response has gone.
69
+ // it guards are the same cookies, `draftMode().isEnabled` gives a guard and
70
+ // the page under it the same answer, and every `after()` on the request is one
71
+ // ordered list the host drains after the response has gone.
72
+ //
73
+ // *Changing* draft mode is not a guard's to do, and that is a separate rule
74
+ // with a separate reason: `enable()` writes a cookie, a cookie is part of a
75
+ // response, and a guard may decline — so a guard that turned draft mode on and
76
+ // then let the request through would have made a decision with nowhere to be
77
+ // written. `asResponder` marks the two calls that do own a response, a route
78
+ // handler and a server action, and `draftMode().enable()` refuses anywhere
79
+ // else by name. A guard that wants draft mode on answers with a redirect to
80
+ // the handler that turns it on. See ubugeeei-prod/uf#282.
44
81
  //
45
82
  // It used to be the other way, and it is worth saying why that was wrong
46
83
  // rather than merely different: this module built its own context and drained
@@ -59,6 +96,7 @@
59
96
  // `routesModuleSource` keeps the middleware table in an export the client
60
97
  // never imports, for the same reason it does that with route handlers.
61
98
 
99
+ import { documentPathOf, flightUrl } from "./internal/flight.js";
62
100
  import { requireRequest } from "./internal/request.js";
63
101
  import type { RouteParams } from "./internal/runtime.js";
64
102
 
@@ -70,11 +108,39 @@ export type MiddlewareContext = {|
70
108
  readonly searchParams: URLSearchParams,
71
109
  |};
72
110
 
111
+ /**
112
+ * What a middleware returns to serve another route at the requested address.
113
+ *
114
+ * Built by [`rewrite`] and read by the runner; a class so that the runner can
115
+ * tell it from a `Response` without trusting the shape of an object.
116
+ */
117
+ export class Rewrite {
118
+ readonly destination: string;
119
+
120
+ constructor(destination: string) {
121
+ this.destination = destination;
122
+ }
123
+ }
124
+
125
+ /**
126
+ * Serve `destination` — a path of this application — in place of the path the
127
+ * request named.
128
+ *
129
+ * Relative to the request, so `"/beta/pricing"` and `"../pricing"` both work.
130
+ * A destination that names no query keeps the request's; one that names a
131
+ * query replaces it. Another origin is refused when the middleware returns it:
132
+ * sending a visitor elsewhere is `Response.redirect`, and proxying to another
133
+ * server is a route handler that fetches.
134
+ */
135
+ export function rewrite(destination: string | URL): Rewrite {
136
+ return new Rewrite(typeof destination === "string" ? destination : destination.href);
137
+ }
138
+
73
139
  /** One middleware function. */
74
140
  export type Middleware = (
75
141
  request: Request,
76
142
  context: MiddlewareContext,
77
- ) => Response | void | Promise<Response | void>;
143
+ ) => Response | Rewrite | void | Promise<Response | Rewrite | void>;
78
144
 
79
145
  /** A middleware module, as the generated table loads it. */
80
146
  export type MiddlewareModule = { readonly [name: string]: mixed };
@@ -91,7 +157,10 @@ export type MiddlewareRecord = {|
91
157
  * Build the middleware runner for one application.
92
158
  *
93
159
  * Returns `null` when every middleware on the path declined, which is the
94
- * caller's signal to carry on to the handler or the page.
160
+ * caller's signal to carry on to the handler or the page. Returns a `Request`
161
+ * when one of them rewrote: the same request at the destination, which the
162
+ * caller carries on with instead — and which has already been past the
163
+ * destination's middleware.
95
164
  *
96
165
  * The runner is called once per request, above both the dispatcher and the
97
166
  * renderer, rather than from inside each of them. Putting the call inside
@@ -103,7 +172,7 @@ export type MiddlewareRecord = {|
103
172
  */
104
173
  export function createMiddlewareRunner(options: {|
105
174
  readonly middleware: $ReadOnlyArray<MiddlewareRecord>,
106
- |}): (request: Request) => Promise<Response | null> {
175
+ |}): (request: Request) => Promise<Response | Request | null> {
107
176
  // Root first, so an application-wide check runs before the one that guards a
108
177
  // section of it. A shorter path is always an ancestor of a longer one that
109
178
  // also matched, so segment count is the whole of the ordering.
@@ -111,7 +180,7 @@ export function createMiddlewareRunner(options: {|
111
180
  (a, b) => segmentsOf(a.path).length - segmentsOf(b.path).length,
112
181
  );
113
182
 
114
- return async function runMiddleware(request: Request): Promise<Response | null> {
183
+ return async function runMiddleware(request: Request): Promise<Response | Request | null> {
115
184
  // Checked rather than assumed, and checked before the table so that a host
116
185
  // is caught on its first request whether or not this project happens to
117
186
  // have a middleware. `createApplicationHandler` makes the same argument
@@ -129,39 +198,109 @@ export function createMiddlewareRunner(options: {|
129
198
  return null;
130
199
  }
131
200
 
132
- const url = new URL(request.url);
201
+ const arrived = new URL(request.url);
202
+ const document = documentPathOf(arrived.pathname);
203
+ // The URL the chain is matched against and every middleware is handed: the
204
+ // document's, for a payload request. See "A payload request is its
205
+ // document" above.
206
+ let url = document == null ? arrived : withPathname(arrived, document);
207
+ let seen = document == null ? request : requestAt(request, url);
208
+ let rewritten = false;
209
+ const ran: Set<MiddlewareRecord> = new Set();
133
210
 
134
- for (const record of table) {
211
+ for (let index = 0; index < table.length; index += 1) {
212
+ const record = table[index];
213
+ if (ran.has(record)) {
214
+ continue;
215
+ }
135
216
  const params = matchPrefix(record.path, url.pathname);
136
217
  if (params == null) {
137
218
  continue;
138
219
  }
220
+ ran.add(record);
139
221
 
140
222
  const middleware = pick(await record.load(), record.file);
141
223
  // In the host's context, not one of this module's own. Two middleware on
142
224
  // the same path see the same cookies, and so does the handler or the page
143
- // underneath them: `draftMode().enable()` in a guard is visible to what
144
- // it guards, and every `after()` on the request lands in one ordered list
225
+ // underneath them: `draftMode().isEnabled` is one answer for the whole
226
+ // request, and every `after()` on the request lands in one ordered list
145
227
  // that the host drains once, after the response has gone.
146
- const result = await middleware(request, { params, searchParams: url.searchParams });
147
- if (result != null) {
148
- return result;
228
+ const result = await middleware(seen, { params, searchParams: url.searchParams });
229
+ if (result == null) {
230
+ continue;
231
+ }
232
+ if (result instanceof Rewrite) {
233
+ url = destinationOf(result.destination, url, record.file);
234
+ seen = requestAt(seen, url);
235
+ rewritten = true;
236
+ // From the root again, over what has not run: the destination's guards
237
+ // are owed their say, and the ones that already had it are not asked
238
+ // twice.
239
+ index = -1;
240
+ continue;
149
241
  }
242
+ return result;
150
243
  }
151
244
 
152
- return null;
245
+ if (!rewritten) {
246
+ return null;
247
+ }
248
+ return document == null
249
+ ? seen
250
+ : requestAt(seen, new URL(flightUrl(url.pathname + url.search), url));
153
251
  };
154
252
  }
155
253
 
254
+ /**
255
+ * Where a rewrite goes, resolved against the URL the middleware was handed.
256
+ *
257
+ * Refused by name when it leaves the origin, because the one thing a rewrite
258
+ * promises is that this application answers.
259
+ */
260
+ function destinationOf(destination: string, base: URL, file: string): URL {
261
+ const next = new URL(destination, base);
262
+ if (next.origin !== base.origin) {
263
+ throw new Error(
264
+ `${file} rewrote ${base.pathname} to ${destination}, which is another origin. A rewrite ` +
265
+ "serves another route of this application: answer with `Response.redirect` to send the " +
266
+ "visitor elsewhere, or fetch the other server from a route handler.",
267
+ );
268
+ }
269
+ if (!destination.includes("?")) {
270
+ next.search = base.search;
271
+ }
272
+ next.hash = "";
273
+ return next;
274
+ }
275
+
276
+ function withPathname(url: URL, pathname: string): URL {
277
+ const next = new URL(url.href);
278
+ next.pathname = pathname;
279
+ return next;
280
+ }
281
+
282
+ /**
283
+ * `request` at another URL: same method, headers, signal and body.
284
+ *
285
+ * A `Request` is a valid `RequestInit`, so a streamed body is handed on rather
286
+ * than read.
287
+ */
288
+ function requestAt(request: Request, url: URL): Request {
289
+ // $FlowFixMe[incompatible-call] - a `Request` is read as the `RequestInit` it satisfies.
290
+ return new Request(url.href, request);
291
+ }
292
+
156
293
  /**
157
294
  * The function a middleware module exports.
158
295
  *
159
296
  * `default` or `middleware`, the same two spellings a page offers for its
160
297
  * component. Anything else is an authoring mistake and throws rather than
161
- * being skipped: a file named `_uf.middleware.js` that the router quietly
298
+ * being skipped: a file named `$middleware.js` that the router quietly
162
299
  * ignored is the bug this whole module exists to stop happening.
163
300
  */
164
301
  function pick(module: MiddlewareModule, file: string): Middleware {
302
+ // `rewrite` is an export a middleware module may well import, and is never
303
+ // the middleware itself.
165
304
  const exported = typeof module.default === "function" ? module.default : module.middleware;
166
305
  if (typeof exported !== "function") {
167
306
  throw new Error(
@@ -0,0 +1,217 @@
1
+ // @flow
2
+ import * as React from "react";
3
+ import { Pressable } from "react-native";
4
+ import {
5
+ CommonActions,
6
+ NavigationContainer,
7
+ StackActions,
8
+ createNavigationContainerRef,
9
+ useRoute,
10
+ } from "@react-navigation/native";
11
+ import { resolveNativeNavigation, createNativeRouter, createNativeLinking } from "./native.js";
12
+ import type { NativeLinkSource } from "./native.js";
13
+ import type { RouteTable } from "./internal/routing.js";
14
+ import type {
15
+ NativeLayout,
16
+ NativeNode,
17
+ NativeTree,
18
+ NavigationPayload,
19
+ NavigationState,
20
+ } from "./internal/native-tree.js";
21
+ import { nativeTree, stateForPath, hrefFromState, paramsForPath } from "./internal/native-tree.js";
22
+
23
+ export interface NavigatorPair {
24
+ readonly Navigator: React.ComponentType<{ ... }>;
25
+ readonly Screen: React.ComponentType<{ ... }>;
26
+ }
27
+ export type FileRouter = {
28
+ readonly push: (href: string) => void,
29
+ readonly replace: (href: string) => void,
30
+ readonly back: () => void,
31
+ readonly prefetch: (href: string) => Promise<void>,
32
+ };
33
+ type Scope = {
34
+ tree: NativeTree,
35
+ node: NativeNode,
36
+ screens: Map<NativeNode, React.ComponentType<{ ... }>>,
37
+ stack: NavigatorPair,
38
+ tabs: ?NavigatorPair,
39
+ router: FileRouter,
40
+ };
41
+ const ScopeContext: React.Context<Scope | null> = React.createContext(null);
42
+
43
+ function useScope(): Scope {
44
+ const scope = React.useContext(ScopeContext);
45
+ if (scope == null)
46
+ throw new Error(
47
+ "Native navigation: mount createNativeNavigation().Root before using its navigator or hooks",
48
+ );
49
+ return scope;
50
+ }
51
+
52
+ /** The application supplies its own React Navigation navigator factories. */
53
+ export function createNativeNavigation(options: {
54
+ table: RouteTable<>,
55
+ layouts: $ReadOnlyArray<NativeLayout>,
56
+ stack: NavigatorPair,
57
+ tabs?: NavigatorPair,
58
+ initialHref?: string,
59
+ links?: NativeLinkSource,
60
+ }): { Root: React.ComponentType<{ ... }>, router: FileRouter, linking: { ... } } {
61
+ const { table, layouts, stack, tabs } = options;
62
+ const tree = nativeTree(table, layouts);
63
+ const ref = createNavigationContainerRef();
64
+ const screens = new Map<NativeNode, React.ComponentType<{ ... }>>();
65
+ const resolve = (href: string): { names: $ReadOnlyArray<string>, payload: NavigationPayload } => {
66
+ const event = resolveNativeNavigation(table, href);
67
+ const names = tree.paths.get(event.route);
68
+ if (names == null) throw new Error(`Native navigation: no screen for ${event.route}`);
69
+ return { names, payload: { ufHref: event.href, ufParams: event.params } };
70
+ };
71
+ function actionFor(
72
+ names: $ReadOnlyArray<string>,
73
+ payload: NavigationPayload,
74
+ kind: "push" | "replace",
75
+ ): { readonly [string]: mixed } {
76
+ if (!ref.isReady()) throw new Error("Native navigation: NavigationContainer is not ready");
77
+ let state: NavigationState = ref.getRootState();
78
+ let depth = 0;
79
+ while (depth < names.length - 1) {
80
+ const active = state.routes[state.index ?? 0];
81
+ if (active?.name !== names[depth] || active?.state == null) break;
82
+ state = active.state;
83
+ depth += 1;
84
+ }
85
+ const name = names[depth];
86
+ const params = paramsForPath(names.slice(depth + 1), payload);
87
+ const action =
88
+ state.type === "stack"
89
+ ? StackActions[kind](name, params)
90
+ : CommonActions.navigate({ name, params });
91
+ return { ...action, target: state.key };
92
+ }
93
+ function navigate(href: string, kind: "push" | "replace"): void {
94
+ const { names, payload } = resolve(href);
95
+ ref.dispatch(actionFor(names, payload, kind));
96
+ }
97
+ const router: FileRouter = {
98
+ push: (href) => navigate(href, "push"),
99
+ replace: (href) => navigate(href, "replace"),
100
+ back: () => {
101
+ if (ref.canGoBack()) ref.goBack();
102
+ },
103
+ prefetch: createNativeRouter(table, {}).prefetch,
104
+ };
105
+ const source = options.links == null ? null : createNativeLinking(table, options.links);
106
+ const linking = {
107
+ prefixes: [""],
108
+ getInitialURL: source?.getInitialURL ?? (async () => null),
109
+ subscribe: source?.subscribe ?? (() => () => {}),
110
+ getStateFromPath: (href: string) => {
111
+ const { names, payload } = resolve(
112
+ href.startsWith("/") || /^[A-Za-z][A-Za-z0-9+.-]*:/.test(href) ? href : `/${href}`,
113
+ );
114
+ return stateForPath(names, payload);
115
+ },
116
+ getPathFromState: (state: NavigationState) => hrefFromState(state) ?? "/",
117
+ getActionFromState: (state: NavigationState) => {
118
+ const href = hrefFromState(state);
119
+ if (href == null) return undefined;
120
+ const { names, payload } = resolve(href);
121
+ return actionFor(names, payload, "push");
122
+ },
123
+ };
124
+ function build(node: NativeNode): React.ComponentType<{ ... }> {
125
+ const load = node.module;
126
+ const Content =
127
+ load == null
128
+ ? Stack
129
+ : React.lazy(async () => {
130
+ const module: $FlowFixMe = await load();
131
+ const Component = module.default ?? (node.layout ? module.Layout : module.Page);
132
+ if (
133
+ typeof Component !== "function" &&
134
+ (Component == null || typeof Component !== "object")
135
+ ) {
136
+ throw new Error(
137
+ `Native navigation: ${node.name} must export ${node.layout ? "Layout" : "Page"} or default`,
138
+ );
139
+ }
140
+ return { default: Component };
141
+ });
142
+ function Screen(props: { ... }): React.Node {
143
+ return (
144
+ <ScopeContext value={{ tree, node, screens, stack, tabs, router }}>
145
+ <React.Suspense fallback={null}>
146
+ <Content {...props} />
147
+ </React.Suspense>
148
+ </ScopeContext>
149
+ );
150
+ }
151
+ screens.set(node, Screen);
152
+ for (const child of node.children) build(child);
153
+ return Screen;
154
+ }
155
+ const RootScreen = build(tree.root);
156
+ const initialState =
157
+ options.initialHref == null ? undefined : linking.getStateFromPath(options.initialHref);
158
+ function Root(props: { ... }): React.Node {
159
+ return (
160
+ <NavigationContainer {...props} ref={ref} linking={linking} initialState={initialState}>
161
+ <RootScreen />
162
+ </NavigationContainer>
163
+ );
164
+ }
165
+ return { Root, router, linking };
166
+ }
167
+
168
+ /** Any React Navigation navigator can consume this segment's direct children. */
169
+ export component Navigator(navigator: NavigatorPair, ...props: { ... }) {
170
+ const scope = useScope();
171
+ const Container = navigator.Navigator;
172
+ const Screen = navigator.Screen;
173
+ return (
174
+ <Container {...props}>
175
+ {scope.node.children.map((node) => (
176
+ <Screen key={node.name} name={node.name} component={scope.screens.get(node)} />
177
+ ))}
178
+ </Container>
179
+ );
180
+ }
181
+
182
+ export component Stack(...props: { ... }) {
183
+ return <Navigator {...props} navigator={useScope().stack} />;
184
+ }
185
+
186
+ export component Tabs(...props: { ... }) {
187
+ const tabs = useScope().tabs;
188
+ if (tabs == null)
189
+ throw new Error("Native navigation: supply the app's tab navigator to createNativeNavigation");
190
+ return <Navigator {...props} navigator={tabs} />;
191
+ }
192
+
193
+ export function useNativeRouter(): FileRouter {
194
+ return useScope().router;
195
+ }
196
+ export function useParams(): { readonly [string]: string | $ReadOnlyArray<string> } {
197
+ const route = useRoute();
198
+ return route.params?.ufParams ?? {};
199
+ }
200
+
201
+ export component Link(
202
+ href: string,
203
+ children: React.Node,
204
+ replace: boolean = false,
205
+ ...props: { ... }
206
+ ) {
207
+ const router = useNativeRouter();
208
+ return (
209
+ <Pressable
210
+ {...props}
211
+ accessibilityRole="link"
212
+ onPress={() => (replace ? router.replace(href) : router.push(href))}
213
+ >
214
+ {children}
215
+ </Pressable>
216
+ );
217
+ }