@sigil-dev/grimoire 0.9.4 → 0.9.6

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 (78) hide show
  1. package/index.ts +37 -37
  2. package/package.json +3 -3
  3. package/preload.js +3 -3
  4. package/server.ts +19 -19
  5. package/src/client/deps.ts +36 -36
  6. package/src/client/enhance.ts +102 -102
  7. package/src/client/head.ts +30 -30
  8. package/src/client/index.ts +5 -5
  9. package/src/client/router.ts +128 -38
  10. package/src/client/scope.ts +22 -22
  11. package/src/dev/compile-module.ts +215 -163
  12. package/src/dev/effect-registry.ts +23 -23
  13. package/src/dev/graph.ts +109 -114
  14. package/src/dev/hmr-client.ts +202 -185
  15. package/src/dev/hmr-server.ts +261 -187
  16. package/src/dev/loader.ts +120 -47
  17. package/src/dev/paths.ts +14 -14
  18. package/src/dev/resolve.ts +70 -0
  19. package/src/dev/runtime-bundle.ts +52 -52
  20. package/src/dev/scan.ts +78 -0
  21. package/src/dev/watcher.ts +69 -47
  22. package/src/env/dynamic-private.ts +19 -19
  23. package/src/env/dynamic-public.ts +22 -22
  24. package/src/env/index.ts +25 -25
  25. package/src/env/plugin.ts +19 -19
  26. package/src/env/private.ts +5 -5
  27. package/src/env/public.ts +7 -7
  28. package/src/env/typegen.ts +61 -61
  29. package/src/headers.ts +114 -114
  30. package/src/integrations/vite.ts +73 -73
  31. package/src/logger/index.ts +4 -4
  32. package/src/logger/instance.ts +6 -6
  33. package/src/logger/logger.ts +113 -113
  34. package/src/logger/request-middleware.ts +24 -24
  35. package/src/logger/transports.ts +117 -117
  36. package/src/logger/types.ts +39 -39
  37. package/src/rendering/head.ts +52 -47
  38. package/src/rendering/hydrate.ts +16 -3
  39. package/src/rendering/index.ts +43 -17
  40. package/src/rendering/ssrPlugin.ts +78 -69
  41. package/src/routing/manifest-gen.ts +55 -55
  42. package/src/routing/router.ts +135 -135
  43. package/src/routing/scanner.ts +196 -187
  44. package/src/routing/transform-routes.ts +102 -102
  45. package/src/sentinels/error.ts +52 -52
  46. package/src/sentinels/fail.ts +41 -41
  47. package/src/sentinels/redirect.ts +35 -35
  48. package/src/server/build.ts +250 -255
  49. package/src/server/context.ts +10 -10
  50. package/src/server/cookie-utils.ts +66 -66
  51. package/src/server/coordinator.ts +1 -1
  52. package/src/server/hooks.ts +114 -114
  53. package/src/server/index.ts +110 -69
  54. package/src/server/interactive.ts +56 -56
  55. package/src/server/plugins.ts +121 -121
  56. package/src/server/worker.ts +58 -58
  57. package/src/typegen/index.ts +389 -389
  58. package/src/types.ts +286 -286
  59. package/test/client-router.test.ts +76 -8
  60. package/test/context.test.ts +52 -52
  61. package/test/env.test.ts +90 -90
  62. package/test/exports.test.ts +37 -37
  63. package/test/fail.test.ts +46 -46
  64. package/test/headers.test.ts +100 -100
  65. package/test/hmr.test.ts +426 -0
  66. package/test/hydration.test.ts +119 -119
  67. package/test/middleware.test.ts +223 -223
  68. package/test/preload.ts +5 -5
  69. package/test/redirect-error.test.ts +112 -112
  70. package/test/rendering.test.ts +719 -728
  71. package/test/routing.test.ts +197 -194
  72. package/test/scanning.test.ts +314 -254
  73. package/test/scope.test.ts +195 -195
  74. package/test/server.test.ts +360 -354
  75. package/test/streaming.test.ts +40 -1
  76. package/test/transform-routes.test.ts +87 -87
  77. package/test/typegen.test.ts +697 -697
  78. package/tsconfig.json +10 -10
