shelving
Version:
Toolkit for using data in JavaScript.
45 lines (44 loc) • 1.5 kB
JavaScript
import { RequiredError } from "../error/RequiredError.js";
import { notNullish } from "./null.js";
export const URL = globalThis.URL;
/**
* Is an unknown value a URL object?
* - Must be a `URL` instance and its origin must start with `scheme://`
*/
export function isURL(value) {
return value instanceof globalThis.URL && _isValidURL(value);
}
function _isValidURL(url) {
return url.href.startsWith(`${url.protocol}//`);
}
/** Assert that an unknown value is a URL object. */
export function assertURL(value, caller = assertURL) {
if (!isURL(value))
throw new RequiredError("Invalid URL", { received: value, caller });
}
/** Convert a possible URL to a URL, or return `undefined` if conversion fails. */
export function getURL(possible, base = _BASE) {
if (notNullish(possible)) {
if (possible instanceof globalThis.URL) {
if (_isValidURL(possible))
return possible;
}
else {
try {
const url = new globalThis.URL(possible, base);
if (_isValidURL(url))
return url;
}
catch {
//
}
}
}
}
const _BASE = typeof document === "object" ? document.baseURI : undefined;
/** Convert a possible URL to a URL, or throw `RequiredError` if conversion fails. */
export function requireURL(possible, base, caller = requireURL) {
const url = getURL(possible, base);
assertURL(url, caller);
return url;
}