@devries-cameron20 / t3code Mirror · read-only
Fork 0

The best way to control Claude Code, Codex and more from any computer or phone

Mirrored from https://github.com/Camo67/t3code.git

Synced Nov 21, 06:00 UTC

main
ts 125 lines 4.48 KB
Raw
1 /**
2 * Seed a persistent vinext data-cache store from `dist/server` prerender
3 * artifacts.
4 *
5 * One write path for every platform: load pairs, then `sink.putText`.
6 *
7 * - Cloudflare: `Website.Vinext` build calls {@link seedPrerenderTo} with
8 * {@link kvHttpSink} (distilled KV HTTP, deploy machine).
9 * - Node / Lambda: the Redis / S3 runtime calls
10 * {@link seedStoreFromPrerenderLogged} on first cache op (artifacts
11 * ship in the image).
12 */
13 import { existsSync } from "node:fs";
14 import { createRequire } from "node:module";
15 import * as nodePath from "node:path";
16 import * as Effect from "effect/Effect";
17 import { buildVinextPrerenderKVPairs, type VinextPrerenderKVPair } from "../PrerenderCache.ts";
18 import type { DataCacheStore } from "./handler.ts";
19
20 export interface SeedSink<E = never, R = never> {
21 readonly putText: (key: string, value: string, ttlMs?: number) => Effect.Effect<unknown, E, R>;
22 }
23
24 export type LoadedPrerenderPairs = {
25 readonly pairs: ReadonlyArray<VinextPrerenderKVPair>;
26 readonly routeCount: number;
27 readonly warnings: ReadonlyArray<string>;
28 };
29
30 const resolveVinextRoot = (cwd: string): string | undefined => {
31 const projectRequire = createRequire(nodePath.join(cwd, "package.json"));
32 // vinext does not export package.json; use Node's package search directories.
33 for (const directory of projectRequire.resolve.paths("vinext") ?? []) {
34 const root = nodePath.join(directory, "vinext");
35 if (existsSync(nodePath.join(root, "package.json"))) return root;
36 }
37 return undefined;
38 };
39
40 const resolveServerDir = (cwd: string): string | undefined => {
41 const fromEnv = process.env.VINEXT_SERVER_DIR;
42 if (typeof fromEnv === "string" && fromEnv.length > 0) return fromEnv;
43 const candidates = [nodePath.join(cwd, "dist", "server"), nodePath.join(cwd, "server"), cwd];
44 for (const dir of candidates) {
45 if (existsSync(nodePath.join(dir, "vinext-prerender.json"))) return dir;
46 }
47 return undefined;
48 };
49
50 const ttlMsOf = (pair: VinextPrerenderKVPair): number | undefined =>
51 pair.expirationTtl !== undefined && pair.expirationTtl > 0
52 ? pair.expirationTtl * 1000
53 : undefined;
54
55 export const loadPrerenderPairs = async (cwd: string): Promise<LoadedPrerenderPairs> => {
56 const vinextRoot = resolveVinextRoot(cwd);
57 const serverDir = resolveServerDir(cwd);
58 if (vinextRoot === undefined || serverDir === undefined) {
59 return { pairs: [], routeCount: 0, warnings: [] };
60 }
61 return buildVinextPrerenderKVPairs(vinextRoot, serverDir);
62 };
63
64 /** Platform-agnostic seed: pairs → `sink.putText`. */
65 export const seedPrerenderTo = <E, R>(
66 sink: SeedSink<E, R>,
67 options: { readonly rootDir: string; readonly label: string },
68 ): Effect.Effect<{ readonly count: number; readonly routeCount: number }, E, R> =>
69 Effect.gen(function* () {
70 const loaded = yield* Effect.promise(() => loadPrerenderPairs(options.rootDir));
71 for (const warning of loaded.warnings) yield* Effect.logWarning(warning);
72 if (loaded.pairs.length === 0) {
73 return { count: 0, routeCount: loaded.routeCount };
74 }
75 yield* Effect.forEach(
76 loaded.pairs,
77 (pair) => sink.putText(pair.key, pair.value, ttlMsOf(pair)),
78 { concurrency: 8 },
79 );
80 yield* Effect.logInfo(
81 `[vinext] seeded ${loaded.pairs.length} prerender cache ${
82 loaded.pairs.length === 1 ? "entry" : "entries"
83 } into ${options.label} (${loaded.routeCount} route${loaded.routeCount === 1 ? "" : "s"})`,
84 );
85 return { count: loaded.pairs.length, routeCount: loaded.routeCount };
86 });
87
88 const promiseSink = (store: DataCacheStore): SeedSink => ({
89 putText: (key, value, ttlMs) =>
90 Effect.promise(() => store.getText(key)).pipe(
91 Effect.flatMap((existing) =>
92 existing === undefined
93 ? Effect.promise(() => store.putText(key, value, ttlMs))
94 : Effect.void,
95 ),
96 ),
97 });
98
99 export const seedStoreFromPrerender = async (
100 store: DataCacheStore,
101 cwd = process.cwd(),
102 ): Promise<number> => {
103 const { count } = await Effect.runPromise(
104 seedPrerenderTo(promiseSink(store), { rootDir: cwd, label: "store" }),
105 );
106 return count;
107 };
108
109 /** Await seed and log how many entries landed. Never throws. */
110 export const seedStoreFromPrerenderLogged = async (
111 store: DataCacheStore,
112 label: string,
113 cwd = process.cwd(),
114 ): Promise<number> => {
115 try {
116 const { count } = await Effect.runPromise(
117 seedPrerenderTo(promiseSink(store), { rootDir: cwd, label }),
118 );
119 return count;
120 } catch {
121 return 0;
122 }
123 };
124
125 export const _resolveForTests = { resolveVinextRoot, resolveServerDir };