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

target.ts

290 lines8.3 KB

1import 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 return window.desktopBridge?.getLocalEnvironmentBootstrap() ?? null;
81​
82function parseTargetUrl(input: {
83 readonly rawValue: string;
84 readonly baseUrl?: string;
85 readonly source: PrimaryEnvironmentTargetSource;
86 readonly urlKind: PrimaryEnvironmentUrlKind;
87}): URL {
88 try {
89 return input.baseUrl === undefined
90 ? new URL(input.rawValue)
91 : new URL(input.rawValue, input.baseUrl);
92 } catch (cause) {
93 throw new PrimaryEnvironmentUrlInvalidError({
94 source: input.source,
95 urlKind: input.urlKind,
96 cause,
97 });
98 }
100​
101function normalizeBaseUrl(
102 rawValue: string,
103 source: PrimaryEnvironmentTargetSource,
104 urlKind: PrimaryEnvironmentUrlKind,
105): string {
106 return parseTargetUrl({
107 rawValue,
108 baseUrl: window.location.origin,
109 source,
110 urlKind,
111 }).toString();
113​
114function swapBaseUrlProtocol(
115 rawValue: string,
116 nextProtocol: "http:" | "https:" | "ws:" | "wss:",
117 urlKind: PrimaryEnvironmentUrlKind,
118): string {
119 const url = parseTargetUrl({
120 rawValue,
121 baseUrl: window.location.origin,
122 source: "configured",
123 urlKind,
124 });
125 url.protocol = nextProtocol;
126 return url.toString();
128​
129function normalizeHostname(hostname: string): string {
130 return hostname
131 .trim()
132 .toLowerCase()
133 .replace(/^\[(.*)\]$/, "$1");
135​
136export function isLoopbackHostname(hostname: string): boolean {
137 return LOOPBACK_HOSTNAMES.has(normalizeHostname(hostname));
139​
140function resolveHttpRequestBaseUrl(primaryTarget: PrimaryEnvironmentTarget): string {
141 const httpBaseUrl = primaryTarget.target.httpBaseUrl;
142 const configuredDevServerUrl = import.meta.env.VITE_DEV_SERVER_URL?.trim();
143 if (!configuredDevServerUrl) {
144 return httpBaseUrl;
145 }
146​
147 const currentUrl = parseTargetUrl({
148 rawValue: window.location.href,
149 source: "window-origin",
150 urlKind: "window-location-url",
151 });
152 const targetUrl = parseTargetUrl({
153 rawValue: httpBaseUrl,
154 source: primaryTarget.source,
155 urlKind: "http-base-url",
156 });
157 const devServerUrl = parseTargetUrl({
158 rawValue: configuredDevServerUrl,
159 baseUrl: currentUrl.origin,
160 source: "configured",
161 urlKind: "development-server-url",
162 });
163​
164 const isCurrentOriginDevServer =
165 (currentUrl.protocol === "http:" || currentUrl.protocol === "https:") &&
166 currentUrl.origin === devServerUrl.origin;
167​
168 if (
169 !isCurrentOriginDevServer ||
170 currentUrl.origin === targetUrl.origin ||
171 !isLoopbackHostname(currentUrl.hostname) ||
172 !isLoopbackHostname(targetUrl.hostname)
173 ) {
174 return httpBaseUrl;
175 }
176​
177 return currentUrl.origin;
179​
180function resolveConfiguredPrimaryTarget(): PrimaryEnvironmentTarget | null {
181 const configuredHttpBaseUrl = import.meta.env.VITE_HTTP_URL?.trim() || undefined;
182 const configuredWsBaseUrl = import.meta.env.VITE_WS_URL?.trim() || undefined;
183​
184 if (!configuredHttpBaseUrl && !configuredWsBaseUrl) {
185 return null;
186 }
187​
188 const resolvedHttpBaseUrl =
189 configuredHttpBaseUrl ??
190 (configuredWsBaseUrl?.startsWith("wss:")
191 ? swapBaseUrlProtocol(configuredWsBaseUrl, "https:", "websocket-base-url")
192 : swapBaseUrlProtocol(configuredWsBaseUrl!, "http:", "websocket-base-url"));
193 const resolvedWsBaseUrl =
194 configuredWsBaseUrl ??
195 (configuredHttpBaseUrl?.startsWith("https:")
196 ? swapBaseUrlProtocol(configuredHttpBaseUrl, "wss:", "http-base-url")
197 : swapBaseUrlProtocol(configuredHttpBaseUrl!, "ws:", "http-base-url"));
198​
199 return {
200 source: "configured",
201 target: {
202 httpBaseUrl: normalizeBaseUrl(resolvedHttpBaseUrl, "configured", "http-base-url"),
203 wsBaseUrl: normalizeBaseUrl(resolvedWsBaseUrl, "configured", "websocket-base-url"),
204 },
205 };
207​
208function resolveWindowOriginPrimaryTarget(): PrimaryEnvironmentTarget {
209 const url = parseTargetUrl({
210 rawValue: window.location.origin,
211 source: "window-origin",
212 urlKind: "http-base-url",
213 });
214 const httpBaseUrl = url.toString();
215 if (url.protocol === "http:") {
216 url.protocol = "ws:";
217 } else if (url.protocol === "https:") {
218 url.protocol = "wss:";
219 } else {
220 throw new PrimaryEnvironmentProtocolUnsupportedError({
221 source: "window-origin",
222 protocol: url.protocol,
223 });
224 }
225 return {
226 source: "window-origin",
227 target: {
228 httpBaseUrl,
229 wsBaseUrl: url.toString(),
230 },
231 };
233​
234function resolveDesktopPrimaryTarget(): PrimaryEnvironmentTarget | null {
235 const desktopBootstrap = getDesktopLocalEnvironmentBootstrap();
236 if (!desktopBootstrap) {
237 return null;
238 }
239 if (!desktopBootstrap.httpBaseUrl && !desktopBootstrap.wsBaseUrl) {
240 return null;
241 }
242 if (!desktopBootstrap.httpBaseUrl || !desktopBootstrap.wsBaseUrl) {
243 throw new DesktopEnvironmentBootstrapIncompleteError({
244 hasHttpBaseUrl: Boolean(desktopBootstrap.httpBaseUrl),
245 hasWsBaseUrl: Boolean(desktopBootstrap.wsBaseUrl),
246 });
247 }
248​
249 return {
250 source: "desktop-managed",
251 target: {
252 httpBaseUrl: normalizeBaseUrl(
253 desktopBootstrap.httpBaseUrl,
254 "desktop-managed",
255 "http-base-url",
256 ),
257 wsBaseUrl: normalizeBaseUrl(
258 desktopBootstrap.wsBaseUrl,
259 "desktop-managed",
260 "websocket-base-url",
261 ),
262 },
263 };
265​
266export function resolvePrimaryEnvironmentHttpUrl(
267 pathname: string,
268 searchParams?: Record<string, string>,
269): string {
270 const primaryTarget = readPrimaryEnvironmentTarget();
271​
272 const url = parseTargetUrl({
273 rawValue: resolveHttpRequestBaseUrl(primaryTarget),
274 source: primaryTarget.source,
275 urlKind: "http-base-url",
276 });
277 url.pathname = pathname;
278 if (searchParams) {
279 url.search = new URLSearchParams(searchParams).toString();
280 }
281 return url.toString();
283​
284export function readPrimaryEnvironmentTarget(): PrimaryEnvironmentTarget {
285 return (
286 resolveDesktopPrimaryTarget() ??
287 resolveConfiguredPrimaryTarget() ??
288 resolveWindowOriginPrimaryTarget()
289 );