@sigil-dev/grimoire 0.9.2 → 0.9.4

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 (88) hide show
  1. package/index.ts +37 -35
  2. package/package.json +9 -12
  3. package/preload.js +3 -3
  4. package/server.ts +19 -19
  5. package/src/client/deps.ts +31 -8
  6. package/src/client/enhance.ts +102 -98
  7. package/src/client/head.ts +30 -30
  8. package/src/client/index.ts +5 -5
  9. package/src/client/router.ts +529 -371
  10. package/src/client/scope.ts +22 -22
  11. package/src/dev/compile-module.ts +163 -163
  12. package/src/dev/effect-registry.ts +23 -23
  13. package/src/dev/graph.ts +114 -114
  14. package/src/dev/hmr-client.ts +185 -185
  15. package/src/dev/loader.ts +47 -47
  16. package/src/dev/paths.ts +14 -14
  17. package/src/dev/runtime-bundle.ts +52 -52
  18. package/src/dev/watcher.ts +47 -46
  19. package/src/env/dynamic-private.ts +19 -19
  20. package/src/env/dynamic-public.ts +22 -22
  21. package/src/env/index.ts +25 -25
  22. package/src/env/plugin.ts +19 -19
  23. package/src/env/private.ts +5 -5
  24. package/src/env/public.ts +7 -7
  25. package/src/env/typegen.ts +61 -61
  26. package/src/headers.ts +114 -114
  27. package/src/integrations/vite.ts +73 -73
  28. package/src/logger/index.ts +4 -4
  29. package/src/logger/instance.ts +6 -6
  30. package/src/logger/logger.ts +113 -113
  31. package/src/logger/request-middleware.ts +24 -24
  32. package/src/logger/transports.ts +117 -117
  33. package/src/logger/types.ts +39 -39
  34. package/src/rendering/head.ts +47 -47
  35. package/src/rendering/hydrate.ts +146 -119
  36. package/src/rendering/index.ts +573 -372
  37. package/src/rendering/ssrPlugin.ts +69 -69
  38. package/src/routing/manifest-gen.ts +55 -42
  39. package/src/routing/router.ts +135 -109
  40. package/src/routing/scanner.ts +187 -141
  41. package/src/routing/transform-routes.ts +102 -102
  42. package/src/sentinels/error.ts +52 -52
  43. package/src/sentinels/fail.ts +41 -41
  44. package/src/sentinels/redirect.ts +35 -35
  45. package/src/server/build.ts +255 -219
  46. package/src/server/context.ts +10 -10
  47. package/src/server/cookie-utils.ts +66 -66
  48. package/src/server/coordinator.ts +364 -356
  49. package/src/server/hooks.ts +114 -114
  50. package/src/server/index.ts +677 -658
  51. package/src/server/interactive.ts +56 -56
  52. package/src/server/plugins.ts +121 -120
  53. package/src/server/worker.ts +58 -58
  54. package/src/typegen/index.ts +389 -356
  55. package/src/types.ts +8 -4
  56. package/test/client-router.test.ts +295 -35
  57. package/test/context.test.ts +52 -52
  58. package/test/env.test.ts +70 -70
  59. package/test/exports.test.ts +37 -37
  60. package/test/fail.test.ts +46 -46
  61. package/test/headers.test.ts +100 -100
  62. package/test/hydration.test.ts +119 -119
  63. package/test/middleware.test.ts +223 -223
  64. package/test/preload.ts +5 -5
  65. package/test/redirect-error.test.ts +112 -112
  66. package/test/rendering.test.ts +728 -579
  67. package/test/routing.test.ts +194 -81
  68. package/test/scanning.test.ts +254 -200
  69. package/test/scope.test.ts +195 -195
  70. package/test/server.test.ts +354 -249
  71. package/test/streaming.test.ts +242 -125
  72. package/test/transform-routes.test.ts +87 -84
  73. package/test/typegen.test.ts +697 -682
  74. package/tsconfig.json +10 -10
  75. package/.grimoire/_routes.dom.js +0 -8
  76. package/.grimoire/_routes.hydrate.js +0 -8
  77. package/.grimoire/tsconfig.generated.json +0 -11
  78. package/.grimoire/types/ambient.d.ts +0 -59
  79. package/.grimoire/types/api/hello/$types.d.ts +0 -50
  80. package/.grimoire/types/api/items/$types.d.ts +0 -50
  81. package/.grimoire/types/echo/$types.d.ts +0 -50
  82. package/.grimoire/types/env-private.d.ts +0 -5
  83. package/.grimoire/types/env-public.d.ts +0 -5
  84. package/.grimoire/types/mixed/$types.d.ts +0 -50
  85. package/.grimoire/types/params/[docId]/$types.d.ts +0 -52
  86. package/.grimoire/types/reject/$types.d.ts +0 -50
  87. package/public/__grimoire__/hydrate.js +0 -585
  88. package/public/__grimoire__/index.js +0 -490
