Revert "Add urlPath util for building escaped URL paths"

This commit is contained in:
Jamie Kyle 2024-09-24 12:43:00 -07:00 committed by GitHub
parent cd50c715a9
commit 03ed42188e
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
3 changed files with 75 additions and 146 deletions

View file

@ -1,8 +1,6 @@
// Copyright 2021 Signal Messenger, LLC
// SPDX-License-Identifier: AGPL-3.0-only
import { strictAssert } from './assert';
export function maybeParseUrl(value: string): undefined | URL {
if (typeof value === 'string') {
try {
@ -34,64 +32,8 @@ function cloneUrl(url: Readonly<URL>): URL {
return new URL(url.href);
}
class UrlPath {
#urlPath: string;
constructor(escapedUrlPath: string) {
this.#urlPath = escapedUrlPath;
}
toString(): string {
return this.#urlPath;
}
}
export type { UrlPath };
export type UrlPathInput = boolean | number | string | UrlPath;
export function isUrlPath(value: unknown): value is UrlPath {
return value instanceof UrlPath;
}
function escapeValueForUrlPath(value: UrlPathInput): string {
if (typeof value === 'boolean' || typeof value === 'number') {
return String(value);
}
if (typeof value === 'string') {
return encodeURIComponent(value);
}
if (isUrlPath(value)) {
return value.toString();
}
throw new TypeError('Unexpected url path component');
}
export function urlPath(
strings: TemplateStringsArray,
...components: ReadonlyArray<UrlPathInput>
): UrlPath {
let result = '';
for (let index = 0; index < strings.length; index += 1) {
result += strings[index];
if (index < components.length) {
result += escapeValueForUrlPath(components[index]);
}
}
return new UrlPath(result);
}
export function urlPathJoin(
values: ReadonlyArray<UrlPathInput>,
separator: string
): UrlPath {
strictAssert(isUrlPath(separator), 'Separator must be an EscapedUrlPath');
let result = '';
for (let index = 0; index < values.length; index += 1) {
result += escapeValueForUrlPath(values[index]);
if (index < values.length - 1) {
result += separator;
}
}
return new UrlPath(result);
export function urlPathFromComponents(
components: ReadonlyArray<string>
): string {
return `/${components.filter(Boolean).map(encodeURIComponent).join('/')}`;
}