@sigil-dev/grimoire 0.9.4 → 0.9.5

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 +42 -20
  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 +10 -6
  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 +364 -364
  52. package/src/server/hooks.ts +114 -114
  53. package/src/server/index.ts +711 -677
  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 +295 -298
  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 +242 -242
  76. package/test/transform-routes.test.ts +87 -87
  77. package/test/typegen.test.ts +697 -697
  78. package/tsconfig.json +10 -10
@@ -1,47 +1,52 @@
1
- import { createContext, getContext, setContext } from "@sigil-dev/runtime";
2
-
3
- const HeadKey = createContext<string[]>();
4
- const NonceKey = createContext<string>();
5
-
6
- export function initHead(nonce?: string): void {
7
- setContext(HeadKey, []);
8
- if (nonce) setContext(NonceKey, nonce);
9
- }
10
-
11
- export function setHeadNonce(nonce: string): void {
12
- setContext(NonceKey, nonce);
13
- }
14
-
15
- export function getHeadNonce(): string {
16
- return getContext(NonceKey) ?? "";
17
- }
18
-
19
- export function collectHead(): string {
20
- return (getContext(HeadKey) ?? []).join("\n ");
21
- }
22
-
23
- export function Head({
24
- children,
25
- }: {
26
- children: string | Node;
27
- }): string | Comment {
28
- if (typeof document === "undefined") {
29
- const buf = getContext(HeadKey);
30
- if (buf) {
31
- const nonce = getContext(NonceKey);
32
- if (nonce) {
33
- const withNonce = String(children)
34
- .replace(/<script /g, `<script nonce="${nonce}" `)
35
- .replace(/<style /g, `<style nonce="${nonce}" `);
36
- buf.push(withNonce);
37
- } else {
38
- buf.push(children as string);
39
- }
40
- }
41
- return "";
42
- }
43
- if (children instanceof Node) {
44
- document.head.appendChild(children);
45
- }
46
- return document.createComment("head");
47
- }
1
+ import { createContext, getContext, setContext } from "@sigil-dev/runtime";
2
+
3
+ const HeadKey = createContext<string[]>();
4
+ const NonceKey = createContext<string>();
5
+
6
+ export function initHead(nonce?: string): void {
7
+ setContext(HeadKey, []);
8
+ if (nonce) setContext(NonceKey, nonce);
9
+ }
10
+
11
+ export function setHeadNonce(nonce: string): void {
12
+ setContext(NonceKey, nonce);
13
+ }
14
+
15
+ export function getHeadNonce(): string {
16
+ return getContext(NonceKey) ?? "";
17
+ }
18
+
19
+ export function collectHead(): string {
20
+ return (getContext(HeadKey) ?? []).join("\n ");
21
+ }
22
+
23
+ export function Head({
24
+ children,
25
+ }: {
26
+ children: string | Node;
27
+ }): string | Comment {
28
+ if (typeof document === "undefined") {
29
+ const buf = getContext(HeadKey);
30
+ if (buf) {
31
+ // Dynamic text inside <Head> children arrives wrapped in hydration
32
+ // claim markers; those belong to the body runtime and must never
33
+ // reach document.title or meta content.
34
+ const nonce = getContext(NonceKey);
35
+ const clean = String(children).replace(/<!--\/?g[^>]*-->/g, "");
36
+ if (nonce) {
37
+ buf.push(
38
+ clean
39
+ .replace(/<script /g, `<script nonce="${nonce}" `)
40
+ .replace(/<style /g, `<style nonce="${nonce}" `),
41
+ );
42
+ } else {
43
+ buf.push(clean);
44
+ }
45
+ }
46
+ return "";
47
+ }
48
+ if (children instanceof Node) {
49
+ document.head.appendChild(children);
50
+ }
51
+ return document.createComment("head");
52
+ }
@@ -1,5 +1,6 @@
1
1
  import {
2
2
  claim,
3
+ flushDeferredEffects,
3
4
  getHydrationNodes,
4
5
  insert,
5
6
  popHydrationNodes,
@@ -65,7 +66,9 @@ async function hydrate(): Promise<(() => void) | undefined> {
65
66
  const ssrClones = inPlace
66
67
  ? Array.from(slot.childNodes).map((n) => n.cloneNode(true))
67
68
  : [];
68
- pushHydrationNodes(inPlace ? (Array.from(slot.childNodes) as ChildNode[]) : []);
69
+ pushHydrationNodes(
70
+ inPlace ? (Array.from(slot.childNodes) as ChildNode[]) : [],
71
+ );
69
72
  let initialDispose: (() => void) | undefined;
70
73
  try {
71
74
  initialDispose = withEffectScope(() => {
@@ -112,13 +115,23 @@ async function hydrate(): Promise<(() => void) | undefined> {
112
115
  return LayoutComponent({
113
116
  data: layoutData,
114
117
  params: state.params,
118
+ path: state.pattern,
115
119
  children: childNode,
116
120
  });
117
121
  };
118
122
  }
119
123
 
120
- const rootNode = renderFn();
121
- insert(slot, rootNode);
124
+ // Defer effects during hydration render — they'll run after DOM insertion,
125
+ // so document.querySelector() etc. can find elements that are in the document.
126
+ (globalThis as any).__sigilDeferEffects = true;
127
+ try {
128
+ const rootNode = renderFn();
129
+ insert(slot, rootNode);
130
+ } finally {
131
+ // finally: a throwing render must not leave the flag set forever
132
+ (globalThis as any).__sigilDeferEffects = false;
133
+ flushDeferredEffects();
134
+ }
122
135
  } finally {
123
136
  popHydrationNodes();
124
137
  }
@@ -102,6 +102,7 @@ function applyLayoutTree(
102
102
  innerHtml: string,
103
103
  layoutPairs: LayoutPair[],
104
104
  params: Record<string, string>,
105
+ pattern?: string,
105
106
  innerId = "grimoire-page",
106
107
  ): string {
107
108
  let bodyHtml = `<div id="${innerId}">${innerHtml}</div>`;
@@ -111,6 +112,7 @@ function applyLayoutTree(
111
112
  data,
112
113
  children: new SafeHtml(bodyHtml),
113
114
  params,
115
+ path: pattern,
114
116
  }),
115
117
  );
116
118
  }
@@ -378,7 +380,7 @@ export async function renderRoute(
378
380
 
379
381
  // helper: wrap page html in layout tree
380
382
  function applyLayouts(pageHtml: string): string {
381
- return applyLayoutTree(pageHtml, layoutPairs, matched.params);
383
+ return applyLayoutTree(pageHtml, layoutPairs, matched.params, matched.route.path);
382
384
  }
383
385
 
384
386
  // ── two-pass streaming (loading export present) ─────────────────────────
@@ -453,9 +455,7 @@ export async function renderRoute(
453
455
  for (const d of deferred) {
454
456
  try {
455
457
  const value = await d.promise;
456
- controller.enqueue(
457
- deferredChunk(d.key, value, false),
458
- );
458
+ controller.enqueue(deferredChunk(d.key, value, false));
459
459
  } catch {
460
460
  controller.enqueue(deferredChunk(d.key, null, true));
461
461
  }
@@ -490,6 +490,12 @@ export async function renderRoute(
490
490
  pageMod.default({ data: mergedData, params: matched.params }),
491
491
  );
492
492
 
493
+ // layouts must render before collectHead(): a <Head> call inside a
494
+ // layout component (a common place for site-wide <title>/meta
495
+ // defaults) only registers once the layout itself has run, so
496
+ // collecting too early silently drops it
497
+ let bodyHtml = applyLayouts(String(pageHtml));
498
+
493
499
  const headHtml = collectHead();
494
500
 
495
501
  if (isNavigate) {
@@ -521,8 +527,6 @@ export async function renderRoute(
521
527
  deps: [...collectedDeps],
522
528
  });
523
529
 
524
- let bodyHtml = applyLayouts(String(pageHtml));
525
-
526
530
  const csrfInput = `<input type="hidden" name="_csrf" value="${csrfToken}">`;
527
531
  bodyHtml = bodyHtml.replace(
528
532
  /<form([^>]*action=[^>]*)>/gi,
@@ -1,69 +1,78 @@
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
+ // scoped <style> blocks never render server-side (SSR mode never
49
+ // injects the CSS — see bun-plugin.ts's mode !== "ssr" guard), but
50
+ // their raw CSS text still needs stripping or the JSX parser treats
51
+ // a bare `{` in a declaration like `position: sticky;` as the start
52
+ // of an embedded expression and throws
53
+ const sourceNoStyle = source.replace(
54
+ /<style[^>]*>[\s\S]*?<\/style>/gi,
55
+ "",
56
+ );
57
+ const result = transformSync(sourceNoStyle, {
58
+ configFile: false,
59
+ babelrc: false,
60
+ parserOpts: {
61
+ plugins: ["typescript", "jsx"],
62
+ },
63
+ plugins: [[sigilPlugin, { mode: "ssr", hash }]],
64
+ filename: path,
65
+ });
66
+
67
+ let contents = transpiler.transformSync(result?.code ?? "");
68
+
69
+ for (const plugin of plugins) {
70
+ if (plugin.transform)
71
+ contents = (await plugin.transform(contents, path)) ?? contents;
72
+ }
73
+
74
+ return { contents, loader: "js" as const };
75
+ });
76
+ },
77
+ });
78
+ }
@@ -1,55 +1,55 @@
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
+ 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
+ }