@sigil-dev/grimoire 0.9.15 → 0.9.16
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/package.json +3 -3
- package/src/client/router.ts +33 -9
- package/src/rendering/index.ts +14 -0
- package/src/routing/router.ts +63 -12
- package/src/server/index.ts +14 -18
- package/test/server.test.ts +40 -0
package/package.json
CHANGED
|
@@ -4,7 +4,7 @@
|
|
|
4
4
|
"module": "index.ts",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"private": false,
|
|
7
|
-
"version": "0.9.
|
|
7
|
+
"version": "0.9.16",
|
|
8
8
|
"exports": {
|
|
9
9
|
".": "./index.ts",
|
|
10
10
|
"./server": "./server.ts",
|
|
@@ -23,8 +23,8 @@
|
|
|
23
23
|
"test": "bun test"
|
|
24
24
|
},
|
|
25
25
|
"dependencies": {
|
|
26
|
-
"@sigil-dev/compiler": "0.9.
|
|
27
|
-
"@sigil-dev/runtime": "0.9.
|
|
26
|
+
"@sigil-dev/compiler": "0.9.16",
|
|
27
|
+
"@sigil-dev/runtime": "0.9.16",
|
|
28
28
|
"vite": "^8.0.16"
|
|
29
29
|
},
|
|
30
30
|
"peerDependencies": {
|
package/src/client/router.ts
CHANGED
|
@@ -1,4 +1,8 @@
|
|
|
1
|
-
import {
|
|
1
|
+
import {
|
|
2
|
+
collectEffects,
|
|
3
|
+
popHydrationNodes,
|
|
4
|
+
pushHydrationNodes,
|
|
5
|
+
} from "@sigil-dev/runtime";
|
|
2
6
|
import { onSubmitEnsureCsrf } from "./csrf.ts";
|
|
3
7
|
import {
|
|
4
8
|
clearDeps,
|
|
@@ -91,12 +95,16 @@ export async function hmrRerender(): Promise<void> {
|
|
|
91
95
|
disposeCurrentPage?.();
|
|
92
96
|
pushHydrationNodes([]);
|
|
93
97
|
let rootNode: any;
|
|
98
|
+
let flush = () => {};
|
|
94
99
|
disposeCurrentPage = withEffectScope(() => {
|
|
95
|
-
rootNode =
|
|
100
|
+
({ value: rootNode, flush } = collectEffects(() =>
|
|
101
|
+
buildRouteTree(lastState!, Page),
|
|
102
|
+
));
|
|
96
103
|
});
|
|
97
104
|
popHydrationNodes();
|
|
98
105
|
const preserved = capturePreservedScroll();
|
|
99
106
|
document.getElementById("grimoire-root")?.replaceChildren(rootNode);
|
|
107
|
+
flush();
|
|
100
108
|
restorePreservedScroll(preserved);
|
|
101
109
|
}
|
|
102
110
|
|
|
@@ -204,7 +212,9 @@ function uniqueTransitionEls(root: ParentNode): Map<string, Element> {
|
|
|
204
212
|
}
|
|
205
213
|
|
|
206
214
|
/** [key, element on the current page, element on the incoming page] */
|
|
207
|
-
function sharedTransitionKeys(
|
|
215
|
+
function sharedTransitionKeys(
|
|
216
|
+
incoming: unknown,
|
|
217
|
+
): Array<[string, Element, Element]> {
|
|
208
218
|
const root = incoming as Partial<ParentNode> | null;
|
|
209
219
|
if (!root || typeof root.querySelectorAll !== "function") return [];
|
|
210
220
|
const next = uniqueTransitionEls(root as ParentNode);
|
|
@@ -269,11 +279,13 @@ function prefetchHref(a: Element | null): string | null {
|
|
|
269
279
|
* response is held for a short while so the click that follows reuses it.
|
|
270
280
|
*/
|
|
271
281
|
export function prefetch(href: string): void {
|
|
272
|
-
const conn = (navigator as { connection?: { saveData?: boolean } })
|
|
282
|
+
const conn = (navigator as { connection?: { saveData?: boolean } })
|
|
283
|
+
.connection;
|
|
273
284
|
if (conn?.saveData) return;
|
|
274
285
|
const url = new URL(href, location.origin);
|
|
275
286
|
// the page already on screen needs no warming
|
|
276
|
-
if (url.pathname === location.pathname && url.search === location.search)
|
|
287
|
+
if (url.pathname === location.pathname && url.search === location.search)
|
|
288
|
+
return;
|
|
277
289
|
const key = prefetchKey(url);
|
|
278
290
|
const hit = prefetched.get(key);
|
|
279
291
|
if (hit && Date.now() - hit.at < PREFETCH_TTL_MS) return;
|
|
@@ -472,14 +484,18 @@ export async function navigate(
|
|
|
472
484
|
disposeCurrentPage = null;
|
|
473
485
|
pushHydrationNodes([]);
|
|
474
486
|
let loadingNode: any;
|
|
487
|
+
let flush = () => {};
|
|
475
488
|
disposeCurrentPage = withEffectScope(() => {
|
|
476
|
-
loadingNode
|
|
489
|
+
({ value: loadingNode, flush } = collectEffects(() =>
|
|
490
|
+
(DestPage as any).loading(),
|
|
491
|
+
));
|
|
477
492
|
});
|
|
478
493
|
popHydrationNodes();
|
|
479
494
|
// replace only grimoire-page, keeps layout stable during transition
|
|
480
495
|
const pageEl = document.getElementById("grimoire-page");
|
|
481
496
|
if (pageEl) pageEl.replaceChildren(loadingNode);
|
|
482
497
|
else document.getElementById("grimoire-root")?.replaceChildren(loadingNode);
|
|
498
|
+
flush();
|
|
483
499
|
}
|
|
484
500
|
|
|
485
501
|
let res: Response;
|
|
@@ -553,9 +569,13 @@ export async function navigate(
|
|
|
553
569
|
disposeCurrentPage = null;
|
|
554
570
|
pushHydrationNodes([]);
|
|
555
571
|
let rootNode: any;
|
|
572
|
+
// the page's effects (and use: directives) run once it is in the document
|
|
573
|
+
let flushEffects = () => {};
|
|
556
574
|
disposeCurrentPage = withEffectScope(() => {
|
|
557
575
|
try {
|
|
558
|
-
rootNode =
|
|
576
|
+
({ value: rootNode, flush: flushEffects } = collectEffects(() =>
|
|
577
|
+
buildRouteTree(lastState!, Page),
|
|
578
|
+
));
|
|
559
579
|
} catch (e) {
|
|
560
580
|
console.error(e);
|
|
561
581
|
}
|
|
@@ -598,7 +618,9 @@ export async function navigate(
|
|
|
598
618
|
// user hasn't asked for reduced motion. The callback must stay synchronous.
|
|
599
619
|
const preserved = capturePreservedScroll();
|
|
600
620
|
const doc = document as Document & {
|
|
601
|
-
startViewTransition?: (
|
|
621
|
+
startViewTransition?: (
|
|
622
|
+
cb: () => void,
|
|
623
|
+
) => { finished?: Promise<unknown> } | undefined;
|
|
602
624
|
};
|
|
603
625
|
const animate =
|
|
604
626
|
typeof doc.startViewTransition === "function" &&
|
|
@@ -612,6 +634,7 @@ export async function navigate(
|
|
|
612
634
|
};
|
|
613
635
|
const doSwap = () => {
|
|
614
636
|
document.getElementById("grimoire-root")?.replaceChildren(rootNode);
|
|
637
|
+
flushEffects();
|
|
615
638
|
for (const [key, , next] of shared) name(next, key);
|
|
616
639
|
restorePreservedScroll(preserved);
|
|
617
640
|
applyScroll();
|
|
@@ -621,7 +644,8 @@ export async function navigate(
|
|
|
621
644
|
for (const [key, prev] of shared) name(prev, key);
|
|
622
645
|
const transition = doc.startViewTransition?.(doSwap);
|
|
623
646
|
const clear = () => {
|
|
624
|
-
for (const el of named)
|
|
647
|
+
for (const el of named)
|
|
648
|
+
(el as HTMLElement).style.removeProperty("view-transition-name");
|
|
625
649
|
};
|
|
626
650
|
Promise.resolve(transition?.finished).then(clear, clear);
|
|
627
651
|
} else {
|
package/src/rendering/index.ts
CHANGED
|
@@ -418,6 +418,20 @@ export async function renderRoute(
|
|
|
418
418
|
}
|
|
419
419
|
}
|
|
420
420
|
|
|
421
|
+
// no page at this address: its layouts are loaded, the 404 goes in them
|
|
422
|
+
if (matched.notFound)
|
|
423
|
+
return (
|
|
424
|
+
(await renderErrorPage(
|
|
425
|
+
errorRoutes,
|
|
426
|
+
context.url.pathname,
|
|
427
|
+
404,
|
|
428
|
+
"Not Found",
|
|
429
|
+
null,
|
|
430
|
+
loadModule,
|
|
431
|
+
{ layoutPairs, params: matched.params, nonceAttr, dev },
|
|
432
|
+
)) ?? new Response("Not Found", { status: 404 })
|
|
433
|
+
);
|
|
434
|
+
|
|
421
435
|
// page loads see every layout's data merged
|
|
422
436
|
context.parent = async () => ({ ...parentData });
|
|
423
437
|
|
package/src/routing/router.ts
CHANGED
|
@@ -6,6 +6,8 @@ export interface MatchedRoute {
|
|
|
6
6
|
layouts: RouteFile[]; // was: layout?: RouteFile
|
|
7
7
|
layoutServers: RouteFile[]; // was: layoutServer?: RouteFile
|
|
8
8
|
pageServer?: RouteFile;
|
|
9
|
+
/** No page has this address: the layouts that cover it render the closest +error.tsx with a 404. */
|
|
10
|
+
notFound?: boolean;
|
|
9
11
|
}
|
|
10
12
|
|
|
11
13
|
export function matchRoute(
|
|
@@ -68,23 +70,72 @@ export function matchRoute(
|
|
|
68
70
|
return null;
|
|
69
71
|
}
|
|
70
72
|
|
|
73
|
+
/** Whether a folder's pattern (a layout's or an error page's path) covers pathname. */
|
|
74
|
+
function covers(
|
|
75
|
+
folder: string,
|
|
76
|
+
pathname: string,
|
|
77
|
+
): Record<string, string> | null {
|
|
78
|
+
if (folder === "/" || folder === "") return {};
|
|
79
|
+
const params = matchPattern(`${folder.replace(/\/$/, "")}/*__rest`, pathname);
|
|
80
|
+
if (params) delete params.__rest;
|
|
81
|
+
return params;
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
/** How specific a folder pattern is: deeper first, then fixed segments over params. */
|
|
85
|
+
function depth(folder: string): number {
|
|
86
|
+
const parts = folder.split("/").filter(Boolean);
|
|
87
|
+
return (
|
|
88
|
+
parts.length * 2 -
|
|
89
|
+
(parts.some((p) => p.startsWith(":") || p.startsWith("*")) ? 1 : 0)
|
|
90
|
+
);
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
/**
|
|
94
|
+
* The +error.tsx closest to pathname: the deepest folder whose pattern covers
|
|
95
|
+
* it, so routes/events/[id]/+error.tsx catches /events/42/anything.
|
|
96
|
+
*/
|
|
71
97
|
export function findClosestError(
|
|
72
98
|
errors: RouteFile[],
|
|
73
99
|
pathname: string,
|
|
74
100
|
): RouteFile | null {
|
|
75
|
-
|
|
76
|
-
|
|
77
|
-
|
|
78
|
-
|
|
79
|
-
|
|
80
|
-
|
|
81
|
-
|
|
82
|
-
|
|
83
|
-
if (error) return error;
|
|
84
|
-
if (segments.length === 0) break;
|
|
85
|
-
segments.pop();
|
|
101
|
+
let best: RouteFile | null = null;
|
|
102
|
+
let bestDepth = -1;
|
|
103
|
+
for (const e of errors) {
|
|
104
|
+
const d = depth(e.path);
|
|
105
|
+
if (d > bestDepth && covers(e.path, pathname)) {
|
|
106
|
+
best = e;
|
|
107
|
+
bestDepth = d;
|
|
108
|
+
}
|
|
86
109
|
}
|
|
87
|
-
return
|
|
110
|
+
return best;
|
|
111
|
+
}
|
|
112
|
+
|
|
113
|
+
/**
|
|
114
|
+
* A match for an address no page has: the layouts (and their server loads)
|
|
115
|
+
* of every folder that covers it, so the 404 renders the closest +error.tsx
|
|
116
|
+
* inside the site's own layout, exactly like a page whose load throws
|
|
117
|
+
* error(404). Without this an unknown address got the error page bare.
|
|
118
|
+
*/
|
|
119
|
+
export function matchNotFound(tree: RouteTree, url: URL): MatchedRoute {
|
|
120
|
+
const pathname = url.pathname;
|
|
121
|
+
const params: Record<string, string> = {};
|
|
122
|
+
const within = (l: RouteFile) => {
|
|
123
|
+
const p = covers(l.path, pathname);
|
|
124
|
+
if (p) Object.assign(params, p);
|
|
125
|
+
return p !== null;
|
|
126
|
+
};
|
|
127
|
+
const byDepth = (a: RouteFile, b: RouteFile) => a.path.length - b.path.length;
|
|
128
|
+
return {
|
|
129
|
+
route: { path: pathname, filePath: "", type: "page" } as RouteFile,
|
|
130
|
+
params,
|
|
131
|
+
layouts: tree.layouts
|
|
132
|
+
.filter((l) => l.type === "layout" && within(l))
|
|
133
|
+
.sort(byDepth),
|
|
134
|
+
layoutServers: tree.layouts
|
|
135
|
+
.filter((l) => l.type === "layoutServer" && within(l))
|
|
136
|
+
.sort(byDepth),
|
|
137
|
+
notFound: true,
|
|
138
|
+
};
|
|
88
139
|
}
|
|
89
140
|
|
|
90
141
|
function matchPattern(
|
package/src/server/index.ts
CHANGED
|
@@ -17,7 +17,7 @@ import { CACHE_CONTROL, cacheControlFor } from "./asset-cache";
|
|
|
17
17
|
import { drainAfterResponse, withAfterResponse } from "./after-response.ts";
|
|
18
18
|
import { renderErrorPage, renderRoute } from "../rendering";
|
|
19
19
|
import { registerSSRPlugin } from "../rendering/ssrPlugin";
|
|
20
|
-
import { matchRoute } from "../routing/router";
|
|
20
|
+
import { matchNotFound, matchRoute } from "../routing/router";
|
|
21
21
|
import { isErrorResult } from "../sentinels/error.ts";
|
|
22
22
|
import { isFailResult } from "../sentinels/fail.ts";
|
|
23
23
|
import { isRedirectResult } from "../sentinels/redirect.ts";
|
|
@@ -511,7 +511,6 @@ export async function createServer(config: GrimoireConfig = {}) {
|
|
|
511
511
|
if (staticAsset) return staticAsset;
|
|
512
512
|
|
|
513
513
|
return runRequestHooks(plugins, req, async () => {
|
|
514
|
-
|
|
515
514
|
const HTTP_METHODS = [
|
|
516
515
|
"GET",
|
|
517
516
|
"POST",
|
|
@@ -557,18 +556,18 @@ export async function createServer(config: GrimoireConfig = {}) {
|
|
|
557
556
|
// matching happens here — after handle() has run
|
|
558
557
|
let matched = matchRoute(tree, evt.url, paramMatcherFns);
|
|
559
558
|
if (!matched) {
|
|
560
|
-
// the nearest +error.tsx
|
|
561
|
-
//
|
|
562
|
-
return (
|
|
563
|
-
(
|
|
564
|
-
|
|
565
|
-
|
|
566
|
-
|
|
567
|
-
|
|
568
|
-
|
|
569
|
-
|
|
570
|
-
|
|
571
|
-
|
|
559
|
+
// the nearest +error.tsx inside the layouts that cover the
|
|
560
|
+
// address, like a page whose load throws error(404)
|
|
561
|
+
return renderRoute(
|
|
562
|
+
matchNotFound(tree, evt.url),
|
|
563
|
+
evt.request,
|
|
564
|
+
tree.errors,
|
|
565
|
+
loader,
|
|
566
|
+
evt.locals,
|
|
567
|
+
plugins,
|
|
568
|
+
cspNonce,
|
|
569
|
+
dev,
|
|
570
|
+
patchedFetch,
|
|
572
571
|
);
|
|
573
572
|
}
|
|
574
573
|
|
|
@@ -858,10 +857,7 @@ export async function createServer(config: GrimoireConfig = {}) {
|
|
|
858
857
|
);
|
|
859
858
|
if (page) return page;
|
|
860
859
|
} catch (pageErr) {
|
|
861
|
-
logger.error(
|
|
862
|
-
"+error.tsx failed while rendering an error:",
|
|
863
|
-
pageErr,
|
|
864
|
-
);
|
|
860
|
+
logger.error("+error.tsx failed while rendering an error:", pageErr);
|
|
865
861
|
}
|
|
866
862
|
const errorHtmlPath = `${process.cwd()}/error.html`;
|
|
867
863
|
try {
|
package/test/server.test.ts
CHANGED
|
@@ -532,6 +532,26 @@ describe("Server — error pages", () => {
|
|
|
532
532
|
join(dir, "boom", "+page.tsx"),
|
|
533
533
|
"export default () => 'never';",
|
|
534
534
|
);
|
|
535
|
+
// a root layout with its own server data, a nested error page, and
|
|
536
|
+
// one in a [param] folder
|
|
537
|
+
await writeFile(
|
|
538
|
+
join(dir, "+layout.tsx"),
|
|
539
|
+
'export default ({ data, children }) => `<main data-site="${data.site}">${children}</main>`;',
|
|
540
|
+
);
|
|
541
|
+
await writeFile(
|
|
542
|
+
join(dir, "+layout.server.ts"),
|
|
543
|
+
'export function load() { return { site: "meow" }; }',
|
|
544
|
+
);
|
|
545
|
+
await mkdir(join(dir, "shop"), { recursive: true });
|
|
546
|
+
await writeFile(
|
|
547
|
+
join(dir, "shop", "+error.tsx"),
|
|
548
|
+
"export default ({ status }) => `<h1>shop ${status}</h1>`;",
|
|
549
|
+
);
|
|
550
|
+
await mkdir(join(dir, "items", "[id]"), { recursive: true });
|
|
551
|
+
await writeFile(
|
|
552
|
+
join(dir, "items", "[id]", "+error.tsx"),
|
|
553
|
+
"export default ({ status }) => `<h1>item ${status}</h1>`;",
|
|
554
|
+
);
|
|
535
555
|
server = await createServer({ port: 3012, routes: dir, _skipBuild: true });
|
|
536
556
|
});
|
|
537
557
|
|
|
@@ -545,6 +565,26 @@ describe("Server — error pages", () => {
|
|
|
545
565
|
expect(html).toContain("oops 404: Not Found");
|
|
546
566
|
});
|
|
547
567
|
|
|
568
|
+
test("an unknown URL's error page sits in the layouts, with their data", async () => {
|
|
569
|
+
const html = await (await fetch(`${base}/nowhere/at/all`)).text();
|
|
570
|
+
expect(html).toContain('<main data-site="meow">');
|
|
571
|
+
expect(html).toContain("oops 404: Not Found");
|
|
572
|
+
});
|
|
573
|
+
|
|
574
|
+
test("an unknown URL gets the closest +error.tsx", async () => {
|
|
575
|
+
const res = await fetch(`${base}/shop/no-such-thing`);
|
|
576
|
+
expect(res.status).toBe(404);
|
|
577
|
+
expect(await res.text()).toContain("shop 404");
|
|
578
|
+
});
|
|
579
|
+
|
|
580
|
+
test("a +error.tsx in a [param] folder covers the addresses under it", async () => {
|
|
581
|
+
expect(await (await fetch(`${base}/items/42/missing`)).text()).toContain(
|
|
582
|
+
"item 404",
|
|
583
|
+
);
|
|
584
|
+
// /items itself is above the [id] folder
|
|
585
|
+
expect(await (await fetch(`${base}/items`)).text()).toContain("oops 404");
|
|
586
|
+
});
|
|
587
|
+
|
|
548
588
|
test("an unexpected error renders +error.tsx with a generic message", async () => {
|
|
549
589
|
const res = await fetch(`${base}/boom`);
|
|
550
590
|
expect(res.status).toBe(500);
|