Open History to see the last commit
1/**
2 * Pure URL helpers shared between the preview server, desktop main process,
3 * and web renderer. Centralising these guarantees the four call sites agree
4 * on what counts as "loopback" and how to normalise a free-form URL string.
5 */
6
7import * as Schema from "effect/Schema";
8
9const TAB_ID_PREFIX = "tab_";
10let nextPreviewTabSequence = 0;
11
12/**
13 * Generate a fresh preview tab id. Lives in shared (not contracts) because
14 * the contracts package is schema-only — runtime helpers belong here.
15 */
16export function newPreviewTabId(): string {
17 nextPreviewTabSequence += 1;
18 return `${TAB_ID_PREFIX}${nextPreviewTabSequence.toString(36)}`;
19}
20
21const LOOPBACK_HOSTS: ReadonlySet<string> = new Set(["localhost", "127.0.0.1", "0.0.0.0", "::1"]);
22
23/** Internal — used by `lsof` parsing where the host string is wire-formatted. */
24export const LSOF_LOCAL_HOST_TOKENS: ReadonlySet<string> = new Set([
25 ...LOOPBACK_HOSTS,
26 "*",
27 "[::]",
28 "[::1]",
29]);
30
31const LOOPBACK_PREFIX_PATTERN = /^(?:localhost|127\.0\.0\.1|0\.0\.0\.0|\[::1?\])(?::|\/|$)/i;
32
33export function isLoopbackHost(host: string): boolean {
34 if (LOOPBACK_HOSTS.has(host)) return true;
35 if (host === "[::1]") return true;
36 return false;
37}
38
39export class PreviewUrlNormalizationError extends Schema.TaggedError<PreviewUrlNormalizationError>()(
40 "PreviewUrlNormalizationError",
41 {
42 inputLength: Schema.Number,
43 reason: Schema.Literals(["empty", "parse", "unsupported-protocol"]),
44 protocol: Schema.optional(Schema.String),
45 cause: Schema.optional(Schema.Defect()),
46 },
47) {
48 override get message(): string {
49 const protocol = this.protocol === undefined ? "" : `: ${this.protocol}`;
50 return `Invalid preview URL (${this.reason}${protocol}; input length ${this.inputLength}).`;
51 }
52}
53
54export const isPreviewUrlNormalizationError = Schema.is(PreviewUrlNormalizationError);
55
56function previewUrlProtocol(rawUrl: string): string | undefined {
57 return /^([A-Za-z][A-Za-z\d+.-]*):/.exec(rawUrl)?.[1]?.toLowerCase().concat(":");
58}
59
60/**
61 * Normalise a free-form URL string into a fully-qualified `http(s)://` URL.
62 *
63 * - Bare loopback hosts (`localhost`, `localhost:5173`) become `http://...`.
64 * - Bare public hosts (`example.com`) become `https://...`.
65 * - Already-qualified URLs are validated and returned as `URL.href`.
66 *
67 * Throws `PreviewUrlNormalizationError` for empty, unparseable, or
68 * unsupported-protocol inputs.
69 */
70export function normalizePreviewUrl(rawUrl: string): string {
71 const trimmed = rawUrl.trim();
72 if (trimmed.length === 0) {
73 throw new PreviewUrlNormalizationError({ inputLength: rawUrl.length, reason: "empty" });
74 }
75 const useHttp = LOOPBACK_PREFIX_PATTERN.test(trimmed);
76 const candidate = trimmed.includes("://")
77 ? trimmed
78 : `${useHttp ? "http" : "https"}://${trimmed}`;
79 let parsed: URL;
80 try {
81 parsed = new URL(candidate);
82 } catch (cause) {
83 throw new PreviewUrlNormalizationError({
84 inputLength: rawUrl.length,
85 reason: "parse",
86 protocol: previewUrlProtocol(candidate),
87 cause,
88 });
89 }
90 if (parsed.protocol !== "http:" && parsed.protocol !== "https:") {
91 throw new PreviewUrlNormalizationError({
92 inputLength: rawUrl.length,
93 reason: "unsupported-protocol",
94 protocol: parsed.protocol,
95 });
96 }
97 return parsed.href;
98}