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

cli.test.ts

356 lines13.1 KB

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