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

theme.ts

566 lines20.7 KB

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