@sigil-dev/grimoire 0.9.21 → 0.9.23

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 (94) hide show
  1. package/README.md +83 -83
  2. package/index.ts +50 -48
  3. package/package.json +22 -10
  4. package/public/__grimoire__/grimoire-client.js +12 -0
  5. package/public/__grimoire__/runtime.js +1241 -0
  6. package/server.ts +22 -20
  7. package/src/adapters/bun.ts +17 -0
  8. package/src/adapters/static.ts +41 -0
  9. package/src/adapters/types.ts +36 -0
  10. package/src/base.ts +91 -0
  11. package/src/client/csrf.ts +47 -47
  12. package/src/client/deferred.ts +179 -179
  13. package/src/client/enhance.ts +160 -160
  14. package/src/client/router.ts +871 -833
  15. package/src/dev/compile-module.ts +211 -211
  16. package/src/dev/loader.ts +141 -141
  17. package/src/dev/resolve.ts +70 -70
  18. package/src/dev/runtime-bundle.ts +51 -51
  19. package/src/env/modules.ts +62 -62
  20. package/src/env/required.ts +42 -0
  21. package/src/env/typegen.ts +61 -61
  22. package/src/headers.ts +105 -105
  23. package/src/logger/transports.ts +117 -117
  24. package/src/rendering/head.ts +49 -49
  25. package/src/rendering/hydrate.ts +161 -161
  26. package/src/rendering/images.ts +43 -43
  27. package/src/rendering/index.ts +755 -749
  28. package/src/rendering/preload.ts +102 -101
  29. package/src/rendering/ssrPlugin.ts +1 -1
  30. package/src/rendering/timing.ts +40 -40
  31. package/src/routing/router.ts +186 -186
  32. package/src/routing/scanner.ts +225 -196
  33. package/src/routing/transform-routes.ts +102 -102
  34. package/src/server/after-response.ts +206 -206
  35. package/src/server/asset-cache.ts +57 -57
  36. package/src/server/build.ts +262 -262
  37. package/src/server/cached.ts +114 -114
  38. package/src/server/client-address.ts +82 -82
  39. package/src/server/client-dir.ts +57 -57
  40. package/src/server/client-entry.ts +44 -44
  41. package/src/server/cookie-utils.ts +80 -80
  42. package/src/server/coordinator.ts +476 -471
  43. package/src/server/hooks.ts +122 -122
  44. package/src/server/index.ts +211 -80
  45. package/src/server/plugins.ts +172 -172
  46. package/src/server/prerender.ts +444 -0
  47. package/src/server/reserved.ts +17 -0
  48. package/src/server/resolver.ts +98 -98
  49. package/src/server/rewrite.ts +28 -0
  50. package/src/server/warm.ts +91 -91
  51. package/src/server/with-headers.ts +27 -27
  52. package/src/server/worker.ts +74 -72
  53. package/src/testing/dom.ts +73 -0
  54. package/src/testing/index.ts +169 -0
  55. package/src/testing/server.ts +162 -0
  56. package/src/typegen/index.ts +450 -450
  57. package/src/types.ts +501 -432
  58. package/test/after-response.test.ts +132 -132
  59. package/test/asset-cache-policy.test.ts +96 -96
  60. package/test/base.test.ts +134 -0
  61. package/test/cached.test.ts +126 -126
  62. package/test/client-address.test.ts +78 -78
  63. package/test/client-csrf.test.ts +61 -61
  64. package/test/client-dir.test.ts +101 -101
  65. package/test/client-router.test.ts +789 -734
  66. package/test/coordinator.test.ts +96 -94
  67. package/test/deferred.test.ts +256 -256
  68. package/test/dev-loader.test.ts +30 -30
  69. package/test/env.test.ts +168 -168
  70. package/test/force-production.test.ts +44 -0
  71. package/test/images.test.ts +49 -49
  72. package/test/locals-header.test.ts +61 -0
  73. package/test/middleware.test.ts +243 -243
  74. package/test/parser-plugins.test.ts +1 -1
  75. package/test/plugin-handle.test.ts +62 -62
  76. package/test/plugin-services-context.test.ts +97 -97
  77. package/test/preload.test.ts +48 -48
  78. package/test/prerender.test.ts +353 -0
  79. package/test/rendering.test.ts +799 -798
  80. package/test/required-env.test.ts +32 -0
  81. package/test/rewrite-html.test.ts +90 -0
  82. package/test/scanning.test.ts +349 -314
  83. package/test/server.test.ts +640 -619
  84. package/test/services.test.ts +90 -90
  85. package/test/streaming.test.ts +381 -378
  86. package/test/testing-helpers.test.ts +166 -0
  87. package/test/typegen.test.ts +808 -799
  88. package/test/warm.test.ts +96 -96
  89. package/test/worker-context.test.ts +59 -59
  90. package/test/workspace-files.test.ts +149 -146
  91. package/test/workspace-versions.test.ts +1 -1
  92. package/.grimoire/_routes.ts +0 -4
  93. package/public/__grimoire__/client.js +0 -55
  94. package/public/__grimoire__/hydrate.js +0 -63
