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 NodeCrypto from "node:crypto";
5import * as NodeFS from "node:fs";
6
7import {
8 EnvironmentThemeFile,
9 EnvironmentThemeId,
10 environmentThemeFileHasColors,
11} from "@t3tools/contracts";
12import { fromJsonStringPretty, fromLenientJson } from "@t3tools/shared/schemaJson";
13import { BUILT_IN_THEME_IDS, UNPUBLISHABLE_THEME_IDS } from "@t3tools/shared/themePalettes";
14import * as Config from "effect/Config";
15import * as Console from "effect/Console";
16import * as DateTime from "effect/DateTime";
17import * as Effect from "effect/Effect";
18import * as FileSystem from "effect/FileSystem";
19import * as Option from "effect/Option";
20import * as Path from "effect/Path";
21import * as Schema from "effect/Schema";
22import { Argument, Command, Flag } from "effect/cli";
23
24import { writeFileStringAtomically } from "@t3tools/shared/atomicWrite";
25import * as HostProcess from "@t3tools/shared/HostProcess";
26import * as ServerConfig from "../config.ts";
27import {
28 MAX_THEME_FILE_BYTES,
29 readPublishedThemes,
30 readThemeFileGuarded,
31} from "../environmentTheme.ts";
32import { expandHomePath, resolveBaseDir } from "../os-jank.ts";
33import { isProcessAlive, readPersistedServerRuntimeState } from "../serverRuntimeState.ts";
34import { baseDirFlag } from "./config.ts";
35
36const SparseSettings = Schema.Record(Schema.String, Schema.Unknown);
37const decodeSettingsJson = Schema.decodeUnknownEffect(fromLenientJson(SparseSettings));
38const encodeSettingsJson = Schema.encodeEffect(fromJsonStringPretty(SparseSettings));
39const decodeThemeFileJsonExit = Schema.decodeUnknownExit(
40 Schema.fromJsonString(EnvironmentThemeFile),
41);
42const isEnvironmentThemeId = Schema.is(EnvironmentThemeId);
43
44export class ThemeSettingsUnreadableError extends Schema.TaggedError<ThemeSettingsUnreadableError>()(
45 "ThemeSettingsUnreadableError",
46 { settingsPath: Schema.String, cause: Schema.Defect() },
47) {
48 override get message(): string {
49 return `Could not read ${this.settingsPath}. Fix its permissions, then run this again.`;
50 }
51}
52
53export class ThemeSettingsMalformedError extends Schema.TaggedError<ThemeSettingsMalformedError>()(
54 "ThemeSettingsMalformedError",
55 { settingsPath: Schema.String, cause: Schema.Defect() },
56) {
57 override get message(): string {
58 return `${this.settingsPath} is not a JSON object. Fix or remove it, then run this again.`;
59 }
60}
61
62export class ThemeSettingsBusyError extends Schema.TaggedError<ThemeSettingsBusyError>()(
63 "ThemeSettingsBusyError",
64 { settingsPath: Schema.String, attempts: Schema.Number },
65) {
66 override get message(): string {
67 return `${this.settingsPath} kept changing while writing (gave up after ${this.attempts} attempts). Try again.`;
68 }
69}
70
71export class ThemeSettingsWriteError extends Schema.TaggedError<ThemeSettingsWriteError>()(
72 "ThemeSettingsWriteError",
73 { settingsPath: Schema.String, cause: Schema.Defect() },
74) {
75 override get message(): string {
76 return `Could not write ${this.settingsPath}.`;
77 }
78}
79
80export class ThemeFileUnreadableError extends Schema.TaggedError<ThemeFileUnreadableError>()(
81 "ThemeFileUnreadableError",
82 { filePath: Schema.String, cause: Schema.optional(Schema.Defect()) },
83) {
84 override get message(): string {
85 return `Could not read ${this.filePath}.`;
86 }
87}
88
89export class ThemeFileInvalidError extends Schema.TaggedError<ThemeFileInvalidError>()(
90 "ThemeFileInvalidError",
91 { filePath: Schema.String, cause: Schema.Defect() },
92) {
93 override get message(): string {
94 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.`;
95 }
96}
97
98export class ThemeFileTooLargeError extends Schema.TaggedError<ThemeFileTooLargeError>()(
99 "ThemeFileTooLargeError",
100 { filePath: Schema.String, limit: Schema.Number },
101) {
102 override get message(): string {
103 return `${this.filePath} is larger than ${this.limit} bytes, which is more than a theme can publish.`;
104 }
105}
106
107export class ThemeFileColorlessError extends Schema.TaggedError<ThemeFileColorlessError>()(
108 "ThemeFileColorlessError",
109 { filePath: Schema.String },
110) {
111 override get message(): string {
112 return `${this.filePath} has no colors to publish.`;
113 }
114}
115
116export class ThemePublishError extends Schema.TaggedError<ThemePublishError>()(
117 "ThemePublishError",
118 { themesDir: Schema.String, cause: Schema.Defect() },
119) {
120 override get message(): string {
121 return `Could not publish the theme into ${this.themesDir}.`;
122 }
123}
124
125export class ThemeDestinationDirectoryError extends Schema.TaggedError<ThemeDestinationDirectoryError>()(
126 "ThemeDestinationDirectoryError",
127 { themeId: Schema.String, destinationPath: Schema.String },
128) {
129 override get message(): string {
130 return `${this.destinationPath} is a directory, so the theme cannot be published as "${this.themeId}". Move it, or pass another id with --id.`;
131 }
132}
133
134const isThemeDestinationDirectoryError = Schema.is(ThemeDestinationDirectoryError);
135
136const INVALID_THEME_ID_REASON =
137 "is not a valid theme id (lowercase letters, digits, and hyphens; not an appearance keyword)";
138
139export class ThemeIdUnknownError extends Schema.TaggedError<ThemeIdUnknownError>()(
140 "ThemeIdUnknownError",
141 { themeId: Schema.String, known: Schema.Array(Schema.String) },
142) {
143 override get message(): string {
144 return `No theme named "${this.themeId}". Available: ${this.known.join(", ")}. Publish one by passing a theme file instead of an id.`;
145 }
146}
147
148export class ThemeIdInvalidError extends Schema.TaggedError<ThemeIdInvalidError>()(
149 "ThemeIdInvalidError",
150 { themeId: Schema.String },
151) {
152 override get message(): string {
153 return `"${this.themeId}" ${INVALID_THEME_ID_REASON}.`;
154 }
155}
156
157export class ThemeFileIdInvalidError extends Schema.TaggedError<ThemeFileIdInvalidError>()(
158 "ThemeFileIdInvalidError",
159 { themeId: Schema.String, filePath: Schema.String },
160) {
161 override get message(): string {
162 return `"${this.themeId}" ${INVALID_THEME_ID_REASON}. Pass one with --id.`;
163 }
164}
165
166export class ThemeTargetMissingError extends Schema.TaggedError<ThemeTargetMissingError>()(
167 "ThemeTargetMissingError",
168 {},
169) {
170 override get message(): string {
171 return "Provide a theme id or file, or run `t3 theme clear` to remove the theme.";
172 }
173}
174
175const envT3Home = Config.String("T3CODE_HOME").pipe(Config.option);
176const DEV_STATE_PLACEHOLDER_URL = new URL("http://localhost");
177
178const hasLiveServer = (statePath: string) =>
179 readPersistedServerRuntimeState(statePath).pipe(
180 Effect.map((state) => Option.isSome(state) && isProcessAlive(state.value.pid)),
181 Effect.orElseSucceed(() => false),
182 );
183
184const resolveThemePaths = Effect.fn(function* (explicitBaseDir: Option.Option<string>) {
185 const envHome = Option.filter(yield* envT3Home, (value) => value.trim().length > 0);
186 const configuredBaseDir = Option.orElse(explicitBaseDir, () => envHome);
187 const baseDir = yield* resolveBaseDir(Option.getOrUndefined(configuredBaseDir));
188 const userdataPaths = yield* ServerConfig.deriveServerPaths(baseDir, undefined, {
189 baseDirIsExplicit: Option.isSome(configuredBaseDir),
190 });
191 // A dev server with an implicit home keeps its state in `dev`; follow it unless a
192 // `userdata` server is running too, the same order `t3 pair` checks.
193 let derivedPaths = userdataPaths;
194 if (
195 Option.isNone(configuredBaseDir) &&
196 !(yield* hasLiveServer(userdataPaths.serverRuntimeStatePath))
197 ) {
198 const devPaths = yield* ServerConfig.deriveServerPaths(baseDir, DEV_STATE_PLACEHOLDER_URL);
199 if (yield* hasLiveServer(devPaths.serverRuntimeStatePath)) derivedPaths = devPaths;
200 }
201 return {
202 settingsPath: derivedPaths.settingsPath,
203 themesDir: derivedPaths.environmentThemesDir,
204 };
205});
206
207/** Propagate read errors to avoid overwriting unread settings with a sparse file. */
208const readSettingsObject = Effect.fn(function* (settingsPath: string) {
209 const fs = yield* FileSystem.FileSystem;
210 const exists = yield* fs
211 .exists(settingsPath)
212 .pipe(Effect.mapError((cause) => new ThemeSettingsUnreadableError({ settingsPath, cause })));
213 if (!exists) return { raw: "", settings: {} };
214
215 const raw = yield* fs
216 .readFileString(settingsPath)
217 .pipe(Effect.mapError((cause) => new ThemeSettingsUnreadableError({ settingsPath, cause })));
218 if (raw.trim().length === 0) return { raw, settings: {} };
219
220 const settings = yield* decodeSettingsJson(raw).pipe(
221 Effect.mapError((cause) => new ThemeSettingsMalformedError({ settingsPath, cause })),
222 );
223 return { raw, settings };
224});
225
226/** The server's in-process semaphore cannot serialize writes from this process. */
227const CONCURRENT_WRITE_ATTEMPTS = 5;
228
229const writeDefaultTheme = Effect.fn(function* (input: {
230 readonly settingsPath: string;
231 readonly themeId: string;
232}) {
233 const fs = yield* FileSystem.FileSystem;
234
235 for (let attempt = 1; ; attempt++) {
236 const { raw, settings } = yield* readSettingsObject(input.settingsPath);
237 const setAt = DateTime.formatIso(yield* DateTime.now);
238 const next =
239 input.themeId.length > 0
240 ? // The timestamp lets clients reapply the same theme.
241 { ...settings, defaultTheme: input.themeId, defaultThemeSetAt: setAt }
242 : Object.fromEntries(
243 Object.entries(settings).filter(
244 ([key]) => key !== "defaultTheme" && key !== "defaultThemeSetAt",
245 ),
246 );
247
248 const contents = yield* encodeSettingsJson(next);
249 const current = yield* fs
250 .readFileString(input.settingsPath)
251 .pipe(Effect.orElseSucceed(() => ""));
252 if (current !== raw) {
253 if (attempt >= CONCURRENT_WRITE_ATTEMPTS) {
254 return yield* new ThemeSettingsBusyError({
255 settingsPath: input.settingsPath,
256 attempts: CONCURRENT_WRITE_ATTEMPTS,
257 });
258 }
259 continue;
260 }
261
262 yield* writeFileStringAtomically({
263 filePath: input.settingsPath,
264 contents: `${contents}\n`,
265 }).pipe(
266 Effect.mapError(
267 (cause) => new ThemeSettingsWriteError({ settingsPath: input.settingsPath, cause }),
268 ),
269 );
270 return;
271 }
272});
273
274const publishThemeFile = Effect.fn(function* (input: {
275 readonly themesDir: string;
276 readonly filePath: string;
277 readonly explicitId: Option.Option<string>;
278}) {
279 const fs = yield* FileSystem.FileSystem;
280 const path = yield* Path.Path;
281 const info = yield* fs
282 .stat(input.filePath)
283 .pipe(
284 Effect.mapError((cause) => new ThemeFileUnreadableError({ filePath: input.filePath, cause })),
285 );
286 if (info.type !== "File") {
287 return yield* new ThemeFileUnreadableError({ filePath: input.filePath });
288 }
289 if (Number(info.size) > MAX_THEME_FILE_BYTES) {
290 return yield* new ThemeFileTooLargeError({
291 filePath: input.filePath,
292 limit: MAX_THEME_FILE_BYTES,
293 });
294 }
295
296 const resolvedSource = yield* fs
297 .realPath(input.filePath)
298 .pipe(
299 Effect.mapError((cause) => new ThemeFileUnreadableError({ filePath: input.filePath, cause })),
300 );
301 const raw = readThemeFileGuarded(resolvedSource, MAX_THEME_FILE_BYTES);
302 if (raw === null) {
303 return yield* new ThemeFileUnreadableError({ filePath: input.filePath });
304 }
305
306 const decoded = decodeThemeFileJsonExit(raw);
307 if (decoded._tag === "Failure") {
308 return yield* new ThemeFileInvalidError({ filePath: input.filePath, cause: decoded.cause });
309 }
310 if (!environmentThemeFileHasColors(decoded.value)) {
311 return yield* new ThemeFileColorlessError({ filePath: input.filePath });
312 }
313
314 const fileBasename = path.basename(input.filePath, ".json");
315 const themeId = Option.getOrElse(input.explicitId, () => fileBasename);
316 // Match watcher validation so published files will not be skipped.
317 if (!isEnvironmentThemeId(themeId) || UNPUBLISHABLE_THEME_IDS.has(themeId)) {
318 return yield* new ThemeFileIdInvalidError({ themeId, filePath: input.filePath });
319 }
320
321 const destinationPath = path.join(input.themesDir, `${themeId}.json`);
322 const stagingPath = `${destinationPath}.staging-${process.pid}`;
323 yield* fs
324 .makeDirectory(input.themesDir, { recursive: true })
325 .pipe(Effect.mapError((cause) => new ThemePublishError({ themesDir: input.themesDir, cause })));
326
327 const publishFailure = (cause: unknown) =>
328 new ThemePublishError({ themesDir: input.themesDir, cause });
329
330 const destinationIsDirectory = yield* Effect.try({
331 try: () => NodeFS.lstatSync(destinationPath, { throwIfNoEntry: false })?.isDirectory() ?? false,
332 catch: publishFailure,
333 });
334 if (destinationIsDirectory) {
335 return yield* new ThemeDestinationDirectoryError({ themeId, destinationPath });
336 }
337
338 // O_EXCL prevents following a symlink at the predictable staging path.
339 // Preserve bytes exactly: even an added newline could exceed the watcher's size limit.
340 const stagedIno = yield* Effect.try({
341 try: () => {
342 try {
343 NodeFS.unlinkSync(stagingPath);
344 } catch {}
345 const fd = NodeFS.openSync(
346 stagingPath,
347 NodeFS.constants.O_WRONLY | NodeFS.constants.O_CREAT | NodeFS.constants.O_EXCL,
348 0o644,
349 );
350 try {
351 NodeFS.writeFileSync(fd, raw);
352 return NodeFS.fstatSync(fd).ino;
353 } finally {
354 NodeFS.closeSync(fd);
355 }
356 },
357 catch: publishFailure,
358 });
359
360 const backupPath = yield* Effect.try({
361 try: () => {
362 // A fresh path leaves any backup from a crashed publish intact.
363 const rollbackPath = `${destinationPath}.rollback-${NodeCrypto.randomUUID()}`;
364 // A rename onto a regular file rejects a directory even if it appeared after lstat.
365 const fd = NodeFS.openSync(rollbackPath, "wx", 0o600);
366 let saved = false;
367 try {
368 NodeFS.closeSync(fd);
369 NodeFS.renameSync(destinationPath, rollbackPath);
370 saved = true;
371 return rollbackPath;
372 } catch (error) {
373 if ((error as NodeJS.ErrnoException).code === "ENOENT") return null;
374 if (NodeFS.lstatSync(destinationPath, { throwIfNoEntry: false })?.isDirectory()) {
375 throw new ThemeDestinationDirectoryError({ themeId, destinationPath });
376 }
377 throw error;
378 } finally {
379 if (!saved) {
380 try {
381 NodeFS.unlinkSync(rollbackPath);
382 } catch {}
383 }
384 }
385 },
386 catch: (cause) => (isThemeDestinationDirectoryError(cause) ? cause : publishFailure(cause)),
387 }).pipe(
388 Effect.onError(() =>
389 Effect.sync(() => {
390 try {
391 NodeFS.unlinkSync(stagingPath);
392 } catch {}
393 }),
394 ),
395 );
396
397 const revert = Effect.sync(() => {
398 try {
399 NodeFS.unlinkSync(stagingPath);
400 } catch {}
401 try {
402 // Only replace this process's inode or an empty destination; concurrent publishers win.
403 const destinationIno = (() => {
404 try {
405 return NodeFS.lstatSync(destinationPath).ino;
406 } catch {
407 return null;
408 }
409 })();
410 if (backupPath !== null) {
411 if (destinationIno === null || destinationIno === stagedIno) {
412 NodeFS.renameSync(backupPath, destinationPath);
413 } else {
414 NodeFS.unlinkSync(backupPath);
415 }
416 } else if (destinationIno === stagedIno) {
417 NodeFS.unlinkSync(destinationPath);
418 }
419 } catch {}
420 });
421 const cleanup = Effect.sync(() => {
422 try {
423 if (backupPath !== null) NodeFS.unlinkSync(backupPath);
424 } catch {}
425 });
426
427 yield* Effect.try({
428 try: () => NodeFS.renameSync(stagingPath, destinationPath),
429 catch: publishFailure,
430 }).pipe(Effect.onError(() => revert));
431
432 return { themeId, revert, cleanup };
433});
434
435/** Web and desktop cannot resolve the mobile default, and mobile does not follow this setting. */
436const resolvableThemeIds = Effect.fn(function* (themesDir: string) {
437 const published = yield* readPublishedThemes(themesDir);
438 return [...BUILT_IN_THEME_IDS, ...published.map((theme) => theme.id)].toSorted();
439});
440
441const themeSetCommand = Command.make("set", {
442 baseDir: baseDirFlag,
443 id: Flag.String("id").pipe(
444 Flag.withDescription("Theme id to publish a file under, instead of its filename."),
445 Flag.optional,
446 ),
447 theme: Argument.String("theme").pipe(
448 Argument.withDescription(
449 'A theme id (a built-in, or one this machine publishes, where themes/nightfall.json is "nightfall"), or a path to a theme JSON file to publish and set in one step.',
450 ),
451 ),
452}).pipe(
453 Command.withDescription(
454 "Set the environment's theme. The web app this server serves and the desktop app on this machine switch to it; a desktop app connected from another machine does not.",
455 ),
456 Command.withHandler((flags) =>
457 Effect.gen(function* () {
458 const fs = yield* FileSystem.FileSystem;
459 let target = yield* expandHomePath(flags.theme.trim());
460 if (target.length === 0) {
461 return yield* new ThemeTargetMissingError();
462 }
463 const paths = yield* resolveThemePaths(flags.baseDir);
464
465 // A bare theme id must not publish a same-named file that happens to exist in cwd.
466 const looksLikePath =
467 target.endsWith(".json") ||
468 target.includes("/") ||
469 target.includes("\\") ||
470 target.startsWith("~");
471 if (looksLikePath) {
472 // Spaces stay part of the path when the argument names a file as typed. Win32 drops
473 // trailing spaces from ordinary paths, so only leading ones can name another file there.
474 const expanded = yield* expandHomePath(flags.theme);
475 const asTyped =
476 (yield* HostProcess.Platform) === "win32" && !expanded.startsWith("\\\\?\\")
477 ? expanded.replace(/ +$/, "")
478 : expanded;
479 const info = yield* fs.stat(asTyped).pipe(Effect.option);
480 if (Option.isSome(info) && info.value.type === "File") target = asTyped;
481 }
482 const targetIsFile =
483 looksLikePath && (yield* fs.exists(target).pipe(Effect.orElseSucceed(() => false)));
484 let themeId: string;
485 let revertPublish: Effect.Effect<void> = Effect.void;
486 let cleanupPublish: Effect.Effect<void> = Effect.void;
487 if (targetIsFile) {
488 yield* readSettingsObject(paths.settingsPath);
489 const published = yield* publishThemeFile({
490 themesDir: paths.themesDir,
491 filePath: target,
492 explicitId: flags.id,
493 });
494 themeId = published.themeId;
495 revertPublish = published.revert;
496 cleanupPublish = published.cleanup;
497 } else if (looksLikePath) {
498 return yield* new ThemeFileUnreadableError({ filePath: target });
499 } else if (isEnvironmentThemeId(target)) {
500 const known = yield* resolvableThemeIds(paths.themesDir);
501 if (!known.includes(target)) {
502 return yield* new ThemeIdUnknownError({ themeId: target, known });
503 }
504 themeId = target;
505 } else {
506 return yield* new ThemeIdInvalidError({ themeId: target });
507 }
508
509 yield* writeDefaultTheme({ settingsPath: paths.settingsPath, themeId }).pipe(
510 Effect.onError(() => revertPublish),
511 );
512 yield* cleanupPublish;
513 yield* Console.log(
514 targetIsFile
515 ? `Published ${target} as "${themeId}" and set it as the environment theme.\n`
516 : `Environment theme set to "${themeId}" in ${paths.settingsPath}.\n`,
517 );
518 }),
519 ),
520);
521
522const themeClearCommand = Command.make("clear", { baseDir: baseDirFlag }).pipe(
523 Command.withDescription("Remove the environment's theme; clients keep what they have."),
524 Command.withHandler((flags) =>
525 Effect.gen(function* () {
526 const paths = yield* resolveThemePaths(flags.baseDir);
527 yield* writeDefaultTheme({ settingsPath: paths.settingsPath, themeId: "" });
528 yield* Console.log(`Environment theme cleared in ${paths.settingsPath}.\n`);
529 }),
530 ),
531);
532
533const themeShowCommand = Command.make("show", { baseDir: baseDirFlag }).pipe(
534 Command.withDescription("Show the environment's theme and its published themes."),
535 Command.withHandler((flags) =>
536 Effect.gen(function* () {
537 const paths = yield* resolveThemePaths(flags.baseDir);
538 const { settings } = yield* readSettingsObject(paths.settingsPath);
539 const defaultTheme =
540 typeof settings.defaultTheme === "string" && settings.defaultTheme.length > 0
541 ? settings.defaultTheme
542 : null;
543
544 const published = (yield* readPublishedThemes(paths.themesDir))
545 .map((theme) => theme.id)
546 .toSorted();
547
548 yield* Console.log(
549 defaultTheme === null
550 ? "Environment theme: not set.\n"
551 : `Environment theme: "${defaultTheme}".\n`,
552 );
553 yield* Console.log(
554 published.length === 0
555 ? `Published themes: none (publish into ${paths.themesDir}).\n`
556 : `Published themes: ${published.join(", ")}.\n`,
557 );
558 }),
559 ),
560);
561
562export const themeCommand = Command.make("theme").pipe(
563 Command.withDescription("Inspect and set environment-wide theme defaults."),
564 Command.withSubcommands([themeSetCommand, themeClearCommand, themeShowCommand]),
565);