UNPKG

react-router

Version:

Declarative routing for React

61 lines (60 loc) • 2.35 kB
/** * react-router v8.5.2 * * 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 */ import { ABSOLUTE_URL_REGEX } from "./url.js"; //#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 validateDocumentNavigationTarget(destination) { let normalized = destination.replace(/[\t\n\r]/g, ""); let start = 0; while (normalized.charCodeAt(start) <= 32) start++; normalized = normalized.slice(start); if (!ABSOLUTE_URL_REGEX.test(normalized)) return; let target; try { target = new URL(destination, DEFAULT_NAVIGATION_URL); } catch { return; } if (!isExplicitUrl(destination, target)) throw new Error("External navigation is not allowed"); } 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, validateDocumentNavigationTarget, validateNavigationTarget };