-
Notifications
You must be signed in to change notification settings - Fork 2.1k
Expand file tree
/
Copy pathhostedPairing.ts
More file actions
89 lines (71 loc) · 2.41 KB
/
hostedPairing.ts
File metadata and controls
89 lines (71 loc) · 2.41 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
import { getPairingTokenFromUrl, setPairingTokenOnUrl } from "./pairingUrl";
const DEFAULT_HOSTED_APP_URL = "https://app.t3.codes";
export interface HostedPairingRequest {
readonly host: string;
readonly token: string;
readonly label: string;
}
export type HostedAppChannel = "latest" | "nightly";
function configuredHostedAppUrl(): string {
return import.meta.env.VITE_HOSTED_APP_URL?.trim() || DEFAULT_HOSTED_APP_URL;
}
function configuredBackendUrl(): string {
return import.meta.env.VITE_HTTP_URL?.trim() || import.meta.env.VITE_WS_URL?.trim() || "";
}
function configuredHostedAppChannel(): HostedAppChannel | null {
const channel = import.meta.env.VITE_HOSTED_APP_CHANNEL?.trim().toLowerCase();
return channel === "latest" || channel === "nightly" ? channel : null;
}
function originFromUrl(value: string): string | null {
try {
return new URL(value).origin;
} catch {
return null;
}
}
export function isHostedStaticApp(url: URL = new URL(window.location.href)): boolean {
if (configuredBackendUrl()) {
return false;
}
if (configuredHostedAppChannel()) {
return true;
}
const hostedOrigin = originFromUrl(configuredHostedAppUrl());
return hostedOrigin !== null && url.origin === hostedOrigin;
}
export function readHostedPairingRequest(url: URL = new URL(window.location.href)) {
const host = url.searchParams.get("host")?.trim() ?? "";
const token = getPairingTokenFromUrl(url)?.trim() ?? "";
const label = url.searchParams.get("label")?.trim() ?? "";
if (!host || !token) {
return null;
}
return {
host,
token,
label,
} satisfies HostedPairingRequest;
}
export function hasHostedPairingRequest(url: URL = new URL(window.location.href)): boolean {
return readHostedPairingRequest(url) !== null;
}
export function buildHostedPairingUrl(input: {
readonly host: string;
readonly token: string;
readonly label?: string | null;
}): string {
const url = new URL("/pair", configuredHostedAppUrl());
url.searchParams.set("host", input.host);
const label = input.label?.trim();
if (label) {
url.searchParams.set("label", label);
}
return setPairingTokenOnUrl(url, input.token).toString();
}
export function buildHostedChannelSelectionUrl(input: {
readonly channel: HostedAppChannel;
}): string {
const url = new URL("/__t3code/channel", configuredHostedAppUrl());
url.searchParams.set("channel", input.channel);
return url.toString();
}