@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
package/index.ts CHANGED
@@ -1,37 +1,37 @@
1
- export { Head } from "./src/rendering/head";
2
- // server loads call depends() to register invalidation keys
3
- export { depends } from "./src/client/deps";
4
- // registerSSRPlugin is server-only — import from "@sigil-dev/grimoire/bun"
5
- export type { RouteFile, RouteTree } from "./src/routing/scanner";
6
- export type { ErrorResult } from "./src/sentinels/error.ts";
7
- export { error, isErrorResult } from "./src/sentinels/error.ts";
8
- export type { FailResult } from "./src/sentinels/fail.ts";
9
- export { fail, isFailResult } from "./src/sentinels/fail.ts";
10
- export type { RedirectResult } from "./src/sentinels/redirect.ts";
11
- export { isRedirectResult, redirect } from "./src/sentinels/redirect.ts";
12
- export type {
13
- CookieOptions,
14
- Cookies,
15
- Handle,
16
- RequestEvent,
17
- ResolveFunction,
18
- } from "./src/server/hooks";
19
- export { createHooks, sequence } from "./src/server/hooks";
20
- export type {
21
- BuiltinWorkerMode,
22
- CoordinatorContext,
23
- GrimoireConfig,
24
- GrimoirePlugin,
25
- LayoutServerLoad,
26
- LoadContext,
27
- PageServerLoad,
28
- RenderContext,
29
- RequestHandler,
30
- RouteInfo,
31
- TypedLoadContext,
32
- WorkerDescriptor,
33
- WorkerEnv,
34
- WorkerMode,
35
- WsRouteHandler,
36
- } from "./src/types";
37
- export { defineConfig } from "./src/types";
1
+ // server loads call depends() to register invalidation keys
2
+ export { depends } from "./src/client/deps";
3
+ export { Head } from "./src/rendering/head";
4
+ // registerSSRPlugin is server-only — import from "@sigil-dev/grimoire/bun"
5
+ export type { RouteFile, RouteTree } from "./src/routing/scanner";
6
+ export type { ErrorResult } from "./src/sentinels/error.ts";
7
+ export { error, isErrorResult } from "./src/sentinels/error.ts";
8
+ export type { FailResult } from "./src/sentinels/fail.ts";
9
+ export { fail, isFailResult } from "./src/sentinels/fail.ts";
10
+ export type { RedirectResult } from "./src/sentinels/redirect.ts";
11
+ export { isRedirectResult, redirect } from "./src/sentinels/redirect.ts";
12
+ export type {
13
+ CookieOptions,
14
+ Cookies,
15
+ Handle,
16
+ RequestEvent,
17
+ ResolveFunction,
18
+ } from "./src/server/hooks";
19
+ export { createHooks, sequence } from "./src/server/hooks";
20
+ export type {
21
+ BuiltinWorkerMode,
22
+ CoordinatorContext,
23
+ GrimoireConfig,
24
+ GrimoirePlugin,
25
+ LayoutServerLoad,
26
+ LoadContext,
27
+ PageServerLoad,
28
+ RenderContext,
29
+ RequestHandler,
30
+ RouteInfo,
31
+ TypedLoadContext,
32
+ WorkerDescriptor,
33
+ WorkerEnv,
34
+ WorkerMode,
35
+ WsRouteHandler,
36
+ } from "./src/types";
37
+ export { defineConfig } from "./src/types";
package/package.json CHANGED
@@ -4,7 +4,7 @@
4
4
  "module": "index.ts",
5
5
  "type": "module",
6
6
  "private": false,
7
- "version": "0.9.4",
7
+ "version": "0.9.5",
8
8
  "exports": {
9
9
  ".": "./index.ts",
10
10
  "./server": "./server.ts",
@@ -23,8 +23,8 @@
23
23
  "test": "bun test"
24
24
  },
25
25
  "dependencies": {
26
- "@sigil-dev/compiler": "0.9.4",
27
- "@sigil-dev/runtime": "0.9.4",
26
+ "@sigil-dev/compiler": "0.9.5",
27
+ "@sigil-dev/runtime": "0.9.5",
28
28
  "vite": "^8.0.16"
29
29
  },
