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