@sigil-dev/grimoire 0.9.21 → 0.9.23

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 (94) hide show
  1. package/README.md +83 -83
  2. package/index.ts +50 -48
  3. package/package.json +22 -10
  4. package/public/__grimoire__/grimoire-client.js +12 -0
  5. package/public/__grimoire__/runtime.js +1241 -0
  6. package/server.ts +22 -20
  7. package/src/adapters/bun.ts +17 -0
  8. package/src/adapters/static.ts +41 -0
  9. package/src/adapters/types.ts +36 -0
  10. package/src/base.ts +91 -0
  11. package/src/client/csrf.ts +47 -47
  12. package/src/client/deferred.ts +179 -179
  13. package/src/client/enhance.ts +160 -160
  14. package/src/client/router.ts +871 -833
  15. package/src/dev/compile-module.ts +211 -211
  16. package/src/dev/loader.ts +141 -141
  17. package/src/dev/resolve.ts +70 -70
  18. package/src/dev/runtime-bundle.ts +51 -51
  19. package/src/env/modules.ts +62 -62
  20. package/src/env/required.ts +42 -0
  21. package/src/env/typegen.ts +61 -61
  22. package/src/headers.ts +105 -105
  23. package/src/logger/transports.ts +117 -117
  24. package/src/rendering/head.ts +49 -49
  25. package/src/rendering/hydrate.ts +161 -161
  26. package/src/rendering/images.ts +43 -43
  27. package/src/rendering/index.ts +755 -749
  28. package/src/rendering/preload.ts +102 -101
  29. package/src/rendering/ssrPlugin.ts +1 -1
  30. package/src/rendering/timing.ts +40 -40
  31. package/src/routing/router.ts +186 -186
  32. package/src/routing/scanner.ts +225 -196
  33. package/src/routing/transform-routes.ts +102 -102
  34. package/src/server/after-response.ts +206 -206
  35. package/src/server/asset-cache.ts +57 -57
  36. package/src/server/build.ts +262 -262
  37. package/src/server/cached.ts +114 -114
  38. package/src/server/client-address.ts +82 -82
  39. package/src/server/client-dir.ts +57 -57
  40. package/src/server/client-entry.ts +44 -44
  41. package/src/server/cookie-utils.ts +80 -80
  42. package/src/server/coordinator.ts +476 -471
  43. package/src/server/hooks.ts +122 -122
  44. package/src/server/index.ts +211 -80
  45. package/src/server/plugins.ts +172 -172
  46. package/src/server/prerender.ts +444 -0
  47. package/src/server/reserved.ts +17 -0
  48. package/src/server/resolver.ts +98 -98
  49. package/src/server/rewrite.ts +28 -0
  50. package/src/server/warm.ts +91 -91
  51. package/src/server/with-headers.ts +27 -27
  52. package/src/server/worker.ts +74 -72
  53. package/src/testing/dom.ts +73 -0
  54. package/src/testing/index.ts +169 -0
  55. package/src/testing/server.ts +162 -0
  56. package/src/typegen/index.ts +450 -450
  57. package/src/types.ts +501 -432
  58. package/test/after-response.test.ts +132 -132
  59. package/test/asset-cache-policy.test.ts +96 -96
  60. package/test/base.test.ts +134 -0
  61. package/test/cached.test.ts +126 -126
  62. package/test/client-address.test.ts +78 -78
  63. package/test/client-csrf.test.ts +61 -61
  64. package/test/client-dir.test.ts +101 -101
  65. package/test/client-router.test.ts +789 -734
  66. package/test/coordinator.test.ts +96 -94
  67. package/test/deferred.test.ts +256 -256
  68. package/test/dev-loader.test.ts +30 -30
  69. package/test/env.test.ts +168 -168
  70. package/test/force-production.test.ts +44 -0
  71. package/test/images.test.ts +49 -49
  72. package/test/locals-header.test.ts +61 -0
  73. package/test/middleware.test.ts +243 -243
  74. package/test/parser-plugins.test.ts +1 -1
  75. package/test/plugin-handle.test.ts +62 -62
  76. package/test/plugin-services-context.test.ts +97 -97
  77. package/test/preload.test.ts +48 -48
  78. package/test/prerender.test.ts +353 -0
  79. package/test/rendering.test.ts +799 -798
  80. package/test/required-env.test.ts +32 -0
  81. package/test/rewrite-html.test.ts +90 -0
  82. package/test/scanning.test.ts +349 -314
  83. package/test/server.test.ts +640 -619
  84. package/test/services.test.ts +90 -90
  85. package/test/streaming.test.ts +381 -378
  86. package/test/testing-helpers.test.ts +166 -0
  87. package/test/typegen.test.ts +808 -799
  88. package/test/warm.test.ts +96 -96
  89. package/test/worker-context.test.ts +59 -59
  90. package/test/workspace-files.test.ts +149 -146
  91. package/test/workspace-versions.test.ts +1 -1
  92. package/.grimoire/_routes.ts +0 -4
  93. package/public/__grimoire__/client.js +0 -55
  94. package/public/__grimoire__/hydrate.js +0 -63
