@sigil-dev/grimoire 0.9.29 → 0.9.31
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/bin/sigil.ts +4 -0
- package/index.ts +16 -10
- package/package.json +14 -6
- package/server.ts +2 -2
- package/src/adapters/bun.ts +17 -17
- package/src/adapters/static.ts +41 -41
- package/src/adapters/types.ts +36 -36
- package/src/base.ts +4 -1
- package/src/client/csrf.ts +47 -47
- package/src/client/deferred.ts +1 -4
- package/src/client/enhance.ts +160 -160
- package/src/client/router.ts +927 -926
- package/src/config-file.ts +84 -0
- package/src/dev/compile-module.ts +199 -193
- package/src/dev/hmr-client.ts +229 -229
- package/src/dev/hmr-server.ts +274 -266
- package/src/dev/loader.ts +144 -144
- package/src/dev/runtime-bundle.ts +5 -3
- package/src/duration.ts +46 -0
- package/src/env/modules.ts +62 -62
- package/src/env/required.ts +42 -42
- package/src/env/typegen.ts +61 -61
- package/src/headers.ts +105 -105
- package/src/logger/transports.ts +117 -117
- package/src/plugin-order.ts +88 -0
- package/src/rendering/head.ts +49 -49
- package/src/rendering/hydrate.ts +162 -162
- package/src/rendering/images.ts +43 -43
- package/src/rendering/preload.ts +22 -8
- package/src/rendering/ssrPlugin.ts +107 -107
- package/src/rendering/timing.ts +40 -40
- package/src/routing/route-ids.ts +65 -0
- package/src/routing/route.ts +65 -0
- package/src/routing/router.ts +84 -32
- package/src/routing/scanner.ts +18 -5
- package/src/routing/transform-routes.ts +102 -102
- package/src/server/after-response.ts +206 -206
- package/src/server/asset-cache.ts +57 -57
- package/src/server/build.ts +304 -295
- package/src/server/cached.ts +114 -114
- package/src/server/client-address.ts +82 -82
- package/src/server/client-dir.ts +63 -63
- package/src/server/client-entry.ts +44 -44
- package/src/server/context.ts +18 -10
- package/src/server/cookie-utils.ts +80 -80
- package/src/server/coordinator.ts +479 -476
- package/src/server/hooks.ts +122 -122
- package/src/server/index.ts +1181 -1171
- package/src/server/plugins.ts +172 -172
- package/src/server/prerender.ts +473 -473
- package/src/server/reserved.ts +17 -17
- package/src/server/resolver.ts +149 -123
- package/src/server/rewrite.ts +28 -28
- package/src/server/warm.ts +9 -3
- package/src/server/with-headers.ts +27 -27
- package/src/server/worker.ts +2 -6
- package/src/server-only.ts +78 -0
- package/src/testing/dom.ts +73 -73
- package/src/testing/index.ts +169 -169
- package/src/testing/server.ts +1 -0
- package/src/typegen/index.ts +97 -2
- package/src/types.ts +642 -508
- package/test/after-response.test.ts +132 -132
- package/test/asset-cache-policy.test.ts +6 -2
- package/test/base.test.ts +20 -6
- package/test/cached.test.ts +126 -126
- package/test/client-address.test.ts +78 -78
- package/test/client-csrf.test.ts +61 -61
- package/test/client-dir.test.ts +101 -101
- package/test/client-router.test.ts +37 -5
- package/test/config-file.test.ts +84 -0
- package/test/coordinator.test.ts +9 -2
- package/test/deferred.test.ts +4 -2
- package/test/dev-loader.test.ts +30 -30
- package/test/env.test.ts +171 -171
- package/test/force-production.test.ts +7 -2
- package/test/images.test.ts +20 -8
- package/test/locals-header.test.ts +61 -61
- package/test/middleware.test.ts +243 -243
- package/test/parser-plugins.test.ts +98 -92
- package/test/plugin-handle.test.ts +62 -62
- package/test/plugin-order.test.ts +98 -0
- package/test/plugin-routes.test.ts +47 -42
- package/test/plugin-services-context.test.ts +7 -2
- package/test/preload.test.ts +4 -1
- package/test/prerender.test.ts +3 -1
- package/test/rendering.test.ts +3 -2
- package/test/required-env.test.ts +32 -32
- package/test/resolver-windows.test.ts +22 -23
- package/test/rewrite-html.test.ts +90 -90
- package/test/route-group-layouts.test.ts +38 -36
- package/test/route.test.ts +103 -0
- package/test/routing.test.ts +225 -197
- package/test/scanning.test.ts +53 -33
- package/test/server-context.test.ts +22 -0
- package/test/server-only.test.ts +110 -0
- package/test/server.test.ts +659 -640
- package/test/services.test.ts +3 -3
- package/test/streaming.test.ts +11 -6
- package/test/testing-helpers.test.ts +166 -166
- package/test/typegen.test.ts +209 -112
- package/test/warm.test.ts +96 -96
- package/test/worker-context.test.ts +59 -59
- package/test/workspace-files.test.ts +26 -10
- package/test/workspace-versions.test.ts +146 -131
|
@@ -1,107 +1,107 @@
|
|
|
1
|
-
import { transformSync } from "@babel/core";
|
|
2
|
-
import
|
|
3
|
-
import
|
|
4
|
-
|
|
5
|
-
|
|
6
|
-
|
|
7
|
-
|
|
8
|
-
|
|
9
|
-
import {
|
|
10
|
-
import
|
|
11
|
-
import type {
|
|
12
|
-
|
|
13
|
-
const logger = log.scope("scope");
|
|
14
|
-
let registered = false;
|
|
15
|
-
|
|
16
|
-
/**
|
|
17
|
-
* `aliases` (prefix → absolute directory, see projectAliases) are rewritten
|
|
18
|
-
* to file paths in every compiled module: Bun's runtime plugins can't
|
|
19
|
-
* resolve them for static imports.
|
|
20
|
-
*/
|
|
21
|
-
export function registerSSRPlugin(
|
|
22
|
-
plugins: GrimoirePlugin[] = [],
|
|
23
|
-
aliases: Record<string, string> = {},
|
|
24
|
-
) {
|
|
25
|
-
if (registered) return;
|
|
26
|
-
registered = true;
|
|
27
|
-
|
|
28
|
-
Bun.plugin({
|
|
29
|
-
name: "sigil-ssr",
|
|
30
|
-
|
|
31
|
-
setup(build) {
|
|
32
|
-
// loader: "ts" not "tsx" — Babel already consumed the JSX,
|
|
33
|
-
// Bun only needs to strip remaining TypeScript types
|
|
34
|
-
const transpiler = new Bun.Transpiler({ loader: "ts", target: "bun" });
|
|
35
|
-
build.onResolve({ filter: /^@sigil-dev\/runtime($|\/)/ }, (args) => {
|
|
36
|
-
try {
|
|
37
|
-
const resolved = Bun.resolveSync(args.path, process.cwd());
|
|
38
|
-
return { path: resolved.replaceAll("\\", "/") };
|
|
39
|
-
} catch {
|
|
40
|
-
return undefined;
|
|
41
|
-
}
|
|
42
|
-
});
|
|
43
|
-
|
|
44
|
-
build.onLoad({ filter: /\.tsx?$/ }, async ({ path }) => {
|
|
45
|
-
if (path.includes("index.tsx"))
|
|
46
|
-
logger.debug("[ssr-plugin] onLoad:", path);
|
|
47
|
-
const source = await Bun.file(path).text();
|
|
48
|
-
|
|
49
|
-
// node_modules and .grimoire files are plain TypeScript (no sigil JSX).
|
|
50
|
-
// Still must return { contents, loader } — never return undefined from onLoad.
|
|
51
|
-
if (path.includes("node_modules") || path.includes(".grimoire")) {
|
|
52
|
-
return {
|
|
53
|
-
contents: transpiler.transformSync(source),
|
|
54
|
-
loader: "js" as const,
|
|
55
|
-
};
|
|
56
|
-
}
|
|
57
|
-
|
|
58
|
-
if (process.env.SIGIL_VERBOSE) {
|
|
59
|
-
logger.debug("[sigil-ssr] XFORM:", path);
|
|
60
|
-
}
|
|
61
|
-
// must match the client build, or scoped classes differ per side;
|
|
62
|
-
// files without a <style> block get no scope class at all. The
|
|
63
|
-
// CSS is registered for the renderer, which puts it in <head>.
|
|
64
|
-
const styles = extractStyles(source, computeHash(path), path);
|
|
65
|
-
const hash = styles.css ? computeHash(path) : undefined;
|
|
66
|
-
const sourceNoStyle = styles.code;
|
|
67
|
-
const result = transformSync(sourceNoStyle, {
|
|
68
|
-
configFile: false,
|
|
69
|
-
babelrc: false,
|
|
70
|
-
parserOpts: {
|
|
71
|
-
// The jsx plugin goes on .tsx files only.
|
|
72
|
-
//
|
|
73
|
-
// With it enabled everywhere, Babel parses `<R>(x: R) => x`
|
|
74
|
-
// as the opening of a JSX element and fails with
|
|
75
|
-
// "Unexpected token `>`". So a generic arrow function in a
|
|
76
|
-
// plain .ts file — completely ordinary TypeScript — could
|
|
77
|
-
// not be compiled. Found while writing the Drizzle adapter
|
|
78
|
-
// recipe, where `transaction: <R>(db, fn) => ...` is the
|
|
79
|
-
// form that removes an `as any`.
|
|
80
|
-
//
|
|
81
|
-
// A .tsx file is genuinely ambiguous (`<R>(x) => x` is
|
|
82
|
-
// JSX there), so .tsx keeps both and users write `<R,>`.
|
|
83
|
-
plugins: path.endsWith(".tsx")
|
|
84
|
-
? (["typescript", "jsx"] as ParserPlugin[])
|
|
85
|
-
: (["typescript"] as ParserPlugin[]),
|
|
86
|
-
},
|
|
87
|
-
plugins: [[sigilPlugin, { mode: "ssr", hash, aliases }]],
|
|
88
|
-
filename: path,
|
|
89
|
-
});
|
|
90
|
-
|
|
91
|
-
let contents = pinRuntime(
|
|
92
|
-
rewriteAliases(transpiler.transformSync(result?.code ?? ""), aliases),
|
|
93
|
-
);
|
|
94
|
-
if (styles.css && hash) {
|
|
95
|
-
contents = serverStyleSnippet(hash, styles.css) + contents;
|
|
96
|
-
}
|
|
97
|
-
|
|
98
|
-
for (const plugin of plugins) {
|
|
99
|
-
if (plugin.transform)
|
|
100
|
-
contents = (await plugin.transform(contents, path)) ?? contents;
|
|
101
|
-
}
|
|
102
|
-
|
|
103
|
-
return { contents, loader: "js" as const };
|
|
104
|
-
});
|
|
105
|
-
},
|
|
106
|
-
});
|
|
107
|
-
}
|
|
1
|
+
import { transformSync } from "@babel/core";
|
|
2
|
+
import type { ParserPlugin } from "@babel/parser";
|
|
3
|
+
import sigilPlugin from "@sigil-dev/compiler/babel";
|
|
4
|
+
import {
|
|
5
|
+
computeHash,
|
|
6
|
+
extractStyles,
|
|
7
|
+
serverStyleSnippet,
|
|
8
|
+
} from "@sigil-dev/compiler/css";
|
|
9
|
+
import { log } from "../logger/instance";
|
|
10
|
+
import { pinRuntime, rewriteAliases } from "../server/resolver";
|
|
11
|
+
import type { GrimoirePlugin } from "../types";
|
|
12
|
+
|
|
13
|
+
const logger = log.scope("scope");
|
|
14
|
+
let registered = false;
|
|
15
|
+
|
|
16
|
+
/**
|
|
17
|
+
* `aliases` (prefix → absolute directory, see projectAliases) are rewritten
|
|
18
|
+
* to file paths in every compiled module: Bun's runtime plugins can't
|
|
19
|
+
* resolve them for static imports.
|
|
20
|
+
*/
|
|
21
|
+
export function registerSSRPlugin(
|
|
22
|
+
plugins: GrimoirePlugin[] = [],
|
|
23
|
+
aliases: Record<string, string> = {},
|
|
24
|
+
) {
|
|
25
|
+
if (registered) return;
|
|
26
|
+
registered = true;
|
|
27
|
+
|
|
28
|
+
Bun.plugin({
|
|
29
|
+
name: "sigil-ssr",
|
|
30
|
+
|
|
31
|
+
setup(build) {
|
|
32
|
+
// loader: "ts" not "tsx" — Babel already consumed the JSX,
|
|
33
|
+
// Bun only needs to strip remaining TypeScript types
|
|
34
|
+
const transpiler = new Bun.Transpiler({ loader: "ts", target: "bun" });
|
|
35
|
+
build.onResolve({ filter: /^@sigil-dev\/runtime($|\/)/ }, (args) => {
|
|
36
|
+
try {
|
|
37
|
+
const resolved = Bun.resolveSync(args.path, process.cwd());
|
|
38
|
+
return { path: resolved.replaceAll("\\", "/") };
|
|
39
|
+
} catch {
|
|
40
|
+
return undefined;
|
|
41
|
+
}
|
|
42
|
+
});
|
|
43
|
+
|
|
44
|
+
build.onLoad({ filter: /\.tsx?$/ }, async ({ path }) => {
|
|
45
|
+
if (path.includes("index.tsx"))
|
|
46
|
+
logger.debug("[ssr-plugin] onLoad:", path);
|
|
47
|
+
const source = await Bun.file(path).text();
|
|
48
|
+
|
|
49
|
+
// node_modules and .grimoire files are plain TypeScript (no sigil JSX).
|
|
50
|
+
// Still must return { contents, loader } — never return undefined from onLoad.
|
|
51
|
+
if (path.includes("node_modules") || path.includes(".grimoire")) {
|
|
52
|
+
return {
|
|
53
|
+
contents: transpiler.transformSync(source),
|
|
54
|
+
loader: "js" as const,
|
|
55
|
+
};
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
if (process.env.SIGIL_VERBOSE) {
|
|
59
|
+
logger.debug("[sigil-ssr] XFORM:", path);
|
|
60
|
+
}
|
|
61
|
+
// must match the client build, or scoped classes differ per side;
|
|
62
|
+
// files without a <style> block get no scope class at all. The
|
|
63
|
+
// CSS is registered for the renderer, which puts it in <head>.
|
|
64
|
+
const styles = extractStyles(source, computeHash(path), path);
|
|
65
|
+
const hash = styles.css ? computeHash(path) : undefined;
|
|
66
|
+
const sourceNoStyle = styles.code;
|
|
67
|
+
const result = transformSync(sourceNoStyle, {
|
|
68
|
+
configFile: false,
|
|
69
|
+
babelrc: false,
|
|
70
|
+
parserOpts: {
|
|
71
|
+
// The jsx plugin goes on .tsx files only.
|
|
72
|
+
//
|
|
73
|
+
// With it enabled everywhere, Babel parses `<R>(x: R) => x`
|
|
74
|
+
// as the opening of a JSX element and fails with
|
|
75
|
+
// "Unexpected token `>`". So a generic arrow function in a
|
|
76
|
+
// plain .ts file — completely ordinary TypeScript — could
|
|
77
|
+
// not be compiled. Found while writing the Drizzle adapter
|
|
78
|
+
// recipe, where `transaction: <R>(db, fn) => ...` is the
|
|
79
|
+
// form that removes an `as any`.
|
|
80
|
+
//
|
|
81
|
+
// A .tsx file is genuinely ambiguous (`<R>(x) => x` is
|
|
82
|
+
// JSX there), so .tsx keeps both and users write `<R,>`.
|
|
83
|
+
plugins: path.endsWith(".tsx")
|
|
84
|
+
? (["typescript", "jsx"] as ParserPlugin[])
|
|
85
|
+
: (["typescript"] as ParserPlugin[]),
|
|
86
|
+
},
|
|
87
|
+
plugins: [[sigilPlugin, { mode: "ssr", hash, aliases }]],
|
|
88
|
+
filename: path,
|
|
89
|
+
});
|
|
90
|
+
|
|
91
|
+
let contents = pinRuntime(
|
|
92
|
+
rewriteAliases(transpiler.transformSync(result?.code ?? ""), aliases),
|
|
93
|
+
);
|
|
94
|
+
if (styles.css && hash) {
|
|
95
|
+
contents = serverStyleSnippet(hash, styles.css) + contents;
|
|
96
|
+
}
|
|
97
|
+
|
|
98
|
+
for (const plugin of plugins) {
|
|
99
|
+
if (plugin.transform)
|
|
100
|
+
contents = (await plugin.transform(contents, path)) ?? contents;
|
|
101
|
+
}
|
|
102
|
+
|
|
103
|
+
return { contents, loader: "js" as const };
|
|
104
|
+
});
|
|
105
|
+
},
|
|
106
|
+
});
|
|
107
|
+
}
|
package/src/rendering/timing.ts
CHANGED
|
@@ -1,40 +1,40 @@
|
|
|
1
|
-
/**
|
|
2
|
-
* `Server-Timing` for route renders, so the browser's network panel shows
|
|
3
|
-
* where a slow page spent its time (`load` = layout and page server loads,
|
|
4
|
-
* `render` = components to HTML) without any extra tooling.
|
|
5
|
-
*
|
|
6
|
-
* On in dev; in production only when `serverTiming: true`, since durations are
|
|
7
|
-
* visible to every visitor.
|
|
8
|
-
*/
|
|
9
|
-
let enabled = false;
|
|
10
|
-
|
|
11
|
-
export function setServerTiming(on: boolean): void {
|
|
12
|
-
enabled = on;
|
|
13
|
-
}
|
|
14
|
-
|
|
15
|
-
export interface Timer {
|
|
16
|
-
/** Close the phase that has been running since the last mark. */
|
|
17
|
-
mark(name: string): void;
|
|
18
|
-
/** `{ "Server-Timing": ... }`, or nothing when disabled or no marks. */
|
|
19
|
-
headers(): Record<string, string>;
|
|
20
|
-
}
|
|
21
|
-
|
|
22
|
-
export function createTimer(): Timer {
|
|
23
|
-
const marks: Array<[string, number]> = [];
|
|
24
|
-
let last = performance.now();
|
|
25
|
-
return {
|
|
26
|
-
mark(name) {
|
|
27
|
-
const now = performance.now();
|
|
28
|
-
marks.push([name, now - last]);
|
|
29
|
-
last = now;
|
|
30
|
-
},
|
|
31
|
-
headers() {
|
|
32
|
-
if (!enabled || marks.length === 0) return {};
|
|
33
|
-
return {
|
|
34
|
-
"Server-Timing": marks
|
|
35
|
-
.map(([n, d]) => `${n};dur=${d.toFixed(1)}`)
|
|
36
|
-
.join(", "),
|
|
37
|
-
};
|
|
38
|
-
},
|
|
39
|
-
};
|
|
40
|
-
}
|
|
1
|
+
/**
|
|
2
|
+
* `Server-Timing` for route renders, so the browser's network panel shows
|
|
3
|
+
* where a slow page spent its time (`load` = layout and page server loads,
|
|
4
|
+
* `render` = components to HTML) without any extra tooling.
|
|
5
|
+
*
|
|
6
|
+
* On in dev; in production only when `serverTiming: true`, since durations are
|
|
7
|
+
* visible to every visitor.
|
|
8
|
+
*/
|
|
9
|
+
let enabled = false;
|
|
10
|
+
|
|
11
|
+
export function setServerTiming(on: boolean): void {
|
|
12
|
+
enabled = on;
|
|
13
|
+
}
|
|
14
|
+
|
|
15
|
+
export interface Timer {
|
|
16
|
+
/** Close the phase that has been running since the last mark. */
|
|
17
|
+
mark(name: string): void;
|
|
18
|
+
/** `{ "Server-Timing": ... }`, or nothing when disabled or no marks. */
|
|
19
|
+
headers(): Record<string, string>;
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
export function createTimer(): Timer {
|
|
23
|
+
const marks: Array<[string, number]> = [];
|
|
24
|
+
let last = performance.now();
|
|
25
|
+
return {
|
|
26
|
+
mark(name) {
|
|
27
|
+
const now = performance.now();
|
|
28
|
+
marks.push([name, now - last]);
|
|
29
|
+
last = now;
|
|
30
|
+
},
|
|
31
|
+
headers() {
|
|
32
|
+
if (!enabled || marks.length === 0) return {};
|
|
33
|
+
return {
|
|
34
|
+
"Server-Timing": marks
|
|
35
|
+
.map(([n, d]) => `${n};dur=${d.toFixed(1)}`)
|
|
36
|
+
.join(", "),
|
|
37
|
+
};
|
|
38
|
+
},
|
|
39
|
+
};
|
|
40
|
+
}
|
|
@@ -0,0 +1,65 @@
|
|
|
1
|
+
import type { RouteFile, RouteTree } from "./scanner";
|
|
2
|
+
|
|
3
|
+
/** A route's id, from its URL pattern: `/blog/:slug` → `/blog/[slug]`. */
|
|
4
|
+
export function routeId(file: RouteFile): string {
|
|
5
|
+
if (file.id) return file.id;
|
|
6
|
+
return (
|
|
7
|
+
file.path
|
|
8
|
+
.split("/")
|
|
9
|
+
.map((seg) => {
|
|
10
|
+
if (seg.startsWith("*")) return `[...${seg.slice(1)}]`;
|
|
11
|
+
if (seg.startsWith(":")) {
|
|
12
|
+
const optional = seg.endsWith("?");
|
|
13
|
+
const name = seg.slice(1, optional ? -1 : undefined);
|
|
14
|
+
const matcher = file.paramMatchers[name];
|
|
15
|
+
const inner = matcher ? `${name}=${matcher}` : name;
|
|
16
|
+
return optional ? `[[${inner}]]` : `[${inner}]`;
|
|
17
|
+
}
|
|
18
|
+
return seg;
|
|
19
|
+
})
|
|
20
|
+
.join("/") || "/"
|
|
21
|
+
);
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
/** The routes a link can point at: pages and +server endpoints, by id. */
|
|
25
|
+
export function linkableRoutes(tree: RouteTree): RouteFile[] {
|
|
26
|
+
const seen = new Map<string, RouteFile>();
|
|
27
|
+
for (const r of [...tree.routes, ...tree.servers]) {
|
|
28
|
+
if (r.type === "page" || r.type === "simple" || r.type === "server") {
|
|
29
|
+
seen.set(routeId(r), r);
|
|
30
|
+
}
|
|
31
|
+
}
|
|
32
|
+
return [...seen.values()];
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
/** `.grimoire/types/routes.d.ts`: the Routes interface `route()` checks against. */
|
|
36
|
+
export function generateRouteTypes(tree: RouteTree): string {
|
|
37
|
+
const lines = linkableRoutes(tree)
|
|
38
|
+
.map((r) => {
|
|
39
|
+
const fields = [
|
|
40
|
+
...r.paramNames
|
|
41
|
+
.filter(
|
|
42
|
+
(n) =>
|
|
43
|
+
!r.optionalParamNames.includes(n) &&
|
|
44
|
+
!r.restParamNames.includes(n),
|
|
45
|
+
)
|
|
46
|
+
.map((n) => `${n}: string`),
|
|
47
|
+
...r.optionalParamNames.map((n) => `${n}?: string`),
|
|
48
|
+
...r.restParamNames.map((n) => `${n}?: string | readonly string[]`),
|
|
49
|
+
];
|
|
50
|
+
const body = fields.length ? `{ ${fields.join("; ")} }` : "{}";
|
|
51
|
+
return `\t\t${JSON.stringify(routeId(r))}: ${body};`;
|
|
52
|
+
})
|
|
53
|
+
.sort();
|
|
54
|
+
return [
|
|
55
|
+
"// Auto-generated by @sigil-dev/grimoire from src/routes — do not edit",
|
|
56
|
+
'import "@sigil-dev/grimoire";',
|
|
57
|
+
"",
|
|
58
|
+
'declare module "@sigil-dev/grimoire" {',
|
|
59
|
+
"\tinterface Routes {",
|
|
60
|
+
...lines,
|
|
61
|
+
"\t}",
|
|
62
|
+
"}",
|
|
63
|
+
"",
|
|
64
|
+
].join("\n");
|
|
65
|
+
}
|
|
@@ -0,0 +1,65 @@
|
|
|
1
|
+
import { withBase } from "../base";
|
|
2
|
+
|
|
3
|
+
/**
|
|
4
|
+
* Every route of the app, by id, with its params. Empty here; the generated
|
|
5
|
+
* `.grimoire/types/routes.d.ts` fills it from src/routes.
|
|
6
|
+
*
|
|
7
|
+
* An id is the route's folder path: `/blog/[slug]`, `/[[lang]]/about`,
|
|
8
|
+
* `/docs/[...rest]`, `/post/[id=int]`.
|
|
9
|
+
*/
|
|
10
|
+
// biome-ignore lint/suspicious/noEmptyInterface: filled by module augmentation
|
|
11
|
+
export interface Routes {}
|
|
12
|
+
|
|
13
|
+
type RouteId = [keyof Routes] extends [never] ? string : keyof Routes & string;
|
|
14
|
+
type ParamsOf<K> = K extends keyof Routes
|
|
15
|
+
? Routes[K]
|
|
16
|
+
: Record<string, string | readonly string[] | undefined>;
|
|
17
|
+
|
|
18
|
+
const PARAM =
|
|
19
|
+
/\[\[\.\.\.(\w+)\]\]|\[\.\.\.(\w+)\]|\[\[(\w+)(?:=\w+)?\]\]|\[(\w+)(?:=\w+)?\]/g;
|
|
20
|
+
|
|
21
|
+
/**
|
|
22
|
+
* The URL of a route, with its params filled in and the base in front:
|
|
23
|
+
* what `<a href>`, `redirect()` and `fetch` take.
|
|
24
|
+
*
|
|
25
|
+
* ```ts
|
|
26
|
+
* <a href={route("/blog/[slug]", { slug: post.slug })}>…</a>
|
|
27
|
+
* route("/") // "/" (or "/repo/" under a base)
|
|
28
|
+
* route("/docs/[...rest]", { rest: ["guide", "install"] }) // "/docs/guide/install"
|
|
29
|
+
* ```
|
|
30
|
+
*
|
|
31
|
+
* The id is checked against src/routes, and the params against the route:
|
|
32
|
+
* a renamed route or a missing param is a type error, not a 404.
|
|
33
|
+
*/
|
|
34
|
+
export function route<K extends RouteId>(
|
|
35
|
+
id: K,
|
|
36
|
+
...params: {} extends ParamsOf<K>
|
|
37
|
+
? [params?: ParamsOf<K>]
|
|
38
|
+
: [params: ParamsOf<K>]
|
|
39
|
+
): string {
|
|
40
|
+
const values = (params[0] ?? {}) as Record<string, unknown>;
|
|
41
|
+
const filled = (id as string).replace(
|
|
42
|
+
PARAM,
|
|
43
|
+
(_m, optRest: string, rest: string, opt: string, required: string) => {
|
|
44
|
+
const name = optRest ?? rest ?? opt ?? required;
|
|
45
|
+
const value = values[name];
|
|
46
|
+
if (
|
|
47
|
+
value === undefined ||
|
|
48
|
+
value === "" ||
|
|
49
|
+
(Array.isArray(value) && value.length === 0)
|
|
50
|
+
) {
|
|
51
|
+
if (required) {
|
|
52
|
+
throw new Error(`route("${id}"): the param "${name}" is missing`);
|
|
53
|
+
}
|
|
54
|
+
return "";
|
|
55
|
+
}
|
|
56
|
+
if (Array.isArray(value))
|
|
57
|
+
return value.map((v) => encodeURIComponent(String(v))).join("/");
|
|
58
|
+
if (optRest ?? rest)
|
|
59
|
+
return String(value).split("/").map(encodeURIComponent).join("/");
|
|
60
|
+
return encodeURIComponent(String(value));
|
|
61
|
+
},
|
|
62
|
+
);
|
|
63
|
+
const path = filled.replace(/\/{2,}/g, "/").replace(/(.)\/$/, "$1") || "/";
|
|
64
|
+
return withBase(path);
|
|
65
|
+
}
|
package/src/routing/router.ts
CHANGED
|
@@ -11,7 +11,49 @@ export interface MatchedRoute {
|
|
|
11
11
|
}
|
|
12
12
|
|
|
13
13
|
/** The folder a route file sits in, as written on disk: /src/routes/(app)/plan. */
|
|
14
|
-
const folderOf = (f: RouteFile) =>
|
|
14
|
+
const folderOf = (f: RouteFile) =>
|
|
15
|
+
f.clientPath.slice(0, f.clientPath.lastIndexOf("/"));
|
|
16
|
+
|
|
17
|
+
/**
|
|
18
|
+
* What a page's match needs besides its params: fixed once the tree is
|
|
19
|
+
* scanned, so worked out on a route's first match instead of every request.
|
|
20
|
+
* A rescan makes a new tree, which starts with nothing cached.
|
|
21
|
+
*/
|
|
22
|
+
type Surroundings = Pick<
|
|
23
|
+
MatchedRoute,
|
|
24
|
+
"layouts" | "layoutServers" | "pageServer"
|
|
25
|
+
>;
|
|
26
|
+
const surroundings = new WeakMap<RouteTree, WeakMap<RouteFile, Surroundings>>();
|
|
27
|
+
|
|
28
|
+
function surroundingsOf(tree: RouteTree, route: RouteFile): Surroundings {
|
|
29
|
+
let perTree = surroundings.get(tree);
|
|
30
|
+
if (!perTree) surroundings.set(tree, (perTree = new WeakMap()));
|
|
31
|
+
let found = perTree.get(route);
|
|
32
|
+
if (found) return found;
|
|
33
|
+
// A layout wraps its own folder and the folders below it, so compare
|
|
34
|
+
// folders on disk, not URL patterns: (app)/+layout.tsx has the URL "/"
|
|
35
|
+
// once the group is stripped, yet must not wrap login/+page.tsx.
|
|
36
|
+
const routeDir = folderOf(route);
|
|
37
|
+
const layoutMatches = (l: RouteFile) => {
|
|
38
|
+
const dir = folderOf(l);
|
|
39
|
+
return routeDir === dir || routeDir.startsWith(`${dir}/`);
|
|
40
|
+
};
|
|
41
|
+
const outermostFirst = (a: RouteFile, b: RouteFile) =>
|
|
42
|
+
folderOf(a).length - folderOf(b).length;
|
|
43
|
+
found = {
|
|
44
|
+
layouts: tree.layouts
|
|
45
|
+
.filter((l) => l.type === "layout" && layoutMatches(l))
|
|
46
|
+
.sort(outermostFirst),
|
|
47
|
+
layoutServers: tree.layouts
|
|
48
|
+
.filter((l) => l.type === "layoutServer" && layoutMatches(l))
|
|
49
|
+
.sort(outermostFirst),
|
|
50
|
+
pageServer: tree.routes.find(
|
|
51
|
+
(r) => r.type === "pageServer" && r.path === route.path,
|
|
52
|
+
),
|
|
53
|
+
};
|
|
54
|
+
perTree.set(route, found);
|
|
55
|
+
return found;
|
|
56
|
+
}
|
|
15
57
|
|
|
16
58
|
export function matchRoute(
|
|
17
59
|
tree: RouteTree,
|
|
@@ -48,30 +90,15 @@ export function matchRoute(
|
|
|
48
90
|
}
|
|
49
91
|
}
|
|
50
92
|
if (!matched) continue;
|
|
51
|
-
|
|
52
|
-
//
|
|
53
|
-
|
|
54
|
-
|
|
55
|
-
|
|
56
|
-
|
|
57
|
-
|
|
93
|
+
const { layouts, layoutServers, pageServer } = surroundingsOf(tree, route);
|
|
94
|
+
// copies: a caller may add to them, and the cached ones are shared
|
|
95
|
+
return {
|
|
96
|
+
route,
|
|
97
|
+
params,
|
|
98
|
+
layouts: [...layouts],
|
|
99
|
+
layoutServers: [...layoutServers],
|
|
100
|
+
pageServer,
|
|
58
101
|
};
|
|
59
|
-
const outermostFirst = (a: RouteFile, b: RouteFile) =>
|
|
60
|
-
folderOf(a).length - folderOf(b).length;
|
|
61
|
-
|
|
62
|
-
const layouts = tree.layouts
|
|
63
|
-
.filter((l) => l.type === "layout" && layoutMatches(l))
|
|
64
|
-
.sort(outermostFirst);
|
|
65
|
-
|
|
66
|
-
const layoutServers = tree.layouts
|
|
67
|
-
.filter((l) => l.type === "layoutServer" && layoutMatches(l))
|
|
68
|
-
.sort(outermostFirst);
|
|
69
|
-
|
|
70
|
-
const pageServer = tree.routes.find(
|
|
71
|
-
(r) => r.type === "pageServer" && r.path === route.path,
|
|
72
|
-
);
|
|
73
|
-
|
|
74
|
-
return { route, params, layouts, layoutServers, pageServer };
|
|
75
102
|
}
|
|
76
103
|
|
|
77
104
|
return null;
|
|
@@ -145,11 +172,30 @@ export function matchNotFound(tree: RouteTree, url: URL): MatchedRoute {
|
|
|
145
172
|
};
|
|
146
173
|
}
|
|
147
174
|
|
|
175
|
+
/** A pattern's segments, split once per pattern rather than per request. */
|
|
176
|
+
const patternCache = new Map<string, string[]>();
|
|
177
|
+
|
|
178
|
+
/** A path segment as the page should see it: "caf%C3%A9" is "café". Malformed escapes stay as sent. */
|
|
179
|
+
function decodeSegment(raw: string): string {
|
|
180
|
+
if (!raw.includes("%")) return raw;
|
|
181
|
+
try {
|
|
182
|
+
return decodeURIComponent(raw);
|
|
183
|
+
} catch {
|
|
184
|
+
return raw;
|
|
185
|
+
}
|
|
186
|
+
}
|
|
187
|
+
|
|
148
188
|
function matchPattern(
|
|
149
189
|
pattern: string,
|
|
150
190
|
pathname: string,
|
|
151
191
|
): Record<string, string> | null {
|
|
152
|
-
|
|
192
|
+
let cached = patternCache.get(pattern);
|
|
193
|
+
if (!cached) {
|
|
194
|
+
cached = pattern.split("/").filter(Boolean);
|
|
195
|
+
if (patternCache.size > 5000) patternCache.clear();
|
|
196
|
+
patternCache.set(pattern, cached);
|
|
197
|
+
}
|
|
198
|
+
const patternParts: string[] = cached;
|
|
153
199
|
const pathParts = pathname.split("/").filter(Boolean);
|
|
154
200
|
|
|
155
201
|
const params: Record<string, string> = {};
|
|
@@ -164,15 +210,21 @@ function matchPattern(
|
|
|
164
210
|
if (patternPart.startsWith("*")) {
|
|
165
211
|
// Rest param — captures zero or more remaining segments joined by "/".
|
|
166
212
|
// Rest must be the last segment in the pattern.
|
|
167
|
-
params[patternPart.slice(1)] = pathParts
|
|
213
|
+
params[patternPart.slice(1)] = pathParts
|
|
214
|
+
.slice(pj)
|
|
215
|
+
.map(decodeSegment)
|
|
216
|
+
.join("/");
|
|
168
217
|
return true;
|
|
169
218
|
}
|
|
170
219
|
|
|
171
|
-
|
|
172
|
-
|
|
173
|
-
|
|
220
|
+
if (
|
|
221
|
+
patternPart.length > 2 &&
|
|
222
|
+
patternPart[0] === ":" &&
|
|
223
|
+
patternPart.endsWith("?")
|
|
224
|
+
) {
|
|
225
|
+
const name = patternPart.slice(1, -1);
|
|
174
226
|
if (pj < pathParts.length) {
|
|
175
|
-
params[name] = pathParts[pj]
|
|
227
|
+
params[name] = decodeSegment(pathParts[pj]!);
|
|
176
228
|
if (walk(pi + 1, pj + 1)) return true;
|
|
177
229
|
delete params[name];
|
|
178
230
|
}
|
|
@@ -182,10 +234,10 @@ function matchPattern(
|
|
|
182
234
|
if (pj >= pathParts.length) return false;
|
|
183
235
|
|
|
184
236
|
if (patternPart.startsWith(":")) {
|
|
185
|
-
params[patternPart.slice(1)] = pathParts[pj]
|
|
237
|
+
params[patternPart.slice(1)] = decodeSegment(pathParts[pj]!);
|
|
186
238
|
return walk(pi + 1, pj + 1);
|
|
187
239
|
}
|
|
188
|
-
if (patternPart !== pathParts[pj]) return false;
|
|
240
|
+
if (patternPart !== decodeSegment(pathParts[pj]!)) return false;
|
|
189
241
|
return walk(pi + 1, pj + 1);
|
|
190
242
|
}
|
|
191
243
|
|
package/src/routing/scanner.ts
CHANGED
|
@@ -18,6 +18,8 @@ export interface RouteFile {
|
|
|
18
18
|
restParamNames: string[]; // ["rest"] in /blog/*rest
|
|
19
19
|
/** param name → matcher name; ["id"] → "int" for /post/[id=int] */
|
|
20
20
|
paramMatchers: Record<string, string>;
|
|
21
|
+
/** The route's id: its folder path, `/docs/[[...slug]]`. What `route()` takes. */
|
|
22
|
+
id?: string;
|
|
21
23
|
}
|
|
22
24
|
|
|
23
25
|
/** A src/params/<name>.ts module exporting match(value: string): boolean. */
|
|
@@ -43,6 +45,7 @@ export function filePathToRoutePath(
|
|
|
43
45
|
optionalParams: string[];
|
|
44
46
|
restParams: string[];
|
|
45
47
|
paramMatchers: Record<string, string>;
|
|
48
|
+
id: string;
|
|
46
49
|
} {
|
|
47
50
|
const rel = relative(routesDir, filePath)
|
|
48
51
|
.replace(/\\/g, "/")
|
|
@@ -90,7 +93,11 @@ export function filePathToRoutePath(
|
|
|
90
93
|
.replace(/^\/?/, "/") || // ensure leading slash
|
|
91
94
|
"/";
|
|
92
95
|
|
|
93
|
-
|
|
96
|
+
const id =
|
|
97
|
+
`/${rel.replace(/\/?(\+\w+(\.\w+)?|index)$/, "")}`
|
|
98
|
+
.replace(/\/{2,}/g, "/")
|
|
99
|
+
.replace(/\/+$/, "") || "/";
|
|
100
|
+
return { pattern, params, optionalParams, restParams, paramMatchers, id };
|
|
94
101
|
}
|
|
95
102
|
|
|
96
103
|
const TEST_FILE = /[._](test|spec)\.[jt]sx?$/;
|
|
@@ -124,7 +131,7 @@ export async function scanRoutes(
|
|
|
124
131
|
if (TEST_FILE.test(file)) continue;
|
|
125
132
|
const filePath = join(routesDir, file);
|
|
126
133
|
const name = basename(file).replace(/\.(tsx?|jsx?)$/, "");
|
|
127
|
-
const { pattern, params, optionalParams, restParams, paramMatchers } =
|
|
134
|
+
const { pattern, params, optionalParams, restParams, paramMatchers, id } =
|
|
128
135
|
filePathToRoutePath(filePath, routesDir);
|
|
129
136
|
|
|
130
137
|
let type: RouteFile["type"];
|
|
@@ -147,6 +154,7 @@ export async function scanRoutes(
|
|
|
147
154
|
optionalParamNames: optionalParams,
|
|
148
155
|
restParamNames: restParams,
|
|
149
156
|
paramMatchers,
|
|
157
|
+
id,
|
|
150
158
|
};
|
|
151
159
|
|
|
152
160
|
if (type === "simple" || type === "page" || type === "pageServer")
|
|
@@ -192,7 +200,8 @@ export async function scanRoutes(
|
|
|
192
200
|
return { routes, layouts, servers, errors, paramMatcherFiles };
|
|
193
201
|
}
|
|
194
202
|
|
|
195
|
-
const folderOf = (f: RouteFile) =>
|
|
203
|
+
const folderOf = (f: RouteFile) =>
|
|
204
|
+
f.clientPath.slice(0, f.clientPath.lastIndexOf("/"));
|
|
196
205
|
|
|
197
206
|
function assertNoDuplicatePaths(
|
|
198
207
|
files: RouteFile[],
|
|
@@ -220,9 +229,13 @@ function assertNoDuplicatePaths(
|
|
|
220
229
|
*/
|
|
221
230
|
function assertEveryPageServerHasAPage(routes: RouteFile[]): void {
|
|
222
231
|
const pages = new Set(
|
|
223
|
-
routes
|
|
232
|
+
routes
|
|
233
|
+
.filter((r) => r.type === "page" || r.type === "simple")
|
|
234
|
+
.map((r) => r.path),
|
|
235
|
+
);
|
|
236
|
+
const orphans = routes.filter(
|
|
237
|
+
(r) => r.type === "pageServer" && !pages.has(r.path),
|
|
224
238
|
);
|
|
225
|
-
const orphans = routes.filter((r) => r.type === "pageServer" && !pages.has(r.path));
|
|
226
239
|
if (!orphans.length) return;
|
|
227
240
|
throw new Error(
|
|
228
241
|
orphans
|