Open History to see the last commit
1import * as Schema from "effect/Schema";
2
3const TAB_ID_PREFIX = "tab_";
4let nextPreviewTabSequence = 0;
5
6export function newPreviewTabId(): string {
7 nextPreviewTabSequence += 1;
8 return `${TAB_ID_PREFIX}${nextPreviewTabSequence.toString(36)}`;
9}
10
11const LOOPBACK_HOSTS: ReadonlySet<string> = new Set(["localhost", "127.0.0.1", "0.0.0.0", "::1"]);
12
13export const LSOF_LOCAL_HOST_TOKENS: ReadonlySet<string> = new Set([
14 ...LOOPBACK_HOSTS,
15 "*",
16 "[::]",
17 "[::1]",
18]);
19
20const LOOPBACK_PREFIX_PATTERN = /^(?:localhost|127\.0\.0\.1|0\.0\.0\.0|\[::1?\])(?::|\/|$)/i;
21
22export function isLoopbackHost(host: string): boolean {
23 if (LOOPBACK_HOSTS.has(host)) return true;
24 if (host === "[::1]") return true;
25 return false;
26}
27
28export class PreviewUrlNormalizationError extends Schema.TaggedError<PreviewUrlNormalizationError>()(
29 "PreviewUrlNormalizationError",
30 {
31 inputLength: Schema.Number,
32 reason: Schema.Literals(["empty", "parse", "unsupported-protocol"]),
33 protocol: Schema.optional(Schema.String),
34 cause: Schema.optional(Schema.Defect()),
35 },
36) {
37 override get message(): string {
38 const protocol = this.protocol === undefined ? "" : `: ${this.protocol}`;
39 return `Invalid preview URL (${this.reason}${protocol}; input length ${this.inputLength}).`;
40 }
41}
42
43export const isPreviewUrlNormalizationError = Schema.is(PreviewUrlNormalizationError);
44
45function previewUrlProtocol(rawUrl: string): string | undefined {
46 return /^([A-Za-z][A-Za-z\d+.-]*):/.exec(rawUrl)?.[1]?.toLowerCase().concat(":");
47}
48
49const SEARCH_URL = "https://duckduckgo.com/?q=";
50const ADDRESS_HOST_PATTERN = /^(?:localhost|\d{1,3}(?:\.\d{1,3}){3}|\[[\da-f:.]+\])$/i;
51const BARE_HOST_PORT_PATTERN = /^[^/?#:@]+:\d+(?:[/?#]|$)/;
52const KNOWN_NON_WEB_SCHEMES: ReadonlySet<string> = new Set([
53 "about:",
54 "blob:",
55 "chrome:",
56 "data:",
57 "file:",
58 "ftp:",
59 "javascript:",
60 "mailto:",
61 "sms:",
62 "ssh:",
63 "tel:",
64 "view-source:",
65 "ws:",
66 "wss:",
67]);
68
69export function resolveAddressBarInput(rawInput: string): string {
70 const trimmed = rawInput.trim();
71 if (/^[a-z][a-z\d+.-]*:\/\//i.test(trimmed) || trimmed.length === 0)
72 return normalizePreviewUrl(trimmed);
73 if (!/\s/.test(trimmed)) {
74 // `mailto:x` or `data:...` is an explicit scheme; `example.com:8080` or
75 // `devbox:8080` is a bare host and port. `normalizePreviewUrl` would read
76 // `mailto:alice@example.com` as credentials on a bare host, so reject here.
77 const protocol = previewUrlProtocol(trimmed);
78 if (
79 protocol !== undefined &&
80 (KNOWN_NON_WEB_SCHEMES.has(protocol) || !BARE_HOST_PORT_PATTERN.test(trimmed))
81 ) {
82 if (protocol !== "http:" && protocol !== "https:") {
83 throw new PreviewUrlNormalizationError({
84 inputLength: rawInput.length,
85 reason: "unsupported-protocol",
86 protocol,
87 });
88 }
89 return normalizePreviewUrl(trimmed);
90 }
91 const authority = trimmed.split(/[/?#]/, 1)[0] ?? "";
92 const host = authority.replace(/^[^@]*@/, "").replace(/:\d+$/, "");
93 const hasPort = host.length < authority.replace(/^[^@]*@/, "").length;
94 if (hasPort || ADDRESS_HOST_PATTERN.test(host) || /^[^.]+(?:\.[^.]+)+\.?$/.test(host)) {
95 try {
96 return normalizePreviewUrl(trimmed);
97 } catch {}
98 }
99 }
100 return `${SEARCH_URL}${encodeURIComponent(trimmed)}`;
101}
102
103export function normalizePreviewUrl(rawUrl: string): string {
104 const trimmed = rawUrl.trim();
105 if (trimmed.length === 0) {
106 throw new PreviewUrlNormalizationError({ inputLength: rawUrl.length, reason: "empty" });
107 }
108 const useHttp = LOOPBACK_PREFIX_PATTERN.test(trimmed);
109 const candidate = trimmed.includes("://")
110 ? trimmed
111 : `${useHttp ? "http" : "https"}://${trimmed}`;
112 let parsed: URL;
113 try {
114 parsed = new URL(candidate);
115 } catch (cause) {
116 throw new PreviewUrlNormalizationError({
117 inputLength: rawUrl.length,
118 reason: "parse",
119 protocol: previewUrlProtocol(candidate),
120 cause,
121 });
122 }
123 if (parsed.protocol !== "http:" && parsed.protocol !== "https:") {
124 throw new PreviewUrlNormalizationError({
125 inputLength: rawUrl.length,
126 reason: "unsupported-protocol",
127 protocol: parsed.protocol,
128 });
129 }
130 return parsed.href;
131}