package/server.ts CHANGED
@@ -1,20 +1,22 @@
1
- export { afterResponse } from "./src/server/after-response.ts";
2
- export { log } from "./src/logger/instance.ts";
3
- export { scanRoutes } from "./src/routing/scanner";
4
- export { createServer } from "./src/server";
5
- export { buildProject } from "./src/server/build";
6
- export { parseCookies } from "./src/server/cookie-utils";
7
- export { startCoordinator } from "./src/server/coordinator.ts";
8
- export {
9
- createWaiter,
10
- listenForKeys,
11
- stopListening,
12
- } from "./src/server/interactive.ts";
13
- export {
14
- runDeserializeLocals,
15
- runRouteRequest,
16
- runSerializeLocals,
17
- runWorkerSpawn,
18
- } from "./src/server/plugins";
19
- export type { TypegenConfig } from "./src/typegen";
20
- export { generateTypes } from "./src/typegen";
1
+ export { afterResponse } from "./src/server/after-response.ts";
2
+ export { log } from "./src/logger/instance.ts";
3
+ export { scanRoutes } from "./src/routing/scanner";
4
+ export type { GrimoireApp } from "./src/server";
5
+ export { createApp, createServer } from "./src/server";
6
+ export { projectAliases } from "./src/server/resolver";
7
+ export { buildProject } from "./src/server/build";
8
+ export { parseCookies } from "./src/server/cookie-utils";
9
+ export { startCoordinator } from "./src/server/coordinator.ts";
10
+ export {
11
+ createWaiter,
12
+ listenForKeys,
13
+ stopListening,
14
+ } from "./src/server/interactive.ts";
15
+ export {
16
+ runDeserializeLocals,
17
+ runRouteRequest,
18
+ runSerializeLocals,
19
+ runWorkerSpawn,
20
+ } from "./src/server/plugins";
21
+ export type { TypegenConfig } from "./src/typegen";
22
+ export { generateTypes } from "./src/typegen";
@@ -0,0 +1,17 @@
1
+ import type { Adapter } from "./types";
2
+
3
+ /**
4
+ * The default target, spelled out: a Bun server (`sigil start`, optionally
5
+ * behind the coordinator). It has no build step of its own, so this exists
6
+ * for a config to say what it means rather than to do anything.
7
+ *
8
+ * Not portable to Node today. The request path itself uses Bun APIs —
9
+ * `Bun.serve` and `ServerWebSocket`, `Bun.Glob` in the route scanner, the
10
+ * Bun plugin that compiles route modules for SSR, `Bun.file` for assets — so
11
+ * a Node adapter would be a port of those, not a packaging step.
12
+ */
13
+ export function adapterBun(): Adapter {
14
+ return { name: "bun" };
15
+ }
16
+
17
+ export default adapterBun;
@@ -0,0 +1,41 @@
1
+ import { type PrerenderOptions, prerenderSite } from "../server/prerender";
2
+ import type { Adapter } from "./types";
3
+
4
+ export type AdapterStaticOptions = Partial<PrerenderOptions>;
5
+
6
+ /**
7
+ * Build the site to plain files: HTML for every page, the client bundles, and
8
+ * everything from `public/`. Serve the output from any static host, no server.
9
+ *
10
+ * ```ts
11
+ * import { defineConfig } from "@sigil-dev/grimoire";
12
+ * import { adapterStatic } from "@sigil-dev/grimoire/adapters/static";
13
+ *
14
+ * export default defineConfig({ adapter: adapterStatic({ out: "build" }) });
15
+ * ```
16
+ *
17
+ * Pages are found from routes that need no params, from `export const entries
18
+ * = () => [{ slug: "a" }]` on routes that do, and by following links from
19
+ * those pages. `export const prerender = false` on a route, a form action, or
20
+ * a `+server.ts` endpoint cannot exist without a server, so the build fails
21
+ * naming each one rather than shipping a site with holes.
22
+ *
23
+ * Client-side navigation stays instant: each page gets a `__data.json` beside
24
+ * it, which the router reads in place of asking a server.
25
+ *
26
+ * A site served under a path (`config.base = "/repo"`) is built the same way:
27
+ * pages are requested and linked with the base, and the files are written
28
+ * without it, so the output directory is what the host serves at that path.
29
+ */
30
+ export function adapterStatic(options: AdapterStaticOptions = {}): Adapter {
31
+ return {
32
+ name: "static",
33
+ async adapt(ctx) {
34
+ const out = options.out ?? "build";
35
+ const report = await prerenderSite(ctx, { ...options, out });
36
+ ctx.log.info(`prerendered ${report.pages.length} page(s) to ${out}/`);
37
+ },
38
+ };
39
+ }
40
+
41
+ export default adapterStatic;
@@ -0,0 +1,36 @@
1
+ import type { GrimoireApp } from "../server/index";
2
+ import type { GrimoireConfig, GrimoirePlugin } from "../types";
3
+
4
+ /**
5
+ * What a deployment target does with a finished build.
6
+ *
7
+ * Without an adapter, `sigil build` leaves the bundles under `public/` and
8
+ * `sigil start` serves them from the Bun server — that is the default and
9
+ * needs nothing. An adapter adds a step after the build: `adapterStatic`
10
+ * prerenders the site to plain files.
11
+ *
12
+ * Deliberately one field on the config rather than a plugin hook. A project
13
+ * has one deployment target, and `onBuildEnd` is handed neither the route
14
+ * tree nor a way to render a page, which is what an adapter needs.
15
+ */
16
+ export interface Adapter {
17
+ name: string;
18
+ /**
19
+ * Runs after the client bundles are built, with the real request pipeline
20
+ * available as `app.fetch`. Throw to fail the build.
21
+ */
22
+ adapt?(ctx: AdapterContext): void | Promise<void>;
23
+ }
24
+
25
+ export interface AdapterContext {
26
+ /** The app as it would run in production, but not listening on a port. */
27
+ app: GrimoireApp;
28
+ config: GrimoireConfig;
29
+ plugins: GrimoirePlugin[];
30
+ /** Project root. */
31
+ root: string;
32
+ log: {
33
+ info(msg: string): void;
34
+ warn(msg: string): void;
35
+ };
36
+ }
package/src/base.ts ADDED
@@ -0,0 +1,91 @@
1
+ /**
2
+ * The path the app is served under: `/repo` for a site at
3
+ * `https://user.github.io/repo/`, `""` at the root.
4
+ *
5
+ * Inside the app a URL has two forms. A *route path* (`/about`) is what routes,
6
+ * loads (`url.pathname`) and `matchRoute` see; the server strips the base from
7
+ * every request before anything else looks at it. A *full path*
8
+ * (`/repo/about`) is what the browser, `<a href>`, `fetch`, `redirect()` and
9
+ * `navigate()` use, and `withBase` turns the first into the second.
10
+ *
11
+ * Nothing prefixes a URL for you, and `withBase` is not idempotent on
12
+ * purpose: "already starts with the base" cannot be told apart from a route
13
+ * whose first segment happens to equal it.
14
+ */
15
+
16
+ /** The configured base: `""` or `/segment[/segment]`, never a trailing slash. */
17
+ export let base = "";
18
+
19
+ // In the browser the server says what the base is in a <meta> tag, so the same
20
+ // bundle works under any base and needs no build-time constant.
21
+ if (typeof document !== "undefined") {
22
+ const meta = document.querySelector('meta[name="grimoire-base"]');
23
+ base = meta?.getAttribute("content") ?? "";
24
+ }
25
+
26
+ export function setBase(value: string): void {
27
+ base = value;
28
+ }
29
+
30
+ /**
31
+ * Check a configured base and return its canonical form. Throws on the
32
+ * mistakes that otherwise surface as a site whose every asset 404s.
33
+ */
34
+ export function normalizeBase(raw: string | undefined): string {
35
+ if (raw === undefined || raw === "" || raw === "/") return "";
36
+ if (/^[a-z][a-z0-9+.-]*:\/\/|^\/\//i.test(raw)) {
37
+ throw new Error(
38
+ `config.base is "${raw}", a full URL. It is the path the site is served under, like "/repo": the host belongs to your deployment, not here.`,
39
+ );
40
+ }
41
+ if (!raw.startsWith("/")) {
42
+ throw new Error(
43
+ `config.base is "${raw}" and must start with a slash: "/${raw}".`,
44
+ );
45
+ }
46
+ if (raw.endsWith("/")) {
47
+ throw new Error(
48
+ `config.base is "${raw}" and must not end with a slash: "${raw.replace(/\/+$/, "")}".`,
49
+ );
50
+ }
51
+ if (/[?#\s"'<>&\\]/.test(raw)) {
52
+ throw new Error(
53
+ `config.base is "${raw}"; it must be a plain path with no query, hash, spaces or quotes.`,
54
+ );
55
+ }
56
+ return raw;
57
+ }
58
+
59
+ /** `/about` → `/repo/about`. Anything that is not a root-relative path is returned as it is. */
60
+ export function withBase(path: string, under: string = base): string {
61
+ if (!under || !path.startsWith("/") || path.startsWith("//")) return path;
62
+ return path === "/" ? `${under}/` : under + path;
63
+ }
64
+
65
+ /**
66
+ * The body of the 404 for a request outside the base. In production that is
67
+ * all it says; in dev it names the URL the visitor should have used, because
68
+ * an unprefixed link is the usual cause and works nowhere else but here.
69
+ */
70
+ export function outsideBaseMessage(
71
+ pathname: string,
72
+ under: string,
73
+ dev: boolean,
74
+ ): string {
75
+ if (!dev) return "Not found";
76
+ return (
77
+ `Not found: ${pathname}\n\nThis app is served under "${under}", so that page is at ${under}${pathname}. ` +
78
+ `Links, fetch() and redirect() take full paths: write withBase("${pathname}") from @sigil-dev/grimoire.`
79
+ );
80
+ }
81
+
82
+ /**
83
+ * The route path for a full pathname, or `null` when the pathname is outside
84
+ * the base. `/repo` and `/repo/` are both `/`.
85
+ */
86
+ export function stripBase(pathname: string, under: string = base): string | null {
87
+ if (!under) return pathname;
88
+ if (pathname === under) return "/";
89
+ if (pathname.startsWith(`${under}/`)) return pathname.slice(under.length);
90
+ return null;
91
+ }
@@ -1,47 +1,47 @@
1
- /**
2
- * CSRF for forms the browser rendered.
3
- *
4
- * The server double-submits a token: the `_csrf` cookie, plus a hidden input
5
- * it injects into every <form> in the SSR HTML (rendering/index.ts). A page
6
- * reached by client-side navigation is rendered in the browser, so its forms
7
- * never got that input and every POST from them was refused with 403.
8
- *
9
- * ensureCsrf copies the cookie's current token into a form just before it
10
- * submits. Always overwriting the value also fixes forms that did get an input
11
- * but are stale, say after the cookie expired and a new one was issued.
12
- */
13
-
14
- export const CSRF_FIELD = "_csrf";
15
-
16
- function cookieToken(): string | null {
17
- const m = /(?:^|;\s*)_csrf=([^;]+)/.exec(document.cookie);
18
- return m ? decodeURIComponent(m[1]) : null;
19
- }
20
-
21
- export function ensureCsrf(form: HTMLFormElement): void {
22
- const token = cookieToken();
23
- if (!token) return;
24
- let input = form.querySelector<HTMLInputElement>(
25
- `input[name="${CSRF_FIELD}"]`,
26
- );
27
- if (!input) {
28
- input = document.createElement("input");
29
- input.type = "hidden";
30
- input.name = CSRF_FIELD;
31
- input.setAttribute("data-grimoire-csrf", "");
32
- form.prepend(input);
33
- }
34
- input.value = token;
35
- }
36
-
37
- /**
38
- * Native (non-enhanced) POST forms: a capture listener on the document runs
39
- * before any handler on the form itself, so the token is in place for both
40
- * the browser's own submission and anything that reads FormData.
41
- */
42
- export function onSubmitEnsureCsrf(e: Event): void {
43
- const form = e.target as HTMLFormElement | null;
44
- if (form?.tagName !== "FORM") return;
45
- if ((form.getAttribute("method") ?? "get").toLowerCase() !== "post") return;
46
- ensureCsrf(form);
47
- }
1
+ /**
2
+ * CSRF for forms the browser rendered.
3
+ *
4
+ * The server double-submits a token: the `_csrf` cookie, plus a hidden input
5
+ * it injects into every <form> in the SSR HTML (rendering/index.ts). A page
6
+ * reached by client-side navigation is rendered in the browser, so its forms
7
+ * never got that input and every POST from them was refused with 403.
8
+ *
9
+ * ensureCsrf copies the cookie's current token into a form just before it
10
+ * submits. Always overwriting the value also fixes forms that did get an input
11
+ * but are stale, say after the cookie expired and a new one was issued.
12
+ */
13
+
14
+ export const CSRF_FIELD = "_csrf";
15
+
16
+ function cookieToken(): string | null {
17
+ const m = /(?:^|;\s*)_csrf=([^;]+)/.exec(document.cookie);
18
+ return m ? decodeURIComponent(m[1]) : null;
19
+ }
20
+
21
+ export function ensureCsrf(form: HTMLFormElement): void {
22
+ const token = cookieToken();
23
+ if (!token) return;
24
+ let input = form.querySelector<HTMLInputElement>(
25
+ `input[name="${CSRF_FIELD}"]`,
26
+ );
27
+ if (!input) {
28
+ input = document.createElement("input");
29
+ input.type = "hidden";
30
+ input.name = CSRF_FIELD;
31
+ input.setAttribute("data-grimoire-csrf", "");
32
+ form.prepend(input);
33
+ }
34
+ input.value = token;
35
+ }
36
+
37
+ /**
38
+ * Native (non-enhanced) POST forms: a capture listener on the document runs
39
+ * before any handler on the form itself, so the token is in place for both
40
+ * the browser's own submission and anything that reads FormData.
41
+ */
42
+ export function onSubmitEnsureCsrf(e: Event): void {
43
+ const form = e.target as HTMLFormElement | null;
44
+ if (form?.tagName !== "FORM") return;
45
+ if ((form.getAttribute("method") ?? "get").toLowerCase() !== "post") return;
46
+ ensureCsrf(form);
47
+ }