The best way to control Claude Code, Codex and more from any computer or phone

main
ts 304 lines 8.79 KB
Raw
1 import { PRIMARY_LOCAL_ENVIRONMENT_ID, type DesktopEnvironmentBootstrap } from "@t3tools/contracts";
2 import * as Schema from "effect/Schema";
3
4 import { isLocalEnvironmentDisabled } from "../../localEnvironment";
5 import { msg } from "gt-react";
6 import { m } from "../../i18n/messages";
7
8 const PrimaryEnvironmentTargetSource = Schema.Literals([
9 "configured",
10 "window-origin",
11 "desktop-managed",
12 ]);
13 type PrimaryEnvironmentTargetSource = typeof PrimaryEnvironmentTargetSource.Type;
14
15 const PrimaryEnvironmentUrlKind = Schema.Literals([
16 "http-base-url",
17 "websocket-base-url",
18 "development-server-url",
19 "window-location-url",
20 ]);
21 type PrimaryEnvironmentUrlKind = typeof PrimaryEnvironmentUrlKind.Type;
22
23 export class PrimaryEnvironmentUrlInvalidError extends Schema.TaggedError<PrimaryEnvironmentUrlInvalidError>()(
24 "PrimaryEnvironmentUrlInvalidError",
25 {
26 source: PrimaryEnvironmentTargetSource,
27 urlKind: PrimaryEnvironmentUrlKind,
28 cause: Schema.Defect(),
29 },
30 ) {
31 override get message(): string {
32 return `Could not parse ${this.urlKind} for the ${this.source} primary environment target.`;
33 }
34 }
35
36 export class PrimaryEnvironmentProtocolUnsupportedError extends Schema.TaggedError<PrimaryEnvironmentProtocolUnsupportedError>()(
37 "PrimaryEnvironmentProtocolUnsupportedError",
38 {
39 source: PrimaryEnvironmentTargetSource,
40 protocol: Schema.String,
41 },
42 ) {
43 override get message(): string {
44 return `The ${this.source} primary environment target uses unsupported protocol ${this.protocol}.`;
45 }
46 }
47
48 export class DesktopEnvironmentBootstrapIncompleteError extends Schema.TaggedError<DesktopEnvironmentBootstrapIncompleteError>()(
49 "DesktopEnvironmentBootstrapIncompleteError",
50 {
51 hasHttpBaseUrl: Schema.Boolean,
52 hasWsBaseUrl: Schema.Boolean,
53 },
54 ) {
55 override get message(): string {
56 const missing = [
57 ...(this.hasHttpBaseUrl ? [] : ["httpBaseUrl"]),
58 ...(this.hasWsBaseUrl ? [] : ["wsBaseUrl"]),
59 ];
60 return `Desktop bootstrap is missing ${missing.join(" and ")} for the local environment.`;
61 }
62 }
63
64 export class PrimaryEnvironmentDisabledError extends Schema.TaggedError<PrimaryEnvironmentDisabledError>()(
65 "PrimaryEnvironmentDisabledError",
66 {},
67 ) {
68 override get message(): string {
69 return m(msg("The local environment is disabled."));
70 }
71 }
72
73 export interface PrimaryEnvironmentTarget {
74 readonly source: PrimaryEnvironmentTargetSource;
75 readonly target: {
76 readonly httpBaseUrl: string;
77 readonly wsBaseUrl: string;
78 };
79 }
80
81 const LOOPBACK_HOSTNAMES = new Set(["127.0.0.1", "::1", "localhost"]);
82
83 function getDesktopLocalEnvironmentBootstrap(): DesktopEnvironmentBootstrap | null {
84 const bootstraps = window.desktopBridge?.getLocalEnvironmentBootstraps() ?? [];
85 return bootstraps.find((entry) => entry.id === PRIMARY_LOCAL_ENVIRONMENT_ID) ?? null;
86 }
87
88 function parseTargetUrl(input: {
89 readonly rawValue: string;
90 readonly baseUrl?: string;
91 readonly source: PrimaryEnvironmentTargetSource;
92 readonly urlKind: PrimaryEnvironmentUrlKind;
93 }): URL {
94 try {
95 return input.baseUrl === undefined
96 ? new URL(input.rawValue)
97 : new URL(input.rawValue, input.baseUrl);
98 } catch (cause) {
99 throw new PrimaryEnvironmentUrlInvalidError({
100 source: input.source,
101 urlKind: input.urlKind,
102 cause,
103 });
104 }
105 }
106
107 function normalizeBaseUrl(
108 rawValue: string,
109 source: PrimaryEnvironmentTargetSource,
110 urlKind: PrimaryEnvironmentUrlKind,
111 ): string {
112 return parseTargetUrl({
113 rawValue,
114 baseUrl: window.location.origin,
115 source,
116 urlKind,
117 }).toString();
118 }
119
120 function swapBaseUrlProtocol(
121 rawValue: string,
122 nextProtocol: "http:" | "https:" | "ws:" | "wss:",
123 urlKind: PrimaryEnvironmentUrlKind,
124 ): string {
125 const url = parseTargetUrl({
126 rawValue,
127 baseUrl: window.location.origin,
128 source: "configured",
129 urlKind,
130 });
131 url.protocol = nextProtocol;
132 return url.toString();
133 }
134
135 function normalizeHostname(hostname: string): string {
136 return hostname
137 .trim()
138 .toLowerCase()
139 .replace(/^\[(.*)\]$/, "$1");
140 }
141
142 export function isLoopbackHostname(hostname: string): boolean {
143 return LOOPBACK_HOSTNAMES.has(normalizeHostname(hostname));
144 }
145
146 function resolveHttpRequestBaseUrl(primaryTarget: PrimaryEnvironmentTarget): string {
147 const httpBaseUrl = primaryTarget.target.httpBaseUrl;
148 const configuredDevServerUrl = import.meta.env.VITE_DEV_SERVER_URL?.trim();
149 if (!configuredDevServerUrl) {
150 return httpBaseUrl;
151 }
152
153 const currentUrl = parseTargetUrl({
154 rawValue: window.location.href,
155 source: "window-origin",
156 urlKind: "window-location-url",
157 });
158 const targetUrl = parseTargetUrl({
159 rawValue: httpBaseUrl,
160 source: primaryTarget.source,
161 urlKind: "http-base-url",
162 });
163 const devServerUrl = parseTargetUrl({
164 rawValue: configuredDevServerUrl,
165 baseUrl: currentUrl.origin,
166 source: "configured",
167 urlKind: "development-server-url",
168 });
169
170 const isCurrentOriginDevServer =
171 (currentUrl.protocol === "http:" || currentUrl.protocol === "https:") &&
172 currentUrl.origin === devServerUrl.origin;
173
174 if (
175 !isCurrentOriginDevServer ||
176 currentUrl.origin === targetUrl.origin ||
177 !isLoopbackHostname(currentUrl.hostname) ||
178 !isLoopbackHostname(targetUrl.hostname)
179 ) {
180 return httpBaseUrl;
181 }
182
183 return currentUrl.origin;
184 }
185
186 function resolveConfiguredPrimaryTarget(): PrimaryEnvironmentTarget | null {
187 const configuredHttpBaseUrl = import.meta.env.VITE_HTTP_URL?.trim() || undefined;
188 const configuredWsBaseUrl = import.meta.env.VITE_WS_URL?.trim() || undefined;
189
190 if (!configuredHttpBaseUrl && !configuredWsBaseUrl) {
191 return null;
192 }
193
194 // Match URL scheme case-folding so uppercase WSS cannot downgrade to plaintext.
195 const resolvedHttpBaseUrl =
196 configuredHttpBaseUrl ??
197 (configuredWsBaseUrl?.toLowerCase().startsWith("wss:")
198 ? swapBaseUrlProtocol(configuredWsBaseUrl, "https:", "websocket-base-url")
199 : swapBaseUrlProtocol(configuredWsBaseUrl!, "http:", "websocket-base-url"));
200 const resolvedWsBaseUrl =
201 configuredWsBaseUrl ??
202 (configuredHttpBaseUrl?.toLowerCase().startsWith("https:")
203 ? swapBaseUrlProtocol(configuredHttpBaseUrl, "wss:", "http-base-url")
204 : swapBaseUrlProtocol(configuredHttpBaseUrl!, "ws:", "http-base-url"));
205
206 return {
207 source: "configured",
208 target: {
209 httpBaseUrl: normalizeBaseUrl(resolvedHttpBaseUrl, "configured", "http-base-url"),
210 wsBaseUrl: normalizeBaseUrl(resolvedWsBaseUrl, "configured", "websocket-base-url"),
211 },
212 };
213 }
214
215 function resolveWindowOriginPrimaryTarget(): PrimaryEnvironmentTarget {
216 const url = parseTargetUrl({
217 rawValue: window.location.origin,
218 source: "window-origin",
219 urlKind: "http-base-url",
220 });
221 const httpBaseUrl = url.toString();
222 if (url.protocol === "http:") {
223 url.protocol = "ws:";
224 } else if (url.protocol === "https:") {
225 url.protocol = "wss:";
226 } else {
227 throw new PrimaryEnvironmentProtocolUnsupportedError({
228 source: "window-origin",
229 protocol: url.protocol,
230 });
231 }
232 return {
233 source: "window-origin",
234 target: {
235 httpBaseUrl,
236 wsBaseUrl: url.toString(),
237 },
238 };
239 }
240
241 function resolveDesktopPrimaryTarget(): PrimaryEnvironmentTarget | null {
242 const desktopBootstrap = getDesktopLocalEnvironmentBootstrap();
243 if (!desktopBootstrap) {
244 return null;
245 }
246 if (!desktopBootstrap.httpBaseUrl && !desktopBootstrap.wsBaseUrl) {
247 return null;
248 }
249 if (!desktopBootstrap.httpBaseUrl || !desktopBootstrap.wsBaseUrl) {
250 throw new DesktopEnvironmentBootstrapIncompleteError({
251 hasHttpBaseUrl: Boolean(desktopBootstrap.httpBaseUrl),
252 hasWsBaseUrl: Boolean(desktopBootstrap.wsBaseUrl),
253 });
254 }
255
256 return {
257 source: "desktop-managed",
258 target: {
259 httpBaseUrl: normalizeBaseUrl(
260 desktopBootstrap.httpBaseUrl,
261 "desktop-managed",
262 "http-base-url",
263 ),
264 wsBaseUrl: normalizeBaseUrl(
265 desktopBootstrap.wsBaseUrl,
266 "desktop-managed",
267 "websocket-base-url",
268 ),
269 },
270 };
271 }
272
273 export function resolvePrimaryEnvironmentHttpUrl(
274 pathname: string,
275 searchParams?: Record<string, string>,
276 ): string {
277 const primaryTarget = readPrimaryEnvironmentTarget();
278 if (!primaryTarget) {
279 throw new PrimaryEnvironmentDisabledError();
280 }
281
282 const url = parseTargetUrl({
283 rawValue: resolveHttpRequestBaseUrl(primaryTarget),
284 source: primaryTarget.source,
285 urlKind: "http-base-url",
286 });
287 url.pathname = pathname;
288 if (searchParams) {
289 url.search = new URLSearchParams(searchParams).toString();
290 }
291 return url.toString();
292 }
293
294 /** Null only for desktop with its local environment disabled; other hosts fall back to page origin. */
295 export function readPrimaryEnvironmentTarget(): PrimaryEnvironmentTarget | null {
296 if (isLocalEnvironmentDisabled()) {
297 return null;
298 }
299 return (
300 resolveDesktopPrimaryTarget() ??
301 resolveConfiguredPrimaryTarget() ??
302 resolveWindowOriginPrimaryTarget()
303 );
304 }