neue Homepage auf react basis

This commit is contained in:
2026-08-07 21:39:30 +02:00
parent 164bdd19ad
commit ee89442c04
52191 changed files with 1230242 additions and 58 deletions
@@ -0,0 +1,264 @@
//#region lib/router/history.d.ts
/**
* Actions represent the type of change to a location value.
*/
declare enum Action {
/**
* A POP indicates a change to an arbitrary index in the history stack, such
* as a back or forward navigation. It does not describe the direction of the
* navigation, only that the current index changed.
*
* Note: This is the default action for newly created history objects.
*/
Pop = "POP",
/**
* A PUSH indicates a new entry being added to the history stack, such as when
* a link is clicked and a new page loads. When this happens, all subsequent
* entries in the stack are lost.
*/
Push = "PUSH",
/**
* A REPLACE indicates the entry at the current index in the history stack
* being replaced by a new one.
*/
Replace = "REPLACE"
}
/**
* The pathname, search, and hash values of a URL.
*/
interface Path {
/**
* A URL pathname, beginning with a /.
*/
pathname: string;
/**
* A URL search string, beginning with a ?.
*/
search: string;
/**
* A URL fragment identifier, beginning with a #.
*/
hash: string;
}
/**
* An entry in a history stack. A location contains information about the
* URL path, as well as possibly some arbitrary state and a key.
*/
interface Location<State = any> extends Path {
/**
* A value of arbitrary data associated with this location.
*/
state: State;
/**
* A unique string associated with this location. May be used to safely store
* and retrieve data in some other storage API, like `localStorage`.
*
* Note: This value is always "default" on the initial location.
*/
key: string;
/**
* The masked location displayed in the URL bar, which differs from the URL the
* router is operating on
*/
mask?: Path;
}
/**
* A change to the current location.
*/
interface Update {
/**
* The action that triggered the change.
*/
action: Action;
/**
* The new location.
*/
location: Location;
/**
* The delta between this location and the former location in the history stack
*/
delta: number | null;
}
/**
* A function that receives notifications about location changes.
*/
interface Listener {
(update: Update): void;
}
/**
* Describes a location that is the destination of some navigation used in
* {@link Link}, {@link useNavigate}, etc.
*/
type To = string | Partial<Path>;
/**
* A history is an interface to the navigation stack. The history serves as the
* source of truth for the current location, as well as provides a set of
* methods that may be used to change it.
*
* It is similar to the DOM's `window.history` object, but with a smaller, more
* focused API.
*/
interface History {
/**
* The last action that modified the current location. This will always be
* Action.Pop when a history instance is first created. This value is mutable.
*/
readonly action: Action;
/**
* The current location. This value is mutable.
*/
readonly location: Location;
/**
* Returns a valid href for the given `to` value that may be used as
* the value of an <a href> attribute.
*
* @param to - The destination URL
*/
createHref(to: To): string;
/**
* Returns a URL for the given `to` value
*
* @param to - The destination URL
*/
createURL(to: To): URL;
/**
* Encode a location the same way window.history would do (no-op for memory
* history) so we ensure our PUSH/REPLACE navigations for data routers
* behave the same as POP
*
* @param to Unencoded path
*/
encodeLocation(to: To): Path;
/**
* Pushes a new location onto the history stack, increasing its length by one.
* If there were any entries in the stack after the current one, they are
* lost.
*
* @param to - The new URL
* @param state - Data to associate with the new location
*/
push(to: To, state?: any): void;
/**
* Replaces the current location in the history stack with a new one. The
* location that was replaced will no longer be available.
*
* @param to - The new URL
* @param state - Data to associate with the new location
*/
replace(to: To, state?: any): void;
/**
* Navigates `n` entries backward/forward in the history stack relative to the
* current index. For example, a "back" navigation would use go(-1).
*
* @param delta - The delta in the stack index
*/
go(delta: number): void;
/**
* Sets up a listener that will be called whenever the current location
* changes.
*
* @param listener - A function that will be called when the location changes
* @returns unlisten - A function that may be used to stop listening
*/
listen(listener: Listener): () => void;
}
/**
* A user-supplied object that describes a location. Used when providing
* entries to `createMemoryHistory` via its `initialEntries` option.
*/
type InitialEntry = string | Partial<Location>;
type MemoryHistoryOptions = {
initialEntries?: InitialEntry[];
initialIndex?: number;
v5Compat?: boolean;
};
/**
* A memory history stores locations in memory. This is useful in stateful
* environments where there is no web browser, such as node tests or React
* Native.
*/
interface MemoryHistory extends History {
/**
* The current index in the history stack.
*/
readonly index: number;
}
/**
* Memory history stores the current location in memory. It is designed for use
* in stateful non-browser environments like tests and React Native.
*/
declare function createMemoryHistory(options?: MemoryHistoryOptions): MemoryHistory;
/**
* A browser history stores the current location in regular URLs in a web
* browser environment. This is the standard for most web apps and provides the
* cleanest URLs the browser's address bar.
*
* @see https://github.com/remix-run/history/tree/main/docs/api-reference.md#browserhistory
*/
interface BrowserHistory extends UrlHistory {}
type BrowserHistoryOptions = UrlHistoryOptions;
/**
* Browser history stores the location in regular URLs. This is the standard for
* most web apps, but it requires some configuration on the server to ensure you
* serve the same app at multiple URLs.
*
* @see https://github.com/remix-run/history/tree/main/docs/api-reference.md#createbrowserhistory
*/
declare function createBrowserHistory(options?: BrowserHistoryOptions): BrowserHistory;
/**
* A hash history stores the current location in the fragment identifier portion
* of the URL in a web browser environment.
*
* This is ideal for apps that do not control the server for some reason
* (because the fragment identifier is never sent to the server), including some
* shared hosting environments that do not provide fine-grained controls over
* which pages are served at which URLs.
*
* @see https://github.com/remix-run/history/tree/main/docs/api-reference.md#hashhistory
*/
interface HashHistory extends UrlHistory {}
type HashHistoryOptions = UrlHistoryOptions;
/**
* Hash history stores the location in window.location.hash. This makes it ideal
* for situations where you don't want to send the location to the server for
* some reason, either because you do cannot configure it or the URL space is
* reserved for something else.
*
* @see https://github.com/remix-run/history/tree/main/docs/api-reference.md#createhashhistory
*/
declare function createHashHistory(options?: HashHistoryOptions): HashHistory;
/**
* @private
*/
declare function invariant(value: boolean, message?: string): asserts value;
declare function invariant<T>(value: T | null | undefined, message?: string): asserts value is T;
/**
* Creates a string URL path from the given pathname, search, and hash components.
*
* @public
* @category Utils
* @param path The pathname, search, and hash components to combine.
* @returns The combined URL path.
*/
declare function createPath({
pathname,
search,
hash
}: Partial<Path>): string;
/**
* Parses a string URL path into its separate pathname, search, and hash components.
*
* @public
* @category Utils
* @param path The URL path to parse.
* @returns The parsed pathname, search, and hash components.
*/
declare function parsePath(path: string): Partial<Path>;
interface UrlHistory extends History {}
type UrlHistoryOptions = {
window?: Window;
v5Compat?: boolean;
};
//#endregion
export { Action, History, InitialEntry, Location, Path, To, createBrowserHistory, createHashHistory, createMemoryHistory, createPath, invariant, parsePath };
@@ -0,0 +1,378 @@
/**
* react-router v8.3.0
*
* 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 { PROTOCOL_RELATIVE_URL_REGEX } from "./url.js";
//#region lib/router/history.ts
/**
* Actions represent the type of change to a location value.
*/
let Action = /* @__PURE__ */ function(Action) {
/**
* A POP indicates a change to an arbitrary index in the history stack, such
* as a back or forward navigation. It does not describe the direction of the
* navigation, only that the current index changed.
*
* Note: This is the default action for newly created history objects.
*/
Action["Pop"] = "POP";
/**
* A PUSH indicates a new entry being added to the history stack, such as when
* a link is clicked and a new page loads. When this happens, all subsequent
* entries in the stack are lost.
*/
Action["Push"] = "PUSH";
/**
* A REPLACE indicates the entry at the current index in the history stack
* being replaced by a new one.
*/
Action["Replace"] = "REPLACE";
return Action;
}({});
const PopStateEventType = "popstate";
function isLocation(obj) {
return typeof obj === "object" && obj != null && "pathname" in obj && "search" in obj && "hash" in obj && "state" in obj && "key" in obj;
}
/**
* Memory history stores the current location in memory. It is designed for use
* in stateful non-browser environments like tests and React Native.
*/
function createMemoryHistory(options = {}) {
let { initialEntries = ["/"], initialIndex, v5Compat = false } = options;
let entries;
entries = initialEntries.map((entry, index) => createMemoryLocation(entry, typeof entry === "string" ? null : entry.state, index === 0 ? "default" : void 0, typeof entry === "string" ? void 0 : entry.mask));
let index = clampIndex(initialIndex == null ? entries.length - 1 : initialIndex);
let action = "POP";
let listener = null;
function clampIndex(n) {
return Math.min(Math.max(n, 0), entries.length - 1);
}
function getCurrentLocation() {
return entries[index];
}
function createMemoryLocation(to, state = null, key, mask) {
let location = createLocation(entries ? getCurrentLocation().pathname : "/", to, state, key, mask);
warning(location.pathname.charAt(0) === "/", `relative pathnames are not supported in memory history: ${JSON.stringify(to)}`);
return location;
}
function createHref(to) {
return typeof to === "string" ? to : createPath(to);
}
return {
get index() {
return index;
},
get action() {
return action;
},
get location() {
return getCurrentLocation();
},
createHref,
createURL(to) {
return new URL(createHref(to), "http://localhost");
},
encodeLocation(to) {
let path = typeof to === "string" ? parsePath(to) : to;
return {
pathname: path.pathname || "",
search: path.search || "",
hash: path.hash || ""
};
},
push(to, state) {
action = "PUSH";
let nextLocation = isLocation(to) ? to : createMemoryLocation(to, state);
index += 1;
entries.splice(index, entries.length, nextLocation);
if (v5Compat && listener) listener({
action,
location: nextLocation,
delta: 1
});
},
replace(to, state) {
action = "REPLACE";
let nextLocation = isLocation(to) ? to : createMemoryLocation(to, state);
entries[index] = nextLocation;
if (v5Compat && listener) listener({
action,
location: nextLocation,
delta: 0
});
},
go(delta) {
action = "POP";
let nextIndex = clampIndex(index + delta);
let nextLocation = entries[nextIndex];
index = nextIndex;
if (listener) listener({
action,
location: nextLocation,
delta
});
},
listen(fn) {
listener = fn;
return () => {
listener = null;
};
}
};
}
/**
* Browser history stores the location in regular URLs. This is the standard for
* most web apps, but it requires some configuration on the server to ensure you
* serve the same app at multiple URLs.
*
* @see https://github.com/remix-run/history/tree/main/docs/api-reference.md#createbrowserhistory
*/
function createBrowserHistory(options = {}) {
function createBrowserLocation(window, globalHistory) {
let maskedLocation = globalHistory.state?.masked;
let { pathname, search, hash } = maskedLocation || window.location;
return createLocation("", {
pathname,
search,
hash
}, globalHistory.state && globalHistory.state.usr || null, globalHistory.state && globalHistory.state.key || "default", maskedLocation ? {
pathname: window.location.pathname,
search: window.location.search,
hash: window.location.hash
} : void 0);
}
function createBrowserHref(window, to) {
return typeof to === "string" ? to : createPath(to);
}
return getUrlBasedHistory(createBrowserLocation, createBrowserHref, null, options);
}
/**
* Hash history stores the location in window.location.hash. This makes it ideal
* for situations where you don't want to send the location to the server for
* some reason, either because you do cannot configure it or the URL space is
* reserved for something else.
*
* @see https://github.com/remix-run/history/tree/main/docs/api-reference.md#createhashhistory
*/
function createHashHistory(options = {}) {
function createHashLocation(window, globalHistory) {
let { pathname = "/", search = "", hash = "" } = parsePath(window.location.hash.substring(1));
if (!pathname.startsWith("/") && !pathname.startsWith(".")) pathname = "/" + pathname;
return createLocation("", {
pathname,
search,
hash
}, globalHistory.state && globalHistory.state.usr || null, globalHistory.state && globalHistory.state.key || "default");
}
function createHashHref(window, to) {
let base = window.document.querySelector("base");
let href = "";
if (base && base.getAttribute("href")) {
let url = window.location.href;
let hashIndex = url.indexOf("#");
href = hashIndex === -1 ? url : url.slice(0, hashIndex);
}
return href + "#" + (typeof to === "string" ? to : createPath(to));
}
function validateHashLocation(location, to) {
warning(location.pathname.charAt(0) === "/", `relative pathnames are not supported in hash history.push(${JSON.stringify(to)})`);
}
return getUrlBasedHistory(createHashLocation, createHashHref, validateHashLocation, options);
}
function invariant(value, message) {
if (value === false || value === null || typeof value === "undefined") throw new Error(message);
}
function warning(cond, message) {
if (!cond) {
if (typeof console !== "undefined") console.warn(message);
try {
throw new Error(message);
} catch (e) {}
}
}
function createKey() {
return Math.random().toString(36).substring(2, 10);
}
/**
* For browser-based histories, we combine the state and key into an object
*/
function getHistoryState(location, index) {
return {
usr: location.state,
key: location.key,
idx: index,
masked: location.mask ? {
pathname: location.pathname,
search: location.search,
hash: location.hash
} : void 0
};
}
/**
* Creates a Location object with a unique key from the given Path
*/
function createLocation(current, to, state = null, key, mask) {
return {
pathname: typeof current === "string" ? current : current.pathname,
search: "",
hash: "",
...typeof to === "string" ? parsePath(to) : to,
state,
key: to && to.key || key || createKey(),
mask
};
}
/**
* Creates a string URL path from the given pathname, search, and hash components.
*
* @public
* @category Utils
* @param path The pathname, search, and hash components to combine.
* @returns The combined URL path.
*/
function createPath({ pathname = "/", search = "", hash = "" }) {
if (search && search !== "?") pathname += search.charAt(0) === "?" ? search : "?" + search;
if (hash && hash !== "#") pathname += hash.charAt(0) === "#" ? hash : "#" + hash;
return pathname;
}
/**
* Parses a string URL path into its separate pathname, search, and hash components.
*
* @public
* @category Utils
* @param path The URL path to parse.
* @returns The parsed pathname, search, and hash components.
*/
function parsePath(path) {
let parsedPath = {};
if (path) {
let hashIndex = path.indexOf("#");
if (hashIndex >= 0) {
parsedPath.hash = path.substring(hashIndex);
path = path.substring(0, hashIndex);
}
let searchIndex = path.indexOf("?");
if (searchIndex >= 0) {
parsedPath.search = path.substring(searchIndex);
path = path.substring(0, searchIndex);
}
if (path) parsedPath.pathname = path;
}
return parsedPath;
}
function getUrlBasedHistory(getLocation, createHref, validateLocation, options = {}) {
let { window = document.defaultView, v5Compat = false } = options;
let globalHistory = window.history;
let action = "POP";
let listener = null;
let index = getIndex();
if (index == null) {
index = 0;
globalHistory.replaceState({
...globalHistory.state,
idx: index
}, "");
}
function getIndex() {
return (globalHistory.state || { idx: null }).idx;
}
function handlePop() {
action = "POP";
let nextIndex = getIndex();
let delta = nextIndex == null ? null : nextIndex - index;
index = nextIndex;
if (listener) listener({
action,
location: history.location,
delta
});
}
function push(to, state) {
action = "PUSH";
let location = isLocation(to) ? to : createLocation(history.location, to, state);
if (validateLocation) validateLocation(location, to);
index = getIndex() + 1;
let historyState = getHistoryState(location, index);
let url = history.createHref(location.mask || location);
try {
globalHistory.pushState(historyState, "", url);
} catch (error) {
if (error instanceof DOMException && error.name === "DataCloneError") throw error;
window.location.assign(url);
}
if (v5Compat && listener) listener({
action,
location: history.location,
delta: 1
});
}
function replace(to, state) {
action = "REPLACE";
let location = isLocation(to) ? to : createLocation(history.location, to, state);
if (validateLocation) validateLocation(location, to);
index = getIndex();
let historyState = getHistoryState(location, index);
let url = history.createHref(location.mask || location);
globalHistory.replaceState(historyState, "", url);
if (v5Compat && listener) listener({
action,
location: history.location,
delta: 0
});
}
function createURL(to) {
return createBrowserURLImpl(window, to);
}
let history = {
get action() {
return action;
},
get location() {
return getLocation(window, globalHistory);
},
listen(fn) {
if (listener) throw new Error("A history only accepts one active listener");
window.addEventListener(PopStateEventType, handlePop);
listener = fn;
return () => {
window.removeEventListener(PopStateEventType, handlePop);
listener = null;
};
},
createHref(to) {
return createHref(window, to);
},
createURL,
encodeLocation(to) {
let url = createURL(to);
return {
pathname: url.pathname,
search: url.search,
hash: url.hash
};
},
push,
replace,
go(n) {
return globalHistory.go(n);
}
};
return history;
}
function createBrowserURLImpl(windowImpl, to, isAbsolute = false) {
let base = "http://localhost";
if (windowImpl) base = windowImpl.location.origin !== "null" ? windowImpl.location.origin : windowImpl.location.href;
invariant(base, "No window.location.(origin|href) available to create URL");
let href = typeof to === "string" ? to : createPath(to);
href = href.replace(/ $/, "%20");
if (!isAbsolute && PROTOCOL_RELATIVE_URL_REGEX.test(href)) href = base + href;
return new URL(href, base);
}
//#endregion
export { Action, createBrowserHistory, createBrowserURLImpl, createHashHistory, createLocation, createMemoryHistory, createPath, invariant, parsePath, warning };
@@ -0,0 +1,111 @@
import { FormEncType, HTMLFormMethod, LoaderFunctionArgs, RouterContextProvider } from "./utils.js";
//#region lib/router/instrumentation.d.ts
type ServerInstrumentation = {
handler?: InstrumentRequestHandlerFunction;
route?: InstrumentRouteFunction;
};
type ClientInstrumentation = {
router?: InstrumentRouterFunction;
route?: InstrumentRouteFunction;
};
type InstrumentRequestHandlerFunction = (handler: InstrumentableRequestHandler) => void;
type InstrumentRouterFunction = (router: InstrumentableRouter) => void;
type InstrumentRouteFunction = (route: InstrumentableRoute) => void;
/**
* Route metadata available after React Router has matched an instrumented
* request, navigation, or fetcher call.
*/
type InstrumentationResultMeta = {
url: LoaderFunctionArgs["url"];
pattern: string;
params: LoaderFunctionArgs["params"];
};
/**
* Result returned by route-level instrumented handler calls, such as
* instrumented loaders, actions, middleware, and lazy route functions.
*/
type InstrumentationHandlerResult = {
status: "success";
error: undefined;
} | {
status: "error";
error: Error;
};
/**
* Result returned by client-side router instrumented navigation and fetcher
* calls.
*/
type InstrumentationClientRouterResult = InstrumentationHandlerResult & {
meta: InstrumentationResultMeta | undefined;
};
/**
* Result returned by server request handler instrumentation.
*/
type InstrumentationServerHandlerResult = InstrumentationHandlerResult & {
statusCode: number;
meta: InstrumentationResultMeta | undefined;
};
type InstrumentFunction<T, TInnerResult = InstrumentationHandlerResult> = (handler: () => Promise<TInnerResult>, info: T) => Promise<void>;
type ReadonlyRequest = {
method: string;
url: string;
headers: Pick<Headers, "get">;
};
type ReadonlyContext = Pick<RouterContextProvider, "get">;
type InstrumentableRoute = {
id: string;
index: boolean | undefined;
path: string | undefined;
instrument(instrumentations: RouteInstrumentations): void;
};
type RouteInstrumentations = {
lazy?: InstrumentFunction<RouteLazyInstrumentationInfo>;
"lazy.loader"?: InstrumentFunction<RouteLazyInstrumentationInfo>;
"lazy.action"?: InstrumentFunction<RouteLazyInstrumentationInfo>;
"lazy.middleware"?: InstrumentFunction<RouteLazyInstrumentationInfo>;
middleware?: InstrumentFunction<RouteHandlerInstrumentationInfo>;
loader?: InstrumentFunction<RouteHandlerInstrumentationInfo>;
action?: InstrumentFunction<RouteHandlerInstrumentationInfo>;
};
type RouteLazyInstrumentationInfo = undefined;
type RouteHandlerInstrumentationInfo = Readonly<Omit<LoaderFunctionArgs, "request" | "context"> & {
request: ReadonlyRequest;
context: ReadonlyContext;
}>;
type InstrumentableRouter = {
instrument(instrumentations: RouterInstrumentations): void;
};
type RouterInstrumentations = {
navigate?: InstrumentFunction<RouterNavigationInstrumentationInfo, InstrumentationClientRouterResult>;
fetch?: InstrumentFunction<RouterFetchInstrumentationInfo, InstrumentationClientRouterResult>;
};
type RouterNavigationInstrumentationInfo = Readonly<{
to: string | number;
currentUrl: string;
formMethod?: HTMLFormMethod;
formEncType?: FormEncType;
formData?: FormData;
body?: any;
}>;
type RouterFetchInstrumentationInfo = Readonly<{
href: string;
currentUrl: string;
fetcherKey: string;
formMethod?: HTMLFormMethod;
formEncType?: FormEncType;
formData?: FormData;
body?: any;
}>;
type InstrumentableRequestHandler = {
instrument(instrumentations: RequestHandlerInstrumentations): void;
};
type RequestHandlerInstrumentations = {
request?: InstrumentFunction<RequestHandlerInstrumentationInfo, InstrumentationServerHandlerResult>;
};
type RequestHandlerInstrumentationInfo = Readonly<{
request: ReadonlyRequest;
context: ReadonlyContext | undefined;
}>;
//#endregion
export { ClientInstrumentation, InstrumentRequestHandlerFunction, InstrumentRouteFunction, InstrumentRouterFunction, InstrumentationClientRouterResult, InstrumentationHandlerResult, InstrumentationServerHandlerResult, ServerInstrumentation };
@@ -0,0 +1,290 @@
/**
* react-router v8.3.0
*
* 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 { createPath, invariant } from "./history.js";
import { RouterContextProvider, createContext } from "./utils.js";
//#region lib/router/instrumentation.ts
const UninstrumentedSymbol = Symbol("Uninstrumented");
const instrumentationResultMetaContext = createContext();
let instrumentationClientResultMetaReceivers = /* @__PURE__ */ new WeakMap();
function getRouteInstrumentationUpdates(fns, route) {
let aggregated = {
lazy: [],
"lazy.loader": [],
"lazy.action": [],
"lazy.middleware": [],
middleware: [],
loader: [],
action: []
};
fns.forEach((fn) => fn({
id: route.id,
index: route.index,
path: route.path,
instrument(i) {
if (i.lazy != null) aggregated.lazy.push(i.lazy);
if (i["lazy.loader"] != null) aggregated["lazy.loader"].push(i["lazy.loader"]);
if (i["lazy.action"] != null) aggregated["lazy.action"].push(i["lazy.action"]);
if (i["lazy.middleware"] != null) aggregated["lazy.middleware"].push(i["lazy.middleware"]);
if (i.middleware != null) aggregated.middleware.push(i.middleware);
if (i.loader != null) aggregated.loader.push(i.loader);
if (i.action != null) aggregated.action.push(i.action);
}
}));
let updates = {};
if (typeof route.lazy === "function" && aggregated.lazy.length > 0) {
let lazy = route.lazy;
updates.lazy = async (...args) => {
return throwOrReturnResult(await recurseRight(aggregated.lazy, void 0, () => lazy(...args), getInstrumentationInnerResult));
};
}
if (typeof route.lazy === "object") {
let lazyObject = route.lazy;
if (typeof lazyObject.middleware === "function" && aggregated["lazy.middleware"].length > 0) {
let middleware = lazyObject.middleware;
updates.lazy = Object.assign(updates.lazy || {}, { middleware: async (...args) => {
return throwOrReturnResult(await recurseRight(aggregated["lazy.middleware"], void 0, () => middleware(...args), getInstrumentationInnerResult));
} });
}
if (typeof lazyObject.loader === "function" && aggregated["lazy.loader"].length > 0) {
let loader = lazyObject.loader;
updates.lazy = Object.assign(updates.lazy || {}, { loader: async (...args) => {
return throwOrReturnResult(await recurseRight(aggregated["lazy.loader"], void 0, () => loader(...args), getInstrumentationInnerResult));
} });
}
if (typeof lazyObject.action === "function" && aggregated["lazy.action"].length > 0) {
let action = lazyObject.action;
updates.lazy = Object.assign(updates.lazy || {}, { action: async (...args) => {
return throwOrReturnResult(await recurseRight(aggregated["lazy.action"], void 0, () => action(...args), getInstrumentationInnerResult));
} });
}
}
if (typeof route.loader === "function" && aggregated.loader.length > 0) {
let original = getUninstrumentedHandler(route.loader);
let instrumented = async (...args) => {
return throwOrReturnResult(await recurseRight(aggregated.loader, getHandlerInfo(args[0]), () => original(...args), getInstrumentationInnerResult));
};
if (original.hydrate === true) instrumented.hydrate = true;
setUninstrumentedHandler(instrumented, original);
updates.loader = instrumented;
}
if (typeof route.action === "function" && aggregated.action.length > 0) {
let original = getUninstrumentedHandler(route.action);
let instrumented = async (...args) => {
return throwOrReturnResult(await recurseRight(aggregated.action, getHandlerInfo(args[0]), () => original(...args), getInstrumentationInnerResult));
};
setUninstrumentedHandler(instrumented, original);
updates.action = instrumented;
}
if (route.middleware && route.middleware.length > 0 && aggregated.middleware.length > 0) updates.middleware = route.middleware.map((middleware) => {
let original = getUninstrumentedHandler(middleware);
let instrumented = async (...args) => {
return throwOrReturnResult(await recurseRight(aggregated.middleware, getHandlerInfo(args[0]), () => original(...args), getInstrumentationInnerResult));
};
setUninstrumentedHandler(instrumented, original);
return instrumented;
});
return updates;
}
function instrumentClientSideRouter(router, fns) {
let aggregated = {
navigate: [],
fetch: []
};
fns.forEach((fn) => fn({ instrument(i) {
if (i.navigate != null) aggregated.navigate.push(i.navigate);
if (i.fetch != null) aggregated.fetch.push(i.fetch);
} }));
if (aggregated.navigate.length > 0) {
let navigate = getUninstrumentedHandler(router.navigate);
let instrumentedNavigate = async (...args) => {
let [to, opts] = args;
let meta;
let info = {
to: typeof to === "number" || typeof to === "string" ? to : to ? createPath(to) : ".",
...getRouterInfo(router, opts ?? {})
};
return throwOrReturnResult(await recurseRight(aggregated.navigate, info, async () => {
if (typeof to === "number") return await navigate(...args);
let cleanup = setInstrumentationClientResultMetaReceiver(router, (value) => {
meta = value;
});
try {
return await navigate(...args);
} finally {
cleanup();
}
}, (result) => ({
...getInstrumentationInnerResult(result),
meta
})));
};
setUninstrumentedHandler(instrumentedNavigate, navigate);
router.navigate = instrumentedNavigate;
}
if (aggregated.fetch.length > 0) {
let fetch = getUninstrumentedHandler(router.fetch);
let instrumentedFetch = async (...args) => {
let [key, _, href, opts] = args;
let meta;
return throwOrReturnResult(await recurseRight(aggregated.fetch, {
href: href ?? ".",
fetcherKey: key,
...getRouterInfo(router, opts ?? {})
}, async () => {
let cleanup = setInstrumentationClientResultMetaReceiver(router, (value) => {
meta = value;
});
try {
return await fetch(...args);
} finally {
cleanup();
}
}, (result) => ({
...getInstrumentationInnerResult(result),
meta
})));
};
setUninstrumentedHandler(instrumentedFetch, fetch);
router.fetch = instrumentedFetch;
}
return router;
}
function instrumentHandler(handler, fns) {
let aggregated = { request: [] };
fns.forEach((fn) => fn({ instrument(i) {
if (i.request != null) aggregated.request.push(i.request);
} }));
let instrumentedHandler = handler;
if (aggregated.request.length > 0) instrumentedHandler = async (...args) => {
let [request, context] = args;
let instrumentationContext = context ?? new RouterContextProvider();
return throwOrReturnResult(await recurseRight(aggregated.request, {
request: getReadonlyRequest(request),
context: getReadonlyContext(instrumentationContext)
}, () => handler(request, instrumentationContext), (result, info) => {
let meta;
try {
meta = info.context?.get(instrumentationResultMetaContext);
} catch {}
invariant(result.value instanceof Response, "Expected a Response from the request handler");
return {
...getInstrumentationInnerResult(result),
statusCode: result.value.status,
meta
};
}));
};
return instrumentedHandler;
}
function getUninstrumentedHandler(handler) {
return handler[UninstrumentedSymbol] ?? handler;
}
function setUninstrumentedHandler(handler, uninstrumentedHandler) {
handler[UninstrumentedSymbol] = uninstrumentedHandler;
}
function setInstrumentationClientResultMetaReceiver(router, receiver) {
instrumentationClientResultMetaReceivers.set(router, receiver);
return () => {
if (instrumentationClientResultMetaReceivers.get(router) === receiver) instrumentationClientResultMetaReceivers.delete(router);
};
}
function consumeInstrumentationClientResultMetaReceiver(router) {
let receiver = instrumentationClientResultMetaReceivers.get(router);
instrumentationClientResultMetaReceivers.delete(router);
return receiver;
}
function throwOrReturnResult(result) {
if (result.type === "error") throw result.value;
return result.value;
}
async function recurseRight(impls, info, handler, getInnerResult, state = {
result: null,
innerResult: null
}, index = impls.length - 1) {
let impl = impls[index];
if (!impl) {
try {
state.result = {
type: "success",
value: await handler()
};
} catch (e) {
state.result = {
type: "error",
value: e
};
}
state.innerResult = getInnerResult(state.result, info);
} else {
let handlerPromise = void 0;
let callHandler = async () => {
if (handlerPromise) console.error("You cannot call instrumented handlers more than once");
else handlerPromise = recurseRight(impls, info, handler, getInnerResult, state, index - 1);
await handlerPromise;
invariant(state.innerResult, "Expected an inner result");
return state.innerResult;
};
try {
await impl(callHandler, info);
} catch (e) {
console.error("An instrumentation function threw an error:", e);
}
if (!handlerPromise) await callHandler();
await handlerPromise;
}
if (state.result) return state.result;
state.result = {
type: "error",
value: /* @__PURE__ */ new Error("No result assigned in instrumentation chain.")
};
state.innerResult = getInnerResult(state.result, info);
return state.result;
}
function getInstrumentationInnerResult(result) {
if (result.type === "error" && result.value instanceof Error) return {
status: "error",
error: result.value
};
return {
status: "success",
error: void 0
};
}
function getHandlerInfo(args) {
let { request, context, params } = args;
return {
...args,
request: getReadonlyRequest(request),
params: { ...params },
context: getReadonlyContext(context)
};
}
function getRouterInfo(router, opts) {
return {
currentUrl: createPath(router.state.location),
..."formMethod" in opts ? { formMethod: opts.formMethod } : {},
..."formEncType" in opts ? { formEncType: opts.formEncType } : {},
..."formData" in opts ? { formData: opts.formData } : {},
..."body" in opts ? { body: opts.body } : {}
};
}
function getReadonlyRequest(request) {
return {
method: request.method,
url: request.url,
headers: { get: (...args) => request.headers.get(...args) }
};
}
function getReadonlyContext(context) {
return { get: (ctx) => context.get(ctx) };
}
//#endregion
export { consumeInstrumentationClientResultMetaReceiver, getRouteInstrumentationUpdates, instrumentClientSideRouter, instrumentHandler, instrumentationResultMetaContext };
@@ -0,0 +1,114 @@
//#region lib/router/links.d.ts
type Primitive = null | undefined | string | number | boolean | symbol | bigint;
type LiteralUnion<LiteralType, BaseType extends Primitive> = LiteralType | (BaseType & Record<never, never>);
interface HtmlLinkProps {
/**
* Address of the hyperlink
*/
href?: string;
/**
* How the element handles crossorigin requests
*/
crossOrigin?: "anonymous" | "use-credentials";
/**
* Relationship between the document containing the hyperlink and the destination resource
*/
rel: LiteralUnion<"alternate" | "dns-prefetch" | "icon" | "manifest" | "modulepreload" | "next" | "pingback" | "preconnect" | "prefetch" | "preload" | "prerender" | "search" | "stylesheet", string>;
/**
* Applicable media: "screen", "print", "(max-width: 764px)"
*/
media?: string;
/**
* Integrity metadata used in Subresource Integrity checks
*/
integrity?: string;
/**
* Language of the linked resource
*/
hrefLang?: string;
/**
* Hint for the type of the referenced resource
*/
type?: string;
/**
* Referrer policy for fetches initiated by the element
*/
referrerPolicy?: "" | "no-referrer" | "no-referrer-when-downgrade" | "same-origin" | "origin" | "strict-origin" | "origin-when-cross-origin" | "strict-origin-when-cross-origin" | "unsafe-url";
/**
* Sizes of the icons (for rel="icon")
*/
sizes?: string;
/**
* Potential destination for a preload request (for rel="preload" and rel="modulepreload")
*/
as?: LiteralUnion<"audio" | "audioworklet" | "document" | "embed" | "fetch" | "font" | "frame" | "iframe" | "image" | "manifest" | "object" | "paintworklet" | "report" | "script" | "serviceworker" | "sharedworker" | "style" | "track" | "video" | "worker" | "xslt", string>;
/**
* Color to use when customizing a site's icon (for rel="mask-icon")
*/
color?: string;
/**
* Whether the link is disabled
*/
disabled?: boolean;
/**
* The title attribute has special semantics on this element: Title of the link; CSS style sheet set name.
*/
title?: string;
/**
* Images to use in different situations, e.g., high-resolution displays,
* small monitors, etc. (for rel="preload")
*/
imageSrcSet?: string;
/**
* Image sizes for different page layouts (for rel="preload")
*/
imageSizes?: string;
}
interface HtmlLinkPreloadImage extends HtmlLinkProps {
/**
* Relationship between the document containing the hyperlink and the destination resource
*/
rel: "preload";
/**
* Potential destination for a preload request (for rel="preload" and rel="modulepreload")
*/
as: "image";
/**
* Address of the hyperlink
*/
href?: string;
/**
* Images to use in different situations, e.g., high-resolution displays,
* small monitors, etc. (for rel="preload")
*/
imageSrcSet: string;
/**
* Image sizes for different page layouts (for rel="preload")
*/
imageSizes?: string;
}
/**
* Represents a `<link>` element.
*
* WHATWG Specification: https://html.spec.whatwg.org/multipage/semantics.html#the-link-element
*/
type HtmlLinkDescriptor = (HtmlLinkProps & Pick<Required<HtmlLinkProps>, "href">) | (HtmlLinkPreloadImage & Pick<Required<HtmlLinkPreloadImage>, "imageSizes">) | (HtmlLinkPreloadImage & Pick<Required<HtmlLinkPreloadImage>, "href"> & {
imageSizes?: never;
});
interface PageLinkDescriptor extends Omit<HtmlLinkDescriptor, "href" | "rel" | "type" | "sizes" | "imageSrcSet" | "imageSizes" | "as" | "color" | "title"> {
/**
* A [`nonce`](https://developer.mozilla.org/en-US/docs/Web/HTML/Reference/Global_attributes/nonce)
* attribute to render on the [`<link>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/link)
* element. If not provided in Framework Mode, it will default to any
* {@link ServerRouter | `<ServerRouter nonce>`} prop.
*/
nonce?: string | undefined;
/**
* The absolute path of the page to prefetch, e.g. `/absolute/path`.
*/
page: string;
}
type LinkDescriptor = HtmlLinkDescriptor | PageLinkDescriptor;
//#endregion
export { HtmlLinkDescriptor, LinkDescriptor, PageLinkDescriptor };
@@ -0,0 +1,663 @@
import { Action, History, Location, Path, To } from "./history.js";
import { DataRouteMatch, DataRouteObject, DataStrategyFunction, FormEncType, HTMLFormMethod, MapRoutePropertiesFunction, MaybePromise, PatchRoutesOnNavigationFunction, RouteBranch, RouteData, RouteManifest, RouteObject, RouterContextProvider, Submission, UIMatch } from "./utils.js";
import { ClientInstrumentation, ServerInstrumentation } from "./instrumentation.js";
//#region lib/router/router.d.ts
/**
* A Router instance manages all navigation and data loading/mutations
*/
interface Router {
/**
* @private
* PRIVATE - DO NOT USE
*
* Return the basename for the router
*/
get basename(): RouterInit["basename"];
/**
* @private
* PRIVATE - DO NOT USE
*
* Return the future config for the router
*/
get future(): FutureConfig;
/**
* @private
* PRIVATE - DO NOT USE
*
* Return the current state of the router
*/
get state(): RouterState;
/**
* @private
* PRIVATE - DO NOT USE
*
* Return the routes for this router instance
*/
get routes(): DataRouteObject[];
/**
* @private
* PRIVATE - DO NOT USE
*
* Return the route branches for this router instance
*/
get branches(): RouteBranch<DataRouteObject>[] | undefined;
/**
* @private
* PRIVATE - DO NOT USE
*
* Return the manifest for this router instance
*/
get manifest(): RouteManifest;
/**
* @private
* PRIVATE - DO NOT USE
*
* Return the window associated with the router
*/
get window(): RouterInit["window"];
/**
* @private
* PRIVATE - DO NOT USE
*
* Initialize the router, including adding history listeners and kicking off
* initial data fetches. Returns a function to cleanup listeners and abort
* any in-progress loads
*/
initialize(): Router;
/**
* @private
* PRIVATE - DO NOT USE
*
* Subscribe to router.state updates
*
* @param fn function to call with the new state
*/
subscribe(fn: RouterSubscriber): () => void;
/**
* @private
* PRIVATE - DO NOT USE
*
* Enable scroll restoration behavior in the router
*
* @param savedScrollPositions Object that will manage positions, in case
* it's being restored from sessionStorage
* @param getScrollPosition Function to get the active Y scroll position
* @param getKey Function to get the key to use for restoration
*/
enableScrollRestoration(savedScrollPositions: Record<string, number>, getScrollPosition: GetScrollPositionFunction, getKey?: GetScrollRestorationKeyFunction): () => void;
/**
* @private
* PRIVATE - DO NOT USE
*
* Navigate forward/backward in the history stack
* @param to Delta to move in the history stack
*/
navigate(to: number): Promise<void>;
/**
* Navigate to the given path
* @param to Path to navigate to
* @param opts Navigation options (method, submission, etc.)
*/
navigate(to: To | null, opts?: RouterNavigateOptions): Promise<void>;
/**
* @private
* PRIVATE - DO NOT USE
*
* Trigger a fetcher load/submission
*
* @param key Fetcher key
* @param routeId Route that owns the fetcher
* @param href href to fetch
* @param opts Fetcher options, (method, submission, etc.)
*/
fetch(key: string, routeId: string, href: string | null, opts?: RouterFetchOptions): Promise<void>;
/**
* @private
* PRIVATE - DO NOT USE
*
* Trigger a revalidation of all current route loaders and fetcher loads
*/
revalidate(): Promise<void>;
/**
* @private
* PRIVATE - DO NOT USE
*
* Utility function to create an href for the given location
* @param location
*/
createHref(location: Location | URL): string;
/**
* @private
* PRIVATE - DO NOT USE
*
* Utility function to URL encode a destination path according to the internal
* history implementation
* @param to
*/
encodeLocation(to: To): Path;
/**
* @private
* PRIVATE - DO NOT USE
*
* Get/create a fetcher for the given key
* @param key
*/
getFetcher<TData = any>(key: string): Fetcher<TData>;
/**
* @internal
* PRIVATE - DO NOT USE
*
* Reset the fetcher for a given key
* @param key
*/
resetFetcher(key: string, opts?: {
reason?: unknown;
}): void;
/**
* @private
* PRIVATE - DO NOT USE
*
* Delete the fetcher for a given key
* @param key
*/
deleteFetcher(key: string): void;
/**
* @private
* PRIVATE - DO NOT USE
*
* Cleanup listeners and abort any in-progress loads
*/
dispose(): void;
/**
* @private
* PRIVATE - DO NOT USE
*
* Get a navigation blocker
* @param key The identifier for the blocker
* @param fn The blocker function implementation
*/
getBlocker(key: string, fn: BlockerFunction): Blocker;
/**
* @private
* PRIVATE - DO NOT USE
*
* Delete a navigation blocker
* @param key The identifier for the blocker
*/
deleteBlocker(key: string): void;
/**
* @private
* PRIVATE DO NOT USE
*
* Patch additional children routes into an existing parent route
* @param routeId The parent route id or a callback function accepting `patch`
* to perform batch patching
* @param children The additional children routes
* @param unstable_allowElementMutations Allow mutation or route elements on
* existing routes. Intended for RSC-usage
* only.
*/
patchRoutes(routeId: string | null, children: RouteObject[], unstable_allowElementMutations?: boolean): void;
/**
* @private
* PRIVATE - DO NOT USE
*
* HMR needs to pass in-flight route updates to React Router
* TODO: Replace this with granular route update APIs (addRoute, updateRoute, deleteRoute)
*/
_internalSetRoutes(routes: RouteObject[]): void;
/**
* @private
* PRIVATE - DO NOT USE
*
* Cause subscribers to re-render. This is used to force a re-render.
*/
_internalSetStateDoNotUseOrYouWillBreakYourApp(state: Partial<RouterState>): void;
/**
* @private
* PRIVATE - DO NOT USE
*
* Internal fetch AbortControllers accessed by unit tests
*/
_internalFetchControllers: Map<string, AbortController>;
}
/**
* State maintained internally by the router. During a navigation, all states
* reflect the "old" location unless otherwise noted.
*/
interface RouterState {
/**
* The action of the most recent navigation
*/
historyAction: Action;
/**
* The current location reflected by the router
*/
location: Location;
/**
* The current set of route matches
*/
matches: DataRouteMatch[];
/**
* Tracks whether we've completed our initial data load
*/
initialized: boolean;
/**
* Tracks whether we should be rendering a HydrateFallback during hydration
*/
renderFallback: boolean;
/**
* Current scroll position we should start at for a new view
* - number -> scroll position to restore to
* - false -> do not restore scroll at all (used during submissions/revalidations)
* - null -> don't have a saved position, scroll to hash or top of page
*/
restoreScrollPosition: number | false | null;
/**
* Indicate whether this navigation should skip resetting the scroll position
* if we are unable to restore the scroll position
*/
preventScrollReset: boolean;
/**
* Tracks the state of the current navigation
*/
navigation: Navigation;
/**
* Tracks any in-progress revalidations
*/
revalidation: RevalidationState;
/**
* Data from the loaders for the current matches
*/
loaderData: RouteData;
/**
* Data from the action for the current matches
*/
actionData: RouteData | null;
/**
* Errors caught from loaders for the current matches
*/
errors: RouteData | null;
/**
* Map of current fetchers
*/
fetchers: Map<string, Fetcher>;
/**
* Map of current blockers
*/
blockers: Map<string, Blocker>;
}
/**
* Data that can be passed into hydrate a Router from SSR
*/
type HydrationState = Partial<Pick<RouterState, "loaderData" | "actionData" | "errors">>;
/**
* Future flags to toggle new feature behavior
*/
interface FutureConfig {}
/**
* Initialization options for createRouter
*/
interface RouterInit {
routes: RouteObject[];
history: History;
basename?: string;
getContext?: () => MaybePromise<RouterContextProvider>;
instrumentations?: ClientInstrumentation[];
mapRouteProperties?: MapRoutePropertiesFunction;
future?: Partial<FutureConfig>;
hydrationRouteProperties?: string[];
hydrationData?: HydrationState;
window?: Window;
dataStrategy?: DataStrategyFunction;
patchRoutesOnNavigation?: PatchRoutesOnNavigationFunction;
}
/**
* State returned from a server-side query() call
*/
interface StaticHandlerContext {
basename: Router["basename"];
location: RouterState["location"];
matches: RouterState["matches"];
loaderData: RouterState["loaderData"];
actionData: RouterState["actionData"];
errors: RouterState["errors"];
statusCode: number;
loaderHeaders: Record<string, Headers>;
actionHeaders: Record<string, Headers>;
_deepestRenderedBoundaryId?: string | null;
}
/**
* A StaticHandler instance manages a singular SSR navigation/fetch event
*/
interface StaticHandler {
/**
* The set of data routes managed by this handler
*/
dataRoutes: DataRouteObject[];
/**
* @private
* PRIVATE - DO NOT USE
*
* The route branches derived from the data routes, used for internal route
* matching in Framework Mode
*/
_internalRouteBranches: RouteBranch<DataRouteObject>[];
/**
* Perform a query for a given request - executing all matched route
* loaders/actions. Used for document requests.
*
* @param request The request to query
* @param opts Optional query options
* @param opts.dataStrategy Alternate dataStrategy implementation
* @param opts.filterMatchesToLoad Predicate function to filter which matches should be loaded
* @param opts.generateMiddlewareResponse To enable middleware, provide a function
* to generate a response to bubble back up the middleware chain
* @param opts.requestContext Context object to pass to loaders/actions
* @param opts.skipLoaderErrorBubbling Skip loader error bubbling
* @param opts.skipRevalidation Skip revalidation after action submission
* @param opts.normalizePath Normalize the request path
*/
query(request: Request, opts?: {
requestContext?: unknown;
filterMatchesToLoad?: (match: DataRouteMatch) => boolean;
skipLoaderErrorBubbling?: boolean;
skipRevalidation?: boolean;
dataStrategy?: DataStrategyFunction<unknown>;
generateMiddlewareResponse?: (query: (r: Request, args?: {
filterMatchesToLoad?: (match: DataRouteMatch) => boolean;
}) => Promise<StaticHandlerContext | Response>) => MaybePromise<Response>;
normalizePath?: (request: Request) => Path;
}): Promise<StaticHandlerContext | Response>;
/**
* Perform a query for a specific route. Used for resource requests.
*
* @param request The request to query
* @param opts Optional queryRoute options
* @param opts.dataStrategy Alternate dataStrategy implementation
* @param opts.generateMiddlewareResponse To enable middleware, provide a function
* to generate a response to bubble back up the middleware chain
* @param opts.requestContext Context object to pass to loaders/actions
* @param opts.routeId The ID of the route to query
* @param opts.normalizePath Normalize the request path
*/
queryRoute(request: Request, opts?: {
routeId?: string;
requestContext?: unknown;
dataStrategy?: DataStrategyFunction<unknown>;
generateMiddlewareResponse?: (queryRoute: (r: Request) => Promise<Response>) => MaybePromise<Response>;
normalizePath?: (request: Request) => Path;
}): Promise<any>;
}
type ViewTransitionOpts = {
currentLocation: Location;
nextLocation: Location;
};
/**
* Subscriber function signature for changes to router state
*/
interface RouterSubscriber {
(state: RouterState, opts: {
deletedFetchers: string[];
newErrors: RouteData | null;
viewTransitionOpts?: ViewTransitionOpts;
flushSync: boolean;
}): void;
}
/**
* Function signature for determining the key to be used in scroll restoration
* for a given location
*/
interface GetScrollRestorationKeyFunction {
(location: Location, matches: UIMatch[]): string | null;
}
/**
* Function signature for determining the current scroll position
*/
interface GetScrollPositionFunction {
(): number;
}
/**
* - "route": relative to the route hierarchy so `..` means remove all segments
* of the current route even if it has many. For example, a `route("posts/:id")`
* would have both `:id` and `posts` removed from the url.
* - "path": relative to the pathname so `..` means remove one segment of the
* pathname. For example, a `route("posts/:id")` would have only `:id` removed
* from the url.
*/
type RelativeRoutingType = "route" | "path";
type BaseNavigateOrFetchOptions = {
preventScrollReset?: boolean;
relative?: RelativeRoutingType;
flushSync?: boolean;
defaultShouldRevalidate?: boolean;
};
type BaseNavigateOptions = BaseNavigateOrFetchOptions & {
replace?: boolean;
state?: any;
fromRouteId?: string;
viewTransition?: boolean;
mask?: To;
};
type BaseSubmissionOptions = {
formMethod?: HTMLFormMethod;
formEncType?: FormEncType;
} & ({
formData: FormData;
body?: undefined;
} | {
formData?: undefined;
body: any;
});
/**
* Options for a navigate() call for a normal (non-submission) navigation
*/
type LinkNavigateOptions = BaseNavigateOptions;
/**
* Options for a navigate() call for a submission navigation
*/
type SubmissionNavigateOptions = BaseNavigateOptions & BaseSubmissionOptions;
/**
* Options to pass to navigate() for a navigation
*/
type RouterNavigateOptions = LinkNavigateOptions | SubmissionNavigateOptions;
/**
* Options for a fetch() load
*/
type LoadFetchOptions = BaseNavigateOrFetchOptions;
/**
* Options for a fetch() submission
*/
type SubmitFetchOptions = BaseNavigateOrFetchOptions & BaseSubmissionOptions;
/**
* Options to pass to fetch()
*/
type RouterFetchOptions = LoadFetchOptions | SubmitFetchOptions;
/**
* Potential states for state.navigation
*/
type NavigationStates = {
Idle: {
state: "idle";
location: undefined;
matches: undefined;
historyAction: undefined;
formMethod: undefined;
formAction: undefined;
formEncType: undefined;
formData: undefined;
json: undefined;
text: undefined;
};
Loading: {
state: "loading";
location: Location;
matches: DataRouteMatch[];
historyAction: Action;
formMethod: Submission["formMethod"] | undefined;
formAction: Submission["formAction"] | undefined;
formEncType: Submission["formEncType"] | undefined;
formData: Submission["formData"] | undefined;
json: Submission["json"] | undefined;
text: Submission["text"] | undefined;
};
Submitting: {
state: "submitting";
location: Location;
matches: DataRouteMatch[];
historyAction: Action;
formMethod: Submission["formMethod"];
formAction: Submission["formAction"];
formEncType: Submission["formEncType"];
formData: Submission["formData"];
json: Submission["json"];
text: Submission["text"];
};
};
type Navigation = NavigationStates[keyof NavigationStates];
type RevalidationState = "idle" | "loading";
/**
* Potential states for fetchers
*/
type FetcherStates<TData = any> = {
/**
* The fetcher is not calling a loader or action
*
* ```tsx
* fetcher.state === "idle"
* ```
*/
Idle: {
state: "idle";
formMethod: undefined;
formAction: undefined;
formEncType: undefined;
text: undefined;
formData: undefined;
json: undefined;
/**
* If the fetcher has never been called, this will be undefined.
*/
data: TData | undefined;
};
/**
* The fetcher is loading data from a {@link LoaderFunction | loader} from a
* call to {@link FetcherWithComponents.load | `fetcher.load`}.
*
* ```tsx
* // somewhere
* <button onClick={() => fetcher.load("/some/route") }>Load</button>
*
* // the state will update
* fetcher.state === "loading"
* ```
*/
Loading: {
state: "loading";
formMethod: Submission["formMethod"] | undefined;
formAction: Submission["formAction"] | undefined;
formEncType: Submission["formEncType"] | undefined;
text: Submission["text"] | undefined;
formData: Submission["formData"] | undefined;
json: Submission["json"] | undefined;
data: TData | undefined;
};
/**
The fetcher is submitting to a {@link LoaderFunction} (GET) or {@link ActionFunction} (POST) from a {@link FetcherWithComponents.Form | `fetcher.Form`} or {@link FetcherWithComponents.submit | `fetcher.submit`}.
```tsx
// somewhere
<input
onChange={e => {
fetcher.submit(event.currentTarget.form, { method: "post" });
}}
/>
// the state will update
fetcher.state === "submitting"
// and formData will be available
fetcher.formData
```
*/
Submitting: {
state: "submitting";
formMethod: Submission["formMethod"];
formAction: Submission["formAction"];
formEncType: Submission["formEncType"];
text: Submission["text"];
formData: Submission["formData"];
json: Submission["json"];
data: TData | undefined;
};
};
type Fetcher<TData = any> = FetcherStates<TData>[keyof FetcherStates<TData>];
interface BlockerBlocked {
state: "blocked";
reset: () => void;
proceed: () => void;
location: Location;
}
interface BlockerUnblocked {
state: "unblocked";
reset: undefined;
proceed: undefined;
location: undefined;
}
interface BlockerProceeding {
state: "proceeding";
reset: undefined;
proceed: undefined;
location: Location;
}
type Blocker = BlockerUnblocked | BlockerBlocked | BlockerProceeding;
type BlockerFunction = (args: {
currentLocation: Location;
nextLocation: Location;
historyAction: Action;
}) => boolean;
declare const IDLE_NAVIGATION: NavigationStates["Idle"];
declare const IDLE_FETCHER: FetcherStates["Idle"];
declare const IDLE_BLOCKER: BlockerUnblocked;
/**
* Create a router and listen to history POP navigations
*/
declare function createRouter(init: RouterInit): Router;
interface CreateStaticHandlerOptions {
basename?: string;
mapRouteProperties?: MapRoutePropertiesFunction;
instrumentations?: Pick<ServerInstrumentation, "route">[];
future?: Partial<FutureConfig>;
}
/**
* Create a static handler to perform server-side data loading
*
* @example
* export async function handleRequest(request: Request) {
* let { query, dataRoutes } = createStaticHandler(routes);
* let context = await query(request);
*
* if (context instanceof Response) {
* return context;
* }
*
* let router = createStaticRouter(dataRoutes, context);
* return new Response(
* ReactDOMServer.renderToString(<StaticRouterProvider ... />),
* { headers: { "Content-Type": "text/html" } }
* );
* }
*
* @public
* @category Data Routers
* @mode data
* @param routes The {@link RouteObject | route objects} to create a static
* handler for
* @param opts Options
* @param opts.basename The base URL for the static handler (default: `/`)
* @param opts.future Future flags for the static handler
* @returns A static handler that can be used to query data for the provided
* routes
*/
declare function createStaticHandler(routes: RouteObject[], opts?: CreateStaticHandlerOptions): StaticHandler;
//#endregion
export { Blocker, BlockerFunction, Fetcher, FutureConfig, GetScrollPositionFunction, GetScrollRestorationKeyFunction, HydrationState, IDLE_BLOCKER, IDLE_FETCHER, IDLE_NAVIGATION, Navigation, NavigationStates, RelativeRoutingType, RevalidationState, Router, RouterFetchOptions, RouterInit, RouterNavigateOptions, RouterState, RouterSubscriber, StaticHandler, StaticHandlerContext, createRouter, createStaticHandler };
File diff suppressed because it is too large Load Diff
+18
View File
@@ -0,0 +1,18 @@
/**
* react-router v8.3.0
*
* 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/url.ts
const ABSOLUTE_URL_REGEX = /^(?:[a-z][a-z0-9+.-]*:|[\\/]{2})/i;
const PROTOCOL_RELATIVE_URL_REGEX = /^[\\/]{2}/;
function normalizeProtocolRelativeUrl(url, protocol) {
return protocol + url.replace(/\\/g, "/");
}
//#endregion
export { ABSOLUTE_URL_REGEX, PROTOCOL_RELATIVE_URL_REGEX, normalizeProtocolRelativeUrl };
@@ -0,0 +1,960 @@
import { Location, Path, To } from "./history.js";
import * as React$1 from "react";
//#region lib/router/utils.d.ts
type MaybePromise<T> = T | Promise<T>;
/**
* Map of routeId -> data returned from a loader/action/error
*/
interface RouteData {
[routeId: string]: any;
}
type LowerCaseFormMethod = "get" | "post" | "put" | "patch" | "delete";
type UpperCaseFormMethod = Uppercase<LowerCaseFormMethod>;
/**
* Users can specify either lowercase or uppercase form methods on `<Form>`,
* useSubmit(), `<fetcher.Form>`, etc.
*/
type HTMLFormMethod = LowerCaseFormMethod | UpperCaseFormMethod;
/**
* Active navigation/fetcher form methods are exposed in uppercase on the
* RouterState. This is to align with the normalization done via fetch().
*/
type FormMethod = UpperCaseFormMethod;
type FormEncType = "application/x-www-form-urlencoded" | "multipart/form-data" | "application/json" | "text/plain";
type JsonObject = { [Key in string]: JsonValue } & { [Key in string]?: JsonValue | undefined };
type JsonArray = JsonValue[] | readonly JsonValue[];
type JsonPrimitive = string | number | boolean | null;
type JsonValue = JsonPrimitive | JsonObject | JsonArray;
/**
* @private
* Internal interface to pass around for action submissions, not intended for
* external consumption
*/
type Submission = {
formMethod: FormMethod;
formAction: string;
formEncType: FormEncType;
formData: FormData;
json: undefined;
text: undefined;
} | {
formMethod: FormMethod;
formAction: string;
formEncType: FormEncType;
formData: undefined;
json: JsonValue;
text: undefined;
} | {
formMethod: FormMethod;
formAction: string;
formEncType: FormEncType;
formData: undefined;
json: undefined;
text: string;
};
/**
* A context instance used as the key for the `get`/`set` methods of a
* {@link RouterContextProvider}. Accepts an optional default
* value to be returned if no value has been set.
*/
interface RouterContext<T = unknown> {
defaultValue?: T;
}
/**
* Creates a type-safe {@link RouterContext} object that can be used to
* store and retrieve arbitrary values in [`action`](../../start/framework/route-module#action)s,
* [`loader`](../../start/framework/route-module#loader)s, and [middleware](../../how-to/middleware).
* Similar to React's [`createContext`](https://react.dev/reference/react/createContext),
* but specifically designed for React Router's request/response lifecycle.
*
* If a `defaultValue` is provided, it will be returned from `context.get()`
* when no value has been set for the context. Otherwise, reading this context
* when no value has been set will throw an error.
*
* ```tsx filename=app/context.ts
* import { createContext } from "react-router";
*
* // Create a context for user data
* export const userContext =
* createContext<User | null>(null);
* ```
*
* ```tsx filename=app/middleware/auth.ts
* import { getUserFromSession } from "~/auth.server";
* import { userContext } from "~/context";
*
* export const authMiddleware = async ({
* context,
* request,
* }) => {
* const user = await getUserFromSession(request);
* context.set(userContext, user);
* };
* ```
*
* ```tsx filename=app/routes/profile.tsx
* import { userContext } from "~/context";
*
* export async function loader({
* context,
* }: Route.LoaderArgs) {
* const user = context.get(userContext);
*
* if (!user) {
* throw new Response("Unauthorized", { status: 401 });
* }
*
* return { user };
* }
* ```
*
* @public
* @category Utils
* @mode framework
* @mode data
* @param defaultValue An optional default value for the context. This value
* will be returned if no value has been set for this context.
* @returns A {@link RouterContext} object that can be used with
* `context.get()` and `context.set()` in [`action`](../../start/framework/route-module#action)s,
* [`loader`](../../start/framework/route-module#loader)s, and [middleware](../../how-to/middleware).
*/
declare function createContext<T>(defaultValue?: T): RouterContext<T>;
/**
* Provides methods for writing/reading values in application context in a
* type-safe way. Primarily for usage with [middleware](../../how-to/middleware).
*
* @example
* import {
* createContext,
* RouterContextProvider
* } from "react-router";
*
* const userContext = createContext<User | null>(null);
* const contextProvider = new RouterContextProvider();
* contextProvider.set(userContext, getUser());
* // ^ Type-safe
* const user = contextProvider.get(userContext);
* // ^ User
*
* @public
* @category Utils
* @mode framework
* @mode data
*/
declare class RouterContextProvider {
#private;
/**
* Create a new `RouterContextProvider` instance
* @param init An optional initial context map to populate the provider with
*/
constructor(init?: Map<RouterContext, unknown>);
/**
* Access a value from the context. If no value has been set for the context,
* it will return the context's `defaultValue` if provided, or throw an error
* if no `defaultValue` was set.
* @param context The context to get the value for
* @returns The value for the context, or the context's `defaultValue` if no
* value was set
*/
get<T>(context: RouterContext<T>): T;
/**
* Set a value for the context. If the context already has a value set, this
* will overwrite it.
*
* @param context The context to set the value for
* @param value The value to set for the context
* @returns {void}
*/
set<C extends RouterContext>(context: C, value: C extends RouterContext<infer T> ? T : never): void;
}
type DefaultContext = Readonly<RouterContextProvider>;
/**
* @private
* Arguments passed to route loader/action functions. Same for now but we keep
* this as a private implementation detail in case they diverge in the future.
*/
interface DataFunctionArgs<Context> {
/** A {@link https://developer.mozilla.org/en-US/docs/Web/API/Request Fetch Request instance} which you can use to read headers (like cookies, and {@link https://developer.mozilla.org/en-US/docs/Web/API/URLSearchParams URLSearchParams} from the request. */
request: Request;
/**
* A URL instance representing the application location being navigated to or
* fetched.
*
* In Framework mode, this is a normalized URL with React-Router-specific
* implementation details removed (`.data` suffixes, `index`/`_routes` search
* params). For the raw incoming URL, use `request.url`.
*/
url: URL;
/**
* Matched un-interpolated route pattern for the current path (i.e., /blog/:slug).
* Mostly useful as a identifier to aggregate on for logging/tracing/etc.
*/
pattern: string;
/**
* {@link https://reactrouter.com/start/framework/routing#dynamic-segments Dynamic route params} for the current route.
* @example
* // app/routes.ts
* route("teams/:teamId", "./team.tsx"),
*
* // app/team.tsx
* export function loader({
* params,
* }: Route.LoaderArgs) {
* params.teamId;
* // ^ string
* }
*/
params: Params;
/**
* This is the context passed in to your server adapter's getLoadContext() function.
* It's a way to bridge the gap between the adapter's request/response API with your React Router app.
* It is only applicable if you are using a custom server adapter.
*/
context: Context;
}
/**
* Route middleware `next` function to call downstream handlers and then complete
* middlewares from the bottom-up
*/
interface MiddlewareNextFunction<Result = unknown> {
(): Promise<Result>;
}
/**
* Route middleware function signature. Receives the same "data" arguments as a
* `loader`/`action` (`request`, `params`, `context`) as the first parameter and
* a `next` function as the second parameter which will call downstream handlers
* and then complete middlewares from the bottom-up
*/
type MiddlewareFunction<Result = unknown> = (args: DataFunctionArgs<Readonly<RouterContextProvider>>, next: MiddlewareNextFunction<Result>) => MaybePromise<Result | void>;
/**
* Arguments passed to loader functions
*/
interface LoaderFunctionArgs<Context = DefaultContext> extends DataFunctionArgs<Context> {}
/**
* Arguments passed to action functions
*/
interface ActionFunctionArgs<Context = DefaultContext> extends DataFunctionArgs<Context> {}
/**
* Loaders and actions can return anything
*/
type DataFunctionValue = unknown;
type DataFunctionReturnValue = MaybePromise<DataFunctionValue>;
/**
* Route loader function signature
*/
type LoaderFunction<Context = DefaultContext> = {
(args: LoaderFunctionArgs<Context>, handlerCtx?: unknown): DataFunctionReturnValue;
} & {
hydrate?: boolean;
};
/**
* Route action function signature
*/
interface ActionFunction<Context = DefaultContext> {
(args: ActionFunctionArgs<Context>, handlerCtx?: unknown): DataFunctionReturnValue;
}
/**
* Arguments passed to shouldRevalidate function
*/
interface ShouldRevalidateFunctionArgs {
/** This is the url the navigation started from. You can compare it with `nextUrl` to decide if you need to revalidate this route's data. */
currentUrl: URL;
/** These are the {@link https://reactrouter.com/start/framework/routing#dynamic-segments dynamic route params} from the URL that can be compared to the `nextParams` to decide if you need to reload or not. Perhaps you're using only a partial piece of the param for data loading, you don't need to revalidate if a superfluous part of the param changed. */
currentParams: DataRouteMatch["params"];
/** In the case of navigation, this the URL the user is requesting. Some revalidations are not navigation, so it will simply be the same as currentUrl. */
nextUrl: URL;
/** In the case of navigation, these are the {@link https://reactrouter.com/start/framework/routing#dynamic-segments dynamic route params} from the next location the user is requesting. Some revalidations are not navigation, so it will simply be the same as currentParams. */
nextParams: DataRouteMatch["params"];
/** The method (probably `"GET"` or `"POST"`) used in the form submission that triggered the revalidation. */
formMethod?: Submission["formMethod"];
/** The form action (`<Form action="/somewhere">`) that triggered the revalidation. */
formAction?: Submission["formAction"];
/** The form encType (`<Form encType="application/x-www-form-urlencoded">) used in the form submission that triggered the revalidation*/
formEncType?: Submission["formEncType"];
/** The form submission data when the form's encType is `text/plain` */
text?: Submission["text"];
/** The form submission data when the form's encType is `application/x-www-form-urlencoded` or `multipart/form-data` */
formData?: Submission["formData"];
/** The form submission data when the form's encType is `application/json` */
json?: Submission["json"];
/** The status code of the action response */
actionStatus?: number;
/**
* When a submission causes the revalidation this will be the result of the action—either action data or an error if the action failed. It's common to include some information in the action result to instruct shouldRevalidate to revalidate or not.
*
* @example
* export async function action() {
* await saveSomeStuff();
* return { ok: true };
* }
*
* export function shouldRevalidate({
* actionResult,
* }) {
* if (actionResult?.ok) {
* return false;
* }
* return true;
* }
*/
actionResult?: any;
/**
* By default, React Router doesn't call every loader all the time. There are reliable optimizations it can make by default. For example, only loaders with changing params are called. Consider navigating from the following URL to the one below it:
*
* /projects/123/tasks/abc
* /projects/123/tasks/def
* React Router will only call the loader for tasks/def because the param for projects/123 didn't change.
*
* It's safest to always return defaultShouldRevalidate after you've done your specific optimizations that return false, otherwise your UI might get out of sync with your data on the server.
*/
defaultShouldRevalidate: boolean;
}
/**
* Route shouldRevalidate function signature. This runs after any submission
* (navigation or fetcher), so we flatten the navigation/fetcher submission
* onto the arguments. It shouldn't matter whether it came from a navigation
* or a fetcher, what really matters is the URLs and the formData since loaders
* have to re-run based on the data models that were potentially mutated.
*/
interface ShouldRevalidateFunction {
(args: ShouldRevalidateFunctionArgs): boolean;
}
interface DataStrategyMatch extends RouteMatch<string, DataRouteObject> {
/**
* @private
*/
_lazyPromises?: {
middleware: Promise<void> | undefined;
handler: Promise<void> | undefined;
route: Promise<void> | undefined;
};
/**
* @deprecated Deprecated in favor of `shouldCallHandler`
*
* A boolean value indicating whether this route handler should be called in
* this pass.
*
* The `matches` array always includes _all_ matched routes even when only
* _some_ route handlers need to be called so that things like middleware can
* be implemented.
*
* `shouldLoad` is usually only interesting if you are skipping the route
* handler entirely and implementing custom handler logic - since it lets you
* determine if that custom logic should run for this route or not.
*
* For example:
* - If you are on `/parent/child/a` and you navigate to `/parent/child/b` -
* you'll get an array of three matches (`[parent, child, b]`), but only `b`
* will have `shouldLoad=true` because the data for `parent` and `child` is
* already loaded
* - If you are on `/parent/child/a` and you submit to `a`'s [`action`](https://reactrouter.com/docs/start/data/route-object#action),
* then only `a` will have `shouldLoad=true` for the action execution of
* `dataStrategy`
* - After the [`action`](https://reactrouter.com/docs/start/data/route-object#action),
* `dataStrategy` will be called again for the [`loader`](https://reactrouter.com/docs/start/data/route-object#loader)
* revalidation, and all matches will have `shouldLoad=true` (assuming no
* custom `shouldRevalidate` implementations)
*/
shouldLoad: boolean;
/**
* Arguments passed to the `shouldRevalidate` function for this `loader` execution.
* Will be `null` if this is not a revalidating loader {@link DataStrategyMatch}.
*/
shouldRevalidateArgs: ShouldRevalidateFunctionArgs | null;
/**
* Determine if this route's handler should be called during this `dataStrategy`
* execution. Calling it with no arguments will leverage the default revalidation
* behavior. You can pass your own `defaultShouldRevalidate` value if you wish
* to change the default revalidation behavior with your `dataStrategy`.
*
* @param defaultShouldRevalidate `defaultShouldRevalidate` override value (optional)
*/
shouldCallHandler(defaultShouldRevalidate?: boolean): boolean;
/**
* An async function that will resolve any `route.lazy` implementations and
* execute the route's handler (if necessary), returning a {@link DataStrategyResult}
*
* - Calling `match.resolve` does not mean you're calling the
* [`action`](https://reactrouter.com/docs/start/data/route-object#action)/[`loader`](https://reactrouter.com/docs/start/data/route-object#loader)
* (the "handler") - `resolve` will only call the `handler` internally if
* needed _and_ if you don't pass your own `handlerOverride` function parameter
* - It is safe to call `match.resolve` for all matches, even if they have
* `shouldLoad=false`, and it will no-op if no loading is required
* - You should generally always call `match.resolve()` for `shouldLoad:true`
* routes to ensure that any `route.lazy` implementations are processed
* - See the examples below for how to implement custom handler execution via
* `match.resolve`
*/
resolve: (handlerOverride?: (handler: (ctx?: unknown) => DataFunctionReturnValue) => DataFunctionReturnValue) => Promise<DataStrategyResult>;
}
interface DataStrategyFunctionArgs<Context = DefaultContext> extends DataFunctionArgs<Context> {
/**
* Matches for this route extended with Data strategy APIs
*/
matches: DataStrategyMatch[];
runClientMiddleware: (cb: DataStrategyFunction<Context>) => Promise<Record<string, DataStrategyResult>>;
/**
* The key of the fetcher we are calling `dataStrategy` for, otherwise `null`
* for navigational executions
*/
fetcherKey: string | null;
}
/**
* Result from a loader or action called via dataStrategy
*/
interface DataStrategyResult {
type: "data" | "error";
result: unknown;
}
interface DataStrategyFunction<Context = DefaultContext> {
(args: DataStrategyFunctionArgs<Context>): Promise<Record<string, DataStrategyResult>>;
}
type PatchRoutesOnNavigationFunctionArgs = {
signal: AbortSignal;
path: string;
matches: RouteMatch[];
fetcherKey: string | undefined;
patch: (routeId: string | null, children: RouteObject[]) => void;
};
type PatchRoutesOnNavigationFunction = (opts: PatchRoutesOnNavigationFunctionArgs) => MaybePromise<void>;
/**
* Function provided to set route-specific properties from route objects
*/
interface MapRoutePropertiesFunction {
(route: DataRouteObject): Partial<DataRouteObject>;
}
/**
* Keys we cannot change from within a lazy object. We spread all other keys
* onto the route. Either they're meaningful to the router, or they'll get
* ignored.
*/
type UnsupportedLazyRouteObjectKey = "lazy" | "caseSensitive" | "path" | "id" | "index" | "children";
/**
* Keys we cannot change from within a lazy() function. We spread all other keys
* onto the route. Either they're meaningful to the router, or they'll get
* ignored.
*/
type UnsupportedLazyRouteFunctionKey = UnsupportedLazyRouteObjectKey | "middleware";
/**
* lazy object to load route properties, which can add non-matching
* related properties to a route
*/
type LazyRouteObject<R extends RouteObject> = { [K in keyof R as K extends UnsupportedLazyRouteObjectKey ? never : K]?: () => Promise<R[K] | null | undefined> };
/**
* lazy() function to load a route definition, which can add non-matching
* related properties to a route
*/
interface LazyRouteFunction<R extends RouteObject> {
(): Promise<Omit<R, UnsupportedLazyRouteFunctionKey> & Partial<Record<UnsupportedLazyRouteFunctionKey, never>>>;
}
type LazyRouteDefinition<R extends RouteObject> = LazyRouteObject<R> | LazyRouteFunction<R>;
/**
* Base RouteObject with common props shared by all types of routes
* @internal
*/
type BaseRouteObject = {
/**
* Whether the path should be case-sensitive. Defaults to `false`.
*/
caseSensitive?: boolean;
/**
* The path pattern to match. If unspecified or empty, then this becomes a
* layout route.
*/
path?: string;
/**
* The unique identifier for this route (for use with {@link DataRouter}s)
*/
id?: string;
/**
* The route middleware.
* See [`middleware`](../../start/data/route-object#middleware).
*/
middleware?: MiddlewareFunction[];
/**
* The route loader.
* See [`loader`](../../start/data/route-object#loader).
*/
loader?: LoaderFunction | boolean;
/**
* The route action.
* See [`action`](../../start/data/route-object#action).
*/
action?: ActionFunction | boolean;
/**
* The route shouldRevalidate function.
* See [`shouldRevalidate`](../../start/data/route-object#shouldRevalidate).
*/
shouldRevalidate?: ShouldRevalidateFunction;
/**
* The route handle.
*/
handle?: any;
/**
* A function that returns a promise that resolves to the route object.
* Used for code-splitting routes.
* See [`lazy`](../../start/data/route-object#lazy).
*/
lazy?: LazyRouteDefinition<BaseRouteObject>;
/**
* The React Component to render when this route matches.
* Mutually exclusive with `element`.
*/
Component?: React$1.ComponentType | null;
/**
* The React element to render when this Route matches.
* Mutually exclusive with `Component`.
*/
element?: React$1.ReactNode | null;
/**
* The React Component to render at this route if an error occurs.
* Mutually exclusive with `errorElement`.
*/
ErrorBoundary?: React$1.ComponentType | null;
/**
* The React element to render at this route if an error occurs.
* Mutually exclusive with `ErrorBoundary`.
*/
errorElement?: React$1.ReactNode | null;
/**
* The React Component to render while this router is loading data.
* Mutually exclusive with `hydrateFallbackElement`.
*/
HydrateFallback?: React$1.ComponentType | null;
/**
* The React element to render while this router is loading data.
* Mutually exclusive with `HydrateFallback`.
*/
hydrateFallbackElement?: React$1.ReactNode | null;
};
/**
* Index routes must not have children
*/
type IndexRouteObject = BaseRouteObject & {
/**
* Child Route objects - not valid on index routes.
*/
children?: undefined;
/**
* Whether this is an index route.
*/
index: true;
};
/**
* Non-index routes may have children, but cannot have `index` set to `true`.
*/
type NonIndexRouteObject = BaseRouteObject & {
/**
* Child Route objects.
*/
children?: RouteObject[];
/**
* Whether this is an index route - must be `false` or undefined on non-index routes.
*/
index?: false;
};
/**
* A route object represents a logical route, with (optionally) its child
* routes organized in a tree-like structure.
*/
type RouteObject = IndexRouteObject | NonIndexRouteObject;
type DataIndexRouteObject = IndexRouteObject & {
id: string;
};
type DataNonIndexRouteObject = NonIndexRouteObject & {
children?: DataRouteObject[];
id: string;
};
/**
* A data route object, which is just a RouteObject with a required unique ID
*/
type DataRouteObject = DataIndexRouteObject | DataNonIndexRouteObject;
type RouteManifest<R = DataRouteObject> = Record<string, R | undefined>;
type Regex_az = "a" | "b" | "c" | "d" | "e" | "f" | "g" | "h" | "i" | "j" | "k" | "l" | "m" | "n" | "o" | "p" | "q" | "r" | "s" | "t" | "u" | "v" | "w" | "x" | "y" | "z";
type Regex_AZ = Uppercase<Regex_az>;
type Regex_09 = "0" | "1" | "2" | "3" | "4" | "5" | "6" | "7" | "8" | "9";
type Regex_w = Regex_az | Regex_AZ | Regex_09 | "_";
/** Emulates Regex `+` operator */
type RegexMatchPlus<char extends string, T extends string> = _RegexMatchPlus<char, T> extends infer result extends string ? result extends '' ? never : result : never;
type _RegexMatchPlus<char extends string, T extends string> = T extends `${infer head extends char}${infer rest}` ? `${head}${_RegexMatchPlus<char, rest>}` : '';
type ParamNameChar = Regex_w | "-";
type Simplify<T> = { [K in keyof T]: T[K] } & {};
type GeneratePathParams<path extends string> = Simplify<ParseParams<path> & { [key in string]: string | null | undefined }>;
type ParseParams<path extends string> = path extends '*' ? {
'*': string;
} : path extends `${infer rest}/*` ? {
'*': string;
} & ParseParams<rest> : _ParseParams<path>;
type _ParseParams<path extends string> = path extends `${infer left}/${infer right}` ? _ParseParams<left> & _ParseParams<right> : path extends `:${infer param}?${string}` ? { [key in RegexMatchPlus<ParamNameChar, param>]?: string | null | undefined } : path extends `:${infer param}` ? { [key in RegexMatchPlus<ParamNameChar, param>]: string } : {};
type PathParam<path extends string> = (keyof ParseParams<path>) & string;
type ParamParseKey<Segment extends string> = [PathParam<Segment>] extends [never] ? string : PathParam<Segment>;
/**
* The parameters that were parsed from the URL path.
*/
type Params<Key extends string = string> = { readonly [key in Key]: string | undefined };
/**
* A RouteMatch contains info about how a route matched a URL.
*/
interface RouteMatch<ParamKey extends string = string, RouteObjectType extends RouteObject = RouteObject> {
/**
* The names and values of dynamic parameters in the URL.
*/
params: Params<ParamKey>;
/**
* The portion of the URL pathname that was matched.
*/
pathname: string;
/**
* The portion of the URL pathname that was matched before child routes.
*/
pathnameBase: string;
/**
* The route object that was used to match.
*/
route: RouteObjectType;
}
interface DataRouteMatch extends RouteMatch<string, DataRouteObject> {}
declare function defaultMapRouteProperties(route: DataRouteObject): Partial<DataRouteObject>;
/**
* Matches the given routes to a location and returns the match data.
*
* @example
* import { matchRoutes } from "react-router";
*
* let routes = [{
* path: "/",
* Component: Root,
* children: [{
* path: "dashboard",
* Component: Dashboard,
* }]
* }];
*
* matchRoutes(routes, "/dashboard"); // [rootMatch, dashboardMatch]
*
* @public
* @category Utils
* @param routes The array of route objects to match against.
* @param locationArg The location to match against, either a string path or a
* partial {@link Location} object
* @param basename Optional base path to strip from the location before matching.
* Defaults to `/`.
* @returns An array of matched routes, or `null` if no matches were found.
*/
declare function matchRoutes<RouteObjectType extends RouteObject = RouteObject>(routes: RouteObjectType[], locationArg: Partial<Location> | string, basename?: string): RouteMatch<string, RouteObjectType>[] | null;
interface UIMatch<Data = unknown, Handle = unknown> {
id: string;
pathname: string;
/**
* {@link https://reactrouter.com/start/framework/routing#dynamic-segments Dynamic route params} for the matched route.
*/
params: RouteMatch["params"];
/**
* The return value from the matched route's loader or clientLoader. This might
* be `undefined` if this route's `loader` (or a deeper route's `loader`) threw
* an error and we're currently displaying an `ErrorBoundary`.
*/
loaderData: Data | undefined;
/**
* The {@link https://reactrouter.com/start/framework/route-module#handle handle object}
* exported from the matched route module
*/
handle: Handle;
}
interface RouteMeta<RouteObjectType extends RouteObject = RouteObject> {
relativePath: string;
caseSensitive: boolean;
childrenIndex: number;
route: RouteObjectType;
matcher?: RegExp;
compiledParams?: CompiledPathParam[];
}
/**
* @private
* PRIVATE - DO NOT USE
*
* A "branch" of routes that match a given route pattern.
* This is an internal interface not intended for direct external usage.
*/
interface RouteBranch<RouteObjectType extends RouteObject = RouteObject> {
path: string;
score: number;
routesMeta: RouteMeta<RouteObjectType>[];
}
/**
* Returns a path with params interpolated.
*
* Param values are percent-encoded for use in a path segment: characters that
* would change the URL structure (`/`, `?`, `#`, `%`, whitespace, non-ASCII)
* are escaped, while characters that RFC 3986 allows literally in a path
* segment (`$ & + , ; = : @`) are kept as-is. Note this differs from query-string
* encoding (`encodeURIComponent`/`URLSearchParams`), where those characters are
* delimiters and must be escaped. Splat (`*`) values are encoded per segment,
* preserving `/` separators.
*
* See [RFC 3986 §3.3](https://datatracker.ietf.org/doc/html/rfc3986#section-3.3)
*
* @example
* import { generatePath } from "react-router";
*
* generatePath("/users/:id", { id: "123" }); // "/users/123"
* generatePath("/files/:name", { name: "a b" }); // "/files/a%20b"
* generatePath("/releases/:v", { v: "1.0.0+1" }); // "/releases/1.0.0+1"
*
* @public
* @category Utils
* @param originalPath The original path to generate.
* @param params The parameters to interpolate into the path.
* @returns The generated path with parameters interpolated.
*/
declare function generatePath<Path extends string>(originalPath: Path, params?: GeneratePathParams<Path>): string;
/**
* Used to match on some portion of a URL pathname.
*/
interface PathPattern<Path extends string = string> {
/**
* A string to match against a URL pathname. May contain `:id`-style segments
* to indicate placeholders for dynamic parameters. It May also end with `/*`
* to indicate matching the rest of the URL pathname.
*/
path: Path;
/**
* Should be `true` if the static portions of the `path` should be matched in
* the same case.
*/
caseSensitive?: boolean;
/**
* Should be `true` if this pattern should match the entire URL pathname.
*/
end?: boolean;
}
/**
* Contains info about how a {@link PathPattern} matched on a URL pathname.
*/
interface PathMatch<ParamKey extends string = string> {
/**
* The names and values of dynamic parameters in the URL.
*/
params: Params<ParamKey>;
/**
* The portion of the URL pathname that was matched.
*/
pathname: string;
/**
* The portion of the URL pathname that was matched before child routes.
*/
pathnameBase: string;
/**
* The pattern that was used to match.
*/
pattern: PathPattern;
}
/**
* Performs pattern matching on a URL pathname and returns information about
* the match.
*
* @public
* @category Utils
* @param pattern The pattern to match against the URL pathname. This can be a
* string or a {@link PathPattern} object. If a string is provided, it will be
* treated as a pattern with `caseSensitive` set to `false` and `end` set to
* `true`.
* @param pathname The URL pathname to match against the pattern.
* @returns A path match object if the pattern matches the pathname,
* or `null` if it does not match.
*/
declare function matchPath<Path extends string>(pattern: PathPattern<Path> | Path, pathname: string): PathMatch<ParamParseKey<Path>> | null;
type CompiledPathParam = {
paramName: string;
isOptional?: boolean;
};
/**
* Returns a resolved {@link Path} object relative to the given pathname.
*
* @public
* @category Utils
* @param to The path to resolve, either a string or a partial {@link Path}
* object.
* @param fromPathname The pathname to resolve the path from. Defaults to `/`.
* @returns A {@link Path} object with the resolved pathname, search, and hash.
*/
declare function resolvePath(to: To, fromPathname?: string): Path;
declare class DataWithResponseInit<D> {
type: string;
data: D;
init: ResponseInit | null;
constructor(data: D, init?: ResponseInit);
}
/**
* Create "responses" that contain `headers`/`status` without forcing
* serialization into an actual [`Response`](https://developer.mozilla.org/en-US/docs/Web/API/Response)
*
* @example
* import { data } from "react-router";
*
* export async function action({ request }: Route.ActionArgs) {
* let formData = await request.formData();
* let item = await createItem(formData);
* return data(item, {
* headers: { "X-Custom-Header": "value" }
* status: 201,
* });
* }
*
* @public
* @category Utils
* @mode framework
* @mode data
* @param data The data to be included in the response.
* @param init The status code or a `ResponseInit` object to be included in the
* response.
* @returns A {@link DataWithResponseInit} instance containing the data and
* response init.
*/
declare function data<D>(data: D, init?: number | ResponseInit): DataWithResponseInit<D>;
interface TrackedPromise extends Promise<any> {
_tracked?: boolean;
_data?: any;
_error?: any;
}
type RedirectFunction = (url: string, init?: number | ResponseInit) => Response;
/**
* A redirect [`Response`](https://developer.mozilla.org/en-US/docs/Web/API/Response).
* Sets the status code and the [`Location`](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Location)
* header. Defaults to [`302 Found`](https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/302).
*
* This utility accepts absolute URLs and can navigate to external domains, so
* the application should validate any user-supplied inputs to redirects.
*
* @example
* import { redirect } from "react-router";
*
* export async function loader({ request }: Route.LoaderArgs) {
* if (!isLoggedIn(request))
* throw redirect("/login");
* }
*
* // ...
* }
*
* @public
* @category Utils
* @mode framework
* @mode data
* @param url The URL to redirect to.
* @param init The status code or a `ResponseInit` object to be included in the
* response.
* @returns A [`Response`](https://developer.mozilla.org/en-US/docs/Web/API/Response)
* object with the redirect status and [`Location`](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Location)
* header.
*/
declare const redirect: RedirectFunction;
/**
* A redirect [`Response`](https://developer.mozilla.org/en-US/docs/Web/API/Response)
* that will force a document reload to the new location. Sets the status code
* and the [`Location`](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Location)
* header. Defaults to [`302 Found`](https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/302).
*
* This utility accepts absolute URLs and can navigate to external domains, so
* the application should validate any user-supplied inputs to redirects.
*
* ```tsx filename=routes/logout.tsx
* import { redirectDocument } from "react-router";
*
* import { destroySession } from "../sessions.server";
*
* export async function action({ request }: Route.ActionArgs) {
* let session = await getSession(request.headers.get("Cookie"));
* return redirectDocument("/", {
* headers: { "Set-Cookie": await destroySession(session) }
* });
* }
* ```
*
* @public
* @category Utils
* @mode framework
* @mode data
* @param url The URL to redirect to.
* @param init The status code or a `ResponseInit` object to be included in the
* response.
* @returns A [`Response`](https://developer.mozilla.org/en-US/docs/Web/API/Response)
* object with the redirect status and [`Location`](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Location)
* header.
*/
declare const redirectDocument: RedirectFunction;
/**
* A redirect [`Response`](https://developer.mozilla.org/en-US/docs/Web/API/Response)
* that will perform a [`history.replaceState`](https://developer.mozilla.org/en-US/docs/Web/API/History/replaceState)
* instead of a [`history.pushState`](https://developer.mozilla.org/en-US/docs/Web/API/History/pushState)
* for client-side navigation redirects. Sets the status code and the [`Location`](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Location)
* header. Defaults to [`302 Found`](https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/302).
*
* @example
* import { replace } from "react-router";
*
* export async function loader() {
* return replace("/new-location");
* }
*
* @public
* @category Utils
* @mode framework
* @mode data
* @param url The URL to redirect to.
* @param init The status code or a `ResponseInit` object to be included in the
* response.
* @returns A [`Response`](https://developer.mozilla.org/en-US/docs/Web/API/Response)
* object with the redirect status and [`Location`](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Location)
* header.
*/
declare const replace: RedirectFunction;
type ErrorResponse = {
status: number;
statusText: string;
data: any;
};
declare class ErrorResponseImpl implements ErrorResponse {
status: number;
statusText: string;
data: any;
private error?;
private internal;
constructor(status: number, statusText: string | undefined, data: any, internal?: boolean);
}
/**
* Check if the given error is an {@link ErrorResponse} generated from a 4xx/5xx
* [`Response`](https://developer.mozilla.org/en-US/docs/Web/API/Response)
* thrown from an [`action`](../../start/framework/route-module#action) or
* [`loader`](../../start/framework/route-module#loader) function.
*
* @example
* import { isRouteErrorResponse } from "react-router";
*
* export function ErrorBoundary({ error }: Route.ErrorBoundaryProps) {
* if (isRouteErrorResponse(error)) {
* return (
* <>
* <p>Error: `${error.status}: ${error.statusText}`</p>
* <p>{error.data}</p>
* </>
* );
* }
*
* return (
* <p>Error: {error instanceof Error ? error.message : "Unknown Error"}</p>
* );
* }
*
* @public
* @category Utils
* @mode framework
* @mode data
* @param error The error to check.
* @returns `true` if the error is an {@link ErrorResponse}, `false` otherwise.
*/
declare function isRouteErrorResponse(error: any): error is ErrorResponse;
//#endregion
export { ActionFunction, ActionFunctionArgs, BaseRouteObject, DataRouteMatch, DataRouteObject, DataStrategyFunction, DataStrategyFunctionArgs, DataStrategyMatch, DataStrategyResult, DataWithResponseInit, ErrorResponse, ErrorResponseImpl, FormEncType, FormMethod, HTMLFormMethod, IndexRouteObject, LazyRouteFunction, LoaderFunction, LoaderFunctionArgs, MapRoutePropertiesFunction, MaybePromise, MiddlewareFunction, MiddlewareNextFunction, NonIndexRouteObject, ParamParseKey, Params, PatchRoutesOnNavigationFunction, PatchRoutesOnNavigationFunctionArgs, PathMatch, PathParam, PathPattern, RedirectFunction, RouteBranch, RouteData, RouteManifest, RouteMatch, RouteObject, RouterContext, RouterContextProvider, ShouldRevalidateFunction, ShouldRevalidateFunctionArgs, Submission, TrackedPromise, UIMatch, createContext, data, defaultMapRouteProperties, generatePath, isRouteErrorResponse, matchPath, matchRoutes, redirect, redirectDocument, replace, resolvePath };
+881
View File
@@ -0,0 +1,881 @@
/**
* react-router v8.3.0
*
* 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, PROTOCOL_RELATIVE_URL_REGEX, normalizeProtocolRelativeUrl } from "./url.js";
import { invariant, parsePath, warning } from "./history.js";
import * as React$1 from "react";
//#region lib/router/utils.ts
/**
* Creates a type-safe {@link RouterContext} object that can be used to
* store and retrieve arbitrary values in [`action`](../../start/framework/route-module#action)s,
* [`loader`](../../start/framework/route-module#loader)s, and [middleware](../../how-to/middleware).
* Similar to React's [`createContext`](https://react.dev/reference/react/createContext),
* but specifically designed for React Router's request/response lifecycle.
*
* If a `defaultValue` is provided, it will be returned from `context.get()`
* when no value has been set for the context. Otherwise, reading this context
* when no value has been set will throw an error.
*
* ```tsx filename=app/context.ts
* import { createContext } from "react-router";
*
* // Create a context for user data
* export const userContext =
* createContext<User | null>(null);
* ```
*
* ```tsx filename=app/middleware/auth.ts
* import { getUserFromSession } from "~/auth.server";
* import { userContext } from "~/context";
*
* export const authMiddleware = async ({
* context,
* request,
* }) => {
* const user = await getUserFromSession(request);
* context.set(userContext, user);
* };
* ```
*
* ```tsx filename=app/routes/profile.tsx
* import { userContext } from "~/context";
*
* export async function loader({
* context,
* }: Route.LoaderArgs) {
* const user = context.get(userContext);
*
* if (!user) {
* throw new Response("Unauthorized", { status: 401 });
* }
*
* return { user };
* }
* ```
*
* @public
* @category Utils
* @mode framework
* @mode data
* @param defaultValue An optional default value for the context. This value
* will be returned if no value has been set for this context.
* @returns A {@link RouterContext} object that can be used with
* `context.get()` and `context.set()` in [`action`](../../start/framework/route-module#action)s,
* [`loader`](../../start/framework/route-module#loader)s, and [middleware](../../how-to/middleware).
*/
function createContext(defaultValue) {
return { defaultValue };
}
/**
* Provides methods for writing/reading values in application context in a
* type-safe way. Primarily for usage with [middleware](../../how-to/middleware).
*
* @example
* import {
* createContext,
* RouterContextProvider
* } from "react-router";
*
* const userContext = createContext<User | null>(null);
* const contextProvider = new RouterContextProvider();
* contextProvider.set(userContext, getUser());
* // ^ Type-safe
* const user = contextProvider.get(userContext);
* // ^ User
*
* @public
* @category Utils
* @mode framework
* @mode data
*/
var RouterContextProvider = class {
#map = /* @__PURE__ */ new Map();
/**
* Create a new `RouterContextProvider` instance
* @param init An optional initial context map to populate the provider with
*/
constructor(init) {
if (init) for (let [context, value] of init) this.set(context, value);
}
/**
* Access a value from the context. If no value has been set for the context,
* it will return the context's `defaultValue` if provided, or throw an error
* if no `defaultValue` was set.
* @param context The context to get the value for
* @returns The value for the context, or the context's `defaultValue` if no
* value was set
*/
get(context) {
if (this.#map.has(context)) return this.#map.get(context);
if (context.defaultValue !== void 0) return context.defaultValue;
throw new Error("No value found for context");
}
/**
* Set a value for the context. If the context already has a value set, this
* will overwrite it.
*
* @param context The context to set the value for
* @param value The value to set for the context
* @returns {void}
*/
set(context, value) {
this.#map.set(context, value);
}
};
const unsupportedLazyRouteObjectKeys = new Set([
"lazy",
"caseSensitive",
"path",
"id",
"index",
"children"
]);
function isUnsupportedLazyRouteObjectKey(key) {
return unsupportedLazyRouteObjectKeys.has(key);
}
const unsupportedLazyRouteFunctionKeys = new Set([
"lazy",
"caseSensitive",
"path",
"id",
"index",
"middleware",
"children"
]);
function isUnsupportedLazyRouteFunctionKey(key) {
return unsupportedLazyRouteFunctionKeys.has(key);
}
function isIndexRoute(route) {
return route.index === true;
}
function defaultMapRouteProperties(route) {
let updates = {};
if (route.Component) {
if (route.element) warning(false, "You should not include both `Component` and `element` on your route - `Component` will be used.");
Object.assign(updates, {
element: React$1.createElement(route.Component),
Component: void 0
});
}
if (route.HydrateFallback) {
if (route.hydrateFallbackElement) warning(false, "You should not include both `HydrateFallback` and `hydrateFallbackElement` on your route - `HydrateFallback` will be used.");
Object.assign(updates, {
hydrateFallbackElement: React$1.createElement(route.HydrateFallback),
HydrateFallback: void 0
});
}
if (route.ErrorBoundary) {
if (route.errorElement) warning(false, "You should not include both `ErrorBoundary` and `errorElement` on your route - `ErrorBoundary` will be used.");
Object.assign(updates, {
errorElement: React$1.createElement(route.ErrorBoundary),
ErrorBoundary: void 0
});
}
return updates;
}
function convertRoutesToDataRoutes(routes, mapRouteProperties = defaultMapRouteProperties, parentPath = [], manifest = {}, allowInPlaceMutations = false) {
return routes.map((route, index) => {
let treePath = [...parentPath, String(index)];
let id = typeof route.id === "string" ? route.id : treePath.join("-");
invariant(route.index !== true || !route.children, `Cannot specify children on an index route`);
invariant(allowInPlaceMutations || !manifest[id], `Found a route id collision on id "${id}". Route id's must be globally unique within Data Router usages`);
if (isIndexRoute(route)) {
let indexRoute = {
...route,
id
};
manifest[id] = mergeRouteUpdates(indexRoute, mapRouteProperties(indexRoute));
return indexRoute;
} else {
let pathOrLayoutRoute = {
...route,
id,
children: void 0
};
manifest[id] = mergeRouteUpdates(pathOrLayoutRoute, mapRouteProperties(pathOrLayoutRoute));
if (route.children) pathOrLayoutRoute.children = convertRoutesToDataRoutes(route.children, mapRouteProperties, treePath, manifest, allowInPlaceMutations);
return pathOrLayoutRoute;
}
});
}
function mergeRouteUpdates(route, updates) {
return Object.assign(route, {
...updates,
...typeof updates.lazy === "object" && updates.lazy != null ? { lazy: {
...route.lazy,
...updates.lazy
} } : {}
});
}
/**
* Matches the given routes to a location and returns the match data.
*
* @example
* import { matchRoutes } from "react-router";
*
* let routes = [{
* path: "/",
* Component: Root,
* children: [{
* path: "dashboard",
* Component: Dashboard,
* }]
* }];
*
* matchRoutes(routes, "/dashboard"); // [rootMatch, dashboardMatch]
*
* @public
* @category Utils
* @param routes The array of route objects to match against.
* @param locationArg The location to match against, either a string path or a
* partial {@link Location} object
* @param basename Optional base path to strip from the location before matching.
* Defaults to `/`.
* @returns An array of matched routes, or `null` if no matches were found.
*/
function matchRoutes(routes, locationArg, basename = "/") {
return matchRoutesImpl(routes, locationArg, basename, false);
}
function matchRoutesImpl(routes, locationArg, basename, allowPartial, precomputedBranches) {
let pathname = stripBasename((typeof locationArg === "string" ? parsePath(locationArg) : locationArg).pathname || "/", basename);
if (pathname == null) return null;
let branches = precomputedBranches ?? flattenAndRankRoutes(routes);
let matches = null;
let decoded = decodePath(pathname);
for (let i = 0; matches == null && i < branches.length; ++i) matches = matchRouteBranch(branches[i], decoded, allowPartial);
return matches;
}
function convertRouteMatchToUiMatch(match, loaderData) {
let { route, pathname, params } = match;
return {
id: route.id,
pathname,
params,
loaderData: loaderData[route.id],
handle: route.handle
};
}
function flattenAndRankRoutes(routes) {
let branches = flattenRoutes(routes);
rankRouteBranches(branches);
return branches;
}
function flattenRoutes(routes, branches = [], parentsMeta = [], parentPath = "", _hasParentOptionalSegments = false) {
let flattenRoute = (route, index, hasParentOptionalSegments = _hasParentOptionalSegments, relativePath) => {
let meta = {
relativePath: relativePath === void 0 ? route.path || "" : relativePath,
caseSensitive: route.caseSensitive === true,
childrenIndex: index,
route
};
if (meta.relativePath.startsWith("/")) {
if (!meta.relativePath.startsWith(parentPath) && hasParentOptionalSegments) return;
invariant(meta.relativePath.startsWith(parentPath), `Absolute route path "${meta.relativePath}" nested under path "${parentPath}" is not valid. An absolute child route path must start with the combined path of all its parent routes.`);
meta.relativePath = meta.relativePath.slice(parentPath.length);
}
let path = joinPaths([parentPath, meta.relativePath]);
let routesMeta = parentsMeta.concat(meta);
if (route.children && route.children.length > 0) {
invariant(route.index !== true, `Index routes must not have child routes. Please remove all child routes from route path "${path}".`);
flattenRoutes(route.children, branches, routesMeta, path, hasParentOptionalSegments);
}
if (route.path == null && !route.index) return;
branches.push({
path,
score: computeScore(path, route.index),
routesMeta: routesMeta.map((meta, i) => {
let [matcher, params] = compilePath(meta.relativePath, meta.caseSensitive, i === routesMeta.length - 1);
return {
...meta,
matcher,
compiledParams: params
};
})
});
};
routes.forEach((route, index) => {
if (route.path === "" || !route.path?.includes("?")) flattenRoute(route, index);
else for (let exploded of explodeOptionalSegments(route.path)) flattenRoute(route, index, true, exploded);
});
return branches;
}
function explodeOptionalSegments(path) {
let segments = path.split("/");
if (segments.length === 0) return [];
let [first, ...rest] = segments;
let isOptional = first.endsWith("?");
let required = first.replace(/\?$/, "");
if (rest.length === 0) return isOptional ? [required, ""] : [required];
let restExploded = explodeOptionalSegments(rest.join("/"));
let result = [];
result.push(...restExploded.map((subpath) => subpath === "" ? required : [required, subpath].join("/")));
if (isOptional) result.push(...restExploded);
return result.map((exploded) => path.startsWith("/") && exploded === "" ? "/" : exploded);
}
function rankRouteBranches(branches) {
branches.sort((a, b) => a.score !== b.score ? b.score - a.score : compareIndexes(a.routesMeta.map((meta) => meta.childrenIndex), b.routesMeta.map((meta) => meta.childrenIndex)));
}
const paramRe = /^:[\w-]+$/;
const partialParamRe = /^:[\w-]+/;
const partialDynamicSegmentValue = 3.5;
const dynamicSegmentValue = 3;
const indexRouteValue = 2;
const emptySegmentValue = 1;
const staticSegmentValue = 10;
const splatPenalty = -2;
const isSplat = (s) => s === "*";
function computeScore(path, index) {
let segments = path.split("/");
let initialScore = segments.length;
if (segments.some(isSplat)) initialScore += splatPenalty;
if (index) initialScore += indexRouteValue;
return segments.filter((s) => !isSplat(s)).reduce((score, segment) => score + (paramRe.test(segment) ? dynamicSegmentValue : partialParamRe.test(segment) ? partialDynamicSegmentValue : segment === "" ? emptySegmentValue : staticSegmentValue), initialScore);
}
function compareIndexes(a, b) {
return a.length === b.length && a.slice(0, -1).every((n, i) => n === b[i]) ? a[a.length - 1] - b[b.length - 1] : 0;
}
function matchRouteBranch(branch, pathname, allowPartial = false) {
let { routesMeta } = branch;
let matchedParams = {};
let matchedPathname = "/";
let matches = [];
for (let i = 0; i < routesMeta.length; ++i) {
let meta = routesMeta[i];
let end = i === routesMeta.length - 1;
let remainingPathname = matchedPathname === "/" ? pathname : pathname.slice(matchedPathname.length) || "/";
let pattern = {
path: meta.relativePath,
caseSensitive: meta.caseSensitive,
end
};
let match = meta.matcher && meta.compiledParams ? matchPathImpl(pattern, remainingPathname, meta.matcher, meta.compiledParams) : matchPath(pattern, remainingPathname);
let route = meta.route;
if (!match && end && allowPartial && !routesMeta[routesMeta.length - 1].route.index) match = matchPath({
path: meta.relativePath,
caseSensitive: meta.caseSensitive,
end: false
}, remainingPathname);
if (!match) return null;
Object.assign(matchedParams, match.params);
matches.push({
params: matchedParams,
pathname: joinPaths([matchedPathname, match.pathname]),
pathnameBase: normalizePathname(joinPaths([matchedPathname, match.pathnameBase])),
route
});
if (match.pathnameBase !== "/") matchedPathname = joinPaths([matchedPathname, match.pathnameBase]);
}
return matches;
}
/**
* Characters that `encodeURIComponent` escapes but that are valid literally in
* a URL path segment. Per RFC 3986 §3.3, a path segment is made of `pchar`:
*
* ```
* pchar = unreserved / pct-encoded / sub-delims / ":" / "@"
* sub-delims = "!" / "$" / "&" / "'" / "(" / ")" / "*" / "+" / "," / ";" / "="
* ```
*
* `encodeURIComponent` targets query-string values, where `$ & + , ; = : @`
* are delimiters and must be escaped — but in a path segment they carry no
* special meaning, and browsers keep them literal in `location.pathname`.
* (`! ' ( ) *` and the unreserved set are already left alone by
* `encodeURIComponent`, so they need no restoring.)
*/
const PATH_PARAM_OVERESCAPED = {
"%24": "$",
"%26": "&",
"%2B": "+",
"%2C": ",",
"%3A": ":",
"%3B": ";",
"%3D": "=",
"%40": "@"
};
/**
* Encodes a param value for interpolation into a single URL path segment.
*
* Escapes characters that would break the path (`/ ? # %`, whitespace,
* non-ASCII, …) while leaving characters that RFC 3986 permits literally in a
* path segment untouched. Escaping those would needlessly rewrite URLs — e.g.
* a semver build param `1.0.0+1` would become `1.0.0%2B1` even though browsers
* display and match the `+` literally in `location.pathname`.
*
* See [RFC 3986 §3.3](https://datatracker.ietf.org/doc/html/rfc3986#section-3.3))
*
* @param value The param value to encode.
* @returns The encoded value, safe for use as a single path segment.
*/
function encodePathParam(value) {
return encodeURIComponent(value).replace(/%(?:24|26|2B|2C|3A|3B|3D|40)/g, (match) => PATH_PARAM_OVERESCAPED[match]);
}
/**
* Returns a path with params interpolated.
*
* Param values are percent-encoded for use in a path segment: characters that
* would change the URL structure (`/`, `?`, `#`, `%`, whitespace, non-ASCII)
* are escaped, while characters that RFC 3986 allows literally in a path
* segment (`$ & + , ; = : @`) are kept as-is. Note this differs from query-string
* encoding (`encodeURIComponent`/`URLSearchParams`), where those characters are
* delimiters and must be escaped. Splat (`*`) values are encoded per segment,
* preserving `/` separators.
*
* See [RFC 3986 §3.3](https://datatracker.ietf.org/doc/html/rfc3986#section-3.3)
*
* @example
* import { generatePath } from "react-router";
*
* generatePath("/users/:id", { id: "123" }); // "/users/123"
* generatePath("/files/:name", { name: "a b" }); // "/files/a%20b"
* generatePath("/releases/:v", { v: "1.0.0+1" }); // "/releases/1.0.0+1"
*
* @public
* @category Utils
* @param originalPath The original path to generate.
* @param params The parameters to interpolate into the path.
* @returns The generated path with parameters interpolated.
*/
function generatePath(originalPath, params = {}) {
let path = originalPath;
if (path.endsWith("*") && path !== "*" && !path.endsWith("/*")) {
warning(false, `Route path "${path}" will be treated as if it were "${path.replace(/\*$/, "/*")}" because the \`*\` character must always follow a \`/\` in the pattern. To get rid of this warning, please change the route path to "${path.replace(/\*$/, "/*")}".`);
path = path.replace(/\*$/, "/*");
}
const prefix = path.startsWith("/") ? "/" : "";
const stringify = (p) => p == null ? "" : typeof p === "string" ? p : String(p);
return prefix + path.split(/\/+/).map((segment, index, array) => {
if (index === array.length - 1 && segment === "*") return stringify(params["*"]);
const keyMatch = segment.match(/^:([\w-]+)(\??)(.*)/);
if (keyMatch) {
const [, key, optional, suffix] = keyMatch;
let param = params[key];
invariant(optional === "?" || param != null, `Missing ":${key}" param`);
return encodePathParam(stringify(param)) + suffix;
}
return segment.replace(/\?$/g, "");
}).filter((segment) => !!segment).join("/");
}
/**
* Performs pattern matching on a URL pathname and returns information about
* the match.
*
* @public
* @category Utils
* @param pattern The pattern to match against the URL pathname. This can be a
* string or a {@link PathPattern} object. If a string is provided, it will be
* treated as a pattern with `caseSensitive` set to `false` and `end` set to
* `true`.
* @param pathname The URL pathname to match against the pattern.
* @returns A path match object if the pattern matches the pathname,
* or `null` if it does not match.
*/
function matchPath(pattern, pathname) {
if (typeof pattern === "string") pattern = {
path: pattern,
caseSensitive: false,
end: true
};
let [matcher, compiledParams] = compilePath(pattern.path, pattern.caseSensitive, pattern.end);
return matchPathImpl(pattern, pathname, matcher, compiledParams);
}
function matchPathImpl(pattern, pathname, matcher, compiledParams) {
let match = pathname.match(matcher);
if (!match) return null;
let matchedPathname = match[0];
let pathnameBase = matchedPathname.replace(/(.)\/+$/, "$1");
let captureGroups = match.slice(1);
return {
params: compiledParams.reduce((memo, { paramName, isOptional }, index) => {
if (paramName === "*") {
let splatValue = captureGroups[index] || "";
pathnameBase = matchedPathname.slice(0, matchedPathname.length - splatValue.length).replace(/(.)\/+$/, "$1");
}
const value = captureGroups[index];
if (isOptional && !value) memo[paramName] = void 0;
else memo[paramName] = (value || "").replace(/%2F/g, "/");
return memo;
}, {}),
pathname: matchedPathname,
pathnameBase,
pattern
};
}
function compilePath(path, caseSensitive = false, end = true) {
warning(path === "*" || !path.endsWith("*") || path.endsWith("/*"), `Route path "${path}" will be treated as if it were "${path.replace(/\*$/, "/*")}" because the \`*\` character must always follow a \`/\` in the pattern. To get rid of this warning, please change the route path to "${path.replace(/\*$/, "/*")}".`);
let params = [];
let regexpSource = "^" + path.replace(/\/*\*?$/, "").replace(/^\/*/, "/").replace(/[\\.*+^${}|()[\]]/g, "\\$&").replace(/\/:([\w-]+)(\?)?/g, (match, paramName, isOptional, index, str) => {
params.push({
paramName,
isOptional: isOptional != null
});
if (isOptional) {
let nextChar = str.charAt(index + match.length);
if (nextChar && nextChar !== "/") return "/([^\\/]*)";
return "(?:/([^\\/]*))?";
}
return "/([^\\/]+)";
}).replace(/\/([\w-]+)\?(?=\/|$|\()/g, "(?:/$1)?");
if (path.endsWith("*")) {
params.push({ paramName: "*" });
regexpSource += path === "*" || path === "/*" ? "(.*)$" : "(?:\\/(.+)|\\/*)$";
} else if (end) regexpSource += "\\/*$";
else if (path !== "" && path !== "/") regexpSource += "(?:(?=\\/|$))";
return [new RegExp(regexpSource, caseSensitive ? void 0 : "i"), params];
}
function decodePath(value) {
try {
return value.split("/").map((v) => decodeURIComponent(v).replace(/\//g, "%2F")).join("/");
} catch (error) {
warning(false, `The URL path "${value}" could not be decoded because it is a malformed URL segment. This is probably due to a bad percent encoding (${error}).`);
return value;
}
}
function stripBasename(pathname, basename) {
if (basename === "/") return pathname;
if (!pathname.toLowerCase().startsWith(basename.toLowerCase())) return null;
let startIndex = basename.endsWith("/") ? basename.length - 1 : basename.length;
let nextChar = pathname.charAt(startIndex);
if (nextChar && nextChar !== "/") return null;
return pathname.slice(startIndex) || "/";
}
function prependBasename({ basename, pathname }) {
return pathname === "/" ? basename : joinPaths([basename, pathname]);
}
const isAbsoluteUrl = (url) => ABSOLUTE_URL_REGEX.test(url);
/**
* Returns a resolved {@link Path} object relative to the given pathname.
*
* @public
* @category Utils
* @param to The path to resolve, either a string or a partial {@link Path}
* object.
* @param fromPathname The pathname to resolve the path from. Defaults to `/`.
* @returns A {@link Path} object with the resolved pathname, search, and hash.
*/
function resolvePath(to, fromPathname = "/") {
let { pathname: toPathname, search = "", hash = "" } = typeof to === "string" ? parsePath(to) : to;
let pathname;
if (toPathname) {
toPathname = removeDoubleSlashes(toPathname);
if (toPathname.startsWith("/")) pathname = resolvePathname(toPathname.substring(1), "/");
else pathname = resolvePathname(toPathname, fromPathname);
} else pathname = fromPathname;
return {
pathname,
search: normalizeSearch(search),
hash: normalizeHash(hash)
};
}
function resolvePathname(relativePath, fromPathname) {
let segments = removeTrailingSlash(fromPathname).split("/");
relativePath.split("/").forEach((segment) => {
if (segment === "..") {
if (segments.length > 1) segments.pop();
} else if (segment !== ".") segments.push(segment);
});
return segments.length > 1 ? segments.join("/") : "/";
}
function getInvalidPathError(char, field, dest, path) {
return `Cannot include a '${char}' character in a manually specified \`to.${field}\` field [${JSON.stringify(path)}]. Please separate it out to the \`to.${dest}\` field. Alternatively you may provide the full path as a string in <Link to="..."> and the router will parse it for you.`;
}
function getPathContributingMatches(matches) {
return matches.filter((match, index) => index === 0 || match.route.path && match.route.path.length > 0);
}
function getResolveToMatches(matches) {
let pathMatches = getPathContributingMatches(matches);
return pathMatches.map((match, idx) => idx === pathMatches.length - 1 ? match.pathname : match.pathnameBase);
}
function resolveTo(toArg, routePathnames, locationPathname, isPathRelative = false) {
let to;
if (typeof toArg === "string") to = parsePath(toArg);
else {
to = { ...toArg };
invariant(!to.pathname || !to.pathname.includes("?"), getInvalidPathError("?", "pathname", "search", to));
invariant(!to.pathname || !to.pathname.includes("#"), getInvalidPathError("#", "pathname", "hash", to));
invariant(!to.search || !to.search.includes("#"), getInvalidPathError("#", "search", "hash", to));
}
let isEmptyPath = toArg === "" || to.pathname === "";
let toPathname = isEmptyPath ? "/" : to.pathname;
let from;
if (toPathname == null) from = locationPathname;
else {
let routePathnameIndex = routePathnames.length - 1;
if (!isPathRelative && toPathname.startsWith("..")) {
let toSegments = toPathname.split("/");
while (toSegments[0] === "..") {
toSegments.shift();
routePathnameIndex -= 1;
}
to.pathname = toSegments.join("/");
}
from = routePathnameIndex >= 0 ? routePathnames[routePathnameIndex] : "/";
}
let path = resolvePath(to, from);
let hasExplicitTrailingSlash = toPathname && toPathname !== "/" && toPathname.endsWith("/");
let hasCurrentTrailingSlash = (isEmptyPath || toPathname === ".") && locationPathname.endsWith("/");
if (!path.pathname.endsWith("/") && (hasExplicitTrailingSlash || hasCurrentTrailingSlash)) path.pathname += "/";
return path;
}
const removeDoubleSlashes = (path) => path.replace(/[\\/]{2,}/g, "/");
const joinPaths = (paths) => removeDoubleSlashes(paths.join("/"));
const removeTrailingSlash = (path) => path.replace(/\/+$/, "");
const normalizePathname = (pathname) => removeTrailingSlash(pathname).replace(/^\/*/, "/");
const normalizeSearch = (search) => !search || search === "?" ? "" : search.startsWith("?") ? search : "?" + search;
const normalizeHash = (hash) => !hash || hash === "#" ? "" : hash.startsWith("#") ? hash : "#" + hash;
var DataWithResponseInit = class {
type = "DataWithResponseInit";
data;
init;
constructor(data, init) {
this.data = data;
this.init = init || null;
}
};
/**
* Create "responses" that contain `headers`/`status` without forcing
* serialization into an actual [`Response`](https://developer.mozilla.org/en-US/docs/Web/API/Response)
*
* @example
* import { data } from "react-router";
*
* export async function action({ request }: Route.ActionArgs) {
* let formData = await request.formData();
* let item = await createItem(formData);
* return data(item, {
* headers: { "X-Custom-Header": "value" }
* status: 201,
* });
* }
*
* @public
* @category Utils
* @mode framework
* @mode data
* @param data The data to be included in the response.
* @param init The status code or a `ResponseInit` object to be included in the
* response.
* @returns A {@link DataWithResponseInit} instance containing the data and
* response init.
*/
function data(data, init) {
return new DataWithResponseInit(data, typeof init === "number" ? { status: init } : init);
}
/**
* A redirect [`Response`](https://developer.mozilla.org/en-US/docs/Web/API/Response).
* Sets the status code and the [`Location`](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Location)
* header. Defaults to [`302 Found`](https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/302).
*
* This utility accepts absolute URLs and can navigate to external domains, so
* the application should validate any user-supplied inputs to redirects.
*
* @example
* import { redirect } from "react-router";
*
* export async function loader({ request }: Route.LoaderArgs) {
* if (!isLoggedIn(request))
* throw redirect("/login");
* }
*
* // ...
* }
*
* @public
* @category Utils
* @mode framework
* @mode data
* @param url The URL to redirect to.
* @param init The status code or a `ResponseInit` object to be included in the
* response.
* @returns A [`Response`](https://developer.mozilla.org/en-US/docs/Web/API/Response)
* object with the redirect status and [`Location`](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Location)
* header.
*/
const redirect = (url, init = 302) => {
let responseInit = init;
if (typeof responseInit === "number") responseInit = { status: responseInit };
else if (typeof responseInit.status === "undefined") responseInit.status = 302;
let headers = new Headers(responseInit.headers);
headers.set("Location", url);
return new Response(null, {
...responseInit,
headers
});
};
/**
* A redirect [`Response`](https://developer.mozilla.org/en-US/docs/Web/API/Response)
* that will force a document reload to the new location. Sets the status code
* and the [`Location`](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Location)
* header. Defaults to [`302 Found`](https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/302).
*
* This utility accepts absolute URLs and can navigate to external domains, so
* the application should validate any user-supplied inputs to redirects.
*
* ```tsx filename=routes/logout.tsx
* import { redirectDocument } from "react-router";
*
* import { destroySession } from "../sessions.server";
*
* export async function action({ request }: Route.ActionArgs) {
* let session = await getSession(request.headers.get("Cookie"));
* return redirectDocument("/", {
* headers: { "Set-Cookie": await destroySession(session) }
* });
* }
* ```
*
* @public
* @category Utils
* @mode framework
* @mode data
* @param url The URL to redirect to.
* @param init The status code or a `ResponseInit` object to be included in the
* response.
* @returns A [`Response`](https://developer.mozilla.org/en-US/docs/Web/API/Response)
* object with the redirect status and [`Location`](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Location)
* header.
*/
const redirectDocument = (url, init) => {
let response = redirect(url, init);
response.headers.set("X-Remix-Reload-Document", "true");
return response;
};
/**
* A redirect [`Response`](https://developer.mozilla.org/en-US/docs/Web/API/Response)
* that will perform a [`history.replaceState`](https://developer.mozilla.org/en-US/docs/Web/API/History/replaceState)
* instead of a [`history.pushState`](https://developer.mozilla.org/en-US/docs/Web/API/History/pushState)
* for client-side navigation redirects. Sets the status code and the [`Location`](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Location)
* header. Defaults to [`302 Found`](https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/302).
*
* @example
* import { replace } from "react-router";
*
* export async function loader() {
* return replace("/new-location");
* }
*
* @public
* @category Utils
* @mode framework
* @mode data
* @param url The URL to redirect to.
* @param init The status code or a `ResponseInit` object to be included in the
* response.
* @returns A [`Response`](https://developer.mozilla.org/en-US/docs/Web/API/Response)
* object with the redirect status and [`Location`](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Location)
* header.
*/
const replace = (url, init) => {
let response = redirect(url, init);
response.headers.set("X-Remix-Replace", "true");
return response;
};
const SUPPORTED_ERROR_TYPES = [
"EvalError",
"RangeError",
"ReferenceError",
"SyntaxError",
"TypeError",
"URIError"
];
var ErrorResponseImpl = class {
status;
statusText;
data;
error;
internal;
constructor(status, statusText, data, internal = false) {
this.status = status;
this.statusText = statusText || "";
this.internal = internal;
if (data instanceof Error) {
this.data = data.toString();
this.error = data;
} else this.data = data;
}
};
/**
* Check if the given error is an {@link ErrorResponse} generated from a 4xx/5xx
* [`Response`](https://developer.mozilla.org/en-US/docs/Web/API/Response)
* thrown from an [`action`](../../start/framework/route-module#action) or
* [`loader`](../../start/framework/route-module#loader) function.
*
* @example
* import { isRouteErrorResponse } from "react-router";
*
* export function ErrorBoundary({ error }: Route.ErrorBoundaryProps) {
* if (isRouteErrorResponse(error)) {
* return (
* <>
* <p>Error: `${error.status}: ${error.statusText}`</p>
* <p>{error.data}</p>
* </>
* );
* }
*
* return (
* <p>Error: {error instanceof Error ? error.message : "Unknown Error"}</p>
* );
* }
*
* @public
* @category Utils
* @mode framework
* @mode data
* @param error The error to check.
* @returns `true` if the error is an {@link ErrorResponse}, `false` otherwise.
*/
function isRouteErrorResponse(error) {
return error != null && typeof error.status === "number" && typeof error.statusText === "string" && typeof error.internal === "boolean" && "data" in error;
}
function getRoutePattern(matches) {
return joinPaths(matches.map((m) => m.route.path).filter(Boolean)) || "/";
}
function createDataFunctionUrl(request, path) {
let url = new URL(typeof request === "string" || request instanceof URL ? request : request.url);
let parsed = typeof path === "string" ? parsePath(path) : path;
url.pathname = parsed.pathname || "/";
if (parsed.search) {
let searchParams = new URLSearchParams(parsed.search);
let indexValues = searchParams.getAll("index");
searchParams.delete("index");
for (let value of indexValues.filter(Boolean)) searchParams.append("index", value);
let search = searchParams.toString();
url.search = search ? `?${search}` : "";
} else url.search = "";
url.hash = parsed.hash || "";
return url;
}
const isBrowser = typeof window !== "undefined" && typeof window.document !== "undefined" && typeof window.document.createElement !== "undefined";
function parseToInfo(_to, basename) {
let to = _to;
if (typeof to !== "string" || !ABSOLUTE_URL_REGEX.test(to)) return {
absoluteURL: void 0,
isExternal: false,
to
};
let absoluteURL = to;
let isExternal = false;
if (isBrowser) try {
let currentUrl = new URL(window.location.href);
let targetUrl = PROTOCOL_RELATIVE_URL_REGEX.test(to) ? new URL(normalizeProtocolRelativeUrl(to, currentUrl.protocol)) : new URL(to);
let path = stripBasename(targetUrl.pathname, basename);
if (targetUrl.origin === currentUrl.origin && path != null) to = path + targetUrl.search + targetUrl.hash;
else isExternal = true;
} catch (e) {
warning(false, `<Link to="${to}"> contains an invalid URL which will probably break when clicked - please update to a valid URL path.`);
}
return {
absoluteURL,
isExternal,
to
};
}
//#endregion
export { ErrorResponseImpl, RouterContextProvider, SUPPORTED_ERROR_TYPES, compilePath, convertRouteMatchToUiMatch, convertRoutesToDataRoutes, createContext, createDataFunctionUrl, data, decodePath, defaultMapRouteProperties, encodePathParam, flattenAndRankRoutes, generatePath, getPathContributingMatches, getResolveToMatches, getRoutePattern, isAbsoluteUrl, isBrowser, isRouteErrorResponse, isUnsupportedLazyRouteFunctionKey, isUnsupportedLazyRouteObjectKey, joinPaths, matchPath, matchRoutes, matchRoutesImpl, parseToInfo, prependBasename, redirect, redirectDocument, removeDoubleSlashes, removeTrailingSlash, replace, resolvePath, resolveTo, stripBasename };