@uniflowed/router 0.0.0-alpha.6 → 0.0.0-alpha.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.
@@ -11,6 +11,7 @@
11
11
 
12
12
  import * as React from "react";
13
13
  import {
14
+ Suspense,
14
15
  createContext,
15
16
  startTransition,
16
17
  useCallback,
@@ -99,6 +100,37 @@ export type LayoutModule = {
99
100
  ...
100
101
  };
101
102
 
103
+ /**
104
+ * What an error module may export. The component is `default` or `Error`.
105
+ *
106
+ * `Error` shadows the global inside the file that writes it, which is the
107
+ * cost of naming the export after what it is; a file that needs the
108
+ * constructor still has `globalThis.Error`. The alternative was a name the
109
+ * convention would have to explain — `ErrorPage`, `Boundary` — for a file
110
+ * whose whole job is already in its name.
111
+ */
112
+ export type ErrorModule = {
113
+ readonly default?: RouteComponent,
114
+ readonly Error?: RouteComponent,
115
+ readonly metadata?: Metadata,
116
+ ...
117
+ };
118
+
119
+ /**
120
+ * What a loading module may export. The component is `default` or `Loading`.
121
+ *
122
+ * No `metadata`, and that is the type saying something true rather than an
123
+ * omission. A fallback renders while the route is still resolving, and the
124
+ * route's metadata was decided before the first byte — a title on a file that
125
+ * renders after the head has gone could never be used. `packages/web/head.js`
126
+ * documents the same constraint from the other side.
127
+ */
128
+ export type LoadingModule = {
129
+ readonly default?: RouteComponent,
130
+ readonly Loading?: RouteComponent,
131
+ ...
132
+ };
133
+
102
134
  /** Document metadata a page or layout declares. */
103
135
  export type Metadata = {
104
136
  readonly title?: string,
@@ -130,22 +162,90 @@ export type RouteRecord = {|
130
162
  readonly params: $ReadOnlyArray<RouteParamSpec>,
131
163
  readonly mdx: boolean,
132
164
  readonly file: string,
133
- readonly page: () => Promise<PageModule>,
165
+ /**
166
+ * The page module — absent when this table cannot render the route.
167
+ *
168
+ * The server's table always has one: the server renders every route. The
169
+ * browser's may not. `@uniflowed/vite` leaves the page out of the client
170
+ * route table when uf's server-component analysis finds no `"use client"`
171
+ * boundary reachable from the page, its layouts or its fallbacks, and with
172
+ * the `import()` gone so is the whole subtree it reached — which is the
173
+ * point of leaving it out.
174
+ *
175
+ * The route stays in the table because the router still has to *match* the
176
+ * URL. Matching is what tells a `Link` that the destination is a document
177
+ * the browser must fetch rather than a page this bundle can render; a route
178
+ * missing from the table entirely would be a 404 instead. See
179
+ * [`hasClientPage`], which is the question every caller asks.
180
+ */
181
+ readonly page?: () => Promise<PageModule>,
134
182
  readonly layouts: $ReadOnlyArray<() => Promise<LayoutModule>>,
183
+ /**
184
+ * The `<Suspense>` boundaries this route renders inside, root first.
185
+ *
186
+ * Optional because a table written before `_uf.loading.js` existed — a
187
+ * hand-written one in a test, a server bundle built by an older `uf` —
188
+ * is still a table this router can render, and a route with no boundary is
189
+ * exactly what it had before.
190
+ */
191
+ readonly loading?: $ReadOnlyArray<LoadingRecord>,
135
192
  |};
136
193
 
137
- /** The not-found page, when the app declares one. */
138
- export type NotFoundRecord = {|
194
+ /**
195
+ * One `_uf.loading.js`, as the route table carries it.
196
+ *
197
+ * `above` is how many of the route's `layouts` are outside the boundary, which
198
+ * is the same number `ResolvedRoute["errorBoundary"].above` means and is
199
+ * spelled the same way on purpose: both answer "where in the stack of layouts
200
+ * does this thing sit", and there is no second vocabulary for it.
201
+ */
202
+ export type LoadingRecord = {|
203
+ readonly above: number,
204
+ readonly module: () => Promise<LoadingModule>,
205
+ |};
206
+
207
+ /**
208
+ * One not-found boundary: the page for a path under `path` that matched
209
+ * nothing.
210
+ *
211
+ * `_uf.not-found.js` is a segment file, so `path` is the route path of the
212
+ * directory that declares it and `layouts` are the layouts in scope *there* —
213
+ * which is what the boundary renders inside. A project with one at the router
214
+ * root has one of these; a project whose manual answers its own 404 has two.
215
+ */
216
+ export type NotFoundBoundary = {|
217
+ readonly path: string,
139
218
  readonly mdx: boolean,
140
219
  readonly file: string,
141
220
  readonly page: () => Promise<PageModule>,
142
221
  readonly layouts: $ReadOnlyArray<() => Promise<LayoutModule>>,
143
222
  |};
144
223
 
145
- /** A route table plus the not-found page. */
224
+ /**
225
+ * One error boundary: what renders in place of the subtree under `path` when
226
+ * something in it throws.
227
+ *
228
+ * The same nearest-ancestor shape as [`NotFoundBoundary`], and `layouts` means
229
+ * the same thing — the layouts in scope where the file is, which stay mounted
230
+ * around the error and are why the rest of the document is still there.
231
+ */
232
+ export type ErrorBoundary = {|
233
+ readonly path: string,
234
+ readonly file: string,
235
+ readonly module: () => Promise<ErrorModule>,
236
+ readonly layouts: $ReadOnlyArray<() => Promise<LayoutModule>>,
237
+ |};
238
+
239
+ /**
240
+ * A route table plus the boundaries declared under it.
241
+ *
242
+ * `errors` is the error boundaries a project declared, not failures that
243
+ * happened.
244
+ */
146
245
  export type RouteTable = {|
147
246
  readonly routes: $ReadOnlyArray<RouteRecord>,
148
- readonly notFound: ?NotFoundRecord,
247
+ readonly notFound: $ReadOnlyArray<NotFoundBoundary>,
248
+ readonly errors: $ReadOnlyArray<ErrorBoundary>,
149
249
  |};
150
250
 
151
251
  /** A URL matched against the table. */
@@ -154,7 +254,40 @@ export type RouteMatch = {|
154
254
  readonly params: RouteParams,
155
255
  |};
156
256
 
157
- /** A match whose modules are loaded and whose loader has run. */
257
+ /**
258
+ * Why the router is rendering an error boundary instead of a page.
259
+ *
260
+ * One union rather than one file convention per status. `forbidden()` and
261
+ * `unauthorized()` are not different *kinds* of file to write; they are
262
+ * different sentences an error page says, and `match` over this is where a
263
+ * page says all three and the checker confirms it covered them. Deciding it
264
+ * the other way — `_uf.forbidden.js` and `_uf.unauthorized.js` beside
265
+ * `_uf.error.js`, which is what Next.js does — is three files per segment to
266
+ * express one thing, and nothing would check that any of them handled the
267
+ * case it was named for.
268
+ *
269
+ * The thrown value is carried but deliberately not rendered by the default
270
+ * boundary: a server exception's message is written for the person who
271
+ * deployed the application, not for whoever asks for the page.
272
+ */
273
+ export type RouteError =
274
+ | {| readonly kind: "thrown", readonly error: mixed |}
275
+ | {| readonly kind: "unauthorized" |}
276
+ | {| readonly kind: "forbidden" |};
277
+
278
+ /** The status a `RouteError` answers with. */
279
+ export function routeErrorStatus(error: RouteError): 401 | 403 | 500 {
280
+ return match (error) {
281
+ {kind: "unauthorized"} => 401,
282
+ {kind: "forbidden"} => 403,
283
+ {kind: "thrown"} => 500,
284
+ };
285
+ }
286
+
287
+ /**
288
+ * A match whose modules are loaded and whose loader has run — or, when `error`
289
+ * is set, the error page that stands in for it.
290
+ */
158
291
  export type ResolvedRoute = {|
159
292
  readonly pathname: string,
160
293
  readonly search: string,
@@ -165,7 +298,36 @@ export type ResolvedRoute = {|
165
298
  readonly layouts: $ReadOnlyArray<LayoutModule>,
166
299
  readonly data: mixed,
167
300
  readonly metadata: Metadata,
168
- readonly status: 200 | 404,
301
+ readonly status: 200 | 401 | 403 | 404 | 500,
302
+ /**
303
+ * Set when this resolution *is* the error page: the loader threw, or the
304
+ * server render did and the renderer resolved again. `null` on the ordinary
305
+ * path.
306
+ */
307
+ readonly error: ?RouteError,
308
+ /**
309
+ * The boundary that would catch a throw while rendering this route.
310
+ *
311
+ * Always present, because every route has an answer for a throw: `module`
312
+ * is `null` when the project declares no `_uf.error.js` above the path, and
313
+ * the framework's own error page renders instead. `above` is how many of
314
+ * `layouts` are outside the boundary — the ones that stay mounted, which is
315
+ * what "the rest of the document is still interactive" means.
316
+ */
317
+ readonly errorBoundary: {|
318
+ readonly module: ?ErrorModule,
319
+ readonly above: number,
320
+ |},
321
+ /**
322
+ * The loading boundaries around this route, root first, already imported.
323
+ *
324
+ * Imported rather than lazy: React decides to render a fallback
325
+ * synchronously, during the render that suspended, so a module that is still
326
+ * being fetched is a module that is not there at the only moment it is
327
+ * wanted. Empty for a route with no `_uf.loading.js` above it, which is the
328
+ * ordinary case and renders exactly the tree it did before.
329
+ */
330
+ readonly loading: $ReadOnlyArray<{| readonly above: number, readonly module: LoadingModule |}>,
169
331
  |};
170
332
 
171
333
  /** Thrown by `notFound()`; the renderer answers with the not-found page. */
@@ -176,6 +338,22 @@ export class NotFoundError extends Error {
176
338
  }
177
339
  }
178
340
 
341
+ /** Thrown by `unauthorized()`; the renderer answers with the error boundary. */
342
+ export class UnauthorizedError extends Error {
343
+ constructor() {
344
+ super("unauthorized");
345
+ this.name = "UnauthorizedError";
346
+ }
347
+ }
348
+
349
+ /** Thrown by `forbidden()`; the renderer answers with the error boundary. */
350
+ export class ForbiddenError extends Error {
351
+ constructor() {
352
+ super("forbidden");
353
+ this.name = "ForbiddenError";
354
+ }
355
+ }
356
+
179
357
  /** Thrown by `redirect()`; the renderer answers with a redirect. */
180
358
  export class RedirectError extends Error {
181
359
  to: string;
@@ -267,6 +445,18 @@ function decodeSegment(segment: string): string {
267
445
  }
268
446
  }
269
447
 
448
+ /**
449
+ * Whether this table can render the route in the browser.
450
+ *
451
+ * False only in the client bundle, and only for a route uf decided ships no
452
+ * JavaScript. Every caller that would load a page asks this first, and the two
453
+ * answers are different actions rather than a success and a failure: render
454
+ * it, or let the browser fetch the document.
455
+ */
456
+ export function hasClientPage(route: RouteRecord): boolean {
457
+ return route.page != null;
458
+ }
459
+
270
460
  /**
271
461
  * Match a pathname against the table, preferring the most specific route.
272
462
  */
@@ -289,6 +479,60 @@ export function matchRoute(routes: $ReadOnlyArray<RouteRecord>, pathname: string
289
479
  return best;
290
480
  }
291
481
 
482
+ /**
483
+ * Whether a boundary declared at `segments` is at or above `parts`.
484
+ *
485
+ * The same segment kinds as [`matchSegments`], stopping when the boundary's
486
+ * own segments run out instead of requiring the path to: `/guide` covers
487
+ * `/guide/nope`, and `/guide` covers `/guide` itself.
488
+ */
489
+ function covers(segments: $ReadOnlyArray<Segment>, parts: $ReadOnlyArray<string>): boolean {
490
+ let index = 0;
491
+ for (const segment of segments) {
492
+ const next = match (segment) {
493
+ {kind: "static", value: const value} => parts[index] === value ? index + 1 : -1,
494
+ {kind: "param"} => index < parts.length ? index + 1 : -1,
495
+ {kind: "catchAll"} => parts.length,
496
+ };
497
+ if (next === -1) {
498
+ return false;
499
+ }
500
+ index = next;
501
+ }
502
+ return true;
503
+ }
504
+
505
+ /**
506
+ * The nearest boundary above `pathname`, or `null` when none covers it.
507
+ *
508
+ * The one rule both `_uf.not-found.js` and `_uf.error.js` are resolved by, and
509
+ * the same one layouts already follow: nearest means the longest path that
510
+ * covers the URL. It is decided here rather than by the table's order — the
511
+ * table is sorted by path so the generated module is stable, and a resolver
512
+ * that read "nearest" as "first" would silently depend on that sort. Two
513
+ * boundaries can share a path (a route group's directory does not appear in
514
+ * the URL), and then the first in the table wins.
515
+ */
516
+ function nearestBoundary<TBoundary: { readonly path: string, ... }>(
517
+ boundaries: $ReadOnlyArray<TBoundary>,
518
+ pathname: string,
519
+ ): ?TBoundary {
520
+ const parts = pathname.split("/").filter((part) => part !== "");
521
+ let best: ?TBoundary = null;
522
+ let bestDepth = -1;
523
+ for (const boundary of boundaries) {
524
+ const segments = compile(boundary.path);
525
+ if (!covers(segments, parts)) {
526
+ continue;
527
+ }
528
+ if (segments.length > bestDepth) {
529
+ best = boundary;
530
+ bestDepth = segments.length;
531
+ }
532
+ }
533
+ return best;
534
+ }
535
+
292
536
  /** Split a URL into its pathname and search string. */
293
537
  export function splitUrl(url: string): {| readonly pathname: string, readonly search: string |} {
294
538
  const hash = url.indexOf("#");
@@ -342,11 +586,39 @@ function loadOnce<T>(load: () => Promise<T>): Promise<T> {
342
586
  * `data` is what the loader returned; on the client after hydration it is the
343
587
  * value the server embedded, so the loader does not run twice for the first
344
588
  * page.
589
+ *
590
+ * # This resolves or redirects; it does not reject
591
+ *
592
+ * Everything a route can go wrong with is a route to render: no match and
593
+ * `notFound()` are the not-found boundary, a loader that threw and
594
+ * `forbidden()`/`unauthorized()` are the error boundary. Only `redirect()`
595
+ * comes back out, because a redirect is a response rather than a page and the
596
+ * caller is what has one to send.
597
+ *
598
+ * That guarantee is the point rather than a convenience. `hydrate` awaits this
599
+ * before `hydrateRoot`, so a rejection there is not an error page — it is no
600
+ * `hydrateRoot` call at all, and the document the server sent stays on screen
601
+ * with nothing attached to it.
345
602
  */
346
603
  export async function resolveMatch(
347
604
  table: RouteTable,
348
605
  url: string,
349
606
  options?: {| readonly data?: mixed, readonly skipLoader?: boolean |},
607
+ ): Promise<ResolvedRoute> {
608
+ try {
609
+ return await resolveRoute(table, url, options);
610
+ } catch (error) {
611
+ if (error instanceof RedirectError) {
612
+ throw error;
613
+ }
614
+ return resolveFailure(table, url, error);
615
+ }
616
+ }
617
+
618
+ async function resolveRoute(
619
+ table: RouteTable,
620
+ url: string,
621
+ options?: {| readonly data?: mixed, readonly skipLoader?: boolean |},
350
622
  ): Promise<ResolvedRoute> {
351
623
  const { pathname, search } = splitUrl(url);
352
624
  const searchParams = parseSearch(search);
@@ -356,21 +628,45 @@ export async function resolveMatch(
356
628
  return resolveNotFound(table, pathname, search, searchParams);
357
629
  }
358
630
 
631
+ const load = matched.route.page;
632
+ if (load == null) {
633
+ // Reachable only by asking this table to render a route it was built
634
+ // without. `hydrate` and every navigation check `hasClientPage` first and
635
+ // hand the URL to the browser instead, so arriving here means a caller
636
+ // went around them — and the honest answer is to say so rather than to
637
+ // render an empty page.
638
+ throw new Error(
639
+ `@uniflowed/router: ${matched.route.path} has no page in this route table; it ships no ` +
640
+ "client JavaScript, so the browser navigates to it rather than rendering it",
641
+ );
642
+ }
359
643
  const [page, ...layouts] = await Promise.all([
360
- loadOnce(matched.route.page),
644
+ loadOnce(load),
361
645
  ...matched.route.layouts.map((layout) => loadOnce(layout)),
362
646
  ]);
647
+ // Started here and awaited at the end: the boundary's module does not depend
648
+ // on the loader, so importing it alongside costs a navigation nothing. It
649
+ // never rejects, so an early throw below leaves no unhandled rejection.
650
+ const boundary = resolveErrorBoundary(table, pathname, matched.route.layouts.length);
651
+ // Started alongside for the same reason, and awaited at the end: a fallback
652
+ // depends on nothing the loader produces.
653
+ const loading = resolveLoading(matched.route, matched.route.layouts.length);
363
654
 
364
655
  let data: mixed = options?.data;
365
656
  if (options?.skipLoader !== true && typeof page.loader === "function") {
366
- try {
367
- data = await page.loader({ params: matched.params, searchParams, pathname });
368
- } catch (error) {
369
- if (error instanceof NotFoundError) {
370
- return resolveNotFound(table, pathname, search, searchParams);
371
- }
372
- throw error;
373
- }
657
+ // Awaited here, so a route's time to first byte is still its slowest
658
+ // loader. A page that suspends while *rendering* streams — that is what the
659
+ // `<Suspense>` boundaries below are for — but a page waiting on its loader
660
+ // has already waited by the time React sees the tree, so its fallback shows
661
+ // for no time at all.
662
+ //
663
+ // Deferring it means handing the page a promise and unwrapping it inside
664
+ // the boundary, and the obstacle is not the awaiting: it is that
665
+ // `generateMetadata` reads `data` and metadata goes in the head, and that
666
+ // the loader data is embedded in the head too, for hydration. Both are
667
+ // decisions about the document rather than about the route.
668
+ // ubugeeei-prod/uf#373 has the design.
669
+ data = await page.loader({ params: matched.params, searchParams, pathname });
374
670
  }
375
671
 
376
672
  const metadata = await resolveMetadata(page, layouts, {
@@ -389,16 +685,209 @@ export async function resolveMatch(
389
685
  data,
390
686
  metadata,
391
687
  status: 200,
688
+ error: null,
689
+ errorBoundary: await boundary,
690
+ loading: await loading,
691
+ };
692
+ }
693
+
694
+ /**
695
+ * The route's loading boundaries, imported.
696
+ *
697
+ * A boundary whose module will not load is dropped rather than thrown for, and
698
+ * this is the same judgement `resolveErrorBoundary` makes one function above: a
699
+ * fallback is what the router shows while it does not yet have the page, so a
700
+ * broken fallback must not become a broken page. The route renders without that
701
+ * boundary — the next one out, or the shell, waits for it instead — and the
702
+ * import error surfaces where it belongs, when the module is next asked for.
703
+ */
704
+ async function resolveLoading(
705
+ route: RouteRecord,
706
+ layoutCount: number,
707
+ ): Promise<$ReadOnlyArray<{| readonly above: number, readonly module: LoadingModule |}>> {
708
+ const records = route.loading ?? [];
709
+ if (records.length === 0) {
710
+ return [];
711
+ }
712
+ const loaded = await Promise.all(
713
+ records.map(async (record) => {
714
+ try {
715
+ return {
716
+ // Clamped exactly as the error boundary's is, and for the same
717
+ // reason: a `(group)` directory can leave a route with fewer layouts
718
+ // than the boundary that covers it.
719
+ above: Math.min(record.above, layoutCount),
720
+ module: await loadOnce(record.module),
721
+ };
722
+ } catch {
723
+ return null;
724
+ }
725
+ }),
726
+ );
727
+ return loaded.filter(Boolean);
728
+ }
729
+
730
+ /**
731
+ * The route to render after something threw.
732
+ *
733
+ * Two callers, one behaviour: [`resolveMatch`] when a loader or a module
734
+ * import threw, and `createRenderer` when the *render* did — React's error
735
+ * boundaries do not run in `renderToString`, so the server has to catch it
736
+ * itself and resolve again.
737
+ */
738
+ export async function resolveFailure(
739
+ table: RouteTable,
740
+ url: string,
741
+ error: mixed,
742
+ ): Promise<ResolvedRoute> {
743
+ const { pathname, search } = splitUrl(url);
744
+ const searchParams = parseSearch(search);
745
+ if (error instanceof NotFoundError) {
746
+ try {
747
+ return await resolveNotFound(table, pathname, search, searchParams);
748
+ } catch (failure) {
749
+ // The not-found page itself would not load. Falling through to the error
750
+ // boundary rather than rethrowing is what keeps the promise above: the
751
+ // page a project wrote to explain a 404 is not more load-bearing than
752
+ // the document staying on screen.
753
+ return resolveError(table, pathname, search, searchParams, routeErrorFor(failure));
754
+ }
755
+ }
756
+ return resolveError(table, pathname, search, searchParams, routeErrorFor(error));
757
+ }
758
+
759
+ /** What a thrown value means to the router. */
760
+ function routeErrorFor(error: mixed): RouteError {
761
+ if (error instanceof UnauthorizedError) {
762
+ return { kind: "unauthorized" };
763
+ }
764
+ if (error instanceof ForbiddenError) {
765
+ return { kind: "forbidden" };
766
+ }
767
+ return { kind: "thrown", error };
768
+ }
769
+
770
+ /**
771
+ * The error boundary a route renders inside, loaded with the route rather than
772
+ * when it is needed.
773
+ *
774
+ * React decides to show a boundary's fallback synchronously, during the render
775
+ * that threw. A module that still has to be imported is a module that is not
776
+ * there at the only moment it can be used, so this is one more dynamic import
777
+ * per navigation and not a lazy one.
778
+ *
779
+ * `above` is the boundary's own layout count, clamped to the route's. The
780
+ * first attempt compared the two layout arrays for a shared prefix, which is
781
+ * more precise when a `(group)` directory puts a boundary beside a route
782
+ * rather than above it — and it worked by *reference identity* of the loader
783
+ * functions, which holds only because `routesModuleSource` deduplicates them
784
+ * by file. A rule that depends on an invisible property of the generated
785
+ * module is a rule that reads as zero the moment a table is built any other
786
+ * way, and it did: it put the boundary outside the layouts it was written
787
+ * inside. Nesting a boundary per group needs parallel-route trees (#267);
788
+ * until then this is the honest approximation, and it is stated rather than
789
+ * inferred.
790
+ */
791
+ async function resolveErrorBoundary(
792
+ table: RouteTable,
793
+ pathname: string,
794
+ layoutCount: number,
795
+ ): Promise<{| readonly module: ?ErrorModule, readonly above: number |}> {
796
+ const boundary = nearestBoundary(table.errors, pathname);
797
+ if (boundary == null) {
798
+ return { module: null, above: 0 };
799
+ }
800
+ // Clamped, because a route group can leave a route with fewer layouts than
801
+ // the boundary covering it, and an `above` past the end would compose the
802
+ // layouts out of nothing.
803
+ const above = Math.min(boundary.layouts.length, layoutCount);
804
+ try {
805
+ return { module: await loadOnce(boundary.module), above };
806
+ } catch {
807
+ // A boundary whose module will not load cannot be the answer to a throw,
808
+ // and this is why the field is nullable: containment must not itself
809
+ // depend on an import working.
810
+ return { module: null, above: 0 };
811
+ }
812
+ }
813
+
814
+ /**
815
+ * The error page for `pathname`, inside the layouts above the boundary that
816
+ * answers it.
817
+ *
818
+ * The layouts are the boundary's, for the same reason [`resolveNotFound`]
819
+ * gives: they are what stays mounted around the error, and the layouts below
820
+ * the boundary belong to the subtree that just stopped.
821
+ */
822
+ async function resolveError(
823
+ table: RouteTable,
824
+ pathname: string,
825
+ search: string,
826
+ searchParams: SearchParams,
827
+ routeError: RouteError,
828
+ ): Promise<ResolvedRoute> {
829
+ const boundary = nearestBoundary(table.errors, pathname);
830
+ let module: ?ErrorModule = null;
831
+ let layouts: $ReadOnlyArray<LayoutModule> = [];
832
+ if (boundary != null) {
833
+ try {
834
+ [module, layouts] = await Promise.all([
835
+ loadOnce(boundary.module),
836
+ Promise.all(boundary.layouts.map((layout) => loadOnce(layout))),
837
+ ]);
838
+ } catch {
839
+ // See `resolveErrorBoundary`: the framework's own page answers instead.
840
+ module = null;
841
+ layouts = [];
842
+ }
843
+ }
844
+
845
+ const declared = await resolveMetadata(
846
+ module?.metadata != null ? { metadata: module.metadata } : {},
847
+ layouts,
848
+ { params: {}, searchParams, data: undefined },
849
+ );
850
+ return {
851
+ pathname,
852
+ search,
853
+ path: "*",
854
+ params: {},
855
+ searchParams,
856
+ page: { default: ResolvedErrorPage },
857
+ layouts,
858
+ data: undefined,
859
+ metadata: declared.title != null ? declared : { ...declared, title: errorTitle(routeError) },
860
+ status: routeErrorStatus(routeError),
861
+ error: routeError,
862
+ // All of the boundary's layouts are above it, and no inner boundary is
863
+ // inserted around a page that already is one; see `RouteView`.
864
+ errorBoundary: { module, above: layouts.length },
865
+ // An error page has nothing left to wait for: it renders the value it was
866
+ // resolved with. A fallback around it would be a boundary that can never
867
+ // show, which is worse than none.
868
+ loading: [],
392
869
  };
393
870
  }
394
871
 
872
+ /**
873
+ * The not-found page for `pathname`, inside the layouts above the boundary
874
+ * that answers it.
875
+ *
876
+ * The layouts are the *boundary's*, not the ones the URL had already matched.
877
+ * Taking the matched route's layouts was the other candidate and it is wrong
878
+ * in both directions: for an unmatched URL there is no matched route to take
879
+ * them from, and for `notFound()` thrown from a page they would keep the
880
+ * layouts *below* the boundary — so `app/guide/[slug]/_uf.layout.js` would
881
+ * wrap a 404 that `app/guide/_uf.not-found.js` answered, which is the layout
882
+ * of the page that just said it does not exist.
883
+ */
395
884
  async function resolveNotFound(
396
885
  table: RouteTable,
397
886
  pathname: string,
398
887
  search: string,
399
888
  searchParams: SearchParams,
400
889
  ): Promise<ResolvedRoute> {
401
- const record = table.notFound;
890
+ const record = nearestBoundary(table.notFound, pathname);
402
891
  if (record == null) {
403
892
  return {
404
893
  pathname,
@@ -411,6 +900,9 @@ async function resolveNotFound(
411
900
  data: undefined,
412
901
  metadata: { title: "Not found" },
413
902
  status: 404,
903
+ error: null,
904
+ errorBoundary: await resolveErrorBoundary(table, pathname, 0),
905
+ loading: [],
414
906
  };
415
907
  }
416
908
  const [page, ...layouts] = await Promise.all([
@@ -433,6 +925,13 @@ async function resolveNotFound(
433
925
  data: undefined,
434
926
  metadata,
435
927
  status: 404,
928
+ error: null,
929
+ // A not-found page is a page: one that throws is contained like any other.
930
+ errorBoundary: await resolveErrorBoundary(table, pathname, layouts.length),
931
+ // A not-found boundary is matched, not nested: `nearestBoundary` picked one
932
+ // record and the loading files are a property of the route that was walked
933
+ // to, which this URL never reached. Nothing to wait for, so no boundary.
934
+ loading: [],
436
935
  };
437
936
  }
438
937
 
@@ -474,6 +973,157 @@ component DefaultNotFound() {
474
973
  );
475
974
  }
476
975
 
976
+ /** The document title an error page gets when nothing declared one. */
977
+ function errorTitle(error: RouteError): string {
978
+ return match (error) {
979
+ {kind: "unauthorized"} => "Sign in required",
980
+ {kind: "forbidden"} => "Not allowed",
981
+ {kind: "thrown"} => "Something went wrong",
982
+ };
983
+ }
984
+
985
+ /**
986
+ * The framework's error page, for a project that declares no `_uf.error.js`.
987
+ *
988
+ * It says which of the three happened and offers the reset, and it does *not*
989
+ * print the thrown error: on the server that message is written for whoever
990
+ * deployed the application — a query, a path, a token in a stack — and this
991
+ * markup is sent to whoever asked for the page. `uf dev` reports the throw in
992
+ * the terminal and `uf build` fails the route, which are the places the person
993
+ * who can act on it is looking.
994
+ */
995
+ component DefaultRouteError(error: RouteError, reset: () => void) {
996
+ const title = errorTitle(error);
997
+ const detail = match (error) {
998
+ {kind: "unauthorized"} => "This page needs you to be signed in.",
999
+ {kind: "forbidden"} => "You do not have access to this page.",
1000
+ {kind: "thrown"} => "This page could not be rendered.",
1001
+ };
1002
+ return (
1003
+ <main>
1004
+ <title>{title}</title>
1005
+ <h1>{title}</h1>
1006
+ <p>{detail}</p>
1007
+ <button type="button" onClick={reset}>
1008
+ Try again
1009
+ </button>
1010
+ </main>
1011
+ );
1012
+ }
1013
+
1014
+ /** The component an error module renders: `default`, or the named `Error`. */
1015
+ function errorComponent(module: ErrorModule): React.ComponentType<ErrorRenderProps> {
1016
+ const component = module.default ?? module.Error;
1017
+ if (component == null) {
1018
+ throw new Error(
1019
+ "@uniflowed/router: an error module must export a component as `default` or `Error`",
1020
+ );
1021
+ }
1022
+ return renderable(component);
1023
+ }
1024
+
1025
+ /** The props an error boundary's component receives. */
1026
+ type ErrorRenderProps = {|
1027
+ readonly error: RouteError,
1028
+ readonly reset: () => void,
1029
+ |};
1030
+
1031
+ /**
1032
+ * The error UI, from whichever module is in scope.
1033
+ *
1034
+ * One component for both ways in — the class boundary below, which catches a
1035
+ * throw while the browser renders, and `ResolvedErrorPage`, which is what the
1036
+ * server renders because React's boundaries do not run in `renderToString`.
1037
+ * Two paths to the same screen is exactly the pair that drifts.
1038
+ */
1039
+ component RouteErrorView(module: ?ErrorModule, error: RouteError, reset: () => void) {
1040
+ if (module == null) {
1041
+ return <DefaultRouteError error={error} reset={reset} />;
1042
+ }
1043
+ const Boundary = errorComponent(module);
1044
+ return <Boundary error={error} reset={reset} />;
1045
+ }
1046
+
1047
+ /**
1048
+ * The page of a route that resolved to an error.
1049
+ *
1050
+ * A resolved error route carries the error and the module on the route itself,
1051
+ * so this is a static component rather than a closure the resolver builds:
1052
+ * `RouteView` composes it in its layouts exactly like a page, which is what
1053
+ * makes "inside the layouts above the boundary" one code path and not two.
1054
+ *
1055
+ * `reset()` here is `router.refresh()` — this route resolved to an error
1056
+ * because a loader or an import threw, so re-running the resolution is what
1057
+ * trying again means. On the server `refresh` does nothing, which is correct:
1058
+ * a static render has nothing to re-run.
1059
+ */
1060
+ component ResolvedErrorPage() {
1061
+ const { resolved, router } = useRouterState();
1062
+ const reset = useCallback(() => {
1063
+ router.refresh().catch(() => {});
1064
+ }, [router]);
1065
+
1066
+ if (resolved.error == null) {
1067
+ // Unreachable: this module is only ever the page of a resolved error route.
1068
+ return null;
1069
+ }
1070
+ return (
1071
+ <RouteErrorView module={resolved.errorBoundary.module} error={resolved.error} reset={reset} />
1072
+ );
1073
+ }
1074
+
1075
+ type RouteErrorBoundaryProps = {|
1076
+ readonly module: ?ErrorModule,
1077
+ readonly resetKey: string,
1078
+ readonly children: React.Node,
1079
+ |};
1080
+
1081
+ type RouteErrorBoundaryState = {| readonly error: ?RouteError |};
1082
+
1083
+ /**
1084
+ * The boundary that catches a throw while the browser renders the subtree.
1085
+ *
1086
+ * A class, because `getDerivedStateFromError` is React's contract for this and
1087
+ * there is no hook that does it — this is the one place in the router where
1088
+ * following React's public contract means not using a function component.
1089
+ *
1090
+ * Recovering on navigation is `componentDidUpdate` watching `resetKey`, not
1091
+ * `key={pathname}` on the boundary. Keying it remounts the subtree on *every*
1092
+ * navigation, error or not, and everything below the boundary goes with it —
1093
+ * which is the layouts, whose whole purpose is to survive navigation with
1094
+ * their scroll position and their open sections intact.
1095
+ */
1096
+ class RouteErrorBoundary extends React.Component<RouteErrorBoundaryProps, RouteErrorBoundaryState> {
1097
+ constructor(props: RouteErrorBoundaryProps) {
1098
+ super(props);
1099
+ this.state = { error: null };
1100
+ }
1101
+
1102
+ static getDerivedStateFromError(error: mixed): RouteErrorBoundaryState {
1103
+ return { error: routeErrorFor(error) };
1104
+ }
1105
+
1106
+ componentDidUpdate(previous: RouteErrorBoundaryProps) {
1107
+ if (this.state.error != null && previous.resetKey !== this.props.resetKey) {
1108
+ this.setState({ error: null });
1109
+ }
1110
+ }
1111
+
1112
+ render(): React.Node {
1113
+ const { error } = this.state;
1114
+ if (error == null) {
1115
+ return this.props.children;
1116
+ }
1117
+ return (
1118
+ <RouteErrorView
1119
+ module={this.props.module}
1120
+ error={error}
1121
+ reset={() => this.setState({ error: null })}
1122
+ />
1123
+ );
1124
+ }
1125
+ }
1126
+
477
1127
  // ---------------------------------------------------------------------------
478
1128
  // The React binding
479
1129
  // ---------------------------------------------------------------------------
@@ -553,6 +1203,18 @@ export component RouterProvider(url: string, initial: ResolvedRoute, children: R
553
1203
  }
554
1204
  const target = new URL(to, window.location.href);
555
1205
  const next = target.pathname + target.search;
1206
+ // The half of the split that is not about bytes. A route whose page is not
1207
+ // in this bundle is not a route this router can render, and pretending
1208
+ // otherwise is the silent break: the navigation would resolve to nothing
1209
+ // and the visitor would be left on the page they clicked from. The browser
1210
+ // has the document, so the browser does the navigation — which is what a
1211
+ // link does when there is no JavaScript at all, and what the anchor
1212
+ // `Link` renders would have done on its own.
1213
+ const matched = matchRoute(routeTable().routes, target.pathname);
1214
+ if (matched != null && !hasClientPage(matched.route)) {
1215
+ window.location.assign(target.href);
1216
+ return;
1217
+ }
556
1218
  setPending(true);
557
1219
  try {
558
1220
  const nextResolved = await resolveMatch(routeTable(), next);
@@ -587,6 +1249,14 @@ export component RouterProvider(url: string, initial: ResolvedRoute, children: R
587
1249
  }
588
1250
  const onPopState = () => {
589
1251
  const next = window.location.pathname + window.location.search;
1252
+ // Back into a route this bundle has no page for. The history entry is
1253
+ // already the browser's — it moved before this listener ran — so the
1254
+ // document that belongs to it is what has to be fetched.
1255
+ const matched = matchRoute(routeTable().routes, window.location.pathname);
1256
+ if (matched != null && !hasClientPage(matched.route)) {
1257
+ window.location.reload();
1258
+ return;
1259
+ }
590
1260
  resolveMatch(routeTable(), next).then((nextResolved) => {
591
1261
  startTransition(() => {
592
1262
  setResolved(nextResolved);
@@ -609,11 +1279,12 @@ export component RouterProvider(url: string, initial: ResolvedRoute, children: R
609
1279
  }
610
1280
  const target = new URL(to, window.location.href);
611
1281
  const matched = matchRoute(routeTable().routes, target.pathname);
612
- if (matched == null) {
1282
+ const load = matched?.route.page;
1283
+ if (matched == null || load == null) {
613
1284
  return;
614
1285
  }
615
1286
  await Promise.all([
616
- loadOnce(matched.route.page),
1287
+ loadOnce(load),
617
1288
  ...matched.route.layouts.map((layout) => loadOnce(layout)),
618
1289
  ]);
619
1290
  },
@@ -705,21 +1376,85 @@ export hook useLoaderData(): mixed {
705
1376
  /**
706
1377
  * Renders the matched page inside its layouts, innermost last, with the
707
1378
  * document metadata as hoistable head elements.
1379
+ *
1380
+ * # One walk down the layouts, not three
1381
+ *
1382
+ * The layouts, the error boundary and the `<Suspense>` boundaries all have to
1383
+ * be threaded into the same stack at the depth each was declared at, so this
1384
+ * is one descending loop over that depth rather than a pass per kind. `depth`
1385
+ * counts the layouts still *outside* the element built so far, which is what
1386
+ * `above` means on both a route's `errorBoundary` and each of its `loading`
1387
+ * entries — one number, one meaning, one place it is compared.
1388
+ *
1389
+ * # Where the error boundaries go
1390
+ *
1391
+ * Two, and they are not the same thing twice. The inner one is the project's
1392
+ * `_uf.error.js`, placed at the depth the file sits at, so the layouts above
1393
+ * it stay mounted and interactive while the subtree below is replaced — that
1394
+ * placement *is* the feature. The outer one has no module and so renders the
1395
+ * framework's page; it is what stands between a throw in a root layout, or in
1396
+ * the error component itself, and an unmounted document. A single boundary
1397
+ * cannot be both: put it outside and a page's throw takes the navigation down
1398
+ * with it; put it inside and nothing catches the layout above.
1399
+ *
1400
+ * # Where the loading boundaries go
1401
+ *
1402
+ * Inside the layout of the segment that declared the file and outside
1403
+ * everything under it, which is what makes the shell arrive first: a renderer
1404
+ * streaming this tree can send every layout down to the boundary, and the
1405
+ * fallback, before whatever the page is waiting for has resolved. A segment
1406
+ * with no `_uf.loading.js` contributes no boundary at all — it is not wrapped
1407
+ * in a `<Suspense fallback={null}>` on the way past — so a project that
1408
+ * declares none renders the tree it rendered before this existed, and a page
1409
+ * that suspends without a boundary above it still fails the way React says it
1410
+ * should rather than silently rendering nothing.
1411
+ *
1412
+ * The error boundary goes *outside* the fallback at the same depth. A throw
1413
+ * while the page is resolving has to reach a boundary that is still mounted,
1414
+ * and the `<Suspense>` is part of what the throw came out of.
708
1415
  */
709
1416
  export component RouteView() {
710
1417
  const { resolved } = useRouterState();
1418
+ const { module, above } = resolved.errorBoundary;
711
1419
  const Page = pageComponent(resolved.page);
712
1420
  let element: React.Node = (
713
1421
  <Page params={resolved.params} searchParams={resolved.searchParams} data={resolved.data} />
714
1422
  );
715
- for (let index = resolved.layouts.length - 1; index >= 0; index -= 1) {
716
- const Layout = layoutComponent(resolved.layouts[index]);
717
- element = <Layout params={resolved.params}>{element}</Layout>;
1423
+
1424
+ for (let depth = resolved.layouts.length; depth >= 0; depth -= 1) {
1425
+ // Backwards over a root-first list, so the deepest segment's fallback ends
1426
+ // up closest to the page. Two segments land on the same depth whenever the
1427
+ // inner one declares no layout of its own, and then this order is the only
1428
+ // thing that keeps them nested the way the directories are.
1429
+ for (let index = resolved.loading.length - 1; index >= 0; index -= 1) {
1430
+ const boundary = resolved.loading[index];
1431
+ if (boundary.above !== depth) {
1432
+ continue;
1433
+ }
1434
+ const Fallback = loadingComponent(boundary.module);
1435
+ element = <Suspense fallback={<Fallback />}>{element}</Suspense>;
1436
+ }
1437
+ // Not around a route that already resolved to its error page: that page is
1438
+ // the boundary's own component, and wrapping it in the same boundary would
1439
+ // answer a throw inside it with itself.
1440
+ if (depth === above && module != null && resolved.error == null) {
1441
+ element = (
1442
+ <RouteErrorBoundary module={module} resetKey={resolved.pathname}>
1443
+ {element}
1444
+ </RouteErrorBoundary>
1445
+ );
1446
+ }
1447
+ if (depth > 0) {
1448
+ const Layout = layoutComponent(resolved.layouts[depth - 1]);
1449
+ element = <Layout params={resolved.params}>{element}</Layout>;
1450
+ }
718
1451
  }
719
1452
  return (
720
1453
  <>
721
1454
  <Head metadata={resolved.metadata} />
722
- {element}
1455
+ <RouteErrorBoundary module={null} resetKey={resolved.pathname}>
1456
+ {element}
1457
+ </RouteErrorBoundary>
723
1458
  </>
724
1459
  );
725
1460
  }
@@ -738,6 +1473,24 @@ function pageComponent(module: PageModule): React.ComponentType<PageRenderProps>
738
1473
  return renderable(component);
739
1474
  }
740
1475
 
1476
+ /**
1477
+ * The component a loading module renders: `default`, or the named `Loading`.
1478
+ *
1479
+ * No props, unlike a page or a layout. A fallback is what the router shows
1480
+ * when it does not have the route's answer yet, so there is nothing it could
1481
+ * be handed that would be true — not `data`, which is the thing being waited
1482
+ * for, and not `children`, because it renders instead of them.
1483
+ */
1484
+ function loadingComponent(module: LoadingModule): React.ComponentType<{||}> {
1485
+ const component = module.default ?? module.Loading;
1486
+ if (component == null) {
1487
+ throw new Error(
1488
+ "@uniflowed/router: a loading module must export a component as `default` or `Loading`",
1489
+ );
1490
+ }
1491
+ return renderable(component);
1492
+ }
1493
+
741
1494
  /** The component a layout module renders: `default`, or the named `Layout`. */
742
1495
  function layoutComponent(module: LayoutModule): React.ComponentType<LayoutRenderProps> {
743
1496
  const component = module.default ?? module.Layout;
@@ -763,11 +1516,14 @@ function layoutComponent(module: LayoutModule): React.ComponentType<LayoutRender
763
1516
  * unsoundness spread over six declarations, where it also stopped anyone from
764
1517
  * checking that `RouteView` passes the props a page is documented to receive.
765
1518
  * Here it is one line, and everything on either side of it is checked: what a
766
- * module may export, and what a page is handed.
1519
+ * module may export, and what a page is handed. Suppressed by name so that
1520
+ * `check:lib` can gate CI without this file being the thing that stops it; the
1521
+ * directive names the rule, and this is the argument for escaping it.
767
1522
  */
768
1523
  function renderable<TProps extends { ... }>(
769
1524
  component: RouteComponent,
770
1525
  ): React.ComponentType<TProps> {
1526
+ // uf-lint-disable-next-line flow/unclear-type
771
1527
  return component as any;
772
1528
  }
773
1529
 
@@ -889,6 +1645,16 @@ export function notFound(): empty {
889
1645
  throw new NotFoundError();
890
1646
  }
891
1647
 
1648
+ /** Stop rendering the current page and show the error boundary, as a 401. */
1649
+ export function unauthorized(): empty {
1650
+ throw new UnauthorizedError();
1651
+ }
1652
+
1653
+ /** Stop rendering the current page and show the error boundary, as a 403. */
1654
+ export function forbidden(): empty {
1655
+ throw new ForbiddenError();
1656
+ }
1657
+
892
1658
  /** Stop rendering the current page and send the visitor elsewhere. */
893
1659
  export function redirect(to: string): empty {
894
1660
  throw new RedirectError(to, false);