@sigil-dev/grimoire 0.9.29 → 0.9.30

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 (105) hide show
  1. package/bin/sigil.ts +4 -0
  2. package/index.ts +16 -10
  3. package/package.json +14 -6
  4. package/server.ts +2 -2
  5. package/src/adapters/bun.ts +17 -17
  6. package/src/adapters/static.ts +41 -41
  7. package/src/adapters/types.ts +36 -36
  8. package/src/base.ts +4 -1
  9. package/src/client/csrf.ts +47 -47
  10. package/src/client/deferred.ts +1 -4
  11. package/src/client/enhance.ts +160 -160
  12. package/src/client/router.ts +927 -926
  13. package/src/config-file.ts +84 -0
  14. package/src/dev/compile-module.ts +199 -193
  15. package/src/dev/hmr-client.ts +229 -229
  16. package/src/dev/hmr-server.ts +274 -266
  17. package/src/dev/loader.ts +144 -144
  18. package/src/dev/runtime-bundle.ts +5 -3
  19. package/src/duration.ts +46 -0
  20. package/src/env/modules.ts +62 -62
  21. package/src/env/required.ts +42 -42
  22. package/src/env/typegen.ts +61 -61
  23. package/src/headers.ts +105 -105
  24. package/src/logger/transports.ts +117 -117
  25. package/src/plugin-order.ts +88 -0
  26. package/src/rendering/head.ts +49 -49
  27. package/src/rendering/hydrate.ts +162 -162
  28. package/src/rendering/images.ts +43 -43
  29. package/src/rendering/preload.ts +22 -8
  30. package/src/rendering/ssrPlugin.ts +107 -107
  31. package/src/rendering/timing.ts +40 -40
  32. package/src/routing/route-ids.ts +65 -0
  33. package/src/routing/route.ts +65 -0
  34. package/src/routing/router.ts +84 -32
  35. package/src/routing/scanner.ts +18 -5
  36. package/src/routing/transform-routes.ts +102 -102
  37. package/src/server/after-response.ts +206 -206
  38. package/src/server/asset-cache.ts +57 -57
  39. package/src/server/build.ts +304 -295
  40. package/src/server/cached.ts +114 -114
  41. package/src/server/client-address.ts +82 -82
  42. package/src/server/client-dir.ts +63 -63
  43. package/src/server/client-entry.ts +44 -44
  44. package/src/server/context.ts +18 -10
  45. package/src/server/cookie-utils.ts +80 -80
  46. package/src/server/coordinator.ts +476 -476
  47. package/src/server/hooks.ts +122 -122
  48. package/src/server/index.ts +8 -0
  49. package/src/server/plugins.ts +172 -172
  50. package/src/server/prerender.ts +473 -473
  51. package/src/server/reserved.ts +17 -17
  52. package/src/server/resolver.ts +149 -123
  53. package/src/server/rewrite.ts +28 -28
  54. package/src/server/warm.ts +9 -3
  55. package/src/server/with-headers.ts +27 -27
  56. package/src/server/worker.ts +2 -6
  57. package/src/server-only.ts +78 -0
  58. package/src/testing/dom.ts +73 -73
  59. package/src/testing/index.ts +169 -169
  60. package/src/testing/server.ts +1 -0
  61. package/src/typegen/index.ts +97 -2
  62. package/src/types.ts +140 -19
  63. package/test/after-response.test.ts +132 -132
  64. package/test/asset-cache-policy.test.ts +6 -2
  65. package/test/base.test.ts +20 -6
  66. package/test/cached.test.ts +126 -126
  67. package/test/client-address.test.ts +78 -78
  68. package/test/client-csrf.test.ts +61 -61
  69. package/test/client-dir.test.ts +101 -101
  70. package/test/client-router.test.ts +37 -5
  71. package/test/config-file.test.ts +84 -0
  72. package/test/coordinator.test.ts +9 -2
  73. package/test/deferred.test.ts +4 -2
  74. package/test/dev-loader.test.ts +30 -30
  75. package/test/env.test.ts +171 -171
  76. package/test/force-production.test.ts +7 -2
  77. package/test/images.test.ts +20 -8
  78. package/test/locals-header.test.ts +61 -61
  79. package/test/middleware.test.ts +243 -243
  80. package/test/parser-plugins.test.ts +98 -92
  81. package/test/plugin-handle.test.ts +62 -62
  82. package/test/plugin-order.test.ts +98 -0
  83. package/test/plugin-routes.test.ts +47 -42
  84. package/test/plugin-services-context.test.ts +7 -2
  85. package/test/preload.test.ts +4 -1
  86. package/test/prerender.test.ts +3 -1
  87. package/test/rendering.test.ts +3 -2
  88. package/test/required-env.test.ts +32 -32
  89. package/test/resolver-windows.test.ts +22 -23
  90. package/test/rewrite-html.test.ts +90 -90
  91. package/test/route-group-layouts.test.ts +38 -36
  92. package/test/route.test.ts +103 -0
  93. package/test/routing.test.ts +225 -197
  94. package/test/scanning.test.ts +53 -33
  95. package/test/server-context.test.ts +22 -0
  96. package/test/server-only.test.ts +110 -0
  97. package/test/server.test.ts +640 -640
  98. package/test/services.test.ts +3 -3
  99. package/test/streaming.test.ts +11 -6
  100. package/test/testing-helpers.test.ts +166 -166
  101. package/test/typegen.test.ts +209 -112
  102. package/test/warm.test.ts +96 -96
  103. package/test/worker-context.test.ts +59 -59
  104. package/test/workspace-files.test.ts +26 -10
  105. package/test/workspace-versions.test.ts +146 -131
