From c469dd4c22f28965fa1cf0231c8b1eeda2eacff8 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E6=9C=A8=E6=9D=89?= Date: Wed, 13 Nov 2019 02:45:48 +0800 Subject: [PATCH] fix url parse bug (#3316) --- cli/js/url.ts | 18 ++++++++++++------ cli/js/url_test.ts | 15 ++++++++++++++- 2 files changed, 26 insertions(+), 7 deletions(-) diff --git a/cli/js/url.ts b/cli/js/url.ts index 7b06fd64c888b6..e5cf3ed6234cec 100644 --- a/cli/js/url.ts +++ b/cli/js/url.ts @@ -17,7 +17,7 @@ interface URLParts { } const patterns = { - protocol: "(?:([^:/?#]+):)", + protocol: "(?:([a-z]+):)", authority: "(?://([^/?#]*))", path: "([^?#]*)", query: "(\\?[^#]*)", @@ -228,10 +228,13 @@ export class URL { this.username || this.password ? `${this.username}${this.password ? ":" + this.password : ""}@` : ""; - - return `${this.protocol}//${authentication}${this.host}${this.pathname}${ - this.search - }${this.hash}`; + let slash = ""; + if (this.host || this.protocol === "file:") { + slash = "//"; + } + return `${this.protocol}${slash}${authentication}${this.host}${ + this.pathname + }${this.search}${this.hash}`; } set href(value: string) { @@ -244,7 +247,10 @@ export class URL { } get origin(): string { - return `${this.protocol}//${this.host}`; + if (this.host) { + return `${this.protocol}//${this.host}`; + } + return "null"; } get password(): string { diff --git a/cli/js/url_test.ts b/cli/js/url_test.ts index 23f9f5f4b03139..1f8e3199974806 100644 --- a/cli/js/url_test.ts +++ b/cli/js/url_test.ts @@ -1,5 +1,5 @@ // Copyright 2018-2019 the Deno authors. All rights reserved. MIT license. -import { test, assert, assertEquals } from "./test_util.ts"; +import { test, assert, assertEquals, assertThrows } from "./test_util.ts"; test(function urlParsing(): void { const url = new URL( @@ -187,3 +187,16 @@ test(function customInspectFunction(): void { 'URL { href: "http://example.com/?", origin: "http://example.com", protocol: "http:", username: "", password: "", host: "example.com", hostname: "example.com", port: "", pathname: "/", hash: "", search: "?" }' ); }); + +test(function protocolNotHttpOrFile() { + const url = new URL("about:blank"); + assertEquals(url.href, "about:blank"); + assertEquals(url.protocol, "about:"); + assertEquals(url.origin, "null"); +}); + +test(function createBadUrl(): void { + assertThrows(() => { + new URL("0.0.0.0:8080"); + }); +});