react-router
Version:
Declarative routing for React
46 lines (45 loc) • 1.8 kB
JavaScript
/**
* react-router v8.3.1
*
* Copyright (c) Remix Software Inc.
*
* This source code is licensed under the MIT license found in the
* LICENSE.md file in the root directory of this source tree.
*
* @license MIT
*/
//#region lib/router/navigation.ts
const DEFAULT_NAVIGATION_URL = new URL("http://localhost");
function getNavigatorCurrentUrl(navigator) {
if (navigator.createURL) return navigator.createURL("/");
try {
return new URL(navigator.createHref("/"), DEFAULT_NAVIGATION_URL);
} catch {
return DEFAULT_NAVIGATION_URL;
}
}
function isSameOrigin(a, b) {
return a.origin === b.origin && (a.origin !== "null" || a.protocol === b.protocol && a.host === b.host);
}
function isExplicitUrl(destination, target) {
if (destination.startsWith("//")) return true;
let protocol = target.protocol.toLowerCase();
if (!destination.toLowerCase().startsWith(protocol)) return false;
return target.host === "" || destination.slice(protocol.length).startsWith("//");
}
function validateNavigationTarget(original, resolved, currentUrl, externalPolicy) {
let originalUrl = null;
try {
originalUrl = original == null ? null : new URL(original, currentUrl);
} catch {}
let resolvedUrl = new URL(resolved, currentUrl);
let originalIsExternal = originalUrl != null && !isSameOrigin(originalUrl, currentUrl);
let resolvedIsExternal = !isSameOrigin(resolvedUrl, currentUrl);
if (externalPolicy === "reject") {
if (originalIsExternal || resolvedIsExternal) throw new Error("External navigation is not allowed");
} else if (resolvedIsExternal) {
if (originalUrl == null || !isExplicitUrl(original, originalUrl) || !isSameOrigin(originalUrl, resolvedUrl)) throw new Error("External navigation is not allowed");
}
}
//#endregion
export { getNavigatorCurrentUrl, validateNavigationTarget };