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

target.ts

302 lines8.7 KB

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