Open History to see the last commit
1import type { NativeAppIconReference } from "@t3tools/contracts";
2import * as Cache from "effect/Cache";
3import type * as Cause from "effect/Cause";
4import * as Context from "effect/Context";
5import * as Duration from "effect/Duration";
6import * as Effect from "effect/Effect";
7import * as Exit from "effect/Exit";
8import * as FileSystem from "effect/FileSystem";
9import * as Layer from "effect/Layer";
10import type * as PlatformError from "effect/PlatformError";
11import * as Semaphore from "effect/Semaphore";
12import * as HostProcess from "@t3tools/shared/HostProcess";
13
14import { darwinSource } from "./nativeAppIcons/darwin.ts";
15import { linuxSource } from "./nativeAppIcons/linux.ts";
16import { win32Source } from "./nativeAppIcons/win32.ts";
17import type { NativeAppIconSource } from "./nativeAppIcons/source.ts";
18
19const RESOLUTION_CACHE_TTL = Duration.hours(1);
20const RESOLUTION_CACHE_MAX_ENTRIES = 256;
21
22/** One source per platform; a platform without one resolves nothing. */
23const SOURCES: ReadonlyArray<NativeAppIconSource> = [darwinSource, linuxSource, win32Source];
24
25/** Resolves and caches host application icons without exposing host paths to clients. */
26export class NativeAppIconResolver extends Context.Service<
27 NativeAppIconResolver,
28 {
29 /** Returns a cached image path for the application, or `null` when no icon is available. */
30 readonly resolve: (app: NativeAppIconReference) => Effect.Effect<string | null>;
31 }
32>()("t3/assets/NativeAppIconResolver") {}
33
34function appCacheKey(app: NativeAppIconReference): string {
35 return JSON.stringify(app);
36}
37
38function appFromCacheKey(key: string): NativeAppIconReference {
39 return JSON.parse(key) as NativeAppIconReference;
40}
41
42function containsControlCharacter(value: string): boolean {
43 return [...value].some((character) => {
44 const codePoint = character.codePointAt(0) ?? 0;
45 return codePoint <= 31 || codePoint === 127;
46 });
47}
48
49/** @public */
50export const make = Effect.gen(function* () {
51 const fileSystem = yield* FileSystem.FileSystem;
52 const hostPlatform = yield* HostProcess.Platform;
53 const source = SOURCES.find((candidate) => candidate.platform === hostPlatform);
54 const resolutionSemaphore = yield* Semaphore.make(2);
55 const resolutionCache: Cache.Cache<
56 string,
57 string | null,
58 PlatformError.PlatformError | Cause.TimeoutError
59 > = yield* Cache.makeWith(
60 (key: string) =>
61 source
62 ? resolutionSemaphore.withPermits(1)(source.resolve(appFromCacheKey(key)))
63 : Effect.succeed(null),
64 {
65 capacity: RESOLUTION_CACHE_MAX_ENTRIES,
66 timeToLive: Exit.match({
67 onSuccess: () => RESOLUTION_CACHE_TTL,
68 onFailure: () => Duration.zero,
69 }),
70 },
71 );
72
73 const cachedFileExists = (filePath: string) =>
74 fileSystem.stat(filePath).pipe(
75 Effect.map((info) => info.type === "File"),
76 Effect.catchTags({
77 PlatformError: (error) =>
78 error.reason._tag === "NotFound" ? Effect.succeed(false) : Effect.fail(error),
79 }),
80 );
81
82 const resolveAttempt = Effect.fn("NativeAppIconResolver.resolve")(function* (
83 app: NativeAppIconReference,
84 ) {
85 if (!source || (app._tag === "display-name" && containsControlCharacter(app.displayName))) {
86 return null;
87 }
88
89 const key = appCacheKey(app);
90 const cached = yield* Cache.get(resolutionCache, key);
91 if (cached === null) return null;
92 if (yield* cachedFileExists(cached)) return cached;
93
94 yield* Cache.invalidate(resolutionCache, key);
95 return yield* Cache.get(resolutionCache, key);
96 });
97
98 const resolve: NativeAppIconResolver["Service"]["resolve"] = (app) =>
99 resolveAttempt(app).pipe(
100 Effect.tapError((cause) =>
101 Effect.logDebug("Failed to resolve native application icon.", { app, cause }),
102 ),
103 Effect.orElseSucceed(() => null),
104 );
105
106 return NativeAppIconResolver.of({ resolve });
107});
108
109export const layer = Layer.effect(NativeAppIconResolver, make);