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

DesktopEnvironment.ts

290 lines10.4 KB

1import type {
2 DesktopAppBranding,
3 DesktopAppStageLabel,
4 DesktopRuntimeArch,
5 DesktopRuntimeInfo,
6} from "@t3tools/contracts";
7import * as Config from "effect/Config";
8import * as Context from "effect/Context";
9import * as Effect from "effect/Effect";
10import * as Layer from "effect/Layer";
11import * as Option from "effect/Option";
12import * as Path from "effect/Path";
13​
14import * as DesktopAppSettings from "../settings/DesktopAppSettings.ts";
15import * as DesktopConfig from "./DesktopConfig.ts";
16import { resolveLinuxDesktopEntryName } from "./DesktopEarlyElectronStartup.ts";
17import { resolveDesktopBaseDir, resolveDesktopStateDir } from "./DesktopStatePaths.ts";
18import { isNightlyDesktopVersion } from "../updates/updateChannels.ts";
19import type { OtlpProtocol } from "@t3tools/shared/observability";
20​
21export interface MakeDesktopEnvironmentInput {
22 readonly dirname: string;
23 readonly homeDirectory: string;
24 readonly platform: NodeJS.Platform;
25 readonly processArch: string;
26 readonly appVersion: string;
27 readonly appPath: string;
28 readonly isPackaged: boolean;
29 readonly resourcesPath: string;
30 readonly runningUnderArm64Translation: boolean;
32​
33export class DesktopEnvironment extends Context.Service<
34 DesktopEnvironment,
35 {
36 readonly path: Path.Path;
37 readonly dirname: string;
38 readonly platform: NodeJS.Platform;
39 readonly processArch: string;
40 readonly isPackaged: boolean;
41 readonly isDevelopment: boolean;
42 readonly appVersion: string;
43 readonly appPath: string;
44 readonly resourcesPath: string;
45 readonly homeDirectory: string;
46 readonly appDataDirectory: string;
47 readonly baseDir: string;
48 readonly stateDir: string;
49 readonly desktopSettingsPath: string;
50 readonly clientSettingsPath: string;
51 readonly savedEnvironmentRegistryPath: string;
52 readonly serverSettingsPath: string;
53 readonly logDir: string;
54 readonly browserArtifactsDir: string;
55 readonly rootDir: string;
56 readonly appRoot: string;
57 // Root of the tree containing apps/server/dist and node_modules for the
58 // backend. Equals appRoot everywhere except packaged Windows, where the
59 // server tree ships as the resources/server.asar sidecar (see
60 // scripts/build-desktop-artifact.ts) that the asar-aware
61 // ELECTRON_RUN_AS_NODE primary reads in place and the WSL backend
62 // extracts on demand (see DesktopWslServerTree).
63 readonly serverRoot: string;
64 readonly backendEntryPath: string;
65 // Built web client the packaged renderer is served from over t3code://app.
66 readonly clientAssetsDir: string;
67 readonly backendCwd: string;
68 readonly packagedClientRootCandidates: readonly string[];
69 readonly preloadPath: string;
70 readonly appUpdateYmlPath: string;
71 readonly devServerUrl: Option.Option<URL>;
72 readonly devRemoteT3ServerEntryPath: Option.Option<string>;
73 readonly configuredBackendPort: Option.Option<number>;
74 readonly commitHashOverride: Option.Option<string>;
75 readonly otlpTracesUrl: Option.Option<string>;
76 readonly otlpExportIntervalMs: number;
77 readonly otlpHeaders: Option.Option<Record<string, string>>;
78 readonly otlpProtocol: OtlpProtocol;
79 readonly branding: DesktopAppBranding;
80 readonly displayName: string;
81 readonly appUserModelId: string;
82 readonly linuxDesktopEntryName: string;
83 readonly linuxWmClass: string;
84 readonly linuxApplicationsDir: string;
85 readonly appImagePath: Option.Option<string>;
86 readonly userDataDirName: string;
87 readonly legacyUserDataDirName: string;
88 readonly defaultDesktopSettings: DesktopAppSettings.DesktopSettings;
89 readonly runtimeInfo: DesktopRuntimeInfo;
90 readonly resolvePickFolderDefaultPath: (rawOptions: unknown) => Option.Option<string>;
91 readonly resolveResourcePathCandidates: (fileName: string) => readonly string[];
92 }
93>()("@t3tools/desktop/app/DesktopEnvironment") {}
94​
95const APP_BASE_NAME = "T3 Code";
96​
97function resolveDesktopAppStageLabel(input: {
98 readonly isDevelopment: boolean;
99 readonly appVersion: string;
100}): DesktopAppStageLabel {
101 if (input.isDevelopment) {
102 return "Dev";
103 }
104​
105 return isNightlyDesktopVersion(input.appVersion) ? "Nightly" : "Alpha";
107​
108export function resolveDesktopAppBranding(input: {
109 readonly isDevelopment: boolean;
110 readonly appVersion: string;
111}): DesktopAppBranding {
112 const stageLabel = resolveDesktopAppStageLabel(input);
113 return {
114 baseName: APP_BASE_NAME,
115 stageLabel,
116 displayName: `${APP_BASE_NAME} (${stageLabel})`,
117 };
119​
120function normalizeDesktopArch(arch: string): DesktopRuntimeArch {
121 if (arch === "arm64") return "arm64";
122 if (arch === "x64") return "x64";
123 return "other";
125​
126function resolveDesktopRuntimeInfo(input: {
127 readonly platform: NodeJS.Platform;
128 readonly processArch: string;
129 readonly runningUnderArm64Translation: boolean;
130}): DesktopRuntimeInfo {
131 const appArch = normalizeDesktopArch(input.processArch);
132​
133 if (input.platform !== "darwin") {
134 return {
135 hostArch: appArch,
136 appArch,
137 runningUnderArm64Translation: false,
138 };
139 }
140​
141 const hostArch = appArch === "arm64" || input.runningUnderArm64Translation ? "arm64" : appArch;
142​
143 return {
144 hostArch,
145 appArch,
146 runningUnderArm64Translation: input.runningUnderArm64Translation,
147 };
149​
150const make = Effect.fn("desktop.environment.make")(function* (
151 input: MakeDesktopEnvironmentInput,
152): Effect.fn.Return<DesktopEnvironment["Service"], Config.ConfigError, Path.Path> {
153 const path = yield* Path.Path;
154 const config = yield* DesktopConfig.DesktopConfig;
155 const homeDirectory = input.homeDirectory;
156 const devServerUrl = config.devServerUrl;
157 const isDevelopment = Option.isSome(devServerUrl);
158 const appDataDirectory =
159 input.platform === "win32"
160 ? Option.getOrElse(config.appDataDirectory, () =>
161 path.join(homeDirectory, "AppData", "Roaming"),
162 )
163 : input.platform === "darwin"
164 ? path.join(homeDirectory, "Library", "Application Support")
165 : Option.getOrElse(config.xdgConfigHome, () => path.join(homeDirectory, ".config"));
166 const baseDir = resolveDesktopBaseDir({
167 homeDirectory,
168 joinPath: path.join,
169 t3Home: config.t3Home,
170 });
171 const rootDir = path.resolve(input.dirname, "../../..");
172 const appRoot = input.isPackaged ? input.appPath : rootDir;
173 const serverRoot =
174 input.isPackaged && input.platform === "win32"
175 ? path.join(input.resourcesPath, "server.asar")
176 : appRoot;
177 const branding = resolveDesktopAppBranding({
178 isDevelopment,
179 appVersion: input.appVersion,
180 });
181 const displayName = branding.displayName;
182 const stateDir = resolveDesktopStateDir({
183 baseDir,
184 isDevelopment,
185 joinPath: path.join,
186 t3Home: config.t3Home,
187 });
188 const userDataDirName = isDevelopment ? "t3code-dev" : "t3code";
189 const legacyUserDataDirName = isDevelopment ? "T3 Code (Dev)" : "T3 Code (Alpha)";
190 const linuxApplicationsDir = path.join(
191 Option.getOrElse(config.xdgDataHome, () => path.join(homeDirectory, ".local", "share")),
192 "applications",
193 );
194 const resourcesPath = input.resourcesPath;
195​
196 return DesktopEnvironment.of({
197 path,
198 dirname: input.dirname,
199 platform: input.platform,
200 processArch: input.processArch,
201 isPackaged: input.isPackaged,
202 isDevelopment,
203 appVersion: input.appVersion,
204 appPath: input.appPath,
205 resourcesPath,
206 homeDirectory,
207 appDataDirectory,
208 baseDir,
209 stateDir,
210 desktopSettingsPath: path.join(stateDir, "desktop-settings.json"),
211 clientSettingsPath: path.join(stateDir, "client-settings.json"),
212 savedEnvironmentRegistryPath: path.join(stateDir, "saved-environments.json"),
213 serverSettingsPath: path.join(stateDir, "settings.json"),
214 logDir: path.join(stateDir, "logs"),
215 browserArtifactsDir: path.join(stateDir, "browser-artifacts"),
216 rootDir,
217 appRoot,
218 serverRoot,
219 backendEntryPath: path.join(serverRoot, "apps/server/dist/bin.mjs"),
220 clientAssetsDir: path.join(serverRoot, "apps/server/dist/client"),
221 backendCwd: input.isPackaged ? homeDirectory : appRoot,
222 packagedClientRootCandidates: [
223 path.join(input.appPath, "apps/server/dist/client"),
224 path.join(resourcesPath, "app.asar.unpacked/apps/server/dist/client"),
225 ],
226 preloadPath: path.join(input.dirname, "preload.cjs"),
227 appUpdateYmlPath: input.isPackaged
228 ? path.join(resourcesPath, "app-update.yml")
229 : path.join(input.appPath, "dev-app-update.yml"),
230 devServerUrl,
231 devRemoteT3ServerEntryPath: config.devRemoteT3ServerEntryPath,
232 configuredBackendPort: config.configuredBackendPort,
233 commitHashOverride: config.commitHashOverride,
234 otlpTracesUrl: config.otlpTracesUrl,
235 otlpExportIntervalMs: config.otlpExportIntervalMs,
236 otlpHeaders: config.otlpHeaders,
237 otlpProtocol: config.otlpProtocol,
238 branding,
239 displayName,
240 appUserModelId: Option.getOrElse(config.appUserModelIdOverride, () =>
241 isDevelopment ? "com.t3tools.t3code.dev" : "com.t3tools.t3code",
242 ),
243 linuxDesktopEntryName: resolveLinuxDesktopEntryName(isDevelopment),
244 linuxWmClass: isDevelopment ? "t3code-dev" : "t3code",
245 linuxApplicationsDir,
246 appImagePath: config.appImagePath,
247 userDataDirName,
248 legacyUserDataDirName,
249 defaultDesktopSettings: DesktopAppSettings.resolveDefaultDesktopSettings(input.appVersion),
250 runtimeInfo: resolveDesktopRuntimeInfo({
251 platform: input.platform,
252 processArch: input.processArch,
253 runningUnderArm64Translation: input.runningUnderArm64Translation,
254 }),
255 resolvePickFolderDefaultPath: (rawOptions) => {
256 if (typeof rawOptions !== "object" || rawOptions === null) {
257 return Option.none();
258 }
259​
260 const { initialPath } = rawOptions as { initialPath?: unknown };
261 if (typeof initialPath !== "string") {
262 return Option.none();
263 }
264​
265 const trimmedPath = initialPath.trim();
266 if (trimmedPath.length === 0) {
267 return Option.none();
268 }
269​
270 if (trimmedPath === "~") {
271 return Option.some(homeDirectory);
272 }
273​
274 if (trimmedPath.startsWith("~/") || trimmedPath.startsWith("~\\")) {
275 return Option.some(path.join(homeDirectory, trimmedPath.slice(2)));
276 }
277​
278 return Option.some(path.resolve(trimmedPath));
279 },
280 resolveResourcePathCandidates: (fileName) => [
281 path.join(input.dirname, "../resources", fileName),
282 path.join(input.dirname, "../prod-resources", fileName),
283 path.join(resourcesPath, "resources", fileName),
284 path.join(resourcesPath, fileName),
285 ],
286 });
287});
288​
289export const layer = (input: MakeDesktopEnvironmentInput) =>
290 Layer.effect(DesktopEnvironment, make(input));