@sigil-dev/grimoire 0.9.10 → 0.9.12

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.
package/index.ts CHANGED
@@ -19,6 +19,7 @@ export type {
19
19
  export { createHooks, sequence } from "./src/server/hooks";
20
20
  export type {
21
21
  BuiltinWorkerMode,
22
+ CliCommand,
22
23
  CoordinatorContext,
23
24
  GrimoireConfig,
24
25
  GrimoirePlugin,
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.10",
7
+ "version": "0.9.12",
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.10",
27
- "@sigil-dev/runtime": "0.9.10",
26
+ "@sigil-dev/compiler": "0.9.12",
27
+ "@sigil-dev/runtime": "0.9.12",
28
28
  "vite": "^8.0.16"
29
29
  },
30
30
  "peerDependencies": {
package/server.ts CHANGED
@@ -1,3 +1,4 @@
1
+ export { afterResponse } from "./src/server/after-response.ts";
1
2
  export { log } from "./src/logger/instance.ts";
2
3
  export { scanRoutes } from "./src/routing/scanner";
3
4
  export { createServer } from "./src/server";
@@ -8,7 +8,7 @@
8
8
  *
9
9
  * ensureCsrf copies the cookie's current token into a form just before it
10
10
  * submits. Always overwriting the value also fixes forms that did get an input
11
- * but are stale: a page opened later in another tab rotates the cookie.
11
+ * but are stale, say after the cookie expired and a new one was issued.
12
12
  */
13
13
 
14
14
  export const CSRF_FIELD = "_csrf";
@@ -18,16 +18,47 @@ import { ensureCsrf } from "./csrf.ts";
18
18
  export interface EnhanceOptions {
19
19
  /** URL to submit to (defaults to form's action) */
20
20
  action?: string;
21
- /** Called on successful submission (303 redirect) */
22
- onSuccess?: (result: { redirect: string }) => void;
21
+ /**
22
+ * Called when the action succeeds, before navigating to `redirect` (the
23
+ * page itself, unless the action redirected). `data` is whatever the
24
+ * action returned.
25
+ */
26
+ onSuccess?: (result: { redirect: string; data?: unknown }) => void;
23
27
  /** Called when server returns fail() with validation data */
24
28
  onFail?: (data: Record<string, unknown>) => void;
25
- /** Called on network or unexpected errors */
29
+ /** Called on network or unexpected errors, and for error() */
26
30
  onError?: (error: Error) => void;
27
31
  /** Whether to reset the form on success (default: true) */
28
32
  reset?: boolean;
29
33
  }
30
34
 
35
+ type Outcome =
36
+ | { fail: true; status: number; data: Record<string, unknown> }
37
+ | { error: true; status: number; message: string }
38
+ | { type: "success"; location: string; data: unknown }
39
+ | { type: "redirect"; status: number; location: string };
40
+
41
+ /**
42
+ * Go where the action sent us through the client router, so the destination's
43
+ * loads run again. Landing back on the same page replaces the history entry
44
+ * rather than adding one, and the router keeps the scroll position.
45
+ */
46
+ function follow(location: string): void {
47
+ const navigate = (
48
+ globalThis as {
49
+ __grimoire_navigate__?: (path: string, replace?: boolean) => void;
50
+ }
51
+ ).__grimoire_navigate__;
52
+ const target = new URL(location, window.location.href);
53
+ if (target.origin !== window.location.origin || !navigate) {
54
+ window.location.href = target.href;
55
+ return;
56
+ }
57
+ const path = target.pathname + target.search + target.hash;
58
+ const here = window.location.pathname + window.location.search;
59
+ navigate(path, target.pathname + target.search === here);
60
+ }
61
+
31
62
  /**
32
63
  * use:enhance directive for progressive form enhancement.
33
64
  * Attaches to a <form> element and intercepts submit events.
@@ -47,6 +78,13 @@ export function enhance(
47
78
  // check covers fetch submissions too
48
79
  ensureCsrf(form);
49
80
  const formData = new FormData(form);
81
+ // the button that submitted the form sends its own name=value, just
82
+ // as a native submission would
83
+ const submitter = (e as SubmitEvent).submitter as
84
+ | HTMLButtonElement
85
+ | HTMLInputElement
86
+ | null;
87
+ if (submitter?.name) formData.append(submitter.name, submitter.value);
50
88
  const resolved =
51
89
  action ?? form.getAttribute("action") ?? window.location.pathname;
52
90
  // SvelteKit-style named action: "?/create" submits to the current path
@@ -59,44 +97,40 @@ export function enhance(
59
97
  method: "POST",
60
98
  headers: {
61
99
  "X-Grimoire-Form": "1",
100
+ Accept: "application/json",
62
101
  },
63
102
  body: formData,
64
103
  });
65
104
 
66
105
  const contentType = res.headers.get("content-type") ?? "";
67
-
68
- if (contentType.includes("application/json")) {
69
- const json = await res.json();
70
-
71
- if (json.fail) {
72
- // fail() response — validation errors
73
- onFail?.(json.data);
74
- return;
75
- }
76
-
77
- // Regular JSON response (API route)
78
- onSuccess?.(json);
106
+ if (!contentType.includes("application/json")) {
107
+ if (!res.ok) throw new Error(`Form submission failed: ${res.status}`);
108
+ // something that isn't a page action answered (a proxy, a plain
109
+ // endpoint): count it as done and stay put
110
+ if (reset) form.reset();
111
+ onSuccess?.({ redirect: window.location.pathname });
79
112
  return;
80
113
  }
81
114
 
82
- // Non-JSON response (303 redirect or other)
83
- if (res.status === 303) {
84
- const location = res.headers.get("location") ?? "/";
85
- if (reset) form.reset();
86
- onSuccess?.({ redirect: location });
87
- // Navigate to the redirect target
88
- window.history.pushState({}, "", location);
89
- window.dispatchEvent(new PopStateEvent("popstate"));
115
+ const json = (await res.json()) as Outcome | Record<string, unknown>;
116
+ if ("fail" in json && json.fail) {
117
+ onFail?.((json as { data: Record<string, unknown> }).data);
90
118
  return;
91
119
  }
92
-
93
- // Other response
94
- if (res.ok) {
120
+ if ("error" in json && json.error) {
121
+ throw new Error(String((json as { message?: unknown }).message));
122
+ }
123
+ if (json.type === "success" || json.type === "redirect") {
124
+ const outcome = json as { location: string; data?: unknown };
95
125
  if (reset) form.reset();
96
- onSuccess?.({ redirect: window.location.pathname });
97
- } else {
98
- onError?.(new Error(`Form submission failed: ${res.status}`));
126
+ onSuccess?.({ redirect: outcome.location, data: outcome.data });
127
+ follow(outcome.location);
128
+ return;
99
129
  }
130
+ // JSON from a +server.ts endpoint (action: "/api/…")
131
+ if (!res.ok) throw new Error(`Form submission failed: ${res.status}`);
132
+ if (reset) form.reset();
133
+ onSuccess?.({ redirect: window.location.pathname, data: json });
100
134
  } catch (err) {
101
135
  onError?.(err instanceof Error ? err : new Error(String(err)));
102
136
  }
@@ -41,7 +41,7 @@ type PageComponent = ((props: any) => any) & {
41
41
  * component functions are also accepted (tests, HMR replacements). */
42
42
  type RouteEntry =
43
43
  | PageComponent
44
- | { __lazy: () => Promise<{ default: PageComponent }> };
44
+ | { __lazy: () => Promise<{ default: PageComponent; loading?: () => any }> };
45
45
 
46
46
  let routeMap: Record<string, RouteEntry> = {};
47
47
  const resolvedRoutes: Record<string, PageComponent> = {};
@@ -51,7 +51,17 @@ async function resolveRoute(pattern: string): Promise<PageComponent | null> {
51
51
  if (!entry) return null;
52
52
  // plain function: eager component or an HMR hot-swap — always wins over cache
53
53
  if (typeof entry === "function") return entry;
54
- return (resolvedRoutes[pattern] ??= (await entry.__lazy()).default);
54
+ if (!resolvedRoutes[pattern]) {
55
+ const mod = (await entry.__lazy()) as {
56
+ default: PageComponent;
57
+ loading?: PageComponent["loading"];
58
+ };
59
+ // `loading` is a named export of the page module; navigation looks
60
+ // for it on the component, and never saw it before
61
+ if (mod.loading && !mod.default.loading) mod.default.loading = mod.loading;
62
+ resolvedRoutes[pattern] = mod.default;
63
+ }
64
+ return resolvedRoutes[pattern];
55
65
  }
56
66
  let layoutList: { path: string; component: (props: any) => any }[] = [];
57
67
  let disposeCurrentPage: (() => void) | null = null;
@@ -568,7 +578,25 @@ export function initRouter(
568
578
  setupPreload();
569
579
  }
570
580
 
581
+ /**
582
+ * Swap the page's <head> tags for the incoming page's. Server-rendered tags
583
+ * sit between `<!--grimoire-head-->` markers; tags added by an earlier
584
+ * navigation carry `data-grimoire-head`. Both are replaced, so the first
585
+ * navigation doesn't leave the server-rendered description or icon behind
586
+ * next to the new ones. With no incoming <title>, the current title stays.
587
+ */
571
588
  function updateHead(headHtml: string) {
589
+ const prevTitle = document.title;
590
+ const markers = Array.from(document.head.childNodes).filter(
591
+ (n): n is Comment => n.nodeType === Node.COMMENT_NODE,
592
+ );
593
+ const start = markers.find((c) => c.data === "grimoire-head");
594
+ const end = markers.find((c) => c.data === "/grimoire-head");
595
+ if (start && end) {
596
+ while (start.nextSibling && start.nextSibling !== end) {
597
+ start.nextSibling.remove();
598
+ }
599
+ }
572
600
  document
573
601
  .querySelectorAll("[data-grimoire-head]")
574
602
  //biome-ignore lint/suspicious/useIterableCallbackReturn: shut up
@@ -577,19 +605,15 @@ function updateHead(headHtml: string) {
577
605
  ? new DOMParser().parseFromString(`<head>${headHtml}</head>`, "text/html")
578
606
  : null;
579
607
  const incomingTitle = parsed?.querySelector("title");
580
- if (incomingTitle) {
581
- // capture before removing <title> elements — reading document.title
582
- // after removal returns "" and would wipe the title
583
- const prevTitle = document.title;
584
- //biome-ignore lint/suspicious/useIterableCallbackReturn: shut up
585
- document.querySelectorAll("title").forEach((el) => el.remove());
586
- document.title = incomingTitle.textContent ?? prevTitle;
587
- }
608
+ //biome-ignore lint/suspicious/useIterableCallbackReturn: shut up
609
+ document.querySelectorAll("title").forEach((el) => el.remove());
610
+ document.title = incomingTitle?.textContent ?? prevTitle;
588
611
  if (parsed) {
589
612
  for (const el of Array.from(parsed.head.children)) {
590
613
  if (el.tagName === "TITLE") continue;
591
614
  (el as HTMLElement).dataset.grimoireHead = "1";
592
- document.head.appendChild(el);
615
+ if (end) document.head.insertBefore(el, end);
616
+ else document.head.appendChild(el);
593
617
  }
594
618
  }
595
619
  }
@@ -3,7 +3,11 @@ import { mkdirSync, writeFileSync } from "node:fs";
3
3
  import { join, relative } from "node:path";
4
4
  import { transformSync } from "@babel/core";
5
5
  import sigilPlugin from "@sigil-dev/compiler/babel";
6
- import { computeHash, scopeCSS } from "@sigil-dev/compiler/css";
6
+ import {
7
+ clientStyleSnippet,
8
+ computeHash,
9
+ extractStyles,
10
+ } from "@sigil-dev/compiler/css";
7
11
  import type { DevGraph } from "./graph";
8
12
  import { normalizePath } from "./paths";
9
13
  import { resolveProjectImport } from "./resolve";
@@ -40,7 +44,8 @@ function rewriteSpecifier(
40
44
  ctx: BrowserCompileContext,
41
45
  ): string {
42
46
  if (specifier === "@sigil-dev/runtime") return RUNTIME_URL;
43
- if (specifier.startsWith("$env/")) return specifier;
47
+ if (specifier.startsWith("$env/"))
48
+ return `/__grimoire__/env/${specifier.slice("$env/".length)}.js`;
44
49
 
45
50
  const resolved = resolveProjectImport(
46
51
  specifier,
@@ -93,8 +98,6 @@ export interface CompileResult {
93
98
  cssHash: string;
94
99
  }
95
100
 
96
- const STYLE_RE = /<style[^>]*>([\s\S]*?)<\/style>/i;
97
-
98
101
  const RUNTIME_SPECIFIERS = [
99
102
  "createSignal",
100
103
  "createRawSignal",
@@ -125,9 +128,7 @@ export async function compileForBrowser(
125
128
  // the scope hash must be the compiler's own: a swapped module whose
126
129
  // elements carry a different class than the emitted CSS loses its styles
127
130
  const hash = computeHash(filePath);
128
- const styleBody = source.match(STYLE_RE)?.[1]?.trim();
129
- const css = styleBody ? scopeCSS(styleBody, hash) : null;
130
- const sourceNoStyle = source.replace(/<style[^>]*>[\s\S]*?<\/style>/gi, "");
131
+ const { code: sourceNoStyle, css } = extractStyles(source, hash, filePath);
131
132
 
132
133
  // dom mode: swapped modules always re-render from scratch, they never
133
134
  // claim server-rendered nodes
@@ -135,7 +136,9 @@ export async function compileForBrowser(
135
136
  configFile: false,
136
137
  babelrc: false,
137
138
  parserOpts: { plugins: ["typescript", "jsx"] },
138
- plugins: [[sigilPlugin, { mode: "dom", hash, dev: true }]],
139
+ plugins: [
140
+ [sigilPlugin, { mode: "dom", hash: css ? hash : undefined, dev: true }],
141
+ ],
139
142
  filename: filePath,
140
143
  });
141
144
  // strip TypeScript types
@@ -148,14 +151,7 @@ export async function compileForBrowser(
148
151
  );
149
152
 
150
153
  // inject scoped CSS at runtime
151
- if (css) {
152
- js = `if (typeof document !== 'undefined' && !document.getElementById('sigil-${hash}')) {
153
- const __s = document.createElement('style');
154
- __s.id = 'sigil-${hash}';
155
- __s.textContent = ${JSON.stringify(css)};
156
- document.head.appendChild(__s);
157
- }\n${js}`;
158
- }
154
+ if (css) js = clientStyleSnippet(hash, css) + js;
159
155
 
160
156
  js = rewriteImports(js, filePath, ctx);
161
157
 
package/src/dev/loader.ts CHANGED
@@ -4,6 +4,11 @@ import { join } from "node:path";
4
4
  import { pathToFileURL } from "node:url";
5
5
  import { transformSync } from "@babel/core";
6
6
  import sigilPlugin from "@sigil-dev/compiler/babel";
7
+ import {
8
+ computeHash,
9
+ extractStyles,
10
+ serverStyleSnippet,
11
+ } from "@sigil-dev/compiler/css";
7
12
  import { disposeModuleEffects } from "./effect-registry";
8
13
  import type { DevGraph } from "./graph";
9
14
  import { normalizePath } from "./paths";
@@ -45,11 +50,11 @@ export function makeDevLoader(
45
50
  // untouched since startup: the SSR plugin handles the source directly
46
51
  if (version === 0) return pathToFileURL(filePath).href;
47
52
 
48
- const hash = createHash("md5")
53
+ const key = createHash("md5")
49
54
  .update(normalizePath(filePath))
50
55
  .digest("hex")
51
56
  .slice(0, 8);
52
- const cachePath = join(cacheDir, `${hash}_v${version}.js`);
57
+ const cachePath = join(cacheDir, `${key}_v${version}.js`);
53
58
  const href = pathToFileURL(cachePath).href;
54
59
  // (file, version) is immutable within a session; import cycles reach
55
60
  // the same deterministic path, and the outer call writes it
@@ -58,15 +63,31 @@ export function makeDevLoader(
58
63
 
59
64
  try {
60
65
  const source = await Bun.file(filePath).text();
61
- const babelResult = transformSync(source, {
66
+ // scoped <style> blocks come out before parsing (CSS braces would
67
+ // read as JSX expressions); their CSS is registered for the
68
+ // renderer, which puts it in <head>
69
+ const styles = extractStyles(source, computeHash(filePath), filePath);
70
+ const babelResult = transformSync(styles.code, {
62
71
  configFile: false,
63
72
  babelrc: false,
64
73
  parserOpts: { plugins: ["typescript", "jsx"] },
65
- plugins: [[sigilPlugin, { mode: "ssr", hash }]],
74
+ plugins: [
75
+ [
76
+ sigilPlugin,
77
+ {
78
+ mode: "ssr",
79
+ hash: styles.css ? computeHash(filePath) : undefined,
80
+ },
81
+ ],
82
+ ],
66
83
  filename: filePath,
67
84
  });
68
85
  const transpiler = new Bun.Transpiler({ loader: "ts", target: "bun" });
69
86
  let compiled = transpiler.transformSync(babelResult?.code ?? "");
87
+ if (styles.css) {
88
+ compiled =
89
+ serverStyleSnippet(computeHash(filePath), styles.css) + compiled;
90
+ }
70
91
  compiled = await rewriteSpecifiers(compiled, async (specifier) => {
71
92
  const resolved = resolveProjectImport(
72
93
  specifier,
@@ -12,7 +12,7 @@ function isFile(p: string): boolean {
12
12
  }
13
13
 
14
14
  /** Add extensions / index files until an on-disk source file is found. */
15
- function resolveFile(base: string): string | null {
15
+ export function resolveFile(base: string): string | null {
16
16
  if (isFile(base)) return base;
17
17
  for (const ext of EXTS) if (isFile(base + ext)) return base + ext;
18
18
  for (const ext of EXTS) {
@@ -0,0 +1,62 @@
1
+ import { join } from "node:path";
2
+ import { filterPrivate, filterPublic } from "./index";
3
+
4
+ /**
5
+ * Source for the `$env/*` modules.
6
+ *
7
+ * - `$env/static/public` and `$env/static/private`: values read when the
8
+ * module is built (the browser build, or server start), as `env` and as
9
+ * one named export per variable.
10
+ * - `$env/dynamic/public`: `env`, read live on the server; in the browser,
11
+ * the values the server rendered into the page (`__grimoire_env__`).
12
+ * - `$env/dynamic/private`: `env`, every variable, read live.
13
+ *
14
+ * `env` reads a missing variable as "".
15
+ *
16
+ * The private modules are server-only: importing one into browser code
17
+ * fails the build rather than shipping secrets.
18
+ */
19
+ export const ENV_MODULE = /^\$env\/(static|dynamic)\/(public|private)$/;
20
+
21
+ const IDENT = /^[A-Za-z_$][\w$]*$/;
22
+
23
+ function snapshot(values: Record<string, string>): string {
24
+ const names = Object.keys(values).filter((k) => IDENT.test(k));
25
+ return [
26
+ `export const env = ${JSON.stringify(values)};`,
27
+ ...names.map((k) => `export const ${k} = env[${JSON.stringify(k)}];`),
28
+ ].join("\n");
29
+ }
30
+
31
+ export function envModuleSource(
32
+ specifier: string,
33
+ target: "server" | "browser",
34
+ ): string {
35
+ const m = ENV_MODULE.exec(specifier);
36
+ if (!m) throw new Error(`unknown env module ${specifier}`);
37
+ const [, kind, visibility] = m;
38
+ if (visibility === "private" && target === "browser") {
39
+ throw new Error(
40
+ `${specifier} holds server secrets and can't be imported into browser code. Import it from a .server.ts file, or use $env/${kind}/public for PUBLIC_ variables.`,
41
+ );
42
+ }
43
+ if (kind === "static") {
44
+ return snapshot(
45
+ visibility === "public"
46
+ ? filterPublic(process.env)
47
+ : filterPrivate(process.env),
48
+ );
49
+ }
50
+ if (target === "browser") {
51
+ // like the server's: a missing PUBLIC_ variable reads as ""
52
+ return `const values = globalThis.__grimoire_env__ ?? {};
53
+ export const env = new Proxy(values, {
54
+ get: (t, k) => (typeof k === "string" ? (t[k] ?? "") : undefined),
55
+ });`;
56
+ }
57
+ const file = join(
58
+ import.meta.dir,
59
+ visibility === "public" ? "dynamic-public.ts" : "dynamic-private.ts",
60
+ );
61
+ return `export { env } from ${JSON.stringify(file)};`;
62
+ }
@@ -32,15 +32,15 @@ export async function generateEnvTypes(
32
32
 
33
33
  const publicTypeContent = `// Auto-generated by Grimoire. Do not edit.
34
34
  declare module "$env/static/public" {
35
+ \texport const env: Record<string, string>;
35
36
  ${publicVars.map((v) => `\texport const ${v}: string;`).join("\n")}
36
- ${publicVars.length === 0 ? "\texport {};" : ""}
37
37
  }
38
38
  `;
39
39
 
40
40
  const privateTypeContent = `// Auto-generated by Grimoire. Do not edit.
41
41
  declare module "$env/static/private" {
42
+ \texport const env: Record<string, string>;
42
43
  ${privateVars.map((v) => `\texport const ${v}: string;`).join("\n")}
43
- ${privateVars.length === 0 ? "\texport {};" : ""}
44
44
  }
45
45
  `;
46
46
 
@@ -20,11 +20,8 @@ export function collectHead(): string {
20
20
  return (getContext(HeadKey) ?? []).join("\n ");
21
21
  }
22
22
 
23
- export function Head({
24
- children,
25
- }: {
26
- children: string | Node;
27
- }): string | Comment {
23
+ /** Puts its children in the page's <head>. */
24
+ export function Head({ children }: { children?: unknown }): string | Comment {
28
25
  if (typeof document === "undefined") {
29
26
  const buf = getContext(HeadKey);
30
27
  if (buf) {
@@ -87,6 +87,7 @@ async function hydrate(): Promise<(() => void) | undefined> {
87
87
  pageNode = Page({
88
88
  data: state.data,
89
89
  params: state.params,
90
+ form: state.form,
90
91
  });
91
92
  } finally {
92
93
  // always rebalance the global hydration stack — a throwing
@@ -98,6 +99,7 @@ async function hydrate(): Promise<(() => void) | undefined> {
98
99
  const pageNode = Page({
99
100
  data: state.data,
100
101
  params: state.params,
102
+ form: state.form,
101
103
  });
102
104
  insert(pageDiv, pageNode);
103
105
  }