@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, 04:45 UTC

main
ts 225 lines 7.89 KB
Raw
1 import * as Effect from "effect/Effect";
2 import * as Equal from "effect/Equal";
3 import * as FileSystem from "effect/FileSystem";
4 import * as Path from "effect/Path";
5 import * as Redacted from "effect/Redacted";
6 import { havePropsChanged, isResolved } from "../Diff.ts";
7 import * as Provider from "../Provider.ts";
8 import { Resource } from "../Resource.ts";
9 import { initialCwd } from "../Util/Node.ts";
10 import { sha256Object } from "../Util/sha256.ts";
11 import {
12 CommandExecutor,
13 OutputNotFound,
14 makeCommandError,
15 type CommandRunProps,
16 } from "./Command.ts";
17 import { hashDirectory, type MemoOptions } from "./Memo.ts";
18
19 export interface BuildProps extends CommandRunProps {
20 /**
21 * The output path (file or directory) produced by the build.
22 * This path is relative to the working directory.
23 * @example "dist"
24 */
25 outdir: string;
26 /**
27 * Controls which files are hashed to decide whether the build should re-run.
28 * By default every non-gitignored file in `cwd` is hashed, plus the nearest
29 * lockfile. Provide explicit globs to narrow the scope, or set `false` to
30 * disable memoization and rebuild on every deploy.
31 *
32 * @see {@link MemoOptions}
33 * @default true
34 */
35 memo?: MemoOptions | boolean;
36 }
37
38 export interface Build extends Resource<
39 "Command.Build",
40 BuildProps,
41 {
42 /**
43 * Path to the build output, relative to the process's initial working
44 * directory (`initialCwd` — captured at startup, immune to transient
45 * chdir by tools sharing the process).
46 *
47 * Stored relative (rather than absolute) so the value is portable across
48 * machines — state written by a CI runner
49 * (`/home/runner/work/.../dist`) resolves correctly on a local laptop and
50 * vice versa. Consumers should resolve it against `initialCwd` to obtain
51 * an absolute path.
52 */
53 outdir: string;
54 hash: {
55 /**
56 * Hash of the input files that produced this build.
57 */
58 input: string | undefined;
59 /**
60 * Hash of the output files from this build.
61 */
62 output: string | undefined;
63 };
64 }
65 > {}
66
67 /**
68 * A `Build` runs a shell command that produces an output asset (a file or
69 * directory) and tracks that asset in state. Unlike `Exec`, a `Build` has an
70 * output contract: `reconcile` verifies the command actually produced `outdir`
71 * and exposes its location so downstream resources (e.g. a `Cloudflare.Worker`'s
72 * static assets) can consume it.
73 *
74 * Inputs are content-hashed by default so an unchanged project skips the
75 * rebuild entirely; set `memo: false` to rebuild on every deploy.
76 *
77 * ### Building a Vite App
78 * **Example:** Basic Vite Build
79 * ```typescript
80 * const build = yield* Build("vite-build", {
81 * command: "npm run build",
82 * cwd: "./frontend",
83 * outdir: "dist",
84 * });
85 * yield* Console.log(build.outdir); // path to the dist directory, relative to the initial cwd
86 * yield* Console.log(build.hash.output); // hash of the output files (when memo is enabled)
87 * ```
88 *
89 * ### Building with Custom Environment
90 * **Example:** Build with Environment Variables
91 * ```typescript
92 * const build = yield* Build("production-build", {
93 * command: "npm run build",
94 * cwd: "./app",
95 * outdir: "dist",
96 * env: {
97 * NODE_ENV: "production",
98 * API_URL: "https://api.example.com",
99 * },
100 * });
101 * ```
102 *
103 * ### Customizing Memoization
104 * **Example:** Customize Memoization
105 * ```typescript
106 * const build = yield* Build("custom-build", {
107 * command: "npm run build",
108 * cwd: "./app",
109 * outdir: "dist",
110 * memo: { include: ["src/**", "package.json"], exclude: ["node_modules", "dist"] },
111 * });
112 * ```
113 *
114 * @resource
115 */
116 export const Build = Resource<Build>("Command.Build");
117
118 /**
119 * Resolves `Redacted` env values to their plain string so that a change in a
120 * secret's value still busts the memo hash (the hash is one-way, so the secret
121 * itself is never recoverable from state). `undefined`-valued entries are
122 * dropped (they mean "unset").
123 */
124 const resolveEnv = (env: CommandRunProps["env"]) =>
125 env
126 ? Object.fromEntries(
127 Object.entries(env)
128 .filter(
129 (entry): entry is [string, string | Redacted.Redacted<string>] =>
130 entry[1] !== undefined,
131 )
132 .map(([key, value]) => [key, Redacted.isRedacted(value) ? Redacted.value(value) : value]),
133 )
134 : undefined;
135
136 export const BuildProvider = () =>
137 Provider.effect(
138 Build,
139 Effect.gen(function* () {
140 const path = yield* Path.Path;
141 const fs = yield* FileSystem.FileSystem;
142 const { run } = yield* CommandExecutor;
143
144 const makeOutput = Effect.fn(function* (props: BuildProps) {
145 // Anchored to the initial cwd: a live `process.cwd()` read can race
146 // a concurrent tool's transient chdir (framework source builds),
147 // and the relative `outdir` stored here is resolved again later
148 // (assets read) — mismatched bases corrupt the path.
149 const cwd = path.resolve(initialCwd, props.cwd ?? ".");
150 const outdir = path.resolve(cwd, props.outdir);
151 if (!(yield* fs.exists(outdir))) {
152 return yield* makeCommandError(
153 props,
154 new OutputNotFound({
155 outdir: props.outdir,
156 }),
157 );
158 }
159 return {
160 outdir: path.relative(initialCwd, outdir),
161 hash:
162 props.memo === false
163 ? { input: undefined, output: undefined }
164 : yield* Effect.all(
165 {
166 // Fold the resolved command + env into the input hash so
167 // two builds that share the same source tree + `outdir`
168 // but differ in their command or environment (e.g.
169 // per-stage builds baking different `EXPO_PUBLIC_*` /
170 // API ids) are never judged reusable. Without this the
171 // second build silently reuses the first's stale output.
172 input: hashDirectory({
173 cwd,
174 memo: props.memo === true ? {} : props.memo,
175 }).pipe(
176 Effect.flatMap((files) =>
177 sha256Object({
178 files,
179 command: props.command,
180 env: resolveEnv(props.env),
181 }),
182 ),
183 ),
184 output: hashDirectory({
185 cwd: outdir,
186 memo: {
187 exclude: [],
188 lockfile: false,
189 },
190 }),
191 },
192 { concurrency: "unbounded" },
193 ),
194 };
195 });
196
197 return {
198 list: () => Effect.succeed([]),
199 diff: Effect.fn(function* ({ olds, news, output }) {
200 if (!output || !isResolved(news)) return undefined;
201
202 // Always update if memoization is disabled or hashes are not available.
203 if (news.memo === false || !output.hash.input || !output.hash.output)
204 return { action: "update" };
205
206 // Optimization: short-circuit if props have changed to avoid unnecessary file system operations.
207 if (havePropsChanged(olds, news)) return { action: "update" };
208
209 const newOutput = yield* makeOutput(news).pipe(
210 Effect.catchReason("CommandError", "OutputNotFound", () => Effect.undefined),
211 );
212 return {
213 action: Equal.equals(newOutput, output) ? "noop" : "update",
214 };
215 }),
216 reconcile: ({ news, session }) => run(news, session).pipe(Effect.andThen(makeOutput(news))),
217 delete: Effect.fn(function* ({ output }) {
218 // `output.outdir` is persisted relative to the initial cwd.
219 const outdir = path.resolve(initialCwd, output.outdir);
220 if (!(yield* fs.exists(outdir))) return;
221 yield* fs.remove(outdir, { recursive: true });
222 }),
223 };
224 }),
225 );