MCPcopy Create free account
hub / github.com/angular/angular / resolveUrl

Function resolveUrl

packages/platform-server/src/url.ts:56–126  ·  view source on GitHub ↗
(
  urlStr: string | undefined,
  origin?: string | URL,
  options: ResolveUrlOptions = {},
)

Source from the content-addressed store, hash-verified

54 options?: ResolveUrlOptions,
55): URL;
56export function resolveUrl(
57 urlStr: string | undefined,
58 origin?: string | URL,
59 options: ResolveUrlOptions = {},
60): URL | null {
61 const originUrl = typeof origin === 'string' ? new URL('/', origin) : origin;
62
63 if (!urlStr) {
64 return originUrl || null;
65 }
66
67 // Fast-path: if the URL is a valid, standard absolute URL, parse and return it immediately.
68 // URLs with no authority (e.g. `http:/path` or `http:path`) must be resolved against the origin when one is provided.
69 let resolved: URL | undefined;
70 if (!originUrl || !HTTP_OR_HTTPS_NO_AUTHORITY_REGEXP.test(urlStr)) {
71 try {
72 resolved = new URL(urlStr);
73 } catch {}
74 }
75 const {allowProtocolRelative = false, allowOriginChange = true} = options;
76
77 if (resolved) {
78 if (isDisallowedProtocolRelative(resolved, allowProtocolRelative)) {
79 throwProtocolRelativeUrlError(urlStr);
80 }
81
82 if (originUrl && !isSafeOriginChange(resolved, originUrl, urlStr, allowOriginChange)) {
83 throwSuspiciousUrlError(urlStr);
84 }
85
86 return resolved;
87 }
88
89 // We identify and throw on malformed absolute URLs (like double port).
90 // Per the WHATWG URL standard, parsing an input starting with a scheme (like 'http:') against
91 // a standard base (like 'http://fake') ignores the base argument and parses strictly as an
92 // absolute URL. Since it is malformed, the native URL constructor will throw a validation
93 // error. Standard relative/protocol-relative paths parse successfully, allowing the flow to continue.
94 if (!URL.canParse(urlStr, 'http://fake')) {
95 throw new RuntimeError(
96 RuntimeErrorCode.INVALID_URL,
97 typeof ngDevMode === 'undefined' || ngDevMode ? `Invalid URL: ${urlStr}` : urlStr,
98 );
99 }
100
101 if (!originUrl) {
102 return null;
103 }
104
105 // Check if we have a legitimate protocol-relative URL (starts with '//' and not a duplicate/backslash bypass)
106 // and we are configured to allow and preserve standard cross-origin protocol-relative requests.
107 if (urlStr.startsWith('//')) {
108 if (!allowProtocolRelative) {
109 throwProtocolRelativeUrlError(urlStr);
110 }
111
112 return new URL(urlStr, origin);
113 }

Callers 6

url_spec.tsFile · 0.90
constructorMethod · 0.90
replaceStateMethod · 0.90
validateAllowedHostsFunction · 0.90
_documentFunction · 0.90

Calls 5

isSafeOriginChangeFunction · 0.85
throwSuspiciousUrlErrorFunction · 0.85
testMethod · 0.45

Tested by

no test coverage detected