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

portDiscoveryState.ts

85 lines2.7 KB

1import {
2 CONFIGURED_LOCAL_SERVER_URLS_MAX_ITEMS,
3 PREVIEW_URL_MAX_LENGTH,
4 type DiscoveredLocalServer,
5 type EnvironmentId,
6 type ThreadId,
7} from "@t3tools/contracts";
8import { isLoopbackHost } from "@t3tools/shared/preview";
9import { useMemo } from "react";
10​
11import { previewEnvironment } from "./state/preview";
12import { useEnvironmentQuery } from "./state/query";
13​
14const EMPTY_PORTS: ReadonlyArray<DiscoveredLocalServer> = Object.freeze([]);
15​
16interface DiscoveredPortsState {
17 readonly servers: ReadonlyArray<DiscoveredLocalServer>;
18 readonly configuredUrlProbing: boolean;
20​
21export function boundConfiguredLocalServerUrls(
22 urls: ReadonlyArray<string> | undefined,
23): ReadonlyArray<string> {
24 const bounded: string[] = [];
25 const seen = new Set<string>();
26 for (const raw of urls ?? []) {
27 if (raw.length === 0 || raw.length > PREVIEW_URL_MAX_LENGTH || raw.trim().length !== raw.length)
28 continue;
29 try {
30 const url = new URL(raw);
31 if (url.protocol !== "http:" && url.protocol !== "https:") continue;
32 if (!isLoopbackHost(url.hostname) || url.href.length > PREVIEW_URL_MAX_LENGTH) continue;
33 const resourceUrl = new URL(url.href);
34 resourceUrl.hash = "";
35 if (seen.has(resourceUrl.href)) continue;
36 seen.add(resourceUrl.href);
37 bounded.push(url.href);
38 if (bounded.length >= CONFIGURED_LOCAL_SERVER_URLS_MAX_ITEMS) break;
39 } catch {}
40 }
41 return bounded;
43​
44function useDiscoveredPorts(
45 environmentId: EnvironmentId | null,
46 configuredUrls?: ReadonlyArray<string>,
47): ReadonlyArray<DiscoveredLocalServer> {
48 return useDiscoveredPortsState(environmentId, configuredUrls).servers;
50​
51export function useDiscoveredPortsState(
52 environmentId: EnvironmentId | null,
53 configuredUrls?: ReadonlyArray<string>,
54): DiscoveredPortsState {
55 const boundedConfiguredUrls = boundConfiguredLocalServerUrls(configuredUrls);
56 const query = useEnvironmentQuery(
57 environmentId === null
58 ? null
59 : previewEnvironment.discoveredServers({
60 environmentId,
61 input: boundedConfiguredUrls.length ? { configuredUrls: boundedConfiguredUrls } : {},
62 }),
63 );
64 return useMemo(
65 () => ({
66 servers: query.data?.servers ?? EMPTY_PORTS,
67 configuredUrlProbing: query.data?.configuredUrlProbing === true,
68 }),
69 [query.data?.configuredUrlProbing, query.data?.servers],
70 );
72​
73export function useThreadDiscoveredPorts(input: {
74 readonly environmentId: EnvironmentId | null;
75 readonly threadId: ThreadId | null;
76}): ReadonlyArray<DiscoveredLocalServer> {
77 const ports = useDiscoveredPorts(input.environmentId);
78 return useMemo(
79 () =>
80 input.threadId
81 ? ports.filter((port) => port.terminal?.threadId === input.threadId)
82 : EMPTY_PORTS,
83 [input.threadId, ports],
84 );