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

target.ts

97 lines2.6 KB

1import { getPairingTokenFromUrl } from "../../pairingUrl";
2import { readHostedPairingRequest } from "../../hostedPairing";
3​
4export interface ResolvedRemotePairingTarget {
5 readonly credential: string;
6 readonly httpBaseUrl: string;
7 readonly wsBaseUrl: string;
8}
9​
10function normalizeRemoteBaseUrl(rawValue: string): URL {
11 const trimmed = rawValue.trim();
12 if (!trimmed) {
13 throw new Error("Enter a backend URL.");
14 }
15​
16 const normalizedInput =
17 /^[a-zA-Z][a-zA-Z\d+-]*:\/\//.test(trimmed) || trimmed.startsWith("//")
18 ? trimmed
19 : `https://${trimmed}`;
20 const url = new URL(normalizedInput, window.location.origin);
21 url.pathname = "/";
22 url.search = "";
23 url.hash = "";
24 return url;
26​
27function toHttpBaseUrl(url: URL): string {
28 const next = new URL(url.toString());
29 if (next.protocol === "ws:") {
30 next.protocol = "http:";
31 } else if (next.protocol === "wss:") {
32 next.protocol = "https:";
33 }
34 next.pathname = "/";
35 next.search = "";
36 next.hash = "";
37 return next.toString();
39​
40function toWsBaseUrl(url: URL): string {
41 const next = new URL(url.toString());
42 if (next.protocol === "http:") {
43 next.protocol = "ws:";
44 } else if (next.protocol === "https:") {
45 next.protocol = "wss:";
46 }
47 next.pathname = "/";
48 next.search = "";
49 next.hash = "";
50 return next.toString();
52​
53export function resolveRemotePairingTarget(input: {
54 readonly pairingUrl?: string;
55 readonly host?: string;
56 readonly pairingCode?: string;
57}): ResolvedRemotePairingTarget {
58 const pairingUrl = input.pairingUrl?.trim() ?? "";
59 if (pairingUrl.length > 0) {
60 const url = new URL(pairingUrl, window.location.origin);
61 const hostedPairingRequest = readHostedPairingRequest(url);
62 if (hostedPairingRequest) {
63 const hostedBackendUrl = normalizeRemoteBaseUrl(hostedPairingRequest.host);
64 return {
65 credential: hostedPairingRequest.token,
66 httpBaseUrl: toHttpBaseUrl(hostedBackendUrl),
67 wsBaseUrl: toWsBaseUrl(hostedBackendUrl),
68 };
69 }
70​
71 const credential = getPairingTokenFromUrl(url) ?? "";
72 if (!credential) {
73 throw new Error("Pairing URL is missing its token.");
74 }
75 return {
76 credential,
77 httpBaseUrl: toHttpBaseUrl(url),
78 wsBaseUrl: toWsBaseUrl(url),
79 };
80 }
81​
82 const host = input.host?.trim() ?? "";
83 const pairingCode = input.pairingCode?.trim() ?? "";
84 if (!host) {
85 throw new Error("Enter a backend URL.");
86 }
87 if (!pairingCode) {
88 throw new Error("Enter a pairing code.");
89 }
90​
91 const normalizedHost = normalizeRemoteBaseUrl(host);
92 return {
93 credential: pairingCode,
94 httpBaseUrl: toHttpBaseUrl(normalizedHost),
95 wsBaseUrl: toWsBaseUrl(normalizedHost),
96 };