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

browserTargetResolver.ts

118 lines4.7 KB

1import type {
2 BrowserNavigationTarget,
3 EnvironmentId,
4 PreviewUrlResolution,
5} from "@t3tools/contracts";
6import { isLoopbackHost, normalizePreviewUrl } from "@t3tools/shared/preview";
7import { isLocalLoopbackHost, isPrivateNetworkHost } from "@t3tools/shared/hostClassification";
8​
9import type { ConnectionTarget } from "@t3tools/client-runtime/connection";
10​
11import { isDesktopLocalConnectionTarget } from "~/connection/desktopLocal";
12import { isElectron } from "~/env";
13import { readPreparedConnection } from "~/state/session";
14​
15export { normalizeHostname, isLocalLoopbackHost } from "@t3tools/shared/hostClassification";
16​
17const readEnvironmentUrl = (environmentId: EnvironmentId): URL => {
18 const connection = readPreparedConnection(environmentId);
19 if (!connection) throw new Error(`Environment ${environmentId} is not connected.`);
20 return new URL(connection.httpBaseUrl);
21};
22​
23const resolveEnvironmentPortTarget = (
24 environmentId: EnvironmentId,
25 target: Extract<BrowserNavigationTarget, { readonly kind: "environment-port" }>,
26 environmentUrl: URL,
27 requestedUrl?: string,
28 sourceUrl?: URL,
29): PreviewUrlResolution => {
30 if (!isPrivateNetworkHost(environmentUrl.hostname)) {
31 throw new Error(
32 "This environment port needs the planned authenticated preview gateway; its server address is not directly private-network reachable.",
33 );
34 }
35 const protocol = target.protocol ?? "http";
36 const path = target.path?.startsWith("/") ? target.path : `/${target.path ?? ""}`;
37 const normalizedEnvironmentHost = environmentUrl.hostname.replace(/^\[|\]$/g, "");
38 // localhost lets Chromium reach loopback servers bound to either IPv4 or IPv6.
39 const resolvedHost = isLocalLoopbackHost(normalizedEnvironmentHost)
40 ? "localhost"
41 : normalizedEnvironmentHost.includes(":")
42 ? `[${normalizedEnvironmentHost}]`
43 : normalizedEnvironmentHost;
44 const resolved = sourceUrl
45 ? new URL(sourceUrl)
46 : new URL(path, `${protocol}://${resolvedHost}:${target.port}`);
47 if (sourceUrl) {
48 resolved.hostname = resolvedHost;
49 resolved.port = String(target.port);
50 }
51 return {
52 requestedUrl: requestedUrl ?? `${protocol}://localhost:${target.port}${path}`,
53 resolvedUrl: resolved.toString(),
54 resolutionKind: isLocalLoopbackHost(normalizedEnvironmentHost)
55 ? "direct"
56 : "direct-private-network",
57 environmentId,
58 };
59};
60​
61// Loopback servers on the desktop's own primary and WSL backends answer on this machine's localhost.
62const reachesEnvironmentLoopback = (target: ConnectionTarget): boolean =>
63 isElectron &&
64 (target._tag === "PrimaryConnectionTarget" || isDesktopLocalConnectionTarget(target));
65​
66/** Desktop carries every other environment's loopback traffic through the preview tunnel. */
67export const tunnelsEnvironmentLoopback = (target: ConnectionTarget | undefined): boolean =>
68 isElectron && !(target !== undefined && reachesEnvironmentLoopback(target));
69​
70const resolveLoopbackUrlOrThrow = (
71 environmentId: EnvironmentId,
72 rawUrl: string,
73 tunnelled: boolean,
74): string => {
75 const normalizedUrl = normalizePreviewUrl(rawUrl);
76 const parsed = new URL(normalizedUrl);
77 if (tunnelled || !isLoopbackHost(parsed.hostname)) return normalizedUrl;
78 const target = readPreparedConnection(environmentId)?.target;
79 if (target && reachesEnvironmentLoopback(target)) return normalizedUrl;
80 return resolveEnvironmentPortTarget(
81 environmentId,
82 {
83 kind: "environment-port",
84 port: Number(parsed.port || (parsed.protocol === "https:" ? 443 : 80)),
85 protocol: parsed.protocol === "https:" ? "https" : "http",
86 path: `${parsed.pathname}${parsed.search}${parsed.hash}`,
87 },
88 readEnvironmentUrl(environmentId),
89 rawUrl,
90 parsed,
91 ).resolvedUrl;
92};
93​
94const resolveLoopbackUrl = (
95 environmentId: EnvironmentId,
96 rawUrl: string,
97 tunnelled: boolean,
98): string => {
99 try {
100 return resolveLoopbackUrlOrThrow(environmentId, rawUrl, tunnelled);
101 } catch {
102 return rawUrl;
103 }
104};
105​
106/** The URL an in-app tab loads. A desktop webview keeps localhost; its partition reaches the environment. */
107export const resolveDiscoveredServerUrl = (environmentId: EnvironmentId, rawUrl: string): string =>
108 resolveLoopbackUrl(environmentId, rawUrl, isElectron);
109​
110/** The URL for the system browser, which has no tunnel and needs an address it can reach itself. */
111export const resolveExternalServerUrl = (environmentId: EnvironmentId, rawUrl: string): string =>
112 resolveLoopbackUrl(environmentId, rawUrl, false);
113​
114/** Like `resolveExternalServerUrl`, but throws when this machine has no route to the environment's loopback. */
115export const resolveReachableExternalServerUrl = (
116 environmentId: EnvironmentId,
117 rawUrl: string,
118): string => resolveLoopbackUrlOrThrow(environmentId, rawUrl, false);