@@ -1,135 +1,135 @@
1
- import type { RouteFile, RouteTree } from "./scanner";
2
-
3
- export interface MatchedRoute {
4
- route: RouteFile;
5
- params: Record<string, string>;
6
- layouts: RouteFile[]; // was: layout?: RouteFile
7
- layoutServers: RouteFile[]; // was: layoutServer?: RouteFile
8
- pageServer?: RouteFile;
9
- }
10
-
11
- export function matchRoute(
12
- tree: RouteTree,
13
- url: URL,
14
- matchers?: Record<string, (value: string) => boolean>,
15
- ): MatchedRoute | null {
16
- const pathname = url.pathname;
17
-
18
- // check server routes first
19
- for (const server of tree.servers) {
20
- const params = matchPattern(server.path, pathname);
21
- if (params !== null)
22
- return {
23
- route: server,
24
- params,
25
- layouts: [],
26
- layoutServers: [],
27
- };
28
- }
29
-
30
- // then pages
31
- for (const route of tree.routes) {
32
- if (route.type === "pageServer") continue;
33
- const params = matchPattern(route.path, pathname);
34
- if (params === null) continue;
35
-
36
- // [param=matcher] validation — a false matcher rejects the route
37
- let matched = true;
38
- for (const [param, name] of Object.entries(route.paramMatchers ?? {})) {
39
- const fn = matchers?.[name];
40
- if (!fn || !fn(params[param] ?? "")) {
41
- matched = false;
42
- break;
43
- }
44
- }
45
- if (!matched) continue;
46
- // find applicable layouts by matching route pattern prefix, not URL pathname.
47
- // pathname.startsWith(l.path) would fail for parameterized layouts like /w/:workspace.
48
- const layoutMatches = (l: RouteFile) =>
49
- l.path === "/" ||
50
- route.path === l.path ||
51
- route.path.startsWith(`${l.path}/`);
52
-
53
- const layouts = tree.layouts
54
- .filter((l) => l.type === "layout" && layoutMatches(l))
55
- .sort((a, b) => a.path.length - b.path.length); // root first, innermost last
56
-
57
- const layoutServers = tree.layouts
58
- .filter((l) => l.type === "layoutServer" && layoutMatches(l))
59
- .sort((a, b) => a.path.length - b.path.length); // root first, innermost last
60
-
61
- const pageServer = tree.routes.find(
62
- (r) => r.type === "pageServer" && r.path === route.path,
63
- );
64
-
65
- return { route, params, layouts, layoutServers, pageServer };
66
- }
67
-
68
- return null;
69
- }
70
-
71
- export function findClosestError(
72
- errors: RouteFile[],
73
- pathname: string,
74
- ): RouteFile | null {
75
- const segments = pathname.split("/").filter(Boolean);
76
-
77
- // walk from most specific to root
78
- while (segments.length >= 0) {
79
- const prefix = `/${segments.join("/")}`;
80
- const error = errors.find(
81
- (e) => e.path === prefix || e.path === `${prefix}/`,
82
- );
83
- if (error) return error;
84
- if (segments.length === 0) break;
85
- segments.pop();
86
- }
87
- return null;
88
- }
89
-
90
- function matchPattern(
91
- pattern: string,
92
- pathname: string,
93
- ): Record<string, string> | null {
94
- const patternParts = pattern.split("/").filter(Boolean);
95
- const pathParts = pathname.split("/").filter(Boolean);
96
-
97
- const params: Record<string, string> = {};
98
-
99
- // Depth-first walk over (patternIndex, pathIndex). Optional segments try
100
- // consuming one path segment first, then zero — so /[[lang]]/about matches
101
- // both /en/about and /about.
102
- function walk(pi: number, pj: number): boolean {
103
- if (pi === patternParts.length) return pj === pathParts.length;
104
- const patternPart = patternParts[pi]!;
105
-
106
- if (patternPart.startsWith("*")) {
107
- // Rest param — captures zero or more remaining segments joined by "/".
108
- // Rest must be the last segment in the pattern.
109
- params[patternPart.slice(1)] = pathParts.slice(pj).join("/");
110
- return true;
111
- }
112
-
113
- const optional = /^:(.+)\?$/.exec(patternPart);
114
- if (optional) {
115
- const name = optional[1]!;
116
- if (pj < pathParts.length) {
117
- params[name] = pathParts[pj]!;
118
- if (walk(pi + 1, pj + 1)) return true;
119
- delete params[name];
120
- }
121
- return walk(pi + 1, pj);
122
- }
123
-
124
- if (pj >= pathParts.length) return false;
125
-
126
- if (patternPart.startsWith(":")) {
127
- params[patternPart.slice(1)] = pathParts[pj]!;
128
- return walk(pi + 1, pj + 1);
129
- }
130
- if (patternPart !== pathParts[pj]) return false;
131
- return walk(pi + 1, pj + 1);
132
- }
133
-
134
- return walk(0, 0) ? params : null;
135
- }
1
+ import type { RouteFile, RouteTree } from "./scanner";
2
+
3
+ export interface MatchedRoute {
4
+ route: RouteFile;
5
+ params: Record<string, string>;
6
+ layouts: RouteFile[]; // was: layout?: RouteFile
7
+ layoutServers: RouteFile[]; // was: layoutServer?: RouteFile
8
+ pageServer?: RouteFile;
9
+ }
10
+
11
+ export function matchRoute(
12
+ tree: RouteTree,
13
+ url: URL,
14
+ matchers?: Record<string, (value: string) => boolean>,
15
+ ): MatchedRoute | null {
16
+ const pathname = url.pathname;
17
+
18
+ // check server routes first
19
+ for (const server of tree.servers) {
20
+ const params = matchPattern(server.path, pathname);
21
+ if (params !== null)
22
+ return {
23
+ route: server,
24
+ params,
25
+ layouts: [],
26
+ layoutServers: [],
27
+ };
28
+ }
29
+
30
+ // then pages
31
+ for (const route of tree.routes) {
32
+ if (route.type === "pageServer") continue;
33
+ const params = matchPattern(route.path, pathname);
34
+ if (params === null) continue;
35
+
36
+ // [param=matcher] validation — a false matcher rejects the route
37
+ let matched = true;
38
+ for (const [param, name] of Object.entries(route.paramMatchers ?? {})) {
39
+ const fn = matchers?.[name];
40
+ if (!fn || !fn(params[param] ?? "")) {
41
+ matched = false;
42
+ break;
43
+ }
44
+ }
45
+ if (!matched) continue;
46
+ // find applicable layouts by matching route pattern prefix, not URL pathname.
47
+ // pathname.startsWith(l.path) would fail for parameterized layouts like /w/:workspace.
48
+ const layoutMatches = (l: RouteFile) =>
49
+ l.path === "/" ||
50
+ route.path === l.path ||
51
+ route.path.startsWith(`${l.path}/`);
52
+
53
+ const layouts = tree.layouts
54
+ .filter((l) => l.type === "layout" && layoutMatches(l))
55
+ .sort((a, b) => a.path.length - b.path.length); // root first, innermost last
56
+
57
+ const layoutServers = tree.layouts
58
+ .filter((l) => l.type === "layoutServer" && layoutMatches(l))
59
+ .sort((a, b) => a.path.length - b.path.length); // root first, innermost last
60
+
61
+ const pageServer = tree.routes.find(
62
+ (r) => r.type === "pageServer" && r.path === route.path,
63
+ );
64
+
65
+ return { route, params, layouts, layoutServers, pageServer };
66
+ }
67
+
68
+ return null;
69
+ }
70
+
71
+ export function findClosestError(
72
+ errors: RouteFile[],
73
+ pathname: string,
74
+ ): RouteFile | null {
75
+ const segments = pathname.split("/").filter(Boolean);
76
+
77
+ // walk from most specific to root
78
+ while (segments.length >= 0) {
79
+ const prefix = `/${segments.join("/")}`;
80
+ const error = errors.find(
81
+ (e) => e.path === prefix || e.path === `${prefix}/`,
82
+ );
83
+ if (error) return error;
84
+ if (segments.length === 0) break;
85
+ segments.pop();
86
+ }
87
+ return null;
88
+ }
89
+
90
+ function matchPattern(
91
+ pattern: string,
92
+ pathname: string,
93
+ ): Record<string, string> | null {
94
+ const patternParts = pattern.split("/").filter(Boolean);
95
+ const pathParts = pathname.split("/").filter(Boolean);
96
+
97
+ const params: Record<string, string> = {};
98
+
99
+ // Depth-first walk over (patternIndex, pathIndex). Optional segments try
100
+ // consuming one path segment first, then zero — so /[[lang]]/about matches
101
+ // both /en/about and /about.
102
+ function walk(pi: number, pj: number): boolean {
103
+ if (pi === patternParts.length) return pj === pathParts.length;
104
+ const patternPart = patternParts[pi]!;
105
+
106
+ if (patternPart.startsWith("*")) {
107
+ // Rest param — captures zero or more remaining segments joined by "/".
108
+ // Rest must be the last segment in the pattern.
109
+ params[patternPart.slice(1)] = pathParts.slice(pj).join("/");
110
+ return true;
111
+ }
112
+
113
+ const optional = /^:(.+)\?$/.exec(patternPart);
114
+ if (optional) {
115
+ const name = optional[1]!;
116
+ if (pj < pathParts.length) {
117
+ params[name] = pathParts[pj]!;
118
+ if (walk(pi + 1, pj + 1)) return true;
119
+ delete params[name];
120
+ }
121
+ return walk(pi + 1, pj);
122
+ }
123
+
124
+ if (pj >= pathParts.length) return false;
125
+
126
+ if (patternPart.startsWith(":")) {
127
+ params[patternPart.slice(1)] = pathParts[pj]!;
128
+ return walk(pi + 1, pj + 1);
129
+ }
130
+ if (patternPart !== pathParts[pj]) return false;
131
+ return walk(pi + 1, pj + 1);
132
+ }
133
+
134
+ return walk(0, 0) ? params : null;
135
+ }
@@ -1,187 +1,196 @@
1
- import { existsSync } from "node:fs";
2
- import { basename, join, relative } from "node:path";
3
-
4
- export interface RouteFile {
5
- path: string; // URL (ie /blog/:slug)
6
- filePath: string; // absolute disk path;
7
- clientPath: string; // Relative path (/src/routes/spells/+page.tsx)
8
- type:
9
- | "page"
10
- | "pageServer"
11
- | "layout"
12
- | "layoutServer"
13
- | "server"
14
- | "error"
15
- | "simple";
16
- paramNames: string[]; // ["slug"] in /blog/:slug
17
- optionalParamNames: string[]; // ["lang"] in /[[lang]]
18
- restParamNames: string[]; // ["rest"] in /blog/*rest
19
- /** param name → matcher name; ["id"] → "int" for /post/[id=int] */
20
- paramMatchers: Record<string, string>;
21
- }
22
-
23
- /** A src/params/<name>.ts module exporting match(value: string): boolean. */
24
- export interface ParamMatcherFile {
25
- name: string;
26
- filePath: string;
27
- }
28
-
29
- export interface RouteTree {
30
- routes: RouteFile[];
31
- layouts: RouteFile[]; // layout + layout.server
32
- servers: RouteFile[]; // +server.ts API routes
33
- errors: RouteFile[]; // +error.tsx
34
- paramMatcherFiles: ParamMatcherFile[]; // from src/params/*.ts
35
- }
36
-
37
- export function filePathToRoutePath(
38
- filePath: string,
39
- routesDir: string,
40
- ): {
41
- pattern: string;
42
- params: string[];
43
- optionalParams: string[];
44
- restParams: string[];
45
- paramMatchers: Record<string, string>;
46
- } {
47
- const rel = relative(routesDir, filePath)
48
- .replace(/\\/g, "/")
49
- .replace(/\.(tsx?|jsx?)$/, "")
50
- .replace(/(?:^|\/)(\([^)]+\))(?=\/|$)/g, "") // strip (groupName) anywhere
51
- .replace(/\/+/g, "/"); // collapse double slashes
52
-
53
- const params: string[] = [];
54
- const optionalParams: string[] = [];
55
- const restParams: string[] = [];
56
- const paramMatchers: Record<string, string> = {};
57
- const pattern =
58
- rel
59
- .replace(/\/?(\+\w+(\.\w+)?|index)$/, "") // index/+page → directory
60
- // [[param]] → :param? (must run before [param] — [[x]] contains [x])
61
- .replace(/\[\[([^\]]+)\]\]/g, (_, name: string) => {
62
- optionalParams.push(name);
63
- return `:${name}?`;
64
- })
65
- // [param=matcher] → :param with a validation matcher (before [param])
66
- .replace(/\[([^\]=]+)=([^\]=]+)\]/g, (_, name: string, matcher: string) => {
67
- params.push(name);
68
- paramMatchers[name] = matcher;
69
- return `:${name}`;
70
- })
71
- .replace(/\[(\.\.\.)?([^\]]+)\]/g, (_, dots: string, name: string) => {
72
- // [...rest] → *rest (captures zero or more remaining path segments)
73
- if (dots) {
74
- restParams.push(name);
75
- return `*${name}`;
76
- }
77
- // [param] → :param
78
- params.push(name);
79
- return `:${name}`;
80
- })
81
- .replace(/^\/?/, "/") || // ensure leading slash
82
- "/";
83
-
84
- return { pattern, params, optionalParams, restParams, paramMatchers };
85
- }
86
-
87
- export async function scanRoutes(
88
- routesDir: string,
89
- viteRoot: string = routesDir,
90
- ): Promise<RouteTree> {
91
- const glob = new Bun.Glob("**/*.{tsx,ts,jsx,js}");
92
- const routes: RouteFile[] = [];
93
- const layouts: RouteFile[] = [];
94
- const servers: RouteFile[] = [];
95
- const errors: RouteFile[] = [];
96
-
97
- // convention: src/params/<name>.ts sits beside src/routes
98
- const paramsDir = join(routesDir, "..", "params");
99
- const paramMatcherFiles: ParamMatcherFile[] = [];
100
- if (existsSync(paramsDir)) {
101
- const paramGlob = new Bun.Glob("*.{ts,js}");
102
- for await (const file of paramGlob.scan(paramsDir)) {
103
- paramMatcherFiles.push({
104
- name: basename(file).replace(/\.(ts|js)$/, ""),
105
- filePath: join(paramsDir, file),
106
- });
107
- }
108
- }
109
-
110
- for await (const file of glob.scan(routesDir)) {
111
- const filePath = join(routesDir, file);
112
- const name = basename(file).replace(/\.(tsx?|jsx?)$/, "");
113
- const { pattern, params, optionalParams, restParams, paramMatchers } =
114
- filePathToRoutePath(filePath, routesDir);
115
-
116
- let type: RouteFile["type"];
117
- if (name === "+page") type = "page";
118
- else if (name === "+page.server") type = "pageServer";
119
- else if (name === "+layout") type = "layout";
120
- else if (name === "+layout.server") type = "layoutServer";
121
- else if (name === "+server") type = "server";
122
- else if (name === "+error") type = "error";
123
- else type = "simple";
124
-
125
- const clientPath = `/${relative(viteRoot, filePath).replace(/\\/g, "/")}`;
126
-
127
- const routeFile: RouteFile = {
128
- path: pattern,
129
- filePath,
130
- clientPath, // add this
131
- type,
132
- paramNames: params,
133
- optionalParamNames: optionalParams,
134
- restParamNames: restParams,
135
- paramMatchers,
136
- };
137
-
138
- if (type === "simple" || type === "page" || type === "pageServer")
139
- routes.push(routeFile);
140
- if (type === "layout" || type === "layoutServer") layouts.push(routeFile);
141
- if (type === "server") servers.push(routeFile);
142
- if (type === "error") errors.push(routeFile);
143
- }
144
-
145
- // sort so static routes match before dynamic ones; optional params sort
146
- // between static and required; rest params last
147
- const scoreRoute = (r: RouteFile) =>
148
- r.paramNames.length * 2 +
149
- r.optionalParamNames.length +
150
- r.restParamNames.length * 1000;
151
- routes.sort((a, b) => scoreRoute(a) - scoreRoute(b));
152
- servers.sort((a, b) => scoreRoute(a) - scoreRoute(b));
153
-
154
- assertNoDuplicatePaths(
155
- routes.filter((r) => r.type === "page" || r.type === "simple"),
156
- "page",
157
- );
158
- assertNoDuplicatePaths(
159
- routes.filter((r) => r.type === "pageServer"),
160
- "page server",
161
- );
162
- assertNoDuplicatePaths(
163
- layouts.filter((l) => l.type === "layout"),
164
- "layout",
165
- );
166
- assertNoDuplicatePaths(
167
- layouts.filter((l) => l.type === "layoutServer"),
168
- "layout server",
169
- );
170
- assertNoDuplicatePaths(servers, "API route");
171
- assertNoDuplicatePaths(errors, "error page");
172
-
173
- return { routes, layouts, servers, errors, paramMatcherFiles };
174
- }
175
-
176
- function assertNoDuplicatePaths(files: RouteFile[], label: string): void {
177
- const seen = new Map<string, string>();
178
- for (const file of files) {
179
- const existing = seen.get(file.path);
180
- if (existing) {
181
- throw new Error(
182
- `Duplicate ${label} at "${file.path}": "${existing}" and "${file.clientPath}"`,
183
- );
184
- }
185
- seen.set(file.path, file.clientPath);
186
- }
187
- }
1
+ import { existsSync } from "node:fs";
2
+ import { basename, join, relative } from "node:path";
3
+
4
+ export interface RouteFile {
5
+ path: string; // URL (ie /blog/:slug)
6
+ filePath: string; // absolute disk path;
7
+ clientPath: string; // Relative path (/src/routes/spells/+page.tsx)
8
+ type:
9
+ | "page"
10
+ | "pageServer"
11
+ | "layout"
12
+ | "layoutServer"
13
+ | "server"
14
+ | "error"
15
+ | "simple";
16
+ paramNames: string[]; // ["slug"] in /blog/:slug
17
+ optionalParamNames: string[]; // ["lang"] in /[[lang]]
18
+ restParamNames: string[]; // ["rest"] in /blog/*rest
19
+ /** param name → matcher name; ["id"] → "int" for /post/[id=int] */
20
+ paramMatchers: Record<string, string>;
21
+ }
22
+
23
+ /** A src/params/<name>.ts module exporting match(value: string): boolean. */
24
+ export interface ParamMatcherFile {
25
+ name: string;
26
+ filePath: string;
27
+ }
28
+
29
+ export interface RouteTree {
30
+ routes: RouteFile[];
31
+ layouts: RouteFile[]; // layout + layout.server
32
+ servers: RouteFile[]; // +server.ts API routes
33
+ errors: RouteFile[]; // +error.tsx
34
+ paramMatcherFiles: ParamMatcherFile[]; // from src/params/*.ts
35
+ }
36
+
37
+ export function filePathToRoutePath(
38
+ filePath: string,
39
+ routesDir: string,
40
+ ): {
41
+ pattern: string;
42
+ params: string[];
43
+ optionalParams: string[];
44
+ restParams: string[];
45
+ paramMatchers: Record<string, string>;
46
+ } {
47
+ const rel = relative(routesDir, filePath)
48
+ .replace(/\\/g, "/")
49
+ .replace(/\.(tsx?|jsx?)$/, "")
50
+ .replace(/(?:^|\/)(\([^)]+\))(?=\/|$)/g, "") // strip (groupName) anywhere
51
+ .replace(/\/+/g, "/"); // collapse double slashes
52
+
53
+ const params: string[] = [];
54
+ const optionalParams: string[] = [];
55
+ const restParams: string[] = [];
56
+ const paramMatchers: Record<string, string> = {};
57
+ const pattern =
58
+ rel
59
+ .replace(/\/?(\+\w+(\.\w+)?|index)$/, "") // index/+page → directory
60
+ // [[param]] → :param? (must run before [param] — [[x]] contains [x])
61
+ // [[...rest]] → *rest (before [[param]] — a rest capture is
62
+ // already optional: it matches zero or more segments)
63
+ .replace(/\[\[\.\.\.([^\]]+)\]\]/g, (_, name: string) => {
64
+ restParams.push(name);
65
+ return `*${name}`;
66
+ })
67
+ .replace(/\[\[([^\]]+)\]\]/g, (_, name: string) => {
68
+ optionalParams.push(name);
69
+ return `:${name}?`;
70
+ })
71
+ // [param=matcher] → :param with a validation matcher (before [param])
72
+ .replace(
73
+ /\[([^\]=]+)=([^\]=]+)\]/g,
74
+ (_, name: string, matcher: string) => {
75
+ params.push(name);
76
+ paramMatchers[name] = matcher;
77
+ return `:${name}`;
78
+ },
79
+ )
80
+ .replace(/\[(\.\.\.)?([^\]]+)\]/g, (_, dots: string, name: string) => {
81
+ // [...rest] → *rest (captures zero or more remaining path segments)
82
+ if (dots) {
83
+ restParams.push(name);
84
+ return `*${name}`;
85
+ }
86
+ // [param] → :param
87
+ params.push(name);
88
+ return `:${name}`;
89
+ })
90
+ .replace(/^\/?/, "/") || // ensure leading slash
91
+ "/";
92
+
93
+ return { pattern, params, optionalParams, restParams, paramMatchers };
94
+ }
95
+
96
+ export async function scanRoutes(
97
+ routesDir: string,
98
+ viteRoot: string = routesDir,
99
+ ): Promise<RouteTree> {
100
+ const glob = new Bun.Glob("**/*.{tsx,ts,jsx,js}");
101
+ const routes: RouteFile[] = [];
102
+ const layouts: RouteFile[] = [];
103
+ const servers: RouteFile[] = [];
104
+ const errors: RouteFile[] = [];
105
+
106
+ // convention: src/params/<name>.ts sits beside src/routes
107
+ const paramsDir = join(routesDir, "..", "params");
108
+ const paramMatcherFiles: ParamMatcherFile[] = [];
109
+ if (existsSync(paramsDir)) {
110
+ const paramGlob = new Bun.Glob("*.{ts,js}");
111
+ for await (const file of paramGlob.scan(paramsDir)) {
112
+ paramMatcherFiles.push({
113
+ name: basename(file).replace(/\.(ts|js)$/, ""),
114
+ filePath: join(paramsDir, file),
115
+ });
116
+ }
117
+ }
118
+
119
+ for await (const file of glob.scan(routesDir)) {
120
+ const filePath = join(routesDir, file);
121
+ const name = basename(file).replace(/\.(tsx?|jsx?)$/, "");
122
+ const { pattern, params, optionalParams, restParams, paramMatchers } =
123
+ filePathToRoutePath(filePath, routesDir);
124
+
125
+ let type: RouteFile["type"];
126
+ if (name === "+page") type = "page";
127
+ else if (name === "+page.server") type = "pageServer";
128
+ else if (name === "+layout") type = "layout";
129
+ else if (name === "+layout.server") type = "layoutServer";
130
+ else if (name === "+server") type = "server";
131
+ else if (name === "+error") type = "error";
132
+ else type = "simple";
133
+
134
+ const clientPath = `/${relative(viteRoot, filePath).replace(/\\/g, "/")}`;
135
+
136
+ const routeFile: RouteFile = {
137
+ path: pattern,
138
+ filePath,
139
+ clientPath, // add this
140
+ type,
141
+ paramNames: params,
142
+ optionalParamNames: optionalParams,
143
+ restParamNames: restParams,
144
+ paramMatchers,
145
+ };
146
+
147
+ if (type === "simple" || type === "page" || type === "pageServer")
148
+ routes.push(routeFile);
149
+ if (type === "layout" || type === "layoutServer") layouts.push(routeFile);
150
+ if (type === "server") servers.push(routeFile);
151
+ if (type === "error") errors.push(routeFile);
152
+ }
153
+
154
+ // sort so static routes match before dynamic ones; optional params sort
155
+ // between static and required; rest params last
156
+ const scoreRoute = (r: RouteFile) =>
157
+ r.paramNames.length * 2 +
158
+ r.optionalParamNames.length +
159
+ r.restParamNames.length * 1000;
160
+ routes.sort((a, b) => scoreRoute(a) - scoreRoute(b));
161
+ servers.sort((a, b) => scoreRoute(a) - scoreRoute(b));
162
+
163
+ assertNoDuplicatePaths(
164
+ routes.filter((r) => r.type === "page" || r.type === "simple"),
165
+ "page",
166
+ );
167
+ assertNoDuplicatePaths(
168
+ routes.filter((r) => r.type === "pageServer"),
169
+ "page server",
170
+ );
171
+ assertNoDuplicatePaths(
172
+ layouts.filter((l) => l.type === "layout"),
173
+ "layout",
174
+ );
175
+ assertNoDuplicatePaths(
176
+ layouts.filter((l) => l.type === "layoutServer"),
177
+ "layout server",
178
+ );
179
+ assertNoDuplicatePaths(servers, "API route");
180
+ assertNoDuplicatePaths(errors, "error page");
181
+
182
+ return { routes, layouts, servers, errors, paramMatcherFiles };
183
+ }
184
+
185
+ function assertNoDuplicatePaths(files: RouteFile[], label: string): void {
186
+ const seen = new Map<string, string>();
187
+ for (const file of files) {
188
+ const existing = seen.get(file.path);
189
+ if (existing) {
190
+ throw new Error(
191
+ `Duplicate ${label} at "${file.path}": "${existing}" and "${file.clientPath}"`,
192
+ );
193
+ }
194
+ seen.set(file.path, file.clientPath);
195
+ }
196
+ }