@@ -1,196 +1,225 @@
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({ cwd: routesDir, dot: true })) {
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
- }
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
+ const TEST_FILE = /[._](test|spec)\.[jt]sx?$/;
97
+
98
+ export async function scanRoutes(
99
+ routesDir: string,
100
+ viteRoot: string = routesDir,
101
+ ): Promise<RouteTree> {
102
+ const glob = new Bun.Glob("**/*.{tsx,ts,jsx,js}");
103
+ const routes: RouteFile[] = [];
104
+ const layouts: RouteFile[] = [];
105
+ const servers: RouteFile[] = [];
106
+ const errors: RouteFile[] = [];
107
+
108
+ // convention: src/params/<name>.ts sits beside src/routes
109
+ const paramsDir = join(routesDir, "..", "params");
110
+ const paramMatcherFiles: ParamMatcherFile[] = [];
111
+ if (existsSync(paramsDir)) {
112
+ const paramGlob = new Bun.Glob("*.{ts,js}");
113
+ for await (const file of paramGlob.scan(paramsDir)) {
114
+ paramMatcherFiles.push({
115
+ name: basename(file).replace(/\.(ts|js)$/, ""),
116
+ filePath: join(paramsDir, file),
117
+ });
118
+ }
119
+ }
120
+
121
+ for await (const file of glob.scan({ cwd: routesDir, dot: true })) {
122
+ // A test beside the route it tests is not a route: it would be served
123
+ // at its own URL and bundled for the browser.
124
+ if (TEST_FILE.test(file)) continue;
125
+ const filePath = join(routesDir, file);
126
+ const name = basename(file).replace(/\.(tsx?|jsx?)$/, "");
127
+ const { pattern, params, optionalParams, restParams, paramMatchers } =
128
+ filePathToRoutePath(filePath, routesDir);
129
+
130
+ let type: RouteFile["type"];
131
+ if (name === "+page") type = "page";
132
+ else if (name === "+page.server") type = "pageServer";
133
+ else if (name === "+layout") type = "layout";
134
+ else if (name === "+layout.server") type = "layoutServer";
135
+ else if (name === "+server") type = "server";
136
+ else if (name === "+error") type = "error";
137
+ else type = "simple";
138
+
139
+ const clientPath = `/${relative(viteRoot, filePath).replace(/\\/g, "/")}`;
140
+
141
+ const routeFile: RouteFile = {
142
+ path: pattern,
143
+ filePath,
144
+ clientPath, // add this
145
+ type,
146
+ paramNames: params,
147
+ optionalParamNames: optionalParams,
148
+ restParamNames: restParams,
149
+ paramMatchers,
150
+ };
151
+
152
+ if (type === "simple" || type === "page" || type === "pageServer")
153
+ routes.push(routeFile);
154
+ if (type === "layout" || type === "layoutServer") layouts.push(routeFile);
155
+ if (type === "server") servers.push(routeFile);
156
+ if (type === "error") errors.push(routeFile);
157
+ }
158
+
159
+ // sort so static routes match before dynamic ones; optional params sort
160
+ // between static and required; rest params last
161
+ const scoreRoute = (r: RouteFile) =>
162
+ r.paramNames.length * 2 +
163
+ r.optionalParamNames.length +
164
+ r.restParamNames.length * 1000;
165
+ routes.sort((a, b) => scoreRoute(a) - scoreRoute(b));
166
+ servers.sort((a, b) => scoreRoute(a) - scoreRoute(b));
167
+
168
+ assertNoDuplicatePaths(
169
+ routes.filter((r) => r.type === "page" || r.type === "simple"),
170
+ "page",
171
+ );
172
+ assertNoDuplicatePaths(
173
+ routes.filter((r) => r.type === "pageServer"),
174
+ "page server",
175
+ );
176
+ assertNoDuplicatePaths(
177
+ layouts.filter((l) => l.type === "layout"),
178
+ "layout",
179
+ );
180
+ assertNoDuplicatePaths(
181
+ layouts.filter((l) => l.type === "layoutServer"),
182
+ "layout server",
183
+ );
184
+ assertNoDuplicatePaths(servers, "API route");
185
+ assertNoDuplicatePaths(errors, "error page");
186
+ assertEveryPageServerHasAPage(routes);
187
+
188
+ return { routes, layouts, servers, errors, paramMatcherFiles };
189
+ }
190
+
191
+ function assertNoDuplicatePaths(files: RouteFile[], label: string): void {
192
+ const seen = new Map<string, string>();
193
+ for (const file of files) {
194
+ const existing = seen.get(file.path);
195
+ if (existing) {
196
+ throw new Error(
197
+ `Duplicate ${label} at "${file.path}": "${existing}" and "${file.clientPath}"`,
198
+ );
199
+ }
200
+ seen.set(file.path, file.clientPath);
201
+ }
202
+ }
203
+
204
+ /**
205
+ * A `+page.server.ts` is the server half of a page, so without a `+page.tsx`
206
+ * (or a plain `index.tsx`) beside it there is nothing to render. It used to be
207
+ * dropped from the route table without a word, and a POST-only logout or
208
+ * consent endpoint written that way was simply unreachable.
209
+ */
210
+ function assertEveryPageServerHasAPage(routes: RouteFile[]): void {
211
+ const pages = new Set(
212
+ routes.filter((r) => r.type === "page" || r.type === "simple").map((r) => r.path),
213
+ );
214
+ const orphans = routes.filter((r) => r.type === "pageServer" && !pages.has(r.path));
215
+ if (!orphans.length) return;
216
+ throw new Error(
217
+ orphans
218
+ .map(
219
+ (r) =>
220
+ `${r.clientPath} has no +page.tsx beside it, so "${r.path}" is not a route and the file would be ignored. ` +
221
+ `Add a +page.tsx, or move the handlers to ${r.clientPath.replace("+page.server", "+server")} if this is an endpoint with no page.`,
222
+ )
223
+ .join("\n"),
224
+ );
225
+ }
@@ -1,102 +1,102 @@
1
- import { basename, dirname, join, relative, resolve } from "node:path";
2
- import { transformSync } from "@babel/core";
3
- import sigilPlugin from "@sigil-dev/compiler/babel";
4
- import {
5
- clientStyleSnippet,
6
- computeHash,
7
- extractStyles,
8
- } from "@sigil-dev/compiler/css";
9
- import type { GrimoirePlugin } from "../types";
10
- import type { RouteFile } from "./scanner";
11
-
12
- function rewriteRelativeImports(filePath: string) {
13
- const basedir = dirname(filePath);
14
- const rewrite = (source?: { value: string }) => {
15
- if (!source?.value.startsWith(".")) return;
16
- source.value = resolve(basedir, source.value);
17
- };
18
-
19
- return {
20
- name: "sigil-rewrite-relative-route-imports",
21
- visitor: {
22
- ImportDeclaration(path: any) {
23
- rewrite(path.node.source);
24
- },
25
- ExportNamedDeclaration(path: any) {
26
- rewrite(path.node.source);
27
- },
28
- ExportAllDeclaration(path: any) {
29
- rewrite(path.node.source);
30
- },
31
- CallExpression(path: any) {
32
- if (path.node.callee.type !== "Import") return;
33
- rewrite(path.node.arguments[0]);
34
- },
35
- },
36
- };
37
- }
38
-
39
- /**
40
- * Pre-transforms route .tsx/.jsx files to plain JS using the Babel sigil
41
- * pipeline, writing the output to `outDir`. Returns a Map from the original
42
- * filePath to the compiled .js path.
43
- *
44
- * Workaround for Bun 1.3.13: Bun.build's native parser runs before onLoad
45
- * hooks fire, crashing on TypeScript syntax. Pre-transforming to JS means
46
- * Bun.build only ever sees plain JavaScript.
47
- */
48
- export async function transformRoutes(
49
- routes: RouteFile[],
50
- outDir: string,
51
- mode: "hydrate" | "dom",
52
- plugins: GrimoirePlugin[] = [],
53
- ): Promise<Map<string, string>> {
54
- const map = new Map<string, string>();
55
- // loader: "ts" — Babel already consumed JSX, Bun only strips remaining types
56
- const transpiler = new Bun.Transpiler({ loader: "ts", target: "browser" });
57
-
58
- await Promise.all(
59
- routes.map(async (route, index) => {
60
- // scope classes only where there is scoped CSS to match. The CSS
61
- // used to be dropped here: a route's own <style> never reached
62
- // the browser build
63
- const styles = extractStyles(
64
- await Bun.file(route.filePath).text(),
65
- computeHash(route.filePath),
66
- route.filePath,
67
- );
68
- const code = styles.code;
69
- const hash = styles.css ? computeHash(route.filePath) : undefined;
70
-
71
- const res = transformSync(code, {
72
- configFile: false,
73
- babelrc: false,
74
- parserOpts: {
75
- plugins: ["typescript", "jsx"], // no isTSX
76
- },
77
- plugins: [
78
- [sigilPlugin, { hash, mode }],
79
- //@ts-expect-error it fills what it needs
80
- rewriteRelativeImports(route.filePath),
81
- ],
82
- filename: route.filePath,
83
- });
84
- let out = transpiler.transformSync(res?.code ?? "");
85
- if (styles.css && hash) out = clientStyleSnippet(hash, styles.css) + out;
86
- for (const plugin of plugins) {
87
- if (plugin.transform)
88
- out = (await plugin.transform(out, route.filePath)) ?? out;
89
- }
90
-
91
- const rel = relative(process.cwd(), route.filePath)
92
- .replace(/\.tsx?$/, "")
93
- .replace(/[^a-zA-Z0-9._-]/g, "_");
94
- const nameBase = rel || basename(route.filePath).replace(/\.[jt]sx$/, "");
95
- const outPath = join(outDir, `${index}-${nameBase}.${mode}.js`);
96
-
97
- await Bun.write(outPath, out);
98
- map.set(route.filePath, outPath);
99
- }),
100
- );
101
- return map;
102
- }
1
+ import { basename, dirname, join, relative, resolve } from "node:path";
2
+ import { transformSync } from "@babel/core";
3
+ import sigilPlugin from "@sigil-dev/compiler/babel";
4
+ import {
5
+ clientStyleSnippet,
6
+ computeHash,
7
+ extractStyles,
8
+ } from "@sigil-dev/compiler/css";
9
+ import type { GrimoirePlugin } from "../types";
10
+ import type { RouteFile } from "./scanner";
11
+
12
+ function rewriteRelativeImports(filePath: string) {
13
+ const basedir = dirname(filePath);
14
+ const rewrite = (source?: { value: string }) => {
15
+ if (!source?.value.startsWith(".")) return;
16
+ source.value = resolve(basedir, source.value);
17
+ };
18
+
19
+ return {
20
+ name: "sigil-rewrite-relative-route-imports",
21
+ visitor: {
22
+ ImportDeclaration(path: any) {
23
+ rewrite(path.node.source);
24
+ },
25
+ ExportNamedDeclaration(path: any) {
26
+ rewrite(path.node.source);
27
+ },
28
+ ExportAllDeclaration(path: any) {
29
+ rewrite(path.node.source);
30
+ },
31
+ CallExpression(path: any) {
32
+ if (path.node.callee.type !== "Import") return;
33
+ rewrite(path.node.arguments[0]);
34
+ },
35
+ },
36
+ };
37
+ }
38
+
39
+ /**
40
+ * Pre-transforms route .tsx/.jsx files to plain JS using the Babel sigil
41
+ * pipeline, writing the output to `outDir`. Returns a Map from the original
42
+ * filePath to the compiled .js path.
43
+ *
44
+ * Workaround for Bun 1.3.13: Bun.build's native parser runs before onLoad
45
+ * hooks fire, crashing on TypeScript syntax. Pre-transforming to JS means
46
+ * Bun.build only ever sees plain JavaScript.
47
+ */
48
+ export async function transformRoutes(
49
+ routes: RouteFile[],
50
+ outDir: string,
51
+ mode: "hydrate" | "dom",
52
+ plugins: GrimoirePlugin[] = [],
53
+ ): Promise<Map<string, string>> {
54
+ const map = new Map<string, string>();
55
+ // loader: "ts" — Babel already consumed JSX, Bun only strips remaining types
56
+ const transpiler = new Bun.Transpiler({ loader: "ts", target: "browser" });
57
+
58
+ await Promise.all(
59
+ routes.map(async (route, index) => {
60
+ // scope classes only where there is scoped CSS to match. The CSS
61
+ // used to be dropped here: a route's own <style> never reached
62
+ // the browser build
63
+ const styles = extractStyles(
64
+ await Bun.file(route.filePath).text(),
65
+ computeHash(route.filePath),
66
+ route.filePath,
67
+ );
68
+ const code = styles.code;
69
+ const hash = styles.css ? computeHash(route.filePath) : undefined;
70
+
71
+ const res = transformSync(code, {
72
+ configFile: false,
73
+ babelrc: false,
74
+ parserOpts: {
75
+ plugins: ["typescript", "jsx"], // no isTSX
76
+ },
77
+ plugins: [
78
+ [sigilPlugin, { hash, mode }],
79
+ //@ts-expect-error it fills what it needs
80
+ rewriteRelativeImports(route.filePath),
81
+ ],
82
+ filename: route.filePath,
83
+ });
84
+ let out = transpiler.transformSync(res?.code ?? "");
85
+ if (styles.css && hash) out = clientStyleSnippet(hash, styles.css) + out;
86
+ for (const plugin of plugins) {
87
+ if (plugin.transform)
88
+ out = (await plugin.transform(out, route.filePath)) ?? out;
89
+ }
90
+
91
+ const rel = relative(process.cwd(), route.filePath)
92
+ .replace(/\.tsx?$/, "")
93
+ .replace(/[^a-zA-Z0-9._-]/g, "_");
94
+ const nameBase = rel || basename(route.filePath).replace(/\.[jt]sx$/, "");
95
+ const outPath = join(outDir, `${index}-${nameBase}.${mode}.js`);
96
+
97
+ await Bun.write(outPath, out);
98
+ map.set(route.filePath, outPath);
99
+ }),
100
+ );
101
+ return map;
102
+ }