30
30
  "peerDependencies": {
package/preload.js CHANGED
@@ -1,3 +1,3 @@
1
- import { registerSSRPlugin } from "./src/rendering/ssrPlugin.ts";
2
-
3
- registerSSRPlugin();
1
+ import { registerSSRPlugin } from "./src/rendering/ssrPlugin.ts";
2
+
3
+ registerSSRPlugin();
package/server.ts CHANGED
@@ -1,19 +1,19 @@
1
- export { log } from "./src/logger/instance.ts";
2
- export { scanRoutes } from "./src/routing/scanner";
3
- export { createServer } from "./src/server";
4
- export { buildProject } from "./src/server/build";
5
- export { parseCookies } from "./src/server/cookie-utils";
6
- export { startCoordinator } from "./src/server/coordinator.ts";
7
- export {
8
- createWaiter,
9
- listenForKeys,
10
- stopListening,
11
- } from "./src/server/interactive.ts";
12
- export {
13
- runDeserializeLocals,
14
- runRouteRequest,
15
- runSerializeLocals,
16
- runWorkerSpawn,
17
- } from "./src/server/plugins";
18
- export type { TypegenConfig } from "./src/typegen";
19
- export { generateTypes } from "./src/typegen";
1
+ export { log } from "./src/logger/instance.ts";
2
+ export { scanRoutes } from "./src/routing/scanner";
3
+ export { createServer } from "./src/server";
4
+ export { buildProject } from "./src/server/build";
5
+ export { parseCookies } from "./src/server/cookie-utils";
6
+ export { startCoordinator } from "./src/server/coordinator.ts";
7
+ export {
8
+ createWaiter,
9
+ listenForKeys,
10
+ stopListening,
11
+ } from "./src/server/interactive.ts";
12
+ export {
13
+ runDeserializeLocals,
14
+ runRouteRequest,
15
+ runSerializeLocals,
16
+ runWorkerSpawn,
17
+ } from "./src/server/plugins";
18
+ export type { TypegenConfig } from "./src/typegen";
19
+ export { generateTypes } from "./src/typegen";
@@ -1,36 +1,36 @@
1
- const routeDeps = new Map<string, Set<string>>();
2
- let _collecting: Set<string> | null = null;
3
-
4
- export function startCollecting(): void {
5
- _collecting = new Set();
6
- }
7
-
8
- /** Stop collecting and return the keys gathered. When `pattern` is given,
9
- * the keys are also recorded as that route's dependency set. */
10
- export function stopCollecting(pattern?: string): string[] {
11
- const keys = _collecting ? [..._collecting] : [];
12
- if (_collecting && pattern) routeDeps.set(pattern, new Set(keys));
13
- _collecting = null;
14
- return keys;
15
- }
16
-
17
- export function depends(key: string): void {
18
- _collecting?.add(key);
19
- }
20
-
21
- export function hasDep(pattern: string, key: string): boolean {
22
- return routeDeps.get(pattern)?.has(key) ?? false;
23
- }
24
-
25
- export function clearDeps(pattern: string): void {
26
- routeDeps.delete(pattern);
27
- }
28
-
29
- /** Seed a route's dependency set (e.g. from server-rendered state). */
30
- export function setDeps(pattern: string, keys: string[]): void {
31
- routeDeps.set(pattern, new Set(keys));
32
- }
33
-
34
- export function getDeps(pattern: string): Set<string> | undefined {
35
- return routeDeps.get(pattern);
36
- }
1
+ const routeDeps = new Map<string, Set<string>>();
2
+ let _collecting: Set<string> | null = null;
3
+
4
+ export function startCollecting(): void {
5
+ _collecting = new Set();
6
+ }
7
+
8
+ /** Stop collecting and return the keys gathered. When `pattern` is given,
9
+ * the keys are also recorded as that route's dependency set. */
10
+ export function stopCollecting(pattern?: string): string[] {
11
+ const keys = _collecting ? [..._collecting] : [];
12
+ if (_collecting && pattern) routeDeps.set(pattern, new Set(keys));
13
+ _collecting = null;
14
+ return keys;
15
+ }
16
+
17
+ export function depends(key: string): void {
18
+ _collecting?.add(key);
19
+ }
20
+
21
+ export function hasDep(pattern: string, key: string): boolean {
22
+ return routeDeps.get(pattern)?.has(key) ?? false;
23
+ }
24
+
25
+ export function clearDeps(pattern: string): void {
26
+ routeDeps.delete(pattern);
27
+ }
28
+
29
+ /** Seed a route's dependency set (e.g. from server-rendered state). */
30
+ export function setDeps(pattern: string, keys: string[]): void {
31
+ routeDeps.set(pattern, new Set(keys));
32
+ }
33
+
34
+ export function getDeps(pattern: string): Set<string> | undefined {
35
+ return routeDeps.get(pattern);
36
+ }
@@ -1,102 +1,102 @@
1
- /**
2
- * Client-side form action handler.
3
- * Wraps form submission with fetch, handles fail() responses, and updates state.
4
- *
5
- * Usage in +page.tsx:
6
- *
7
- * import { enhance } from "@sigil-dev/grimoire/client";
8
- * import { createSignal } from "@sigil-dev/runtime";
9
- *
10
- * const [errors, setErrors] = createSignal({});
11
- *
12
- * <form use={[enhance, { action: "/api/login", onSuccess: () => { ... }, onFail: (data) => setErrors(data) }]}>
13
- * ...
14
- * </form>
15
- */
16
- export interface EnhanceOptions {
17
- /** URL to submit to (defaults to form's action) */
18
- action?: string;
19
- /** Called on successful submission (303 redirect) */
20
- onSuccess?: (result: { redirect: string }) => void;
21
- /** Called when server returns fail() with validation data */
22
- onFail?: (data: Record<string, unknown>) => void;
23
- /** Called on network or unexpected errors */
24
- onError?: (error: Error) => void;
25
- /** Whether to reset the form on success (default: true) */
26
- reset?: boolean;
27
- }
28
-
29
- /**
30
- * use:enhance directive for progressive form enhancement.
31
- * Attaches to a <form> element and intercepts submit events.
32
- *
33
- * Returns a cleanup function.
34
- */
35
- export function enhance(
36
- form: HTMLFormElement,
37
- options: EnhanceOptions = {},
38
- ): () => void {
39
- const { action, onSuccess, onFail, onError, reset = true } = options;
40
-
41
- async function handleSubmit(e: Event) {
42
- e.preventDefault();
43
-
44
- const formData = new FormData(form);
45
- const resolved =
46
- action ?? form.getAttribute("action") ?? window.location.pathname;
47
- // SvelteKit-style named action: "?/create" submits to the current path
48
- const url = resolved.startsWith("?/")
49
- ? window.location.pathname + resolved
50
- : resolved;
51
-
52
- try {
53
- const res = await fetch(url, {
54
- method: "POST",
55
- headers: {
56
- "X-Grimoire-Form": "1",
57
- },
58
- body: formData,
59
- });
60
-
61
- const contentType = res.headers.get("content-type") ?? "";
62
-
63
- if (contentType.includes("application/json")) {
64
- const json = await res.json();
65
-
66
- if (json.fail) {
67
- // fail() response — validation errors
68
- onFail?.(json.data);
69
- return;
70
- }
71
-
72
- // Regular JSON response (API route)
73
- onSuccess?.(json);
74
- return;
75
- }
76
-
77
- // Non-JSON response (303 redirect or other)
78
- if (res.status === 303) {
79
- const location = res.headers.get("location") ?? "/";
80
- if (reset) form.reset();
81
- onSuccess?.({ redirect: location });
82
- // Navigate to the redirect target
83
- window.history.pushState({}, "", location);
84
- window.dispatchEvent(new PopStateEvent("popstate"));
85
- return;
86
- }
87
-
88
- // Other response
89
- if (res.ok) {
90
- if (reset) form.reset();
91
- onSuccess?.({ redirect: window.location.pathname });
92
- } else {
93
- onError?.(new Error(`Form submission failed: ${res.status}`));
94
- }
95
- } catch (err) {
96
- onError?.(err instanceof Error ? err : new Error(String(err)));
97
- }
98
- }
99
-
100
- form.addEventListener("submit", handleSubmit);
101
- return () => form.removeEventListener("submit", handleSubmit);
102
- }
1
+ /**
2
+ * Client-side form action handler.
3
+ * Wraps form submission with fetch, handles fail() responses, and updates state.
4
+ *
5
+ * Usage in +page.tsx:
6
+ *
7
+ * import { enhance } from "@sigil-dev/grimoire/client";
8
+ * import { createSignal } from "@sigil-dev/runtime";
9
+ *
10
+ * const [errors, setErrors] = createSignal({});
11
+ *
12
+ * <form use={[enhance, { action: "/api/login", onSuccess: () => { ... }, onFail: (data) => setErrors(data) }]}>
13
+ * ...
14
+ * </form>
15
+ */
16
+ export interface EnhanceOptions {
17
+ /** URL to submit to (defaults to form's action) */
18
+ action?: string;
19
+ /** Called on successful submission (303 redirect) */
20
+ onSuccess?: (result: { redirect: string }) => void;
21
+ /** Called when server returns fail() with validation data */
22
+ onFail?: (data: Record<string, unknown>) => void;
23
+ /** Called on network or unexpected errors */
24
+ onError?: (error: Error) => void;
25
+ /** Whether to reset the form on success (default: true) */
26
+ reset?: boolean;
27
+ }
28
+
29
+ /**
30
+ * use:enhance directive for progressive form enhancement.
31
+ * Attaches to a <form> element and intercepts submit events.
32
+ *
33
+ * Returns a cleanup function.
34
+ */
35
+ export function enhance(
36
+ form: HTMLFormElement,
37
+ options: EnhanceOptions = {},
38
+ ): () => void {
39
+ const { action, onSuccess, onFail, onError, reset = true } = options;
40
+
41
+ async function handleSubmit(e: Event) {
42
+ e.preventDefault();
43
+
44
+ const formData = new FormData(form);
45
+ const resolved =
46
+ action ?? form.getAttribute("action") ?? window.location.pathname;
47
+ // SvelteKit-style named action: "?/create" submits to the current path
48
+ const url = resolved.startsWith("?/")
49
+ ? window.location.pathname + resolved
50
+ : resolved;
51
+
52
+ try {
53
+ const res = await fetch(url, {
54
+ method: "POST",
55
+ headers: {
56
+ "X-Grimoire-Form": "1",
57
+ },
58
+ body: formData,
59
+ });
60
+
61
+ const contentType = res.headers.get("content-type") ?? "";
62
+
63
+ if (contentType.includes("application/json")) {
64
+ const json = await res.json();
65
+
66
+ if (json.fail) {
67
+ // fail() response — validation errors
68
+ onFail?.(json.data);
69
+ return;
70
+ }
71
+
72
+ // Regular JSON response (API route)
73
+ onSuccess?.(json);
74
+ return;
75
+ }
76
+
77
+ // Non-JSON response (303 redirect or other)
78
+ if (res.status === 303) {
79
+ const location = res.headers.get("location") ?? "/";
80
+ if (reset) form.reset();
81
+ onSuccess?.({ redirect: location });
82
+ // Navigate to the redirect target
83
+ window.history.pushState({}, "", location);
84
+ window.dispatchEvent(new PopStateEvent("popstate"));
85
+ return;
86
+ }
87
+
88
+ // Other response
89
+ if (res.ok) {
90
+ if (reset) form.reset();
91
+ onSuccess?.({ redirect: window.location.pathname });
92
+ } else {
93
+ onError?.(new Error(`Form submission failed: ${res.status}`));
94
+ }
95
+ } catch (err) {
96
+ onError?.(err instanceof Error ? err : new Error(String(err)));
97
+ }
98
+ }
99
+
100
+ form.addEventListener("submit", handleSubmit);
101
+ return () => form.removeEventListener("submit", handleSubmit);
102
+ }
@@ -1,30 +1,30 @@
1
- let headElements: (string | Node)[] = [];
2
-
3
- export function resetHead(): void {
4
- headElements = [];
5
- }
6
-
7
- export function collectHead(): (string | Node)[] {
8
- return headElements;
9
- }
10
-
11
- export function applyHead(): void {
12
- //biome-ignore lint: ChildNode.remove() returns void??? sure typescript
13
- document.querySelectorAll("[data-sigil-head]").forEach((el) => el.remove());
14
- for (const el of headElements) {
15
- if (el instanceof Node) {
16
- const clone = el.cloneNode(true) as HTMLElement;
17
- clone.dataset.sigilHead = "1";
18
- document.head.appendChild(clone);
19
- }
20
- }
21
- }
22
-
23
- export function Head({ children }: { children: string | Node }): Comment {
24
- if (typeof document === "undefined") {
25
- headElements.push(children);
26
- } else if (children instanceof Node) {
27
- (headElements as Node[]).push(children);
28
- }
29
- return document.createComment("head");
30
- }
1
+ let headElements: (string | Node)[] = [];
2
+
3
+ export function resetHead(): void {
4
+ headElements = [];
5
+ }
6
+
7
+ export function collectHead(): (string | Node)[] {
8
+ return headElements;
9
+ }
10
+
11
+ export function applyHead(): void {
12
+ //biome-ignore lint: ChildNode.remove() returns void??? sure typescript
13
+ document.querySelectorAll("[data-sigil-head]").forEach((el) => el.remove());
14
+ for (const el of headElements) {
15
+ if (el instanceof Node) {
16
+ const clone = el.cloneNode(true) as HTMLElement;
17
+ clone.dataset.sigilHead = "1";
18
+ document.head.appendChild(clone);
19
+ }
20
+ }
21
+ }
22
+
23
+ export function Head({ children }: { children: string | Node }): Comment {
24
+ if (typeof document === "undefined") {
25
+ headElements.push(children);
26
+ } else if (children instanceof Node) {
27
+ (headElements as Node[]).push(children);
28
+ }
29
+ return document.createComment("head");
30
+ }
@@ -1,5 +1,5 @@
1
- // @ts-expect-error Compiler generated/linked
2
- import { layouts, matchers, routes } from "#grimoire-routes";
3
- import { initRouter } from "./router.ts";
4
-
5
- initRouter(routes, layouts, undefined, { matchers });
1
+ // @ts-expect-error Compiler generated/linked
2
+ import { layouts, matchers, routes } from "#grimoire-routes";
3
+ import { initRouter } from "./router.ts";
4
+
5
+ initRouter(routes, layouts, undefined, { matchers });
@@ -61,11 +61,6 @@ let beforeNavigateCb: ((url: URL) => boolean | undefined) | null = null;
61
61
  let onNavigateCb: ((url: URL) => void) | null = null;
62
62
  let afterNavigateCb: ((url: URL) => void) | null = null;
63
63
 
64
- // // HMR
65
- // (globalThis as any).__grimoire_routes__ = routeMap;
66
- // (globalThis as any).__grimoire_current_pattern__ = currentPath;
67
- // (globalThis as any).__grimoire_navigate__ = navigate;
68
-
69
64
  export async function hmrRerender(): Promise<void> {
70
65
  if (!lastState) {
71
66
  location.reload();
@@ -86,7 +81,29 @@ export async function hmrRerender(): Promise<void> {
86
81
  document.getElementById("grimoire-root")?.replaceChildren(rootNode);
87
82
  }
88
83
 
89
- // (globalThis as any).__grimoire_rerender__ = hmrRerender;
84
+ /**
85
+ * Dev-only surface the HMR client drives. Route entries are replaced rather
86
+ * than mutated in place so a swapped module also wins for later navigations,
87
+ * and the resolved-module cache is dropped with them.
88
+ */
89
+ export interface HmrControl {
90
+ setRoute(pattern: string, entry: RouteEntry): void;
91
+ setLayout(path: string, component: (props: any) => any): void;
92
+ rerender(): Promise<void>;
93
+ }
94
+
95
+ const hmrControl: HmrControl = {
96
+ setRoute(pattern, entry) {
97
+ routeMap[pattern] = entry;
98
+ delete resolvedRoutes[pattern];
99
+ },
100
+ setLayout(path, component) {
101
+ const existing = layoutList.find((l) => l.path === path);
102
+ if (existing) existing.component = component;
103
+ else layoutList.push({ path, component });
104
+ },
105
+ rerender: hmrRerender,
106
+ };
90
107
 
91
108
  export function beforeNavigate(cb: (url: URL) => boolean | undefined): void {
92
109
  beforeNavigateCb = cb;
@@ -203,6 +220,7 @@ function buildRouteTree(state: typeof lastState, Page: PageComponent): any {
203
220
  return LayoutComponent({
204
221
  data: currentLayoutData,
205
222
  params,
223
+ path: pattern,
206
224
  children: childNode,
207
225
  });
208
226
  };
@@ -340,9 +358,7 @@ export async function navigate(
340
358
  } catch (e: unknown) {
341
359
  stopCollecting();
342
360
  if (e && typeof e === "object" && "location" in e) {
343
- window.location.href = String(
344
- (e as { location: unknown }).location,
345
- );
361
+ window.location.href = String((e as { location: unknown }).location);
346
362
  return;
347
363
  }
348
364
  console.error("[grimoire] universal load error:", e);
@@ -438,7 +454,22 @@ export function initRouter(
438
454
  // the app owns scroll: the browser's automatic restoration fires after
439
455
  // the router's own scroll and clobbers scroll-to-top / saved positions
440
456
  if ("scrollRestoration" in history) history.scrollRestoration = "manual";
441
- // set initial HMR state from SSR
457
+ // dev HMR surface: available even without SSR state so the client can tell
458
+ // a missing router apart from a missing initial payload
459
+ const globals = globalThis as unknown as {
460
+ __grimoire_current_pattern__?: string;
461
+ __grimoire_routes__?: Record<string, RouteEntry>;
462
+ __grimoire_rerender__?: () => Promise<void>;
463
+ __grimoire_navigate__?: (path: string, replace?: boolean) => void;
464
+ __grimoire_hmr__?: HmrControl;
465
+ };
466
+ globals.__grimoire_routes__ = routeMap;
467
+ globals.__grimoire_rerender__ = hmrRerender;
468
+ globals.__grimoire_hmr__ = hmrControl;
469
+ globals.__grimoire_navigate__ = (path, replace) =>
470
+ navigate(path, replace ?? false);
471
+
472
+ // initial HMR state from SSR
442
473
  const stateEl = document.getElementById("__grimoire_state__");
443
474
  if (stateEl) {
444
475
  const state = JSON.parse(stateEl.textContent!);
@@ -451,16 +482,7 @@ export function initRouter(
451
482
  if (Array.isArray(state.deps)) {
452
483
  setDeps(state.pattern, state.deps);
453
484
  }
454
- (globalThis as unknown as { __grimoire_current_pattern__: string }).__grimoire_current_pattern__ =
455
- state.pattern;
456
- (globalThis as unknown as { __grimoire_routes__: Record<string, RouteEntry> }).__grimoire_routes__ =
457
- routeMap;
458
- (globalThis as unknown as { __grimoire_rerender__: () => Promise<void> }).__grimoire_rerender__ =
459
- hmrRerender;
460
- (globalThis as unknown as {
461
- __grimoire_navigate__: (path: string, replace?: boolean) => void;
462
- }).__grimoire_navigate__ = (path: string, replace?: boolean) =>
463
- navigate(path, replace ?? false);
485
+ globals.__grimoire_current_pattern__ = state.pattern;
464
486
  }
465
487
 
466
488
  saveScrollPosition();
@@ -1,22 +1,22 @@
1
- /**
2
- * Open an effect scope: run fn() and return a dispose function that tears down
3
- * every createEffect registered during that call.
4
- *
5
- * Communicates with @sigil-dev/runtime's createEffect via globalThis.__sigilEffectScope
6
- * so this file does not need to import from @sigil-dev/runtime (which would pull the
7
- * runtime source into Bun.build and break the test sandbox).
8
- */
9
- export function withEffectScope(fn: () => void): () => void {
10
- const prev = (globalThis as any).__sigilEffectScope;
11
- const disposers: (() => void)[] = [];
12
- (globalThis as any).__sigilEffectScope = disposers;
13
- try {
14
- fn();
15
- } finally {
16
- (globalThis as any).__sigilEffectScope = prev;
17
- }
18
- return () => {
19
- for (const d of disposers) d();
20
- disposers.length = 0;
21
- };
22
- }
1
+ /**
2
+ * Open an effect scope: run fn() and return a dispose function that tears down
3
+ * every createEffect registered during that call.
4
+ *
5
+ * Communicates with @sigil-dev/runtime's createEffect via globalThis.__sigilEffectScope
6
+ * so this file does not need to import from @sigil-dev/runtime (which would pull the
7
+ * runtime source into Bun.build and break the test sandbox).
8
+ */
9
+ export function withEffectScope(fn: () => void): () => void {
10
+ const prev = (globalThis as any).__sigilEffectScope;
11
+ const disposers: (() => void)[] = [];
12
+ (globalThis as any).__sigilEffectScope = disposers;
13
+ try {
14
+ fn();
15
+ } finally {
16
+ (globalThis as any).__sigilEffectScope = prev;
17
+ }
18
+ return () => {
19
+ for (const d of disposers) d();
20
+ disposers.length = 0;
21
+ };
22
+ }