@sigil-dev/grimoire 0.9.32 → 0.10.0

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.
@@ -139,6 +139,12 @@ export const HMR_CLIENT_SOURCE = `
139
139
  window.__hmrCapture__ = null;
140
140
  }
141
141
 
142
+ // A navigation away (OAuth redirects, a slow callback) closes the socket
143
+ // before the next page arrives; reloading then would cancel it.
144
+ let leaving = 0;
145
+ window.addEventListener('beforeunload', () => { leaving = Date.now(); });
146
+ window.addEventListener('pageshow', () => { leaving = 0; });
147
+
142
148
  function connect() {
143
149
  const ws = new WebSocket(
144
150
  (location.protocol === 'https:' ? 'wss' : 'ws') +
@@ -165,6 +171,8 @@ export const HMR_CLIENT_SOURCE = `
165
171
  ws.onclose = () => {
166
172
  console.log('[sigil hmr] disconnected, reconnecting...');
167
173
  const retry = setInterval(async () => {
174
+ // still navigating away: let that finish instead (gives up after 15s)
175
+ if (leaving && Date.now() - leaving < 15000) return;
168
176
  try {
169
177
  await fetch('/', { method: 'HEAD' });
170
178
  clearInterval(retry);
@@ -35,8 +35,8 @@ export function parseChunkGraph(source: string): ChunkGraph | null {
35
35
  let ids: string[];
36
36
  let raw: Array<Array<string | number>>;
37
37
  try {
38
- ids = JSON.parse(call[1]);
39
- raw = JSON.parse(call[2]);
38
+ ids = JSON.parse(call[1]!);
39
+ raw = JSON.parse(call[2]!);
40
40
  } catch {
41
41
  return null;
42
42
  }
@@ -46,14 +46,14 @@ export function parseChunkGraph(source: string): ChunkGraph | null {
46
46
  if (typeof file !== "string") return;
47
47
  nodes.set(id, {
48
48
  file,
49
- deps: deps.map((d) => ids[Number(d)]).filter(Boolean),
49
+ deps: deps.map((d) => ids[Number(d)]).filter((d): d is string => !!d),
50
50
  });
51
51
  });
52
52
  const routes = new Map<string, string>();
53
53
  for (const m of source.matchAll(
54
54
  /^\s*("(?:[^"\\]|\\.)*"):\s*\{\s*__lazy:\s*\(\)\s*=>\s*\(__preload\("([^"]+)"\)/gm,
55
55
  )) {
56
- routes.set(JSON.parse(m[1]), m[2]);
56
+ routes.set(JSON.parse(m[1]!), m[2]!);
57
57
  }
58
58
  return { routes, nodes };
59
59
  }
@@ -1,107 +1,114 @@
1
- import { transformSync } from "@babel/core";
2
- import type { ParserPlugin } from "@babel/parser";
3
- import sigilPlugin from "@sigil-dev/compiler/babel";
4
- import {
5
- computeHash,
6
- extractStyles,
7
- serverStyleSnippet,
8
- } from "@sigil-dev/compiler/css";
9
- import { log } from "../logger/instance";
10
- import { pinRuntime, rewriteAliases } from "../server/resolver";
11
- import type { GrimoirePlugin } from "../types";
12
-
13
- const logger = log.scope("scope");
14
- let registered = false;
15
-
16
- /**
17
- * `aliases` (prefix → absolute directory, see projectAliases) are rewritten
18
- * to file paths in every compiled module: Bun's runtime plugins can't
19
- * resolve them for static imports.
20
- */
21
- export function registerSSRPlugin(
22
- plugins: GrimoirePlugin[] = [],
23
- aliases: Record<string, string> = {},
24
- ) {
25
- if (registered) return;
26
- registered = true;
27
-
28
- Bun.plugin({
29
- name: "sigil-ssr",
30
-
31
- setup(build) {
32
- // loader: "ts" not "tsx" — Babel already consumed the JSX,
33
- // Bun only needs to strip remaining TypeScript types
34
- const transpiler = new Bun.Transpiler({ loader: "ts", target: "bun" });
35
- build.onResolve({ filter: /^@sigil-dev\/runtime($|\/)/ }, (args) => {
36
- try {
37
- const resolved = Bun.resolveSync(args.path, process.cwd());
38
- return { path: resolved.replaceAll("\\", "/") };
39
- } catch {
40
- return undefined;
41
- }
42
- });
43
-
44
- build.onLoad({ filter: /\.tsx?$/ }, async ({ path }) => {
45
- if (path.includes("index.tsx"))
46
- logger.debug("[ssr-plugin] onLoad:", path);
47
- const source = await Bun.file(path).text();
48
-
49
- // node_modules and .grimoire files are plain TypeScript (no sigil JSX).
50
- // Still must return { contents, loader } — never return undefined from onLoad.
51
- if (path.includes("node_modules") || path.includes(".grimoire")) {
52
- return {
53
- contents: transpiler.transformSync(source),
54
- loader: "js" as const,
55
- };
56
- }
57
-
58
- if (process.env.SIGIL_VERBOSE) {
59
- logger.debug("[sigil-ssr] XFORM:", path);
60
- }
61
- // must match the client build, or scoped classes differ per side;
62
- // files without a <style> block get no scope class at all. The
63
- // CSS is registered for the renderer, which puts it in <head>.
64
- const styles = extractStyles(source, computeHash(path), path);
65
- const hash = styles.css ? computeHash(path) : undefined;
66
- const sourceNoStyle = styles.code;
67
- const result = transformSync(sourceNoStyle, {
68
- configFile: false,
69
- babelrc: false,
70
- parserOpts: {
71
- // The jsx plugin goes on .tsx files only.
72
- //
73
- // With it enabled everywhere, Babel parses `<R>(x: R) => x`
74
- // as the opening of a JSX element and fails with
75
- // "Unexpected token `>`". So a generic arrow function in a
76
- // plain .ts file — completely ordinary TypeScript — could
77
- // not be compiled. Found while writing the Drizzle adapter
78
- // recipe, where `transaction: <R>(db, fn) => ...` is the
79
- // form that removes an `as any`.
80
- //
81
- // A .tsx file is genuinely ambiguous (`<R>(x) => x` is
82
- // JSX there), so .tsx keeps both and users write `<R,>`.
83
- plugins: path.endsWith(".tsx")
84
- ? (["typescript", "jsx"] as ParserPlugin[])
85
- : (["typescript"] as ParserPlugin[]),
86
- },
87
- plugins: [[sigilPlugin, { mode: "ssr", hash, aliases }]],
88
- filename: path,
89
- });
90
-
91
- let contents = pinRuntime(
92
- rewriteAliases(transpiler.transformSync(result?.code ?? ""), aliases),
93
- );
94
- if (styles.css && hash) {
95
- contents = serverStyleSnippet(hash, styles.css) + contents;
96
- }
97
-
98
- for (const plugin of plugins) {
99
- if (plugin.transform)
100
- contents = (await plugin.transform(contents, path)) ?? contents;
101
- }
102
-
103
- return { contents, loader: "js" as const };
104
- });
105
- },
106
- });
107
- }
1
+ import { transformSync } from "@babel/core";
2
+ import type { ParserPlugin } from "@babel/parser";
3
+ import sigilPlugin from "@sigil-dev/compiler/babel";
4
+ import {
5
+ computeHash,
6
+ extractStyles,
7
+ serverStyleSnippet,
8
+ } from "@sigil-dev/compiler/css";
9
+ import { log } from "../logger/instance";
10
+ import { pinRuntime, rewriteAliases } from "../server/resolver";
11
+ import type { GrimoirePlugin } from "../types";
12
+
13
+ const logger = log.scope("scope");
14
+ let registered = false;
15
+ let current: { plugins: GrimoirePlugin[]; aliases: Record<string, string> } = { plugins: [], aliases: {} };
16
+
17
+ /**
18
+ * `aliases` (prefix → absolute directory, see projectAliases) are rewritten
19
+ * to file paths in every compiled module: Bun's runtime plugins can't
20
+ * resolve them for static imports.
21
+ */
22
+ export function registerSSRPlugin(
23
+ plugins: GrimoirePlugin[] = [],
24
+ aliases: Record<string, string> = {},
25
+ ) {
26
+ // Registered once (Bun keeps every plugin), but a later call brings the
27
+ // app's real plugins and aliases: `sigil test` registers early with the
28
+ // defaults, so a test's own imports compile with Sigil's JSX, and the app
29
+ // fills in the rest when it starts.
30
+ current = { plugins, aliases };
31
+ if (registered) return;
32
+ registered = true;
33
+
34
+ Bun.plugin({
35
+ name: "sigil-ssr",
36
+
37
+ setup(build) {
38
+ // loader: "ts" not "tsx" — Babel already consumed the JSX,
39
+ // Bun only needs to strip remaining TypeScript types
40
+ const transpiler = new Bun.Transpiler({ loader: "ts", target: "bun" });
41
+ build.onResolve({ filter: /^@sigil-dev\/runtime($|\/)/ }, (args) => {
42
+ try {
43
+ const resolved = Bun.resolveSync(args.path, process.cwd());
44
+ return { path: resolved.replaceAll("\\", "/") };
45
+ } catch {
46
+ return undefined;
47
+ }
48
+ });
49
+
50
+ build.onLoad({ filter: /\.tsx?$/ }, async ({ path }) => {
51
+ const { plugins, aliases } = current;
52
+ if (path.includes("index.tsx"))
53
+ logger.debug("[ssr-plugin] onLoad:", path);
54
+ const source = await Bun.file(path).text();
55
+
56
+ // node_modules and .grimoire files are plain TypeScript (no sigil JSX).
57
+ // Still must return { contents, loader } — never return undefined from onLoad.
58
+ if (path.includes("node_modules") || path.includes(".grimoire")) {
59
+ return {
60
+ contents: transpiler.transformSync(source),
61
+ loader: "js" as const,
62
+ };
63
+ }
64
+
65
+ if (process.env.SIGIL_VERBOSE) {
66
+ logger.debug("[sigil-ssr] XFORM:", path);
67
+ }
68
+ // must match the client build, or scoped classes differ per side;
69
+ // files without a <style> block get no scope class at all. The
70
+ // CSS is registered for the renderer, which puts it in <head>.
71
+ const styles = extractStyles(source, computeHash(path), path);
72
+ const hash = styles.css ? computeHash(path) : undefined;
73
+ const sourceNoStyle = styles.code;
74
+ const result = transformSync(sourceNoStyle, {
75
+ configFile: false,
76
+ babelrc: false,
77
+ parserOpts: {
78
+ // The jsx plugin goes on .tsx files only.
79
+ //
80
+ // With it enabled everywhere, Babel parses `<R>(x: R) => x`
81
+ // as the opening of a JSX element and fails with
82
+ // "Unexpected token `>`". So a generic arrow function in a
83
+ // plain .ts file — completely ordinary TypeScript — could
84
+ // not be compiled. Found while writing the Drizzle adapter
85
+ // recipe, where `transaction: <R>(db, fn) => ...` is the
86
+ // form that removes an `as any`.
87
+ //
88
+ // A .tsx file is genuinely ambiguous (`<R>(x) => x` is
89
+ // JSX there), so .tsx keeps both and users write `<R,>`.
90
+ plugins: path.endsWith(".tsx")
91
+ ? (["typescript", "jsx"] as ParserPlugin[])
92
+ : (["typescript"] as ParserPlugin[]),
93
+ },
94
+ plugins: [[sigilPlugin, { mode: "ssr", hash, aliases }]],
95
+ filename: path,
96
+ });
97
+
98
+ let contents = pinRuntime(
99
+ rewriteAliases(transpiler.transformSync(result?.code ?? ""), aliases),
100
+ );
101
+ if (styles.css && hash) {
102
+ contents = serverStyleSnippet(hash, styles.css) + contents;
103
+ }
104
+
105
+ for (const plugin of plugins) {
106
+ if (plugin.transform)
107
+ contents = (await plugin.transform(contents, path)) ?? contents;
108
+ }
109
+
110
+ return { contents, loader: "js" as const };
111
+ });
112
+ },
113
+ });
114
+ }
@@ -28,7 +28,7 @@ export function createTimer(): Timer {
28
28
  marks.push([name, now - last]);
29
29
  last = now;
30
30
  },
31
- headers() {
31
+ headers(): Record<string, string> {
32
32
  if (!enabled || marks.length === 0) return {};
33
33
  return {
34
34
  "Server-Timing": marks
@@ -102,6 +102,26 @@ export function filePathToRoutePath(
102
102
 
103
103
  const TEST_FILE = /[._](test|spec)\.[jt]sx?$/;
104
104
 
105
+ /** How loosely a pattern segment matches: fixed text, a param, an optional one, the rest. */
106
+ const segmentRank = (seg: string) =>
107
+ seg.startsWith("*") ? 3 : seg.endsWith("?") ? 2 : seg.startsWith(":") ? 1 : 0;
108
+
109
+ /**
110
+ * Between routes that score the same, the one that is more specific earlier
111
+ * in the path goes first: /wiki/_history/*page before /wiki/*page, though
112
+ * both have one rest param. Without this, ties fell to the order the
113
+ * filesystem listed the folders in, which differs between machines.
114
+ */
115
+ export function byShape(a: string, b: string): number {
116
+ const as = a.split("/").filter(Boolean);
117
+ const bs = b.split("/").filter(Boolean);
118
+ for (let i = 0; i < Math.min(as.length, bs.length); i++) {
119
+ const d = segmentRank(as[i]!) - segmentRank(bs[i]!);
120
+ if (d) return d;
121
+ }
122
+ return bs.length - as.length || (a < b ? -1 : a > b ? 1 : 0);
123
+ }
124
+
105
125
  export async function scanRoutes(
106
126
  routesDir: string,
107
127
  viteRoot: string = routesDir,
@@ -170,8 +190,10 @@ export async function scanRoutes(
170
190
  r.paramNames.length * 2 +
171
191
  r.optionalParamNames.length +
172
192
  r.restParamNames.length * 1000;
173
- routes.sort((a, b) => scoreRoute(a) - scoreRoute(b));
174
- servers.sort((a, b) => scoreRoute(a) - scoreRoute(b));
193
+ const byScore = (a: RouteFile, b: RouteFile) =>
194
+ scoreRoute(a) - scoreRoute(b) || byShape(a.path, b.path);
195
+ routes.sort(byScore);
196
+ servers.sort(byScore);
175
197
 
176
198
  assertNoDuplicatePaths(
177
199
  routes.filter((r) => r.type === "page" || r.type === "simple"),
@@ -51,7 +51,7 @@ async function waitForWorkers(
51
51
 
52
52
  function roundRobin(workers: WorkerDescriptor[]): WorkerDescriptor {
53
53
  const idx = roundRobinCounter++ % workers.length;
54
- return workers[idx];
54
+ return workers[idx]!;
55
55
  }
56
56
  let roundRobinCounter = 0;
57
57
 
@@ -63,7 +63,7 @@ function consistentHash(
63
63
  let hash = 0;
64
64
  for (let i = 0; i < key.length; i++)
65
65
  hash = (hash * 31 + key.charCodeAt(i)) >>> 0;
66
- return workers[hash % workers.length];
66
+ return workers[hash % workers.length]!;
67
67
  }
68
68
 
69
69
  function defaultRoute(
@@ -86,7 +86,7 @@ function defaultRoute(
86
86
  (w) => w.mode === "frontend" || w.mode === "full",
87
87
  );
88
88
  if (frontend.length) return roundRobin(frontend);
89
- return workers[0];
89
+ return workers[0]!;
90
90
  }
91
91
 
92
92
  export interface ScaleSpec {
@@ -226,7 +226,7 @@ export async function startCoordinator(options: CoordinatorOptions) {
226
226
  index: i + 1,
227
227
  globalIndex: globalIndex++,
228
228
  internalUrl: `http://127.0.0.1:${workerPort}`,
229
- routes: slices[mode] ?? slices.full,
229
+ routes: slices[mode] ?? slices.full ?? [],
230
230
  };
231
231
 
232
232
  const publicEnvVars: Record<string, string> = {};
@@ -311,7 +311,8 @@ export async function startCoordinator(options: CoordinatorOptions) {
311
311
  return new Response("Upgrade Required", { status: 426 });
312
312
  }
313
313
 
314
- const locals: App.Locals = {};
314
+ // filled in by the plugins' handles before anything reads it
315
+ const locals = {} as App.Locals;
315
316
  const descriptors = liveWorkers.map((w) => w.descriptor);
316
317
  const chosen =
317
318
  (await runRouteRequest(plugins, req, descriptors, tree)) ??
@@ -479,14 +479,13 @@ export async function createApp(
479
479
  const rawLocals = finalConfig._behindCoordinator
480
480
  ? req.headers.get("X-Grimoire-Locals")
481
481
  : null;
482
- const locals: App.Locals = rawLocals
483
- ? ((await runDeserializeLocals(plugins, rawLocals)) ?? {})
484
- : {};
482
+ // filled in by the plugins' handles before anything reads it
483
+ const locals = (rawLocals ? ((await runDeserializeLocals(plugins, rawLocals)) ?? {}) : {}) as App.Locals;
485
484
  // Plugin services sit under the request's own locals: what the app
486
485
  // set (a session, a user) always wins over what a plugin declared,
487
486
  // so a plugin cannot clobber auth by defining a common key.
488
487
  for (const [key, value] of Object.entries(services)) {
489
- if (!(key in locals)) locals[key] = value;
488
+ if (!(key in locals)) (locals as unknown as Record<string, unknown>)[key] = value;
490
489
  }
491
490
  const url = new URL(req.url);
492
491
 
@@ -639,7 +638,7 @@ export async function createApp(
639
638
  ] as const;
640
639
 
641
640
  // Build event BEFORE matching — handle() runs pre-match like SvelteKit
642
- trackClientAddress(req, server);
641
+ trackClientAddress(req, server ?? null);
643
642
  const cookieHeader = req.headers.get("cookie") ?? "";
644
643
  const cookies = createCookies(cookieHeader);
645
644
  const setHeadersMap: Record<string, string> = {};
@@ -664,13 +663,13 @@ export async function createApp(
664
663
  );
665
664
  };
666
665
  }
667
- const patchedFetch: typeof fetch = (input, init) => {
666
+ const patchedFetch = ((input: Parameters<typeof fetch>[0], init?: Parameters<typeof fetch>[1]) => {
668
667
  const resolved =
669
668
  typeof input === "string" && input.startsWith("/")
670
669
  ? new URL(input, url.origin).toString()
671
670
  : input;
672
671
  return globalThis.fetch(resolved as any, init);
673
- };
672
+ }) as typeof fetch;
674
673
  const resolve: ResolveFunction = async (evt) => {
675
674
  // matching happens here — after handle() has run
676
675
  let matched = matchRoute(tree, evt.url, paramMatcherFns);
@@ -737,7 +736,7 @@ export async function createApp(
737
736
  locals: evt.locals,
738
737
  fetch: patchedFetch,
739
738
  cookies,
740
- setHeaders: (headers) => Object.assign(setHeadersMap, headers),
739
+ setHeaders: (headers: Record<string, string>) => Object.assign(setHeadersMap, headers),
741
740
  getClientAddress: () => clientAddressOf(evt.request),
742
741
  });
743
742
  } catch (e) {
@@ -748,6 +747,24 @@ export async function createApp(
748
747
  headers: { Location: e.location },
749
748
  });
750
749
  }
750
+ // so do a thrown Response and `throw error(404, "…")`: a helper the
751
+ // endpoint shares with pages (a "load the repo or 404" one, say) must
752
+ // not turn its 404 into a 500 here
753
+ if (e instanceof Response) return e;
754
+ if (isErrorResult(e)) {
755
+ const json = evt.request.headers
756
+ .get("accept")
757
+ ?.includes("application/json");
758
+ return json
759
+ ? Response.json(
760
+ { error: true, status: e.status, message: e.message },
761
+ { status: e.status },
762
+ )
763
+ : new Response(`${e.message}\n`, {
764
+ status: e.status,
765
+ headers: { "Content-Type": "text/plain; charset=utf-8" },
766
+ });
767
+ }
751
768
  throw e;
752
769
  }
753
770
  }
@@ -1110,7 +1127,7 @@ export async function createApp(
1110
1127
  };
1111
1128
 
1112
1129
  return {
1113
- fetch: fetchUnderBase,
1130
+ fetch: async (req: Request) => fetchUnderBase(req),
1114
1131
  websocket,
1115
1132
  tree,
1116
1133
  matchers: paramMatcherFns,
@@ -101,9 +101,7 @@ export async function runWorkerSpawn(
101
101
  const merged: WorkerEnv = { env: {} };
102
102
  for (const plugin of plugins) {
103
103
  const result = await plugin.onWorkerSpawn?.(worker);
104
- //@ts-expect-error WTF TS? its result? meaning its not gonna do anything if null.
105
104
  if (result?.env) Object.assign(merged.env!, result.env);
106
- //@ts-expect-error WTF TS? its result? meaning its not gonna do anything if null.
107
105
  if (result?.name) merged.name = result.name;
108
106
  }
109
107
  return merged;
@@ -161,7 +161,7 @@ export function context(options: ContextOptions = {}) {
161
161
  request,
162
162
  url,
163
163
  params: options.params ?? {},
164
- locals: (options.locals ?? {}) as App.Locals,
164
+ locals: (options.locals ?? {}) as unknown as App.Locals,
165
165
  cookies,
166
166
  fetch: options.fetch ?? globalThis.fetch,
167
167
  parent: async () => options.parent ?? {},
@@ -0,0 +1,14 @@
1
+ /**
2
+ * Preloaded by `sigil test` for `*.server.test.ts` files.
3
+ *
4
+ * Bun compiles a test file's static imports before any of its code runs, so
5
+ * server code a test imports directly (a module that renders a mail
6
+ * template, say) would be compiled before `createTestApp()` sets up Sigil's
7
+ * compiler, and its `.tsx` would get React's JSX. Registering the compiler
8
+ * here, first, means it compiles the same as when the app loads it. The app
9
+ * adds its plugins and aliases when it starts.
10
+ */
11
+ import { registerSSRPlugin } from "../rendering/ssrPlugin";
12
+ import { projectAliases } from "../server/resolver";
13
+
14
+ registerSSRPlugin([], projectAliases({}));