@sigil-dev/grimoire 0.9.11 → 0.9.13
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 +5 -1
- package/package.json +3 -3
- package/server.ts +1 -0
- package/src/client/deferred.ts +179 -0
- package/src/rendering/ssrPlugin.ts +16 -1
- package/src/server/after-response.ts +194 -0
- package/src/server/asset-cache.ts +51 -0
- package/src/server/coordinator.ts +26 -6
- package/src/server/index.ts +593 -468
- package/src/server/plugins.ts +35 -0
- package/src/server/worker.ts +13 -1
- package/src/types.ts +118 -1
- package/test/after-response.test.ts +113 -0
- package/test/asset-cache-policy.test.ts +83 -0
- package/test/coordinator.test.ts +9 -0
- package/test/deferred.test.ts +256 -0
- package/test/parser-plugins.test.ts +92 -0
- package/test/plugin-services-context.test.ts +97 -0
- package/test/services.test.ts +90 -0
- package/test/streaming.test.ts +56 -0
- package/test/worker-context.test.ts +59 -0
- package/test/workspace-files.test.ts +146 -0
- package/test/workspace-versions.test.ts +131 -0
- package/.grimoire/_routes.ts +0 -4
- package/public/__grimoire__/client.js +0 -55
- package/public/__grimoire__/hydrate.js +0 -63
package/src/server/plugins.ts
CHANGED
|
@@ -39,6 +39,41 @@ export async function runHook<K extends FireAndForgetHook>(
|
|
|
39
39
|
}
|
|
40
40
|
}
|
|
41
41
|
|
|
42
|
+
/**
|
|
43
|
+
* Collect `services()` from every plugin, merged in plugin order.
|
|
44
|
+
*
|
|
45
|
+
* Called once at startup and cached by the caller: the result is shared by
|
|
46
|
+
* every request. `services` is a fire-and-forget hook, so it is kept out of
|
|
47
|
+
* HookArgs on purpose — its return value is used, unlike every other entry
|
|
48
|
+
* in that map.
|
|
49
|
+
*
|
|
50
|
+
* Each plugin is handed what the plugins before it already published, so a
|
|
51
|
+
* plugin can build on a resource another one owns. The SQL plugin opening the
|
|
52
|
+
* connection and a jobs plugin writing rows through it is the case that
|
|
53
|
+
* matters: without this, every consumer opens a second pool and the worker
|
|
54
|
+
* budget is split again by whoever registered first.
|
|
55
|
+
*
|
|
56
|
+
* The context is a snapshot, so a plugin registered before the one it needs
|
|
57
|
+
* sees nothing and reports that. It does not see its own contribution, and
|
|
58
|
+
* it cannot write into the result — a plugin that wants to publish does so by
|
|
59
|
+
* returning, which is what keeps the merge order predictable.
|
|
60
|
+
*/
|
|
61
|
+
export async function collectServices(
|
|
62
|
+
plugins: GrimoirePlugin[],
|
|
63
|
+
): Promise<Record<string, unknown>> {
|
|
64
|
+
const collected: Record<string, unknown> = {};
|
|
65
|
+
for (const plugin of plugins) {
|
|
66
|
+
if (!plugin.services) continue;
|
|
67
|
+
const provided = await plugin.services({ services: { ...collected } });
|
|
68
|
+
if (!provided) continue;
|
|
69
|
+
for (const [key, value] of Object.entries(provided)) {
|
|
70
|
+
if (value === undefined) continue;
|
|
71
|
+
collected[key] = value;
|
|
72
|
+
}
|
|
73
|
+
}
|
|
74
|
+
return collected;
|
|
75
|
+
}
|
|
76
|
+
|
|
42
77
|
export async function runRequestHooks(
|
|
43
78
|
plugins: GrimoirePlugin[],
|
|
44
79
|
req: Request,
|
package/src/server/worker.ts
CHANGED
|
@@ -42,11 +42,23 @@ if (process.env.GRIMOIRE_INTERNAL_SECRET) {
|
|
|
42
42
|
? ((await import(configFile)).default ?? {})
|
|
43
43
|
: {};
|
|
44
44
|
|
|
45
|
+
// Forced, not defaulted. The worker re-reads sigil.config.ts from disk
|
|
46
|
+
// rather than trusting what the CLI passed, so a `dev: true` left in the
|
|
47
|
+
// config reaches the request handler — which gates the HMR socket, the
|
|
48
|
+
// dependency-source endpoints, and /__grimoire__/open, that spawns an
|
|
49
|
+
// editor on the host from a query string. Overriding here as well as in
|
|
50
|
+
// the CLI is deliberate: the CLI's copy is not the one that binds.
|
|
51
|
+
//
|
|
52
|
+
// The worker is only ever spawned by `sigil start` or `sigil preview`.
|
|
53
|
+
// `sigil dev` runs in-process and never gets here, which is why forcing
|
|
54
|
+
// this cannot disable HMR for anyone.
|
|
45
55
|
let finalConfig: GrimoireConfig = { ...config, port, host: "127.0.0.1" };
|
|
46
56
|
const plugins = finalConfig.plugins ?? [];
|
|
47
57
|
for (const plugin of plugins) {
|
|
48
|
-
finalConfig = plugin.config?.(finalConfig) ?? finalConfig;
|
|
58
|
+
finalConfig = (await plugin.config?.(finalConfig)) ?? finalConfig;
|
|
49
59
|
}
|
|
60
|
+
// Last, so a plugin config hook cannot turn it back on either.
|
|
61
|
+
finalConfig = { ...finalConfig, dev: false };
|
|
50
62
|
|
|
51
63
|
await startWorker({
|
|
52
64
|
config: finalConfig,
|
package/src/types.ts
CHANGED
|
@@ -2,6 +2,22 @@ import type { Server, ServerWebSocket } from "bun";
|
|
|
2
2
|
import type { ScopedLogger } from "./logger";
|
|
3
3
|
import type { RouteFile, RouteTree } from "./routing/scanner";
|
|
4
4
|
|
|
5
|
+
/**
|
|
6
|
+
* Structural subset of commander's Command that plugins need to register
|
|
7
|
+
* subcommands. Declared here rather than importing Command so that
|
|
8
|
+
* @sigil-dev/grimoire does not take a dependency on commander — the CLI is
|
|
9
|
+
* one consumer of plugins, not the only one.
|
|
10
|
+
*/
|
|
11
|
+
export interface CliCommand {
|
|
12
|
+
name(): string;
|
|
13
|
+
command(nameAndArgs: string, opts?: { hidden?: boolean }): CliCommand;
|
|
14
|
+
description(text: string): CliCommand;
|
|
15
|
+
alias(alias: string): CliCommand;
|
|
16
|
+
option(flags: string, description?: string, defaultValue?: unknown): CliCommand;
|
|
17
|
+
argument(name: string, description?: string): CliCommand;
|
|
18
|
+
action(fn: (...args: never[]) => unknown): CliCommand;
|
|
19
|
+
}
|
|
20
|
+
|
|
5
21
|
/// <reference types="bun-types">
|
|
6
22
|
declare global {
|
|
7
23
|
namespace App {
|
|
@@ -66,18 +82,92 @@ export interface PluginContext {
|
|
|
66
82
|
logger: ScopedLogger;
|
|
67
83
|
}
|
|
68
84
|
|
|
85
|
+
/**
|
|
86
|
+
* Which worker this process is, and how many there are.
|
|
87
|
+
*
|
|
88
|
+
* A plugin that creates one resource per worker — a connection pool, an
|
|
89
|
+
* embedded database handle — needs both numbers to divide a global budget
|
|
90
|
+
* correctly. `maxConnections: 20` across 4 workers is 5 each; a plugin that
|
|
91
|
+
* only knows its own index has no way to work that out and quietly opens 80.
|
|
92
|
+
*
|
|
93
|
+
* The coordinator sets both as env vars at spawn, so this resolves in a
|
|
94
|
+
* worker process. Running without a coordinator (`sigil dev`, or a single
|
|
95
|
+
* process) is one worker of one, which is the honest answer rather than a
|
|
96
|
+
* guess.
|
|
97
|
+
*/
|
|
98
|
+
export interface WorkerContext {
|
|
99
|
+
/** 0-based within this mode. 0 when there is no coordinator. */
|
|
100
|
+
workerId: number;
|
|
101
|
+
/** Total workers across all modes. At least 1. */
|
|
102
|
+
workers: number;
|
|
103
|
+
/** Whether the server is in development mode. */
|
|
104
|
+
dev: boolean;
|
|
105
|
+
}
|
|
106
|
+
|
|
107
|
+
export function workerContext(env: Record<string, string | undefined> = process.env): WorkerContext {
|
|
108
|
+
const parsed = Number(env.GRIMOIRE_WORKER_INDEX);
|
|
109
|
+
const count = Number(env.GRIMOIRE_WORKER_COUNT);
|
|
110
|
+
return {
|
|
111
|
+
// A NaN here means no coordinator set them, which is one worker.
|
|
112
|
+
workerId: Number.isFinite(parsed) && parsed > 0 ? parsed - 1 : 0,
|
|
113
|
+
// Never 0: a budget divided by zero is Infinity, and a pool of
|
|
114
|
+
// Infinity is a crash at the first connection.
|
|
115
|
+
workers: Number.isFinite(count) && count > 0 ? count : 1,
|
|
116
|
+
dev: env.GRIMOIRE_MODE === "development",
|
|
117
|
+
};
|
|
118
|
+
}
|
|
119
|
+
|
|
69
120
|
export interface BuildResult {
|
|
70
121
|
success: boolean;
|
|
71
122
|
outputs: string[];
|
|
72
123
|
errors: string[];
|
|
73
124
|
}
|
|
74
125
|
|
|
126
|
+
export interface ServicesContext {
|
|
127
|
+
/**
|
|
128
|
+
* What the plugins before this one published, keyed the same way it will
|
|
129
|
+
* appear on `locals`. A snapshot: mutating it changes nothing.
|
|
130
|
+
*/
|
|
131
|
+
services: Record<string, unknown>;
|
|
132
|
+
}
|
|
133
|
+
|
|
75
134
|
export interface GrimoirePlugin {
|
|
76
135
|
name: string;
|
|
77
136
|
|
|
78
137
|
// plugin lifecycle
|
|
79
138
|
onPluginsResolved?(ctx: PluginContext): void | Promise<void>;
|
|
80
139
|
|
|
140
|
+
/**
|
|
141
|
+
* Expose values on `locals` for the whole app to use.
|
|
142
|
+
*
|
|
143
|
+
* Returns an object merged into the per-request `locals` before any
|
|
144
|
+
* route, load, action or +server.ts handler runs, so a route reaches it
|
|
145
|
+
* as `locals.<key>` with nothing imported and nothing exported from
|
|
146
|
+
* sigil.config.ts.
|
|
147
|
+
*
|
|
148
|
+
* The merge is shallow and runs in plugin order, so a later plugin
|
|
149
|
+
* overriding an earlier plugin's key wins — same rule as every other
|
|
150
|
+
* merge in the pipeline. It is collected once, at startup, and the same
|
|
151
|
+
* values are merged into every request, so a request-scoped value here
|
|
152
|
+
* is a mistake.
|
|
153
|
+
*
|
|
154
|
+
* This is the place to open a connection pool. It runs only where
|
|
155
|
+
* requests are served — `sigil dev` and each `sigil start` worker, not
|
|
156
|
+
* the coordinator or `sigil build`, which do run `config()` — and before
|
|
157
|
+
* hooks.server.ts `init()`, so `init` can use what it opened.
|
|
158
|
+
*
|
|
159
|
+
* `ctx.services` is what the plugins before this one published, so a
|
|
160
|
+
* plugin can build on a resource another plugin owns instead of opening
|
|
161
|
+
* a second one. Register the SQL plugin first and a consumer reads
|
|
162
|
+
* `ctx.services.db` — the same client, not a parallel pool.
|
|
163
|
+
*
|
|
164
|
+
* It is a snapshot taken before this plugin runs, so a plugin registered
|
|
165
|
+
* before the one it needs sees nothing. Plugins that must not depend on
|
|
166
|
+
* ordering should fail loudly when the key is absent rather than quietly
|
|
167
|
+
* open their own fallback.
|
|
168
|
+
*/
|
|
169
|
+
services?(ctx: ServicesContext): Record<string, unknown> | Promise<Record<string, unknown>>;
|
|
170
|
+
|
|
81
171
|
// server lifecycle
|
|
82
172
|
// we dont care about what the impl puts as websocket data therefore unknown.
|
|
83
173
|
onStart?(server: Server<unknown>): void | Promise<void>;
|
|
@@ -108,7 +198,34 @@ export interface GrimoirePlugin {
|
|
|
108
198
|
onBuildEnd?(result: BuildResult): void | Promise<void>;
|
|
109
199
|
|
|
110
200
|
// config
|
|
111
|
-
|
|
201
|
+
/**
|
|
202
|
+
* Transform the project config at load time.
|
|
203
|
+
*
|
|
204
|
+
* May be async. Plugins need this to open a database connection or run
|
|
205
|
+
* migrations before the server starts, and a sync-only signature makes
|
|
206
|
+
* that impossible without blocking module scope. Every call site awaits
|
|
207
|
+
* the result, so a returned Promise is never mistaken for a config.
|
|
208
|
+
*/
|
|
209
|
+
config?: (config: GrimoireConfig) =>
|
|
210
|
+
| GrimoireConfig
|
|
211
|
+
| undefined
|
|
212
|
+
| Promise<GrimoireConfig | undefined>;
|
|
213
|
+
|
|
214
|
+
/**
|
|
215
|
+
* Register CLI subcommands for this plugin.
|
|
216
|
+
*
|
|
217
|
+
* Called by the `sigil` CLI after it has loaded the project's sigil.config.ts,
|
|
218
|
+
* before command parsing, so a plugin can add `sigil jobs work` or similar.
|
|
219
|
+
* The project config is passed through as-is (after this plugin's own
|
|
220
|
+
* `config` transform, so it reflects the same values the server sees).
|
|
221
|
+
*
|
|
222
|
+
* Plugins without this hook are simply skipped. A plugin that throws here
|
|
223
|
+
* aborts the CLI with that error rather than failing obscurely later.
|
|
224
|
+
*/
|
|
225
|
+
cli?: (
|
|
226
|
+
program: CliCommand,
|
|
227
|
+
context: GrimoireConfig,
|
|
228
|
+
) => void | Promise<void>;
|
|
112
229
|
|
|
113
230
|
// process lifecycle
|
|
114
231
|
|
|
@@ -0,0 +1,113 @@
|
|
|
1
|
+
import { beforeEach, describe, expect, test } from "bun:test";
|
|
2
|
+
import {
|
|
3
|
+
_resetAfterResponseForTest,
|
|
4
|
+
afterResponse,
|
|
5
|
+
drainAfterResponse,
|
|
6
|
+
withAfterResponse,
|
|
7
|
+
} from "../src/server/after-response.ts";
|
|
8
|
+
|
|
9
|
+
const req = () => new Request("http://localhost/");
|
|
10
|
+
|
|
11
|
+
beforeEach(() => {
|
|
12
|
+
_resetAfterResponseForTest();
|
|
13
|
+
});
|
|
14
|
+
|
|
15
|
+
describe("afterResponse", () => {
|
|
16
|
+
test("does not run before the body is consumed", async () => {
|
|
17
|
+
let ran = false;
|
|
18
|
+
const res = await withAfterResponse(req(), async () => {
|
|
19
|
+
afterResponse(() => {
|
|
20
|
+
ran = true;
|
|
21
|
+
});
|
|
22
|
+
return new Response("hello");
|
|
23
|
+
});
|
|
24
|
+
expect(ran).toBe(false);
|
|
25
|
+
await res.text();
|
|
26
|
+
await Bun.sleep(10);
|
|
27
|
+
expect(ran).toBe(true);
|
|
28
|
+
});
|
|
29
|
+
|
|
30
|
+
test("runs for a response with no body", async () => {
|
|
31
|
+
let ran = false;
|
|
32
|
+
await withAfterResponse(req(), async () => {
|
|
33
|
+
afterResponse(() => {
|
|
34
|
+
ran = true;
|
|
35
|
+
});
|
|
36
|
+
return new Response(null, { status: 204 });
|
|
37
|
+
});
|
|
38
|
+
await Bun.sleep(10);
|
|
39
|
+
expect(ran).toBe(true);
|
|
40
|
+
});
|
|
41
|
+
|
|
42
|
+
test("a throwing task does not corrupt the response", async () => {
|
|
43
|
+
const res = await withAfterResponse(req(), async () => {
|
|
44
|
+
afterResponse(() => {
|
|
45
|
+
throw new Error("boom");
|
|
46
|
+
});
|
|
47
|
+
return new Response("still fine");
|
|
48
|
+
});
|
|
49
|
+
expect(await res.text()).toBe("still fine");
|
|
50
|
+
await Bun.sleep(10);
|
|
51
|
+
});
|
|
52
|
+
|
|
53
|
+
test("tasks are isolated per request under concurrency", async () => {
|
|
54
|
+
const order: string[] = [];
|
|
55
|
+
const make = (tag: string) =>
|
|
56
|
+
withAfterResponse(req(), async () => {
|
|
57
|
+
afterResponse(() => order.push(tag));
|
|
58
|
+
return new Response(tag);
|
|
59
|
+
});
|
|
60
|
+
|
|
61
|
+
const [a, b] = await Promise.all([make("A"), make("B")]);
|
|
62
|
+
await Promise.all([a.text(), b.text()]);
|
|
63
|
+
await Bun.sleep(20);
|
|
64
|
+
|
|
65
|
+
expect(order.sort()).toEqual(["A", "B"]);
|
|
66
|
+
});
|
|
67
|
+
|
|
68
|
+
test("preserves status, statusText and headers through the rewrap", async () => {
|
|
69
|
+
const res = await withAfterResponse(
|
|
70
|
+
req(),
|
|
71
|
+
async () =>
|
|
72
|
+
new Response("x", {
|
|
73
|
+
status: 404,
|
|
74
|
+
statusText: "Nope",
|
|
75
|
+
headers: { "x-test": "1" },
|
|
76
|
+
}),
|
|
77
|
+
);
|
|
78
|
+
expect(res.status).toBe(404);
|
|
79
|
+
expect(res.headers.get("x-test")).toBe("1");
|
|
80
|
+
expect(await res.text()).toBe("x");
|
|
81
|
+
});
|
|
82
|
+
|
|
83
|
+
test("drain waits for a task that is still running", async () => {
|
|
84
|
+
let done = false;
|
|
85
|
+
const res = await withAfterResponse(req(), async () => {
|
|
86
|
+
afterResponse(async () => {
|
|
87
|
+
await Bun.sleep(50);
|
|
88
|
+
done = true;
|
|
89
|
+
});
|
|
90
|
+
return new Response("y");
|
|
91
|
+
});
|
|
92
|
+
await res.text();
|
|
93
|
+
await drainAfterResponse(1000);
|
|
94
|
+
expect(done).toBe(true);
|
|
95
|
+
});
|
|
96
|
+
|
|
97
|
+
test("drain returns promptly when nothing is pending", async () => {
|
|
98
|
+
const t = Date.now();
|
|
99
|
+
await drainAfterResponse(500);
|
|
100
|
+
expect(Date.now() - t).toBeLessThan(200);
|
|
101
|
+
});
|
|
102
|
+
|
|
103
|
+
test("drain gives up rather than hanging on a stuck task", async () => {
|
|
104
|
+
const res = await withAfterResponse(req(), async () => {
|
|
105
|
+
afterResponse(() => Bun.sleep(60_000));
|
|
106
|
+
return new Response("z");
|
|
107
|
+
});
|
|
108
|
+
await res.text();
|
|
109
|
+
const t = Date.now();
|
|
110
|
+
await drainAfterResponse(200);
|
|
111
|
+
expect(Date.now() - t).toBeLessThan(1500);
|
|
112
|
+
});
|
|
113
|
+
});
|
|
@@ -0,0 +1,83 @@
|
|
|
1
|
+
import { describe, expect, test } from "bun:test";
|
|
2
|
+
import {
|
|
3
|
+
CACHE_CONTROL,
|
|
4
|
+
cacheControlFor,
|
|
5
|
+
isContentAddressed,
|
|
6
|
+
} from "../src/server/asset-cache.ts";
|
|
7
|
+
|
|
8
|
+
/**
|
|
9
|
+
* The policy, tested directly rather than through a booted server.
|
|
10
|
+
*
|
|
11
|
+
* This is where the bug lived — a caching decision, not a routing one — so
|
|
12
|
+
* it is the decision worth pinning. Importing the real function rather than
|
|
13
|
+
* restating it here: a test that keeps its own copy passes no matter what
|
|
14
|
+
* the server does, which is worse than no test at all.
|
|
15
|
+
*/
|
|
16
|
+
describe("isContentAddressed", () => {
|
|
17
|
+
test("a hash in the filename counts", () => {
|
|
18
|
+
expect(isContentAddressed("/style.a1b2c3d4.css", "")).toBe(true);
|
|
19
|
+
expect(isContentAddressed("/glyphs/ok.9f8e7d6c.svg", "")).toBe(true);
|
|
20
|
+
});
|
|
21
|
+
|
|
22
|
+
test("a longer hash still counts", () => {
|
|
23
|
+
expect(isContentAddressed("/style.deadbeef0123456789.css", "")).toBe(true);
|
|
24
|
+
});
|
|
25
|
+
|
|
26
|
+
test("a bare filename does not count", () => {
|
|
27
|
+
// The bug this policy exists to prevent: a year-long cache at a URL
|
|
28
|
+
// that never changes, so an edited stylesheet is never seen.
|
|
29
|
+
expect(isContentAddressed("/style.css", "")).toBe(false);
|
|
30
|
+
expect(isContentAddressed("/mark.svg", "")).toBe(false);
|
|
31
|
+
});
|
|
32
|
+
|
|
33
|
+
test("a version query counts", () => {
|
|
34
|
+
expect(isContentAddressed("/style.css", "?v=1")).toBe(true);
|
|
35
|
+
expect(isContentAddressed("/style.css", "?v=abc123")).toBe(true);
|
|
36
|
+
expect(isContentAddressed("/style.css", "?a=1&v=2")).toBe(true);
|
|
37
|
+
});
|
|
38
|
+
|
|
39
|
+
test("an empty version value does not count", () => {
|
|
40
|
+
// /style.css? and /style.css are the same resource, so treating it
|
|
41
|
+
// as addressed would cache it forever without it ever changing.
|
|
42
|
+
expect(isContentAddressed("/style.css", "?v=")).toBe(false);
|
|
43
|
+
expect(isContentAddressed("/style.css", "?")).toBe(false);
|
|
44
|
+
});
|
|
45
|
+
|
|
46
|
+
test("an unrelated query does not count", () => {
|
|
47
|
+
expect(isContentAddressed("/style.css", "?theme=dark")).toBe(false);
|
|
48
|
+
expect(isContentAddressed("/style.css", "?cachebust=1")).toBe(false);
|
|
49
|
+
});
|
|
50
|
+
|
|
51
|
+
test("a non-hash dotted name is not treated as addressed", () => {
|
|
52
|
+
// theme.min.css is common and 3 hex chars is not a hash.
|
|
53
|
+
expect(isContentAddressed("/app.min.css", "")).toBe(false);
|
|
54
|
+
expect(isContentAddressed("/style.abc.css", "")).toBe(false);
|
|
55
|
+
});
|
|
56
|
+
});
|
|
57
|
+
|
|
58
|
+
describe("cacheControlFor", () => {
|
|
59
|
+
test("the document is never cached", () => {
|
|
60
|
+
expect(cacheControlFor("/", "")).toBe("no-cache");
|
|
61
|
+
expect(cacheControlFor("/index.html", "")).toBe("no-cache");
|
|
62
|
+
});
|
|
63
|
+
|
|
64
|
+
test("a content-addressed asset is immutable", () => {
|
|
65
|
+
expect(cacheControlFor("/style.a1b2c3d4.css", "")).toBe("immutable");
|
|
66
|
+
expect(cacheControlFor("/style.css", "?v=2")).toBe("immutable");
|
|
67
|
+
});
|
|
68
|
+
|
|
69
|
+
test("everything else revalidates", () => {
|
|
70
|
+
expect(cacheControlFor("/style.css", "")).toBe("revalidate");
|
|
71
|
+
expect(cacheControlFor("/mark.svg", "")).toBe("revalidate");
|
|
72
|
+
});
|
|
73
|
+
|
|
74
|
+
test("every policy has a header", () => {
|
|
75
|
+
expect(CACHE_CONTROL[cacheControlFor("/", "")]).toBe("no-cache");
|
|
76
|
+
expect(CACHE_CONTROL[cacheControlFor("/a.12345678.css", "")]).toContain(
|
|
77
|
+
"immutable",
|
|
78
|
+
);
|
|
79
|
+
expect(CACHE_CONTROL[cacheControlFor("/a.css", "")]).toContain(
|
|
80
|
+
"must-revalidate",
|
|
81
|
+
);
|
|
82
|
+
});
|
|
83
|
+
});
|
package/test/coordinator.test.ts
CHANGED
|
@@ -22,6 +22,8 @@ describe("coordinator", () => {
|
|
|
22
22
|
' message(ws, data) { ws.send("echo:" + data); },',
|
|
23
23
|
"};",
|
|
24
24
|
"export function GET({ request }) {",
|
|
25
|
+
' if (new URL(request.url).searchParams.has("nav"))',
|
|
26
|
+
' return new Response(request.headers.get("x-grimoire-navigate") ?? "none");',
|
|
25
27
|
' return new Response(request.headers.get("cookie") ?? "no cookie");',
|
|
26
28
|
"}",
|
|
27
29
|
].join("\n"),
|
|
@@ -55,6 +57,13 @@ describe("coordinator", () => {
|
|
|
55
57
|
expect(res.status).toBe(200);
|
|
56
58
|
});
|
|
57
59
|
|
|
60
|
+
test("client-side navigation reaches the worker with its header", async () => {
|
|
61
|
+
const res = await fetch(`http://127.0.0.1:${port}/echo?nav`, {
|
|
62
|
+
headers: { "x-grimoire-navigate": "1" },
|
|
63
|
+
});
|
|
64
|
+
expect(await res.text()).toBe("1");
|
|
65
|
+
});
|
|
66
|
+
|
|
58
67
|
test("relays WebSockets, including a message sent right on open", async () => {
|
|
59
68
|
const ws = new WebSocket(`ws://127.0.0.1:${port}/echo`);
|
|
60
69
|
const got: string[] = [];
|
|
@@ -0,0 +1,256 @@
|
|
|
1
|
+
import { afterEach, describe, expect, test } from "bun:test";
|
|
2
|
+
import { deferred, onDeferred } from "../src/client/deferred";
|
|
3
|
+
|
|
4
|
+
/**
|
|
5
|
+
* `deferred()` reads a value that is still in flight.
|
|
6
|
+
*
|
|
7
|
+
* The interesting cases are all about timing, so the tests drive the real
|
|
8
|
+
* patch script — the exact string the server appends when a streamed promise
|
|
9
|
+
* settles — against a real event target, rather than dispatching a
|
|
10
|
+
* hand-written event. If the server's script changes shape, these fail,
|
|
11
|
+
* which is the point: the helper and the patch script are a pair and should
|
|
12
|
+
* not be able to drift apart silently.
|
|
13
|
+
*/
|
|
14
|
+
|
|
15
|
+
/** The script from `deferredChunk()` in src/rendering/index.ts. */
|
|
16
|
+
const patchScript = (key: string, value: unknown, error = false) =>
|
|
17
|
+
`<script>(function(){var value=${JSON.stringify(value)};var tag=document.getElementById("__grimoire_state__");if(tag){try{var s=JSON.parse(tag.textContent);s.data[${JSON.stringify(
|
|
18
|
+
key,
|
|
19
|
+
)}]=value;tag.textContent=JSON.stringify(s)}catch(e){}}var w=window.__grimoire_state__;if(!w||w.nodeType)w=window.__grimoire_state__={data:{}};if(!w.data)w.data={};w.data[${JSON.stringify(
|
|
20
|
+
key,
|
|
21
|
+
)}]=value;window.dispatchEvent(new CustomEvent("grimoire:deferred",{detail:{key:${JSON.stringify(
|
|
22
|
+
key,
|
|
23
|
+
)},error:${error ? "true" : "false"}}}))})()</script>`;
|
|
24
|
+
|
|
25
|
+
const listeners = new Map<string, Set<(e: Event) => void>>();
|
|
26
|
+
|
|
27
|
+
/** The `window` the helper sees: enough of one to exercise the real paths. */
|
|
28
|
+
interface FakeWindow {
|
|
29
|
+
__grimoire_state__: unknown;
|
|
30
|
+
addEventListener: (type: string, fn: (e: Event) => void) => void;
|
|
31
|
+
dispatchEvent: (e: Event) => boolean;
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
const setWindow = (w: FakeWindow | undefined) => {
|
|
35
|
+
(globalThis as unknown as { window?: FakeWindow }).window = w;
|
|
36
|
+
};
|
|
37
|
+
|
|
38
|
+
const fakeWindow = (state: unknown = { pattern: "/", data: {} }): FakeWindow => {
|
|
39
|
+
const w: FakeWindow = {
|
|
40
|
+
__grimoire_state__: state,
|
|
41
|
+
addEventListener: (type, fn) => {
|
|
42
|
+
if (!listeners.has(type)) listeners.set(type, new Set());
|
|
43
|
+
listeners.get(type)!.add(fn);
|
|
44
|
+
},
|
|
45
|
+
dispatchEvent: (e) => {
|
|
46
|
+
listeners.get(e.type)?.forEach((fn) => fn(e));
|
|
47
|
+
return true;
|
|
48
|
+
},
|
|
49
|
+
};
|
|
50
|
+
setWindow(w);
|
|
51
|
+
return w;
|
|
52
|
+
};
|
|
53
|
+
|
|
54
|
+
const fire = (script: string) => {
|
|
55
|
+
// The real script body, run with window in scope. Anything it catches,
|
|
56
|
+
// it catches the same way in a browser.
|
|
57
|
+
const body = script.replace(/^<script>|<\/script>$/g, "");
|
|
58
|
+
const run = new Function("window", "document", body) as (
|
|
59
|
+
w: FakeWindow,
|
|
60
|
+
d: { getElementById: () => null },
|
|
61
|
+
) => void;
|
|
62
|
+
run(fakeWindow(), { getElementById: () => null });
|
|
63
|
+
};
|
|
64
|
+
|
|
65
|
+
// The real `window`, captured once. Bun provides one, and other tests in
|
|
66
|
+
// this package read `window.location` — so "no window, as on the server"
|
|
67
|
+
// cannot be modelled by assigning undefined to the global, which breaks
|
|
68
|
+
// every test that runs after this file. The server path is a `typeof window
|
|
69
|
+
// === "undefined"` branch, so it is exercised by deleting the binding
|
|
70
|
+
// temporarily and restoring it immediately, inside the one test that needs
|
|
71
|
+
// it.
|
|
72
|
+
const REAL_WINDOW = (globalThis as { window?: unknown }).window;
|
|
73
|
+
|
|
74
|
+
// Every test leaves a stub window behind, so put the real one back whatever
|
|
75
|
+
// happens. Without this the stub outlives the file and the next test to read
|
|
76
|
+
// `window.location` gets a hangup — which is exactly what happened before.
|
|
77
|
+
afterEach(() => {
|
|
78
|
+
(globalThis as unknown as { window?: unknown }).window = REAL_WINDOW;
|
|
79
|
+
});
|
|
80
|
+
|
|
81
|
+
function reset() {
|
|
82
|
+
listeners.clear();
|
|
83
|
+
(globalThis as unknown as { window?: unknown }).window = REAL_WINDOW;
|
|
84
|
+
}
|
|
85
|
+
|
|
86
|
+
/** Run with no `window` at all, then put the real one back. */
|
|
87
|
+
async function withoutWindow<T>(fn: () => T): Promise<T> {
|
|
88
|
+
const g = globalThis as unknown as { window?: unknown };
|
|
89
|
+
const had = Object.prototype.hasOwnProperty.call(g, "window");
|
|
90
|
+
const saved = g.window;
|
|
91
|
+
// `delete` rather than `undefined`: a global that exists with the value
|
|
92
|
+
// undefined is still `typeof window === "object"`, so the helper would
|
|
93
|
+
// take the browser path and crash on the missing addEventListener.
|
|
94
|
+
delete g.window;
|
|
95
|
+
try {
|
|
96
|
+
return fn();
|
|
97
|
+
} finally {
|
|
98
|
+
if (had) g.window = saved;
|
|
99
|
+
}
|
|
100
|
+
}
|
|
101
|
+
|
|
102
|
+
describe("deferred()", () => {
|
|
103
|
+
test("an already-resolved value is done immediately", () => {
|
|
104
|
+
reset();
|
|
105
|
+
// The normal case: a client-side navigation resolves the promise
|
|
106
|
+
// before responding, so there is nothing to wait for.
|
|
107
|
+
const d = deferred<string[]>(["a"], []);
|
|
108
|
+
expect(d.done).toBe(true);
|
|
109
|
+
expect(d.value).toEqual(["a"]);
|
|
110
|
+
});
|
|
111
|
+
|
|
112
|
+
test("an undefined value reads as the fallback, not done", () => {
|
|
113
|
+
reset();
|
|
114
|
+
const d = deferred<string[]>(undefined, []);
|
|
115
|
+
expect(d.done).toBe(false);
|
|
116
|
+
expect(d.value).toEqual([]);
|
|
117
|
+
});
|
|
118
|
+
|
|
119
|
+
test("a late patch script fills the value in", () => {
|
|
120
|
+
reset();
|
|
121
|
+
fakeWindow();
|
|
122
|
+
const d = deferred<string[]>(undefined, []);
|
|
123
|
+
expect(d.done).toBe(false);
|
|
124
|
+
|
|
125
|
+
fire(patchScript("reviews", ["great", "long"]));
|
|
126
|
+
|
|
127
|
+
expect(d.done).toBe(true);
|
|
128
|
+
expect(d.value).toEqual(["great", "long"]);
|
|
129
|
+
});
|
|
130
|
+
|
|
131
|
+
test("a value that landed before the listener was attached is not missed", () => {
|
|
132
|
+
reset();
|
|
133
|
+
fakeWindow();
|
|
134
|
+
// The realistic race: a value that resolves in ~1ms patches the state
|
|
135
|
+
// before this component gets to wire its listener. Reading the state
|
|
136
|
+
// on the way in is what closes it.
|
|
137
|
+
fakeWindow({ pattern: "/", data: { reviews: ["already here"] } });
|
|
138
|
+
|
|
139
|
+
const d = deferred<string[]>(undefined, []);
|
|
140
|
+
expect(d.done).toBe(true);
|
|
141
|
+
expect(d.value).toEqual(["already here"]);
|
|
142
|
+
});
|
|
143
|
+
|
|
144
|
+
test("a rejected promise arrives as null, so it reads as still loading", () => {
|
|
145
|
+
reset();
|
|
146
|
+
fakeWindow();
|
|
147
|
+
const d = deferred<string[]>(undefined, []);
|
|
148
|
+
// error:true with a null value is what a rejected promise sends. The
|
|
149
|
+
// helper must not claim to be done with a null it cannot use, and
|
|
150
|
+
// must not throw on it either.
|
|
151
|
+
fire(patchScript("reviews", null, true));
|
|
152
|
+
expect(d.done).toBe(false);
|
|
153
|
+
expect(d.value).toEqual([]);
|
|
154
|
+
});
|
|
155
|
+
|
|
156
|
+
test("the state element is distinguished from the plain object", () => {
|
|
157
|
+
reset();
|
|
158
|
+
fakeWindow();
|
|
159
|
+
// The runtime's own guard: the element has nodeType, the mirror does
|
|
160
|
+
// not. Reading `.data` off the element would be undefined and the
|
|
161
|
+
// value would be silently missed.
|
|
162
|
+
const carrier = fakeWindow();
|
|
163
|
+
setWindow({
|
|
164
|
+
__grimoire_state__: { nodeType: 1, textContent: "{}" },
|
|
165
|
+
addEventListener: carrier.addEventListener,
|
|
166
|
+
dispatchEvent: () => true,
|
|
167
|
+
});
|
|
168
|
+
const d = deferred<string[]>(undefined, []);
|
|
169
|
+
expect(d.done).toBe(false);
|
|
170
|
+
});
|
|
171
|
+
|
|
172
|
+
test("with a key, another value settling does not mark this one done", () => {
|
|
173
|
+
reset();
|
|
174
|
+
fakeWindow();
|
|
175
|
+
// Two deferred values on one page. The patch event says that
|
|
176
|
+
// *something* settled, so without a key the first component to read
|
|
177
|
+
// would take the other's data — two pages showing the same list.
|
|
178
|
+
const reviews = deferred<string[]>(undefined, [], "reviews");
|
|
179
|
+
const similar = deferred<string[]>(undefined, [], "similar");
|
|
180
|
+
expect(reviews.done).toBe(false);
|
|
181
|
+
|
|
182
|
+
// A different key settles. This one must not be marked done.
|
|
183
|
+
fire(patchScript("similar", ["other"], false));
|
|
184
|
+
expect(similar.done).toBe(true);
|
|
185
|
+
expect(similar.value).toEqual(["other"]);
|
|
186
|
+
expect(reviews.done).toBe(false);
|
|
187
|
+
expect(reviews.value).toEqual([]);
|
|
188
|
+
|
|
189
|
+
// Now the right one.
|
|
190
|
+
fire(patchScript("reviews", ["mine"], false));
|
|
191
|
+
expect(reviews.done).toBe(true);
|
|
192
|
+
expect(reviews.value).toEqual(["mine"]);
|
|
193
|
+
});
|
|
194
|
+
|
|
195
|
+
test("with a key, a value that landed early is found by name", () => {
|
|
196
|
+
reset();
|
|
197
|
+
fakeWindow({
|
|
198
|
+
pattern: "/",
|
|
199
|
+
data: { reviews: ["early"], similar: ["also early"] },
|
|
200
|
+
});
|
|
201
|
+
const reviews = deferred<string[]>(undefined, [], "reviews");
|
|
202
|
+
expect(reviews.done).toBe(true);
|
|
203
|
+
expect(reviews.value).toEqual(["early"]);
|
|
204
|
+
});
|
|
205
|
+
|
|
206
|
+
test("onDeferred applies a late value", () => {
|
|
207
|
+
reset();
|
|
208
|
+
fakeWindow();
|
|
209
|
+
// The module-level `$state` shape, which `deferred()` cannot serve
|
|
210
|
+
// because a snapshot does not survive outside a render.
|
|
211
|
+
const seen: string[] = [];
|
|
212
|
+
onDeferred<string>((v) => seen.push(v), "omen");
|
|
213
|
+
expect(seen).toEqual([]);
|
|
214
|
+
|
|
215
|
+
fire(patchScript("omen", "the ink dries", false));
|
|
216
|
+
expect(seen).toEqual(["the ink dries"]);
|
|
217
|
+
});
|
|
218
|
+
|
|
219
|
+
test("onDeferred applies immediately when the value already landed", () => {
|
|
220
|
+
reset();
|
|
221
|
+
fakeWindow({ pattern: "/", data: { omen: "already dry" } });
|
|
222
|
+
// Without this, a value that settled before the module ran would
|
|
223
|
+
// never be applied at all.
|
|
224
|
+
const seen: string[] = [];
|
|
225
|
+
onDeferred<string>((v) => seen.push(v), "omen");
|
|
226
|
+
expect(seen).toEqual(["already dry"]);
|
|
227
|
+
});
|
|
228
|
+
|
|
229
|
+
test("onDeferred ignores another key settling", () => {
|
|
230
|
+
reset();
|
|
231
|
+
fakeWindow();
|
|
232
|
+
const seen: string[] = [];
|
|
233
|
+
onDeferred<string>((v) => seen.push(v), "omen");
|
|
234
|
+
fire(patchScript("other", "not mine", false));
|
|
235
|
+
expect(seen).toEqual([]);
|
|
236
|
+
});
|
|
237
|
+
|
|
238
|
+
test("onDeferred on the server is a no-op", async () => {
|
|
239
|
+
await withoutWindow(() => {
|
|
240
|
+
// Must not throw: a module that calls this runs on the server too.
|
|
241
|
+
const seen: string[] = [];
|
|
242
|
+
onDeferred<string>((v) => seen.push(v), "omen");
|
|
243
|
+
expect(seen).toEqual([]);
|
|
244
|
+
});
|
|
245
|
+
});
|
|
246
|
+
|
|
247
|
+
test("no window, as on the server, is not a crash", async () => {
|
|
248
|
+
await withoutWindow(() => {
|
|
249
|
+
// A universal load renders on the server too, where window does
|
|
250
|
+
// not exist and the value is legitimately still in flight.
|
|
251
|
+
const d = deferred<string[]>(undefined, []);
|
|
252
|
+
expect(d.done).toBe(false);
|
|
253
|
+
expect(d.value).toEqual([]);
|
|
254
|
+
});
|
|
255
|
+
});
|
|
256
|
+
});
|