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

bin.test.ts

274 lines10.3 KB

1// @effect-diagnostics-next-line nodeBuiltinImport:off
2import { mkdtempSync } from "node:fs";
3import { tmpdir } from "node:os";
4// @effect-diagnostics-next-line nodeBuiltinImport:off
5import { join } from "node:path";
6​
7import * as NodeServices from "@effect/platform-node/NodeServices";
8import * as 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 CliError from "effect/unstable/cli/CliError";
13import * as TestConsole from "effect/testing/TestConsole";
14import { Command } from "effect/unstable/cli";
15​
16import { cli } from "./bin.ts";
17import { deriveServerPaths, ServerConfig, type ServerConfigShape } from "./config.ts";
18import { ProjectionSnapshotQuery } from "./orchestration/Services/ProjectionSnapshotQuery.ts";
19import { OrchestrationLayerLive } from "./orchestration/runtimeLayer.ts";
20import { layerConfig as SqlitePersistenceLayerLive } from "./persistence/Layers/Sqlite.ts";
21import { RepositoryIdentityResolverLive } from "./project/Layers/RepositoryIdentityResolver.ts";
22import { WorkspacePathsLive } from "./workspace/Layers/WorkspacePaths.ts";
23​
24const CliRuntimeLayer = Layer.mergeAll(NodeServices.layer, NetService.layer);
25​
26const runCli = (args: ReadonlyArray<string>) => Command.runWith(cli, { version: "0.0.0" })(args);
27const runCliWithRuntime = (args: ReadonlyArray<string>) =>
28 runCli(args).pipe(Effect.provide(CliRuntimeLayer));
29​
30const captureStdout = <A, E, R>(effect: Effect.Effect<A, E, R>) =>
31 Effect.gen(function* () {
32 const result = yield* effect;
33 const output =
34 (yield* TestConsole.logLines).findLast((line): line is string => typeof line === "string") ??
35 "";
36 return { result, output };
37 }).pipe(Effect.provide(Layer.mergeAll(CliRuntimeLayer, TestConsole.layer)));
38​
39const makeCliTestServerConfig = (baseDir: string) =>
40 Effect.gen(function* () {
41 const derivedPaths = yield* deriveServerPaths(baseDir, undefined);
42 return {
43 logLevel: "Info",
44 traceMinLevel: "Info",
45 traceTimingEnabled: true,
46 traceBatchWindowMs: 200,
47 traceMaxBytes: 10 * 1024 * 1024,
48 traceMaxFiles: 10,
49 otlpTracesUrl: undefined,
50 otlpMetricsUrl: undefined,
51 otlpExportIntervalMs: 10_000,
52 otlpServiceName: "t3-server",
53 mode: "web",
54 port: 0,
55 host: "127.0.0.1",
56 cwd: process.cwd(),
57 baseDir,
58 ...derivedPaths,
59 staticDir: undefined,
60 devUrl: undefined,
61 noBrowser: true,
62 startupPresentation: "browser",
63 desktopBootstrapToken: undefined,
64 autoBootstrapProjectFromCwd: false,
65 logWebSocketEvents: false,
66 tailscaleServeEnabled: false,
67 tailscaleServePort: 443,
68 } satisfies ServerConfigShape;
69 });
70​
71const makeProjectPersistenceLayer = (config: ServerConfigShape) =>
72 Layer.mergeAll(
73 OrchestrationLayerLive.pipe(
74 Layer.provideMerge(RepositoryIdentityResolverLive),
75 Layer.provideMerge(SqlitePersistenceLayerLive),
76 ),
77 WorkspacePathsLive,
78 ).pipe(
79 Layer.provideMerge(NodeServices.layer),
80 Layer.provide(Layer.succeed(ServerConfig, config)),
81 );
82​
83const readPersistedSnapshot = (baseDir: string) =>
84 Effect.gen(function* () {
85 const config = yield* makeCliTestServerConfig(baseDir);
86 return yield* Effect.gen(function* () {
87 const projectionSnapshotQuery = yield* ProjectionSnapshotQuery;
88 return yield* projectionSnapshotQuery.getSnapshot();
89 }).pipe(Effect.provide(makeProjectPersistenceLayer(config)));
90 });
91​
92it.layer(NodeServices.layer)("bin cli parsing", (it) => {
93 it.effect("accepts the built-in lowercase log-level flag values", () =>
94 runCliWithRuntime(["--log-level", "debug", "--version"]),
95 );
96​
97 it.effect("accepts canonical --no-<flag> boolean negation", () =>
98 runCliWithRuntime(["--no-log-websocket-events", "--version"]),
99 );
100​
101 it.effect("rejects invalid log-level casing before launching the server", () =>
102 Effect.gen(function* () {
103 const error = yield* runCliWithRuntime(["--log-level", "Debug"]).pipe(Effect.flip);
104​
105 if (!CliError.isCliError(error)) {
106 assert.fail(`Expected CliError, got ${String(error)}`);
107 }
108 if (error._tag !== "InvalidValue") {
109 assert.fail(`Expected InvalidValue, got ${error._tag}`);
110 }
111 assert.equal(error.option, "log-level");
112 assert.equal(error.value, "Debug");
113 }),
114 );
115​
116 it.effect("executes auth pairing subcommands and redacts secrets from list output", () =>
117 Effect.gen(function* () {
118 const baseDir = mkdtempSync(join(tmpdir(), "t3-cli-auth-pairing-test-"));
119​
120 const createdOutput = yield* captureStdout(
121 runCli(["auth", "pairing", "create", "--base-dir", baseDir, "--json"]),
122 );
123 // @effect-diagnostics-next-line preferSchemaOverJson:off
124 const created = JSON.parse(createdOutput.output) as {
125 readonly id: string;
126 readonly credential: string;
127 };
128 const listedOutput = yield* captureStdout(
129 runCli(["auth", "pairing", "list", "--base-dir", baseDir, "--json"]),
130 );
131 // @effect-diagnostics-next-line preferSchemaOverJson:off
132 const listed = JSON.parse(listedOutput.output) as ReadonlyArray<{
133 readonly id: string;
134 readonly credential?: string;
135 }>;
136​
137 assert.equal(typeof created.id, "string");
138 assert.equal(typeof created.credential, "string");
139 assert.equal(created.credential.length > 0, true);
140 assert.equal(listed.length, 1);
141 assert.equal(listed[0]?.id, created.id);
142 assert.equal("credential" in (listed[0] ?? {}), false);
143 }),
144 );
145​
146 it.effect("executes auth session subcommands and redacts secrets from list output", () =>
147 Effect.gen(function* () {
148 const baseDir = mkdtempSync(join(tmpdir(), "t3-cli-auth-session-test-"));
149​
150 const issuedOutput = yield* captureStdout(
151 runCli(["auth", "session", "issue", "--base-dir", baseDir, "--json"]),
152 );
153 // @effect-diagnostics-next-line preferSchemaOverJson:off
154 const issued = JSON.parse(issuedOutput.output) as {
155 readonly sessionId: string;
156 readonly token: string;
157 readonly role: string;
158 };
159 const listedOutput = yield* captureStdout(
160 runCli(["auth", "session", "list", "--base-dir", baseDir, "--json"]),
161 );
162 // @effect-diagnostics-next-line preferSchemaOverJson:off
163 const listed = JSON.parse(listedOutput.output) as ReadonlyArray<{
164 readonly sessionId: string;
165 readonly token?: string;
166 readonly role: string;
167 }>;
168​
169 assert.equal(typeof issued.sessionId, "string");
170 assert.equal(typeof issued.token, "string");
171 assert.equal(issued.role, "owner");
172 assert.equal(listed.length, 1);
173 assert.equal(listed[0]?.sessionId, issued.sessionId);
174 assert.equal(listed[0]?.role, "owner");
175 assert.equal("token" in (listed[0] ?? {}), false);
176 }),
177 );
178​
179 it.effect("rejects invalid ttl values before running auth commands", () =>
180 Effect.gen(function* () {
181 const error = yield* runCliWithRuntime(["auth", "pairing", "create", "--ttl", "soon"]).pipe(
182 Effect.flip,
183 );
184​
185 if (!CliError.isCliError(error)) {
186 assert.fail(`Expected CliError, got ${String(error)}`);
187 }
188 if (error._tag !== "ShowHelp") {
189 assert.fail(`Expected ShowHelp, got ${error._tag}`);
190 }
191 assert.deepEqual(error.commandPath, ["t3", "auth", "pairing", "create"]);
192 const ttlError = error.errors[0] as CliError.CliError | undefined;
193 if (!ttlError || ttlError._tag !== "InvalidValue") {
194 assert.fail(`Expected InvalidValue, got ${String(ttlError?._tag)}`);
195 }
196 assert.equal(ttlError.option, "ttl");
197 assert.equal(ttlError.value, "soon");
198 assert.isTrue(ttlError.message.includes("Invalid duration"));
199 assert.isTrue(ttlError.message.includes("5m, 1h, 30d, or 15 minutes"));
200 }),
201 );
202​
203 it.effect("adds, renames, and removes projects offline through the orchestration engine", () =>
204 Effect.gen(function* () {
205 const baseDir = mkdtempSync(join(tmpdir(), "t3-cli-projects-offline-test-"));
206 const workspaceRoot = mkdtempSync(join(tmpdir(), "t3-cli-projects-workspace-"));
207​
208 yield* runCliWithRuntime([
209 "project",
210 "add",
211 workspaceRoot,
212 "--title",
213 "Alpha",
214 "--base-dir",
215 baseDir,
216 ]);
217 const afterAdd = yield* readPersistedSnapshot(baseDir);
218 const addedProject = afterAdd.projects.find(
219 (project) => project.workspaceRoot === workspaceRoot && project.deletedAt === null,
220 );
221 assert.isTrue(addedProject !== undefined);
222 assert.equal(addedProject?.title, "Alpha");
223​
224 yield* runCliWithRuntime(["project", "rename", workspaceRoot, "Beta", "--base-dir", baseDir]);
225 const afterRename = yield* readPersistedSnapshot(baseDir);
226 const renamedProject = afterRename.projects.find(
227 (project) => project.id === addedProject?.id,
228 );
229 assert.equal(renamedProject?.title, "Beta");
230 assert.equal(renamedProject?.deletedAt, null);
231​
232 yield* runCliWithRuntime([
233 "project",
234 "remove",
235 addedProject?.id ?? "",
236 "--base-dir",
237 baseDir,
238 ]);
239 const afterRemove = yield* readPersistedSnapshot(baseDir);
240 const removedProject = afterRemove.projects.find(
241 (project) => project.id === addedProject?.id,
242 );
243 assert.isTrue((removedProject?.deletedAt ?? null) !== null);
244 }),
245 );
246​
247 it.effect("rejects dev-url on project commands", () =>
248 Effect.gen(function* () {
249 const workspaceRoot = mkdtempSync(
250 join(tmpdir(), "t3-cli-projects-unknown-option-workspace-"),
251 );
252 const error = yield* runCliWithRuntime([
253 "project",
254 "add",
255 workspaceRoot,
256 "--dev-url",
257 "http://127.0.0.1:5173",
258 ]).pipe(Effect.flip);
259​
260 if (!CliError.isCliError(error)) {
261 assert.fail(`Expected CliError, got ${String(error)}`);
262 }
263 if (error._tag !== "ShowHelp") {
264 assert.fail(`Expected ShowHelp, got ${error._tag}`);
265 }
266 assert.deepEqual(error.commandPath, ["t3", "project", "add"]);
267 const optionError = error.errors[0] as CliError.CliError | undefined;
268 if (!optionError || optionError._tag !== "UnrecognizedOption") {
269 assert.fail(`Expected UnrecognizedOption, got ${String(optionError?._tag)}`);
270 }
271 assert.equal(optionError.option, "--dev-url");
272 }),
273 );
274});