(url: string, urlBase?: string | URL | undefined)
| 61 | * @returns The parsed URL object or undefined if the URL is invalid |
| 62 | */ |
| 63 | export function parseStringToURLObject(url: string, urlBase?: string | URL | undefined): URLObject | undefined { |
| 64 | const isRelative = url.indexOf('://') <= 0 && url.indexOf('//') !== 0; |
| 65 | const base = urlBase ?? (isRelative ? DEFAULT_BASE_URL : undefined); |
| 66 | try { |
| 67 | // Use `canParse` to short-circuit the URL constructor if it's not a valid URL |
| 68 | // This is faster than trying to construct the URL and catching the error |
| 69 | // Node 20+, Chrome 120+, Firefox 115+, Safari 17+ |
| 70 | if ('canParse' in URL && !(URL as unknown as URLwithCanParse).canParse(url, base)) { |
| 71 | return undefined; |
| 72 | } |
| 73 | |
| 74 | const fullUrlObject = new URL(url, base); |
| 75 | if (isRelative) { |
| 76 | // Because we used a fake base URL, we need to return a relative URL object. |
| 77 | // We cannot return anything about the origin, host, etc. because it will refer to the fake base URL. |
| 78 | return { |
| 79 | isRelative, |
| 80 | pathname: fullUrlObject.pathname, |
| 81 | search: fullUrlObject.search, |
| 82 | hash: fullUrlObject.hash, |
| 83 | }; |
| 84 | } |
| 85 | return fullUrlObject; |
| 86 | } catch { |
| 87 | // empty body |
| 88 | } |
| 89 | |
| 90 | return undefined; |
| 91 | } |
| 92 | |
| 93 | /** |
| 94 | * Takes a URL object and returns a sanitized string which is safe to use as span name |
no outgoing calls
no test coverage detected