@sigil-dev/grimoire 0.9.21 → 0.9.22
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/README.md +83 -83
- package/index.ts +50 -48
- package/package.json +16 -5
- package/public/__grimoire__/grimoire-client.js +12 -0
- package/public/__grimoire__/runtime.js +1241 -0
- package/server.ts +22 -20
- package/src/adapters/bun.ts +17 -0
- package/src/adapters/static.ts +41 -0
- package/src/adapters/types.ts +36 -0
- package/src/base.ts +91 -0
- package/src/client/csrf.ts +47 -47
- package/src/client/deferred.ts +179 -179
- package/src/client/enhance.ts +160 -160
- package/src/client/router.ts +870 -833
- package/src/dev/compile-module.ts +211 -211
- package/src/dev/loader.ts +141 -141
- package/src/dev/resolve.ts +70 -70
- package/src/dev/runtime-bundle.ts +51 -51
- package/src/env/modules.ts +62 -62
- package/src/env/required.ts +42 -0
- package/src/env/typegen.ts +61 -61
- package/src/headers.ts +105 -105
- package/src/logger/transports.ts +117 -117
- package/src/rendering/head.ts +49 -49
- package/src/rendering/hydrate.ts +161 -161
- package/src/rendering/images.ts +43 -43
- package/src/rendering/index.ts +755 -749
- package/src/rendering/preload.ts +101 -101
- package/src/rendering/ssrPlugin.ts +108 -108
- package/src/rendering/timing.ts +40 -40
- package/src/routing/router.ts +186 -186
- package/src/routing/scanner.ts +225 -196
- package/src/routing/transform-routes.ts +102 -102
- package/src/server/after-response.ts +206 -206
- package/src/server/asset-cache.ts +57 -57
- package/src/server/build.ts +262 -262
- package/src/server/cached.ts +114 -114
- package/src/server/client-address.ts +82 -82
- package/src/server/client-dir.ts +57 -57
- package/src/server/client-entry.ts +44 -44
- package/src/server/cookie-utils.ts +80 -80
- package/src/server/coordinator.ts +476 -471
- package/src/server/hooks.ts +122 -122
- package/src/server/index.ts +1138 -1018
- package/src/server/plugins.ts +172 -172
- package/src/server/prerender.ts +444 -0
- package/src/server/reserved.ts +17 -0
- package/src/server/resolver.ts +98 -98
- package/src/server/rewrite.ts +28 -0
- package/src/server/warm.ts +91 -91
- package/src/server/with-headers.ts +27 -27
- package/src/server/worker.ts +74 -72
- package/src/testing/dom.ts +73 -0
- package/src/testing/index.ts +169 -0
- package/src/testing/server.ts +162 -0
- package/src/typegen/index.ts +450 -450
- package/src/types.ts +501 -432
- package/test/after-response.test.ts +132 -132
- package/test/asset-cache-policy.test.ts +96 -96
- package/test/base.test.ts +134 -0
- package/test/cached.test.ts +126 -126
- package/test/client-address.test.ts +78 -78
- package/test/client-csrf.test.ts +61 -61
- package/test/client-dir.test.ts +101 -101
- package/test/client-router.test.ts +789 -734
- package/test/coordinator.test.ts +96 -94
- package/test/deferred.test.ts +256 -256
- package/test/dev-loader.test.ts +30 -30
- package/test/env.test.ts +168 -168
- package/test/force-production.test.ts +44 -0
- package/test/images.test.ts +49 -49
- package/test/locals-header.test.ts +61 -0
- package/test/middleware.test.ts +243 -243
- package/test/parser-plugins.test.ts +92 -92
- package/test/plugin-handle.test.ts +62 -62
- package/test/plugin-services-context.test.ts +97 -97
- package/test/preload.test.ts +48 -48
- package/test/prerender.test.ts +353 -0
- package/test/rendering.test.ts +798 -798
- package/test/required-env.test.ts +32 -0
- package/test/rewrite-html.test.ts +90 -0
- package/test/scanning.test.ts +349 -314
- package/test/server.test.ts +640 -619
- package/test/services.test.ts +90 -90
- package/test/streaming.test.ts +378 -378
- package/test/testing-helpers.test.ts +166 -0
- package/test/typegen.test.ts +805 -799
- package/test/warm.test.ts +96 -96
- package/test/worker-context.test.ts +59 -59
- package/test/workspace-files.test.ts +149 -146
- package/test/workspace-versions.test.ts +131 -131
- package/.grimoire/_routes.ts +0 -4
- package/public/__grimoire__/client.js +0 -55
- package/public/__grimoire__/hydrate.js +0 -63
package/src/server/cached.ts
CHANGED
|
@@ -1,114 +1,114 @@
|
|
|
1
|
-
/**
|
|
2
|
-
* In-memory stale-while-revalidate cache for expensive server-side values.
|
|
3
|
-
*
|
|
4
|
-
* The common hand-rolled version is "if the entry is older than an hour,
|
|
5
|
-
* rebuild it inline", which makes one unlucky visitor per hour (per worker)
|
|
6
|
-
* wait for the rebuild. Here, once a value exists it is always returned at
|
|
7
|
-
* once; an expired one is refreshed in the background, by a single shared
|
|
8
|
-
* call, while callers keep getting the old value.
|
|
9
|
-
*
|
|
10
|
-
* const costumeIndex = cached(() => buildIndex(), { ttl: 3600_000 });
|
|
11
|
-
* const index = await costumeIndex();
|
|
12
|
-
*
|
|
13
|
-
* const player = cachedBy((id: string) => fetchPlayer(id), { ttl: 60_000 });
|
|
14
|
-
* await player("123");
|
|
15
|
-
*/
|
|
16
|
-
|
|
17
|
-
export interface CachedOptions {
|
|
18
|
-
/** How long (ms) a value is fresh. */
|
|
19
|
-
ttl: number;
|
|
20
|
-
/**
|
|
21
|
-
* How long (ms) past `ttl` a stale value may still be served while the
|
|
22
|
-
* refresh runs. Past it, the next caller waits. Default: forever.
|
|
23
|
-
*/
|
|
24
|
-
staleFor?: number;
|
|
25
|
-
/** cachedBy only: the most keys held; the least recently used goes first. */
|
|
26
|
-
max?: number;
|
|
27
|
-
/** Called when a background refresh fails; the stale value stays. */
|
|
28
|
-
onError?: (error: unknown) => void;
|
|
29
|
-
}
|
|
30
|
-
|
|
31
|
-
interface Entry<T> {
|
|
32
|
-
value: T;
|
|
33
|
-
at: number;
|
|
34
|
-
}
|
|
35
|
-
|
|
36
|
-
export interface CachedFn<A extends unknown[], T> {
|
|
37
|
-
(...args: A): Promise<T>;
|
|
38
|
-
/** Drop one entry (or all with no argument); the next call refetches. */
|
|
39
|
-
invalidate(...args: A | []): void;
|
|
40
|
-
}
|
|
41
|
-
|
|
42
|
-
function build<A extends unknown[], T>(
|
|
43
|
-
fn: (...args: A) => Promise<T>,
|
|
44
|
-
keyOf: (args: A) => string,
|
|
45
|
-
opts: CachedOptions,
|
|
46
|
-
): CachedFn<A, T> {
|
|
47
|
-
const { ttl, staleFor = Number.POSITIVE_INFINITY, max = 500, onError } = opts;
|
|
48
|
-
const entries = new Map<string, Entry<T>>();
|
|
49
|
-
const running = new Map<string, Promise<T>>();
|
|
50
|
-
|
|
51
|
-
function refresh(key: string, args: A): Promise<T> {
|
|
52
|
-
const existing = running.get(key);
|
|
53
|
-
if (existing) return existing;
|
|
54
|
-
const p = fn(...args).then(
|
|
55
|
-
(value) => {
|
|
56
|
-
running.delete(key);
|
|
57
|
-
entries.delete(key); // re-insert so insertion order = recency
|
|
58
|
-
entries.set(key, { value, at: Date.now() });
|
|
59
|
-
while (entries.size > max) {
|
|
60
|
-
const oldest = entries.keys().next().value as string;
|
|
61
|
-
entries.delete(oldest);
|
|
62
|
-
}
|
|
63
|
-
return value;
|
|
64
|
-
},
|
|
65
|
-
(e) => {
|
|
66
|
-
running.delete(key);
|
|
67
|
-
throw e;
|
|
68
|
-
},
|
|
69
|
-
);
|
|
70
|
-
running.set(key, p);
|
|
71
|
-
return p;
|
|
72
|
-
}
|
|
73
|
-
|
|
74
|
-
const call = ((...args: A): Promise<T> => {
|
|
75
|
-
const key = keyOf(args);
|
|
76
|
-
const hit = entries.get(key);
|
|
77
|
-
if (hit) {
|
|
78
|
-
const age = Date.now() - hit.at;
|
|
79
|
-
entries.delete(key); // a read counts as use
|
|
80
|
-
entries.set(key, hit);
|
|
81
|
-
if (age < ttl) return Promise.resolve(hit.value);
|
|
82
|
-
if (age < ttl + staleFor) {
|
|
83
|
-
refresh(key, args).catch((e) => onError?.(e));
|
|
84
|
-
return Promise.resolve(hit.value);
|
|
85
|
-
}
|
|
86
|
-
}
|
|
87
|
-
return refresh(key, args);
|
|
88
|
-
}) as CachedFn<A, T>;
|
|
89
|
-
|
|
90
|
-
call.invalidate = (...args: A | []) => {
|
|
91
|
-
if (args.length === 0) {
|
|
92
|
-
entries.clear();
|
|
93
|
-
return;
|
|
94
|
-
}
|
|
95
|
-
entries.delete(keyOf(args as A));
|
|
96
|
-
};
|
|
97
|
-
return call;
|
|
98
|
-
}
|
|
99
|
-
|
|
100
|
-
/** A value with no arguments, cached process-wide. */
|
|
101
|
-
export function cached<T>(
|
|
102
|
-
fn: () => Promise<T>,
|
|
103
|
-
opts: CachedOptions,
|
|
104
|
-
): CachedFn<[], T> {
|
|
105
|
-
return build(fn, () => "", opts);
|
|
106
|
-
}
|
|
107
|
-
|
|
108
|
-
/** A value per argument list (compared as JSON), with an LRU cap. */
|
|
109
|
-
export function cachedBy<A extends unknown[], T>(
|
|
110
|
-
fn: (...args: A) => Promise<T>,
|
|
111
|
-
opts: CachedOptions,
|
|
112
|
-
): CachedFn<A, T> {
|
|
113
|
-
return build(fn, (args) => JSON.stringify(args), opts);
|
|
114
|
-
}
|
|
1
|
+
/**
|
|
2
|
+
* In-memory stale-while-revalidate cache for expensive server-side values.
|
|
3
|
+
*
|
|
4
|
+
* The common hand-rolled version is "if the entry is older than an hour,
|
|
5
|
+
* rebuild it inline", which makes one unlucky visitor per hour (per worker)
|
|
6
|
+
* wait for the rebuild. Here, once a value exists it is always returned at
|
|
7
|
+
* once; an expired one is refreshed in the background, by a single shared
|
|
8
|
+
* call, while callers keep getting the old value.
|
|
9
|
+
*
|
|
10
|
+
* const costumeIndex = cached(() => buildIndex(), { ttl: 3600_000 });
|
|
11
|
+
* const index = await costumeIndex();
|
|
12
|
+
*
|
|
13
|
+
* const player = cachedBy((id: string) => fetchPlayer(id), { ttl: 60_000 });
|
|
14
|
+
* await player("123");
|
|
15
|
+
*/
|
|
16
|
+
|
|
17
|
+
export interface CachedOptions {
|
|
18
|
+
/** How long (ms) a value is fresh. */
|
|
19
|
+
ttl: number;
|
|
20
|
+
/**
|
|
21
|
+
* How long (ms) past `ttl` a stale value may still be served while the
|
|
22
|
+
* refresh runs. Past it, the next caller waits. Default: forever.
|
|
23
|
+
*/
|
|
24
|
+
staleFor?: number;
|
|
25
|
+
/** cachedBy only: the most keys held; the least recently used goes first. */
|
|
26
|
+
max?: number;
|
|
27
|
+
/** Called when a background refresh fails; the stale value stays. */
|
|
28
|
+
onError?: (error: unknown) => void;
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
interface Entry<T> {
|
|
32
|
+
value: T;
|
|
33
|
+
at: number;
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
export interface CachedFn<A extends unknown[], T> {
|
|
37
|
+
(...args: A): Promise<T>;
|
|
38
|
+
/** Drop one entry (or all with no argument); the next call refetches. */
|
|
39
|
+
invalidate(...args: A | []): void;
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
function build<A extends unknown[], T>(
|
|
43
|
+
fn: (...args: A) => Promise<T>,
|
|
44
|
+
keyOf: (args: A) => string,
|
|
45
|
+
opts: CachedOptions,
|
|
46
|
+
): CachedFn<A, T> {
|
|
47
|
+
const { ttl, staleFor = Number.POSITIVE_INFINITY, max = 500, onError } = opts;
|
|
48
|
+
const entries = new Map<string, Entry<T>>();
|
|
49
|
+
const running = new Map<string, Promise<T>>();
|
|
50
|
+
|
|
51
|
+
function refresh(key: string, args: A): Promise<T> {
|
|
52
|
+
const existing = running.get(key);
|
|
53
|
+
if (existing) return existing;
|
|
54
|
+
const p = fn(...args).then(
|
|
55
|
+
(value) => {
|
|
56
|
+
running.delete(key);
|
|
57
|
+
entries.delete(key); // re-insert so insertion order = recency
|
|
58
|
+
entries.set(key, { value, at: Date.now() });
|
|
59
|
+
while (entries.size > max) {
|
|
60
|
+
const oldest = entries.keys().next().value as string;
|
|
61
|
+
entries.delete(oldest);
|
|
62
|
+
}
|
|
63
|
+
return value;
|
|
64
|
+
},
|
|
65
|
+
(e) => {
|
|
66
|
+
running.delete(key);
|
|
67
|
+
throw e;
|
|
68
|
+
},
|
|
69
|
+
);
|
|
70
|
+
running.set(key, p);
|
|
71
|
+
return p;
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
const call = ((...args: A): Promise<T> => {
|
|
75
|
+
const key = keyOf(args);
|
|
76
|
+
const hit = entries.get(key);
|
|
77
|
+
if (hit) {
|
|
78
|
+
const age = Date.now() - hit.at;
|
|
79
|
+
entries.delete(key); // a read counts as use
|
|
80
|
+
entries.set(key, hit);
|
|
81
|
+
if (age < ttl) return Promise.resolve(hit.value);
|
|
82
|
+
if (age < ttl + staleFor) {
|
|
83
|
+
refresh(key, args).catch((e) => onError?.(e));
|
|
84
|
+
return Promise.resolve(hit.value);
|
|
85
|
+
}
|
|
86
|
+
}
|
|
87
|
+
return refresh(key, args);
|
|
88
|
+
}) as CachedFn<A, T>;
|
|
89
|
+
|
|
90
|
+
call.invalidate = (...args: A | []) => {
|
|
91
|
+
if (args.length === 0) {
|
|
92
|
+
entries.clear();
|
|
93
|
+
return;
|
|
94
|
+
}
|
|
95
|
+
entries.delete(keyOf(args as A));
|
|
96
|
+
};
|
|
97
|
+
return call;
|
|
98
|
+
}
|
|
99
|
+
|
|
100
|
+
/** A value with no arguments, cached process-wide. */
|
|
101
|
+
export function cached<T>(
|
|
102
|
+
fn: () => Promise<T>,
|
|
103
|
+
opts: CachedOptions,
|
|
104
|
+
): CachedFn<[], T> {
|
|
105
|
+
return build(fn, () => "", opts);
|
|
106
|
+
}
|
|
107
|
+
|
|
108
|
+
/** A value per argument list (compared as JSON), with an LRU cap. */
|
|
109
|
+
export function cachedBy<A extends unknown[], T>(
|
|
110
|
+
fn: (...args: A) => Promise<T>,
|
|
111
|
+
opts: CachedOptions,
|
|
112
|
+
): CachedFn<A, T> {
|
|
113
|
+
return build(fn, (args) => JSON.stringify(args), opts);
|
|
114
|
+
}
|
|
@@ -1,82 +1,82 @@
|
|
|
1
|
-
import type { Server } from "bun";
|
|
2
|
-
|
|
3
|
-
/**
|
|
4
|
-
* The visitor's address, as the coordinator saw it, on a request it forwards
|
|
5
|
-
* to a worker. A client's own copy of the header is dropped by the
|
|
6
|
-
* coordinator, and a worker only accepts requests that carry its secret, so
|
|
7
|
-
* inside a worker the value can be trusted.
|
|
8
|
-
*/
|
|
9
|
-
export const CLIENT_ADDRESS_HEADER = "x-grimoire-client-address";
|
|
10
|
-
|
|
11
|
-
const isWorker = () => Boolean(process.env.GRIMOIRE_INTERNAL_SECRET);
|
|
12
|
-
|
|
13
|
-
/** Loopback and private ranges: where a reverse proxy on the same machine or network connects from. */
|
|
14
|
-
function isPrivate(ip: string): boolean {
|
|
15
|
-
const v4 = ip.startsWith("::ffff:") ? ip.slice(7) : ip;
|
|
16
|
-
if (/^(127\.|10\.|192\.168\.|169\.254\.)/.test(v4)) return true;
|
|
17
|
-
const m = /^172\.(\d+)\./.exec(v4);
|
|
18
|
-
if (m && Number(m[1]) >= 16 && Number(m[1]) <= 31) return true;
|
|
19
|
-
const v6 = ip.toLowerCase();
|
|
20
|
-
return (
|
|
21
|
-
v6 === "::1" ||
|
|
22
|
-
v6.startsWith("fc") ||
|
|
23
|
-
v6.startsWith("fd") ||
|
|
24
|
-
v6.startsWith("fe80:")
|
|
25
|
-
);
|
|
26
|
-
}
|
|
27
|
-
|
|
28
|
-
/**
|
|
29
|
-
* Who sent the request, given the address of the connection it came over.
|
|
30
|
-
*
|
|
31
|
-
* A connection from a private address is a reverse proxy (Caddy, nginx, a
|
|
32
|
-
* load balancer, Docker's network), and the visitor is the last entry it
|
|
33
|
-
* appended to X-Forwarded-For. Earlier entries came from the client and can
|
|
34
|
-
* say anything. A connection from a public address is the visitor itself, so
|
|
35
|
-
* any X-Forwarded-For it sends is ignored rather than believed.
|
|
36
|
-
*/
|
|
37
|
-
export function resolveClientAddress(
|
|
38
|
-
req: Request,
|
|
39
|
-
peer: string | undefined,
|
|
40
|
-
): string {
|
|
41
|
-
if (!peer) return "unknown";
|
|
42
|
-
if (!isPrivate(peer)) return peer;
|
|
43
|
-
const forwarded = req.headers
|
|
44
|
-
.get("x-forwarded-for")
|
|
45
|
-
?.split(",")
|
|
46
|
-
.map((s) => s.trim())
|
|
47
|
-
.filter(Boolean);
|
|
48
|
-
return forwarded?.at(-1) ?? req.headers.get("x-real-ip")?.trim() ?? peer;
|
|
49
|
-
}
|
|
50
|
-
|
|
51
|
-
/**
|
|
52
|
-
* The visitor's IP address. Under `sigil start` it is what the coordinator
|
|
53
|
-
* worked out; otherwise it is read from the connection the same way.
|
|
54
|
-
*/
|
|
55
|
-
export function clientAddress(
|
|
56
|
-
req: Request,
|
|
57
|
-
server: Server<unknown> | null,
|
|
58
|
-
): string {
|
|
59
|
-
if (isWorker()) {
|
|
60
|
-
return req.headers.get(CLIENT_ADDRESS_HEADER) ?? "unknown";
|
|
61
|
-
}
|
|
62
|
-
return resolveClientAddress(req, server?.requestIP(req)?.address);
|
|
63
|
-
}
|
|
64
|
-
|
|
65
|
-
const lookups = new WeakMap<Request, () => string>();
|
|
66
|
-
|
|
67
|
-
/** Remembers how to find the address of a request, so every context built for it can offer one. */
|
|
68
|
-
export function trackClientAddress(
|
|
69
|
-
req: Request,
|
|
70
|
-
server: Server<unknown> | null,
|
|
71
|
-
): void {
|
|
72
|
-
let address: string | undefined;
|
|
73
|
-
lookups.set(req, () => {
|
|
74
|
-
address ??= clientAddress(req, server);
|
|
75
|
-
return address;
|
|
76
|
-
});
|
|
77
|
-
}
|
|
78
|
-
|
|
79
|
-
/** The address of a request the server is handling. */
|
|
80
|
-
export function clientAddressOf(req: Request): string {
|
|
81
|
-
return lookups.get(req)?.() ?? "unknown";
|
|
82
|
-
}
|
|
1
|
+
import type { Server } from "bun";
|
|
2
|
+
|
|
3
|
+
/**
|
|
4
|
+
* The visitor's address, as the coordinator saw it, on a request it forwards
|
|
5
|
+
* to a worker. A client's own copy of the header is dropped by the
|
|
6
|
+
* coordinator, and a worker only accepts requests that carry its secret, so
|
|
7
|
+
* inside a worker the value can be trusted.
|
|
8
|
+
*/
|
|
9
|
+
export const CLIENT_ADDRESS_HEADER = "x-grimoire-client-address";
|
|
10
|
+
|
|
11
|
+
const isWorker = () => Boolean(process.env.GRIMOIRE_INTERNAL_SECRET);
|
|
12
|
+
|
|
13
|
+
/** Loopback and private ranges: where a reverse proxy on the same machine or network connects from. */
|
|
14
|
+
function isPrivate(ip: string): boolean {
|
|
15
|
+
const v4 = ip.startsWith("::ffff:") ? ip.slice(7) : ip;
|
|
16
|
+
if (/^(127\.|10\.|192\.168\.|169\.254\.)/.test(v4)) return true;
|
|
17
|
+
const m = /^172\.(\d+)\./.exec(v4);
|
|
18
|
+
if (m && Number(m[1]) >= 16 && Number(m[1]) <= 31) return true;
|
|
19
|
+
const v6 = ip.toLowerCase();
|
|
20
|
+
return (
|
|
21
|
+
v6 === "::1" ||
|
|
22
|
+
v6.startsWith("fc") ||
|
|
23
|
+
v6.startsWith("fd") ||
|
|
24
|
+
v6.startsWith("fe80:")
|
|
25
|
+
);
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
/**
|
|
29
|
+
* Who sent the request, given the address of the connection it came over.
|
|
30
|
+
*
|
|
31
|
+
* A connection from a private address is a reverse proxy (Caddy, nginx, a
|
|
32
|
+
* load balancer, Docker's network), and the visitor is the last entry it
|
|
33
|
+
* appended to X-Forwarded-For. Earlier entries came from the client and can
|
|
34
|
+
* say anything. A connection from a public address is the visitor itself, so
|
|
35
|
+
* any X-Forwarded-For it sends is ignored rather than believed.
|
|
36
|
+
*/
|
|
37
|
+
export function resolveClientAddress(
|
|
38
|
+
req: Request,
|
|
39
|
+
peer: string | undefined,
|
|
40
|
+
): string {
|
|
41
|
+
if (!peer) return "unknown";
|
|
42
|
+
if (!isPrivate(peer)) return peer;
|
|
43
|
+
const forwarded = req.headers
|
|
44
|
+
.get("x-forwarded-for")
|
|
45
|
+
?.split(",")
|
|
46
|
+
.map((s) => s.trim())
|
|
47
|
+
.filter(Boolean);
|
|
48
|
+
return forwarded?.at(-1) ?? req.headers.get("x-real-ip")?.trim() ?? peer;
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
/**
|
|
52
|
+
* The visitor's IP address. Under `sigil start` it is what the coordinator
|
|
53
|
+
* worked out; otherwise it is read from the connection the same way.
|
|
54
|
+
*/
|
|
55
|
+
export function clientAddress(
|
|
56
|
+
req: Request,
|
|
57
|
+
server: Server<unknown> | null,
|
|
58
|
+
): string {
|
|
59
|
+
if (isWorker()) {
|
|
60
|
+
return req.headers.get(CLIENT_ADDRESS_HEADER) ?? "unknown";
|
|
61
|
+
}
|
|
62
|
+
return resolveClientAddress(req, server?.requestIP(req)?.address);
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
const lookups = new WeakMap<Request, () => string>();
|
|
66
|
+
|
|
67
|
+
/** Remembers how to find the address of a request, so every context built for it can offer one. */
|
|
68
|
+
export function trackClientAddress(
|
|
69
|
+
req: Request,
|
|
70
|
+
server: Server<unknown> | null,
|
|
71
|
+
): void {
|
|
72
|
+
let address: string | undefined;
|
|
73
|
+
lookups.set(req, () => {
|
|
74
|
+
address ??= clientAddress(req, server);
|
|
75
|
+
return address;
|
|
76
|
+
});
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
/** The address of a request the server is handling. */
|
|
80
|
+
export function clientAddressOf(req: Request): string {
|
|
81
|
+
return lookups.get(req)?.() ?? "unknown";
|
|
82
|
+
}
|
package/src/server/client-dir.ts
CHANGED
|
@@ -1,57 +1,57 @@
|
|
|
1
|
-
import { existsSync } from "node:fs";
|
|
2
|
-
import { readdir, rm } from "node:fs/promises";
|
|
3
|
-
import { join, relative } from "node:path";
|
|
4
|
-
import { log } from "../logger/instance";
|
|
5
|
-
|
|
6
|
-
const logger = log.scope("build");
|
|
7
|
-
|
|
8
|
-
/** The URL the browser bundle is served under. */
|
|
9
|
-
export const CLIENT_URL = "/__grimoire__/";
|
|
10
|
-
|
|
11
|
-
/**
|
|
12
|
-
* Where the browser bundle is written: hydrate.js, the client router, their
|
|
13
|
-
* chunks, and in dev the runtime. Generated output, so it lives in .grimoire/
|
|
14
|
-
* with the rest of the build rather than in public/, which is the app's own.
|
|
15
|
-
*/
|
|
16
|
-
export const clientDir = (root = process.cwd()) =>
|
|
17
|
-
join(root, ".grimoire", "client");
|
|
18
|
-
|
|
19
|
-
/** Files dev writes beside the bundle, which a dev rebuild must keep. */
|
|
20
|
-
const DEV_FILES = new Set(["runtime.js", "grimoire-client.js"]);
|
|
21
|
-
|
|
22
|
-
/**
|
|
23
|
-
* Empties the bundle directory before a build, so the chunks of the last one
|
|
24
|
-
* are not left behind and served forever. Also removes public/__grimoire__,
|
|
25
|
-
* where older versions wrote the bundle.
|
|
26
|
-
*/
|
|
27
|
-
export async function resetClientDir(root = process.cwd()): Promise<void> {
|
|
28
|
-
await rm(clientDir(root), { recursive: true, force: true });
|
|
29
|
-
const legacy = join(root, "public", "__grimoire__");
|
|
30
|
-
if (existsSync(legacy)) {
|
|
31
|
-
await rm(legacy, { recursive: true, force: true });
|
|
32
|
-
logger.info(
|
|
33
|
-
"removed public/__grimoire__: the client bundle is now built into .grimoire/client. " +
|
|
34
|
-
"Its line in .gitignore can go.",
|
|
35
|
-
);
|
|
36
|
-
}
|
|
37
|
-
}
|
|
38
|
-
|
|
39
|
-
/**
|
|
40
|
-
* After a dev rebuild, deletes what that rebuild did not produce: the chunks
|
|
41
|
-
* an edit replaced. The dev runtime files stay.
|
|
42
|
-
*/
|
|
43
|
-
export async function pruneClientDir(
|
|
44
|
-
outputs: readonly string[],
|
|
45
|
-
root = process.cwd(),
|
|
46
|
-
): Promise<void> {
|
|
47
|
-
const dir = clientDir(root);
|
|
48
|
-
const keep = new Set(outputs.map((p) => relative(dir, p)));
|
|
49
|
-
const entries = await readdir(dir, { recursive: true, withFileTypes: true });
|
|
50
|
-
await Promise.all(
|
|
51
|
-
entries
|
|
52
|
-
.filter((e) => e.isFile())
|
|
53
|
-
.map((e) => relative(dir, join(e.parentPath, e.name)))
|
|
54
|
-
.filter((file) => !keep.has(file) && !DEV_FILES.has(file))
|
|
55
|
-
.map((file) => rm(join(dir, file), { force: true })),
|
|
56
|
-
);
|
|
57
|
-
}
|
|
1
|
+
import { existsSync } from "node:fs";
|
|
2
|
+
import { readdir, rm } from "node:fs/promises";
|
|
3
|
+
import { join, relative } from "node:path";
|
|
4
|
+
import { log } from "../logger/instance";
|
|
5
|
+
|
|
6
|
+
const logger = log.scope("build");
|
|
7
|
+
|
|
8
|
+
/** The URL the browser bundle is served under. */
|
|
9
|
+
export const CLIENT_URL = "/__grimoire__/";
|
|
10
|
+
|
|
11
|
+
/**
|
|
12
|
+
* Where the browser bundle is written: hydrate.js, the client router, their
|
|
13
|
+
* chunks, and in dev the runtime. Generated output, so it lives in .grimoire/
|
|
14
|
+
* with the rest of the build rather than in public/, which is the app's own.
|
|
15
|
+
*/
|
|
16
|
+
export const clientDir = (root = process.cwd()) =>
|
|
17
|
+
join(root, ".grimoire", "client");
|
|
18
|
+
|
|
19
|
+
/** Files dev writes beside the bundle, which a dev rebuild must keep. */
|
|
20
|
+
const DEV_FILES = new Set(["runtime.js", "grimoire-client.js"]);
|
|
21
|
+
|
|
22
|
+
/**
|
|
23
|
+
* Empties the bundle directory before a build, so the chunks of the last one
|
|
24
|
+
* are not left behind and served forever. Also removes public/__grimoire__,
|
|
25
|
+
* where older versions wrote the bundle.
|
|
26
|
+
*/
|
|
27
|
+
export async function resetClientDir(root = process.cwd()): Promise<void> {
|
|
28
|
+
await rm(clientDir(root), { recursive: true, force: true });
|
|
29
|
+
const legacy = join(root, "public", "__grimoire__");
|
|
30
|
+
if (existsSync(legacy)) {
|
|
31
|
+
await rm(legacy, { recursive: true, force: true });
|
|
32
|
+
logger.info(
|
|
33
|
+
"removed public/__grimoire__: the client bundle is now built into .grimoire/client. " +
|
|
34
|
+
"Its line in .gitignore can go.",
|
|
35
|
+
);
|
|
36
|
+
}
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
/**
|
|
40
|
+
* After a dev rebuild, deletes what that rebuild did not produce: the chunks
|
|
41
|
+
* an edit replaced. The dev runtime files stay.
|
|
42
|
+
*/
|
|
43
|
+
export async function pruneClientDir(
|
|
44
|
+
outputs: readonly string[],
|
|
45
|
+
root = process.cwd(),
|
|
46
|
+
): Promise<void> {
|
|
47
|
+
const dir = clientDir(root);
|
|
48
|
+
const keep = new Set(outputs.map((p) => relative(dir, p)));
|
|
49
|
+
const entries = await readdir(dir, { recursive: true, withFileTypes: true });
|
|
50
|
+
await Promise.all(
|
|
51
|
+
entries
|
|
52
|
+
.filter((e) => e.isFile())
|
|
53
|
+
.map((e) => relative(dir, join(e.parentPath, e.name)))
|
|
54
|
+
.filter((file) => !keep.has(file) && !DEV_FILES.has(file))
|
|
55
|
+
.map((file) => rm(join(dir, file), { force: true })),
|
|
56
|
+
);
|
|
57
|
+
}
|
|
@@ -1,44 +1,44 @@
|
|
|
1
|
-
import { readFileSync, statSync, writeFileSync } from "node:fs";
|
|
2
|
-
import { basename, join } from "node:path";
|
|
3
|
-
|
|
4
|
-
/**
|
|
5
|
-
* The client entry is named by its content (`hydrate-a1b2c3d4.js`), like the
|
|
6
|
-
* chunks, so each build has its own URL. A fixed `hydrate.js` let a CDN that
|
|
7
|
-
* caches scripts regardless of Cache-Control (Cloudflare does by default)
|
|
8
|
-
* keep serving the previous build's script against the new build's HTML,
|
|
9
|
-
* for hours after every deploy. The build records the name here.
|
|
10
|
-
*/
|
|
11
|
-
const entryFile = (root = process.cwd()) =>
|
|
12
|
-
join(root, ".grimoire", "client-entry.json");
|
|
13
|
-
|
|
14
|
-
let cached: { mtime: number; hydrate: string } | undefined;
|
|
15
|
-
|
|
16
|
-
/** The hydrate entry's file name, relative to /__grimoire__/. */
|
|
17
|
-
export function hydrateEntry(root = process.cwd()): string {
|
|
18
|
-
try {
|
|
19
|
-
const mtime = statSync(entryFile(root)).mtimeMs;
|
|
20
|
-
if (cached?.mtime !== mtime) {
|
|
21
|
-
const { hydrate } = JSON.parse(readFileSync(entryFile(root), "utf8"));
|
|
22
|
-
cached = { mtime, hydrate };
|
|
23
|
-
}
|
|
24
|
-
return cached.hydrate;
|
|
25
|
-
} catch {
|
|
26
|
-
// built by an older version, or not built yet
|
|
27
|
-
return "hydrate.js";
|
|
28
|
-
}
|
|
29
|
-
}
|
|
30
|
-
|
|
31
|
-
/** Records the entry a build produced. */
|
|
32
|
-
export function recordClientEntry(
|
|
33
|
-
outputs: readonly { path: string; kind: string }[],
|
|
34
|
-
root = process.cwd(),
|
|
35
|
-
): void {
|
|
36
|
-
const entry = outputs.find(
|
|
37
|
-
(o) => o.kind === "entry-point" && basename(o.path).startsWith("hydrate"),
|
|
38
|
-
);
|
|
39
|
-
if (!entry) return;
|
|
40
|
-
writeFileSync(
|
|
41
|
-
entryFile(root),
|
|
42
|
-
JSON.stringify({ hydrate: basename(entry.path) }),
|
|
43
|
-
);
|
|
44
|
-
}
|
|
1
|
+
import { readFileSync, statSync, writeFileSync } from "node:fs";
|
|
2
|
+
import { basename, join } from "node:path";
|
|
3
|
+
|
|
4
|
+
/**
|
|
5
|
+
* The client entry is named by its content (`hydrate-a1b2c3d4.js`), like the
|
|
6
|
+
* chunks, so each build has its own URL. A fixed `hydrate.js` let a CDN that
|
|
7
|
+
* caches scripts regardless of Cache-Control (Cloudflare does by default)
|
|
8
|
+
* keep serving the previous build's script against the new build's HTML,
|
|
9
|
+
* for hours after every deploy. The build records the name here.
|
|
10
|
+
*/
|
|
11
|
+
const entryFile = (root = process.cwd()) =>
|
|
12
|
+
join(root, ".grimoire", "client-entry.json");
|
|
13
|
+
|
|
14
|
+
let cached: { mtime: number; hydrate: string } | undefined;
|
|
15
|
+
|
|
16
|
+
/** The hydrate entry's file name, relative to /__grimoire__/. */
|
|
17
|
+
export function hydrateEntry(root = process.cwd()): string {
|
|
18
|
+
try {
|
|
19
|
+
const mtime = statSync(entryFile(root)).mtimeMs;
|
|
20
|
+
if (cached?.mtime !== mtime) {
|
|
21
|
+
const { hydrate } = JSON.parse(readFileSync(entryFile(root), "utf8"));
|
|
22
|
+
cached = { mtime, hydrate };
|
|
23
|
+
}
|
|
24
|
+
return cached.hydrate;
|
|
25
|
+
} catch {
|
|
26
|
+
// built by an older version, or not built yet
|
|
27
|
+
return "hydrate.js";
|
|
28
|
+
}
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
/** Records the entry a build produced. */
|
|
32
|
+
export function recordClientEntry(
|
|
33
|
+
outputs: readonly { path: string; kind: string }[],
|
|
34
|
+
root = process.cwd(),
|
|
35
|
+
): void {
|
|
36
|
+
const entry = outputs.find(
|
|
37
|
+
(o) => o.kind === "entry-point" && basename(o.path).startsWith("hydrate"),
|
|
38
|
+
);
|
|
39
|
+
if (!entry) return;
|
|
40
|
+
writeFileSync(
|
|
41
|
+
entryFile(root),
|
|
42
|
+
JSON.stringify({ hydrate: basename(entry.path) }),
|
|
43
|
+
);
|
|
44
|
+
}
|