@@ -1,23 +1,22 @@
1
- import { expect, test } from "bun:test";
2
- import { mkdirSync, mkdtempSync, writeFileSync } from "node:fs";
3
- import { tmpdir } from "node:os";
4
- import { join } from "node:path";
5
- import { rewriteAliases } from "../src/server/resolver";
6
-
7
- // On Windows the resolved file is D:\Projects\app\src\lib\x.ts. Written into a
8
- // string literal as is, every backslash is an escape and the import becomes
9
- // "D:Projectsappsrclibx.ts". The specifier must use forward slashes.
10
- test("aliased imports are written with forward slashes", () => {
11
- const root = mkdtempSync(join(tmpdir(), "grimoire-alias-"));
12
- mkdirSync(join(root, "src/lib/server"), { recursive: true });
13
- writeFileSync(join(root, "src/lib/server/auth.ts"), "export const auth = 1;");
14
-
15
- const out = rewriteAliases(
16
- 'import { auth } from "$lib/server/auth";',
17
- { $lib: join(root, "src/lib") },
18
- );
19
-
20
- const specifier = out.match(/from "([^"]+)"/)?.[1] ?? "";
21
- expect(specifier).not.toContain("\\");
22
- expect(specifier.endsWith("/src/lib/server/auth.ts")).toBe(true);
23
- });
1
+ import { expect, test } from "bun:test";
2
+ import { mkdirSync, mkdtempSync, writeFileSync } from "node:fs";
3
+ import { tmpdir } from "node:os";
4
+ import { join } from "node:path";
5
+ import { rewriteAliases } from "../src/server/resolver";
6
+
7
+ // On Windows the resolved file is D:\Projects\app\src\lib\x.ts. Written into a
8
+ // string literal as is, every backslash is an escape and the import becomes
9
+ // "D:Projectsappsrclibx.ts". The specifier must use forward slashes.
10
+ test("aliased imports are written with forward slashes", () => {
11
+ const root = mkdtempSync(join(tmpdir(), "grimoire-alias-"));
12
+ mkdirSync(join(root, "src/lib/server"), { recursive: true });
13
+ writeFileSync(join(root, "src/lib/server/auth.ts"), "export const auth = 1;");
14
+
15
+ const out = rewriteAliases('import { auth } from "$lib/server/auth";', {
16
+ $lib: join(root, "src/lib"),
17
+ });
18
+
19
+ const specifier = out.match(/from "([^"]+)"/)?.[1] ?? "";
20
+ expect(specifier).not.toContain("\\");
21
+ expect(specifier.endsWith("/src/lib/server/auth.ts")).toBe(true);
22
+ });
@@ -1,90 +1,90 @@
1
- import { describe, expect, test } from "bun:test";
2
- import { applyRewriters } from "../src/server/rewrite";
3
- import type { GrimoirePlugin, RenderContext } from "../src/types";
4
-
5
- const ctx = {
6
- route: { path: "/", filePath: "/x", type: "page" },
7
- request: new Request("http://localhost/"),
8
- params: {},
9
- data: undefined,
10
- } as RenderContext;
11
-
12
- const enc = new TextEncoder();
13
-
14
- /** A page that sends its shell, waits, then sends the rest: the shape of a streamed route. */
15
- function streamedPage(delayMs: number): Response {
16
- return new Response(
17
- new ReadableStream({
18
- async start(c) {
19
- c.enqueue(
20
- enc.encode("<html><head><title>x</title></head><body><p>shell</p>"),
21
- );
22
- await Bun.sleep(delayMs);
23
- c.enqueue(enc.encode("<p>late</p></body></html>"));
24
- c.close();
25
- },
26
- }),
27
- { status: 200, headers: { "content-type": "text/html", "x-keep": "1" } },
28
- );
29
- }
30
-
31
- const injectMeta: GrimoirePlugin = {
32
- name: "inject",
33
- rewriteHtml(rewriter) {
34
- rewriter.on("head", {
35
- element: (el) => el.append('<meta name="added">', { html: true }),
36
- });
37
- },
38
- };
39
-
40
- describe("rewriteHtml", () => {
41
- test("rewrites the shell before the rest of the response exists", async () => {
42
- const res = await applyRewriters(streamedPage(300), [injectMeta], ctx);
43
- const reader = res.body!.getReader();
44
- const t0 = performance.now();
45
- const first = await reader.read();
46
- const firstAt = performance.now() - t0;
47
- expect(new TextDecoder().decode(first.value)).toContain(
48
- '<meta name="added">',
49
- );
50
- // the late chunk is 300ms away: a buffered rewrite could not have answered yet
51
- expect(firstAt).toBeLessThan(200);
52
- const rest = await reader.read();
53
- expect(new TextDecoder().decode(rest.value)).toContain("late");
54
- });
55
-
56
- test("several plugins compose on one pass, in plugin order", async () => {
57
- const second: GrimoirePlugin = {
58
- name: "second",
59
- rewriteHtml(rewriter) {
60
- rewriter.on("head", {
61
- element: (el) => el.append("<!--two-->", { html: true }),
62
- });
63
- },
64
- };
65
- const html = await (
66
- await applyRewriters(streamedPage(0), [injectMeta, second], ctx)
67
- ).text();
68
- expect(html.indexOf('name="added"')).toBeLessThan(
69
- html.indexOf("<!--two-->"),
70
- );
71
- });
72
-
73
- test("keeps status and headers", async () => {
74
- const res = await applyRewriters(streamedPage(0), [injectMeta], ctx);
75
- expect(res.status).toBe(200);
76
- expect(res.headers.get("x-keep")).toBe("1");
77
- });
78
-
79
- test("leaves non-HTML, empty and plugin-less responses alone", async () => {
80
- const json = Response.json({ a: 1 });
81
- expect(await applyRewriters(json, [injectMeta], ctx)).toBe(json);
82
- const redirect = new Response(null, {
83
- status: 303,
84
- headers: { location: "/" },
85
- });
86
- expect(await applyRewriters(redirect, [injectMeta], ctx)).toBe(redirect);
87
- const page = streamedPage(0);
88
- expect(await applyRewriters(page, [{ name: "none" }], ctx)).toBe(page);
89
- });
90
- });
1
+ import { describe, expect, test } from "bun:test";
2
+ import { applyRewriters } from "../src/server/rewrite";
3
+ import type { GrimoirePlugin, RenderContext } from "../src/types";
4
+
5
+ const ctx = {
6
+ route: { path: "/", filePath: "/x", type: "page" },
7
+ request: new Request("http://localhost/"),
8
+ params: {},
9
+ data: undefined,
10
+ } as RenderContext;
11
+
12
+ const enc = new TextEncoder();
13
+
14
+ /** A page that sends its shell, waits, then sends the rest: the shape of a streamed route. */
15
+ function streamedPage(delayMs: number): Response {
16
+ return new Response(
17
+ new ReadableStream({
18
+ async start(c) {
19
+ c.enqueue(
20
+ enc.encode("<html><head><title>x</title></head><body><p>shell</p>"),
21
+ );
22
+ await Bun.sleep(delayMs);
23
+ c.enqueue(enc.encode("<p>late</p></body></html>"));
24
+ c.close();
25
+ },
26
+ }),
27
+ { status: 200, headers: { "content-type": "text/html", "x-keep": "1" } },
28
+ );
29
+ }
30
+
31
+ const injectMeta: GrimoirePlugin = {
32
+ name: "inject",
33
+ rewriteHtml(rewriter) {
34
+ rewriter.on("head", {
35
+ element: (el) => el.append('<meta name="added">', { html: true }),
36
+ });
37
+ },
38
+ };
39
+
40
+ describe("rewriteHtml", () => {
41
+ test("rewrites the shell before the rest of the response exists", async () => {
42
+ const res = await applyRewriters(streamedPage(300), [injectMeta], ctx);
43
+ const reader = res.body!.getReader();
44
+ const t0 = performance.now();
45
+ const first = await reader.read();
46
+ const firstAt = performance.now() - t0;
47
+ expect(new TextDecoder().decode(first.value)).toContain(
48
+ '<meta name="added">',
49
+ );
50
+ // the late chunk is 300ms away: a buffered rewrite could not have answered yet
51
+ expect(firstAt).toBeLessThan(200);
52
+ const rest = await reader.read();
53
+ expect(new TextDecoder().decode(rest.value)).toContain("late");
54
+ });
55
+
56
+ test("several plugins compose on one pass, in plugin order", async () => {
57
+ const second: GrimoirePlugin = {
58
+ name: "second",
59
+ rewriteHtml(rewriter) {
60
+ rewriter.on("head", {
61
+ element: (el) => el.append("<!--two-->", { html: true }),
62
+ });
63
+ },
64
+ };
65
+ const html = await (
66
+ await applyRewriters(streamedPage(0), [injectMeta, second], ctx)
67
+ ).text();
68
+ expect(html.indexOf('name="added"')).toBeLessThan(
69
+ html.indexOf("<!--two-->"),
70
+ );
71
+ });
72
+
73
+ test("keeps status and headers", async () => {
74
+ const res = await applyRewriters(streamedPage(0), [injectMeta], ctx);
75
+ expect(res.status).toBe(200);
76
+ expect(res.headers.get("x-keep")).toBe("1");
77
+ });
78
+
79
+ test("leaves non-HTML, empty and plugin-less responses alone", async () => {
80
+ const json = Response.json({ a: 1 });
81
+ expect(await applyRewriters(json, [injectMeta], ctx)).toBe(json);
82
+ const redirect = new Response(null, {
83
+ status: 303,
84
+ headers: { location: "/" },
85
+ });
86
+ expect(await applyRewriters(redirect, [injectMeta], ctx)).toBe(redirect);
87
+ const page = streamedPage(0);
88
+ expect(await applyRewriters(page, [{ name: "none" }], ctx)).toBe(page);
89
+ });
90
+ });
@@ -1,36 +1,38 @@
1
- import { expect, test } from "bun:test";
2
- import { mkdirSync, mkdtempSync, writeFileSync } from "node:fs";
3
- import { tmpdir } from "node:os";
4
- import { join } from "node:path";
5
- import { matchRoute } from "../src/routing/router";
6
- import { scanRoutes } from "../src/routing/scanner";
7
-
8
- // (app)/+layout.tsx has the URL "/" once the group is stripped. Matched by URL
9
- // it wrapped every page, login included; a layout covers its folder on disk.
10
- test("a layout inside a route group wraps only that group", async () => {
11
- const root = mkdtempSync(join(tmpdir(), "grimoire-groups-"));
12
- const routes = join(root, "src/routes");
13
- for (const f of [
14
- "+layout.tsx",
15
- "(app)/+layout.tsx",
16
- "(app)/plan/+page.tsx",
17
- "(app)/+page.tsx",
18
- "login/+page.tsx",
19
- ]) {
20
- mkdirSync(join(routes, f, ".."), { recursive: true });
21
- writeFileSync(join(routes, f), "export default () => null;");
22
- }
23
- const tree = await scanRoutes(routes, root);
24
- const layoutsFor = (path: string) =>
25
- matchRoute(tree, new URL(path, "http://x"))!.layouts.map((l) => l.clientPath);
26
-
27
- expect(layoutsFor("/plan")).toEqual([
28
- "/src/routes/+layout.tsx",
29
- "/src/routes/(app)/+layout.tsx",
30
- ]);
31
- expect(layoutsFor("/")).toEqual([
32
- "/src/routes/+layout.tsx",
33
- "/src/routes/(app)/+layout.tsx",
34
- ]);
35
- expect(layoutsFor("/login")).toEqual(["/src/routes/+layout.tsx"]);
36
- });
1
+ import { expect, test } from "bun:test";
2
+ import { mkdirSync, mkdtempSync, writeFileSync } from "node:fs";
3
+ import { tmpdir } from "node:os";
4
+ import { join } from "node:path";
5
+ import { matchRoute } from "../src/routing/router";
6
+ import { scanRoutes } from "../src/routing/scanner";
7
+
8
+ // (app)/+layout.tsx has the URL "/" once the group is stripped. Matched by URL
9
+ // it wrapped every page, login included; a layout covers its folder on disk.
10
+ test("a layout inside a route group wraps only that group", async () => {
11
+ const root = mkdtempSync(join(tmpdir(), "grimoire-groups-"));
12
+ const routes = join(root, "src/routes");
13
+ for (const f of [
14
+ "+layout.tsx",
15
+ "(app)/+layout.tsx",
16
+ "(app)/plan/+page.tsx",
17
+ "(app)/+page.tsx",
18
+ "login/+page.tsx",
19
+ ]) {
20
+ mkdirSync(join(routes, f, ".."), { recursive: true });
21
+ writeFileSync(join(routes, f), "export default () => null;");
22
+ }
23
+ const tree = await scanRoutes(routes, root);
24
+ const layoutsFor = (path: string) =>
25
+ matchRoute(tree, new URL(path, "http://x"))!.layouts.map(
26
+ (l) => l.clientPath,
27
+ );
28
+
29
+ expect(layoutsFor("/plan")).toEqual([
30
+ "/src/routes/+layout.tsx",
31
+ "/src/routes/(app)/+layout.tsx",
32
+ ]);
33
+ expect(layoutsFor("/")).toEqual([
34
+ "/src/routes/+layout.tsx",
35
+ "/src/routes/(app)/+layout.tsx",
36
+ ]);
37
+ expect(layoutsFor("/login")).toEqual(["/src/routes/+layout.tsx"]);
38
+ });
@@ -0,0 +1,103 @@
1
+ import { afterEach, describe, expect, test } from "bun:test";
2
+ import { setBase } from "../src/base";
3
+ import { route } from "../src/routing/route";
4
+ import { generateRouteTypes, routeId } from "../src/routing/route-ids";
5
+ import type { RouteFile } from "../src/routing/scanner";
6
+
7
+ afterEach(() => setBase(""));
8
+
9
+ describe("route()", () => {
10
+ test("fills params, encoded", () => {
11
+ expect(route("/")).toBe("/");
12
+ expect(route("/blog/[slug]", { slug: "hello world" })).toBe(
13
+ "/blog/hello%20world",
14
+ );
15
+ expect(route("/post/[id=int]", { id: "7" })).toBe("/post/7");
16
+ });
17
+
18
+ test("an optional param left out drops its segment", () => {
19
+ expect(route("/[[lang]]/about", {})).toBe("/about");
20
+ expect(route("/[[lang]]/about", { lang: "sr" })).toBe("/sr/about");
21
+ });
22
+
23
+ test("a rest param takes segments or a path", () => {
24
+ expect(route("/docs/[...rest]", { rest: ["guide", "a b"] })).toBe(
25
+ "/docs/guide/a%20b",
26
+ );
27
+ expect(route("/docs/[...rest]", { rest: "guide/install" })).toBe(
28
+ "/docs/guide/install",
29
+ );
30
+ expect(route("/docs/[...rest]", {})).toBe("/docs");
31
+ });
32
+
33
+ test("a missing required param is an error, not /blog/undefined", () => {
34
+ expect(() => route("/blog/[slug]", {})).toThrow(/"slug" is missing/);
35
+ });
36
+
37
+ test("the base goes in front", () => {
38
+ setBase("/repo");
39
+ expect(route("/blog/[slug]", { slug: "a" })).toBe("/repo/blog/a");
40
+ });
41
+ });
42
+
43
+ describe("route ids and types", () => {
44
+ const file = (path: string, extra: Partial<RouteFile> = {}): RouteFile => ({
45
+ path,
46
+ filePath: "",
47
+ clientPath: "",
48
+ type: "page",
49
+ paramNames: [],
50
+ optionalParamNames: [],
51
+ restParamNames: [],
52
+ paramMatchers: {},
53
+ ...extra,
54
+ });
55
+
56
+ test("ids read like the folders", () => {
57
+ expect(routeId(file("/"))).toBe("/");
58
+ expect(routeId(file("/blog/:slug", { paramNames: ["slug"] }))).toBe(
59
+ "/blog/[slug]",
60
+ );
61
+ expect(
62
+ routeId(file("/:lang?/about", { optionalParamNames: ["lang"] })),
63
+ ).toBe("/[[lang]]/about");
64
+ expect(routeId(file("/docs/*rest", { restParamNames: ["rest"] }))).toBe(
65
+ "/docs/[...rest]",
66
+ );
67
+ expect(
68
+ routeId(
69
+ file("/post/:id", { paramNames: ["id"], paramMatchers: { id: "int" } }),
70
+ ),
71
+ ).toBe("/post/[id=int]");
72
+ });
73
+
74
+ test("routes.d.ts lists pages and endpoints with their params", () => {
75
+ const out = generateRouteTypes({
76
+ routes: [
77
+ file("/blog/:slug", { paramNames: ["slug"] }),
78
+ file("/blog/:slug", { type: "pageServer", paramNames: ["slug"] }),
79
+ ],
80
+ servers: [file("/api/feed", { type: "server" })],
81
+ layouts: [],
82
+ errors: [],
83
+ paramMatcherFiles: [],
84
+ });
85
+ expect(out).toContain('"/blog/[slug]": { slug: string };');
86
+ expect(out).toContain('"/api/feed": {};');
87
+ expect(out.match(/\/blog\/\[slug\]/g)).toHaveLength(1);
88
+ });
89
+ });
90
+
91
+ describe("ids from the scanner", () => {
92
+ test("keep the folder's own spelling", async () => {
93
+ const { filePathToRoutePath } = await import("../src/routing/scanner");
94
+ const id = (p: string) =>
95
+ filePathToRoutePath(`/app/src/routes/${p}`, "/app/src/routes").id;
96
+ expect(id("+page.tsx")).toBe("/");
97
+ expect(id("docs/[[...slug]]/+page.tsx")).toBe("/docs/[[...slug]]");
98
+ expect(id("(marketing)/pricing/+page.tsx")).toBe("/pricing");
99
+ expect(id("post/[id=int]/+page.tsx")).toBe("/post/[id=int]");
100
+ expect(id("about.tsx")).toBe("/about");
101
+ expect(id("blog/index.tsx")).toBe("/blog");
102
+ });
103
+ });