Open History to see the last commit
1// @effect-diagnostics nodeBuiltinImport:off - publish commits and rollbacks
2// move exact directory entries with rename, which the FileSystem service does
3// not expose atomically.
4import * as NodeFS from "node:fs";
5
6import {
7 EnvironmentThemeFile,
8 EnvironmentThemeId,
9 environmentThemeFileHasColors,
10} from "@t3tools/contracts";
11import { fromJsonStringPretty, fromLenientJson } from "@t3tools/shared/schemaJson";
12import { BUILT_IN_THEME_IDS, UNPUBLISHABLE_THEME_IDS } from "@t3tools/shared/themePalettes";
13import * as Config from "effect/Config";
14import * as Console from "effect/Console";
15import * as DateTime from "effect/DateTime";
16import * as Effect from "effect/Effect";
17import * as FileSystem from "effect/FileSystem";
18import * as Option from "effect/Option";
19import * as Path from "effect/Path";
20import * as Schema from "effect/Schema";
21import { Argument, Command, Flag } from "effect/cli";
22
23import { writeFileStringAtomically } from "@t3tools/shared/atomicWrite";
24import * as ServerConfig from "../config.ts";
25import {
26 MAX_THEME_FILE_BYTES,
27 readPublishedThemes,
28 readThemeFileGuarded,
29} from "../environmentTheme.ts";
30import { expandHomePath, resolveBaseDir } from "../os-jank.ts";
31import { baseDirFlag } from "./config.ts";
32
33const SparseSettings = Schema.Record(Schema.String, Schema.Unknown);
34const decodeSettingsJson = Schema.decodeUnknownEffect(fromLenientJson(SparseSettings));
35const encodeSettingsJson = Schema.encodeEffect(fromJsonStringPretty(SparseSettings));
36const decodeThemeFileJsonExit = Schema.decodeUnknownExit(
37 Schema.fromJsonString(EnvironmentThemeFile),
38);
39const isEnvironmentThemeId = Schema.is(EnvironmentThemeId);
40
41export class ThemeSettingsUnreadableError extends Schema.TaggedError<ThemeSettingsUnreadableError>()(
42 "ThemeSettingsUnreadableError",
43 { settingsPath: Schema.String, cause: Schema.Defect() },
44) {
45 override get message(): string {
46 return `Could not read ${this.settingsPath}. Fix its permissions, then run this again.`;
47 }
48}
49
50export class ThemeSettingsMalformedError extends Schema.TaggedError<ThemeSettingsMalformedError>()(
51 "ThemeSettingsMalformedError",
52 { settingsPath: Schema.String, cause: Schema.Defect() },
53) {
54 override get message(): string {
55 return `${this.settingsPath} is not a JSON object. Fix or remove it, then run this again.`;
56 }
57}
58
59export class ThemeSettingsBusyError extends Schema.TaggedError<ThemeSettingsBusyError>()(
60 "ThemeSettingsBusyError",
61 { settingsPath: Schema.String, attempts: Schema.Number },
62) {
63 override get message(): string {
64 return `${this.settingsPath} kept changing while writing (gave up after ${this.attempts} attempts). Try again.`;
65 }
66}
67
68export class ThemeSettingsWriteError extends Schema.TaggedError<ThemeSettingsWriteError>()(
69 "ThemeSettingsWriteError",
70 { settingsPath: Schema.String, cause: Schema.Defect() },
71) {
72 override get message(): string {
73 return `Could not write ${this.settingsPath}.`;
74 }
75}
76
77export class ThemeFileUnreadableError extends Schema.TaggedError<ThemeFileUnreadableError>()(
78 "ThemeFileUnreadableError",
79 { filePath: Schema.String, cause: Schema.optional(Schema.Defect()) },
80) {
81 override get message(): string {
82 return `Could not read ${this.filePath}.`;
83 }
84}
85
86export class ThemeFileInvalidError extends Schema.TaggedError<ThemeFileInvalidError>()(
87 "ThemeFileInvalidError",
88 { filePath: Schema.String, cause: Schema.Defect() },
89) {
90 override get message(): string {
91 return `${this.filePath} is not a valid theme file. Use a theme exported from T3 Code, or a seeded file with name, appearance, canvas, and accent.`;
92 }
93}
94
95export class ThemeFileTooLargeError extends Schema.TaggedError<ThemeFileTooLargeError>()(
96 "ThemeFileTooLargeError",
97 { filePath: Schema.String, limit: Schema.Number },
98) {
99 override get message(): string {
100 return `${this.filePath} is larger than ${this.limit} bytes, which is more than a theme can publish.`;
101 }
102}
103
104export class ThemeFileColorlessError extends Schema.TaggedError<ThemeFileColorlessError>()(
105 "ThemeFileColorlessError",
106 { filePath: Schema.String },
107) {
108 override get message(): string {
109 return `${this.filePath} has no colors to publish.`;
110 }
111}
112
113export class ThemePublishError extends Schema.TaggedError<ThemePublishError>()(
114 "ThemePublishError",
115 { themesDir: Schema.String, cause: Schema.Defect() },
116) {
117 override get message(): string {
118 return `Could not publish the theme into ${this.themesDir}.`;
119 }
120}
121
122const INVALID_THEME_ID_REASON =
123 "is not a valid theme id (lowercase letters, digits, and hyphens; not an appearance keyword)";
124
125export class ThemeIdUnknownError extends Schema.TaggedError<ThemeIdUnknownError>()(
126 "ThemeIdUnknownError",
127 { themeId: Schema.String, known: Schema.Array(Schema.String) },
128) {
129 override get message(): string {
130 return `No theme named "${this.themeId}". Available: ${this.known.join(", ")}. Publish one by passing a theme file instead of an id.`;
131 }
132}
133
134export class ThemeIdInvalidError extends Schema.TaggedError<ThemeIdInvalidError>()(
135 "ThemeIdInvalidError",
136 { themeId: Schema.String },
137) {
138 override get message(): string {
139 return `"${this.themeId}" ${INVALID_THEME_ID_REASON}.`;
140 }
141}
142
143export class ThemeFileIdInvalidError extends Schema.TaggedError<ThemeFileIdInvalidError>()(
144 "ThemeFileIdInvalidError",
145 { themeId: Schema.String, filePath: Schema.String },
146) {
147 override get message(): string {
148 return `"${this.themeId}" ${INVALID_THEME_ID_REASON}. Pass one with --id.`;
149 }
150}
151
152export class ThemeTargetMissingError extends Schema.TaggedError<ThemeTargetMissingError>()(
153 "ThemeTargetMissingError",
154 {},
155) {
156 override get message(): string {
157 return "Provide a theme id or file, or run `t3 theme clear` to remove the theme.";
158 }
159}
160
161const envT3Home = Config.String("T3CODE_HOME").pipe(Config.option);
162
163const resolveThemePaths = Effect.fn(function* (explicitBaseDir: Option.Option<string>) {
164 const envHome = Option.filter(yield* envT3Home, (value) => value.trim().length > 0);
165 const configuredBaseDir = Option.orElse(explicitBaseDir, () => envHome);
166 const baseDir = yield* resolveBaseDir(Option.getOrUndefined(configuredBaseDir));
167 const derivedPaths = yield* ServerConfig.deriveServerPaths(baseDir, undefined, {
168 baseDirIsExplicit: Option.isSome(configuredBaseDir),
169 });
170 return {
171 settingsPath: derivedPaths.settingsPath,
172 themesDir: derivedPaths.environmentThemesDir,
173 };
174});
175
176/**
177 * A permission or I/O error must propagate: reading it as "no settings" would
178 * have the caller write a fresh sparse file over settings it never saw.
179 */
180const readSettingsObject = Effect.fn(function* (settingsPath: string) {
181 const fs = yield* FileSystem.FileSystem;
182 const exists = yield* fs
183 .exists(settingsPath)
184 .pipe(Effect.mapError((cause) => new ThemeSettingsUnreadableError({ settingsPath, cause })));
185 if (!exists) return { raw: "", settings: {} };
186
187 const raw = yield* fs
188 .readFileString(settingsPath)
189 .pipe(Effect.mapError((cause) => new ThemeSettingsUnreadableError({ settingsPath, cause })));
190 if (raw.trim().length === 0) return { raw, settings: {} };
191
192 const settings = yield* decodeSettingsJson(raw).pipe(
193 Effect.mapError((cause) => new ThemeSettingsMalformedError({ settingsPath, cause })),
194 );
195 return { raw, settings };
196});
197
198/**
199 * A running server owns this file too, and its write path is an in-process
200 * semaphore that cannot serialize against another process.
201 */
202const CONCURRENT_WRITE_ATTEMPTS = 5;
203
204const writeDefaultTheme = Effect.fn(function* (input: {
205 readonly settingsPath: string;
206 readonly themeId: string;
207}) {
208 const fs = yield* FileSystem.FileSystem;
209
210 for (let attempt = 1; ; attempt++) {
211 const { raw, settings } = yield* readSettingsObject(input.settingsPath);
212 const setAt = DateTime.formatIso(yield* DateTime.now);
213 const next =
214 input.themeId.length > 0
215 ? // The timestamp is the set-generation: it lets clients apply a re-set
216 // of the same value they already applied once.
217 { ...settings, defaultTheme: input.themeId, defaultThemeSetAt: setAt }
218 : Object.fromEntries(
219 Object.entries(settings).filter(
220 ([key]) => key !== "defaultTheme" && key !== "defaultThemeSetAt",
221 ),
222 );
223
224 const contents = yield* encodeSettingsJson(next);
225 const current = yield* fs
226 .readFileString(input.settingsPath)
227 .pipe(Effect.orElseSucceed(() => ""));
228 if (current !== raw) {
229 if (attempt >= CONCURRENT_WRITE_ATTEMPTS) {
230 return yield* new ThemeSettingsBusyError({
231 settingsPath: input.settingsPath,
232 attempts: CONCURRENT_WRITE_ATTEMPTS,
233 });
234 }
235 continue;
236 }
237
238 yield* writeFileStringAtomically({
239 filePath: input.settingsPath,
240 contents: `${contents}\n`,
241 }).pipe(
242 Effect.mapError(
243 (cause) => new ThemeSettingsWriteError({ settingsPath: input.settingsPath, cause }),
244 ),
245 );
246 return;
247 }
248});
249
250const publishThemeFile = Effect.fn(function* (input: {
251 readonly themesDir: string;
252 readonly filePath: string;
253 readonly explicitId: Option.Option<string>;
254}) {
255 const fs = yield* FileSystem.FileSystem;
256 const path = yield* Path.Path;
257 const info = yield* fs
258 .stat(input.filePath)
259 .pipe(
260 Effect.mapError((cause) => new ThemeFileUnreadableError({ filePath: input.filePath, cause })),
261 );
262 if (info.type !== "File") {
263 return yield* new ThemeFileUnreadableError({ filePath: input.filePath });
264 }
265 if (Number(info.size) > MAX_THEME_FILE_BYTES) {
266 return yield* new ThemeFileTooLargeError({
267 filePath: input.filePath,
268 limit: MAX_THEME_FILE_BYTES,
269 });
270 }
271
272 const resolvedSource = yield* fs
273 .realPath(input.filePath)
274 .pipe(
275 Effect.mapError((cause) => new ThemeFileUnreadableError({ filePath: input.filePath, cause })),
276 );
277 const raw = readThemeFileGuarded(resolvedSource, MAX_THEME_FILE_BYTES);
278 if (raw === null) {
279 return yield* new ThemeFileUnreadableError({ filePath: input.filePath });
280 }
281
282 const decoded = decodeThemeFileJsonExit(raw);
283 if (decoded._tag === "Failure") {
284 return yield* new ThemeFileInvalidError({ filePath: input.filePath, cause: decoded.cause });
285 }
286 if (!environmentThemeFileHasColors(decoded.value)) {
287 return yield* new ThemeFileColorlessError({ filePath: input.filePath });
288 }
289
290 const fileBasename = path.basename(input.filePath, ".json");
291 const themeId = Option.getOrElse(input.explicitId, () => fileBasename);
292 // The same rules the watcher applies when it reads the directory back, so a
293 // publish cannot report success for a file that will then be skipped.
294 if (!isEnvironmentThemeId(themeId) || UNPUBLISHABLE_THEME_IDS.has(themeId)) {
295 return yield* new ThemeFileIdInvalidError({ themeId, filePath: input.filePath });
296 }
297
298 const destinationPath = path.join(input.themesDir, `${themeId}.json`);
299 // Neither ends in `.json`, so the watcher never mistakes them for themes.
300 // Both names carry the pid, so concurrent publishers of one id cannot
301 // unlink or restore over each other's staging and rollback copies.
302 const backupPath = `${destinationPath}.rollback-${process.pid}`;
303 const stagingPath = `${destinationPath}.staging-${process.pid}`;
304 yield* fs
305 .makeDirectory(input.themesDir, { recursive: true })
306 .pipe(Effect.mapError((cause) => new ThemePublishError({ themesDir: input.themesDir, cause })));
307
308 const publishFailure = (cause: unknown) =>
309 new ThemePublishError({ themesDir: input.themesDir, cause });
310
311 // The staging entry is created O_EXCL after clearing any stale leftover, so a
312 // symlink or file already at that predictable name is never followed or
313 // written through. Written verbatim: appending so much as a newline could
314 // push a file at the size limit past it and have the watcher skip what was
315 // just accepted.
316 const stagedIno = yield* Effect.try({
317 try: () => {
318 try {
319 NodeFS.unlinkSync(stagingPath);
320 } catch {}
321 const fd = NodeFS.openSync(
322 stagingPath,
323 NodeFS.constants.O_WRONLY | NodeFS.constants.O_CREAT | NodeFS.constants.O_EXCL,
324 0o644,
325 );
326 try {
327 NodeFS.writeFileSync(fd, raw);
328 return NodeFS.fstatSync(fd).ino;
329 } finally {
330 NodeFS.closeSync(fd);
331 }
332 },
333 catch: publishFailure,
334 });
335
336 // Whatever occupies the destination -- a theme, a symlink, anything -- is
337 // moved aside in one atomic step rather than inspected and then replaced:
338 // there is no window between a check and the commit, and rollback restores
339 // that exact directory entry instead of a re-read of it.
340 const hadPrevious = yield* Effect.try({
341 try: () => {
342 try {
343 NodeFS.renameSync(destinationPath, backupPath);
344 return true;
345 } catch (error) {
346 if ((error as NodeJS.ErrnoException).code === "ENOENT") return false;
347 throw error;
348 }
349 },
350 catch: publishFailure,
351 });
352
353 const revert = Effect.sync(() => {
354 try {
355 NodeFS.unlinkSync(stagingPath);
356 } catch {}
357 try {
358 // The destination is touched only while it is empty or still holds
359 // the exact file this process put there; a concurrent publisher's
360 // newer file wins, and this process's obsolete copy is discarded.
361 const destinationIno = (() => {
362 try {
363 return NodeFS.lstatSync(destinationPath).ino;
364 } catch {
365 return null;
366 }
367 })();
368 if (hadPrevious) {
369 if (destinationIno === null || destinationIno === stagedIno) {
370 NodeFS.renameSync(backupPath, destinationPath);
371 } else {
372 NodeFS.unlinkSync(backupPath);
373 }
374 } else if (destinationIno === stagedIno) {
375 NodeFS.unlinkSync(destinationPath);
376 }
377 } catch {}
378 });
379 const cleanup = Effect.sync(() => {
380 try {
381 if (hadPrevious) NodeFS.unlinkSync(backupPath);
382 } catch {}
383 });
384
385 yield* Effect.try({
386 try: () => NodeFS.renameSync(stagingPath, destinationPath),
387 catch: publishFailure,
388 }).pipe(Effect.onError(() => revert));
389
390 return { themeId, revert, cleanup };
391});
392
393/**
394 * The mobile default is absent on purpose -- web and desktop cannot resolve it
395 * and mobile does not follow this setting, so naming it would be the silent
396 * no-op this check exists to stop.
397 */
398const resolvableThemeIds = Effect.fn(function* (themesDir: string) {
399 const published = yield* readPublishedThemes(themesDir);
400 return [...BUILT_IN_THEME_IDS, ...published.map((theme) => theme.id)].toSorted();
401});
402
403const themeSetCommand = Command.make("set", {
404 baseDir: baseDirFlag,
405 id: Flag.String("id").pipe(
406 Flag.withDescription("Theme id to publish a file under, instead of its filename."),
407 Flag.optional,
408 ),
409 theme: Argument.String("theme").pipe(
410 Argument.withDescription(
411 'A theme id (a built-in, or one this machine publishes — themes/nightfall.json is "nightfall"), or a path to a theme JSON file to publish and set in one step.',
412 ),
413 ),
414}).pipe(
415 Command.withDescription("Set the environment's theme; connected clients switch to it."),
416 Command.withHandler((flags) =>
417 Effect.gen(function* () {
418 const fs = yield* FileSystem.FileSystem;
419 const target = yield* expandHomePath(flags.theme.trim());
420 if (target.length === 0) {
421 return yield* new ThemeTargetMissingError();
422 }
423 const paths = yield* resolveThemePaths(flags.baseDir);
424
425 // Path-shaped first, existence second. Deciding on existence alone would
426 // make `t3 theme set ocean` publish ./ocean whenever the cwd happens to
427 // hold a file by that name, instead of selecting the built-in.
428 const looksLikePath =
429 target.endsWith(".json") ||
430 target.includes("/") ||
431 target.includes("\\") ||
432 target.startsWith("~");
433 const targetIsFile =
434 looksLikePath && (yield* fs.exists(target).pipe(Effect.orElseSucceed(() => false)));
435 let themeId: string;
436 let revertPublish: Effect.Effect<void> = Effect.void;
437 let cleanupPublish: Effect.Effect<void> = Effect.void;
438 if (targetIsFile) {
439 yield* readSettingsObject(paths.settingsPath);
440 const published = yield* publishThemeFile({
441 themesDir: paths.themesDir,
442 filePath: target,
443 explicitId: flags.id,
444 });
445 themeId = published.themeId;
446 revertPublish = published.revert;
447 cleanupPublish = published.cleanup;
448 } else if (looksLikePath) {
449 return yield* new ThemeFileUnreadableError({ filePath: target });
450 } else if (isEnvironmentThemeId(target)) {
451 const known = yield* resolvableThemeIds(paths.themesDir);
452 if (!known.includes(target)) {
453 return yield* new ThemeIdUnknownError({ themeId: target, known });
454 }
455 themeId = target;
456 } else {
457 return yield* new ThemeIdInvalidError({ themeId: target });
458 }
459
460 yield* writeDefaultTheme({ settingsPath: paths.settingsPath, themeId }).pipe(
461 Effect.onError(() => revertPublish),
462 );
463 yield* cleanupPublish;
464 yield* Console.log(
465 targetIsFile
466 ? `Published ${target} as "${themeId}" and set it as the environment theme.\n`
467 : `Environment theme set to "${themeId}" in ${paths.settingsPath}.\n`,
468 );
469 }),
470 ),
471);
472
473const themeClearCommand = Command.make("clear", { baseDir: baseDirFlag }).pipe(
474 Command.withDescription("Remove the environment's theme; clients keep what they have."),
475 Command.withHandler((flags) =>
476 Effect.gen(function* () {
477 const paths = yield* resolveThemePaths(flags.baseDir);
478 yield* writeDefaultTheme({ settingsPath: paths.settingsPath, themeId: "" });
479 yield* Console.log(`Environment theme cleared in ${paths.settingsPath}.\n`);
480 }),
481 ),
482);
483
484const themeShowCommand = Command.make("show", { baseDir: baseDirFlag }).pipe(
485 Command.withDescription("Show the environment's theme and its published themes."),
486 Command.withHandler((flags) =>
487 Effect.gen(function* () {
488 const paths = yield* resolveThemePaths(flags.baseDir);
489 const { settings } = yield* readSettingsObject(paths.settingsPath);
490 const defaultTheme =
491 typeof settings.defaultTheme === "string" && settings.defaultTheme.length > 0
492 ? settings.defaultTheme
493 : null;
494
495 const published = (yield* readPublishedThemes(paths.themesDir))
496 .map((theme) => theme.id)
497 .toSorted();
498
499 yield* Console.log(
500 defaultTheme === null
501 ? "Environment theme: not set.\n"
502 : `Environment theme: "${defaultTheme}".\n`,
503 );
504 yield* Console.log(
505 published.length === 0
506 ? `Published themes: none (publish into ${paths.themesDir}).\n`
507 : `Published themes: ${published.join(", ")}.\n`,
508 );
509 }),
510 ),
511);
512
513export const themeCommand = Command.make("theme").pipe(
514 Command.withDescription("Inspect and set environment-wide theme defaults."),
515 Command.withSubcommands([themeSetCommand, themeClearCommand, themeShowCommand]),
516);