Open History to see the last commit
1// @effect-diagnostics nodeBuiltinImport:off -- Runs before loading the Effect CLI or server graph.
2import * as NodeFS from "node:fs";
3import * as NodeModule from "node:module";
4import * as NodeOS from "node:os";
5import * as NodePath from "node:path";
6
7const UNUSED_VERSION_MAX_AGE_MS = 7 * 24 * 60 * 60 * 1000;
8
9/** Cache bundled code under the selected T3 home; leave source dev uncached. */
10export function enableCliCompileCache(input: {
11 readonly bundled: boolean;
12 readonly argv: readonly string[];
13 readonly environment: NodeJS.ProcessEnv;
14 readonly version: string;
15}) {
16 if (
17 !input.bundled ||
18 // AppImage mount paths change each launch, so path-keyed entries never hit.
19 input.environment.APPIMAGE ||
20 input.environment.NODE_DISABLE_COMPILE_CACHE === "1" ||
21 input.environment.NODE_COMPILE_CACHE
22 )
23 return;
24 const index = input.argv.indexOf("--base-dir");
25 const configured =
26 (index >= 0 ? input.argv[index + 1] : undefined) ??
27 input.argv
28 .find((argument) => argument.startsWith("--base-dir="))
29 ?.slice("--base-dir=".length) ??
30 input.environment.T3CODE_HOME;
31 const home = NodeOS.homedir();
32 const base = configured?.trim();
33 const directory = !base
34 ? NodePath.join(home, ".t3")
35 : base === "~"
36 ? home
37 : base.startsWith("~/") || base.startsWith("~\\")
38 ? NodePath.join(home, base.slice(2))
39 : NodePath.resolve(base);
40 const root = NodePath.join(directory, "compile-cache");
41 // Cache failures never prevent CLI or server startup, including a read-only home.
42 try {
43 const current = NodePath.join(root, input.version);
44 const { status } = NodeModule.enableCompileCache(current);
45 if (status !== NodeModule.constants.compileCacheStatus.ENABLED) return;
46 // Other installed versions share this home; remove only caches unused for a week.
47 // @effect-diagnostics-next-line globalDate:off -- Runs before the Effect runtime loads.
48 const now = new Date();
49 NodeFS.utimes(current, now, now, () => {});
50 const cutoff = now.getTime() - UNUSED_VERSION_MAX_AGE_MS;
51 for (const entry of NodeFS.readdirSync(root)) {
52 if (entry === input.version) continue;
53 const path = NodePath.join(root, entry);
54 NodeFS.stat(path, (error, stats) => {
55 if (error === null && stats.mtimeMs < cutoff) {
56 NodeFS.rm(path, { recursive: true, force: true }, () => {});
57 }
58 });
59 }
60 } catch {}
61}