TypeScript
fix(shared): preview addresses containing another URL open instead of searching (#17943)
Maxwell Young25aa9fc4e449
diff --git a/packages/shared/src/preview.test.ts b/packages/shared/src/preview.test.tsindex b08c9b12423..9902e6994d4 100644--- a/packages/shared/src/preview.test.ts+++ b/packages/shared/src/preview.test.ts@@ -64,6 +64,14 @@ describe("previewPdfAssetUrl", () => {});describe("resolveAddressBarInput", () => {+ it.each([+ ["localhost:3000/?next=https://example.com", "http://localhost:3000/?next=https://example.com"],+ ["127.0.0.1:3000/#https://example.com", "http://127.0.0.1:3000/#https://example.com"],+ ["example.com/https://example.org", "https://example.com/https://example.org"],+ ])("opens the outer address when it contains another URL: %s", (input, expected) => {+ expect(resolveAddressBarInput(input)).toBe(expected);+ });+it("opens what users type as addresses", () => {expect(resolveAddressBarInput("localhost:5173")).toBe("http://localhost:5173/");expect(resolveAddressBarInput("127.0.0.1:3000/path")).toBe("http://127.0.0.1:3000/path");diff --git a/packages/shared/src/preview.ts b/packages/shared/src/preview.tsindex 5da5f66b44c..43e8af5adaa 100644--- a/packages/shared/src/preview.ts+++ b/packages/shared/src/preview.ts@@ -78,6 +78,7 @@ function previewUrlProtocol(rawUrl: string): string | undefined {const SEARCH_URL = "https://duckduckgo.com/?q=";const ADDRESS_HOST_PATTERN = /^(?:localhost|\d{1,3}(?:\.\d{1,3}){3}|\[[\da-f:.]+\])$/i;const BARE_HOST_PORT_PATTERN = /^[^/?#:@]+:\d+(?:[/?#]|$)/;+const URL_SCHEME_WITH_AUTHORITY_PATTERN = /^[a-z][a-z\d+.-]*:\/\//i;const KNOWN_NON_WEB_SCHEMES: ReadonlySet<string> = new Set(["about:","blob:",@@ -97,7 +98,7 @@ const KNOWN_NON_WEB_SCHEMES: ReadonlySet<string> = new Set([export function resolveAddressBarInput(rawInput: string): string {const trimmed = rawInput.trim();- if (/^[a-z][a-z\d+.-]*:\/\//i.test(trimmed) || trimmed.length === 0)+ if (URL_SCHEME_WITH_AUTHORITY_PATTERN.test(trimmed) || trimmed.length === 0)return normalizePreviewUrl(trimmed);if (!/\s/.test(trimmed)) {// `mailto:x` or `data:...` is an explicit scheme; `example.com:8080` or@@ -135,7 +136,7 @@ export function normalizePreviewUrl(rawUrl: string): string {throw new PreviewUrlNormalizationError({ inputLength: rawUrl.length, reason: "empty" });}const useHttp = LOOPBACK_PREFIX_PATTERN.test(trimmed);- const candidate = trimmed.includes("://")+ const candidate = URL_SCHEME_WITH_AUTHORITY_PATTERN.test(trimmed)? trimmed: `${useHttp ? "http" : "https"}://${trimmed}`;let parsed: URL;