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

target.ts

294 lines8.6 KB

1import { PRIMARY_LOCAL_ENVIRONMENT_ID, type DesktopEnvironmentBootstrap } from "@t3tools/contracts";
2import * as Schema from "effect/Schema";
3​
4const PrimaryEnvironmentTargetSource = Schema.Literals([
5 "configured",
6 "window-origin",
7 "desktop-managed",
8]);
9type PrimaryEnvironmentTargetSource = typeof PrimaryEnvironmentTargetSource.Type;
10​
11const PrimaryEnvironmentUrlKind = Schema.Literals([
12 "http-base-url",
13 "websocket-base-url",
14 "development-server-url",
15 "window-location-url",
16]);
17type PrimaryEnvironmentUrlKind = typeof PrimaryEnvironmentUrlKind.Type;
18​
19export class PrimaryEnvironmentUrlInvalidError extends Schema.TaggedErrorClass<PrimaryEnvironmentUrlInvalidError>()(
20 "PrimaryEnvironmentUrlInvalidError",
21 {
22 source: PrimaryEnvironmentTargetSource,
23 urlKind: PrimaryEnvironmentUrlKind,
24 cause: Schema.Defect(),
25 },
26) {
27 override get message(): string {
28 return `Could not parse ${this.urlKind} for the ${this.source} primary environment target.`;
29 }
31​
32export class PrimaryEnvironmentProtocolUnsupportedError extends Schema.TaggedErrorClass<PrimaryEnvironmentProtocolUnsupportedError>()(
33 "PrimaryEnvironmentProtocolUnsupportedError",
34 {
35 source: PrimaryEnvironmentTargetSource,
36 protocol: Schema.String,
37 },
38) {
39 override get message(): string {
40 return `The ${this.source} primary environment target uses unsupported protocol ${this.protocol}.`;
41 }
43​
44export class DesktopEnvironmentBootstrapIncompleteError extends Schema.TaggedErrorClass<DesktopEnvironmentBootstrapIncompleteError>()(
45 "DesktopEnvironmentBootstrapIncompleteError",
46 {
47 hasHttpBaseUrl: Schema.Boolean,
48 hasWsBaseUrl: Schema.Boolean,
49 },
50) {
51 override get message(): string {
52 const missing = [
53 ...(this.hasHttpBaseUrl ? [] : ["httpBaseUrl"]),
54 ...(this.hasWsBaseUrl ? [] : ["wsBaseUrl"]),
55 ];
56 return `Desktop bootstrap is missing ${missing.join(" and ")} for the local environment.`;
57 }
59​
60export const isPrimaryEnvironmentUrlInvalidError = Schema.is(PrimaryEnvironmentUrlInvalidError);
61export const isPrimaryEnvironmentProtocolUnsupportedError = Schema.is(
62 PrimaryEnvironmentProtocolUnsupportedError,
63);
64export const isDesktopEnvironmentBootstrapIncompleteError = Schema.is(
65 DesktopEnvironmentBootstrapIncompleteError,
66);
67​
68export interface PrimaryEnvironmentTarget {
69 readonly source: PrimaryEnvironmentTargetSource;
70 readonly target: {
71 readonly httpBaseUrl: string;
72 readonly wsBaseUrl: string;
73 };
75​
76const LOOPBACK_HOSTNAMES = new Set(["127.0.0.1", "::1", "localhost"]);
77​
78function getDesktopLocalEnvironmentBootstrap(): DesktopEnvironmentBootstrap | null {
79 // The primary (Windows-native) backend keeps the "primary" id. The
80 // plural list may include a second WSL entry; the primary-target
81 // resolver only cares about the primary, so just find it.
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 const resolvedHttpBaseUrl =
193 configuredHttpBaseUrl ??
194 (configuredWsBaseUrl?.startsWith("wss:")
195 ? swapBaseUrlProtocol(configuredWsBaseUrl, "https:", "websocket-base-url")
196 : swapBaseUrlProtocol(configuredWsBaseUrl!, "http:", "websocket-base-url"));
197 const resolvedWsBaseUrl =
198 configuredWsBaseUrl ??
199 (configuredHttpBaseUrl?.startsWith("https:")
200 ? swapBaseUrlProtocol(configuredHttpBaseUrl, "wss:", "http-base-url")
201 : swapBaseUrlProtocol(configuredHttpBaseUrl!, "ws:", "http-base-url"));
202​
203 return {
204 source: "configured",
205 target: {
206 httpBaseUrl: normalizeBaseUrl(resolvedHttpBaseUrl, "configured", "http-base-url"),
207 wsBaseUrl: normalizeBaseUrl(resolvedWsBaseUrl, "configured", "websocket-base-url"),
208 },
209 };
211​
212function resolveWindowOriginPrimaryTarget(): PrimaryEnvironmentTarget {
213 const url = parseTargetUrl({
214 rawValue: window.location.origin,
215 source: "window-origin",
216 urlKind: "http-base-url",
217 });
218 const httpBaseUrl = url.toString();
219 if (url.protocol === "http:") {
220 url.protocol = "ws:";
221 } else if (url.protocol === "https:") {
222 url.protocol = "wss:";
223 } else {
224 throw new PrimaryEnvironmentProtocolUnsupportedError({
225 source: "window-origin",
226 protocol: url.protocol,
227 });
228 }
229 return {
230 source: "window-origin",
231 target: {
232 httpBaseUrl,
233 wsBaseUrl: url.toString(),
234 },
235 };
237​
238function resolveDesktopPrimaryTarget(): PrimaryEnvironmentTarget | null {
239 const desktopBootstrap = getDesktopLocalEnvironmentBootstrap();
240 if (!desktopBootstrap) {
241 return null;
242 }
243 if (!desktopBootstrap.httpBaseUrl && !desktopBootstrap.wsBaseUrl) {
244 return null;
245 }
246 if (!desktopBootstrap.httpBaseUrl || !desktopBootstrap.wsBaseUrl) {
247 throw new DesktopEnvironmentBootstrapIncompleteError({
248 hasHttpBaseUrl: Boolean(desktopBootstrap.httpBaseUrl),
249 hasWsBaseUrl: Boolean(desktopBootstrap.wsBaseUrl),
250 });
251 }
252​
253 return {
254 source: "desktop-managed",
255 target: {
256 httpBaseUrl: normalizeBaseUrl(
257 desktopBootstrap.httpBaseUrl,
258 "desktop-managed",
259 "http-base-url",
260 ),
261 wsBaseUrl: normalizeBaseUrl(
262 desktopBootstrap.wsBaseUrl,
263 "desktop-managed",
264 "websocket-base-url",
265 ),
266 },
267 };
269​
270export function resolvePrimaryEnvironmentHttpUrl(
271 pathname: string,
272 searchParams?: Record<string, string>,
273): string {
274 const primaryTarget = readPrimaryEnvironmentTarget();
275​
276 const url = parseTargetUrl({
277 rawValue: resolveHttpRequestBaseUrl(primaryTarget),
278 source: primaryTarget.source,
279 urlKind: "http-base-url",
280 });
281 url.pathname = pathname;
282 if (searchParams) {
283 url.search = new URLSearchParams(searchParams).toString();
284 }
285 return url.toString();
287​
288export function readPrimaryEnvironmentTarget(): PrimaryEnvironmentTarget {
289 return (
290 resolveDesktopPrimaryTarget() ??
291 resolveConfiguredPrimaryTarget() ??
292 resolveWindowOriginPrimaryTarget()
293 );