Merge pull request 'feat:adiciona router-dom' (#5) from feature/body into main

Reviewed-on: #5
This commit is contained in:
Naian Felix dos Santos 2023-01-21 02:55:48 +00:00
commit 781caac9ed
71 changed files with 29447 additions and 23 deletions

View File

@ -9,32 +9,33 @@ import TrocaEDevolucao from "./Tabs/TrocaEDevolucao";
import SegurancaEPrivacidade from "./Tabs/SegurancaEPrivacidade";
import Contato from "./Tabs/Contato";
import style from "./body.module.scss";
import { Route, Routes } from "react-router";
const Body = () => {
const TabsItems = [
{
title: "Sobre",
component: <Sobre />,
path: "sobre",
},
{
title: "Forma de Pagamento",
component: <FormaDePagamento />,
path: "formadepagamento",
},
{
title: "Entrega",
component: <Entrega />,
path: "entrega",
},
{
title: "Troca e Devolução",
component: <TrocaEDevolucao />,
path: "trocaedevolucao",
},
{
title: "Segurança e Privacidade",
component: <SegurancaEPrivacidade />,
path: "segurancaeprivacidade",
},
{
title: "Contato",
component: <Contato />,
path: "contato",
},
];
@ -48,6 +49,20 @@ const Body = () => {
<h1 className={style["title-body"]}>INSTITUCIONAL</h1>
<div className={style["container"]}>
<TabLayout tabs={TabsItems} />
<div className={style["wrapper-text"]}>
<Routes>
<Route path="sobre" element={<Sobre />} />
<Route path="formadepagamento" element={<FormaDePagamento />} />
<Route path="entrega" element={<Entrega />} />
<Route path="trocaedevolucao" element={<TrocaEDevolucao />} />
<Route
path="segurancaeprivacidade"
element={<SegurancaEPrivacidade />}
/>
<Route path="contato" element={<Contato />} />
</Routes>
</div>
</div>
</div>
);

View File

@ -1,9 +1,10 @@
import React, { useState, useEffect } from "react";
import { Link } from "react-router-dom";
import style from "../body.module.scss";
interface MenuValue {
title: string;
component: JSX.Element;
path: string;
}
export interface TabLayoutProps {
@ -23,19 +24,20 @@ const TabLayout: React.FC<TabLayoutProps> = ({ tabs }) => {
<ul className={style["list"]}>
{tabs.map((tab, index) => {
return (
<li
onClick={() => {
handleClick(tab);
}}
className={
tabs.indexOf(selectedTab!) === index ? style["active"] : ""
}>
{tab.title}
</li>
<Link to={tab.path}>
<li
onClick={() => {
handleClick(tab);
}}
className={
tabs.indexOf(selectedTab!) === index ? style["active"] : ""
}>
{tab.title}
</li>
</Link>
);
})}
</ul>
<div className={style["wrapper-text"]}>{selectedTab?.component}</div>
</>
);
};

View File

@ -1,14 +1,17 @@
import React from 'react';
import ReactDOM from 'react-dom/client';
import { Home } from './pages/Home';
import './style/index.css';
import React from "react";
import ReactDOM from "react-dom/client";
import { Home } from "./pages/Home";
import "./style/index.css";
import { BrowserRouter } from "react-router-dom";
const root = ReactDOM.createRoot(
document.getElementById('root') as HTMLElement
document.getElementById("root") as HTMLElement
);
root.render(
<React.StrictMode>
<Home />
<BrowserRouter>
<Home />
</BrowserRouter>
</React.StrictMode>
);

18
node_modules/.yarn-integrity generated vendored Normal file
View File

@ -0,0 +1,18 @@
{
"systemParams": "win32-x64-108",
"modulesFolders": [
"node_modules"
],
"flags": [],
"linkedModules": [],
"topLevelPatterns": [
"react-router-dom@^6.7.0"
],
"lockfileEntries": {
"@remix-run/router@1.3.0": "https://registry.yarnpkg.com/@remix-run/router/-/router-1.3.0.tgz#b6ee542c7f087b73b3d8215b9bf799f648be71cb",
"react-router-dom@^6.7.0": "https://registry.yarnpkg.com/react-router-dom/-/react-router-dom-6.7.0.tgz#0249f4ca4eb704562b8b0ff29caeb928c3a6ed38",
"react-router@6.7.0": "https://registry.yarnpkg.com/react-router/-/react-router-6.7.0.tgz#db262684c13b5c2970694084ae9e8531718a0681"
},
"files": [],
"artifacts": {}
}

156
node_modules/@remix-run/router/CHANGELOG.md generated vendored Normal file
View File

@ -0,0 +1,156 @@
# `@remix-run/router`
## 1.3.0
### Minor Changes
- Added support for navigation blocking APIs ([#9709](https://github.com/remix-run/react-router/pull/9709))
- Expose deferred information from `createStaticHandler` ([#9760](https://github.com/remix-run/react-router/pull/9760))
### Patch Changes
- Improved absolute redirect url detection in actions/loaders ([#9829](https://github.com/remix-run/react-router/pull/9829))
- Fix URL creation with memory histories ([#9814](https://github.com/remix-run/react-router/pull/9814))
- Fix `generatePath` when optional params are present ([#9764](https://github.com/remix-run/react-router/pull/9764))
- Fix scroll reset if a submission redirects ([#9886](https://github.com/remix-run/react-router/pull/9886))
- Fix 404 bug with same-origin absolute redirects ([#9913](https://github.com/remix-run/react-router/pull/9913))
- Support `OPTIONS` requests in `staticHandler.queryRoute` ([#9914](https://github.com/remix-run/react-router/pull/9914))
## 1.2.1
### Patch Changes
- Include submission info in `shouldRevalidate` on action redirects ([#9777](https://github.com/remix-run/react-router/pull/9777), [#9782](https://github.com/remix-run/react-router/pull/9782))
- Reset `actionData` on action redirect to current location ([#9772](https://github.com/remix-run/react-router/pull/9772))
## 1.2.0
### Minor Changes
- Remove `unstable_` prefix from `createStaticHandler`/`createStaticRouter`/`StaticRouterProvider` ([#9738](https://github.com/remix-run/react-router/pull/9738))
### Patch Changes
- Fix explicit `replace` on submissions and `PUSH` on submission to new paths ([#9734](https://github.com/remix-run/react-router/pull/9734))
- Fix a few bugs where loader/action data wasn't properly cleared on errors ([#9735](https://github.com/remix-run/react-router/pull/9735))
- Prevent `useLoaderData` usage in `errorElement` ([#9735](https://github.com/remix-run/react-router/pull/9735))
- Skip initial scroll restoration for SSR apps with `hydrationData` ([#9664](https://github.com/remix-run/react-router/pull/9664))
## 1.1.0
This release introduces support for [Optional Route Segments](https://github.com/remix-run/react-router/issues/9546). Now, adding a `?` to the end of any path segment will make that entire segment optional. This works for both static segments and dynamic parameters.
**Optional Params Examples**
- Path `lang?/about` will match:
- `/:lang/about`
- `/about`
- Path `/multistep/:widget1?/widget2?/widget3?` will match:
- `/multistep`
- `/multistep/:widget1`
- `/multistep/:widget1/:widget2`
- `/multistep/:widget1/:widget2/:widget3`
**Optional Static Segment Example**
- Path `/home?` will match:
- `/`
- `/home`
- Path `/fr?/about` will match:
- `/about`
- `/fr/about`
### Minor Changes
- Allows optional routes and optional static segments ([#9650](https://github.com/remix-run/react-router/pull/9650))
### Patch Changes
- Stop incorrectly matching on partial named parameters, i.e. `<Route path="prefix-:param">`, to align with how splat parameters work. If you were previously relying on this behavior then it's recommended to extract the static portion of the path at the `useParams` call site: ([#9506](https://github.com/remix-run/react-router/pull/9506))
```jsx
// Old behavior at URL /prefix-123
<Route path="prefix-:id" element={<Comp /> }>
function Comp() {
let params = useParams(); // { id: '123' }
let id = params.id; // "123"
...
}
// New behavior at URL /prefix-123
<Route path=":id" element={<Comp /> }>
function Comp() {
let params = useParams(); // { id: 'prefix-123' }
let id = params.id.replace(/^prefix-/, ''); // "123"
...
}
```
- Persist `headers` on `loader` `request`'s after SSR document `action` request ([#9721](https://github.com/remix-run/react-router/pull/9721))
- Fix requests sent to revalidating loaders so they reflect a GET request ([#9660](https://github.com/remix-run/react-router/pull/9660))
- Fix issue with deeply nested optional segments ([#9727](https://github.com/remix-run/react-router/pull/9727))
- GET forms now expose a submission on the loading navigation ([#9695](https://github.com/remix-run/react-router/pull/9695))
- Fix error boundary tracking for multiple errors bubbling to the same boundary ([#9702](https://github.com/remix-run/react-router/pull/9702))
## 1.0.5
### Patch Changes
- Fix requests sent to revalidating loaders so they reflect a `GET` request ([#9680](https://github.com/remix-run/react-router/pull/9680))
- Remove `instanceof Response` checks in favor of `isResponse` ([#9690](https://github.com/remix-run/react-router/pull/9690))
- Fix `URL` creation in Cloudflare Pages or other non-browser-environments ([#9682](https://github.com/remix-run/react-router/pull/9682), [#9689](https://github.com/remix-run/react-router/pull/9689))
- Add `requestContext` support to static handler `query`/`queryRoute` ([#9696](https://github.com/remix-run/react-router/pull/9696))
- Note that the unstable API of `queryRoute(path, routeId)` has been changed to `queryRoute(path, { routeId, requestContext })`
## 1.0.4
### Patch Changes
- Throw an error if an `action`/`loader` function returns `undefined` as revalidations need to know whether the loader has previously been executed. `undefined` also causes issues during SSR stringification for hydration. You should always ensure you `loader`/`action` returns a value, and you may return `null` if you don't wish to return anything. ([#9511](https://github.com/remix-run/react-router/pull/9511))
- Properly handle redirects to external domains ([#9590](https://github.com/remix-run/react-router/pull/9590), [#9654](https://github.com/remix-run/react-router/pull/9654))
- Preserve the HTTP method on 307/308 redirects ([#9597](https://github.com/remix-run/react-router/pull/9597))
- Support `basename` in static data routers ([#9591](https://github.com/remix-run/react-router/pull/9591))
- Enhanced `ErrorResponse` bodies to contain more descriptive text in internal 403/404/405 scenarios
## 1.0.3
### Patch Changes
- Fix hrefs generated when using `createHashRouter` ([#9409](https://github.com/remix-run/react-router/pull/9409))
- fix encoding/matching issues with special chars ([#9477](https://github.com/remix-run/react-router/pull/9477), [#9496](https://github.com/remix-run/react-router/pull/9496))
- Support `basename` and relative routing in `loader`/`action` redirects ([#9447](https://github.com/remix-run/react-router/pull/9447))
- Ignore pathless layout routes when looking for proper submission `action` function ([#9455](https://github.com/remix-run/react-router/pull/9455))
- properly support `index` routes with a `path` in `useResolvedPath` ([#9486](https://github.com/remix-run/react-router/pull/9486))
- Add UMD build for `@remix-run/router` ([#9446](https://github.com/remix-run/react-router/pull/9446))
- fix `createURL` in local file execution in Firefox ([#9464](https://github.com/remix-run/react-router/pull/9464))
- Updates to `unstable_createStaticHandler` for incorporating into Remix ([#9482](https://github.com/remix-run/react-router/pull/9482), [#9465](https://github.com/remix-run/react-router/pull/9465))
## 1.0.2
### Patch Changes
- Reset `actionData` after a successful action redirect ([#9334](https://github.com/remix-run/react-router/pull/9334))
- Update `matchPath` to avoid false positives on dash-separated segments ([#9300](https://github.com/remix-run/react-router/pull/9300))
- If an index route has children, it will result in a runtime error. We have strengthened our `RouteObject`/`RouteProps` types to surface the error in TypeScript. ([#9366](https://github.com/remix-run/react-router/pull/9366))
## 1.0.1
### Patch Changes
- Preserve state from `initialEntries` ([#9288](https://github.com/remix-run/react-router/pull/9288))
- Preserve `?index` for fetcher get submissions to index routes ([#9312](https://github.com/remix-run/react-router/pull/9312))
## 1.0.0
This is the first stable release of `@remix-run/router`, which provides all the underlying routing and data loading/mutation logic for `react-router`. You should _not_ be using this package directly unless you are authoring a routing library similar to `react-router`.
For an overview of the features provided by `react-router`, we recommend you go check out the [docs][rr-docs], especially the [feature overview][rr-feature-overview] and the [tutorial][rr-tutorial].
For an overview of the features provided by `@remix-run/router`, please check out the [`README`][remix-router-readme].
[rr-docs]: https://reactrouter.com
[rr-feature-overview]: https://reactrouter.com/start/overview
[rr-tutorial]: https://reactrouter.com/start/tutorial
[remix-router-readme]: https://github.com/remix-run/react-router/blob/main/packages/router/README.md

22
node_modules/@remix-run/router/LICENSE.md generated vendored Normal file
View File

@ -0,0 +1,22 @@
MIT License
Copyright (c) React Training 2015-2019
Copyright (c) Remix Software 2020-2022
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.

107
node_modules/@remix-run/router/README.md generated vendored Normal file
View File

@ -0,0 +1,107 @@
# Remix Router
The `@remix-run/router` package is a framework-agnostic routing package (sometimes referred to as a browser-emulator) that serves as the heart of [React Router][react-router] and [Remix][remix] and provides all the core functionality for routing coupled with data loading and data mutations. It comes with built-in handling of errors, race-conditions, interruptions, cancellations, lazy-loading data, and much, much more.
If you're using React Router, you should never `import` anything directly from the `@remix-run/router` or `react-router` packages, but you should have everything you need in either `react-router-dom` or `react-router-native`. Both of those packages re-export everything from `@remix-run/router` and `react-router`.
> **Warning**
>
> This router is a low-level package intended to be consumed by UI layer routing libraries. You should very likely not be using this package directly unless you are authoring a routing library such as [`react-router-dom`][react-router-repo] or one of it's other [UI ports][remix-routers-repo].
## API
A Router instance can be created using `createRouter`:
```js
// Create and initialize a router. "initialize" contains all side effects
// including history listeners and kicking off the initial data fetch
let router = createRouter({
// Routes array
routes: ,
// History instance
history,
}).initialize()
```
Internally, the Router represents the state in an object of the following format, which is available through `router.state`. You can also register a subscriber of the signature `(state: RouterState) => void` to execute when the state updates via `router.subscribe()`;
```ts
interface RouterState {
// False during the initial data load, true once we have our initial data
initialized: boolean;
// The `history` action of the most recently completed navigation
historyAction: Action;
// The current location of the router. During a navigation this reflects
// the "old" location and is updated upon completion of the navigation
location: Location;
// The current set of route matches
matches: DataRouteMatch[];
// The state of the current navigation
navigation: Navigation;
// The state of any in-progress router.revalidate() calls
revalidation: RevalidationState;
// Data from the loaders for the current matches
loaderData: RouteData;
// Data from the action for the current matches
actionData: RouteData | null;
// Errors thrown from loaders/actions for the current matches
errors: RouteData | null;
// Map of all active fetchers
fetchers: Map<string, Fetcher>;
// Scroll position to restore to for the active Location, false if we
// should not restore, or null if we don't have a saved position
// Note: must be enabled via router.enableScrollRestoration()
restoreScrollPosition: number | false | null;
// Proxied `preventScrollReset` value passed to router.navigate()
preventScrollReset: boolean;
}
```
### Navigations
All navigations are done through the `router.navigate` API which is overloaded to support different types of navigations:
```js
// Link navigation (pushes onto the history stack by default)
router.navigate("/page");
// Link navigation (replacing the history stack)
router.navigate("/page", { replace: true });
// Pop navigation (moving backward/forward in the history stack)
router.navigate(-1);
// Form submission navigation
let formData = new FormData();
formData.append(key, value);
router.navigate("/page", {
formMethod: "post",
formData,
});
```
### Fetchers
Fetchers are a mechanism to call loaders/actions without triggering a navigation, and are done through the `router.fetch()` API. All fetch calls require a unique key to identify the fetcher.
```js
// Execute the loader for /page
router.fetch("key", "/page");
// Submit to the action for /page
let formData = new FormData();
formData.append(key, value);
router.fetch("key", "/page", {
formMethod: "post",
formData,
});
```
### Revalidation
By default, active loaders will revalidate after any navigation or fetcher mutation. If you need to kick off a revalidation for other use-cases, you can use `router.revalidate()` to re-execute all active loaders.
[react-router]: https://reactrouter.com
[remix]: https://remix.run
[react-router-repo]: https://github.com/remix-run/react-router
[remix-routers-repo]: https://github.com/brophdawg11/remix-routers

249
node_modules/@remix-run/router/dist/history.d.ts generated vendored Normal file
View File

@ -0,0 +1,249 @@
/**
* Actions represent the type of change to a location value.
*/
export 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.
*/
export 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.
*/
export interface Location extends Path {
/**
* A value of arbitrary data associated with this location.
*/
state: any;
/**
* 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;
}
/**
* A change to the current location.
*/
export 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;
}
/**
* A function that receives notifications about location changes.
*/
export interface Listener {
(update: Update): void;
}
/**
* Describes a location that is the destination of some navigation, either via
* `history.push` or `history.replace`. May be either a URL or the pieces of a
* URL path.
*/
export declare 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.
*/
export 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.
*/
export declare type InitialEntry = string | Partial<Location>;
export declare 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.
*/
export 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.
*/
export 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
*/
export interface BrowserHistory extends UrlHistory {
}
export declare 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
*/
export 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
*/
export interface HashHistory extends UrlHistory {
}
export declare 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
*/
export declare function createHashHistory(options?: HashHistoryOptions): HashHistory;
/**
* @private
*/
export declare function invariant(value: boolean, message?: string): asserts value;
export declare function invariant<T>(value: T | null | undefined, message?: string): asserts value is T;
/**
* Creates a Location object with a unique key from the given Path
*/
export declare function createLocation(current: string | Location, to: To, state?: any, key?: string): Readonly<Location>;
/**
* Creates a string URL path from the given pathname, search, and hash components.
*/
export declare function createPath({ pathname, search, hash, }: Partial<Path>): string;
/**
* Parses a string URL path into its separate pathname, search, and hash components.
*/
export declare function parsePath(path: string): Partial<Path>;
export interface UrlHistory extends History {
}
export declare type UrlHistoryOptions = {
window?: Window;
v5Compat?: boolean;
};

7
node_modules/@remix-run/router/dist/index.d.ts generated vendored Normal file
View File

@ -0,0 +1,7 @@
export type { ActionFunction, ActionFunctionArgs, AgnosticDataIndexRouteObject, AgnosticDataNonIndexRouteObject, AgnosticDataRouteMatch, AgnosticDataRouteObject, AgnosticIndexRouteObject, AgnosticNonIndexRouteObject, AgnosticRouteMatch, AgnosticRouteObject, TrackedPromise, FormEncType, FormMethod, JsonFunction, LoaderFunction, LoaderFunctionArgs, ParamParseKey, Params, PathMatch, PathPattern, RedirectFunction, ShouldRevalidateFunction, Submission, } from "./utils";
export { AbortedDeferredError, ErrorResponse, defer, generatePath, getToPathname, isRouteErrorResponse, joinPaths, json, matchPath, matchRoutes, normalizePathname, redirect, resolvePath, resolveTo, stripBasename, warning, } from "./utils";
export type { BrowserHistory, BrowserHistoryOptions, HashHistory, HashHistoryOptions, History, InitialEntry, Location, MemoryHistory, MemoryHistoryOptions, Path, To, } from "./history";
export { Action, createBrowserHistory, createPath, createHashHistory, createMemoryHistory, invariant, parsePath, } from "./history";
export * from "./router";
/** @internal */
export { DeferredData as UNSAFE_DeferredData, convertRoutesToDataRoutes as UNSAFE_convertRoutesToDataRoutes, getPathContributingMatches as UNSAFE_getPathContributingMatches, } from "./utils";

4067
node_modules/@remix-run/router/dist/router.cjs.js generated vendored Normal file

File diff suppressed because it is too large Load Diff

File diff suppressed because one or more lines are too long

426
node_modules/@remix-run/router/dist/router.d.ts generated vendored Normal file
View File

@ -0,0 +1,426 @@
import type { History, Location, Path, To } from "./history";
import { Action as HistoryAction } from "./history";
import type { AgnosticDataRouteMatch, AgnosticDataRouteObject, FormEncType, FormMethod, RouteData, AgnosticRouteObject, AgnosticRouteMatch } from "./utils";
import { DeferredData } from "./utils";
/**
* A Router instance manages all navigation and data loading/mutations
*/
export interface Router {
/**
* @internal
* PRIVATE - DO NOT USE
*
* Return the basename for the router
*/
get basename(): RouterInit["basename"];
/**
* @internal
* PRIVATE - DO NOT USE
*
* Return the current state of the router
*/
get state(): RouterState;
/**
* @internal
* PRIVATE - DO NOT USE
*
* Return the routes for this router instance
*/
get routes(): AgnosticDataRouteObject[];
/**
* @internal
* 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;
/**
* @internal
* PRIVATE - DO NOT USE
*
* Subscribe to router.state updates
*
* @param fn function to call with the new state
*/
subscribe(fn: RouterSubscriber): () => void;
/**
* @internal
* 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;
/**
* @internal
* 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, opts?: RouterNavigateOptions): Promise<void>;
/**
* @internal
* 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, opts?: RouterNavigateOptions): void;
/**
* @internal
* PRIVATE - DO NOT USE
*
* Trigger a revalidation of all current route loaders and fetcher loads
*/
revalidate(): void;
/**
* @internal
* PRIVATE - DO NOT USE
*
* Utility function to create an href for the given location
* @param location
*/
createHref(location: Location | URL): string;
/**
* @internal
* PRIVATE - DO NOT USE
*
* Utility function to URL encode a destination path according to the internal
* history implementation
* @param to
*/
encodeLocation(to: To): Path;
/**
* @internal
* 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
*
* Delete the fetcher for a given key
* @param key
*/
deleteFetcher(key?: string): void;
/**
* @internal
* PRIVATE - DO NOT USE
*
* Cleanup listeners and abort any in-progress loads
*/
dispose(): void;
/**
* @internal
* 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;
/**
* @internal
* PRIVATE - DO NOT USE
*
* Delete a navigation blocker
* @param key The identifier for the blocker
*/
deleteBlocker(key: string): void;
/**
* @internal
* PRIVATE - DO NOT USE
*
* Internal fetch AbortControllers accessed by unit tests
*/
_internalFetchControllers: Map<string, AbortController>;
/**
* @internal
* PRIVATE - DO NOT USE
*
* Internal pending DeferredData instances accessed by unit tests
*/
_internalActiveDeferreds: Map<string, DeferredData>;
}
/**
* State maintained internally by the router. During a navigation, all states
* reflect the the "old" location unless otherwise noted.
*/
export interface RouterState {
/**
* The action of the most recent navigation
*/
historyAction: HistoryAction;
/**
* The current location reflected by the router
*/
location: Location;
/**
* The current set of route matches
*/
matches: AgnosticDataRouteMatch[];
/**
* Tracks whether we've completed our initial data load
*/
initialized: 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)
* - 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
*/
export declare type HydrationState = Partial<Pick<RouterState, "loaderData" | "actionData" | "errors">>;
/**
* Initialization options for createRouter
*/
export interface RouterInit {
basename?: string;
routes: AgnosticRouteObject[];
history: History;
hydrationData?: HydrationState;
}
/**
* State returned from a server-side query() call
*/
export 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>;
activeDeferreds: Record<string, DeferredData> | null;
_deepestRenderedBoundaryId?: string | null;
}
/**
* A StaticHandler instance manages a singular SSR navigation/fetch event
*/
export interface StaticHandler {
dataRoutes: AgnosticDataRouteObject[];
query(request: Request, opts?: {
requestContext?: unknown;
}): Promise<StaticHandlerContext | Response>;
queryRoute(request: Request, opts?: {
routeId?: string;
requestContext?: unknown;
}): Promise<any>;
}
/**
* Subscriber function signature for changes to router state
*/
export interface RouterSubscriber {
(state: RouterState): void;
}
interface UseMatchesMatch {
id: string;
pathname: string;
params: AgnosticRouteMatch["params"];
data: unknown;
handle: unknown;
}
/**
* Function signature for determining the key to be used in scroll restoration
* for a given location
*/
export interface GetScrollRestorationKeyFunction {
(location: Location, matches: UseMatchesMatch[]): string | null;
}
/**
* Function signature for determining the current scroll position
*/
export interface GetScrollPositionFunction {
(): number;
}
/**
* Options for a navigate() call for a Link navigation
*/
declare type LinkNavigateOptions = {
replace?: boolean;
state?: any;
preventScrollReset?: boolean;
};
/**
* Options for a navigate() call for a Form navigation
*/
declare type SubmissionNavigateOptions = {
replace?: boolean;
state?: any;
preventScrollReset?: boolean;
formMethod?: FormMethod;
formEncType?: FormEncType;
formData: FormData;
};
/**
* Options to pass to navigate() for either a Link or Form navigation
*/
export declare type RouterNavigateOptions = LinkNavigateOptions | SubmissionNavigateOptions;
/**
* Options to pass to fetch()
*/
export declare type RouterFetchOptions = Omit<LinkNavigateOptions, "replace"> | Omit<SubmissionNavigateOptions, "replace">;
/**
* Potential states for state.navigation
*/
export declare type NavigationStates = {
Idle: {
state: "idle";
location: undefined;
formMethod: undefined;
formAction: undefined;
formEncType: undefined;
formData: undefined;
};
Loading: {
state: "loading";
location: Location;
formMethod: FormMethod | undefined;
formAction: string | undefined;
formEncType: FormEncType | undefined;
formData: FormData | undefined;
};
Submitting: {
state: "submitting";
location: Location;
formMethod: FormMethod;
formAction: string;
formEncType: FormEncType;
formData: FormData;
};
};
export declare type Navigation = NavigationStates[keyof NavigationStates];
export declare type RevalidationState = "idle" | "loading";
/**
* Potential states for fetchers
*/
declare type FetcherStates<TData = any> = {
Idle: {
state: "idle";
formMethod: undefined;
formAction: undefined;
formEncType: undefined;
formData: undefined;
data: TData | undefined;
" _hasFetcherDoneAnything "?: boolean;
};
Loading: {
state: "loading";
formMethod: FormMethod | undefined;
formAction: string | undefined;
formEncType: FormEncType | undefined;
formData: FormData | undefined;
data: TData | undefined;
" _hasFetcherDoneAnything "?: boolean;
};
Submitting: {
state: "submitting";
formMethod: FormMethod;
formAction: string;
formEncType: FormEncType;
formData: FormData;
data: TData | undefined;
" _hasFetcherDoneAnything "?: boolean;
};
};
export declare 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;
}
export declare type Blocker = BlockerUnblocked | BlockerBlocked | BlockerProceeding;
export declare type BlockerFunction = (args: {
currentLocation: Location;
nextLocation: Location;
historyAction: HistoryAction;
}) => boolean;
export declare const IDLE_NAVIGATION: NavigationStates["Idle"];
export declare const IDLE_FETCHER: FetcherStates["Idle"];
export declare const IDLE_BLOCKER: BlockerUnblocked;
/**
* Create a router and listen to history POP navigations
*/
export declare function createRouter(init: RouterInit): Router;
export declare const UNSAFE_DEFERRED_SYMBOL: unique symbol;
export declare function createStaticHandler(routes: AgnosticRouteObject[], opts?: {
basename?: string;
}): StaticHandler;
/**
* Given an existing StaticHandlerContext and an error thrown at render time,
* provide an updated StaticHandlerContext suitable for a second SSR render
*/
export declare function getStaticContextFromError(routes: AgnosticDataRouteObject[], context: StaticHandlerContext, error: any): StaticHandlerContext;
export {};

3987
node_modules/@remix-run/router/dist/router.js generated vendored Normal file

File diff suppressed because it is too large Load Diff

1
node_modules/@remix-run/router/dist/router.js.map generated vendored Normal file

File diff suppressed because one or more lines are too long

4073
node_modules/@remix-run/router/dist/router.umd.js generated vendored Normal file

File diff suppressed because it is too large Load Diff

File diff suppressed because one or more lines are too long

12
node_modules/@remix-run/router/dist/router.umd.min.js generated vendored Normal file

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

389
node_modules/@remix-run/router/dist/utils.d.ts generated vendored Normal file
View File

@ -0,0 +1,389 @@
import type { Location, Path, To } from "./history";
/**
* Map of routeId -> data returned from a loader/action/error
*/
export interface RouteData {
[routeId: string]: any;
}
export declare enum ResultType {
data = "data",
deferred = "deferred",
redirect = "redirect",
error = "error"
}
/**
* Successful result from a loader or action
*/
export interface SuccessResult {
type: ResultType.data;
data: any;
statusCode?: number;
headers?: Headers;
}
/**
* Successful defer() result from a loader or action
*/
export interface DeferredResult {
type: ResultType.deferred;
deferredData: DeferredData;
statusCode?: number;
headers?: Headers;
}
/**
* Redirect result from a loader or action
*/
export interface RedirectResult {
type: ResultType.redirect;
status: number;
location: string;
revalidate: boolean;
}
/**
* Unsuccessful result from a loader or action
*/
export interface ErrorResult {
type: ResultType.error;
error: any;
headers?: Headers;
}
/**
* Result from a loader or action - potentially successful or unsuccessful
*/
export declare type DataResult = SuccessResult | DeferredResult | RedirectResult | ErrorResult;
export declare type MutationFormMethod = "post" | "put" | "patch" | "delete";
export declare type FormMethod = "get" | MutationFormMethod;
export declare type FormEncType = "application/x-www-form-urlencoded" | "multipart/form-data";
/**
* @private
* Internal interface to pass around for action submissions, not intended for
* external consumption
*/
export interface Submission {
formMethod: FormMethod;
formAction: string;
formEncType: FormEncType;
formData: FormData;
}
/**
* @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 {
request: Request;
params: Params;
context?: any;
}
/**
* Arguments passed to loader functions
*/
export interface LoaderFunctionArgs extends DataFunctionArgs {
}
/**
* Arguments passed to action functions
*/
export interface ActionFunctionArgs extends DataFunctionArgs {
}
/**
* Route loader function signature
*/
export interface LoaderFunction {
(args: LoaderFunctionArgs): Promise<Response> | Response | Promise<any> | any;
}
/**
* Route action function signature
*/
export interface ActionFunction {
(args: ActionFunctionArgs): Promise<Response> | Response | Promise<any> | any;
}
/**
* 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.
*/
export interface ShouldRevalidateFunction {
(args: {
currentUrl: URL;
currentParams: AgnosticDataRouteMatch["params"];
nextUrl: URL;
nextParams: AgnosticDataRouteMatch["params"];
formMethod?: Submission["formMethod"];
formAction?: Submission["formAction"];
formEncType?: Submission["formEncType"];
formData?: Submission["formData"];
actionResult?: DataResult;
defaultShouldRevalidate: boolean;
}): boolean;
}
/**
* Base RouteObject with common props shared by all types of routes
*/
declare type AgnosticBaseRouteObject = {
caseSensitive?: boolean;
path?: string;
id?: string;
loader?: LoaderFunction;
action?: ActionFunction;
hasErrorBoundary?: boolean;
shouldRevalidate?: ShouldRevalidateFunction;
handle?: any;
};
/**
* Index routes must not have children
*/
export declare type AgnosticIndexRouteObject = AgnosticBaseRouteObject & {
children?: undefined;
index: true;
};
/**
* Non-index routes may have children, but cannot have index
*/
export declare type AgnosticNonIndexRouteObject = AgnosticBaseRouteObject & {
children?: AgnosticRouteObject[];
index?: false;
};
/**
* A route object represents a logical route, with (optionally) its child
* routes organized in a tree-like structure.
*/
export declare type AgnosticRouteObject = AgnosticIndexRouteObject | AgnosticNonIndexRouteObject;
export declare type AgnosticDataIndexRouteObject = AgnosticIndexRouteObject & {
id: string;
};
export declare type AgnosticDataNonIndexRouteObject = AgnosticNonIndexRouteObject & {
children?: AgnosticDataRouteObject[];
id: string;
};
/**
* A data route object, which is just a RouteObject with a required unique ID
*/
export declare type AgnosticDataRouteObject = AgnosticDataIndexRouteObject | AgnosticDataNonIndexRouteObject;
declare type _PathParam<Path extends string> = Path extends `${infer L}/${infer R}` ? _PathParam<L> | _PathParam<R> : Path extends `:${infer Param}` ? Param extends `${infer Optional}?` ? Optional : Param : never;
/**
* Examples:
* "/a/b/*" -> "*"
* ":a" -> "a"
* "/a/:b" -> "b"
* "/a/blahblahblah:b" -> "b"
* "/:a/:b" -> "a" | "b"
* "/:a/b/:c/*" -> "a" | "c" | "*"
*/
declare type PathParam<Path extends string> = Path extends "*" ? "*" : Path extends `${infer Rest}/*` ? "*" | _PathParam<Rest> : _PathParam<Path>;
export declare type ParamParseKey<Segment extends string> = [
PathParam<Segment>
] extends [never] ? string : PathParam<Segment>;
/**
* The parameters that were parsed from the URL path.
*/
export declare type Params<Key extends string = string> = {
readonly [key in Key]: string | undefined;
};
/**
* A RouteMatch contains info about how a route matched a URL.
*/
export interface AgnosticRouteMatch<ParamKey extends string = string, RouteObjectType extends AgnosticRouteObject = AgnosticRouteObject> {
/**
* 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;
}
export interface AgnosticDataRouteMatch extends AgnosticRouteMatch<string, AgnosticDataRouteObject> {
}
export declare function convertRoutesToDataRoutes(routes: AgnosticRouteObject[], parentPath?: number[], allIds?: Set<string>): AgnosticDataRouteObject[];
/**
* Matches the given routes to a location and returns the match data.
*
* @see https://reactrouter.com/utils/match-routes
*/
export declare function matchRoutes<RouteObjectType extends AgnosticRouteObject = AgnosticRouteObject>(routes: RouteObjectType[], locationArg: Partial<Location> | string, basename?: string): AgnosticRouteMatch<string, RouteObjectType>[] | null;
/**
* Returns a path with params interpolated.
*
* @see https://reactrouter.com/utils/generate-path
*/
export declare function generatePath<Path extends string>(originalPath: Path, params?: {
[key in PathParam<Path>]: string | null;
}): string;
/**
* A PathPattern is used to match on some portion of a URL pathname.
*/
export 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. 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;
}
/**
* A PathMatch contains info about how a PathPattern matched on a URL pathname.
*/
export 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.
*
* @see https://reactrouter.com/utils/match-path
*/
export declare function matchPath<ParamKey extends ParamParseKey<Path>, Path extends string>(pattern: PathPattern<Path> | Path, pathname: string): PathMatch<ParamKey> | null;
/**
* @private
*/
export declare function stripBasename(pathname: string, basename: string): string | null;
/**
* @private
*/
export declare function warning(cond: any, message: string): void;
/**
* Returns a resolved path object relative to the given pathname.
*
* @see https://reactrouter.com/utils/resolve-path
*/
export declare function resolvePath(to: To, fromPathname?: string): Path;
/**
* @private
*
* When processing relative navigation we want to ignore ancestor routes that
* do not contribute to the path, such that index/pathless layout routes don't
* interfere.
*
* For example, when moving a route element into an index route and/or a
* pathless layout route, relative link behavior contained within should stay
* the same. Both of the following examples should link back to the root:
*
* <Route path="/">
* <Route path="accounts" element={<Link to=".."}>
* </Route>
*
* <Route path="/">
* <Route path="accounts">
* <Route element={<AccountsLayout />}> // <-- Does not contribute
* <Route index element={<Link to=".."} /> // <-- Does not contribute
* </Route
* </Route>
* </Route>
*/
export declare function getPathContributingMatches<T extends AgnosticRouteMatch = AgnosticRouteMatch>(matches: T[]): T[];
/**
* @private
*/
export declare function resolveTo(toArg: To, routePathnames: string[], locationPathname: string, isPathRelative?: boolean): Path;
/**
* @private
*/
export declare function getToPathname(to: To): string | undefined;
/**
* @private
*/
export declare const joinPaths: (paths: string[]) => string;
/**
* @private
*/
export declare const normalizePathname: (pathname: string) => string;
/**
* @private
*/
export declare const normalizeSearch: (search: string) => string;
/**
* @private
*/
export declare const normalizeHash: (hash: string) => string;
export declare type JsonFunction = <Data>(data: Data, init?: number | ResponseInit) => Response;
/**
* This is a shortcut for creating `application/json` responses. Converts `data`
* to JSON and sets the `Content-Type` header.
*/
export declare const json: JsonFunction;
export interface TrackedPromise extends Promise<any> {
_tracked?: boolean;
_data?: any;
_error?: any;
}
export declare class AbortedDeferredError extends Error {
}
export declare class DeferredData {
private pendingKeysSet;
private controller;
private abortPromise;
private unlistenAbortSignal;
private subscribers;
data: Record<string, unknown>;
init?: ResponseInit;
deferredKeys: string[];
constructor(data: Record<string, unknown>, responseInit?: ResponseInit);
private trackPromise;
private onSettle;
private emit;
subscribe(fn: (aborted: boolean, settledKey?: string) => void): () => boolean;
cancel(): void;
resolveData(signal: AbortSignal): Promise<boolean>;
get done(): boolean;
get unwrappedData(): {};
get pendingKeys(): string[];
}
export declare type DeferFunction = (data: Record<string, unknown>, init?: number | ResponseInit) => DeferredData;
export declare const defer: DeferFunction;
export declare type RedirectFunction = (url: string, init?: number | ResponseInit) => Response;
/**
* A redirect response. Sets the status code and the `Location` header.
* Defaults to "302 Found".
*/
export declare const redirect: RedirectFunction;
/**
* @private
* Utility class we use to hold auto-unwrapped 4xx/5xx Response bodies
*/
export declare class ErrorResponse {
status: number;
statusText: string;
data: any;
error?: Error;
internal: boolean;
constructor(status: number, statusText: string | undefined, data: any, internal?: boolean);
}
/**
* Check if the given error is an ErrorResponse generated from a 4xx/5xx
* Response throw from an action/loader
*/
export declare function isRouteErrorResponse(e: any): e is ErrorResponse;
export {};

737
node_modules/@remix-run/router/history.ts generated vendored Normal file
View File

@ -0,0 +1,737 @@
////////////////////////////////////////////////////////////////////////////////
//#region Types and Constants
////////////////////////////////////////////////////////////////////////////////
/**
* Actions represent the type of change to a location value.
*/
export 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.
*/
export 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.
*/
export interface Location extends Path {
/**
* A value of arbitrary data associated with this location.
*/
state: any;
/**
* 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;
}
/**
* A change to the current location.
*/
export 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;
}
/**
* A function that receives notifications about location changes.
*/
export interface Listener {
(update: Update): void;
}
/**
* Describes a location that is the destination of some navigation, either via
* `history.push` or `history.replace`. May be either a URL or the pieces of a
* URL path.
*/
export 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.
*/
export 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;
}
type HistoryState = {
usr: any;
key?: string;
idx: number;
};
const PopStateEventType = "popstate";
//#endregion
////////////////////////////////////////////////////////////////////////////////
//#region Memory History
////////////////////////////////////////////////////////////////////////////////
/**
* A user-supplied object that describes a location. Used when providing
* entries to `createMemoryHistory` via its `initialEntries` option.
*/
export type InitialEntry = string | Partial<Location>;
export 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.
*/
export 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.
*/
export function createMemoryHistory(
options: MemoryHistoryOptions = {}
): MemoryHistory {
let { initialEntries = ["/"], initialIndex, v5Compat = false } = options;
let entries: Location[]; // Declare so we can access from createMemoryLocation
entries = initialEntries.map((entry, index) =>
createMemoryLocation(
entry,
typeof entry === "string" ? null : entry.state,
index === 0 ? "default" : undefined
)
);
let index = clampIndex(
initialIndex == null ? entries.length - 1 : initialIndex
);
let action = Action.Pop;
let listener: Listener | null = null;
function clampIndex(n: number): number {
return Math.min(Math.max(n, 0), entries.length - 1);
}
function getCurrentLocation(): Location {
return entries[index];
}
function createMemoryLocation(
to: To,
state: any = null,
key?: string
): Location {
let location = createLocation(
entries ? getCurrentLocation().pathname : "/",
to,
state,
key
);
warning(
location.pathname.charAt(0) === "/",
`relative pathnames are not supported in memory history: ${JSON.stringify(
to
)}`
);
return location;
}
function createHref(to: To) {
return typeof to === "string" ? to : createPath(to);
}
let history: MemoryHistory = {
get index() {
return index;
},
get action() {
return action;
},
get location() {
return getCurrentLocation();
},
createHref,
createURL(to) {
return new URL(createHref(to), "http://localhost");
},
encodeLocation(to: To) {
let path = typeof to === "string" ? parsePath(to) : to;
return {
pathname: path.pathname || "",
search: path.search || "",
hash: path.hash || "",
};
},
push(to, state) {
action = Action.Push;
let nextLocation = createMemoryLocation(to, state);
index += 1;
entries.splice(index, entries.length, nextLocation);
if (v5Compat && listener) {
listener({ action, location: nextLocation, delta: 1 });
}
},
replace(to, state) {
action = Action.Replace;
let nextLocation = createMemoryLocation(to, state);
entries[index] = nextLocation;
if (v5Compat && listener) {
listener({ action, location: nextLocation, delta: 0 });
}
},
go(delta) {
action = Action.Pop;
let nextIndex = clampIndex(index + delta);
let nextLocation = entries[nextIndex];
index = nextIndex;
if (listener) {
listener({ action, location: nextLocation, delta });
}
},
listen(fn: Listener) {
listener = fn;
return () => {
listener = null;
};
},
};
return history;
}
//#endregion
////////////////////////////////////////////////////////////////////////////////
//#region Browser History
////////////////////////////////////////////////////////////////////////////////
/**
* 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
*/
export interface BrowserHistory extends UrlHistory {}
export 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
*/
export function createBrowserHistory(
options: BrowserHistoryOptions = {}
): BrowserHistory {
function createBrowserLocation(
window: Window,
globalHistory: Window["history"]
) {
let { pathname, search, hash } = window.location;
return createLocation(
"",
{ pathname, search, hash },
// state defaults to `null` because `window.history.state` does
(globalHistory.state && globalHistory.state.usr) || null,
(globalHistory.state && globalHistory.state.key) || "default"
);
}
function createBrowserHref(window: Window, to: To) {
return typeof to === "string" ? to : createPath(to);
}
return getUrlBasedHistory(
createBrowserLocation,
createBrowserHref,
null,
options
);
}
//#endregion
////////////////////////////////////////////////////////////////////////////////
//#region Hash History
////////////////////////////////////////////////////////////////////////////////
/**
* 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
*/
export interface HashHistory extends UrlHistory {}
export 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
*/
export function createHashHistory(
options: HashHistoryOptions = {}
): HashHistory {
function createHashLocation(
window: Window,
globalHistory: Window["history"]
) {
let {
pathname = "/",
search = "",
hash = "",
} = parsePath(window.location.hash.substr(1));
return createLocation(
"",
{ pathname, search, hash },
// state defaults to `null` because `window.history.state` does
(globalHistory.state && globalHistory.state.usr) || null,
(globalHistory.state && globalHistory.state.key) || "default"
);
}
function createHashHref(window: Window, to: 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: Location, to: To) {
warning(
location.pathname.charAt(0) === "/",
`relative pathnames are not supported in hash history.push(${JSON.stringify(
to
)})`
);
}
return getUrlBasedHistory(
createHashLocation,
createHashHref,
validateHashLocation,
options
);
}
//#endregion
////////////////////////////////////////////////////////////////////////////////
//#region UTILS
////////////////////////////////////////////////////////////////////////////////
/**
* @private
*/
export function invariant(value: boolean, message?: string): asserts value;
export function invariant<T>(
value: T | null | undefined,
message?: string
): asserts value is T;
export function invariant(value: any, message?: string) {
if (value === false || value === null || typeof value === "undefined") {
throw new Error(message);
}
}
function warning(cond: any, message: string) {
if (!cond) {
// eslint-disable-next-line no-console
if (typeof console !== "undefined") console.warn(message);
try {
// Welcome to debugging history!
//
// This error is thrown as a convenience so you can more easily
// find the source for a warning that appears in the console by
// enabling "pause on exceptions" in your JavaScript debugger.
throw new Error(message);
// eslint-disable-next-line no-empty
} catch (e) {}
}
}
function createKey() {
return Math.random().toString(36).substr(2, 8);
}
/**
* For browser-based histories, we combine the state and key into an object
*/
function getHistoryState(location: Location, index: number): HistoryState {
return {
usr: location.state,
key: location.key,
idx: index,
};
}
/**
* Creates a Location object with a unique key from the given Path
*/
export function createLocation(
current: string | Location,
to: To,
state: any = null,
key?: string
): Readonly<Location> {
let location: Readonly<Location> = {
pathname: typeof current === "string" ? current : current.pathname,
search: "",
hash: "",
...(typeof to === "string" ? parsePath(to) : to),
state,
// TODO: This could be cleaned up. push/replace should probably just take
// full Locations now and avoid the need to run through this flow at all
// But that's a pretty big refactor to the current test suite so going to
// keep as is for the time being and just let any incoming keys take precedence
key: (to && (to as Location).key) || key || createKey(),
};
return location;
}
/**
* Creates a string URL path from the given pathname, search, and hash components.
*/
export function createPath({
pathname = "/",
search = "",
hash = "",
}: Partial<Path>) {
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.
*/
export function parsePath(path: string): Partial<Path> {
let parsedPath: Partial<Path> = {};
if (path) {
let hashIndex = path.indexOf("#");
if (hashIndex >= 0) {
parsedPath.hash = path.substr(hashIndex);
path = path.substr(0, hashIndex);
}
let searchIndex = path.indexOf("?");
if (searchIndex >= 0) {
parsedPath.search = path.substr(searchIndex);
path = path.substr(0, searchIndex);
}
if (path) {
parsedPath.pathname = path;
}
}
return parsedPath;
}
export interface UrlHistory extends History {}
export type UrlHistoryOptions = {
window?: Window;
v5Compat?: boolean;
};
function getUrlBasedHistory(
getLocation: (window: Window, globalHistory: Window["history"]) => Location,
createHref: (window: Window, to: To) => string,
validateLocation: ((location: Location, to: To) => void) | null,
options: UrlHistoryOptions = {}
): UrlHistory {
let { window = document.defaultView!, v5Compat = false } = options;
let globalHistory = window.history;
let action = Action.Pop;
let listener: Listener | null = null;
let index = getIndex()!;
// Index should only be null when we initialize. If not, it's because the
// user called history.pushState or history.replaceState directly, in which
// case we should log a warning as it will result in bugs.
if (index == null) {
index = 0;
globalHistory.replaceState({ ...globalHistory.state, idx: index }, "");
}
function getIndex(): number {
let state = globalHistory.state || { idx: null };
return state.idx;
}
function handlePop() {
let nextAction = Action.Pop;
let nextIndex = getIndex();
if (nextIndex != null) {
let delta = nextIndex - index;
action = nextAction;
index = nextIndex;
if (listener) {
listener({ action, location: history.location, delta });
}
} else {
warning(
false,
// TODO: Write up a doc that explains our blocking strategy in detail
// and link to it here so people can understand better what is going on
// and how to avoid it.
`You are trying to block a POP navigation to a location that was not ` +
`created by @remix-run/router. The block will fail silently in ` +
`production, but in general you should do all navigation with the ` +
`router (instead of using window.history.pushState directly) ` +
`to avoid this situation.`
);
}
}
function push(to: To, state?: any) {
action = Action.Push;
let location = createLocation(history.location, to, state);
if (validateLocation) validateLocation(location, to);
index = getIndex() + 1;
let historyState = getHistoryState(location, index);
let url = history.createHref(location);
// try...catch because iOS limits us to 100 pushState calls :/
try {
globalHistory.pushState(historyState, "", url);
} catch (error) {
// They are going to lose state here, but there is no real
// way to warn them about it since the page will refresh...
window.location.assign(url);
}
if (v5Compat && listener) {
listener({ action, location: history.location, delta: 1 });
}
}
function replace(to: To, state?: any) {
action = Action.Replace;
let location = createLocation(history.location, to, state);
if (validateLocation) validateLocation(location, to);
index = getIndex();
let historyState = getHistoryState(location, index);
let url = history.createHref(location);
globalHistory.replaceState(historyState, "", url);
if (v5Compat && listener) {
listener({ action, location: history.location, delta: 0 });
}
}
function createURL(to: To): URL {
// window.location.origin is "null" (the literal string value) in Firefox
// under certain conditions, notably when serving from a local HTML file
// See https://bugzilla.mozilla.org/show_bug.cgi?id=878297
let base =
window.location.origin !== "null"
? window.location.origin
: window.location.href;
let href = typeof to === "string" ? to : createPath(to);
invariant(
base,
`No window.location.(origin|href) available to create URL for href: ${href}`
);
return new URL(href, base);
}
let history: History = {
get action() {
return action;
},
get location() {
return getLocation(window, globalHistory);
},
listen(fn: Listener) {
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) {
// Encode a Location the same way window.location would
let url = createURL(to);
return {
pathname: url.pathname,
search: url.search,
hash: url.hash,
};
},
push,
replace,
go(n) {
return globalHistory.go(n);
},
};
return history;
}
//#endregion

84
node_modules/@remix-run/router/index.ts generated vendored Normal file
View File

@ -0,0 +1,84 @@
export type {
ActionFunction,
ActionFunctionArgs,
AgnosticDataIndexRouteObject,
AgnosticDataNonIndexRouteObject,
AgnosticDataRouteMatch,
AgnosticDataRouteObject,
AgnosticIndexRouteObject,
AgnosticNonIndexRouteObject,
AgnosticRouteMatch,
AgnosticRouteObject,
TrackedPromise,
FormEncType,
FormMethod,
JsonFunction,
LoaderFunction,
LoaderFunctionArgs,
ParamParseKey,
Params,
PathMatch,
PathPattern,
RedirectFunction,
ShouldRevalidateFunction,
Submission,
} from "./utils";
export {
AbortedDeferredError,
ErrorResponse,
defer,
generatePath,
getToPathname,
isRouteErrorResponse,
joinPaths,
json,
matchPath,
matchRoutes,
normalizePathname,
redirect,
resolvePath,
resolveTo,
stripBasename,
warning,
} from "./utils";
export type {
BrowserHistory,
BrowserHistoryOptions,
HashHistory,
HashHistoryOptions,
History,
InitialEntry,
Location,
MemoryHistory,
MemoryHistoryOptions,
Path,
To,
} from "./history";
export {
Action,
createBrowserHistory,
createPath,
createHashHistory,
createMemoryHistory,
invariant,
parsePath,
} from "./history";
export * from "./router";
///////////////////////////////////////////////////////////////////////////////
// DANGER! PLEASE READ ME!
// We consider these exports an implementation detail and do not guarantee
// against any breaking changes, regardless of the semver release. Use with
// extreme caution and only if you understand the consequences. Godspeed.
///////////////////////////////////////////////////////////////////////////////
/** @internal */
export {
DeferredData as UNSAFE_DeferredData,
convertRoutesToDataRoutes as UNSAFE_convertRoutesToDataRoutes,
getPathContributingMatches as UNSAFE_getPathContributingMatches,
} from "./utils";

33
node_modules/@remix-run/router/package.json generated vendored Normal file
View File

@ -0,0 +1,33 @@
{
"name": "@remix-run/router",
"version": "1.3.0",
"description": "Nested/Data-driven/Framework-agnostic Routing",
"keywords": [
"remix",
"router",
"location"
],
"repository": {
"type": "git",
"url": "https://github.com/remix-run/react-router",
"directory": "packages/router"
},
"license": "MIT",
"author": "Remix Software <hello@remix.run>",
"sideEffects": false,
"main": "./dist/router.cjs.js",
"unpkg": "./dist/router.umd.min.js",
"module": "./dist/router.js",
"types": "./dist/index.d.ts",
"files": [
"dist/",
"*.ts",
"CHANGELOG.md"
],
"engines": {
"node": ">=14"
},
"publishConfig": {
"access": "public"
}
}

3692
node_modules/@remix-run/router/router.ts generated vendored Normal file

File diff suppressed because it is too large Load Diff

1402
node_modules/@remix-run/router/utils.ts generated vendored Normal file

File diff suppressed because it is too large Load Diff

142
node_modules/react-router-dom/CHANGELOG.md generated vendored Normal file
View File

@ -0,0 +1,142 @@
# `react-router-dom`
## 6.7.0
### Minor Changes
- Add `unstable_useBlocker` hook for blocking navigations within the app's location origin ([#9709](https://github.com/remix-run/react-router/pull/9709))
- Add `unstable_usePrompt` hook for blocking navigations within the app's location origin ([#9932](https://github.com/remix-run/react-router/pull/9932))
- Add `preventScrollReset` prop to `<Form>` ([#9886](https://github.com/remix-run/react-router/pull/9886))
### Patch Changes
- Added pass-through event listener options argument to `useBeforeUnload` ([#9709](https://github.com/remix-run/react-router/pull/9709))
- Streamline jsdom bug workaround in tests ([#9824](https://github.com/remix-run/react-router/pull/9824))
- Updated dependencies:
- `@remix-run/router@1.3.0`
- `react-router@6.7.0`
## 6.6.2
### Patch Changes
- Ensure `useId` consistency during SSR ([#9805](https://github.com/remix-run/react-router/pull/9805))
- Updated dependencies:
- `react-router@6.6.2`
## 6.6.1
### Patch Changes
- Updated dependencies:
- `@remix-run/router@1.2.1`
- `react-router@6.6.1`
## 6.6.0
### Minor Changes
- Add `useBeforeUnload()` hook ([#9664](https://github.com/remix-run/react-router/pull/9664))
- Remove `unstable_` prefix from `createStaticHandler`/`createStaticRouter`/`StaticRouterProvider` ([#9738](https://github.com/remix-run/react-router/pull/9738))
### Patch Changes
- Proper hydration of `Error` objects from `StaticRouterProvider` ([#9664](https://github.com/remix-run/react-router/pull/9664))
- Support uppercase `<Form method>` and `useSubmit` method values ([#9664](https://github.com/remix-run/react-router/pull/9664))
- Skip initial scroll restoration for SSR apps with `hydrationData` ([#9664](https://github.com/remix-run/react-router/pull/9664))
- Fix `<button formmethod>` form submission overriddes ([#9664](https://github.com/remix-run/react-router/pull/9664))
- Updated dependencies:
- `@remix-run/router@1.2.0`
- `react-router@6.6.0`
## 6.5.0
### Patch Changes
- Updated dependencies:
- `react-router@6.5.0`
- `@remix-run/router@1.1.0`
## 6.4.5
### Patch Changes
- Updated dependencies:
- `@remix-run/router@1.0.5`
- `react-router@6.4.5`
## 6.4.4
### Patch Changes
- Fix issues with encoded characters in `NavLink` and descendant `<Routes>` ([#9589](https://github.com/remix-run/react-router/pull/9589), [#9647](https://github.com/remix-run/react-router/pull/9647))
- Properly serialize/deserialize `ErrorResponse` instances when using built-in hydration ([#9593](https://github.com/remix-run/react-router/pull/9593))
- Support `basename` in static data routers ([#9591](https://github.com/remix-run/react-router/pull/9591))
- Updated dependencies:
- `@remix-run/router@1.0.4`
- `react-router@6.4.4`
## 6.4.3
### Patch Changes
- Fix hrefs generated for `createHashRouter` ([#9409](https://github.com/remix-run/react-router/pull/9409))
- fix encoding/matching issues with special chars ([#9477](https://github.com/remix-run/react-router/pull/9477), [#9496](https://github.com/remix-run/react-router/pull/9496))
- Properly support `index` routes with a `path` in `useResolvedPath` ([#9486](https://github.com/remix-run/react-router/pull/9486))
- Respect `relative=path` prop on `NavLink` ([#9453](https://github.com/remix-run/react-router/pull/9453))
- Fix `NavLink` behavior for root urls ([#9497](https://github.com/remix-run/react-router/pull/9497))
- Updated dependencies:
- `@remix-run/router@1.0.3`
- `react-router@6.4.3`
## 6.4.2
### Patch Changes
- Respect `basename` in `useFormAction` ([#9352](https://github.com/remix-run/react-router/pull/9352))
- Enhance console error messages for invalid usage of data router hooks ([#9311](https://github.com/remix-run/react-router/pull/9311))
- If an index route has children, it will result in a runtime error. We have strengthened our `RouteObject`/`RouteProps` types to surface the error in TypeScript. ([#9366](https://github.com/remix-run/react-router/pull/9366))
- Updated dependencies:
- `react-router@6.4.2`
- `@remix-run/router@1.0.2`
## 6.4.1
### Patch Changes
- Updated dependencies:
- `react-router@6.4.1`
- `@remix-run/router@1.0.1`
## 6.4.0
Whoa this is a big one! `6.4.0` brings all the data loading and mutation APIs over from Remix. Here's a quick high level overview, but it's recommended you go check out the [docs][rr-docs], especially the [feature overview][rr-feature-overview] and the [tutorial][rr-tutorial].
**New APIs**
- Create your router with `createMemoryRouter`/`createBrowserRouter`/`createHashRouter`
- Render your router with `<RouterProvider>`
- Load data with a Route `loader` and mutate with a Route `action`
- Handle errors with Route `errorElement`
- Submit data with the new `<Form>` component
- Perform in-page data loads and mutations with `useFetcher()`
- Defer non-critical data with `defer` and `Await`
- Manage scroll position with `<ScrollRestoration>`
**New Features**
- Perform path-relative navigations with `<Link relative="path">` (#9160)
**Bug Fixes**
- Path resolution is now trailing slash agnostic (#8861)
- `useLocation` returns the scoped location inside a `<Routes location>` component (#9094)
- respect the `<Link replace>` prop if it is defined (#8779)
**Updated Dependencies**
- `react-router@6.4.0`
[rr-docs]: https://reactrouter.com
[rr-feature-overview]: https://reactrouter.com/start/overview
[rr-tutorial]: https://reactrouter.com/start/tutorial

22
node_modules/react-router-dom/LICENSE.md generated vendored Normal file
View File

@ -0,0 +1,22 @@
MIT License
Copyright (c) React Training 2015-2019
Copyright (c) Remix Software 2020-2022
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.

5
node_modules/react-router-dom/README.md generated vendored Normal file
View File

@ -0,0 +1,5 @@
# React Router DOM
The `react-router-dom` package contains bindings for using [React
Router](https://github.com/remix-run/react-router) in web applications.
Please see [the Getting Started guide](https://github.com/remix-run/react-router/blob/main/docs/start/tutorial.md) for more information on how to get started with React Router.

80
node_modules/react-router-dom/dist/dom.d.ts generated vendored Normal file
View File

@ -0,0 +1,80 @@
import type { FormEncType, FormMethod } from "@remix-run/router";
import type { RelativeRoutingType } from "react-router";
export declare const defaultMethod = "get";
export declare function isHtmlElement(object: any): object is HTMLElement;
export declare function isButtonElement(object: any): object is HTMLButtonElement;
export declare function isFormElement(object: any): object is HTMLFormElement;
export declare function isInputElement(object: any): object is HTMLInputElement;
declare type LimitedMouseEvent = Pick<MouseEvent, "button" | "metaKey" | "altKey" | "ctrlKey" | "shiftKey">;
export declare function shouldProcessLinkClick(event: LimitedMouseEvent, target?: string): boolean;
export declare type ParamKeyValuePair = [string, string];
export declare type URLSearchParamsInit = string | ParamKeyValuePair[] | Record<string, string | string[]> | URLSearchParams;
/**
* Creates a URLSearchParams object using the given initializer.
*
* This is identical to `new URLSearchParams(init)` except it also
* supports arrays as values in the object form of the initializer
* instead of just strings. This is convenient when you need multiple
* values for a given key, but don't want to use an array initializer.
*
* For example, instead of:
*
* let searchParams = new URLSearchParams([
* ['sort', 'name'],
* ['sort', 'price']
* ]);
*
* you can do:
*
* let searchParams = createSearchParams({
* sort: ['name', 'price']
* });
*/
export declare function createSearchParams(init?: URLSearchParamsInit): URLSearchParams;
export declare function getSearchParamsForLocation(locationSearch: string, defaultSearchParams: URLSearchParams): URLSearchParams;
export interface SubmitOptions {
/**
* The HTTP method used to submit the form. Overrides `<form method>`.
* Defaults to "GET".
*/
method?: FormMethod;
/**
* The action URL path used to submit the form. Overrides `<form action>`.
* Defaults to the path of the current route.
*
* Note: It is assumed the path is already resolved. If you need to resolve a
* relative path, use `useFormAction`.
*/
action?: string;
/**
* The action URL used to submit the form. Overrides `<form encType>`.
* Defaults to "application/x-www-form-urlencoded".
*/
encType?: FormEncType;
/**
* Set `true` to replace the current entry in the browser's history stack
* instead of creating a new one (i.e. stay on "the same page"). Defaults
* to `false`.
*/
replace?: boolean;
/**
* Determines whether the form action is relative to the route hierarchy or
* the pathname. Use this if you want to opt out of navigating the route
* hierarchy and want to instead route based on /-delimited URL segments
*/
relative?: RelativeRoutingType;
/**
* In browser-based environments, prevent resetting scroll after this
* navigation when using the <ScrollRestoration> component
*/
preventScrollReset?: boolean;
}
export declare function getFormSubmissionInfo(target: HTMLFormElement | HTMLButtonElement | HTMLInputElement | FormData | URLSearchParams | {
[name: string]: string;
} | null, defaultAction: string, options: SubmitOptions): {
url: URL;
method: string;
encType: string;
formData: FormData;
};
export {};

248
node_modules/react-router-dom/dist/index.d.ts generated vendored Normal file
View File

@ -0,0 +1,248 @@
/**
* NOTE: If you refactor this to split up the modules into separate files,
* you'll need to update the rollup config for react-router-dom-v5-compat.
*/
import * as React from "react";
import type { NavigateOptions, RelativeRoutingType, RouteObject, To } from "react-router";
import type { Fetcher, FormEncType, FormMethod, GetScrollRestorationKeyFunction, History, HydrationState, Router as RemixRouter } from "@remix-run/router";
import type { SubmitOptions, ParamKeyValuePair, URLSearchParamsInit } from "./dom";
import { createSearchParams } from "./dom";
export type { FormEncType, FormMethod, GetScrollRestorationKeyFunction, ParamKeyValuePair, SubmitOptions, URLSearchParamsInit, };
export { createSearchParams };
export type { ActionFunction, ActionFunctionArgs, AwaitProps, unstable_Blocker, unstable_BlockerFunction, DataRouteMatch, DataRouteObject, Fetcher, Hash, IndexRouteObject, IndexRouteProps, JsonFunction, LayoutRouteProps, LoaderFunction, LoaderFunctionArgs, Location, MemoryRouterProps, NavigateFunction, NavigateOptions, NavigateProps, Navigation, Navigator, NonIndexRouteObject, OutletProps, Params, ParamParseKey, Path, PathMatch, Pathname, PathPattern, PathRouteProps, RedirectFunction, RelativeRoutingType, RouteMatch, RouteObject, RouteProps, RouterProps, RouterProviderProps, RoutesProps, Search, ShouldRevalidateFunction, To, } from "react-router";
export { AbortedDeferredError, Await, MemoryRouter, Navigate, NavigationType, Outlet, Route, Router, RouterProvider, Routes, createMemoryRouter, createPath, createRoutesFromChildren, createRoutesFromElements, defer, isRouteErrorResponse, generatePath, json, matchPath, matchRoutes, parsePath, redirect, renderMatches, resolvePath, useActionData, useAsyncError, useAsyncValue, unstable_useBlocker, useHref, useInRouterContext, useLoaderData, useLocation, useMatch, useMatches, useNavigate, useNavigation, useNavigationType, useOutlet, useOutletContext, useParams, useResolvedPath, useRevalidator, useRouteError, useRouteLoaderData, useRoutes, } from "react-router";
/** @internal */
export { UNSAFE_DataRouterContext, UNSAFE_DataRouterStateContext, UNSAFE_NavigationContext, UNSAFE_LocationContext, UNSAFE_RouteContext, UNSAFE_enhanceManualRouteObjects, } from "react-router";
declare global {
var __staticRouterHydrationData: HydrationState | undefined;
}
export declare function createBrowserRouter(routes: RouteObject[], opts?: {
basename?: string;
hydrationData?: HydrationState;
window?: Window;
}): RemixRouter;
export declare function createHashRouter(routes: RouteObject[], opts?: {
basename?: string;
hydrationData?: HydrationState;
window?: Window;
}): RemixRouter;
export interface BrowserRouterProps {
basename?: string;
children?: React.ReactNode;
window?: Window;
}
/**
* A `<Router>` for use in web browsers. Provides the cleanest URLs.
*/
export declare function BrowserRouter({ basename, children, window, }: BrowserRouterProps): JSX.Element;
export interface HashRouterProps {
basename?: string;
children?: React.ReactNode;
window?: Window;
}
/**
* A `<Router>` for use in web browsers. Stores the location in the hash
* portion of the URL so it is not sent to the server.
*/
export declare function HashRouter({ basename, children, window }: HashRouterProps): JSX.Element;
export interface HistoryRouterProps {
basename?: string;
children?: React.ReactNode;
history: History;
}
/**
* A `<Router>` that accepts a pre-instantiated history object. It's important
* to note that using your own history object is highly discouraged and may add
* two versions of the history library to your bundles unless you use the same
* version of the history library that React Router uses internally.
*/
declare function HistoryRouter({ basename, children, history }: HistoryRouterProps): JSX.Element;
declare namespace HistoryRouter {
var displayName: string;
}
export { HistoryRouter as unstable_HistoryRouter };
export interface LinkProps extends Omit<React.AnchorHTMLAttributes<HTMLAnchorElement>, "href"> {
reloadDocument?: boolean;
replace?: boolean;
state?: any;
preventScrollReset?: boolean;
relative?: RelativeRoutingType;
to: To;
}
/**
* The public API for rendering a history-aware <a>.
*/
export declare const Link: React.ForwardRefExoticComponent<LinkProps & React.RefAttributes<HTMLAnchorElement>>;
export interface NavLinkProps extends Omit<LinkProps, "className" | "style" | "children"> {
children?: React.ReactNode | ((props: {
isActive: boolean;
isPending: boolean;
}) => React.ReactNode);
caseSensitive?: boolean;
className?: string | ((props: {
isActive: boolean;
isPending: boolean;
}) => string | undefined);
end?: boolean;
style?: React.CSSProperties | ((props: {
isActive: boolean;
isPending: boolean;
}) => React.CSSProperties | undefined);
}
/**
* A <Link> wrapper that knows if it's "active" or not.
*/
export declare const NavLink: React.ForwardRefExoticComponent<NavLinkProps & React.RefAttributes<HTMLAnchorElement>>;
export interface FormProps extends React.FormHTMLAttributes<HTMLFormElement> {
/**
* The HTTP verb to use when the form is submit. Supports "get", "post",
* "put", "delete", "patch".
*/
method?: FormMethod;
/**
* Normal `<form action>` but supports React Router's relative paths.
*/
action?: string;
/**
* Forces a full document navigation instead of a fetch.
*/
reloadDocument?: boolean;
/**
* Replaces the current entry in the browser history stack when the form
* navigates. Use this if you don't want the user to be able to click "back"
* to the page with the form on it.
*/
replace?: boolean;
/**
* Determines whether the form action is relative to the route hierarchy or
* the pathname. Use this if you want to opt out of navigating the route
* hierarchy and want to instead route based on /-delimited URL segments
*/
relative?: RelativeRoutingType;
/**
* Prevent the scroll position from resetting to the top of the viewport on
* completion of the navigation when using the <ScrollRestoration> component
*/
preventScrollReset?: boolean;
/**
* A function to call when the form is submitted. If you call
* `event.preventDefault()` then this form will not do anything.
*/
onSubmit?: React.FormEventHandler<HTMLFormElement>;
}
/**
* A `@remix-run/router`-aware `<form>`. It behaves like a normal form except
* that the interaction with the server is with `fetch` instead of new document
* requests, allowing components to add nicer UX to the page as the form is
* submitted and returns with data.
*/
export declare const Form: React.ForwardRefExoticComponent<FormProps & React.RefAttributes<HTMLFormElement>>;
export interface ScrollRestorationProps {
getKey?: GetScrollRestorationKeyFunction;
storageKey?: string;
}
/**
* This component will emulate the browser's scroll restoration on location
* changes.
*/
export declare function ScrollRestoration({ getKey, storageKey, }: ScrollRestorationProps): null;
export declare namespace ScrollRestoration {
var displayName: string;
}
/**
* Handles the click behavior for router `<Link>` components. This is useful if
* you need to create custom `<Link>` components with the same click behavior we
* use in our exported `<Link>`.
*/
export declare function useLinkClickHandler<E extends Element = HTMLAnchorElement>(to: To, { target, replace: replaceProp, state, preventScrollReset, relative, }?: {
target?: React.HTMLAttributeAnchorTarget;
replace?: boolean;
state?: any;
preventScrollReset?: boolean;
relative?: RelativeRoutingType;
}): (event: React.MouseEvent<E, MouseEvent>) => void;
/**
* A convenient wrapper for reading and writing search parameters via the
* URLSearchParams interface.
*/
export declare function useSearchParams(defaultInit?: URLSearchParamsInit): [URLSearchParams, SetURLSearchParams];
declare type SetURLSearchParams = (nextInit?: URLSearchParamsInit | ((prev: URLSearchParams) => URLSearchParamsInit), navigateOpts?: NavigateOptions) => void;
declare type SubmitTarget = HTMLFormElement | HTMLButtonElement | HTMLInputElement | FormData | URLSearchParams | {
[name: string]: string;
} | null;
/**
* Submits a HTML `<form>` to the server without reloading the page.
*/
export interface SubmitFunction {
(
/**
* Specifies the `<form>` to be submitted to the server, a specific
* `<button>` or `<input type="submit">` to use to submit the form, or some
* arbitrary data to submit.
*
* Note: When using a `<button>` its `name` and `value` will also be
* included in the form data that is submitted.
*/
target: SubmitTarget,
/**
* Options that override the `<form>`'s own attributes. Required when
* submitting arbitrary data without a backing `<form>`.
*/
options?: SubmitOptions): void;
}
/**
* Returns a function that may be used to programmatically submit a form (or
* some arbitrary data) to the server.
*/
export declare function useSubmit(): SubmitFunction;
export declare function useFormAction(action?: string, { relative }?: {
relative?: RelativeRoutingType;
}): string;
declare function createFetcherForm(fetcherKey: string, routeId: string): React.ForwardRefExoticComponent<FormProps & React.RefAttributes<HTMLFormElement>>;
export declare type FetcherWithComponents<TData> = Fetcher<TData> & {
Form: ReturnType<typeof createFetcherForm>;
submit: (target: SubmitTarget, options?: Omit<SubmitOptions, "replace" | "preventScrollReset">) => void;
load: (href: string) => void;
};
/**
* Interacts with route loaders and actions without causing a navigation. Great
* for any interaction that stays on the same page.
*/
export declare function useFetcher<TData = any>(): FetcherWithComponents<TData>;
/**
* Provides all fetchers currently on the page. Useful for layouts and parent
* routes that need to provide pending/optimistic UI regarding the fetch.
*/
export declare function useFetchers(): Fetcher[];
/**
* When rendered inside a RouterProvider, will restore scroll positions on navigations
*/
declare function useScrollRestoration({ getKey, storageKey, }?: {
getKey?: GetScrollRestorationKeyFunction;
storageKey?: string;
}): void;
/**
* Setup a callback to be fired on the window's `beforeunload` event. This is
* useful for saving some data to `window.localStorage` just before the page
* refreshes.
*
* Note: The `callback` argument should be a function created with
* `React.useCallback()`.
*/
export declare function useBeforeUnload(callback: (event: BeforeUnloadEvent) => any, options?: {
capture?: boolean;
}): void;
/**
* Wrapper around useBlocker to show a window.confirm prompt to users instead
* of building a custom UI with useBlocker.
*
* Warning: This has *a lot of rough edges* and behaves very differently (and
* very incorrectly in some cases) across browsers if user click addition
* back/forward navigations while the confirm is open. Use at your own risk.
*/
declare function usePrompt({ when, message }: {
when: boolean;
message: string;
}): void;
export { usePrompt as unstable_usePrompt };
export { useScrollRestoration as UNSAFE_useScrollRestoration };

987
node_modules/react-router-dom/dist/index.js generated vendored Normal file
View File

@ -0,0 +1,987 @@
/**
* React Router DOM v6.7.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 * as React from 'react';
import { UNSAFE_enhanceManualRouteObjects, Router, useHref, useResolvedPath, useLocation, UNSAFE_DataRouterStateContext, UNSAFE_NavigationContext, useNavigate, createPath, UNSAFE_RouteContext, useMatches, useNavigation, unstable_useBlocker, UNSAFE_DataRouterContext } from 'react-router';
export { AbortedDeferredError, Await, MemoryRouter, Navigate, NavigationType, Outlet, Route, Router, RouterProvider, Routes, UNSAFE_DataRouterContext, UNSAFE_DataRouterStateContext, UNSAFE_LocationContext, UNSAFE_NavigationContext, UNSAFE_RouteContext, UNSAFE_enhanceManualRouteObjects, createMemoryRouter, createPath, createRoutesFromChildren, createRoutesFromElements, defer, generatePath, isRouteErrorResponse, json, matchPath, matchRoutes, parsePath, redirect, renderMatches, resolvePath, unstable_useBlocker, useActionData, useAsyncError, useAsyncValue, useHref, useInRouterContext, useLoaderData, useLocation, useMatch, useMatches, useNavigate, useNavigation, useNavigationType, useOutlet, useOutletContext, useParams, useResolvedPath, useRevalidator, useRouteError, useRouteLoaderData, useRoutes } from 'react-router';
import { createRouter, createBrowserHistory, createHashHistory, ErrorResponse, invariant, joinPaths } from '@remix-run/router';
function _extends() {
_extends = Object.assign ? Object.assign.bind() : function (target) {
for (var i = 1; i < arguments.length; i++) {
var source = arguments[i];
for (var key in source) {
if (Object.prototype.hasOwnProperty.call(source, key)) {
target[key] = source[key];
}
}
}
return target;
};
return _extends.apply(this, arguments);
}
function _objectWithoutPropertiesLoose(source, excluded) {
if (source == null) return {};
var target = {};
var sourceKeys = Object.keys(source);
var key, i;
for (i = 0; i < sourceKeys.length; i++) {
key = sourceKeys[i];
if (excluded.indexOf(key) >= 0) continue;
target[key] = source[key];
}
return target;
}
const defaultMethod = "get";
const defaultEncType = "application/x-www-form-urlencoded";
function isHtmlElement(object) {
return object != null && typeof object.tagName === "string";
}
function isButtonElement(object) {
return isHtmlElement(object) && object.tagName.toLowerCase() === "button";
}
function isFormElement(object) {
return isHtmlElement(object) && object.tagName.toLowerCase() === "form";
}
function isInputElement(object) {
return isHtmlElement(object) && object.tagName.toLowerCase() === "input";
}
function isModifiedEvent(event) {
return !!(event.metaKey || event.altKey || event.ctrlKey || event.shiftKey);
}
function shouldProcessLinkClick(event, target) {
return event.button === 0 && ( // Ignore everything but left clicks
!target || target === "_self") && // Let browser handle "target=_blank" etc.
!isModifiedEvent(event) // Ignore clicks with modifier keys
;
}
/**
* Creates a URLSearchParams object using the given initializer.
*
* This is identical to `new URLSearchParams(init)` except it also
* supports arrays as values in the object form of the initializer
* instead of just strings. This is convenient when you need multiple
* values for a given key, but don't want to use an array initializer.
*
* For example, instead of:
*
* let searchParams = new URLSearchParams([
* ['sort', 'name'],
* ['sort', 'price']
* ]);
*
* you can do:
*
* let searchParams = createSearchParams({
* sort: ['name', 'price']
* });
*/
function createSearchParams(init) {
if (init === void 0) {
init = "";
}
return new URLSearchParams(typeof init === "string" || Array.isArray(init) || init instanceof URLSearchParams ? init : Object.keys(init).reduce((memo, key) => {
let value = init[key];
return memo.concat(Array.isArray(value) ? value.map(v => [key, v]) : [[key, value]]);
}, []));
}
function getSearchParamsForLocation(locationSearch, defaultSearchParams) {
let searchParams = createSearchParams(locationSearch);
for (let key of defaultSearchParams.keys()) {
if (!searchParams.has(key)) {
defaultSearchParams.getAll(key).forEach(value => {
searchParams.append(key, value);
});
}
}
return searchParams;
}
function getFormSubmissionInfo(target, defaultAction, options) {
let method;
let action;
let encType;
let formData;
if (isFormElement(target)) {
let submissionTrigger = options.submissionTrigger;
method = options.method || target.getAttribute("method") || defaultMethod;
action = options.action || target.getAttribute("action") || defaultAction;
encType = options.encType || target.getAttribute("enctype") || defaultEncType;
formData = new FormData(target);
if (submissionTrigger && submissionTrigger.name) {
formData.append(submissionTrigger.name, submissionTrigger.value);
}
} else if (isButtonElement(target) || isInputElement(target) && (target.type === "submit" || target.type === "image")) {
let form = target.form;
if (form == null) {
throw new Error("Cannot submit a <button> or <input type=\"submit\"> without a <form>");
} // <button>/<input type="submit"> may override attributes of <form>
method = options.method || target.getAttribute("formmethod") || form.getAttribute("method") || defaultMethod;
action = options.action || target.getAttribute("formaction") || form.getAttribute("action") || defaultAction;
encType = options.encType || target.getAttribute("formenctype") || form.getAttribute("enctype") || defaultEncType;
formData = new FormData(form); // Include name + value from a <button>, appending in case the button name
// matches an existing input name
if (target.name) {
formData.append(target.name, target.value);
}
} else if (isHtmlElement(target)) {
throw new Error("Cannot submit element that is not <form>, <button>, or " + "<input type=\"submit|image\">");
} else {
method = options.method || defaultMethod;
action = options.action || defaultAction;
encType = options.encType || defaultEncType;
if (target instanceof FormData) {
formData = target;
} else {
formData = new FormData();
if (target instanceof URLSearchParams) {
for (let [name, value] of target) {
formData.append(name, value);
}
} else if (target != null) {
for (let name of Object.keys(target)) {
formData.append(name, target[name]);
}
}
}
}
let {
protocol,
host
} = window.location;
let url = new URL(action, protocol + "//" + host);
return {
url,
method: method.toLowerCase(),
encType,
formData
};
}
const _excluded = ["onClick", "relative", "reloadDocument", "replace", "state", "target", "to", "preventScrollReset"],
_excluded2 = ["aria-current", "caseSensitive", "className", "end", "style", "to", "children"],
_excluded3 = ["reloadDocument", "replace", "method", "action", "onSubmit", "fetcherKey", "routeId", "relative", "preventScrollReset"];
//#region Routers
////////////////////////////////////////////////////////////////////////////////
function createBrowserRouter(routes, opts) {
return createRouter({
basename: opts == null ? void 0 : opts.basename,
history: createBrowserHistory({
window: opts == null ? void 0 : opts.window
}),
hydrationData: (opts == null ? void 0 : opts.hydrationData) || parseHydrationData(),
routes: UNSAFE_enhanceManualRouteObjects(routes)
}).initialize();
}
function createHashRouter(routes, opts) {
return createRouter({
basename: opts == null ? void 0 : opts.basename,
history: createHashHistory({
window: opts == null ? void 0 : opts.window
}),
hydrationData: (opts == null ? void 0 : opts.hydrationData) || parseHydrationData(),
routes: UNSAFE_enhanceManualRouteObjects(routes)
}).initialize();
}
function parseHydrationData() {
var _window;
let state = (_window = window) == null ? void 0 : _window.__staticRouterHydrationData;
if (state && state.errors) {
state = _extends({}, state, {
errors: deserializeErrors(state.errors)
});
}
return state;
}
function deserializeErrors(errors) {
if (!errors) return null;
let entries = Object.entries(errors);
let serialized = {};
for (let [key, val] of entries) {
// Hey you! If you change this, please change the corresponding logic in
// serializeErrors in react-router-dom/server.tsx :)
if (val && val.__type === "RouteErrorResponse") {
serialized[key] = new ErrorResponse(val.status, val.statusText, val.data, val.internal === true);
} else if (val && val.__type === "Error") {
let error = new Error(val.message); // Wipe away the client-side stack trace. Nothing to fill it in with
// because we don't serialize SSR stack traces for security reasons
error.stack = "";
serialized[key] = error;
} else {
serialized[key] = val;
}
}
return serialized;
}
/**
* A `<Router>` for use in web browsers. Provides the cleanest URLs.
*/
function BrowserRouter(_ref) {
let {
basename,
children,
window
} = _ref;
let historyRef = React.useRef();
if (historyRef.current == null) {
historyRef.current = createBrowserHistory({
window,
v5Compat: true
});
}
let history = historyRef.current;
let [state, setState] = React.useState({
action: history.action,
location: history.location
});
React.useLayoutEffect(() => history.listen(setState), [history]);
return /*#__PURE__*/React.createElement(Router, {
basename: basename,
children: children,
location: state.location,
navigationType: state.action,
navigator: history
});
}
/**
* A `<Router>` for use in web browsers. Stores the location in the hash
* portion of the URL so it is not sent to the server.
*/
function HashRouter(_ref2) {
let {
basename,
children,
window
} = _ref2;
let historyRef = React.useRef();
if (historyRef.current == null) {
historyRef.current = createHashHistory({
window,
v5Compat: true
});
}
let history = historyRef.current;
let [state, setState] = React.useState({
action: history.action,
location: history.location
});
React.useLayoutEffect(() => history.listen(setState), [history]);
return /*#__PURE__*/React.createElement(Router, {
basename: basename,
children: children,
location: state.location,
navigationType: state.action,
navigator: history
});
}
/**
* A `<Router>` that accepts a pre-instantiated history object. It's important
* to note that using your own history object is highly discouraged and may add
* two versions of the history library to your bundles unless you use the same
* version of the history library that React Router uses internally.
*/
function HistoryRouter(_ref3) {
let {
basename,
children,
history
} = _ref3;
const [state, setState] = React.useState({
action: history.action,
location: history.location
});
React.useLayoutEffect(() => history.listen(setState), [history]);
return /*#__PURE__*/React.createElement(Router, {
basename: basename,
children: children,
location: state.location,
navigationType: state.action,
navigator: history
});
}
if (process.env.NODE_ENV !== "production") {
HistoryRouter.displayName = "unstable_HistoryRouter";
}
/**
* The public API for rendering a history-aware <a>.
*/
const Link = /*#__PURE__*/React.forwardRef(function LinkWithRef(_ref4, ref) {
let {
onClick,
relative,
reloadDocument,
replace,
state,
target,
to,
preventScrollReset
} = _ref4,
rest = _objectWithoutPropertiesLoose(_ref4, _excluded);
let href = useHref(to, {
relative
});
let internalOnClick = useLinkClickHandler(to, {
replace,
state,
target,
preventScrollReset,
relative
});
function handleClick(event) {
if (onClick) onClick(event);
if (!event.defaultPrevented) {
internalOnClick(event);
}
}
return (
/*#__PURE__*/
// eslint-disable-next-line jsx-a11y/anchor-has-content
React.createElement("a", _extends({}, rest, {
href: href,
onClick: reloadDocument ? onClick : handleClick,
ref: ref,
target: target
}))
);
});
if (process.env.NODE_ENV !== "production") {
Link.displayName = "Link";
}
/**
* A <Link> wrapper that knows if it's "active" or not.
*/
const NavLink = /*#__PURE__*/React.forwardRef(function NavLinkWithRef(_ref5, ref) {
let {
"aria-current": ariaCurrentProp = "page",
caseSensitive = false,
className: classNameProp = "",
end = false,
style: styleProp,
to,
children
} = _ref5,
rest = _objectWithoutPropertiesLoose(_ref5, _excluded2);
let path = useResolvedPath(to, {
relative: rest.relative
});
let location = useLocation();
let routerState = React.useContext(UNSAFE_DataRouterStateContext);
let {
navigator
} = React.useContext(UNSAFE_NavigationContext);
let toPathname = navigator.encodeLocation ? navigator.encodeLocation(path).pathname : path.pathname;
let locationPathname = location.pathname;
let nextLocationPathname = routerState && routerState.navigation && routerState.navigation.location ? routerState.navigation.location.pathname : null;
if (!caseSensitive) {
locationPathname = locationPathname.toLowerCase();
nextLocationPathname = nextLocationPathname ? nextLocationPathname.toLowerCase() : null;
toPathname = toPathname.toLowerCase();
}
let isActive = locationPathname === toPathname || !end && locationPathname.startsWith(toPathname) && locationPathname.charAt(toPathname.length) === "/";
let isPending = nextLocationPathname != null && (nextLocationPathname === toPathname || !end && nextLocationPathname.startsWith(toPathname) && nextLocationPathname.charAt(toPathname.length) === "/");
let ariaCurrent = isActive ? ariaCurrentProp : undefined;
let className;
if (typeof classNameProp === "function") {
className = classNameProp({
isActive,
isPending
});
} else {
// If the className prop is not a function, we use a default `active`
// class for <NavLink />s that are active. In v5 `active` was the default
// value for `activeClassName`, but we are removing that API and can still
// use the old default behavior for a cleaner upgrade path and keep the
// simple styling rules working as they currently do.
className = [classNameProp, isActive ? "active" : null, isPending ? "pending" : null].filter(Boolean).join(" ");
}
let style = typeof styleProp === "function" ? styleProp({
isActive,
isPending
}) : styleProp;
return /*#__PURE__*/React.createElement(Link, _extends({}, rest, {
"aria-current": ariaCurrent,
className: className,
ref: ref,
style: style,
to: to
}), typeof children === "function" ? children({
isActive,
isPending
}) : children);
});
if (process.env.NODE_ENV !== "production") {
NavLink.displayName = "NavLink";
}
/**
* A `@remix-run/router`-aware `<form>`. It behaves like a normal form except
* that the interaction with the server is with `fetch` instead of new document
* requests, allowing components to add nicer UX to the page as the form is
* submitted and returns with data.
*/
const Form = /*#__PURE__*/React.forwardRef((props, ref) => {
return /*#__PURE__*/React.createElement(FormImpl, _extends({}, props, {
ref: ref
}));
});
if (process.env.NODE_ENV !== "production") {
Form.displayName = "Form";
}
const FormImpl = /*#__PURE__*/React.forwardRef((_ref6, forwardedRef) => {
let {
reloadDocument,
replace,
method = defaultMethod,
action,
onSubmit,
fetcherKey,
routeId,
relative,
preventScrollReset
} = _ref6,
props = _objectWithoutPropertiesLoose(_ref6, _excluded3);
let submit = useSubmitImpl(fetcherKey, routeId);
let formMethod = method.toLowerCase() === "get" ? "get" : "post";
let formAction = useFormAction(action, {
relative
});
let submitHandler = event => {
onSubmit && onSubmit(event);
if (event.defaultPrevented) return;
event.preventDefault();
let submitter = event.nativeEvent.submitter;
let submitMethod = (submitter == null ? void 0 : submitter.getAttribute("formmethod")) || method;
submit(submitter || event.currentTarget, {
method: submitMethod,
replace,
relative,
preventScrollReset
});
};
return /*#__PURE__*/React.createElement("form", _extends({
ref: forwardedRef,
method: formMethod,
action: formAction,
onSubmit: reloadDocument ? onSubmit : submitHandler
}, props));
});
if (process.env.NODE_ENV !== "production") {
FormImpl.displayName = "FormImpl";
}
/**
* This component will emulate the browser's scroll restoration on location
* changes.
*/
function ScrollRestoration(_ref7) {
let {
getKey,
storageKey
} = _ref7;
useScrollRestoration({
getKey,
storageKey
});
return null;
}
if (process.env.NODE_ENV !== "production") {
ScrollRestoration.displayName = "ScrollRestoration";
} //#endregion
////////////////////////////////////////////////////////////////////////////////
//#region Hooks
////////////////////////////////////////////////////////////////////////////////
var DataRouterHook;
(function (DataRouterHook) {
DataRouterHook["UseScrollRestoration"] = "useScrollRestoration";
DataRouterHook["UseSubmitImpl"] = "useSubmitImpl";
DataRouterHook["UseFetcher"] = "useFetcher";
})(DataRouterHook || (DataRouterHook = {}));
var DataRouterStateHook;
(function (DataRouterStateHook) {
DataRouterStateHook["UseFetchers"] = "useFetchers";
DataRouterStateHook["UseScrollRestoration"] = "useScrollRestoration";
})(DataRouterStateHook || (DataRouterStateHook = {}));
function getDataRouterConsoleError(hookName) {
return hookName + " must be used within a data router. See https://reactrouter.com/routers/picking-a-router.";
}
function useDataRouterContext(hookName) {
let ctx = React.useContext(UNSAFE_DataRouterContext);
!ctx ? process.env.NODE_ENV !== "production" ? invariant(false, getDataRouterConsoleError(hookName)) : invariant(false) : void 0;
return ctx;
}
function useDataRouterState(hookName) {
let state = React.useContext(UNSAFE_DataRouterStateContext);
!state ? process.env.NODE_ENV !== "production" ? invariant(false, getDataRouterConsoleError(hookName)) : invariant(false) : void 0;
return state;
}
/**
* Handles the click behavior for router `<Link>` components. This is useful if
* you need to create custom `<Link>` components with the same click behavior we
* use in our exported `<Link>`.
*/
function useLinkClickHandler(to, _temp) {
let {
target,
replace: replaceProp,
state,
preventScrollReset,
relative
} = _temp === void 0 ? {} : _temp;
let navigate = useNavigate();
let location = useLocation();
let path = useResolvedPath(to, {
relative
});
return React.useCallback(event => {
if (shouldProcessLinkClick(event, target)) {
event.preventDefault(); // If the URL hasn't changed, a regular <a> will do a replace instead of
// a push, so do the same here unless the replace prop is explicitly set
let replace = replaceProp !== undefined ? replaceProp : createPath(location) === createPath(path);
navigate(to, {
replace,
state,
preventScrollReset,
relative
});
}
}, [location, navigate, path, replaceProp, state, target, to, preventScrollReset, relative]);
}
/**
* A convenient wrapper for reading and writing search parameters via the
* URLSearchParams interface.
*/
function useSearchParams(defaultInit) {
process.env.NODE_ENV !== "production" ? warning(typeof URLSearchParams !== "undefined", "You cannot use the `useSearchParams` hook in a browser that does not " + "support the URLSearchParams API. If you need to support Internet " + "Explorer 11, we recommend you load a polyfill such as " + "https://github.com/ungap/url-search-params\n\n" + "If you're unsure how to load polyfills, we recommend you check out " + "https://polyfill.io/v3/ which provides some recommendations about how " + "to load polyfills only for users that need them, instead of for every " + "user.") : void 0;
let defaultSearchParamsRef = React.useRef(createSearchParams(defaultInit));
let location = useLocation();
let searchParams = React.useMemo(() => getSearchParamsForLocation(location.search, defaultSearchParamsRef.current), [location.search]);
let navigate = useNavigate();
let setSearchParams = React.useCallback((nextInit, navigateOptions) => {
const newSearchParams = createSearchParams(typeof nextInit === "function" ? nextInit(searchParams) : nextInit);
navigate("?" + newSearchParams, navigateOptions);
}, [navigate, searchParams]);
return [searchParams, setSearchParams];
}
/**
* Returns a function that may be used to programmatically submit a form (or
* some arbitrary data) to the server.
*/
function useSubmit() {
return useSubmitImpl();
}
function useSubmitImpl(fetcherKey, routeId) {
let {
router
} = useDataRouterContext(DataRouterHook.UseSubmitImpl);
let defaultAction = useFormAction();
return React.useCallback(function (target, options) {
if (options === void 0) {
options = {};
}
if (typeof document === "undefined") {
throw new Error("You are calling submit during the server render. " + "Try calling submit within a `useEffect` or callback instead.");
}
let {
method,
encType,
formData,
url
} = getFormSubmissionInfo(target, defaultAction, options);
let href = url.pathname + url.search;
let opts = {
replace: options.replace,
preventScrollReset: options.preventScrollReset,
formData,
formMethod: method,
formEncType: encType
};
if (fetcherKey) {
!(routeId != null) ? process.env.NODE_ENV !== "production" ? invariant(false, "No routeId available for useFetcher()") : invariant(false) : void 0;
router.fetch(fetcherKey, routeId, href, opts);
} else {
router.navigate(href, opts);
}
}, [defaultAction, router, fetcherKey, routeId]);
}
function useFormAction(action, _temp2) {
let {
relative
} = _temp2 === void 0 ? {} : _temp2;
let {
basename
} = React.useContext(UNSAFE_NavigationContext);
let routeContext = React.useContext(UNSAFE_RouteContext);
!routeContext ? process.env.NODE_ENV !== "production" ? invariant(false, "useFormAction must be used inside a RouteContext") : invariant(false) : void 0;
let [match] = routeContext.matches.slice(-1); // Shallow clone path so we can modify it below, otherwise we modify the
// object referenced by useMemo inside useResolvedPath
let path = _extends({}, useResolvedPath(action ? action : ".", {
relative
})); // Previously we set the default action to ".". The problem with this is that
// `useResolvedPath(".")` excludes search params and the hash of the resolved
// URL. This is the intended behavior of when "." is specifically provided as
// the form action, but inconsistent w/ browsers when the action is omitted.
// https://github.com/remix-run/remix/issues/927
let location = useLocation();
if (action == null) {
// Safe to write to these directly here since if action was undefined, we
// would have called useResolvedPath(".") which will never include a search
// or hash
path.search = location.search;
path.hash = location.hash; // When grabbing search params from the URL, remove the automatically
// inserted ?index param so we match the useResolvedPath search behavior
// which would not include ?index
if (match.route.index) {
let params = new URLSearchParams(path.search);
params.delete("index");
path.search = params.toString() ? "?" + params.toString() : "";
}
}
if ((!action || action === ".") && match.route.index) {
path.search = path.search ? path.search.replace(/^\?/, "?index&") : "?index";
} // If we're operating within a basename, prepend it to the pathname prior
// to creating the form action. If this is a root navigation, then just use
// the raw basename which allows the basename to have full control over the
// presence of a trailing slash on root actions
if (basename !== "/") {
path.pathname = path.pathname === "/" ? basename : joinPaths([basename, path.pathname]);
}
return createPath(path);
}
function createFetcherForm(fetcherKey, routeId) {
let FetcherForm = /*#__PURE__*/React.forwardRef((props, ref) => {
return /*#__PURE__*/React.createElement(FormImpl, _extends({}, props, {
ref: ref,
fetcherKey: fetcherKey,
routeId: routeId
}));
});
if (process.env.NODE_ENV !== "production") {
FetcherForm.displayName = "fetcher.Form";
}
return FetcherForm;
}
let fetcherId = 0;
/**
* Interacts with route loaders and actions without causing a navigation. Great
* for any interaction that stays on the same page.
*/
function useFetcher() {
var _route$matches;
let {
router
} = useDataRouterContext(DataRouterHook.UseFetcher);
let route = React.useContext(UNSAFE_RouteContext);
!route ? process.env.NODE_ENV !== "production" ? invariant(false, "useFetcher must be used inside a RouteContext") : invariant(false) : void 0;
let routeId = (_route$matches = route.matches[route.matches.length - 1]) == null ? void 0 : _route$matches.route.id;
!(routeId != null) ? process.env.NODE_ENV !== "production" ? invariant(false, "useFetcher can only be used on routes that contain a unique \"id\"") : invariant(false) : void 0;
let [fetcherKey] = React.useState(() => String(++fetcherId));
let [Form] = React.useState(() => {
!routeId ? process.env.NODE_ENV !== "production" ? invariant(false, "No routeId available for fetcher.Form()") : invariant(false) : void 0;
return createFetcherForm(fetcherKey, routeId);
});
let [load] = React.useState(() => href => {
!router ? process.env.NODE_ENV !== "production" ? invariant(false, "No router available for fetcher.load()") : invariant(false) : void 0;
!routeId ? process.env.NODE_ENV !== "production" ? invariant(false, "No routeId available for fetcher.load()") : invariant(false) : void 0;
router.fetch(fetcherKey, routeId, href);
});
let submit = useSubmitImpl(fetcherKey, routeId);
let fetcher = router.getFetcher(fetcherKey);
let fetcherWithComponents = React.useMemo(() => _extends({
Form,
submit,
load
}, fetcher), [fetcher, Form, submit, load]);
React.useEffect(() => {
// Is this busted when the React team gets real weird and calls effects
// twice on mount? We really just need to garbage collect here when this
// fetcher is no longer around.
return () => {
if (!router) {
console.warn("No fetcher available to clean up from useFetcher()");
return;
}
router.deleteFetcher(fetcherKey);
};
}, [router, fetcherKey]);
return fetcherWithComponents;
}
/**
* Provides all fetchers currently on the page. Useful for layouts and parent
* routes that need to provide pending/optimistic UI regarding the fetch.
*/
function useFetchers() {
let state = useDataRouterState(DataRouterStateHook.UseFetchers);
return [...state.fetchers.values()];
}
const SCROLL_RESTORATION_STORAGE_KEY = "react-router-scroll-positions";
let savedScrollPositions = {};
/**
* When rendered inside a RouterProvider, will restore scroll positions on navigations
*/
function useScrollRestoration(_temp3) {
let {
getKey,
storageKey
} = _temp3 === void 0 ? {} : _temp3;
let {
router
} = useDataRouterContext(DataRouterHook.UseScrollRestoration);
let {
restoreScrollPosition,
preventScrollReset
} = useDataRouterState(DataRouterStateHook.UseScrollRestoration);
let location = useLocation();
let matches = useMatches();
let navigation = useNavigation(); // Trigger manual scroll restoration while we're active
React.useEffect(() => {
window.history.scrollRestoration = "manual";
return () => {
window.history.scrollRestoration = "auto";
};
}, []); // Save positions on unload
useBeforeUnload(React.useCallback(() => {
if (navigation.state === "idle") {
let key = (getKey ? getKey(location, matches) : null) || location.key;
savedScrollPositions[key] = window.scrollY;
}
sessionStorage.setItem(storageKey || SCROLL_RESTORATION_STORAGE_KEY, JSON.stringify(savedScrollPositions));
window.history.scrollRestoration = "auto";
}, [storageKey, getKey, navigation.state, location, matches])); // Read in any saved scroll locations
if (typeof document !== "undefined") {
// eslint-disable-next-line react-hooks/rules-of-hooks
React.useLayoutEffect(() => {
try {
let sessionPositions = sessionStorage.getItem(storageKey || SCROLL_RESTORATION_STORAGE_KEY);
if (sessionPositions) {
savedScrollPositions = JSON.parse(sessionPositions);
}
} catch (e) {// no-op, use default empty object
}
}, [storageKey]); // Enable scroll restoration in the router
// eslint-disable-next-line react-hooks/rules-of-hooks
React.useLayoutEffect(() => {
let disableScrollRestoration = router == null ? void 0 : router.enableScrollRestoration(savedScrollPositions, () => window.scrollY, getKey);
return () => disableScrollRestoration && disableScrollRestoration();
}, [router, getKey]); // Restore scrolling when state.restoreScrollPosition changes
// eslint-disable-next-line react-hooks/rules-of-hooks
React.useLayoutEffect(() => {
// Explicit false means don't do anything (used for submissions)
if (restoreScrollPosition === false) {
return;
} // been here before, scroll to it
if (typeof restoreScrollPosition === "number") {
window.scrollTo(0, restoreScrollPosition);
return;
} // try to scroll to the hash
if (location.hash) {
let el = document.getElementById(location.hash.slice(1));
if (el) {
el.scrollIntoView();
return;
}
} // Don't reset if this navigation opted out
if (preventScrollReset === true) {
return;
} // otherwise go to the top on new locations
window.scrollTo(0, 0);
}, [location, restoreScrollPosition, preventScrollReset]);
}
}
/**
* Setup a callback to be fired on the window's `beforeunload` event. This is
* useful for saving some data to `window.localStorage` just before the page
* refreshes.
*
* Note: The `callback` argument should be a function created with
* `React.useCallback()`.
*/
function useBeforeUnload(callback, options) {
let {
capture
} = options || {};
React.useEffect(() => {
let opts = capture != null ? {
capture
} : undefined;
window.addEventListener("beforeunload", callback, opts);
return () => {
window.removeEventListener("beforeunload", callback, opts);
};
}, [callback, capture]);
}
/**
* Wrapper around useBlocker to show a window.confirm prompt to users instead
* of building a custom UI with useBlocker.
*
* Warning: This has *a lot of rough edges* and behaves very differently (and
* very incorrectly in some cases) across browsers if user click addition
* back/forward navigations while the confirm is open. Use at your own risk.
*/
function usePrompt(_ref8) {
let {
when,
message
} = _ref8;
let blocker = unstable_useBlocker(when);
React.useEffect(() => {
if (blocker.state === "blocked" && !when) {
blocker.reset();
}
}, [blocker, when]);
React.useEffect(() => {
if (blocker.state === "blocked") {
let proceed = window.confirm(message);
if (proceed) {
setTimeout(blocker.proceed, 0);
} else {
blocker.reset();
}
}
}, [blocker, message]);
}
////////////////////////////////////////////////////////////////////////////////
//#region Utils
////////////////////////////////////////////////////////////////////////////////
function warning(cond, message) {
if (!cond) {
// eslint-disable-next-line no-console
if (typeof console !== "undefined") console.warn(message);
try {
// Welcome to debugging React Router!
//
// This error is thrown as a convenience so you can more easily
// find the source for a warning that appears in the console by
// enabling "pause on exceptions" in your JavaScript debugger.
throw new Error(message); // eslint-disable-next-line no-empty
} catch (e) {}
}
} //#endregion
export { BrowserRouter, Form, HashRouter, Link, NavLink, ScrollRestoration, useScrollRestoration as UNSAFE_useScrollRestoration, createBrowserRouter, createHashRouter, createSearchParams, HistoryRouter as unstable_HistoryRouter, usePrompt as unstable_usePrompt, useBeforeUnload, useFetcher, useFetchers, useFormAction, useLinkClickHandler, useSearchParams, useSubmit };
//# sourceMappingURL=index.js.map

1
node_modules/react-router-dom/dist/index.js.map generated vendored Normal file

File diff suppressed because one or more lines are too long

19
node_modules/react-router-dom/dist/main.js generated vendored Normal file
View File

@ -0,0 +1,19 @@
/**
* React Router DOM v6.7.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
*/
'use strict';
/* eslint-env node */
if (process.env.NODE_ENV === "production") {
module.exports = require("./umd/react-router-dom.production.min.js");
} else {
module.exports = require("./umd/react-router-dom.development.js");
}

View File

@ -0,0 +1,934 @@
/**
* React Router DOM v6.7.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 * as React from 'react';
import { UNSAFE_enhanceManualRouteObjects, Router, useHref, useResolvedPath, useLocation, UNSAFE_DataRouterStateContext, UNSAFE_NavigationContext, useNavigate, createPath, UNSAFE_RouteContext, useMatches, useNavigation, unstable_useBlocker, UNSAFE_DataRouterContext } from 'react-router';
export { AbortedDeferredError, Await, MemoryRouter, Navigate, NavigationType, Outlet, Route, Router, RouterProvider, Routes, UNSAFE_DataRouterContext, UNSAFE_DataRouterStateContext, UNSAFE_LocationContext, UNSAFE_NavigationContext, UNSAFE_RouteContext, UNSAFE_enhanceManualRouteObjects, createMemoryRouter, createPath, createRoutesFromChildren, createRoutesFromElements, defer, generatePath, isRouteErrorResponse, json, matchPath, matchRoutes, parsePath, redirect, renderMatches, resolvePath, unstable_useBlocker, useActionData, useAsyncError, useAsyncValue, useHref, useInRouterContext, useLoaderData, useLocation, useMatch, useMatches, useNavigate, useNavigation, useNavigationType, useOutlet, useOutletContext, useParams, useResolvedPath, useRevalidator, useRouteError, useRouteLoaderData, useRoutes } from 'react-router';
import { createRouter, createBrowserHistory, createHashHistory, ErrorResponse, invariant, joinPaths } from '@remix-run/router';
const defaultMethod = "get";
const defaultEncType = "application/x-www-form-urlencoded";
function isHtmlElement(object) {
return object != null && typeof object.tagName === "string";
}
function isButtonElement(object) {
return isHtmlElement(object) && object.tagName.toLowerCase() === "button";
}
function isFormElement(object) {
return isHtmlElement(object) && object.tagName.toLowerCase() === "form";
}
function isInputElement(object) {
return isHtmlElement(object) && object.tagName.toLowerCase() === "input";
}
function isModifiedEvent(event) {
return !!(event.metaKey || event.altKey || event.ctrlKey || event.shiftKey);
}
function shouldProcessLinkClick(event, target) {
return event.button === 0 && ( // Ignore everything but left clicks
!target || target === "_self") && // Let browser handle "target=_blank" etc.
!isModifiedEvent(event) // Ignore clicks with modifier keys
;
}
/**
* Creates a URLSearchParams object using the given initializer.
*
* This is identical to `new URLSearchParams(init)` except it also
* supports arrays as values in the object form of the initializer
* instead of just strings. This is convenient when you need multiple
* values for a given key, but don't want to use an array initializer.
*
* For example, instead of:
*
* let searchParams = new URLSearchParams([
* ['sort', 'name'],
* ['sort', 'price']
* ]);
*
* you can do:
*
* let searchParams = createSearchParams({
* sort: ['name', 'price']
* });
*/
function createSearchParams(init = "") {
return new URLSearchParams(typeof init === "string" || Array.isArray(init) || init instanceof URLSearchParams ? init : Object.keys(init).reduce((memo, key) => {
let value = init[key];
return memo.concat(Array.isArray(value) ? value.map(v => [key, v]) : [[key, value]]);
}, []));
}
function getSearchParamsForLocation(locationSearch, defaultSearchParams) {
let searchParams = createSearchParams(locationSearch);
for (let key of defaultSearchParams.keys()) {
if (!searchParams.has(key)) {
defaultSearchParams.getAll(key).forEach(value => {
searchParams.append(key, value);
});
}
}
return searchParams;
}
function getFormSubmissionInfo(target, defaultAction, options) {
let method;
let action;
let encType;
let formData;
if (isFormElement(target)) {
let submissionTrigger = options.submissionTrigger;
method = options.method || target.getAttribute("method") || defaultMethod;
action = options.action || target.getAttribute("action") || defaultAction;
encType = options.encType || target.getAttribute("enctype") || defaultEncType;
formData = new FormData(target);
if (submissionTrigger && submissionTrigger.name) {
formData.append(submissionTrigger.name, submissionTrigger.value);
}
} else if (isButtonElement(target) || isInputElement(target) && (target.type === "submit" || target.type === "image")) {
let form = target.form;
if (form == null) {
throw new Error(`Cannot submit a <button> or <input type="submit"> without a <form>`);
} // <button>/<input type="submit"> may override attributes of <form>
method = options.method || target.getAttribute("formmethod") || form.getAttribute("method") || defaultMethod;
action = options.action || target.getAttribute("formaction") || form.getAttribute("action") || defaultAction;
encType = options.encType || target.getAttribute("formenctype") || form.getAttribute("enctype") || defaultEncType;
formData = new FormData(form); // Include name + value from a <button>, appending in case the button name
// matches an existing input name
if (target.name) {
formData.append(target.name, target.value);
}
} else if (isHtmlElement(target)) {
throw new Error(`Cannot submit element that is not <form>, <button>, or ` + `<input type="submit|image">`);
} else {
method = options.method || defaultMethod;
action = options.action || defaultAction;
encType = options.encType || defaultEncType;
if (target instanceof FormData) {
formData = target;
} else {
formData = new FormData();
if (target instanceof URLSearchParams) {
for (let [name, value] of target) {
formData.append(name, value);
}
} else if (target != null) {
for (let name of Object.keys(target)) {
formData.append(name, target[name]);
}
}
}
}
let {
protocol,
host
} = window.location;
let url = new URL(action, `${protocol}//${host}`);
return {
url,
method: method.toLowerCase(),
encType,
formData
};
}
/**
* NOTE: If you refactor this to split up the modules into separate files,
* you'll need to update the rollup config for react-router-dom-v5-compat.
*/
////////////////////////////////////////////////////////////////////////////////
//#region Routers
////////////////////////////////////////////////////////////////////////////////
function createBrowserRouter(routes, opts) {
return createRouter({
basename: opts?.basename,
history: createBrowserHistory({
window: opts?.window
}),
hydrationData: opts?.hydrationData || parseHydrationData(),
routes: UNSAFE_enhanceManualRouteObjects(routes)
}).initialize();
}
function createHashRouter(routes, opts) {
return createRouter({
basename: opts?.basename,
history: createHashHistory({
window: opts?.window
}),
hydrationData: opts?.hydrationData || parseHydrationData(),
routes: UNSAFE_enhanceManualRouteObjects(routes)
}).initialize();
}
function parseHydrationData() {
let state = window?.__staticRouterHydrationData;
if (state && state.errors) {
state = { ...state,
errors: deserializeErrors(state.errors)
};
}
return state;
}
function deserializeErrors(errors) {
if (!errors) return null;
let entries = Object.entries(errors);
let serialized = {};
for (let [key, val] of entries) {
// Hey you! If you change this, please change the corresponding logic in
// serializeErrors in react-router-dom/server.tsx :)
if (val && val.__type === "RouteErrorResponse") {
serialized[key] = new ErrorResponse(val.status, val.statusText, val.data, val.internal === true);
} else if (val && val.__type === "Error") {
let error = new Error(val.message); // Wipe away the client-side stack trace. Nothing to fill it in with
// because we don't serialize SSR stack traces for security reasons
error.stack = "";
serialized[key] = error;
} else {
serialized[key] = val;
}
}
return serialized;
} //#endregion
////////////////////////////////////////////////////////////////////////////////
//#region Components
////////////////////////////////////////////////////////////////////////////////
/**
* A `<Router>` for use in web browsers. Provides the cleanest URLs.
*/
function BrowserRouter({
basename,
children,
window
}) {
let historyRef = React.useRef();
if (historyRef.current == null) {
historyRef.current = createBrowserHistory({
window,
v5Compat: true
});
}
let history = historyRef.current;
let [state, setState] = React.useState({
action: history.action,
location: history.location
});
React.useLayoutEffect(() => history.listen(setState), [history]);
return /*#__PURE__*/React.createElement(Router, {
basename: basename,
children: children,
location: state.location,
navigationType: state.action,
navigator: history
});
}
/**
* A `<Router>` for use in web browsers. Stores the location in the hash
* portion of the URL so it is not sent to the server.
*/
function HashRouter({
basename,
children,
window
}) {
let historyRef = React.useRef();
if (historyRef.current == null) {
historyRef.current = createHashHistory({
window,
v5Compat: true
});
}
let history = historyRef.current;
let [state, setState] = React.useState({
action: history.action,
location: history.location
});
React.useLayoutEffect(() => history.listen(setState), [history]);
return /*#__PURE__*/React.createElement(Router, {
basename: basename,
children: children,
location: state.location,
navigationType: state.action,
navigator: history
});
}
/**
* A `<Router>` that accepts a pre-instantiated history object. It's important
* to note that using your own history object is highly discouraged and may add
* two versions of the history library to your bundles unless you use the same
* version of the history library that React Router uses internally.
*/
function HistoryRouter({
basename,
children,
history
}) {
const [state, setState] = React.useState({
action: history.action,
location: history.location
});
React.useLayoutEffect(() => history.listen(setState), [history]);
return /*#__PURE__*/React.createElement(Router, {
basename: basename,
children: children,
location: state.location,
navigationType: state.action,
navigator: history
});
}
{
HistoryRouter.displayName = "unstable_HistoryRouter";
}
/**
* The public API for rendering a history-aware <a>.
*/
const Link = /*#__PURE__*/React.forwardRef(function LinkWithRef({
onClick,
relative,
reloadDocument,
replace,
state,
target,
to,
preventScrollReset,
...rest
}, ref) {
let href = useHref(to, {
relative
});
let internalOnClick = useLinkClickHandler(to, {
replace,
state,
target,
preventScrollReset,
relative
});
function handleClick(event) {
if (onClick) onClick(event);
if (!event.defaultPrevented) {
internalOnClick(event);
}
}
return (
/*#__PURE__*/
// eslint-disable-next-line jsx-a11y/anchor-has-content
React.createElement("a", Object.assign({}, rest, {
href: href,
onClick: reloadDocument ? onClick : handleClick,
ref: ref,
target: target
}))
);
});
{
Link.displayName = "Link";
}
/**
* A <Link> wrapper that knows if it's "active" or not.
*/
const NavLink = /*#__PURE__*/React.forwardRef(function NavLinkWithRef({
"aria-current": ariaCurrentProp = "page",
caseSensitive = false,
className: classNameProp = "",
end = false,
style: styleProp,
to,
children,
...rest
}, ref) {
let path = useResolvedPath(to, {
relative: rest.relative
});
let location = useLocation();
let routerState = React.useContext(UNSAFE_DataRouterStateContext);
let {
navigator
} = React.useContext(UNSAFE_NavigationContext);
let toPathname = navigator.encodeLocation ? navigator.encodeLocation(path).pathname : path.pathname;
let locationPathname = location.pathname;
let nextLocationPathname = routerState && routerState.navigation && routerState.navigation.location ? routerState.navigation.location.pathname : null;
if (!caseSensitive) {
locationPathname = locationPathname.toLowerCase();
nextLocationPathname = nextLocationPathname ? nextLocationPathname.toLowerCase() : null;
toPathname = toPathname.toLowerCase();
}
let isActive = locationPathname === toPathname || !end && locationPathname.startsWith(toPathname) && locationPathname.charAt(toPathname.length) === "/";
let isPending = nextLocationPathname != null && (nextLocationPathname === toPathname || !end && nextLocationPathname.startsWith(toPathname) && nextLocationPathname.charAt(toPathname.length) === "/");
let ariaCurrent = isActive ? ariaCurrentProp : undefined;
let className;
if (typeof classNameProp === "function") {
className = classNameProp({
isActive,
isPending
});
} else {
// If the className prop is not a function, we use a default `active`
// class for <NavLink />s that are active. In v5 `active` was the default
// value for `activeClassName`, but we are removing that API and can still
// use the old default behavior for a cleaner upgrade path and keep the
// simple styling rules working as they currently do.
className = [classNameProp, isActive ? "active" : null, isPending ? "pending" : null].filter(Boolean).join(" ");
}
let style = typeof styleProp === "function" ? styleProp({
isActive,
isPending
}) : styleProp;
return /*#__PURE__*/React.createElement(Link, Object.assign({}, rest, {
"aria-current": ariaCurrent,
className: className,
ref: ref,
style: style,
to: to
}), typeof children === "function" ? children({
isActive,
isPending
}) : children);
});
{
NavLink.displayName = "NavLink";
}
/**
* A `@remix-run/router`-aware `<form>`. It behaves like a normal form except
* that the interaction with the server is with `fetch` instead of new document
* requests, allowing components to add nicer UX to the page as the form is
* submitted and returns with data.
*/
const Form = /*#__PURE__*/React.forwardRef((props, ref) => {
return /*#__PURE__*/React.createElement(FormImpl, Object.assign({}, props, {
ref: ref
}));
});
{
Form.displayName = "Form";
}
const FormImpl = /*#__PURE__*/React.forwardRef(({
reloadDocument,
replace,
method: _method = defaultMethod,
action,
onSubmit,
fetcherKey,
routeId,
relative,
preventScrollReset,
...props
}, forwardedRef) => {
let submit = useSubmitImpl(fetcherKey, routeId);
let formMethod = _method.toLowerCase() === "get" ? "get" : "post";
let formAction = useFormAction(action, {
relative
});
let submitHandler = event => {
onSubmit && onSubmit(event);
if (event.defaultPrevented) return;
event.preventDefault();
let submitter = event.nativeEvent.submitter;
let submitMethod = submitter?.getAttribute("formmethod") || _method;
submit(submitter || event.currentTarget, {
method: submitMethod,
replace,
relative,
preventScrollReset
});
};
return /*#__PURE__*/React.createElement("form", Object.assign({
ref: forwardedRef,
method: formMethod,
action: formAction,
onSubmit: reloadDocument ? onSubmit : submitHandler
}, props));
});
{
FormImpl.displayName = "FormImpl";
}
/**
* This component will emulate the browser's scroll restoration on location
* changes.
*/
function ScrollRestoration({
getKey,
storageKey
}) {
useScrollRestoration({
getKey,
storageKey
});
return null;
}
{
ScrollRestoration.displayName = "ScrollRestoration";
} //#endregion
////////////////////////////////////////////////////////////////////////////////
//#region Hooks
////////////////////////////////////////////////////////////////////////////////
var DataRouterHook;
(function (DataRouterHook) {
DataRouterHook["UseScrollRestoration"] = "useScrollRestoration";
DataRouterHook["UseSubmitImpl"] = "useSubmitImpl";
DataRouterHook["UseFetcher"] = "useFetcher";
})(DataRouterHook || (DataRouterHook = {}));
var DataRouterStateHook;
(function (DataRouterStateHook) {
DataRouterStateHook["UseFetchers"] = "useFetchers";
DataRouterStateHook["UseScrollRestoration"] = "useScrollRestoration";
})(DataRouterStateHook || (DataRouterStateHook = {}));
function getDataRouterConsoleError(hookName) {
return `${hookName} must be used within a data router. See https://reactrouter.com/routers/picking-a-router.`;
}
function useDataRouterContext(hookName) {
let ctx = React.useContext(UNSAFE_DataRouterContext);
!ctx ? invariant(false, getDataRouterConsoleError(hookName)) : void 0;
return ctx;
}
function useDataRouterState(hookName) {
let state = React.useContext(UNSAFE_DataRouterStateContext);
!state ? invariant(false, getDataRouterConsoleError(hookName)) : void 0;
return state;
}
/**
* Handles the click behavior for router `<Link>` components. This is useful if
* you need to create custom `<Link>` components with the same click behavior we
* use in our exported `<Link>`.
*/
function useLinkClickHandler(to, {
target,
replace: replaceProp,
state,
preventScrollReset,
relative
} = {}) {
let navigate = useNavigate();
let location = useLocation();
let path = useResolvedPath(to, {
relative
});
return React.useCallback(event => {
if (shouldProcessLinkClick(event, target)) {
event.preventDefault(); // If the URL hasn't changed, a regular <a> will do a replace instead of
// a push, so do the same here unless the replace prop is explicitly set
let replace = replaceProp !== undefined ? replaceProp : createPath(location) === createPath(path);
navigate(to, {
replace,
state,
preventScrollReset,
relative
});
}
}, [location, navigate, path, replaceProp, state, target, to, preventScrollReset, relative]);
}
/**
* A convenient wrapper for reading and writing search parameters via the
* URLSearchParams interface.
*/
function useSearchParams(defaultInit) {
warning(typeof URLSearchParams !== "undefined", `You cannot use the \`useSearchParams\` hook in a browser that does not ` + `support the URLSearchParams API. If you need to support Internet ` + `Explorer 11, we recommend you load a polyfill such as ` + `https://github.com/ungap/url-search-params\n\n` + `If you're unsure how to load polyfills, we recommend you check out ` + `https://polyfill.io/v3/ which provides some recommendations about how ` + `to load polyfills only for users that need them, instead of for every ` + `user.`) ;
let defaultSearchParamsRef = React.useRef(createSearchParams(defaultInit));
let location = useLocation();
let searchParams = React.useMemo(() => getSearchParamsForLocation(location.search, defaultSearchParamsRef.current), [location.search]);
let navigate = useNavigate();
let setSearchParams = React.useCallback((nextInit, navigateOptions) => {
const newSearchParams = createSearchParams(typeof nextInit === "function" ? nextInit(searchParams) : nextInit);
navigate("?" + newSearchParams, navigateOptions);
}, [navigate, searchParams]);
return [searchParams, setSearchParams];
}
/**
* Returns a function that may be used to programmatically submit a form (or
* some arbitrary data) to the server.
*/
function useSubmit() {
return useSubmitImpl();
}
function useSubmitImpl(fetcherKey, routeId) {
let {
router
} = useDataRouterContext(DataRouterHook.UseSubmitImpl);
let defaultAction = useFormAction();
return React.useCallback((target, options = {}) => {
if (typeof document === "undefined") {
throw new Error("You are calling submit during the server render. " + "Try calling submit within a `useEffect` or callback instead.");
}
let {
method,
encType,
formData,
url
} = getFormSubmissionInfo(target, defaultAction, options);
let href = url.pathname + url.search;
let opts = {
replace: options.replace,
preventScrollReset: options.preventScrollReset,
formData,
formMethod: method,
formEncType: encType
};
if (fetcherKey) {
!(routeId != null) ? invariant(false, "No routeId available for useFetcher()") : void 0;
router.fetch(fetcherKey, routeId, href, opts);
} else {
router.navigate(href, opts);
}
}, [defaultAction, router, fetcherKey, routeId]);
}
function useFormAction(action, {
relative
} = {}) {
let {
basename
} = React.useContext(UNSAFE_NavigationContext);
let routeContext = React.useContext(UNSAFE_RouteContext);
!routeContext ? invariant(false, "useFormAction must be used inside a RouteContext") : void 0;
let [match] = routeContext.matches.slice(-1); // Shallow clone path so we can modify it below, otherwise we modify the
// object referenced by useMemo inside useResolvedPath
let path = { ...useResolvedPath(action ? action : ".", {
relative
})
}; // Previously we set the default action to ".". The problem with this is that
// `useResolvedPath(".")` excludes search params and the hash of the resolved
// URL. This is the intended behavior of when "." is specifically provided as
// the form action, but inconsistent w/ browsers when the action is omitted.
// https://github.com/remix-run/remix/issues/927
let location = useLocation();
if (action == null) {
// Safe to write to these directly here since if action was undefined, we
// would have called useResolvedPath(".") which will never include a search
// or hash
path.search = location.search;
path.hash = location.hash; // When grabbing search params from the URL, remove the automatically
// inserted ?index param so we match the useResolvedPath search behavior
// which would not include ?index
if (match.route.index) {
let params = new URLSearchParams(path.search);
params.delete("index");
path.search = params.toString() ? `?${params.toString()}` : "";
}
}
if ((!action || action === ".") && match.route.index) {
path.search = path.search ? path.search.replace(/^\?/, "?index&") : "?index";
} // If we're operating within a basename, prepend it to the pathname prior
// to creating the form action. If this is a root navigation, then just use
// the raw basename which allows the basename to have full control over the
// presence of a trailing slash on root actions
if (basename !== "/") {
path.pathname = path.pathname === "/" ? basename : joinPaths([basename, path.pathname]);
}
return createPath(path);
}
function createFetcherForm(fetcherKey, routeId) {
let FetcherForm = /*#__PURE__*/React.forwardRef((props, ref) => {
return /*#__PURE__*/React.createElement(FormImpl, Object.assign({}, props, {
ref: ref,
fetcherKey: fetcherKey,
routeId: routeId
}));
});
{
FetcherForm.displayName = "fetcher.Form";
}
return FetcherForm;
}
let fetcherId = 0;
/**
* Interacts with route loaders and actions without causing a navigation. Great
* for any interaction that stays on the same page.
*/
function useFetcher() {
let {
router
} = useDataRouterContext(DataRouterHook.UseFetcher);
let route = React.useContext(UNSAFE_RouteContext);
!route ? invariant(false, `useFetcher must be used inside a RouteContext`) : void 0;
let routeId = route.matches[route.matches.length - 1]?.route.id;
!(routeId != null) ? invariant(false, `useFetcher can only be used on routes that contain a unique "id"`) : void 0;
let [fetcherKey] = React.useState(() => String(++fetcherId));
let [Form] = React.useState(() => {
!routeId ? invariant(false, `No routeId available for fetcher.Form()`) : void 0;
return createFetcherForm(fetcherKey, routeId);
});
let [load] = React.useState(() => href => {
!router ? invariant(false, "No router available for fetcher.load()") : void 0;
!routeId ? invariant(false, "No routeId available for fetcher.load()") : void 0;
router.fetch(fetcherKey, routeId, href);
});
let submit = useSubmitImpl(fetcherKey, routeId);
let fetcher = router.getFetcher(fetcherKey);
let fetcherWithComponents = React.useMemo(() => ({
Form,
submit,
load,
...fetcher
}), [fetcher, Form, submit, load]);
React.useEffect(() => {
// Is this busted when the React team gets real weird and calls effects
// twice on mount? We really just need to garbage collect here when this
// fetcher is no longer around.
return () => {
if (!router) {
console.warn(`No fetcher available to clean up from useFetcher()`);
return;
}
router.deleteFetcher(fetcherKey);
};
}, [router, fetcherKey]);
return fetcherWithComponents;
}
/**
* Provides all fetchers currently on the page. Useful for layouts and parent
* routes that need to provide pending/optimistic UI regarding the fetch.
*/
function useFetchers() {
let state = useDataRouterState(DataRouterStateHook.UseFetchers);
return [...state.fetchers.values()];
}
const SCROLL_RESTORATION_STORAGE_KEY = "react-router-scroll-positions";
let savedScrollPositions = {};
/**
* When rendered inside a RouterProvider, will restore scroll positions on navigations
*/
function useScrollRestoration({
getKey,
storageKey
} = {}) {
let {
router
} = useDataRouterContext(DataRouterHook.UseScrollRestoration);
let {
restoreScrollPosition,
preventScrollReset
} = useDataRouterState(DataRouterStateHook.UseScrollRestoration);
let location = useLocation();
let matches = useMatches();
let navigation = useNavigation(); // Trigger manual scroll restoration while we're active
React.useEffect(() => {
window.history.scrollRestoration = "manual";
return () => {
window.history.scrollRestoration = "auto";
};
}, []); // Save positions on unload
useBeforeUnload(React.useCallback(() => {
if (navigation.state === "idle") {
let key = (getKey ? getKey(location, matches) : null) || location.key;
savedScrollPositions[key] = window.scrollY;
}
sessionStorage.setItem(storageKey || SCROLL_RESTORATION_STORAGE_KEY, JSON.stringify(savedScrollPositions));
window.history.scrollRestoration = "auto";
}, [storageKey, getKey, navigation.state, location, matches])); // Read in any saved scroll locations
if (typeof document !== "undefined") {
// eslint-disable-next-line react-hooks/rules-of-hooks
React.useLayoutEffect(() => {
try {
let sessionPositions = sessionStorage.getItem(storageKey || SCROLL_RESTORATION_STORAGE_KEY);
if (sessionPositions) {
savedScrollPositions = JSON.parse(sessionPositions);
}
} catch (e) {// no-op, use default empty object
}
}, [storageKey]); // Enable scroll restoration in the router
// eslint-disable-next-line react-hooks/rules-of-hooks
React.useLayoutEffect(() => {
let disableScrollRestoration = router?.enableScrollRestoration(savedScrollPositions, () => window.scrollY, getKey);
return () => disableScrollRestoration && disableScrollRestoration();
}, [router, getKey]); // Restore scrolling when state.restoreScrollPosition changes
// eslint-disable-next-line react-hooks/rules-of-hooks
React.useLayoutEffect(() => {
// Explicit false means don't do anything (used for submissions)
if (restoreScrollPosition === false) {
return;
} // been here before, scroll to it
if (typeof restoreScrollPosition === "number") {
window.scrollTo(0, restoreScrollPosition);
return;
} // try to scroll to the hash
if (location.hash) {
let el = document.getElementById(location.hash.slice(1));
if (el) {
el.scrollIntoView();
return;
}
} // Don't reset if this navigation opted out
if (preventScrollReset === true) {
return;
} // otherwise go to the top on new locations
window.scrollTo(0, 0);
}, [location, restoreScrollPosition, preventScrollReset]);
}
}
/**
* Setup a callback to be fired on the window's `beforeunload` event. This is
* useful for saving some data to `window.localStorage` just before the page
* refreshes.
*
* Note: The `callback` argument should be a function created with
* `React.useCallback()`.
*/
function useBeforeUnload(callback, options) {
let {
capture
} = options || {};
React.useEffect(() => {
let opts = capture != null ? {
capture
} : undefined;
window.addEventListener("beforeunload", callback, opts);
return () => {
window.removeEventListener("beforeunload", callback, opts);
};
}, [callback, capture]);
}
/**
* Wrapper around useBlocker to show a window.confirm prompt to users instead
* of building a custom UI with useBlocker.
*
* Warning: This has *a lot of rough edges* and behaves very differently (and
* very incorrectly in some cases) across browsers if user click addition
* back/forward navigations while the confirm is open. Use at your own risk.
*/
function usePrompt({
when,
message
}) {
let blocker = unstable_useBlocker(when);
React.useEffect(() => {
if (blocker.state === "blocked" && !when) {
blocker.reset();
}
}, [blocker, when]);
React.useEffect(() => {
if (blocker.state === "blocked") {
let proceed = window.confirm(message);
if (proceed) {
setTimeout(blocker.proceed, 0);
} else {
blocker.reset();
}
}
}, [blocker, message]);
}
////////////////////////////////////////////////////////////////////////////////
//#region Utils
////////////////////////////////////////////////////////////////////////////////
function warning(cond, message) {
if (!cond) {
// eslint-disable-next-line no-console
if (typeof console !== "undefined") console.warn(message);
try {
// Welcome to debugging React Router!
//
// This error is thrown as a convenience so you can more easily
// find the source for a warning that appears in the console by
// enabling "pause on exceptions" in your JavaScript debugger.
throw new Error(message); // eslint-disable-next-line no-empty
} catch (e) {}
}
} //#endregion
export { BrowserRouter, Form, HashRouter, Link, NavLink, ScrollRestoration, useScrollRestoration as UNSAFE_useScrollRestoration, createBrowserRouter, createHashRouter, createSearchParams, HistoryRouter as unstable_HistoryRouter, usePrompt as unstable_usePrompt, useBeforeUnload, useFetcher, useFetchers, useFormAction, useLinkClickHandler, useSearchParams, useSubmit };
//# sourceMappingURL=react-router-dom.development.js.map

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

25
node_modules/react-router-dom/dist/server.d.ts generated vendored Normal file
View File

@ -0,0 +1,25 @@
import * as React from "react";
import type { Router as RemixRouter, StaticHandlerContext } from "@remix-run/router";
import type { Location, RouteObject } from "react-router-dom";
export interface StaticRouterProps {
basename?: string;
children?: React.ReactNode;
location: Partial<Location> | string;
}
/**
* A <Router> that may not navigate to any other location. This is useful
* on the server where there is no stateful UI.
*/
export declare function StaticRouter({ basename, children, location: locationProp, }: StaticRouterProps): JSX.Element;
export interface StaticRouterProviderProps {
context: StaticHandlerContext;
router: RemixRouter;
hydrate?: boolean;
nonce?: string;
}
/**
* A Data Router that may not navigate to any other location. This is useful
* on the server where there is no stateful UI.
*/
export declare function StaticRouterProvider({ context, router, hydrate, nonce, }: StaticRouterProviderProps): JSX.Element;
export declare function createStaticRouter(routes: RouteObject[], context: StaticHandlerContext): RemixRouter;

293
node_modules/react-router-dom/dist/server.js generated vendored Normal file
View File

@ -0,0 +1,293 @@
'use strict';
Object.defineProperty(exports, '__esModule', { value: true });
var React = require('react');
var router = require('@remix-run/router');
var reactRouterDom = require('react-router-dom');
function _interopNamespace(e) {
if (e && e.__esModule) return e;
var n = Object.create(null);
if (e) {
Object.keys(e).forEach(function (k) {
if (k !== 'default') {
var d = Object.getOwnPropertyDescriptor(e, k);
Object.defineProperty(n, k, d.get ? d : {
enumerable: true,
get: function () { return e[k]; }
});
}
});
}
n["default"] = e;
return Object.freeze(n);
}
var React__namespace = /*#__PURE__*/_interopNamespace(React);
/**
* A <Router> that may not navigate to any other location. This is useful
* on the server where there is no stateful UI.
*/
function StaticRouter({
basename,
children,
location: locationProp = "/"
}) {
if (typeof locationProp === "string") {
locationProp = reactRouterDom.parsePath(locationProp);
}
let action = router.Action.Pop;
let location = {
pathname: locationProp.pathname || "/",
search: locationProp.search || "",
hash: locationProp.hash || "",
state: locationProp.state || null,
key: locationProp.key || "default"
};
let staticNavigator = getStatelessNavigator();
return /*#__PURE__*/React__namespace.createElement(reactRouterDom.Router, {
basename: basename,
children: children,
location: location,
navigationType: action,
navigator: staticNavigator,
static: true
});
}
/**
* A Data Router that may not navigate to any other location. This is useful
* on the server where there is no stateful UI.
*/
function StaticRouterProvider({
context,
router: router$1,
hydrate = true,
nonce
}) {
!(router$1 && context) ? process.env.NODE_ENV !== "production" ? router.invariant(false, "You must provide `router` and `context` to <StaticRouterProvider>") : router.invariant(false) : void 0;
let dataRouterContext = {
router: router$1,
navigator: getStatelessNavigator(),
static: true,
staticContext: context,
basename: context.basename || "/"
};
let hydrateScript = "";
if (hydrate !== false) {
let data = {
loaderData: context.loaderData,
actionData: context.actionData,
errors: serializeErrors(context.errors)
}; // Use JSON.parse here instead of embedding a raw JS object here to speed
// up parsing on the client. Dual-stringify is needed to ensure all quotes
// are properly escaped in the resulting string. See:
// https://v8.dev/blog/cost-of-javascript-2019#json
let json = JSON.stringify(JSON.stringify(data));
hydrateScript = `window.__staticRouterHydrationData = JSON.parse(${json});`;
}
return /*#__PURE__*/React__namespace.createElement(React__namespace.Fragment, null, /*#__PURE__*/React__namespace.createElement(reactRouterDom.UNSAFE_DataRouterContext.Provider, {
value: dataRouterContext
}, /*#__PURE__*/React__namespace.createElement(reactRouterDom.UNSAFE_DataRouterStateContext.Provider, {
value: dataRouterContext.router.state
}, /*#__PURE__*/React__namespace.createElement(reactRouterDom.Router, {
basename: dataRouterContext.basename,
location: dataRouterContext.router.state.location,
navigationType: dataRouterContext.router.state.historyAction,
navigator: dataRouterContext.navigator
}, /*#__PURE__*/React__namespace.createElement(reactRouterDom.Routes, null)))), hydrateScript ? /*#__PURE__*/React__namespace.createElement("script", {
suppressHydrationWarning: true,
nonce: nonce,
dangerouslySetInnerHTML: {
__html: hydrateScript
}
}) : null);
}
function serializeErrors(errors) {
if (!errors) return null;
let entries = Object.entries(errors);
let serialized = {};
for (let [key, val] of entries) {
// Hey you! If you change this, please change the corresponding logic in
// deserializeErrors in react-router-dom/index.tsx :)
if (router.isRouteErrorResponse(val)) {
serialized[key] = { ...val,
__type: "RouteErrorResponse"
};
} else if (val instanceof Error) {
// Do not serialize stack traces from SSR for security reasons
serialized[key] = {
message: val.message,
__type: "Error"
};
} else {
serialized[key] = val;
}
}
return serialized;
}
function getStatelessNavigator() {
return {
createHref,
encodeLocation,
push(to) {
throw new Error(`You cannot use navigator.push() on the server because it is a stateless ` + `environment. This error was probably triggered when you did a ` + `\`navigate(${JSON.stringify(to)})\` somewhere in your app.`);
},
replace(to) {
throw new Error(`You cannot use navigator.replace() on the server because it is a stateless ` + `environment. This error was probably triggered when you did a ` + `\`navigate(${JSON.stringify(to)}, { replace: true })\` somewhere ` + `in your app.`);
},
go(delta) {
throw new Error(`You cannot use navigator.go() on the server because it is a stateless ` + `environment. This error was probably triggered when you did a ` + `\`navigate(${delta})\` somewhere in your app.`);
},
back() {
throw new Error(`You cannot use navigator.back() on the server because it is a stateless ` + `environment.`);
},
forward() {
throw new Error(`You cannot use navigator.forward() on the server because it is a stateless ` + `environment.`);
}
};
} // Temporary manifest generation - we should optimize this by combining the
// tree-walks between convertRoutesToDataRoutes, enhanceManualRouteObjects,
// and generateManifest.
// Also look into getting rid of `route as AgnosticDataRouteObject` down below?
function generateManifest(routes, manifest = new Map()) {
routes.forEach(route => {
manifest.set(route.id, route);
if (route.children) {
generateManifest(route.children, manifest);
}
});
return manifest;
}
function createStaticRouter(routes, context) {
let dataRoutes = router.UNSAFE_convertRoutesToDataRoutes(reactRouterDom.UNSAFE_enhanceManualRouteObjects(routes));
let manifest = generateManifest(dataRoutes); // Because our context matches may be from a framework-agnostic set of
// routes passed to createStaticHandler(), we update them here with our
// newly created/enhanced data routes
let matches = context.matches.map(match => {
let route = manifest.get(match.route.id) || match.route;
return { ...match,
route: route
};
});
let msg = method => `You cannot use router.${method}() on the server because it is a stateless environment`;
return {
get basename() {
return context.basename;
},
get state() {
return {
historyAction: router.Action.Pop,
location: context.location,
matches,
loaderData: context.loaderData,
actionData: context.actionData,
errors: context.errors,
initialized: true,
navigation: router.IDLE_NAVIGATION,
restoreScrollPosition: null,
preventScrollReset: false,
revalidation: "idle",
fetchers: new Map(),
blockers: new Map()
};
},
get routes() {
return dataRoutes;
},
initialize() {
throw msg("initialize");
},
subscribe() {
throw msg("subscribe");
},
enableScrollRestoration() {
throw msg("enableScrollRestoration");
},
navigate() {
throw msg("navigate");
},
fetch() {
throw msg("fetch");
},
revalidate() {
throw msg("revalidate");
},
createHref,
encodeLocation,
getFetcher() {
return router.IDLE_FETCHER;
},
deleteFetcher() {
throw msg("deleteFetcher");
},
dispose() {
throw msg("dispose");
},
getBlocker() {
throw msg("getBlocker");
},
deleteBlocker() {
throw msg("deleteBlocker");
},
_internalFetchControllers: new Map(),
_internalActiveDeferreds: new Map()
};
}
function createHref(to) {
return typeof to === "string" ? to : reactRouterDom.createPath(to);
}
function encodeLocation(to) {
// Locations should already be encoded on the server, so just return as-is
let path = typeof to === "string" ? reactRouterDom.parsePath(to) : to;
return {
pathname: path.pathname || "",
search: path.search || "",
hash: path.hash || ""
};
}
exports.StaticRouter = StaticRouter;
exports.StaticRouterProvider = StaticRouterProvider;
exports.createStaticRouter = createStaticRouter;

266
node_modules/react-router-dom/dist/server.mjs generated vendored Normal file
View File

@ -0,0 +1,266 @@
import * as React from 'react';
import { Action, invariant, isRouteErrorResponse, UNSAFE_convertRoutesToDataRoutes, IDLE_NAVIGATION, IDLE_FETCHER } from '@remix-run/router';
import { parsePath, Router, UNSAFE_DataRouterContext, UNSAFE_DataRouterStateContext, Routes, UNSAFE_enhanceManualRouteObjects, createPath } from 'react-router-dom';
/**
* A <Router> that may not navigate to any other location. This is useful
* on the server where there is no stateful UI.
*/
function StaticRouter({
basename,
children,
location: locationProp = "/"
}) {
if (typeof locationProp === "string") {
locationProp = parsePath(locationProp);
}
let action = Action.Pop;
let location = {
pathname: locationProp.pathname || "/",
search: locationProp.search || "",
hash: locationProp.hash || "",
state: locationProp.state || null,
key: locationProp.key || "default"
};
let staticNavigator = getStatelessNavigator();
return /*#__PURE__*/React.createElement(Router, {
basename: basename,
children: children,
location: location,
navigationType: action,
navigator: staticNavigator,
static: true
});
}
/**
* A Data Router that may not navigate to any other location. This is useful
* on the server where there is no stateful UI.
*/
function StaticRouterProvider({
context,
router,
hydrate = true,
nonce
}) {
!(router && context) ? process.env.NODE_ENV !== "production" ? invariant(false, "You must provide `router` and `context` to <StaticRouterProvider>") : invariant(false) : void 0;
let dataRouterContext = {
router,
navigator: getStatelessNavigator(),
static: true,
staticContext: context,
basename: context.basename || "/"
};
let hydrateScript = "";
if (hydrate !== false) {
let data = {
loaderData: context.loaderData,
actionData: context.actionData,
errors: serializeErrors(context.errors)
}; // Use JSON.parse here instead of embedding a raw JS object here to speed
// up parsing on the client. Dual-stringify is needed to ensure all quotes
// are properly escaped in the resulting string. See:
// https://v8.dev/blog/cost-of-javascript-2019#json
let json = JSON.stringify(JSON.stringify(data));
hydrateScript = `window.__staticRouterHydrationData = JSON.parse(${json});`;
}
return /*#__PURE__*/React.createElement(React.Fragment, null, /*#__PURE__*/React.createElement(UNSAFE_DataRouterContext.Provider, {
value: dataRouterContext
}, /*#__PURE__*/React.createElement(UNSAFE_DataRouterStateContext.Provider, {
value: dataRouterContext.router.state
}, /*#__PURE__*/React.createElement(Router, {
basename: dataRouterContext.basename,
location: dataRouterContext.router.state.location,
navigationType: dataRouterContext.router.state.historyAction,
navigator: dataRouterContext.navigator
}, /*#__PURE__*/React.createElement(Routes, null)))), hydrateScript ? /*#__PURE__*/React.createElement("script", {
suppressHydrationWarning: true,
nonce: nonce,
dangerouslySetInnerHTML: {
__html: hydrateScript
}
}) : null);
}
function serializeErrors(errors) {
if (!errors) return null;
let entries = Object.entries(errors);
let serialized = {};
for (let [key, val] of entries) {
// Hey you! If you change this, please change the corresponding logic in
// deserializeErrors in react-router-dom/index.tsx :)
if (isRouteErrorResponse(val)) {
serialized[key] = { ...val,
__type: "RouteErrorResponse"
};
} else if (val instanceof Error) {
// Do not serialize stack traces from SSR for security reasons
serialized[key] = {
message: val.message,
__type: "Error"
};
} else {
serialized[key] = val;
}
}
return serialized;
}
function getStatelessNavigator() {
return {
createHref,
encodeLocation,
push(to) {
throw new Error(`You cannot use navigator.push() on the server because it is a stateless ` + `environment. This error was probably triggered when you did a ` + `\`navigate(${JSON.stringify(to)})\` somewhere in your app.`);
},
replace(to) {
throw new Error(`You cannot use navigator.replace() on the server because it is a stateless ` + `environment. This error was probably triggered when you did a ` + `\`navigate(${JSON.stringify(to)}, { replace: true })\` somewhere ` + `in your app.`);
},
go(delta) {
throw new Error(`You cannot use navigator.go() on the server because it is a stateless ` + `environment. This error was probably triggered when you did a ` + `\`navigate(${delta})\` somewhere in your app.`);
},
back() {
throw new Error(`You cannot use navigator.back() on the server because it is a stateless ` + `environment.`);
},
forward() {
throw new Error(`You cannot use navigator.forward() on the server because it is a stateless ` + `environment.`);
}
};
} // Temporary manifest generation - we should optimize this by combining the
// tree-walks between convertRoutesToDataRoutes, enhanceManualRouteObjects,
// and generateManifest.
// Also look into getting rid of `route as AgnosticDataRouteObject` down below?
function generateManifest(routes, manifest = new Map()) {
routes.forEach(route => {
manifest.set(route.id, route);
if (route.children) {
generateManifest(route.children, manifest);
}
});
return manifest;
}
function createStaticRouter(routes, context) {
let dataRoutes = UNSAFE_convertRoutesToDataRoutes(UNSAFE_enhanceManualRouteObjects(routes));
let manifest = generateManifest(dataRoutes); // Because our context matches may be from a framework-agnostic set of
// routes passed to createStaticHandler(), we update them here with our
// newly created/enhanced data routes
let matches = context.matches.map(match => {
let route = manifest.get(match.route.id) || match.route;
return { ...match,
route: route
};
});
let msg = method => `You cannot use router.${method}() on the server because it is a stateless environment`;
return {
get basename() {
return context.basename;
},
get state() {
return {
historyAction: Action.Pop,
location: context.location,
matches,
loaderData: context.loaderData,
actionData: context.actionData,
errors: context.errors,
initialized: true,
navigation: IDLE_NAVIGATION,
restoreScrollPosition: null,
preventScrollReset: false,
revalidation: "idle",
fetchers: new Map(),
blockers: new Map()
};
},
get routes() {
return dataRoutes;
},
initialize() {
throw msg("initialize");
},
subscribe() {
throw msg("subscribe");
},
enableScrollRestoration() {
throw msg("enableScrollRestoration");
},
navigate() {
throw msg("navigate");
},
fetch() {
throw msg("fetch");
},
revalidate() {
throw msg("revalidate");
},
createHref,
encodeLocation,
getFetcher() {
return IDLE_FETCHER;
},
deleteFetcher() {
throw msg("deleteFetcher");
},
dispose() {
throw msg("dispose");
},
getBlocker() {
throw msg("getBlocker");
},
deleteBlocker() {
throw msg("deleteBlocker");
},
_internalFetchControllers: new Map(),
_internalActiveDeferreds: new Map()
};
}
function createHref(to) {
return typeof to === "string" ? to : createPath(to);
}
function encodeLocation(to) {
// Locations should already be encoded on the server, so just return as-is
let path = typeof to === "string" ? parsePath(to) : to;
return {
pathname: path.pathname || "",
search: path.search || "",
hash: path.hash || ""
};
}
export { StaticRouter, StaticRouterProvider, createStaticRouter };

File diff suppressed because it is too large Load Diff

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

49
node_modules/react-router-dom/package.json generated vendored Normal file
View File

@ -0,0 +1,49 @@
{
"name": "react-router-dom",
"version": "6.7.0",
"description": "Declarative routing for React web applications",
"keywords": [
"react",
"router",
"route",
"routing",
"history",
"link"
],
"repository": {
"type": "git",
"url": "https://github.com/remix-run/react-router",
"directory": "packages/react-router-dom"
},
"license": "MIT",
"author": "Remix Software <hello@remix.run>",
"sideEffects": false,
"main": "./dist/main.js",
"unpkg": "./dist/umd/react-router-dom.production.min.js",
"module": "./dist/index.js",
"types": "./dist/index.d.ts",
"dependencies": {
"@remix-run/router": "1.3.0",
"react-router": "6.7.0"
},
"devDependencies": {
"react": "^18.2.0",
"react-dom": "^18.2.0"
},
"peerDependencies": {
"react": ">=16.8",
"react-dom": ">=16.8"
},
"files": [
"dist/",
"CHANGELOG.md",
"LICENSE.md",
"README.md",
"server.d.ts",
"server.js",
"server.mjs"
],
"engines": {
"node": ">=14"
}
}

25
node_modules/react-router-dom/server.d.ts generated vendored Normal file
View File

@ -0,0 +1,25 @@
import * as React from "react";
import type { Router as RemixRouter, StaticHandlerContext } from "@remix-run/router";
import type { Location, RouteObject } from "react-router-dom";
export interface StaticRouterProps {
basename?: string;
children?: React.ReactNode;
location: Partial<Location> | string;
}
/**
* A <Router> that may not navigate to any other location. This is useful
* on the server where there is no stateful UI.
*/
export declare function StaticRouter({ basename, children, location: locationProp, }: StaticRouterProps): JSX.Element;
export interface StaticRouterProviderProps {
context: StaticHandlerContext;
router: RemixRouter;
hydrate?: boolean;
nonce?: string;
}
/**
* A Data Router that may not navigate to any other location. This is useful
* on the server where there is no stateful UI.
*/
export declare function StaticRouterProvider({ context, router, hydrate, nonce, }: StaticRouterProviderProps): JSX.Element;
export declare function createStaticRouter(routes: RouteObject[], context: StaticHandlerContext): RemixRouter;

293
node_modules/react-router-dom/server.js generated vendored Normal file
View File

@ -0,0 +1,293 @@
'use strict';
Object.defineProperty(exports, '__esModule', { value: true });
var React = require('react');
var router = require('@remix-run/router');
var reactRouterDom = require('react-router-dom');
function _interopNamespace(e) {
if (e && e.__esModule) return e;
var n = Object.create(null);
if (e) {
Object.keys(e).forEach(function (k) {
if (k !== 'default') {
var d = Object.getOwnPropertyDescriptor(e, k);
Object.defineProperty(n, k, d.get ? d : {
enumerable: true,
get: function () { return e[k]; }
});
}
});
}
n["default"] = e;
return Object.freeze(n);
}
var React__namespace = /*#__PURE__*/_interopNamespace(React);
/**
* A <Router> that may not navigate to any other location. This is useful
* on the server where there is no stateful UI.
*/
function StaticRouter({
basename,
children,
location: locationProp = "/"
}) {
if (typeof locationProp === "string") {
locationProp = reactRouterDom.parsePath(locationProp);
}
let action = router.Action.Pop;
let location = {
pathname: locationProp.pathname || "/",
search: locationProp.search || "",
hash: locationProp.hash || "",
state: locationProp.state || null,
key: locationProp.key || "default"
};
let staticNavigator = getStatelessNavigator();
return /*#__PURE__*/React__namespace.createElement(reactRouterDom.Router, {
basename: basename,
children: children,
location: location,
navigationType: action,
navigator: staticNavigator,
static: true
});
}
/**
* A Data Router that may not navigate to any other location. This is useful
* on the server where there is no stateful UI.
*/
function StaticRouterProvider({
context,
router: router$1,
hydrate = true,
nonce
}) {
!(router$1 && context) ? process.env.NODE_ENV !== "production" ? router.invariant(false, "You must provide `router` and `context` to <StaticRouterProvider>") : router.invariant(false) : void 0;
let dataRouterContext = {
router: router$1,
navigator: getStatelessNavigator(),
static: true,
staticContext: context,
basename: context.basename || "/"
};
let hydrateScript = "";
if (hydrate !== false) {
let data = {
loaderData: context.loaderData,
actionData: context.actionData,
errors: serializeErrors(context.errors)
}; // Use JSON.parse here instead of embedding a raw JS object here to speed
// up parsing on the client. Dual-stringify is needed to ensure all quotes
// are properly escaped in the resulting string. See:
// https://v8.dev/blog/cost-of-javascript-2019#json
let json = JSON.stringify(JSON.stringify(data));
hydrateScript = `window.__staticRouterHydrationData = JSON.parse(${json});`;
}
return /*#__PURE__*/React__namespace.createElement(React__namespace.Fragment, null, /*#__PURE__*/React__namespace.createElement(reactRouterDom.UNSAFE_DataRouterContext.Provider, {
value: dataRouterContext
}, /*#__PURE__*/React__namespace.createElement(reactRouterDom.UNSAFE_DataRouterStateContext.Provider, {
value: dataRouterContext.router.state
}, /*#__PURE__*/React__namespace.createElement(reactRouterDom.Router, {
basename: dataRouterContext.basename,
location: dataRouterContext.router.state.location,
navigationType: dataRouterContext.router.state.historyAction,
navigator: dataRouterContext.navigator
}, /*#__PURE__*/React__namespace.createElement(reactRouterDom.Routes, null)))), hydrateScript ? /*#__PURE__*/React__namespace.createElement("script", {
suppressHydrationWarning: true,
nonce: nonce,
dangerouslySetInnerHTML: {
__html: hydrateScript
}
}) : null);
}
function serializeErrors(errors) {
if (!errors) return null;
let entries = Object.entries(errors);
let serialized = {};
for (let [key, val] of entries) {
// Hey you! If you change this, please change the corresponding logic in
// deserializeErrors in react-router-dom/index.tsx :)
if (router.isRouteErrorResponse(val)) {
serialized[key] = { ...val,
__type: "RouteErrorResponse"
};
} else if (val instanceof Error) {
// Do not serialize stack traces from SSR for security reasons
serialized[key] = {
message: val.message,
__type: "Error"
};
} else {
serialized[key] = val;
}
}
return serialized;
}
function getStatelessNavigator() {
return {
createHref,
encodeLocation,
push(to) {
throw new Error(`You cannot use navigator.push() on the server because it is a stateless ` + `environment. This error was probably triggered when you did a ` + `\`navigate(${JSON.stringify(to)})\` somewhere in your app.`);
},
replace(to) {
throw new Error(`You cannot use navigator.replace() on the server because it is a stateless ` + `environment. This error was probably triggered when you did a ` + `\`navigate(${JSON.stringify(to)}, { replace: true })\` somewhere ` + `in your app.`);
},
go(delta) {
throw new Error(`You cannot use navigator.go() on the server because it is a stateless ` + `environment. This error was probably triggered when you did a ` + `\`navigate(${delta})\` somewhere in your app.`);
},
back() {
throw new Error(`You cannot use navigator.back() on the server because it is a stateless ` + `environment.`);
},
forward() {
throw new Error(`You cannot use navigator.forward() on the server because it is a stateless ` + `environment.`);
}
};
} // Temporary manifest generation - we should optimize this by combining the
// tree-walks between convertRoutesToDataRoutes, enhanceManualRouteObjects,
// and generateManifest.
// Also look into getting rid of `route as AgnosticDataRouteObject` down below?
function generateManifest(routes, manifest = new Map()) {
routes.forEach(route => {
manifest.set(route.id, route);
if (route.children) {
generateManifest(route.children, manifest);
}
});
return manifest;
}
function createStaticRouter(routes, context) {
let dataRoutes = router.UNSAFE_convertRoutesToDataRoutes(reactRouterDom.UNSAFE_enhanceManualRouteObjects(routes));
let manifest = generateManifest(dataRoutes); // Because our context matches may be from a framework-agnostic set of
// routes passed to createStaticHandler(), we update them here with our
// newly created/enhanced data routes
let matches = context.matches.map(match => {
let route = manifest.get(match.route.id) || match.route;
return { ...match,
route: route
};
});
let msg = method => `You cannot use router.${method}() on the server because it is a stateless environment`;
return {
get basename() {
return context.basename;
},
get state() {
return {
historyAction: router.Action.Pop,
location: context.location,
matches,
loaderData: context.loaderData,
actionData: context.actionData,
errors: context.errors,
initialized: true,
navigation: router.IDLE_NAVIGATION,
restoreScrollPosition: null,
preventScrollReset: false,
revalidation: "idle",
fetchers: new Map(),
blockers: new Map()
};
},
get routes() {
return dataRoutes;
},
initialize() {
throw msg("initialize");
},
subscribe() {
throw msg("subscribe");
},
enableScrollRestoration() {
throw msg("enableScrollRestoration");
},
navigate() {
throw msg("navigate");
},
fetch() {
throw msg("fetch");
},
revalidate() {
throw msg("revalidate");
},
createHref,
encodeLocation,
getFetcher() {
return router.IDLE_FETCHER;
},
deleteFetcher() {
throw msg("deleteFetcher");
},
dispose() {
throw msg("dispose");
},
getBlocker() {
throw msg("getBlocker");
},
deleteBlocker() {
throw msg("deleteBlocker");
},
_internalFetchControllers: new Map(),
_internalActiveDeferreds: new Map()
};
}
function createHref(to) {
return typeof to === "string" ? to : reactRouterDom.createPath(to);
}
function encodeLocation(to) {
// Locations should already be encoded on the server, so just return as-is
let path = typeof to === "string" ? reactRouterDom.parsePath(to) : to;
return {
pathname: path.pathname || "",
search: path.search || "",
hash: path.hash || ""
};
}
exports.StaticRouter = StaticRouter;
exports.StaticRouterProvider = StaticRouterProvider;
exports.createStaticRouter = createStaticRouter;

266
node_modules/react-router-dom/server.mjs generated vendored Normal file
View File

@ -0,0 +1,266 @@
import * as React from 'react';
import { Action, invariant, isRouteErrorResponse, UNSAFE_convertRoutesToDataRoutes, IDLE_NAVIGATION, IDLE_FETCHER } from '@remix-run/router';
import { parsePath, Router, UNSAFE_DataRouterContext, UNSAFE_DataRouterStateContext, Routes, UNSAFE_enhanceManualRouteObjects, createPath } from 'react-router-dom';
/**
* A <Router> that may not navigate to any other location. This is useful
* on the server where there is no stateful UI.
*/
function StaticRouter({
basename,
children,
location: locationProp = "/"
}) {
if (typeof locationProp === "string") {
locationProp = parsePath(locationProp);
}
let action = Action.Pop;
let location = {
pathname: locationProp.pathname || "/",
search: locationProp.search || "",
hash: locationProp.hash || "",
state: locationProp.state || null,
key: locationProp.key || "default"
};
let staticNavigator = getStatelessNavigator();
return /*#__PURE__*/React.createElement(Router, {
basename: basename,
children: children,
location: location,
navigationType: action,
navigator: staticNavigator,
static: true
});
}
/**
* A Data Router that may not navigate to any other location. This is useful
* on the server where there is no stateful UI.
*/
function StaticRouterProvider({
context,
router,
hydrate = true,
nonce
}) {
!(router && context) ? process.env.NODE_ENV !== "production" ? invariant(false, "You must provide `router` and `context` to <StaticRouterProvider>") : invariant(false) : void 0;
let dataRouterContext = {
router,
navigator: getStatelessNavigator(),
static: true,
staticContext: context,
basename: context.basename || "/"
};
let hydrateScript = "";
if (hydrate !== false) {
let data = {
loaderData: context.loaderData,
actionData: context.actionData,
errors: serializeErrors(context.errors)
}; // Use JSON.parse here instead of embedding a raw JS object here to speed
// up parsing on the client. Dual-stringify is needed to ensure all quotes
// are properly escaped in the resulting string. See:
// https://v8.dev/blog/cost-of-javascript-2019#json
let json = JSON.stringify(JSON.stringify(data));
hydrateScript = `window.__staticRouterHydrationData = JSON.parse(${json});`;
}
return /*#__PURE__*/React.createElement(React.Fragment, null, /*#__PURE__*/React.createElement(UNSAFE_DataRouterContext.Provider, {
value: dataRouterContext
}, /*#__PURE__*/React.createElement(UNSAFE_DataRouterStateContext.Provider, {
value: dataRouterContext.router.state
}, /*#__PURE__*/React.createElement(Router, {
basename: dataRouterContext.basename,
location: dataRouterContext.router.state.location,
navigationType: dataRouterContext.router.state.historyAction,
navigator: dataRouterContext.navigator
}, /*#__PURE__*/React.createElement(Routes, null)))), hydrateScript ? /*#__PURE__*/React.createElement("script", {
suppressHydrationWarning: true,
nonce: nonce,
dangerouslySetInnerHTML: {
__html: hydrateScript
}
}) : null);
}
function serializeErrors(errors) {
if (!errors) return null;
let entries = Object.entries(errors);
let serialized = {};
for (let [key, val] of entries) {
// Hey you! If you change this, please change the corresponding logic in
// deserializeErrors in react-router-dom/index.tsx :)
if (isRouteErrorResponse(val)) {
serialized[key] = { ...val,
__type: "RouteErrorResponse"
};
} else if (val instanceof Error) {
// Do not serialize stack traces from SSR for security reasons
serialized[key] = {
message: val.message,
__type: "Error"
};
} else {
serialized[key] = val;
}
}
return serialized;
}
function getStatelessNavigator() {
return {
createHref,
encodeLocation,
push(to) {
throw new Error(`You cannot use navigator.push() on the server because it is a stateless ` + `environment. This error was probably triggered when you did a ` + `\`navigate(${JSON.stringify(to)})\` somewhere in your app.`);
},
replace(to) {
throw new Error(`You cannot use navigator.replace() on the server because it is a stateless ` + `environment. This error was probably triggered when you did a ` + `\`navigate(${JSON.stringify(to)}, { replace: true })\` somewhere ` + `in your app.`);
},
go(delta) {
throw new Error(`You cannot use navigator.go() on the server because it is a stateless ` + `environment. This error was probably triggered when you did a ` + `\`navigate(${delta})\` somewhere in your app.`);
},
back() {
throw new Error(`You cannot use navigator.back() on the server because it is a stateless ` + `environment.`);
},
forward() {
throw new Error(`You cannot use navigator.forward() on the server because it is a stateless ` + `environment.`);
}
};
} // Temporary manifest generation - we should optimize this by combining the
// tree-walks between convertRoutesToDataRoutes, enhanceManualRouteObjects,
// and generateManifest.
// Also look into getting rid of `route as AgnosticDataRouteObject` down below?
function generateManifest(routes, manifest = new Map()) {
routes.forEach(route => {
manifest.set(route.id, route);
if (route.children) {
generateManifest(route.children, manifest);
}
});
return manifest;
}
function createStaticRouter(routes, context) {
let dataRoutes = UNSAFE_convertRoutesToDataRoutes(UNSAFE_enhanceManualRouteObjects(routes));
let manifest = generateManifest(dataRoutes); // Because our context matches may be from a framework-agnostic set of
// routes passed to createStaticHandler(), we update them here with our
// newly created/enhanced data routes
let matches = context.matches.map(match => {
let route = manifest.get(match.route.id) || match.route;
return { ...match,
route: route
};
});
let msg = method => `You cannot use router.${method}() on the server because it is a stateless environment`;
return {
get basename() {
return context.basename;
},
get state() {
return {
historyAction: Action.Pop,
location: context.location,
matches,
loaderData: context.loaderData,
actionData: context.actionData,
errors: context.errors,
initialized: true,
navigation: IDLE_NAVIGATION,
restoreScrollPosition: null,
preventScrollReset: false,
revalidation: "idle",
fetchers: new Map(),
blockers: new Map()
};
},
get routes() {
return dataRoutes;
},
initialize() {
throw msg("initialize");
},
subscribe() {
throw msg("subscribe");
},
enableScrollRestoration() {
throw msg("enableScrollRestoration");
},
navigate() {
throw msg("navigate");
},
fetch() {
throw msg("fetch");
},
revalidate() {
throw msg("revalidate");
},
createHref,
encodeLocation,
getFetcher() {
return IDLE_FETCHER;
},
deleteFetcher() {
throw msg("deleteFetcher");
},
dispose() {
throw msg("dispose");
},
getBlocker() {
throw msg("getBlocker");
},
deleteBlocker() {
throw msg("deleteBlocker");
},
_internalFetchControllers: new Map(),
_internalActiveDeferreds: new Map()
};
}
function createHref(to) {
return typeof to === "string" ? to : createPath(to);
}
function encodeLocation(to) {
// Locations should already be encoded on the server, so just return as-is
let path = typeof to === "string" ? parsePath(to) : to;
return {
pathname: path.pathname || "",
search: path.search || "",
hash: path.hash || ""
};
}
export { StaticRouter, StaticRouterProvider, createStaticRouter };

162
node_modules/react-router/CHANGELOG.md generated vendored Normal file
View File

@ -0,0 +1,162 @@
# `react-router`
## 6.7.0
### Minor Changes
- Add `unstable_useBlocker` hook for blocking navigations within the app's location origin ([#9709](https://github.com/remix-run/react-router/pull/9709))
### Patch Changes
- Fix `generatePath` when optional params are present ([#9764](https://github.com/remix-run/react-router/pull/9764))
- Update `<Await>` to accept `ReactNode` as children function return result ([#9896](https://github.com/remix-run/react-router/pull/9896))
- Updated dependencies:
- `@remix-run/router@1.3.0`
## 6.6.2
### Patch Changes
- Ensure `useId` consistency during SSR ([#9805](https://github.com/remix-run/react-router/pull/9805))
## 6.6.2-pre.0
### Patch Changes
- Ensure `useId` consistency during SSR ([#9805](https://github.com/remix-run/react-router/pull/9805))
## 6.6.1
### Patch Changes
- Updated dependencies:
- `@remix-run/router@1.2.1`
## 6.6.0
### Patch Changes
- Prevent `useLoaderData` usage in `errorElement` ([#9735](https://github.com/remix-run/react-router/pull/9735))
- Updated dependencies:
- `@remix-run/router@1.2.0`
## 6.5.0
This release introduces support for [Optional Route Segments](https://github.com/remix-run/react-router/issues/9546). Now, adding a `?` to the end of any path segment will make that entire segment optional. This works for both static segments and dynamic parameters.
**Optional Params Examples**
- `<Route path=":lang?/about>` will match:
- `/:lang/about`
- `/about`
- `<Route path="/multistep/:widget1?/widget2?/widget3?">` will match:
- `/multistep`
- `/multistep/:widget1`
- `/multistep/:widget1/:widget2`
- `/multistep/:widget1/:widget2/:widget3`
**Optional Static Segment Example**
- `<Route path="/home?">` will match:
- `/`
- `/home`
- `<Route path="/fr?/about">` will match:
- `/about`
- `/fr/about`
### Minor Changes
- Allows optional routes and optional static segments ([#9650](https://github.com/remix-run/react-router/pull/9650))
### Patch Changes
- Stop incorrectly matching on partial named parameters, i.e. `<Route path="prefix-:param">`, to align with how splat parameters work. If you were previously relying on this behavior then it's recommended to extract the static portion of the path at the `useParams` call site: ([#9506](https://github.com/remix-run/react-router/pull/9506))
```jsx
// Old behavior at URL /prefix-123
<Route path="prefix-:id" element={<Comp /> }>
function Comp() {
let params = useParams(); // { id: '123' }
let id = params.id; // "123"
...
}
// New behavior at URL /prefix-123
<Route path=":id" element={<Comp /> }>
function Comp() {
let params = useParams(); // { id: 'prefix-123' }
let id = params.id.replace(/^prefix-/, ''); // "123"
...
}
```
- Updated dependencies:
- `@remix-run/router@1.1.0`
## 6.4.5
### Patch Changes
- Updated dependencies:
- `@remix-run/router@1.0.5`
## 6.4.4
### Patch Changes
- Updated dependencies:
- `@remix-run/router@1.0.4`
## 6.4.3
### Patch Changes
- `useRoutes` should be able to return `null` when passing `locationArg` ([#9485](https://github.com/remix-run/react-router/pull/9485))
- fix `initialEntries` type in `createMemoryRouter` ([#9498](https://github.com/remix-run/react-router/pull/9498))
- Updated dependencies:
- `@remix-run/router@1.0.3`
## 6.4.2
### Patch Changes
- Fix `IndexRouteObject` and `NonIndexRouteObject` types to make `hasErrorElement` optional ([#9394](https://github.com/remix-run/react-router/pull/9394))
- Enhance console error messages for invalid usage of data router hooks ([#9311](https://github.com/remix-run/react-router/pull/9311))
- If an index route has children, it will result in a runtime error. We have strengthened our `RouteObject`/`RouteProps` types to surface the error in TypeScript. ([#9366](https://github.com/remix-run/react-router/pull/9366))
- Updated dependencies:
- `@remix-run/router@1.0.2`
## 6.4.1
### Patch Changes
- Preserve state from `initialEntries` ([#9288](https://github.com/remix-run/react-router/pull/9288))
- Updated dependencies:
- `@remix-run/router@1.0.1`
## 6.4.0
Whoa this is a big one! `6.4.0` brings all the data loading and mutation APIs over from Remix. Here's a quick high level overview, but it's recommended you go check out the [docs][rr-docs], especially the [feature overview][rr-feature-overview] and the [tutorial][rr-tutorial].
**New APIs**
- Create your router with `createMemoryRouter`
- Render your router with `<RouterProvider>`
- Load data with a Route `loader` and mutate with a Route `action`
- Handle errors with Route `errorElement`
- Defer non-critical data with `defer` and `Await`
**Bug Fixes**
- Path resolution is now trailing slash agnostic (#8861)
- `useLocation` returns the scoped location inside a `<Routes location>` component (#9094)
**Updated Dependencies**
- `@remix-run/router@1.0.0`
[rr-docs]: https://reactrouter.com
[rr-feature-overview]: https://reactrouter.com/start/overview
[rr-tutorial]: https://reactrouter.com/start/tutorial

22
node_modules/react-router/LICENSE.md generated vendored Normal file
View File

@ -0,0 +1,22 @@
MIT License
Copyright (c) React Training 2015-2019
Copyright (c) Remix Software 2020-2022
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.

16
node_modules/react-router/README.md generated vendored Normal file
View File

@ -0,0 +1,16 @@
# React Router
The `react-router` package is the heart of [React Router](https://github.com/remix-run/react-router) and provides all
the core functionality for both
[`react-router-dom`](/packages/react-router-dom)
and
[`react-router-native`](/packages/react-router-native).
If you're using React Router, you should never `import` anything directly from
the `react-router` package, but you should have everything you need in either
`react-router-dom` or `react-router-native`. Both of those packages re-export
everything from `react-router`.
If you'd like to extend React Router and you know what you're doing, you should
add `react-router` **as a peer dependency, not a regular dependency** in your
package.

21
node_modules/react-router/dist/index.d.ts generated vendored Normal file
View File

@ -0,0 +1,21 @@
import type { ActionFunction, ActionFunctionArgs, Blocker, BlockerFunction, Fetcher, HydrationState, JsonFunction, LoaderFunction, LoaderFunctionArgs, Location, Navigation, Params, ParamParseKey, Path, PathMatch, PathPattern, RedirectFunction, Router as RemixRouter, ShouldRevalidateFunction, To, InitialEntry } from "@remix-run/router";
import { AbortedDeferredError, Action as NavigationType, createPath, defer, generatePath, isRouteErrorResponse, json, matchPath, matchRoutes, parsePath, redirect, resolvePath } from "@remix-run/router";
import type { AwaitProps, MemoryRouterProps, NavigateProps, OutletProps, RouteProps, PathRouteProps, LayoutRouteProps, IndexRouteProps, RouterProps, RoutesProps, RouterProviderProps } from "./lib/components";
import { enhanceManualRouteObjects, createRoutesFromChildren, renderMatches, Await, MemoryRouter, Navigate, Outlet, Route, Router, RouterProvider, Routes } from "./lib/components";
import type { DataRouteMatch, DataRouteObject, IndexRouteObject, Navigator, NavigateOptions, NonIndexRouteObject, RouteMatch, RouteObject, RelativeRoutingType } from "./lib/context";
import { DataRouterContext, DataRouterStateContext, LocationContext, NavigationContext, RouteContext } from "./lib/context";
import type { NavigateFunction } from "./lib/hooks";
import { useBlocker, useHref, useInRouterContext, useLocation, useMatch, useNavigationType, useNavigate, useOutlet, useOutletContext, useParams, useResolvedPath, useRoutes, useActionData, useAsyncError, useAsyncValue, useLoaderData, useMatches, useNavigation, useRevalidator, useRouteError, useRouteLoaderData } from "./lib/hooks";
declare type Hash = string;
declare type Pathname = string;
declare type Search = string;
export type { ActionFunction, ActionFunctionArgs, AwaitProps, Blocker as unstable_Blocker, BlockerFunction as unstable_BlockerFunction, DataRouteMatch, DataRouteObject, Fetcher, Hash, IndexRouteObject, IndexRouteProps, JsonFunction, LayoutRouteProps, LoaderFunction, LoaderFunctionArgs, Location, MemoryRouterProps, NavigateFunction, NavigateOptions, NavigateProps, Navigation, Navigator, NonIndexRouteObject, OutletProps, Params, ParamParseKey, Path, PathMatch, Pathname, PathPattern, PathRouteProps, RedirectFunction, RelativeRoutingType, RouteMatch, RouteObject, RouteProps, RouterProps, RouterProviderProps, RoutesProps, Search, ShouldRevalidateFunction, To, };
export { AbortedDeferredError, Await, MemoryRouter, Navigate, NavigationType, Outlet, Route, Router, RouterProvider, Routes, createPath, createRoutesFromChildren, createRoutesFromChildren as createRoutesFromElements, defer, isRouteErrorResponse, generatePath, json, matchPath, matchRoutes, parsePath, redirect, renderMatches, resolvePath, useActionData, useAsyncError, useAsyncValue, useBlocker as unstable_useBlocker, useHref, useInRouterContext, useLoaderData, useLocation, useMatch, useMatches, useNavigate, useNavigation, useNavigationType, useOutlet, useOutletContext, useParams, useResolvedPath, useRevalidator, useRouteError, useRouteLoaderData, useRoutes, };
export declare function createMemoryRouter(routes: RouteObject[], opts?: {
basename?: string;
hydrationData?: HydrationState;
initialEntries?: InitialEntry[];
initialIndex?: number;
}): RemixRouter;
/** @internal */
export { NavigationContext as UNSAFE_NavigationContext, LocationContext as UNSAFE_LocationContext, RouteContext as UNSAFE_RouteContext, DataRouterContext as UNSAFE_DataRouterContext, DataRouterStateContext as UNSAFE_DataRouterStateContext, enhanceManualRouteObjects as UNSAFE_enhanceManualRouteObjects, };

1392
node_modules/react-router/dist/index.js generated vendored Normal file

File diff suppressed because it is too large Load Diff

1
node_modules/react-router/dist/index.js.map generated vendored Normal file

File diff suppressed because one or more lines are too long

146
node_modules/react-router/dist/lib/components.d.ts generated vendored Normal file
View File

@ -0,0 +1,146 @@
import * as React from "react";
import type { TrackedPromise, InitialEntry, Location, Router as RemixRouter, To } from "@remix-run/router";
import { Action as NavigationType } from "@remix-run/router";
import type { IndexRouteObject, RouteMatch, RouteObject, Navigator, NonIndexRouteObject, RelativeRoutingType } from "./context";
export interface RouterProviderProps {
fallbackElement?: React.ReactNode;
router: RemixRouter;
}
/**
* Given a Remix Router instance, render the appropriate UI
*/
export declare function RouterProvider({ fallbackElement, router, }: RouterProviderProps): React.ReactElement;
export interface MemoryRouterProps {
basename?: string;
children?: React.ReactNode;
initialEntries?: InitialEntry[];
initialIndex?: number;
}
/**
* A <Router> that stores all entries in memory.
*
* @see https://reactrouter.com/router-components/memory-router
*/
export declare function MemoryRouter({ basename, children, initialEntries, initialIndex, }: MemoryRouterProps): React.ReactElement;
export interface NavigateProps {
to: To;
replace?: boolean;
state?: any;
relative?: RelativeRoutingType;
}
/**
* Changes the current location.
*
* Note: This API is mostly useful in React.Component subclasses that are not
* able to use hooks. In functional components, we recommend you use the
* `useNavigate` hook instead.
*
* @see https://reactrouter.com/components/navigate
*/
export declare function Navigate({ to, replace, state, relative, }: NavigateProps): null;
export interface OutletProps {
context?: unknown;
}
/**
* Renders the child route's element, if there is one.
*
* @see https://reactrouter.com/components/outlet
*/
export declare function Outlet(props: OutletProps): React.ReactElement | null;
export interface PathRouteProps {
caseSensitive?: NonIndexRouteObject["caseSensitive"];
path?: NonIndexRouteObject["path"];
id?: NonIndexRouteObject["id"];
loader?: NonIndexRouteObject["loader"];
action?: NonIndexRouteObject["action"];
hasErrorBoundary?: NonIndexRouteObject["hasErrorBoundary"];
shouldRevalidate?: NonIndexRouteObject["shouldRevalidate"];
handle?: NonIndexRouteObject["handle"];
index?: false;
children?: React.ReactNode;
element?: React.ReactNode | null;
errorElement?: React.ReactNode | null;
}
export interface LayoutRouteProps extends PathRouteProps {
}
export interface IndexRouteProps {
caseSensitive?: IndexRouteObject["caseSensitive"];
path?: IndexRouteObject["path"];
id?: IndexRouteObject["id"];
loader?: IndexRouteObject["loader"];
action?: IndexRouteObject["action"];
hasErrorBoundary?: IndexRouteObject["hasErrorBoundary"];
shouldRevalidate?: IndexRouteObject["shouldRevalidate"];
handle?: IndexRouteObject["handle"];
index: true;
children?: undefined;
element?: React.ReactNode | null;
errorElement?: React.ReactNode | null;
}
export declare type RouteProps = PathRouteProps | LayoutRouteProps | IndexRouteProps;
/**
* Declares an element that should be rendered at a certain URL path.
*
* @see https://reactrouter.com/components/route
*/
export declare function Route(_props: RouteProps): React.ReactElement | null;
export interface RouterProps {
basename?: string;
children?: React.ReactNode;
location: Partial<Location> | string;
navigationType?: NavigationType;
navigator: Navigator;
static?: boolean;
}
/**
* Provides location context for the rest of the app.
*
* Note: You usually won't render a <Router> directly. Instead, you'll render a
* router that is more specific to your environment such as a <BrowserRouter>
* in web browsers or a <StaticRouter> for server rendering.
*
* @see https://reactrouter.com/router-components/router
*/
export declare function Router({ basename: basenameProp, children, location: locationProp, navigationType, navigator, static: staticProp, }: RouterProps): React.ReactElement | null;
export interface RoutesProps {
children?: React.ReactNode;
location?: Partial<Location> | string;
}
/**
* A container for a nested tree of <Route> elements that renders the branch
* that best matches the current location.
*
* @see https://reactrouter.com/components/routes
*/
export declare function Routes({ children, location, }: RoutesProps): React.ReactElement | null;
export interface AwaitResolveRenderFunction {
(data: Awaited<any>): React.ReactNode;
}
export interface AwaitProps {
children: React.ReactNode | AwaitResolveRenderFunction;
errorElement?: React.ReactNode;
resolve: TrackedPromise | any;
}
/**
* Component to use for rendering lazily loaded data from returning defer()
* in a loader function
*/
export declare function Await({ children, errorElement, resolve }: AwaitProps): JSX.Element;
/**
* Creates a route config from a React "children" object, which is usually
* either a `<Route>` element or an array of them. Used internally by
* `<Routes>` to create a route config from its children.
*
* @see https://reactrouter.com/utils/create-routes-from-children
*/
export declare function createRoutesFromChildren(children: React.ReactNode, parentPath?: number[]): RouteObject[];
/**
* Renders the result of `matchRoutes()` into a React element.
*/
export declare function renderMatches(matches: RouteMatch[] | null): React.ReactElement | null;
/**
* @private
* Walk the route tree and add hasErrorBoundary if it's not provided, so that
* users providing manual route arrays can just specify errorElement
*/
export declare function enhanceManualRouteObjects(routes: RouteObject[]): RouteObject[];

88
node_modules/react-router/dist/lib/context.d.ts generated vendored Normal file
View File

@ -0,0 +1,88 @@
import * as React from "react";
import type { AgnosticRouteMatch, AgnosticIndexRouteObject, AgnosticNonIndexRouteObject, History, Location, Router, StaticHandlerContext, To, TrackedPromise } from "@remix-run/router";
import type { Action as NavigationType } from "@remix-run/router";
export interface IndexRouteObject {
caseSensitive?: AgnosticIndexRouteObject["caseSensitive"];
path?: AgnosticIndexRouteObject["path"];
id?: AgnosticIndexRouteObject["id"];
loader?: AgnosticIndexRouteObject["loader"];
action?: AgnosticIndexRouteObject["action"];
hasErrorBoundary?: AgnosticIndexRouteObject["hasErrorBoundary"];
shouldRevalidate?: AgnosticIndexRouteObject["shouldRevalidate"];
handle?: AgnosticIndexRouteObject["handle"];
index: true;
children?: undefined;
element?: React.ReactNode | null;
errorElement?: React.ReactNode | null;
}
export interface NonIndexRouteObject {
caseSensitive?: AgnosticNonIndexRouteObject["caseSensitive"];
path?: AgnosticNonIndexRouteObject["path"];
id?: AgnosticNonIndexRouteObject["id"];
loader?: AgnosticNonIndexRouteObject["loader"];
action?: AgnosticNonIndexRouteObject["action"];
hasErrorBoundary?: AgnosticNonIndexRouteObject["hasErrorBoundary"];
shouldRevalidate?: AgnosticNonIndexRouteObject["shouldRevalidate"];
handle?: AgnosticNonIndexRouteObject["handle"];
index?: false;
children?: RouteObject[];
element?: React.ReactNode | null;
errorElement?: React.ReactNode | null;
}
export declare type RouteObject = IndexRouteObject | NonIndexRouteObject;
export declare type DataRouteObject = RouteObject & {
children?: DataRouteObject[];
id: string;
};
export interface RouteMatch<ParamKey extends string = string, RouteObjectType extends RouteObject = RouteObject> extends AgnosticRouteMatch<ParamKey, RouteObjectType> {
}
export interface DataRouteMatch extends RouteMatch<string, DataRouteObject> {
}
export interface DataRouterContextObject extends NavigationContextObject {
router: Router;
staticContext?: StaticHandlerContext;
}
export declare const DataRouterContext: React.Context<DataRouterContextObject | null>;
export declare const DataRouterStateContext: React.Context<import("@remix-run/router").RouterState | null>;
export declare const AwaitContext: React.Context<TrackedPromise | null>;
export declare type RelativeRoutingType = "route" | "path";
export interface NavigateOptions {
replace?: boolean;
state?: any;
preventScrollReset?: boolean;
relative?: RelativeRoutingType;
}
/**
* A Navigator is a "location changer"; it's how you get to different locations.
*
* Every history instance conforms to the Navigator interface, but the
* distinction is useful primarily when it comes to the low-level <Router> API
* where both the location and a navigator must be provided separately in order
* to avoid "tearing" that may occur in a suspense-enabled app if the action
* and/or location were to be read directly from the history instance.
*/
export interface Navigator {
createHref: History["createHref"];
encodeLocation?: History["encodeLocation"];
go: History["go"];
push(to: To, state?: any, opts?: NavigateOptions): void;
replace(to: To, state?: any, opts?: NavigateOptions): void;
}
interface NavigationContextObject {
basename: string;
navigator: Navigator;
static: boolean;
}
export declare const NavigationContext: React.Context<NavigationContextObject>;
interface LocationContextObject {
location: Location;
navigationType: NavigationType;
}
export declare const LocationContext: React.Context<LocationContextObject>;
export interface RouteContextObject {
outlet: React.ReactElement | null;
matches: RouteMatch[];
}
export declare const RouteContext: React.Context<RouteContextObject>;
export declare const RouteErrorContext: React.Context<any>;
export {};

179
node_modules/react-router/dist/lib/hooks.d.ts generated vendored Normal file
View File

@ -0,0 +1,179 @@
import * as React from "react";
import type { Blocker, BlockerFunction, Location, ParamParseKey, Params, Path, PathMatch, PathPattern, Router as RemixRouter, To } from "@remix-run/router";
import { Action as NavigationType } from "@remix-run/router";
import type { NavigateOptions, RouteContextObject, RouteMatch, RouteObject, RelativeRoutingType } from "./context";
/**
* Returns the full href for the given "to" value. This is useful for building
* custom links that are also accessible and preserve right-click behavior.
*
* @see https://reactrouter.com/hooks/use-href
*/
export declare function useHref(to: To, { relative }?: {
relative?: RelativeRoutingType;
}): string;
/**
* Returns true if this component is a descendant of a <Router>.
*
* @see https://reactrouter.com/hooks/use-in-router-context
*/
export declare function useInRouterContext(): boolean;
/**
* Returns the current location object, which represents the current URL in web
* browsers.
*
* Note: If you're using this it may mean you're doing some of your own
* "routing" in your app, and we'd like to know what your use case is. We may
* be able to provide something higher-level to better suit your needs.
*
* @see https://reactrouter.com/hooks/use-location
*/
export declare function useLocation(): Location;
/**
* Returns the current navigation action which describes how the router came to
* the current location, either by a pop, push, or replace on the history stack.
*
* @see https://reactrouter.com/hooks/use-navigation-type
*/
export declare function useNavigationType(): NavigationType;
/**
* Returns a PathMatch object if the given pattern matches the current URL.
* This is useful for components that need to know "active" state, e.g.
* <NavLink>.
*
* @see https://reactrouter.com/hooks/use-match
*/
export declare function useMatch<ParamKey extends ParamParseKey<Path>, Path extends string>(pattern: PathPattern<Path> | Path): PathMatch<ParamKey> | null;
/**
* The interface for the navigate() function returned from useNavigate().
*/
export interface NavigateFunction {
(to: To, options?: NavigateOptions): void;
(delta: number): void;
}
/**
* Returns an imperative method for changing the location. Used by <Link>s, but
* may also be used by other elements to change the location.
*
* @see https://reactrouter.com/hooks/use-navigate
*/
export declare function useNavigate(): NavigateFunction;
/**
* Returns the context (if provided) for the child route at this level of the route
* hierarchy.
* @see https://reactrouter.com/hooks/use-outlet-context
*/
export declare function useOutletContext<Context = unknown>(): Context;
/**
* Returns the element for the child route at this level of the route
* hierarchy. Used internally by <Outlet> to render child routes.
*
* @see https://reactrouter.com/hooks/use-outlet
*/
export declare function useOutlet(context?: unknown): React.ReactElement | null;
/**
* Returns an object of key/value pairs of the dynamic params from the current
* URL that were matched by the route path.
*
* @see https://reactrouter.com/hooks/use-params
*/
export declare function useParams<ParamsOrKey extends string | Record<string, string | undefined> = string>(): Readonly<[
ParamsOrKey
] extends [string] ? Params<ParamsOrKey> : Partial<ParamsOrKey>>;
/**
* Resolves the pathname of the given `to` value against the current location.
*
* @see https://reactrouter.com/hooks/use-resolved-path
*/
export declare function useResolvedPath(to: To, { relative }?: {
relative?: RelativeRoutingType;
}): Path;
/**
* Returns the element of the route that matched the current location, prepared
* with the correct context to render the remainder of the route tree. Route
* elements in the tree must render an <Outlet> to render their child route's
* element.
*
* @see https://reactrouter.com/hooks/use-routes
*/
export declare function useRoutes(routes: RouteObject[], locationArg?: Partial<Location> | string): React.ReactElement | null;
declare type RenderErrorBoundaryProps = React.PropsWithChildren<{
location: Location;
error: any;
component: React.ReactNode;
routeContext: RouteContextObject;
}>;
declare type RenderErrorBoundaryState = {
location: Location;
error: any;
};
export declare class RenderErrorBoundary extends React.Component<RenderErrorBoundaryProps, RenderErrorBoundaryState> {
constructor(props: RenderErrorBoundaryProps);
static getDerivedStateFromError(error: any): {
error: any;
};
static getDerivedStateFromProps(props: RenderErrorBoundaryProps, state: RenderErrorBoundaryState): {
error: any;
location: Location;
};
componentDidCatch(error: any, errorInfo: any): void;
render(): string | number | boolean | React.ReactFragment | JSX.Element | null | undefined;
}
export declare function _renderMatches(matches: RouteMatch[] | null, parentMatches?: RouteMatch[], dataRouterState?: RemixRouter["state"]): React.ReactElement | null;
/**
* Returns the current navigation, defaulting to an "idle" navigation when
* no navigation is in progress
*/
export declare function useNavigation(): import("@remix-run/router").Navigation;
/**
* Returns a revalidate function for manually triggering revalidation, as well
* as the current state of any manual revalidations
*/
export declare function useRevalidator(): {
revalidate: () => void;
state: import("@remix-run/router").RevalidationState;
};
/**
* Returns the active route matches, useful for accessing loaderData for
* parent/child routes or the route "handle" property
*/
export declare function useMatches(): {
id: string;
pathname: string;
params: Params<string>;
data: unknown;
handle: unknown;
}[];
/**
* Returns the loader data for the nearest ancestor Route loader
*/
export declare function useLoaderData(): unknown;
/**
* Returns the loaderData for the given routeId
*/
export declare function useRouteLoaderData(routeId: string): unknown;
/**
* Returns the action data for the nearest ancestor Route action
*/
export declare function useActionData(): unknown;
/**
* Returns the nearest ancestor Route error, which could be a loader/action
* error or a render error. This is intended to be called from your
* errorElement to display a proper error message.
*/
export declare function useRouteError(): unknown;
/**
* Returns the happy-path data from the nearest ancestor <Await /> value
*/
export declare function useAsyncValue(): unknown;
/**
* Returns the error from the nearest ancestor <Await /> value
*/
export declare function useAsyncError(): unknown;
/**
* Allow the application to block navigations within the SPA and present the
* user a confirmation dialog to confirm the navigation. Mostly used to avoid
* using half-filled form data. This does not handle hard-reloads or
* cross-origin navigations.
*/
export declare function useBlocker(shouldBlock: boolean | BlockerFunction): Blocker;
export {};

View File

@ -0,0 +1,7 @@
/**
* Inlined into the react-router repo since use-sync-external-store does not
* provide a UMD-compatible package, so we need this to be able to distribute
* UMD react-router bundles
*/
import { useSyncExternalStore as server } from "./useSyncExternalStoreShimServer";
export declare const useSyncExternalStore: typeof server;

View File

@ -0,0 +1,7 @@
/**
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
export declare function useSyncExternalStore<T>(subscribe: (fn: () => void) => () => void, getSnapshot: () => T, getServerSnapshot?: () => T): T;

View File

@ -0,0 +1,9 @@
/**
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
* @flow
*/
export declare function useSyncExternalStore<T>(subscribe: (fn: () => void) => () => void, getSnapshot: () => T, getServerSnapshot?: () => T): T;

19
node_modules/react-router/dist/main.js generated vendored Normal file
View File

@ -0,0 +1,19 @@
/**
* React Router v6.7.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
*/
'use strict';
/* eslint-env node */
if (process.env.NODE_ENV === "production") {
module.exports = require("./umd/react-router.production.min.js");
} else {
module.exports = require("./umd/react-router.development.js");
}

File diff suppressed because it is too large Load Diff

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

File diff suppressed because it is too large Load Diff

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

43
node_modules/react-router/package.json generated vendored Normal file
View File

@ -0,0 +1,43 @@
{
"name": "react-router",
"version": "6.7.0",
"description": "Declarative routing for React",
"keywords": [
"react",
"router",
"route",
"routing",
"history",
"link"
],
"repository": {
"type": "git",
"url": "https://github.com/remix-run/react-router",
"directory": "packages/react-router"
},
"license": "MIT",
"author": "Remix Software <hello@remix.run>",
"sideEffects": false,
"main": "./dist/main.js",
"unpkg": "./dist/umd/react-router.production.min.js",
"module": "./dist/index.js",
"types": "./dist/index.d.ts",
"dependencies": {
"@remix-run/router": "1.3.0"
},
"devDependencies": {
"react": "^18.2.0"
},
"peerDependencies": {
"react": ">=16.8"
},
"files": [
"dist/",
"CHANGELOG.md",
"LICENSE.md",
"README.md"
],
"engines": {
"node": ">=14"
}
}

5
package.json Normal file
View File

@ -0,0 +1,5 @@
{
"dependencies": {
"react-router-dom": "^6.7.0"
}
}

23
yarn.lock Normal file
View File

@ -0,0 +1,23 @@
# THIS IS AN AUTOGENERATED FILE. DO NOT EDIT THIS FILE DIRECTLY.
# yarn lockfile v1
"@remix-run/router@1.3.0":
version "1.3.0"
resolved "https://registry.yarnpkg.com/@remix-run/router/-/router-1.3.0.tgz#b6ee542c7f087b73b3d8215b9bf799f648be71cb"
integrity sha512-nwQoYb3m4DDpHTeOwpJEuDt8lWVcujhYYSFGLluC+9es2PyLjm+jjq3IeRBQbwBtPLJE/lkuHuGHr8uQLgmJRA==
react-router-dom@^6.7.0:
version "6.7.0"
resolved "https://registry.yarnpkg.com/react-router-dom/-/react-router-dom-6.7.0.tgz#0249f4ca4eb704562b8b0ff29caeb928c3a6ed38"
integrity sha512-jQtXUJyhso3kFw430+0SPCbmCmY1/kJv8iRffGHwHy3CkoomGxeYzMkmeSPYo6Egzh3FKJZRAL22yg5p2tXtfg==
dependencies:
"@remix-run/router" "1.3.0"
react-router "6.7.0"
react-router@6.7.0:
version "6.7.0"
resolved "https://registry.yarnpkg.com/react-router/-/react-router-6.7.0.tgz#db262684c13b5c2970694084ae9e8531718a0681"
integrity sha512-KNWlG622ddq29MAM159uUsNMdbX8USruoKnwMMQcs/QWZgFUayICSn2oB7reHce1zPj6CG18kfkZIunSSRyGHg==
dependencies:
"@remix-run/router" "1.3.0"