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

theme.ts

492 lines17.5 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 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 }
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 }
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 }
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 }
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 }
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 }
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 }
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 }
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 }
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 }
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 }
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 }
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 }
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/** Propagate read errors to avoid overwriting unread settings with a sparse file. */
177const readSettingsObject = Effect.fn(function* (settingsPath: string) {
178 const fs = yield* FileSystem.FileSystem;
179 const exists = yield* fs
180 .exists(settingsPath)
181 .pipe(Effect.mapError((cause) => new ThemeSettingsUnreadableError({ settingsPath, cause })));
182 if (!exists) return { raw: "", settings: {} };
183​
184 const raw = yield* fs
185 .readFileString(settingsPath)
186 .pipe(Effect.mapError((cause) => new ThemeSettingsUnreadableError({ settingsPath, cause })));
187 if (raw.trim().length === 0) return { raw, settings: {} };
188​
189 const settings = yield* decodeSettingsJson(raw).pipe(
190 Effect.mapError((cause) => new ThemeSettingsMalformedError({ settingsPath, cause })),
191 );
192 return { raw, settings };
193});
194​
195/** The server's in-process semaphore cannot serialize writes from this process. */
196const CONCURRENT_WRITE_ATTEMPTS = 5;
197​
198const writeDefaultTheme = Effect.fn(function* (input: {
199 readonly settingsPath: string;
200 readonly themeId: string;
201}) {
202 const fs = yield* FileSystem.FileSystem;
203​
204 for (let attempt = 1; ; attempt++) {
205 const { raw, settings } = yield* readSettingsObject(input.settingsPath);
206 const setAt = DateTime.formatIso(yield* DateTime.now);
207 const next =
208 input.themeId.length > 0
209 ? // The timestamp lets clients reapply the same theme.
210 { ...settings, defaultTheme: input.themeId, defaultThemeSetAt: setAt }
211 : Object.fromEntries(
212 Object.entries(settings).filter(
213 ([key]) => key !== "defaultTheme" && key !== "defaultThemeSetAt",
214 ),
215 );
216​
217 const contents = yield* encodeSettingsJson(next);
218 const current = yield* fs
219 .readFileString(input.settingsPath)
220 .pipe(Effect.orElseSucceed(() => ""));
221 if (current !== raw) {
222 if (attempt >= CONCURRENT_WRITE_ATTEMPTS) {
223 return yield* new ThemeSettingsBusyError({
224 settingsPath: input.settingsPath,
225 attempts: CONCURRENT_WRITE_ATTEMPTS,
226 });
227 }
228 continue;
229 }
230​
231 yield* writeFileStringAtomically({
232 filePath: input.settingsPath,
233 contents: `${contents}\n`,
234 }).pipe(
235 Effect.mapError(
236 (cause) => new ThemeSettingsWriteError({ settingsPath: input.settingsPath, cause }),
237 ),
238 );
239 return;
240 }
241});
242​
243const publishThemeFile = Effect.fn(function* (input: {
244 readonly themesDir: string;
245 readonly filePath: string;
246 readonly explicitId: Option.Option<string>;
247}) {
248 const fs = yield* FileSystem.FileSystem;
249 const path = yield* Path.Path;
250 const info = yield* fs
251 .stat(input.filePath)
252 .pipe(
253 Effect.mapError((cause) => new ThemeFileUnreadableError({ filePath: input.filePath, cause })),
254 );
255 if (info.type !== "File") {
256 return yield* new ThemeFileUnreadableError({ filePath: input.filePath });
257 }
258 if (Number(info.size) > MAX_THEME_FILE_BYTES) {
259 return yield* new ThemeFileTooLargeError({
260 filePath: input.filePath,
261 limit: MAX_THEME_FILE_BYTES,
262 });
263 }
264​
265 const resolvedSource = yield* fs
266 .realPath(input.filePath)
267 .pipe(
268 Effect.mapError((cause) => new ThemeFileUnreadableError({ filePath: input.filePath, cause })),
269 );
270 const raw = readThemeFileGuarded(resolvedSource, MAX_THEME_FILE_BYTES);
271 if (raw === null) {
272 return yield* new ThemeFileUnreadableError({ filePath: input.filePath });
273 }
274​
275 const decoded = decodeThemeFileJsonExit(raw);
276 if (decoded._tag === "Failure") {
277 return yield* new ThemeFileInvalidError({ filePath: input.filePath, cause: decoded.cause });
278 }
279 if (!environmentThemeFileHasColors(decoded.value)) {
280 return yield* new ThemeFileColorlessError({ filePath: input.filePath });
281 }
282​
283 const fileBasename = path.basename(input.filePath, ".json");
284 const themeId = Option.getOrElse(input.explicitId, () => fileBasename);
285 // Match watcher validation so published files will not be skipped.
286 if (!isEnvironmentThemeId(themeId) || UNPUBLISHABLE_THEME_IDS.has(themeId)) {
287 return yield* new ThemeFileIdInvalidError({ themeId, filePath: input.filePath });
288 }
289​
290 const destinationPath = path.join(input.themesDir, `${themeId}.json`);
291 // Non-JSON suffixes hide these from the watcher; PIDs isolate concurrent publishers.
292 const backupPath = `${destinationPath}.rollback-${process.pid}`;
293 const stagingPath = `${destinationPath}.staging-${process.pid}`;
294 yield* fs
295 .makeDirectory(input.themesDir, { recursive: true })
296 .pipe(Effect.mapError((cause) => new ThemePublishError({ themesDir: input.themesDir, cause })));
297​
298 const publishFailure = (cause: unknown) =>
299 new ThemePublishError({ themesDir: input.themesDir, cause });
300​
301 // O_EXCL prevents following a symlink at the predictable staging path.
302 // Preserve bytes exactly: even an added newline could exceed the watcher's size limit.
303 const stagedIno = yield* Effect.try({
304 try: () => {
305 try {
306 NodeFS.unlinkSync(stagingPath);
307 } catch {}
308 const fd = NodeFS.openSync(
309 stagingPath,
310 NodeFS.constants.O_WRONLY | NodeFS.constants.O_CREAT | NodeFS.constants.O_EXCL,
311 0o644,
312 );
313 try {
314 NodeFS.writeFileSync(fd, raw);
315 return NodeFS.fstatSync(fd).ino;
316 } finally {
317 NodeFS.closeSync(fd);
318 }
319 },
320 catch: publishFailure,
321 });
322​
323 // Atomic rename avoids a check/replace race and preserves the exact entry for rollback.
324 const hadPrevious = yield* Effect.try({
325 try: () => {
326 try {
327 NodeFS.renameSync(destinationPath, backupPath);
328 return true;
329 } catch (error) {
330 if ((error as NodeJS.ErrnoException).code === "ENOENT") return false;
331 throw error;
332 }
333 },
334 catch: publishFailure,
335 });
336​
337 const revert = Effect.sync(() => {
338 try {
339 NodeFS.unlinkSync(stagingPath);
340 } catch {}
341 try {
342 // Only replace this process's inode or an empty destination; concurrent publishers win.
343 const destinationIno = (() => {
344 try {
345 return NodeFS.lstatSync(destinationPath).ino;
346 } catch {
347 return null;
348 }
349 })();
350 if (hadPrevious) {
351 if (destinationIno === null || destinationIno === stagedIno) {
352 NodeFS.renameSync(backupPath, destinationPath);
353 } else {
354 NodeFS.unlinkSync(backupPath);
355 }
356 } else if (destinationIno === stagedIno) {
357 NodeFS.unlinkSync(destinationPath);
358 }
359 } catch {}
360 });
361 const cleanup = Effect.sync(() => {
362 try {
363 if (hadPrevious) NodeFS.unlinkSync(backupPath);
364 } catch {}
365 });
366​
367 yield* Effect.try({
368 try: () => NodeFS.renameSync(stagingPath, destinationPath),
369 catch: publishFailure,
370 }).pipe(Effect.onError(() => revert));
371​
372 return { themeId, revert, cleanup };
373});
374​
375/** Web and desktop cannot resolve the mobile default, and mobile does not follow this setting. */
376const resolvableThemeIds = Effect.fn(function* (themesDir: string) {
377 const published = yield* readPublishedThemes(themesDir);
378 return [...BUILT_IN_THEME_IDS, ...published.map((theme) => theme.id)].toSorted();
379});
380​
381const themeSetCommand = Command.make("set", {
382 baseDir: baseDirFlag,
383 id: Flag.String("id").pipe(
384 Flag.withDescription("Theme id to publish a file under, instead of its filename."),
385 Flag.optional,
386 ),
387 theme: Argument.String("theme").pipe(
388 Argument.withDescription(
389 '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.',
390 ),
391 ),
392}).pipe(
393 Command.withDescription("Set the environment's theme; connected clients switch to it."),
394 Command.withHandler((flags) =>
395 Effect.gen(function* () {
396 const fs = yield* FileSystem.FileSystem;
397 const target = yield* expandHomePath(flags.theme.trim());
398 if (target.length === 0) {
399 return yield* new ThemeTargetMissingError();
400 }
401 const paths = yield* resolveThemePaths(flags.baseDir);
402​
403 // A bare theme id must not publish a same-named file that happens to exist in cwd.
404 const looksLikePath =
405 target.endsWith(".json") ||
406 target.includes("/") ||
407 target.includes("\\") ||
408 target.startsWith("~");
409 const targetIsFile =
410 looksLikePath && (yield* fs.exists(target).pipe(Effect.orElseSucceed(() => false)));
411 let themeId: string;
412 let revertPublish: Effect.Effect<void> = Effect.void;
413 let cleanupPublish: Effect.Effect<void> = Effect.void;
414 if (targetIsFile) {
415 yield* readSettingsObject(paths.settingsPath);
416 const published = yield* publishThemeFile({
417 themesDir: paths.themesDir,
418 filePath: target,
419 explicitId: flags.id,
420 });
421 themeId = published.themeId;
422 revertPublish = published.revert;
423 cleanupPublish = published.cleanup;
424 } else if (looksLikePath) {
425 return yield* new ThemeFileUnreadableError({ filePath: target });
426 } else if (isEnvironmentThemeId(target)) {
427 const known = yield* resolvableThemeIds(paths.themesDir);
428 if (!known.includes(target)) {
429 return yield* new ThemeIdUnknownError({ themeId: target, known });
430 }
431 themeId = target;
432 } else {
433 return yield* new ThemeIdInvalidError({ themeId: target });
434 }
435​
436 yield* writeDefaultTheme({ settingsPath: paths.settingsPath, themeId }).pipe(
437 Effect.onError(() => revertPublish),
438 );
439 yield* cleanupPublish;
440 yield* Console.log(
441 targetIsFile
442 ? `Published ${target} as "${themeId}" and set it as the environment theme.\n`
443 : `Environment theme set to "${themeId}" in ${paths.settingsPath}.\n`,
444 );
445 }),
446 ),
447);
448​
449const themeClearCommand = Command.make("clear", { baseDir: baseDirFlag }).pipe(
450 Command.withDescription("Remove the environment's theme; clients keep what they have."),
451 Command.withHandler((flags) =>
452 Effect.gen(function* () {
453 const paths = yield* resolveThemePaths(flags.baseDir);
454 yield* writeDefaultTheme({ settingsPath: paths.settingsPath, themeId: "" });
455 yield* Console.log(`Environment theme cleared in ${paths.settingsPath}.\n`);
456 }),
457 ),
458);
459​
460const themeShowCommand = Command.make("show", { baseDir: baseDirFlag }).pipe(
461 Command.withDescription("Show the environment's theme and its published themes."),
462 Command.withHandler((flags) =>
463 Effect.gen(function* () {
464 const paths = yield* resolveThemePaths(flags.baseDir);
465 const { settings } = yield* readSettingsObject(paths.settingsPath);
466 const defaultTheme =
467 typeof settings.defaultTheme === "string" && settings.defaultTheme.length > 0
468 ? settings.defaultTheme
469 : null;
470​
471 const published = (yield* readPublishedThemes(paths.themesDir))
472 .map((theme) => theme.id)
473 .toSorted();
474​
475 yield* Console.log(
476 defaultTheme === null
477 ? "Environment theme: not set.\n"
478 : `Environment theme: "${defaultTheme}".\n`,
479 );
480 yield* Console.log(
481 published.length === 0
482 ? `Published themes: none (publish into ${paths.themesDir}).\n`
483 : `Published themes: ${published.join(", ")}.\n`,
484 );
485 }),
486 ),
487);
488​
489export const themeCommand = Command.make("theme").pipe(
490 Command.withDescription("Inspect and set environment-wide theme defaults."),
491 Command.withSubcommands([themeSetCommand, themeClearCommand, themeShowCommand]),
492);