| 
									
										
										
										
											2021-05-13 12:18:51 -05:00
										 |  |  | // Copyright 2021 Signal Messenger, LLC
 | 
					
						
							|  |  |  | // SPDX-License-Identifier: AGPL-3.0-only
 | 
					
						
							|  |  |  | 
 | 
					
						
							|  |  |  | export function maybeParseUrl(value: string): undefined | URL { | 
					
						
							|  |  |  |   if (typeof value === 'string') { | 
					
						
							|  |  |  |     try { | 
					
						
							|  |  |  |       return new URL(value); | 
					
						
							| 
									
										
										
										
											2023-11-02 12:42:31 -07:00
										 |  |  |     } catch { | 
					
						
							| 
									
										
										
										
											2021-05-13 12:18:51 -05:00
										 |  |  |       /* Errors are ignored. */ | 
					
						
							|  |  |  |     } | 
					
						
							|  |  |  |   } | 
					
						
							|  |  |  | 
 | 
					
						
							|  |  |  |   return undefined; | 
					
						
							|  |  |  | } | 
					
						
							|  |  |  | 
 | 
					
						
							|  |  |  | export function setUrlSearchParams( | 
					
						
							|  |  |  |   url: Readonly<URL>, | 
					
						
							|  |  |  |   searchParams: Readonly<Record<string, unknown>> | 
					
						
							|  |  |  | ): URL { | 
					
						
							|  |  |  |   const result = cloneUrl(url); | 
					
						
							| 
									
										
										
										
											2023-04-07 09:42:12 -07:00
										 |  |  |   result.search = ''; | 
					
						
							|  |  |  |   for (const [key, value] of Object.entries(searchParams)) { | 
					
						
							|  |  |  |     if (value == null) { | 
					
						
							|  |  |  |       continue; | 
					
						
							|  |  |  |     } | 
					
						
							|  |  |  |     result.searchParams.append(key, String(value)); | 
					
						
							|  |  |  |   } | 
					
						
							| 
									
										
										
										
											2021-05-13 12:18:51 -05:00
										 |  |  |   return result; | 
					
						
							|  |  |  | } | 
					
						
							|  |  |  | 
 | 
					
						
							|  |  |  | function cloneUrl(url: Readonly<URL>): URL { | 
					
						
							|  |  |  |   return new URL(url.href); | 
					
						
							|  |  |  | } | 
					
						
							|  |  |  | 
 | 
					
						
							| 
									
										
										
										
											2023-01-19 13:53:04 -06:00
										 |  |  | export function urlPathFromComponents( | 
					
						
							|  |  |  |   components: ReadonlyArray<string> | 
					
						
							|  |  |  | ): string { | 
					
						
							|  |  |  |   return `/${components.filter(Boolean).map(encodeURIComponent).join('/')}`; | 
					
						
							|  |  |  | } |