Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

bin.test.ts

362 lines13.5 KB

1// @effect-diagnostics nodeBuiltinImport:off - CLI integration exercises Node HTTP and filesystem boundaries.
2import * as NodeHttp from "node:http";
3import { mkdtempSync } from "node:fs";
4import { tmpdir } from "node:os";
5import { join } from "node:path";
6​
7import * as NodeHttpServer from "@effect/platform-node/NodeHttpServer";
8import * as NodeServices from "@effect/platform-node/NodeServices";
9import * as NetService from "@t3tools/shared/Net";
10import { assert, it } from "@effect/vitest";
11import * as Effect from "effect/Effect";
12import * as Layer from "effect/Layer";
13import * as HttpRouter from "effect/unstable/http/HttpRouter";
14import * as HttpServer from "effect/unstable/http/HttpServer";
15import * as CliError from "effect/unstable/cli/CliError";
16import * as TestConsole from "effect/testing/TestConsole";
17import { Command } from "effect/unstable/cli";
18​
19import { cli } from "./bin.ts";
20import { deriveServerPaths, ServerConfig, type ServerConfigShape } from "./config.ts";
21import { ProjectionSnapshotQuery } from "./orchestration/Services/ProjectionSnapshotQuery.ts";
22import { OrchestrationLayerLive } from "./orchestration/runtimeLayer.ts";
23import {
24 orchestrationDispatchRouteLayer,
25 orchestrationSnapshotRouteLayer,
26} from "./orchestration/http.ts";
27import { layerConfig as SqlitePersistenceLayerLive } from "./persistence/Layers/Sqlite.ts";
28import { RepositoryIdentityResolverLive } from "./project/Layers/RepositoryIdentityResolver.ts";
29import {
30 makePersistedServerRuntimeState,
31 persistServerRuntimeState,
32} from "./serverRuntimeState.ts";
33import { WorkspacePathsLive } from "./workspace/Layers/WorkspacePaths.ts";
34import { ServerSecretStoreLive } from "./auth/Layers/ServerSecretStore.ts";
35import { ServerAuthLive } from "./auth/Layers/ServerAuth.ts";
36​
37const CliRuntimeLayer = Layer.mergeAll(NodeServices.layer, NetService.layer);
38​
39const runCli = (args: ReadonlyArray<string>) => Command.runWith(cli, { version: "0.0.0" })(args);
40const runCliWithRuntime = (args: ReadonlyArray<string>) =>
41 runCli(args).pipe(Effect.provide(CliRuntimeLayer));
42​
43const captureStdout = <A, E, R>(effect: Effect.Effect<A, E, R>) =>
44 Effect.gen(function* () {
45 const result = yield* effect;
46 const output =
47 (yield* TestConsole.logLines).findLast((line): line is string => typeof line === "string") ??
48 "";
49 return { result, output };
50 }).pipe(Effect.provide(Layer.mergeAll(CliRuntimeLayer, TestConsole.layer)));
51​
52const makeCliTestServerConfig = (baseDir: string) =>
53 Effect.gen(function* () {
54 const derivedPaths = yield* deriveServerPaths(baseDir, undefined);
55 return {
56 logLevel: "Info",
57 traceMinLevel: "Info",
58 traceTimingEnabled: true,
59 traceBatchWindowMs: 200,
60 traceMaxBytes: 10 * 1024 * 1024,
61 traceMaxFiles: 10,
62 otlpTracesUrl: undefined,
63 otlpMetricsUrl: undefined,
64 otlpExportIntervalMs: 10_000,
65 otlpServiceName: "t3-server",
66 mode: "web",
67 port: 0,
68 host: "127.0.0.1",
69 cwd: process.cwd(),
70 baseDir,
71 ...derivedPaths,
72 staticDir: undefined,
73 devUrl: undefined,
74 noBrowser: true,
75 startupPresentation: "browser",
76 desktopBootstrapToken: undefined,
77 autoBootstrapProjectFromCwd: false,
78 logWebSocketEvents: false,
79 tailscaleServeEnabled: false,
80 tailscaleServePort: 443,
81 } satisfies ServerConfigShape;
82 });
83​
84const makeProjectPersistenceLayer = (config: ServerConfigShape) =>
85 Layer.mergeAll(
86 OrchestrationLayerLive.pipe(
87 Layer.provideMerge(RepositoryIdentityResolverLive),
88 Layer.provideMerge(SqlitePersistenceLayerLive),
89 ),
90 WorkspacePathsLive,
91 ).pipe(
92 Layer.provideMerge(NodeServices.layer),
93 Layer.provide(Layer.succeed(ServerConfig, config)),
94 );
95​
96const readPersistedSnapshot = (baseDir: string) =>
97 Effect.gen(function* () {
98 const config = yield* makeCliTestServerConfig(baseDir);
99 return yield* Effect.gen(function* () {
100 const projectionSnapshotQuery = yield* ProjectionSnapshotQuery;
101 return yield* projectionSnapshotQuery.getSnapshot();
102 }).pipe(Effect.provide(makeProjectPersistenceLayer(config)));
103 });
104​
105const withLiveProjectCliServer = <A, E, R>(baseDir: string, run: () => Effect.Effect<A, E, R>) =>
106 Effect.gen(function* () {
107 const config = yield* makeCliTestServerConfig(baseDir);
108 const routesLayer = Layer.mergeAll(
109 orchestrationSnapshotRouteLayer,
110 orchestrationDispatchRouteLayer,
111 );
112 const appLayer = HttpRouter.serve(routesLayer, {
113 disableListenLog: true,
114 disableLogger: true,
115 }).pipe(
116 Layer.provideMerge(
117 ServerAuthLive.pipe(
118 Layer.provideMerge(SqlitePersistenceLayerLive),
119 Layer.provide(ServerSecretStoreLive),
120 ),
121 ),
122 Layer.provideMerge(makeProjectPersistenceLayer(config)),
123 Layer.provideMerge(
124 NodeHttpServer.layer(NodeHttp.createServer, {
125 host: "127.0.0.1",
126 port: 0,
127 }),
128 ),
129 Layer.provideMerge(NodeServices.layer),
130 Layer.provide(Layer.succeed(ServerConfig, config)),
131 );
132​
133 return yield* Effect.scoped(
134 Effect.gen(function* () {
135 const server = yield* HttpServer.HttpServer;
136 const address = server.address;
137 if (typeof address === "string" || !("port" in address)) {
138 assert.fail(`Expected TCP address, got ${address}`);
139 }
140 yield* persistServerRuntimeState({
141 path: config.serverRuntimeStatePath,
142 state: yield* makePersistedServerRuntimeState({
143 config,
144 port: address.port,
145 }),
146 });
147 return yield* run();
148 }).pipe(Effect.provide(Layer.mergeAll(appLayer, NodeServices.layer))),
149 );
150 });
151​
152it.layer(NodeServices.layer)("bin cli parsing", (it) => {
153 it.effect("accepts the built-in lowercase log-level flag values", () =>
154 runCliWithRuntime(["--log-level", "debug", "--version"]),
155 );
156​
157 it.effect("accepts canonical --no-<flag> boolean negation", () =>
158 runCliWithRuntime(["--no-log-websocket-events", "--version"]),
159 );
160​
161 it.effect("rejects invalid log-level casing before launching the server", () =>
162 Effect.gen(function* () {
163 const error = yield* runCliWithRuntime(["--log-level", "Debug"]).pipe(Effect.flip);
164​
165 if (!CliError.isCliError(error)) {
166 assert.fail(`Expected CliError, got ${String(error)}`);
167 }
168 if (error._tag !== "InvalidValue") {
169 assert.fail(`Expected InvalidValue, got ${error._tag}`);
170 }
171 assert.equal(error.option, "log-level");
172 assert.equal(error.value, "Debug");
173 }),
174 );
175​
176 it.effect("executes auth pairing subcommands and redacts secrets from list output", () =>
177 Effect.gen(function* () {
178 const baseDir = mkdtempSync(join(tmpdir(), "t3-cli-auth-pairing-test-"));
179​
180 const createdOutput = yield* captureStdout(
181 runCli(["auth", "pairing", "create", "--base-dir", baseDir, "--json"]),
182 );
183 // @effect-diagnostics-next-line preferSchemaOverJson:off
184 const created = JSON.parse(createdOutput.output) as {
185 readonly id: string;
186 readonly credential: string;
187 };
188 const listedOutput = yield* captureStdout(
189 runCli(["auth", "pairing", "list", "--base-dir", baseDir, "--json"]),
190 );
191 // @effect-diagnostics-next-line preferSchemaOverJson:off
192 const listed = JSON.parse(listedOutput.output) as ReadonlyArray<{
193 readonly id: string;
194 readonly credential?: string;
195 }>;
196​
197 assert.equal(typeof created.id, "string");
198 assert.equal(typeof created.credential, "string");
199 assert.equal(created.credential.length > 0, true);
200 assert.equal(listed.length, 1);
201 assert.equal(listed[0]?.id, created.id);
202 assert.equal("credential" in (listed[0] ?? {}), false);
203 }),
204 );
205​
206 it.effect("executes auth session subcommands and redacts secrets from list output", () =>
207 Effect.gen(function* () {
208 const baseDir = mkdtempSync(join(tmpdir(), "t3-cli-auth-session-test-"));
209​
210 const issuedOutput = yield* captureStdout(
211 runCli(["auth", "session", "issue", "--base-dir", baseDir, "--json"]),
212 );
213 // @effect-diagnostics-next-line preferSchemaOverJson:off
214 const issued = JSON.parse(issuedOutput.output) as {
215 readonly sessionId: string;
216 readonly token: string;
217 readonly role: string;
218 };
219 const listedOutput = yield* captureStdout(
220 runCli(["auth", "session", "list", "--base-dir", baseDir, "--json"]),
221 );
222 // @effect-diagnostics-next-line preferSchemaOverJson:off
223 const listed = JSON.parse(listedOutput.output) as ReadonlyArray<{
224 readonly sessionId: string;
225 readonly token?: string;
226 readonly role: string;
227 }>;
228​
229 assert.equal(typeof issued.sessionId, "string");
230 assert.equal(typeof issued.token, "string");
231 assert.equal(issued.role, "owner");
232 assert.equal(listed.length, 1);
233 assert.equal(listed[0]?.sessionId, issued.sessionId);
234 assert.equal(listed[0]?.role, "owner");
235 assert.equal("token" in (listed[0] ?? {}), false);
236 }),
237 );
238​
239 it.effect("rejects invalid ttl values before running auth commands", () =>
240 Effect.gen(function* () {
241 const error = yield* runCliWithRuntime(["auth", "pairing", "create", "--ttl", "soon"]).pipe(
242 Effect.flip,
243 );
244​
245 if (!CliError.isCliError(error)) {
246 assert.fail(`Expected CliError, got ${String(error)}`);
247 }
248 if (error._tag !== "ShowHelp") {
249 assert.fail(`Expected ShowHelp, got ${error._tag}`);
250 }
251 assert.deepEqual(error.commandPath, ["t3", "auth", "pairing", "create"]);
252 const ttlError = error.errors[0] as CliError.CliError | undefined;
253 if (!ttlError || ttlError._tag !== "InvalidValue") {
254 assert.fail(`Expected InvalidValue, got ${String(ttlError?._tag)}`);
255 }
256 assert.equal(ttlError.option, "ttl");
257 assert.equal(ttlError.value, "soon");
258 assert.isTrue(ttlError.message.includes("Invalid duration"));
259 assert.isTrue(ttlError.message.includes("5m, 1h, 30d, or 15 minutes"));
260 }),
261 );
262​
263 it.effect("adds, renames, and removes projects offline through the orchestration engine", () =>
264 Effect.gen(function* () {
265 const baseDir = mkdtempSync(join(tmpdir(), "t3-cli-projects-offline-test-"));
266 const workspaceRoot = mkdtempSync(join(tmpdir(), "t3-cli-projects-workspace-"));
267​
268 yield* runCliWithRuntime([
269 "project",
270 "add",
271 workspaceRoot,
272 "--title",
273 "Alpha",
274 "--base-dir",
275 baseDir,
276 ]);
277 const afterAdd = yield* readPersistedSnapshot(baseDir);
278 const addedProject = afterAdd.projects.find(
279 (project) => project.workspaceRoot === workspaceRoot && project.deletedAt === null,
280 );
281 assert.isTrue(addedProject !== undefined);
282 assert.equal(addedProject?.title, "Alpha");
283​
284 yield* runCliWithRuntime(["project", "rename", workspaceRoot, "Beta", "--base-dir", baseDir]);
285 const afterRename = yield* readPersistedSnapshot(baseDir);
286 const renamedProject = afterRename.projects.find(
287 (project) => project.id === addedProject?.id,
288 );
289 assert.equal(renamedProject?.title, "Beta");
290 assert.equal(renamedProject?.deletedAt, null);
291​
292 yield* runCliWithRuntime([
293 "project",
294 "remove",
295 addedProject?.id ?? "",
296 "--base-dir",
297 baseDir,
298 ]);
299 const afterRemove = yield* readPersistedSnapshot(baseDir);
300 const removedProject = afterRemove.projects.find(
301 (project) => project.id === addedProject?.id,
302 );
303 assert.isTrue((removedProject?.deletedAt ?? null) !== null);
304 }),
305 );
306​
307 it.effect("routes project commands through a running server when runtime state is present", () =>
308 Effect.gen(function* () {
309 const baseDir = mkdtempSync(join(tmpdir(), "t3-cli-projects-live-test-"));
310 const workspaceRoot = mkdtempSync(join(tmpdir(), "t3-cli-projects-live-workspace-"));
311​
312 yield* withLiveProjectCliServer(baseDir, () =>
313 Effect.gen(function* () {
314 yield* runCliWithRuntime([
315 "project",
316 "add",
317 workspaceRoot,
318 "--title",
319 "Live Project",
320 "--base-dir",
321 baseDir,
322 ]);
323 const projectionSnapshotQuery = yield* ProjectionSnapshotQuery;
324 const readModel = yield* projectionSnapshotQuery.getSnapshot();
325 const addedProject = readModel.projects.find(
326 (project) => project.workspaceRoot === workspaceRoot && project.deletedAt === null,
327 );
328 assert.isTrue(addedProject !== undefined);
329 assert.equal(addedProject?.title, "Live Project");
330 }),
331 );
332 }),
333 );
334​
335 it.effect("rejects dev-url on project commands", () =>
336 Effect.gen(function* () {
337 const workspaceRoot = mkdtempSync(
338 join(tmpdir(), "t3-cli-projects-unknown-option-workspace-"),
339 );
340 const error = yield* runCliWithRuntime([
341 "project",
342 "add",
343 workspaceRoot,
344 "--dev-url",
345 "http://127.0.0.1:5173",
346 ]).pipe(Effect.flip);
347​
348 if (!CliError.isCliError(error)) {
349 assert.fail(`Expected CliError, got ${String(error)}`);
350 }
351 if (error._tag !== "ShowHelp") {
352 assert.fail(`Expected ShowHelp, got ${error._tag}`);
353 }
354 assert.deepEqual(error.commandPath, ["t3", "project", "add"]);
355 const optionError = error.errors[0] as CliError.CliError | undefined;
356 if (!optionError || optionError._tag !== "UnrecognizedOption") {
357 assert.fail(`Expected UnrecognizedOption, got ${String(optionError?._tag)}`);
358 }
359 assert.equal(optionError.option, "--dev-url");
360 }),
361 );
362});