@@ -1,69 +1,69 @@
1
- import { createHash } from "node:crypto";
2
- import { transformSync } from "@babel/core";
3
- import sigilPlugin from "@sigil-dev/compiler/babel";
4
- import { log } from "../logger/instance";
5
- import type { GrimoirePlugin } from "../types";
6
-
7
- const logger = log.scope("scope");
8
- let registered = false;
9
-
10
- export function registerSSRPlugin(plugins: GrimoirePlugin[] = []) {
11
- if (registered) return;
12
- registered = true;
13
-
14
- Bun.plugin({
15
- name: "sigil-ssr",
16
-
17
- setup(build) {
18
- // loader: "ts" not "tsx" — Babel already consumed the JSX,
19
- // Bun only needs to strip remaining TypeScript types
20
- const transpiler = new Bun.Transpiler({ loader: "ts", target: "bun" });
21
- build.onResolve({ filter: /^@sigil-dev\/runtime($|\/)/ }, (args) => {
22
- try {
23
- const resolved = Bun.resolveSync(args.path, process.cwd());
24
- return { path: resolved.replaceAll("\\", "/") };
25
- } catch {
26
- return undefined;
27
- }
28
- });
29
-
30
- build.onLoad({ filter: /\.tsx?$/ }, async ({ path }) => {
31
- if (path.includes("index.tsx"))
32
- logger.debug("[ssr-plugin] onLoad:", path);
33
- const source = await Bun.file(path).text();
34
-
35
- // node_modules and .grimoire files are plain TypeScript (no sigil JSX).
36
- // Still must return { contents, loader } — never return undefined from onLoad.
37
- if (path.includes("node_modules") || path.includes(".grimoire")) {
38
- return {
39
- contents: transpiler.transformSync(source),
40
- loader: "js" as const,
41
- };
42
- }
43
-
44
- if (process.env.SIGIL_VERBOSE) {
45
- logger.debug("[sigil-ssr] XFORM:", path);
46
- }
47
- const hash = createHash("md5").update(path).digest("hex").slice(0, 8);
48
- const result = transformSync(source, {
49
- configFile: false,
50
- babelrc: false,
51
- parserOpts: {
52
- plugins: ["typescript", "jsx"],
53
- },
54
- plugins: [[sigilPlugin, { mode: "ssr", hash }]],
55
- filename: path,
56
- });
57
-
58
- let contents = transpiler.transformSync(result?.code ?? "");
59
-
60
- for (const plugin of plugins) {
61
- if (plugin.transform)
62
- contents = (await plugin.transform(contents, path)) ?? contents;
63
- }
64
-
65
- return { contents, loader: "js" as const };
66
- });
67
- },
68
- });
69
- }
1
+ import { createHash } from "node:crypto";
2
+ import { transformSync } from "@babel/core";
3
+ import sigilPlugin from "@sigil-dev/compiler/babel";
4
+ import { log } from "../logger/instance";
5
+ import type { GrimoirePlugin } from "../types";
6
+
7
+ const logger = log.scope("scope");
8
+ let registered = false;
9
+
10
+ export function registerSSRPlugin(plugins: GrimoirePlugin[] = []) {
11
+ if (registered) return;
12
+ registered = true;
13
+
14
+ Bun.plugin({
15
+ name: "sigil-ssr",
16
+
17
+ setup(build) {
18
+ // loader: "ts" not "tsx" — Babel already consumed the JSX,
19
+ // Bun only needs to strip remaining TypeScript types
20
+ const transpiler = new Bun.Transpiler({ loader: "ts", target: "bun" });
21
+ build.onResolve({ filter: /^@sigil-dev\/runtime($|\/)/ }, (args) => {
22
+ try {
23
+ const resolved = Bun.resolveSync(args.path, process.cwd());
24
+ return { path: resolved.replaceAll("\\", "/") };
25
+ } catch {
26
+ return undefined;
27
+ }
28
+ });
29
+
30
+ build.onLoad({ filter: /\.tsx?$/ }, async ({ path }) => {
31
+ if (path.includes("index.tsx"))
32
+ logger.debug("[ssr-plugin] onLoad:", path);
33
+ const source = await Bun.file(path).text();
34
+
35
+ // node_modules and .grimoire files are plain TypeScript (no sigil JSX).
36
+ // Still must return { contents, loader } — never return undefined from onLoad.
37
+ if (path.includes("node_modules") || path.includes(".grimoire")) {
38
+ return {
39
+ contents: transpiler.transformSync(source),
40
+ loader: "js" as const,
41
+ };
42
+ }
43
+
44
+ if (process.env.SIGIL_VERBOSE) {
45
+ logger.debug("[sigil-ssr] XFORM:", path);
46
+ }
47
+ const hash = createHash("md5").update(path).digest("hex").slice(0, 8);
48
+ const result = transformSync(source, {
49
+ configFile: false,
50
+ babelrc: false,
51
+ parserOpts: {
52
+ plugins: ["typescript", "jsx"],
53
+ },
54
+ plugins: [[sigilPlugin, { mode: "ssr", hash }]],
55
+ filename: path,
56
+ });
57
+
58
+ let contents = transpiler.transformSync(result?.code ?? "");
59
+
60
+ for (const plugin of plugins) {
61
+ if (plugin.transform)
62
+ contents = (await plugin.transform(contents, path)) ?? contents;
63
+ }
64
+
65
+ return { contents, loader: "js" as const };
66
+ });
67
+ },
68
+ });
69
+ }
@@ -1,42 +1,55 @@
1
- import type { RouteFile } from "./scanner";
2
-
3
- /**
4
- * Generates a manifest module that re-exports page route components keyed
5
- * by route path. Emits plain JS so the same output is valid as both `.ts`
6
- * and `.js`.
7
- *
8
- * If `fileMap` is provided, original `filePath`s are remapped to compiled
9
- * `.js` paths (used after pre-transforming routes to plain JS).
10
- */
11
- export function generateManifest(
12
- routes: RouteFile[],
13
- fileMap?: Map<string, string>,
14
- ): string {
15
- const pages = routes.filter((r) => r.type === "page" || r.type === "simple");
16
- const layouts = routes.filter((r) => r.type === "layout");
17
-
18
- const pageImports = pages
19
- .map((r, i) => {
20
- const path = fileMap?.get(r.filePath) ?? r.filePath;
21
- return `import __Page${i} from ${JSON.stringify(path)};`;
22
- })
23
- .join("\n");
24
- const layoutImports = layouts
25
- .map((r, i) => {
26
- const path = fileMap?.get(r.filePath) ?? r.filePath;
27
- return `import __Layout${i} from ${JSON.stringify(path)};`;
28
- })
29
- .join("\n");
30
-
31
- const map = pages
32
- .map((r, i) => ` ${JSON.stringify(r.path)}: __Page${i},`)
33
- .join("\n");
34
- const layoutMap = layouts
35
- .map(
36
- (r, i) =>
37
- ` { path: ${JSON.stringify(r.path)}, component: __Layout${i}, load: __Layout${i}.load },`,
38
- )
39
- .join("\n");
40
-
41
- return `${pageImports}\n${layoutImports}\nexport const routes = {\n${map}\n};\nexport const layouts = [\n${layoutMap}\n];\n`;
42
- }
1
+ import type { RouteFile } from "./scanner";
2
+
3
+ /**
4
+ * Generates a manifest module that exposes page routes keyed by route path.
5
+ * Emits plain JS so the same output is valid as both `.ts` and `.js`.
6
+ *
7
+ * Pages are emitted as lazy entries (`{ __lazy: () => import(...) }`) so a
8
+ * route module — including its module-level $state/$effect code — only
9
+ * executes when that route is actually visited. Layouts stay eager: they are
10
+ * needed for every render.
11
+ *
12
+ * If `fileMap` is provided, original `filePath`s are remapped to compiled
13
+ * `.js` paths (used after pre-transforming routes to plain JS).
14
+ */
15
+ export function generateManifest(
16
+ routes: RouteFile[],
17
+ fileMap?: Map<string, string>,
18
+ paramMatcherFiles: { name: string; filePath: string }[] = [],
19
+ ): string {
20
+ const pages = routes.filter((r) => r.type === "page" || r.type === "simple");
21
+ const layouts = routes.filter((r) => r.type === "layout");
22
+
23
+ const layoutImports = layouts
24
+ .map((r, i) => {
25
+ const path = fileMap?.get(r.filePath) ?? r.filePath;
26
+ return `import __Layout${i} from ${JSON.stringify(path)};`;
27
+ })
28
+ .join("\n");
29
+
30
+ // param matchers are eager: the client router validates on every match
31
+ const matcherImports = paramMatcherFiles
32
+ .map(
33
+ (pm) =>
34
+ `import * as __param_${pm.name} from ${JSON.stringify(pm.filePath)};`,
35
+ )
36
+ .join("\n");
37
+ const matcherRecord = `export const matchers = {\n${paramMatcherFiles
38
+ .map((pm) => ` ${JSON.stringify(pm.name)}: __param_${pm.name}.match,`)
39
+ .join("\n")}\n};`;
40
+
41
+ const map = pages
42
+ .map((r) => {
43
+ const path = fileMap?.get(r.filePath) ?? r.filePath;
44
+ return ` ${JSON.stringify(r.path)}: { __lazy: () => import(${JSON.stringify(path)}) },`;
45
+ })
46
+ .join("\n");
47
+ const layoutMap = layouts
48
+ .map(
49
+ (r, i) =>
50
+ ` { path: ${JSON.stringify(r.path)}, component: __Layout${i}, load: __Layout${i}.load },`,
51
+ )
52
+ .join("\n");
53
+
54
+ return `${layoutImports}\n${matcherImports}\nexport const routes = {\n${map}\n};\nexport const layouts = [\n${layoutMap}\n];\n${matcherRecord}\n`;
55
+ }
@@ -1,109 +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(tree: RouteTree, url: URL): MatchedRoute | null {
12
- const pathname = url.pathname;
13
-
14
- // check server routes first
15
- for (const server of tree.servers) {
16
- const params = matchPattern(server.path, pathname);
17
- if (params !== null)
18
- return {
19
- route: server,
20
- params,
21
- layouts: [],
22
- layoutServers: [],
23
- };
24
- }
25
-
26
- // then pages
27
- for (const route of tree.routes) {
28
- if (route.type === "pageServer") continue;
29
- const params = matchPattern(route.path, pathname);
30
- if (params === null) continue;
31
-
32
- // find applicable layouts by matching route pattern prefix, not URL pathname.
33
- // pathname.startsWith(l.path) would fail for parameterized layouts like /w/:workspace.
34
- const layoutMatches = (l: RouteFile) =>
35
- l.path === "/" ||
36
- route.path === l.path ||
37
- route.path.startsWith(`${l.path}/`);
38
-
39
- const layouts = tree.layouts
40
- .filter((l) => l.type === "layout" && layoutMatches(l))
41
- .sort((a, b) => a.path.length - b.path.length); // root first, innermost last
42
-
43
- const layoutServers = tree.layouts
44
- .filter((l) => l.type === "layoutServer" && layoutMatches(l))
45
- .sort((a, b) => a.path.length - b.path.length); // root first, innermost last
46
-
47
- const pageServer = tree.routes.find(
48
- (r) => r.type === "pageServer" && r.path === route.path,
49
- );
50
-
51
- return { route, params, layouts, layoutServers, pageServer };
52
- }
53
-
54
- return null;
55
- }
56
-
57
- export function findClosestError(
58
- errors: RouteFile[],
59
- pathname: string,
60
- ): RouteFile | null {
61
- const segments = pathname.split("/").filter(Boolean);
62
-
63
- // walk from most specific to root
64
- while (segments.length >= 0) {
65
- const prefix = `/${segments.join("/")}`;
66
- const error = errors.find(
67
- (e) => e.path === prefix || e.path === `${prefix}/`,
68
- );
69
- if (error) return error;
70
- if (segments.length === 0) break;
71
- segments.pop();
72
- }
73
- return null;
74
- }
75
-
76
- function matchPattern(
77
- pattern: string,
78
- pathname: string,
79
- ): Record<string, string> | null {
80
- const patternParts = pattern.split("/").filter(Boolean);
81
- const pathParts = pathname.split("/").filter(Boolean);
82
-
83
- const params: Record<string, string> = {};
84
- let pi = 0;
85
- let pj = 0;
86
- while (pi < patternParts.length) {
87
- const patternPart = patternParts[pi]!;
88
-
89
- if (patternPart.startsWith("*")) {
90
- // Rest param — captures zero or more remaining path segments joined by "/".
91
- // Rest must be the last segment in the pattern.
92
- params[patternPart.slice(1)] = pathParts.slice(pj).join("/");
93
- return params;
94
- }
95
-
96
- if (pj >= pathParts.length) return null;
97
- const pathPart = pathParts[pj]!;
98
-
99
- if (patternPart.startsWith(":")) {
100
- params[patternPart.slice(1)] = pathPart;
101
- } else if (patternPart !== pathPart) {
102
- return null;
103
- }
104
- pi++;
105
- pj++;
106
- }
107
- if (pj < pathParts.length) return null;
108
- return params;
109
- }
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
+ }