UNPKG

2.35 kBJavaScriptView Raw
1/**
2 * react-router v8.5.2
3 *
4 * Copyright (c) Remix Software Inc.
5 *
6 * This source code is licensed under the MIT license found in the
7 * LICENSE.md file in the root directory of this source tree.
8 *
9 * @license MIT
10 */
11import { ABSOLUTE_URL_REGEX } from "./url.js";
12//#region lib/router/navigation.ts
13const DEFAULT_NAVIGATION_URL = new URL("http://localhost");
14function getNavigatorCurrentUrl(navigator) {
15 if (navigator.createURL) return navigator.createURL("/");
16 try {
17 return new URL(navigator.createHref("/"), DEFAULT_NAVIGATION_URL);
18 } catch {
19 return DEFAULT_NAVIGATION_URL;
20 }
21}
22function isSameOrigin(a, b) {
23 return a.origin === b.origin && (a.origin !== "null" || a.protocol === b.protocol && a.host === b.host);
24}
25function isExplicitUrl(destination, target) {
26 if (destination.startsWith("//")) return true;
27 let protocol = target.protocol.toLowerCase();
28 if (!destination.toLowerCase().startsWith(protocol)) return false;
29 return target.host === "" || destination.slice(protocol.length).startsWith("//");
30}
31function validateDocumentNavigationTarget(destination) {
32 let normalized = destination.replace(/[\t\n\r]/g, "");
33 let start = 0;
34 while (normalized.charCodeAt(start) <= 32) start++;
35 normalized = normalized.slice(start);
36 if (!ABSOLUTE_URL_REGEX.test(normalized)) return;
37 let target;
38 try {
39 target = new URL(destination, DEFAULT_NAVIGATION_URL);
40 } catch {
41 return;
42 }
43 if (!isExplicitUrl(destination, target)) throw new Error("External navigation is not allowed");
44}
45function validateNavigationTarget(original, resolved, currentUrl, externalPolicy) {
46 let originalUrl = null;
47 try {
48 originalUrl = original == null ? null : new URL(original, currentUrl);
49 } catch {}
50 let resolvedUrl = new URL(resolved, currentUrl);
51 let originalIsExternal = originalUrl != null && !isSameOrigin(originalUrl, currentUrl);
52 let resolvedIsExternal = !isSameOrigin(resolvedUrl, currentUrl);
53 if (externalPolicy === "reject") {
54 if (originalIsExternal || resolvedIsExternal) throw new Error("External navigation is not allowed");
55 } else if (resolvedIsExternal) {
56 if (originalUrl == null || !isExplicitUrl(original, originalUrl) || !isSameOrigin(originalUrl, resolvedUrl)) throw new Error("External navigation is not allowed");
57 }
58}
59//#endregion
60export { getNavigatorCurrentUrl, validateDocumentNavigationTarget, validateNavigationTarget };