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

theme.test.ts

456 lines18.1 KB

1// @effect-diagnostics nodeBuiltinImport:off - CLI integration exercises the filesystem boundary.
2import * as NodeFS from "node:fs";
3import * as NodeOS from "node:os";
4import * as NodePath from "node:path";
5​
6import * as NodeCrypto from "@effect/platform-node/NodeCrypto";
7import * as NodeServices from "@effect/platform-node/NodeServices";
8import * as NetService from "@t3tools/shared/Net";
9import { assert, describe, it } from "@effect/vitest";
10import * as ConfigProvider from "effect/ConfigProvider";
11import * as Effect from "effect/Effect";
12import * as Layer from "effect/Layer";
13import * as TestConsole from "effect/testing/TestConsole";
14import { Command } from "effect/cli";
15import { lock } from "proper-lockfile";
16import { vi } from "vite-plus/test";
17​
18import { cli } from "../binCli.ts";
19import { symlinksSupported } from "@t3tools/shared/testing/symlinks";
20import * as HostProcess from "@t3tools/shared/HostProcess";
21​
22vi.mock("node:fs", { spy: true });
23​
24// Windows chmod cannot force these directory or file permission failures.
25const windowsHost = HostProcess.Platform.defaultValue() === "win32";
26​
27const runCli = (args: ReadonlyArray<string>) =>
28 Command.runWith(cli, { version: "0.0.0" })(args).pipe(
29 Effect.provide(
30 Layer.mergeAll(NodeServices.layer, NodeCrypto.layer, NetService.layer, TestConsole.layer),
31 ),
32 );
33​
34const runCliIn = (cwd: string, args: ReadonlyArray<string>) =>
35 Effect.acquireUseRelease(
36 Effect.sync(() => {
37 const previous = process.cwd();
38 process.chdir(cwd);
39 return previous;
40 }),
41 () => runCli(args),
42 (previous) => Effect.sync(() => process.chdir(previous)),
43 );
44​
45const makeBaseDir = () => NodeFS.mkdtempSync(NodePath.join(NodeOS.tmpdir(), "t3code-theme-cli-"));
46​
47const settingsPathFor = (baseDir: string) => NodePath.join(baseDir, "userdata", "settings.json");
48​
49const NIGHTFALL_THEME_JSON = `${JSON.stringify({
50 name: "Nightfall",
51 appearance: "dark",
52 canvas: "#1a1b26",
53 accent: "#7aa2f7",
54})}\n`;
55const JUNK_THEME_JSON = `${JSON.stringify({ name: "Junk" })}\n`;
56​
57const readSettings = (baseDir: string): Record<string, unknown> => {
58 const raw = NodeFS.readFileSync(settingsPathFor(baseDir), "utf8");
59 return JSON.parse(raw) as Record<string, unknown>;
60};
61​
62const writeSettings = (baseDir: string, settings: Record<string, unknown>) => {
63 NodeFS.mkdirSync(NodePath.dirname(settingsPathFor(baseDir)), { recursive: true });
64 NodeFS.writeFileSync(settingsPathFor(baseDir), `${JSON.stringify(settings, null, 2)}\n`);
65};
66​
67describe("t3 theme", () => {
68 it.effect("preserves settings it does not recognise", () =>
69 Effect.gen(function* () {
70 const baseDir = makeBaseDir();
71 writeSettings(baseDir, {
72 enableProviderUpdateChecks: false,
73 somethingFromANewerBuild: { nested: true },
74 });
75​
76 yield* runCli(["theme", "set", "ocean", "--base-dir", baseDir]);
77​
78 const settings = readSettings(baseDir);
79 assert.equal(settings.defaultTheme, "ocean");
80 assert.equal(settings.enableProviderUpdateChecks, false);
81 assert.deepEqual(settings.somethingFromANewerBuild, { nested: true });
82 }),
83 );
84​
85 it.effect("clears the default back to leaving fresh clients alone", () =>
86 Effect.gen(function* () {
87 const baseDir = makeBaseDir();
88 writeSettings(baseDir, { enableProviderUpdateChecks: false });
89​
90 yield* runCli(["theme", "set", "ocean", "--base-dir", baseDir]);
91 yield* runCli(["theme", "clear", "--base-dir", baseDir]);
92​
93 const settings = readSettings(baseDir);
94 assert.equal(Object.hasOwn(settings, "defaultTheme"), false);
95 assert.equal(settings.enableProviderUpdateChecks, false);
96 }),
97 );
98​
99 it.effect("sets the theme of a dev server running in the default home", () =>
100 Effect.gen(function* () {
101 const home = makeBaseDir();
102 const devStateDir = NodePath.join(home, ".t3", "dev");
103 NodeFS.mkdirSync(devStateDir, { recursive: true });
104 NodeFS.writeFileSync(
105 NodePath.join(devStateDir, "server-runtime.json"),
106 `${JSON.stringify({
107 version: 1,
108 pid: process.pid,
109 port: 4888,
110 origin: "http://127.0.0.1:4888",
111 devUrl: "http://127.0.0.1:5999",
112 startedAt: "1970-01-01T00:00:00.000Z",
113 })}\n`,
114 );
115​
116 const result = yield* runCli(["theme", "set", "ocean"]).pipe(
117 Effect.provideService(HostProcess.HomeDirectory, home),
118 Effect.provide(ConfigProvider.layer(ConfigProvider.fromEnv({ env: {} }))),
119 Effect.result,
120 );
121​
122 assert.equal(
123 NodeFS.existsSync(NodePath.join(home, ".t3", "userdata", "settings.json")),
124 false,
125 );
126 if (result._tag === "Success") {
127 const devSettings = NodePath.join(devStateDir, "settings.json");
128 assert.equal(JSON.parse(NodeFS.readFileSync(devSettings, "utf8")).defaultTheme, "ocean");
129 }
130 }),
131 );
132​
133 it.effect.each([
134 { extension: "json", relativePath: null },
135 { extension: "JSON", relativePath: "nightfall.JSON" },
136 ])(
137 "publishes a .$extension theme file under its filename and sets it",
138 ({ extension, relativePath }) =>
139 Effect.gen(function* () {
140 const baseDir = makeBaseDir();
141 const themeFile = NodePath.join(baseDir, `nightfall.${extension}`);
142 NodeFS.writeFileSync(themeFile, NIGHTFALL_THEME_JSON);
143​
144 yield* runCliIn(baseDir, [
145 "theme",
146 "set",
147 relativePath ?? themeFile,
148 "--base-dir",
149 baseDir,
150 ]);
151​
152 const published = NodePath.join(baseDir, "userdata", "themes", "nightfall.json");
153 assert.equal(NodeFS.readFileSync(published, "utf8"), NIGHTFALL_THEME_JSON);
154 assert.equal(readSettings(baseDir).defaultTheme, "nightfall");
155 const residue = NodeFS.readdirSync(NodePath.dirname(published)).filter(
156 (entry) => !entry.endsWith(".json"),
157 );
158 assert.deepEqual(residue, []);
159 }),
160 );
161​
162 it.effect("publishes the file named with a leading space, not its trimmed sibling", () =>
163 Effect.gen(function* () {
164 const baseDir = makeBaseDir();
165 NodeFS.mkdirSync(NodePath.join(baseDir, " palettes"));
166 NodeFS.mkdirSync(NodePath.join(baseDir, "palettes"));
167 NodeFS.writeFileSync(
168 NodePath.join(baseDir, " palettes", "nightfall.json"),
169 NIGHTFALL_THEME_JSON,
170 );
171 NodeFS.writeFileSync(NodePath.join(baseDir, "palettes", "nightfall.json"), JUNK_THEME_JSON);
172​
173 yield* runCliIn(baseDir, ["theme", "set", " palettes/nightfall.json", "--base-dir", "."]);
174​
175 const published = NodePath.join(baseDir, "userdata", "themes", "nightfall.json");
176 assert.equal(NodeFS.readFileSync(published, "utf8"), NIGHTFALL_THEME_JSON);
177 assert.equal(readSettings(baseDir).defaultTheme, "nightfall");
178 }),
179 );
180​
181 it.effect("refuses --id with a theme id, which has no file to publish", () =>
182 Effect.gen(function* () {
183 const baseDir = makeBaseDir();
184​
185 const exit = yield* runCli([
186 "theme",
187 "set",
188 "ocean",
189 "--id",
190 "nightfall",
191 "--base-dir",
192 baseDir,
193 ]).pipe(Effect.exit);
194​
195 assert.equal(exit._tag, "Failure");
196 assert.include(String(exit), "--id");
197 assert.equal(NodeFS.existsSync(settingsPathFor(baseDir)), false);
198 }),
199 );
200​
201 // Win32 resolves both names to one file.
202 it.effect.skipIf(windowsHost)("publishes a file whose name ends in a space", () =>
203 Effect.gen(function* () {
204 const baseDir = makeBaseDir();
205 NodeFS.writeFileSync(NodePath.join(baseDir, "nightfall.json "), NIGHTFALL_THEME_JSON);
206 NodeFS.writeFileSync(NodePath.join(baseDir, "nightfall.json"), JUNK_THEME_JSON);
207​
208 yield* runCliIn(baseDir, [
209 "theme",
210 "set",
211 "nightfall.json ",
212 "--id",
213 "nightfall",
214 "--base-dir",
215 ".",
216 ]);
217​
218 const published = NodePath.join(baseDir, "userdata", "themes", "nightfall.json");
219 assert.equal(NodeFS.readFileSync(published, "utf8"), NIGHTFALL_THEME_JSON);
220 }),
221 );
222​
223 // Simulates Win32 on other hosts; on Windows itself the two fixtures would be one file.
224 it.effect.skipIf(windowsHost)("drops trailing spaces from the path on Windows", () =>
225 Effect.gen(function* () {
226 const baseDir = makeBaseDir();
227 const themeFile = NodePath.join(baseDir, "nightfall.json");
228 NodeFS.writeFileSync(themeFile, NIGHTFALL_THEME_JSON);
229 NodeFS.writeFileSync(`${themeFile} `, JUNK_THEME_JSON);
230​
231 yield* runCli(["theme", "set", `${themeFile} `, "--base-dir", baseDir]).pipe(
232 Effect.provideService(HostProcess.Platform, "win32"),
233 );
234​
235 const published = NodePath.join(baseDir, "userdata", "themes", "nightfall.json");
236 assert.equal(NodeFS.readFileSync(published, "utf8"), NIGHTFALL_THEME_JSON);
237 }),
238 );
239​
240 it.effect("still trims a path that only names a file once trimmed", () =>
241 Effect.gen(function* () {
242 const baseDir = makeBaseDir();
243 const themeFile = NodePath.join(baseDir, "palettes", "nightfall.json");
244 NodeFS.mkdirSync(NodePath.dirname(themeFile));
245 NodeFS.writeFileSync(themeFile, NIGHTFALL_THEME_JSON);
246 NodeFS.mkdirSync(NodePath.join(baseDir, " palettes", "nightfall.json"), { recursive: true });
247​
248 yield* runCliIn(baseDir, ["theme", "set", " palettes/nightfall.json", "--base-dir", "."]);
249 assert.equal(readSettings(baseDir).defaultTheme, "nightfall");
250 }),
251 );
252​
253 it.effect("refuses to publish over a directory with the theme's file name", () =>
254 Effect.gen(function* () {
255 const baseDir = makeBaseDir();
256 const taken = NodePath.join(baseDir, "userdata", "themes", "nightfall.json");
257 NodeFS.mkdirSync(taken, { recursive: true });
258 NodeFS.writeFileSync(NodePath.join(taken, "notes.txt"), "notes");
259 const themeFile = NodePath.join(baseDir, "nightfall.json");
260 NodeFS.writeFileSync(themeFile, NIGHTFALL_THEME_JSON);
261​
262 const failure = yield* runCli(["theme", "set", themeFile, "--base-dir", baseDir]).pipe(
263 Effect.flip,
264 );
265​
266 assert.include(String(failure), "is a directory");
267 assert.equal(NodeFS.readFileSync(NodePath.join(taken, "notes.txt"), "utf8"), "notes");
268 assert.deepEqual(NodeFS.readdirSync(NodePath.dirname(taken)), ["nightfall.json"]);
269 assert.equal(NodeFS.existsSync(settingsPathFor(baseDir)), false);
270 }),
271 );
272​
273 it.effect("refuses to publish over a directory created just before backup", () =>
274 Effect.gen(function* () {
275 const baseDir = makeBaseDir();
276 const themeFile = NodePath.join(baseDir, "nightfall.json");
277 NodeFS.writeFileSync(themeFile, NIGHTFALL_THEME_JSON);
278 const themesDir = NodePath.join(baseDir, "userdata", "themes");
279 const destination = NodePath.join(themesDir, "nightfall.json");
280 const notes = NodePath.join(destination, "notes.txt");
281 const { renameSync } = yield* Effect.promise(() => vi.importActual<typeof NodeFS>("node:fs"));
282 using _insertDirectory = vi.spyOn(NodeFS, "renameSync").mockImplementationOnce((from, to) => {
283 NodeFS.mkdirSync(destination);
284 NodeFS.writeFileSync(notes, "notes");
285 renameSync(from, to);
286 });
287​
288 const failure = yield* runCli(["theme", "set", themeFile, "--base-dir", baseDir]).pipe(
289 Effect.flip,
290 );
291​
292 assert.include(String(failure), "is a directory");
293 assert.equal(NodeFS.readFileSync(notes, "utf8"), "notes");
294 assert.deepEqual(NodeFS.readdirSync(themesDir), ["nightfall.json"]);
295 assert.equal(NodeFS.existsSync(settingsPathFor(baseDir)), false);
296 }),
297 );
298​
299 it.effect("publishes a theme despite a rollback file left by an earlier process", () =>
300 Effect.gen(function* () {
301 const baseDir = makeBaseDir();
302 const themeFile = NodePath.join(baseDir, "nightfall.json");
303 NodeFS.writeFileSync(themeFile, NIGHTFALL_THEME_JSON);
304 const themesDir = NodePath.join(baseDir, "userdata", "themes");
305 const destination = NodePath.join(themesDir, "nightfall.json");
306 const staleBackup = `${destination}.rollback-${process.pid}`;
307 NodeFS.mkdirSync(themesDir, { recursive: true });
308 NodeFS.writeFileSync(staleBackup, "previous theme");
309​
310 yield* runCli(["theme", "set", themeFile, "--base-dir", baseDir]);
311​
312 assert.equal(readSettings(baseDir).defaultTheme, "nightfall");
313 assert.equal(NodeFS.readFileSync(destination, "utf8"), NIGHTFALL_THEME_JSON);
314 assert.equal(NodeFS.readFileSync(staleBackup, "utf8"), "previous theme");
315 assert.deepEqual(NodeFS.readdirSync(themesDir).sort(), [
316 "nightfall.json",
317 NodePath.basename(staleBackup),
318 ]);
319 }),
320 );
321​
322 it.effect.each(["aa-first", "zz-last"])(
323 "refuses to publish %s into a full theme catalog",
324 (themeId) =>
325 Effect.gen(function* () {
326 const baseDir = makeBaseDir();
327 const themesDir = NodePath.join(baseDir, "userdata", "themes");
328 const existingThemes = Array.from(
329 { length: 32 },
330 (_, index) => `theme-${String(index).padStart(2, "0")}.json`,
331 );
332 const previousSettings = {
333 defaultTheme: "theme-31",
334 defaultThemeSetAt: "2026-01-01T00:00:00Z",
335 };
336 writeSettings(baseDir, previousSettings);
337 NodeFS.mkdirSync(themesDir);
338 for (const filename of existingThemes) {
339 NodeFS.writeFileSync(NodePath.join(themesDir, filename), NIGHTFALL_THEME_JSON);
340 }
341 const themeFile = NodePath.join(baseDir, `${themeId}.json`);
342 NodeFS.writeFileSync(themeFile, NIGHTFALL_THEME_JSON);
343​
344 const outcome = yield* runCli(["theme", "set", themeFile, "--base-dir", baseDir]).pipe(
345 Effect.match({ onFailure: String, onSuccess: () => "theme set succeeded" }),
346 );
347​
348 assert.include(outcome, `Theme "${themeId}" could not be published.`);
349 assert.deepEqual(NodeFS.readdirSync(themesDir).sort(), existingThemes);
350 assert.deepEqual(readSettings(baseDir), previousSettings);
351 }),
352 );
353​
354 it.effect("keeps the theme catalog and settings when another publisher holds the lock", () =>
355 Effect.gen(function* () {
356 const baseDir = makeBaseDir();
357 const themesDir = NodePath.join(baseDir, "userdata", "themes");
358 const previousSettings = { defaultTheme: "original" };
359 writeSettings(baseDir, previousSettings);
360 NodeFS.mkdirSync(themesDir);
361 NodeFS.writeFileSync(NodePath.join(themesDir, "original.json"), NIGHTFALL_THEME_JSON);
362 const themeFile = NodePath.join(baseDir, "nightfall.json");
363 NodeFS.writeFileSync(themeFile, NIGHTFALL_THEME_JSON);
364​
365 const outcome = yield* Effect.acquireUseRelease(
366 Effect.promise(() =>
367 lock(themesDir, { lockfilePath: NodePath.join(themesDir, ".t3-theme-publish.lock") }),
368 ),
369 () =>
370 runCli(["theme", "set", themeFile, "--base-dir", baseDir]).pipe(
371 Effect.match({ onFailure: String, onSuccess: () => "theme set succeeded" }),
372 ),
373 (release) => Effect.promise(() => release()),
374 );
375​
376 assert.include(outcome, "is busy");
377 assert.deepEqual(NodeFS.readdirSync(themesDir), ["original.json"]);
378 assert.deepEqual(readSettings(baseDir), previousSettings);
379 }),
380 );
381​
382 it.effect("rejects a file that is not a theme and sets nothing", () =>
383 Effect.gen(function* () {
384 const baseDir = makeBaseDir();
385 const themeFile = NodePath.join(baseDir, "junk.json");
386 NodeFS.writeFileSync(themeFile, JUNK_THEME_JSON);
387​
388 const failure = yield* runCli(["theme", "set", themeFile, "--base-dir", baseDir]).pipe(
389 Effect.flip,
390 );
391​
392 assert.include(String(failure), "not a valid theme file");
393 assert.equal(NodeFS.existsSync(NodePath.join(baseDir, "userdata", "themes")), false);
394 assert.equal(NodeFS.existsSync(settingsPathFor(baseDir)), false);
395 }),
396 );
397​
398 it.effect.skipIf(!symlinksSupported)("never writes through a symlink at the staging path", () =>
399 Effect.gen(function* () {
400 const baseDir = makeBaseDir();
401 const themesDir = NodePath.join(baseDir, "userdata", "themes");
402 NodeFS.mkdirSync(themesDir, { recursive: true });
403 const victim = NodePath.join(baseDir, "victim.txt");
404 NodeFS.writeFileSync(victim, "precious");
405 NodeFS.symlinkSync(victim, NodePath.join(themesDir, `nightfall.json.staging-${process.pid}`));
406 const themeFile = NodePath.join(baseDir, "nightfall.json");
407 NodeFS.writeFileSync(themeFile, NIGHTFALL_THEME_JSON);
408​
409 yield* runCli(["theme", "set", themeFile, "--base-dir", baseDir]);
410​
411 assert.equal(NodeFS.readFileSync(victim, "utf8"), "precious");
412 assert.equal(readSettings(baseDir).defaultTheme, "nightfall");
413 }),
414 );
415​
416 it.effect.skipIf(windowsHost)("restores the previous theme when a re-publish fails to set", () =>
417 Effect.gen(function* () {
418 const baseDir = makeBaseDir();
419 writeSettings(baseDir, {});
420 const userdataDir = NodePath.dirname(settingsPathFor(baseDir));
421 const themesDir = NodePath.join(userdataDir, "themes");
422 NodeFS.mkdirSync(themesDir, { recursive: true });
423 const publishedPath = NodePath.join(themesDir, "nightfall.json");
424 const previous =
425 '{ "name": "Old Nightfall", "appearance": "dark", "canvas": "#000000", "accent": "#ffffff" }\n';
426 NodeFS.writeFileSync(publishedPath, previous);
427 const themeFile = NodePath.join(baseDir, "nightfall.json");
428 NodeFS.writeFileSync(themeFile, NIGHTFALL_THEME_JSON);
429​
430 NodeFS.chmodSync(userdataDir, 0o555);
431 try {
432 yield* runCli(["theme", "set", themeFile, "--base-dir", baseDir]).pipe(Effect.flip);
433 assert.equal(NodeFS.readFileSync(publishedPath, "utf8"), previous);
434 } finally {
435 NodeFS.chmodSync(userdataDir, 0o755);
436 }
437 }),
438 );
439​
440 it.effect.skipIf(windowsHost)("refuses to write when the settings file cannot be read", () =>
441 Effect.gen(function* () {
442 const baseDir = makeBaseDir();
443 writeSettings(baseDir, { enableProviderUpdateChecks: false });
444 NodeFS.chmodSync(settingsPathFor(baseDir), 0o000);
445​
446 const failure = yield* runCli(["theme", "set", "ocean", "--base-dir", baseDir]).pipe(
447 Effect.flip,
448 );
449​
450 NodeFS.chmodSync(settingsPathFor(baseDir), 0o644);
451 assert.include(String(failure), "Could not read");
452 assert.equal(readSettings(baseDir).enableProviderUpdateChecks, false);
453 assert.equal(Object.hasOwn(readSettings(baseDir), "defaultTheme"), false);
454 }),
455 );
456});