@renr/parcel-rsc-router 1.0.0-alpha.8 → 1.0.0-beta.10

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -7,12 +7,13 @@ A client-side router designed for React Server Components (RSC) applications bui
7
7
  ## Features
8
8
 
9
9
  - **Client-side navigation:** Navigate between pages using the `<Link>` component.
10
+ - **Route prefetching:** Automatically prefetches RSC payloads on hover or focus for instant navigation.
10
11
  - **Type safety:** Type-safe route definitions via `@renr/parcel-reporter-rsc-router` (the Link's `to` prop is typed).
11
12
  - **Programmatic navigation:** Control navigation programmatically using the `useRouter` hook.
12
13
  - **Location access:** Access the current URL and its properties with the `useLocation` hook.
13
14
  - **Route data access:** Retrieve data associated with the current route using the `useCurrentRoute` hook.
14
15
  - **Automatic scroll restoration:** Remembers and restores scroll positions when navigating back and forth.
15
- - **Hash scrolling:** Automatically scrolls to elements identified by URL hash.
16
+ - **Instant hash navigation & scrolling:** Automatically scrolls to elements identified by URL hash, handling in-page hash changes instantly without refetching.
16
17
  - **RSC integration:** Navigations fetch the rsc payload for the target route and update the UI without a full page reload.
17
18
 
18
19
  ## Installation
@@ -172,6 +173,7 @@ A component for declarative client-side navigation.
172
173
  children={React.ReactNode}
173
174
  onClick?: (e: React.MouseEvent<HTMLAnchorElement>) => void
174
175
  target?: HTMLAttributeAnchorTarget
176
+ prefetch?: boolean // Defaults to true; prefetches RSC payload on hover and focus
175
177
  {...restProps: React.AnchorHTMLAttributes<HTMLAnchorElement>}
176
178
  />
177
179
  ```
@@ -182,17 +184,19 @@ A component for declarative client-side navigation.
182
184
  - `children`: The content to render inside the link.
183
185
  - `onClick`: Optional click handler.
184
186
  - `target`: Standard `target` attribute for `<a>` tags (e.g., `"_blank"`).
187
+ - `prefetch`: Whether to prefetch the route's RSC stream on hover and focus (default: `true`).
185
188
  - `{...restProps}`: Any other standard HTML `<a>` tag attributes.
186
189
 
187
190
  ### Hooks
188
191
 
189
192
  #### `useRouter()`
190
193
 
191
- Returns an object with methods for programmatic navigation.
194
+ Returns an object with methods for programmatic navigation and prefetching.
192
195
 
193
196
  ```typescript
194
- const { navigate } = useRouter();
197
+ const { navigate, prefetch } = useRouter();
195
198
  navigate(to: string); // Navigates to the specified path.
199
+ await prefetch(to: string); // Prefetches the RSC payload for the path.
196
200
  ```
197
201
 
198
202
  #### `useLocation()`
@@ -1,23 +1,13 @@
1
1
  import { RoutePath } from "./types.mjs";
2
2
  import React, { HTMLAttributeAnchorTarget } from "react";
3
-
4
3
  //#region src/Link.d.ts
5
- declare function Link({
6
- to,
7
- children,
8
- hash,
9
- target,
10
- search,
11
- onClick,
12
- ...props
13
- }: {
4
+ export declare function Link({ to, children, hash, target, search, onClick, onMouseEnter, onFocus, prefetch, ...props }: {
14
5
  to: RoutePath;
15
6
  hash?: string;
16
7
  search?: Record<string, string>;
17
8
  children: React.ReactNode;
18
- onClick?: (e: React.MouseEvent<HTMLAnchorElement>) => void;
19
9
  target?: HTMLAttributeAnchorTarget;
10
+ prefetch?: boolean;
20
11
  } & React.AnchorHTMLAttributes<HTMLAnchorElement>): React.JSX.Element;
21
12
  //#endregion
22
- export { Link };
23
13
  //# sourceMappingURL=Link.d.mts.map
@@ -1 +1 @@
1
- {"version":3,"file":"Link.d.mts","names":[],"sources":["../../src/Link.tsx"],"mappings":";;;;iBAMgB,IAAA,CAAA;EACd,EAAA;EACA,QAAA;EACA,IAAA;EACA,MAAA;EACA,MAAA;EACA,OAAA;EAAA,GACG;AAAA;EAEH,EAAA,EAAI,SAAA;EACJ,IAAA;EACA,MAAA,GAAS,MAAA;EACT,QAAA,EAAU,KAAA,CAAM,SAAA;EAChB,OAAA,IAAW,CAAA,EAAG,KAAA,CAAM,UAAA,CAAW,iBAAA;EAC/B,MAAA,GAAS,yBAAA;AAAA,IACP,KAAA,CAAM,oBAAA,CAAqB,iBAAA,IAAkB,KAAA,CAAA,GAAA,CAAA,OAAA"}
1
+ {"version":3,"file":"Link.d.mts","names":[],"sources":["../../src/Link.tsx"],"mappings":";;;wBAMgB,OACd,IACA,UACA,MACA,QACA,QACA,SACA,cACA,SACA,aACG;EAEH,IAAI;EACJ;EACA,SAAS;EACT,UAAU,MAAM;EAChB,SAAS;EACT;IACE,MAAM,qBAAqB,qBAAkB,MAAA,IAAA"}
package/dist/esm/Link.mjs CHANGED
@@ -1,12 +1,29 @@
1
1
  "use client";
2
2
  import { useRouter } from "./Router.mjs";
3
3
  import React from "react";
4
+ import { jsx } from "react/jsx-runtime";
4
5
  //#region src/Link.tsx
5
- function Link({ to, children, hash, target, search, onClick, ...props }) {
6
- const { navigate } = useRouter();
6
+ function Link({ to, children, hash, target, search, onClick, onMouseEnter, onFocus, prefetch = true, ...props }) {
7
+ const { navigate, prefetch: prefetchRoute } = useRouter();
7
8
  const href = `${to}${hash ? `#${hash}` : ""}${search ? `?${new URLSearchParams(search)}` : ""}`;
8
- return /* @__PURE__ */ React.createElement("a", {
9
+ const handlePrefetch = React.useCallback(() => {
10
+ if (prefetch && (!target || target === "_self") && prefetchRoute) prefetchRoute(to);
11
+ }, [
12
+ prefetch,
13
+ target,
14
+ prefetchRoute,
15
+ to
16
+ ]);
17
+ return /* @__PURE__ */ jsx("a", {
9
18
  href,
19
+ onMouseEnter: (e) => {
20
+ if (onMouseEnter) onMouseEnter(e);
21
+ handlePrefetch();
22
+ },
23
+ onFocus: (e) => {
24
+ if (onFocus) onFocus(e);
25
+ handlePrefetch();
26
+ },
10
27
  onClick: (e) => {
11
28
  if (onClick) onClick(e);
12
29
  if ((!target || target === "_self") && e.button === 0 && !e.metaKey && !e.ctrlKey && !e.altKey && !e.shiftKey && !e.defaultPrevented) {
@@ -14,8 +31,9 @@ function Link({ to, children, hash, target, search, onClick, ...props }) {
14
31
  navigate(href);
15
32
  }
16
33
  },
17
- ...props
18
- }, children);
34
+ ...props,
35
+ children
36
+ });
19
37
  }
20
38
  //#endregion
21
39
  export { Link };
@@ -1 +1 @@
1
- {"version":3,"file":"Link.mjs","names":[],"sources":["../../src/Link.tsx"],"sourcesContent":["\"use client\";\n\nimport React, { type HTMLAttributeAnchorTarget } from \"react\";\nimport { RoutePath } from \"./types.js\";\nimport { useRouter } from \"./Router.js\";\n\nexport function Link({\n to,\n children,\n hash,\n target,\n search,\n onClick,\n ...props\n}: {\n to: RoutePath;\n hash?: string;\n search?: Record<string, string>;\n children: React.ReactNode;\n onClick?: (e: React.MouseEvent<HTMLAnchorElement>) => void;\n target?: HTMLAttributeAnchorTarget;\n} & React.AnchorHTMLAttributes<HTMLAnchorElement>) {\n const { navigate } = useRouter();\n const href = `${to}${hash ? `#${hash}` : \"\"}${search ? `?${new URLSearchParams(search)}` : \"\"}`;\n\n return (\n <a\n href={href}\n onClick={(e) => {\n if (onClick) {\n onClick(e);\n }\n\n if (\n (!target || target === \"_self\") &&\n e.button === 0 && // left clicks only\n !e.metaKey && // open in new tab (mac)\n !e.ctrlKey && // open in new tab (windows)\n !e.altKey && // download\n !e.shiftKey &&\n !e.defaultPrevented\n ) {\n // Intercept link clicks to perform RSC navigation.\n e.preventDefault();\n navigate(href);\n }\n }}\n {...props}\n >\n {children}\n </a>\n );\n}\n"],"mappings":";;;;AAMA,SAAgB,KAAK,EACnB,IACA,UACA,MACA,QACA,QACA,SACA,GAAG,SAQ8C;CACjD,MAAM,EAAE,aAAa,WAAW;CAChC,MAAM,OAAO,GAAG,KAAK,OAAO,IAAI,SAAS,KAAK,SAAS,IAAI,IAAI,gBAAgB,OAAO,KAAK;CAE3F,OACE,sBAAA,cAAC,KAAD;EACQ;EACN,UAAU,MAAM;GACd,IAAI,SACF,QAAQ,EAAE;GAGZ,KACG,CAAC,UAAU,WAAW,YACvB,EAAE,WAAW,KACb,CAAC,EAAE,WACH,CAAC,EAAE,WACH,CAAC,EAAE,UACH,CAAC,EAAE,YACH,CAAC,EAAE,kBACH;IAEA,EAAE,gBAAgB;IAClB,SAAS,KAAK;;;EAGlB,GAAI;EAGF,EADD,SACC"}
1
+ {"version":3,"file":"Link.mjs","names":[],"sources":["../../src/Link.tsx"],"sourcesContent":["\"use client\";\n\nimport React, { type HTMLAttributeAnchorTarget } from \"react\";\nimport { RoutePath } from \"./types.js\";\nimport { useRouter } from \"./Router.js\";\n\nexport function Link({\n to,\n children,\n hash,\n target,\n search,\n onClick,\n onMouseEnter,\n onFocus,\n prefetch = true,\n ...props\n}: {\n to: RoutePath;\n hash?: string;\n search?: Record<string, string>;\n children: React.ReactNode;\n target?: HTMLAttributeAnchorTarget;\n prefetch?: boolean;\n} & React.AnchorHTMLAttributes<HTMLAnchorElement>) {\n const { navigate, prefetch: prefetchRoute } = useRouter();\n const href = `${to}${hash ? `#${hash}` : \"\"}${search ? `?${new URLSearchParams(search)}` : \"\"}`;\n\n const handlePrefetch = React.useCallback(() => {\n if (prefetch && (!target || target === \"_self\") && prefetchRoute) {\n void prefetchRoute(to);\n }\n }, [prefetch, target, prefetchRoute, to]);\n\n return (\n <a\n href={href}\n onMouseEnter={(e) => {\n if (onMouseEnter) {\n onMouseEnter(e);\n }\n handlePrefetch();\n }}\n onFocus={(e) => {\n if (onFocus) {\n onFocus(e);\n }\n handlePrefetch();\n }}\n onClick={(e) => {\n if (onClick) {\n onClick(e);\n }\n\n if (\n (!target || target === \"_self\") &&\n e.button === 0 && // left clicks only\n !e.metaKey && // open in new tab (mac)\n !e.ctrlKey && // open in new tab (windows)\n !e.altKey && // download\n !e.shiftKey &&\n !e.defaultPrevented\n ) {\n // Intercept link clicks to perform RSC navigation.\n e.preventDefault();\n navigate(href);\n }\n }}\n {...props}\n >\n {children}\n </a>\n );\n}\n"],"mappings":";;;;;AAMA,SAAgB,KAAK,EACnB,IACA,UACA,MACA,QACA,QACA,SACA,cACA,SACA,WAAW,MACX,GAAG,SAQ8C;CACjD,MAAM,EAAE,UAAU,UAAU,kBAAkB,UAAU;CACxD,MAAM,OAAO,GAAG,KAAK,OAAO,IAAI,SAAS,KAAK,SAAS,IAAI,IAAI,gBAAgB,MAAM,MAAM;CAE3F,MAAM,iBAAiB,MAAM,kBAAkB;EAC7C,IAAI,aAAa,CAAC,UAAU,WAAW,YAAY,eACjD,cAAmB,EAAE;CAEzB,GAAG;EAAC;EAAU;EAAQ;EAAe;CAAE,CAAC;CAExC,OACE,oBAAC,KAAD;EACQ;EACN,eAAe,MAAM;GACnB,IAAI,cACF,aAAa,CAAC;GAEhB,eAAe;EACjB;EACA,UAAU,MAAM;GACd,IAAI,SACF,QAAQ,CAAC;GAEX,eAAe;EACjB;EACA,UAAU,MAAM;GACd,IAAI,SACF,QAAQ,CAAC;GAGX,KACG,CAAC,UAAU,WAAW,YACvB,EAAE,WAAW,KACb,CAAC,EAAE,WACH,CAAC,EAAE,WACH,CAAC,EAAE,UACH,CAAC,EAAE,YACH,CAAC,EAAE,kBACH;IAEA,EAAE,eAAe;IACjB,SAAS,IAAI;GACf;EACF;EACA,GAAI;EAEH;CACA,CAAA;AAEP"}
@@ -1,25 +1,21 @@
1
1
  import { RouteData } from "./types.mjs";
2
2
  import * as React$1 from "react";
3
-
4
3
  //#region src/Router.d.ts
5
- declare function useRouter(): {
4
+ export declare function useRouter(): {
6
5
  navigate: (to: string) => void;
6
+ prefetch: (to: string) => Promise<void>;
7
7
  };
8
- declare function useLocation(): Location;
9
- declare function useCurrentRoute(): {
10
- rsc: `${string}.rsc`;
11
- url: string;
8
+ export declare function useLocation(): Location;
9
+ export declare function useCurrentRoute(): {
12
10
  path: string;
13
11
  slug: string;
14
12
  html: `${string}.html`;
13
+ rsc: `${string}.rsc`;
14
+ url: string;
15
15
  } | null;
16
- declare const RouterProvider: ({
17
- children,
18
- routes
19
- }: {
16
+ export declare const RouterProvider: ({ children, routes }: {
20
17
  children: React$1.ReactNode;
21
18
  routes: RouteData[];
22
19
  }) => React$1.JSX.Element;
23
20
  //#endregion
24
- export { RouterProvider, useCurrentRoute, useLocation, useRouter };
25
21
  //# sourceMappingURL=Router.d.mts.map
@@ -1 +1 @@
1
- {"version":3,"file":"Router.d.mts","names":[],"sources":["../../src/Router.tsx"],"mappings":";;;;iBAuBgB,SAAA,CAAA;EAAS,QAAA,GAHZ,EAAA;AAAA;AAAA,iBAaG,WAAA,CAAA,GAAW,QAAA;AAAA,iBAQX,eAAA,CAAA;;;;;;;cAeH,cAAA;EAAkB,QAAA;EAAA;AAAA;EAI7B,QAAA,EAAU,OAAA,CAAM,SAAA;EAChB,MAAA,EAAQ,SAAA;AAAA,MACT,OAAA,CAAA,GAAA,CAAA,OAAA"}
1
+ {"version":3,"file":"Router.d.mts","names":["React"],"sources":["../../src/Router.tsx"],"mappings":";;;wBA2BgB;EAJJ,WAAC;EACD,WAAC,eAAe;;wBAeZ,eAAe;wBAQf;;;;;;;qBAeH,mBAAc,UAAA;EAIzB,UAAUA,QAAM;EAChB,QAAQ;MACTA,QAAA,IAAA"}
@@ -1,10 +1,12 @@
1
1
  "use client";
2
2
  import { createHistory } from "./history.mjs";
3
3
  import { getPathData } from "./util.mjs";
4
- import { navigate } from "./rsc.mjs";
4
+ import { navigate, prefetch } from "./rsc.mjs";
5
5
  import * as React$1 from "react";
6
6
  import { useSyncExternalStore } from "react";
7
+ import { jsx } from "react/jsx-runtime";
7
8
  //#region src/Router.tsx
9
+ const useIsomorphicLayoutEffect = typeof window !== "undefined" ? React$1.useLayoutEffect : React$1.useEffect;
8
10
  const RoutesContext = React$1.createContext(null);
9
11
  const useRoutes = () => {
10
12
  const routes = React$1.useContext(RoutesContext);
@@ -17,16 +19,16 @@ function useRouter() {
17
19
  if (context === null) throw new Error("useRouter must be used within a RouterProvider");
18
20
  return context;
19
21
  }
20
- const LocationContext = React$1.createContext(null);
22
+ const LocationContext = React$1.createContext(void 0);
21
23
  function useLocation() {
22
24
  const context = React$1.useContext(LocationContext);
23
- if (context === null) throw new Error("useLocation must be used within a RouterProvider");
25
+ if (context === void 0) throw new Error("useLocation must be used within a RouterProvider");
24
26
  return context;
25
27
  }
26
28
  function useCurrentRoute() {
27
29
  const location = useLocation();
28
30
  const routes = useRoutes();
29
- return getPathData(location.pathname, routes);
31
+ return location ? getPathData(location.pathname, routes) : null;
30
32
  }
31
33
  const history = createHistory();
32
34
  const ssrSnapshot = {
@@ -36,16 +38,26 @@ const ssrSnapshot = {
36
38
  const getSsrSnapshot = () => ssrSnapshot;
37
39
  const RouterProvider = ({ children, routes }) => {
38
40
  const { location, state } = useSyncExternalStore(history.subscribe, history.getSnapshot, getSsrSnapshot);
41
+ const href = location === null || location === void 0 ? void 0 : location.href;
39
42
  const navigate$1 = React$1.useCallback((to) => {
40
43
  var _history$snapshot$sta, _history$snapshot$sta2;
41
- if (!(location === null || location === void 0 ? void 0 : location.href)) throw new Error("Location is not available");
42
- if (location.href === new URL(to, location.href).href) return;
43
- history.replace(location.href, {
44
+ if (!href) throw new Error("Location is not available");
45
+ const targetUrl = new URL(to, href);
46
+ if (href === targetUrl.href) return;
47
+ history.replace(href, {
44
48
  ...history.snapshot.state,
45
49
  key: (_history$snapshot$sta = (_history$snapshot$sta2 = history.snapshot.state) === null || _history$snapshot$sta2 === void 0 ? void 0 : _history$snapshot$sta2.key) !== null && _history$snapshot$sta !== void 0 ? _history$snapshot$sta : Math.random().toString(36).slice(2),
46
50
  scrollX: window.scrollX,
47
51
  scrollY: window.scrollY
48
52
  });
53
+ if ((location === null || location === void 0 ? void 0 : location.pathname) === targetUrl.pathname && (location === null || location === void 0 ? void 0 : location.search) === targetUrl.search && (location === null || location === void 0 ? void 0 : location.hash) !== targetUrl.hash) {
54
+ history.push(targetUrl.pathname + targetUrl.search + targetUrl.hash, {
55
+ key: Math.random().toString(36).slice(2),
56
+ scrollX: window.scrollX,
57
+ scrollY: window.scrollY
58
+ });
59
+ return;
60
+ }
49
61
  navigate(to, routes, (url) => {
50
62
  history.push(url, {
51
63
  key: Math.random().toString(36).slice(2),
@@ -53,8 +65,20 @@ const RouterProvider = ({ children, routes }) => {
53
65
  scrollY: 0
54
66
  });
55
67
  });
56
- }, [routes, location === null || location === void 0 ? void 0 : location.href]);
57
- const routerContextValue = React$1.useMemo(() => ({ navigate: navigate$1 }), [navigate$1]);
68
+ }, [
69
+ routes,
70
+ href,
71
+ location === null || location === void 0 ? void 0 : location.pathname,
72
+ location === null || location === void 0 ? void 0 : location.search,
73
+ location === null || location === void 0 ? void 0 : location.hash
74
+ ]);
75
+ const prefetch$1 = React$1.useCallback(async (to) => {
76
+ await prefetch(to, routes);
77
+ }, [routes]);
78
+ const routerContextValue = React$1.useMemo(() => ({
79
+ navigate: navigate$1,
80
+ prefetch: prefetch$1
81
+ }), [navigate$1, prefetch$1]);
58
82
  React$1.useEffect(() => {
59
83
  const handlePopState = () => {
60
84
  navigate(window.location.pathname, routes, () => {}, { push: false });
@@ -62,14 +86,16 @@ const RouterProvider = ({ children, routes }) => {
62
86
  window.addEventListener("popstate", handlePopState);
63
87
  return () => window.removeEventListener("popstate", handlePopState);
64
88
  }, [routes]);
65
- React$1.useLayoutEffect(() => {
66
- if (location === null || location === void 0 ? void 0 : location.hash) {
67
- const element = document.querySelector(location.hash);
89
+ useIsomorphicLayoutEffect(() => {
90
+ if (location === null || location === void 0 ? void 0 : location.hash) try {
91
+ var _document$getElementB;
92
+ const id = decodeURIComponent(location.hash.slice(1));
93
+ const element = (_document$getElementB = document.getElementById(id)) !== null && _document$getElementB !== void 0 ? _document$getElementB : document.querySelector(location.hash);
68
94
  if (element) {
69
95
  element.scrollIntoView();
70
96
  return;
71
97
  }
72
- }
98
+ } catch (_unused) {}
73
99
  if ((state === null || state === void 0 ? void 0 : state.scrollY) !== void 0) window.scrollTo(state.scrollX, state.scrollY);
74
100
  else window.scrollTo(0, 0);
75
101
  }, [
@@ -77,9 +103,18 @@ const RouterProvider = ({ children, routes }) => {
77
103
  location === null || location === void 0 ? void 0 : location.hash,
78
104
  state
79
105
  ]);
80
- return /* @__PURE__ */ React$1.createElement(RoutesContext.Provider, { value: routes }, /* @__PURE__ */ React$1.createElement(LocationContext.Provider, { value: location }, /* @__PURE__ */ React$1.createElement(RouterContext.Provider, { value: routerContextValue }, children)));
106
+ return /* @__PURE__ */ jsx(RoutesContext.Provider, {
107
+ value: routes,
108
+ children: /* @__PURE__ */ jsx(LocationContext.Provider, {
109
+ value: location,
110
+ children: /* @__PURE__ */ jsx(RouterContext.Provider, {
111
+ value: routerContextValue,
112
+ children
113
+ })
114
+ })
115
+ });
81
116
  };
82
117
  //#endregion
83
- export { RouterProvider, useCurrentRoute, useLocation, useRouter };
118
+ export { RouterProvider, useCurrentRoute, useLocation, useRouter, useRoutes };
84
119
 
85
120
  //# sourceMappingURL=Router.mjs.map
@@ -1 +1 @@
1
- {"version":3,"file":"Router.mjs","names":["React","navigate","rscNavigate"],"sources":["../../src/Router.tsx"],"sourcesContent":["\"use client\";\n\nimport * as React from \"react\";\nimport { useSyncExternalStore } from \"react\";\nimport { createHistory } from \"./history.js\";\nimport { navigate as rscNavigate } from \"./rsc.js\";\nimport { RouteData } from \"./types.js\";\nimport { getPathData } from \"./util.js\";\n\nconst RoutesContext = React.createContext<RouteData[] | null>(null);\n\nexport const useRoutes = () => {\n const routes = React.useContext(RoutesContext);\n if (routes === null) {\n throw new Error(\"useRoutes must be used within a RouterProvider\");\n }\n return routes;\n};\n\nconst RouterContext = React.createContext<{\n navigate: (to: string) => void;\n} | null>(null);\n\nexport function useRouter() {\n const context = React.useContext(RouterContext);\n if (context === null) {\n throw new Error(\"useRouter must be used within a RouterProvider\");\n }\n return context;\n}\n\nconst LocationContext = React.createContext<Location | null>(null);\n\nexport function useLocation() {\n const context = React.useContext(LocationContext);\n if (context === null) {\n throw new Error(\"useLocation must be used within a RouterProvider\");\n }\n return context;\n}\n\nexport function useCurrentRoute() {\n const location = useLocation();\n const routes = useRoutes();\n return getPathData(location.pathname, routes);\n}\n\nconst history = createHistory();\n\nconst ssrSnapshot = {\n location: null,\n state: null,\n};\n\nconst getSsrSnapshot = () => ssrSnapshot;\n\nexport const RouterProvider = ({\n children,\n routes,\n}: {\n children: React.ReactNode;\n routes: RouteData[];\n}) => {\n // subscribe to history changes\n const { location, state } = useSyncExternalStore(\n history.subscribe,\n history.getSnapshot,\n getSsrSnapshot\n );\n\n const navigate = React.useCallback(\n (to: string) => {\n if (!location?.href) {\n throw new Error(\"Location is not available\");\n }\n\n if (location.href === new URL(to, location.href).href) {\n return;\n }\n\n // save scroll position for the current entry\n history.replace(location.href, {\n ...history.snapshot.state,\n key: history.snapshot.state?.key ?? Math.random().toString(36).slice(2),\n scrollX: window.scrollX,\n scrollY: window.scrollY,\n });\n\n void rscNavigate(to, routes, (url) => {\n history.push(url, {\n key: Math.random().toString(36).slice(2),\n scrollX: 0,\n scrollY: 0,\n });\n });\n },\n [routes, location?.href]\n );\n\n const routerContextValue = React.useMemo(() => ({ navigate }), [navigate]);\n\n React.useEffect(() => {\n const handlePopState = () => {\n void rscNavigate(\n window.location.pathname,\n routes,\n () => {\n // noop, history is already updated\n },\n { push: false }\n );\n };\n\n window.addEventListener(\"popstate\", handlePopState);\n return () => window.removeEventListener(\"popstate\", handlePopState);\n }, [routes]);\n\n React.useLayoutEffect(() => {\n // hash scrolling takes priority\n if (location?.hash) {\n const element = document.querySelector(location.hash);\n if (element) {\n element.scrollIntoView();\n return;\n }\n }\n\n // otherwise use saved scroll position\n if (state?.scrollY !== undefined) {\n window.scrollTo(state.scrollX, state.scrollY);\n } else {\n window.scrollTo(0, 0);\n }\n }, [location?.pathname, location?.hash, state]);\n\n return (\n <RoutesContext.Provider value={routes}>\n <LocationContext.Provider value={location}>\n <RouterContext.Provider value={routerContextValue}>\n {children}\n </RouterContext.Provider>\n </LocationContext.Provider>\n </RoutesContext.Provider>\n );\n};\n"],"mappings":";;;;;;;AASA,MAAM,gBAAgBA,QAAM,cAAkC,KAAK;AAEnE,MAAa,kBAAkB;CAC7B,MAAM,SAASA,QAAM,WAAW,cAAc;CAC9C,IAAI,WAAW,MACb,MAAM,IAAI,MAAM,iDAAiD;CAEnE,OAAO;;AAGT,MAAM,gBAAgBA,QAAM,cAElB,KAAK;AAEf,SAAgB,YAAY;CAC1B,M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aAAA,QAAA,aAAA,KAAA,IAAA,KAAA,IAAQ,SAAU,KAAK,CACzB;CAED,MAAM,qBAAqBA,QAAM,eAAe,EAAE,UAAA,YAAU,GAAG,CAACC,WAAS,CAAC;CAE1E,QAAM,gBAAgB;EACpB,MAAM,uBAAuB;GAC3B,SACE,OAAO,SAAS,UAChB,cACM,IAGN,EAAE,MAAM,OAAO,CAChB;;EAGH,OAAO,iBAAiB,YAAY,eAAe;EACnD,aAAa,OAAO,oBAAoB,YAAY,eAAe;IAClE,CAAC,OAAO,CAAC;CAEZ,QAAM,sBAAsB;EAE1B,IAAA,aAAA,QAAA,aAAA,KAAA,IAAA,KAAA,IAAI,SAAU,MAAM;GAClB,MAAM,UAAU,SAAS,cAAc,SAAS,KAAK;GACrD,IAAI,SAAS;IACX,QAAQ,gBAAgB;IACxB;;;EAKJ,KAAA,UAAA,QAAA,UAAA,KAAA,IAAA,KAAA,IAAI,MAAO,aAAY,KAAA,GACrB,OAAO,SAAS,MAAM,SAAS,MAAM,QAAQ;OAE7C,OAAO,SAAS,GAAG,EAAE;IAEtB;sDAAC,SAAU;sDAAU,SAAU;EAAM;EAAM,CAAC;CAE/C,OACE,wBAAA,cAAC,cAAc,UAAf,EAAwB,OAAO,QAMN,EALvB,wBAAA,cAAC,gBAAgB,UAAjB,EAA0B,OAAO,UAIN,EAHzB,wBAAA,cAAC,cAAc,UAAf,EAAwB,OAAO,oBAEN,EADtB,SACsB,CACA,CACJ"}
1
+ {"version":3,"file":"Router.mjs","names":["React","navigate","rscNavigate","prefetch","rscPrefetch"],"sources":["../../src/Router.tsx"],"sourcesContent":["\"use client\";\n\nimport * as React from \"react\";\nimport { useSyncExternalStore } from \"react\";\nimport { createHistory } from \"./history.js\";\nimport { navigate as rscNavigate, prefetch as rscPrefetch } from \"./rsc.js\";\nimport { RouteData } from \"./types.js\";\nimport { getPathData } from \"./util.js\";\n\nconst useIsomorphicLayoutEffect =\n typeof window !== \"undefined\" ? React.useLayoutEffect : React.useEffect;\n\nconst RoutesContext = React.createContext<RouteData[] | null>(null);\n\nexport const useRoutes = () => {\n const routes = React.useContext(RoutesContext);\n if (routes === null) {\n throw new Error(\"useRoutes must be used within a RouterProvider\");\n }\n return routes;\n};\n\nconst RouterContext = React.createContext<{\n navigate: (to: string) => void;\n prefetch: (to: string) => Promise<void>;\n} | null>(null);\n\nexport function useRouter() {\n const context = React.useContext(RouterContext);\n if (context === null) {\n throw new Error(\"useRouter must be used within a RouterProvider\");\n }\n return context;\n}\n\nconst LocationContext = React.createContext<Location | null | undefined>(\n undefined\n);\n\nexport function useLocation(): Location {\n const context = React.useContext(LocationContext);\n if (context === undefined) {\n throw new Error(\"useLocation must be used within a RouterProvider\");\n }\n return context as Location;\n}\n\nexport function useCurrentRoute() {\n const location = useLocation();\n const routes = useRoutes();\n return location ? getPathData(location.pathname, routes) : null;\n}\n\nconst history = createHistory();\n\nconst ssrSnapshot = {\n location: null,\n state: null,\n};\n\nconst getSsrSnapshot = () => ssrSnapshot;\n\nexport const RouterProvider = ({\n children,\n routes,\n}: {\n children: React.ReactNode;\n routes: RouteData[];\n}) => {\n // subscribe to history changes\n const { location, state } = useSyncExternalStore(\n history.subscribe,\n history.getSnapshot,\n getSsrSnapshot\n );\n\n const href = location?.href;\n\n const navigate = React.useCallback(\n (to: string) => {\n if (!href) {\n throw new Error(\"Location is not available\");\n }\n\n const targetUrl = new URL(to, href);\n\n if (href === targetUrl.href) {\n return;\n }\n\n // save scroll position for the current entry\n history.replace(href, {\n ...history.snapshot.state,\n key: history.snapshot.state?.key ?? Math.random().toString(36).slice(2),\n scrollX: window.scrollX,\n scrollY: window.scrollY,\n });\n\n // If only hash changed on the current page, skip RSC refetch and navigate directly\n if (\n location?.pathname === targetUrl.pathname &&\n location?.search === targetUrl.search &&\n location?.hash !== targetUrl.hash\n ) {\n history.push(targetUrl.pathname + targetUrl.search + targetUrl.hash, {\n key: Math.random().toString(36).slice(2),\n scrollX: window.scrollX,\n scrollY: window.scrollY,\n });\n return;\n }\n\n void rscNavigate(to, routes, (url) => {\n history.push(url, {\n key: Math.random().toString(36).slice(2),\n scrollX: 0,\n scrollY: 0,\n });\n });\n },\n [routes, href, location?.pathname, location?.search, location?.hash]\n );\n\n const prefetch = React.useCallback(\n async (to: string) => {\n await rscPrefetch(to, routes);\n },\n [routes]\n );\n\n const routerContextValue = React.useMemo(\n () => ({ navigate, prefetch }),\n [navigate, prefetch]\n );\n\n React.useEffect(() => {\n const handlePopState = () => {\n void rscNavigate(\n window.location.pathname,\n routes,\n () => {\n // noop, history is already updated\n },\n { push: false }\n );\n };\n\n window.addEventListener(\"popstate\", handlePopState);\n return () => window.removeEventListener(\"popstate\", handlePopState);\n }, [routes]);\n\n useIsomorphicLayoutEffect(() => {\n // hash scrolling takes priority\n if (location?.hash) {\n try {\n const id = decodeURIComponent(location.hash.slice(1));\n const element =\n document.getElementById(id) ?? document.querySelector(location.hash);\n if (element) {\n element.scrollIntoView();\n return;\n }\n } catch {\n // Ignore invalid CSS selector syntax in hash\n }\n }\n\n // otherwise use saved scroll position\n if (state?.scrollY !== undefined) {\n window.scrollTo(state.scrollX, state.scrollY);\n } else {\n window.scrollTo(0, 0);\n }\n }, [location?.pathname, location?.hash, state]);\n\n return (\n <RoutesContext.Provider value={routes}>\n <LocationContext.Provider value={location}>\n <RouterContext.Provider value={routerContextValue}>\n {children}\n </RouterContext.Provider>\n </LocationContext.Provider>\n </RoutesContext.Provider>\n );\n};\n"],"mappings":";;;;;;;;AASA,MAAM,4BACJ,OAAO,WAAW,cAAcA,QAAM,kBAAkBA,QAAM;AAEhE,MAAM,gBAAgBA,QAAM,cAAkC,IAAI;AAElE,MAAa,kBAAkB;CAC7B,MAAM,SAASA,QAAM,WAAW,aAAa;CAC7C,IAAI,WAAW,MACb,MAAM,IAAI,MAAM,gDAAgD;CAElE,OAAO;AACT;AAEA,MAAM,gBAAgBA,QAAM,cAGlB,IAAI;AAEd,SAAgB,YAAY;CAC1B,MAAM,UAAUA,QAAM,WAA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,EAAE,OAAA,QAAA,0BAAA,KAAA,IAAA,wBAAK,SAAS,cAAc,SAAS,IAAI;GACrE,IAAI,SAAS;IACX,QAAQ,eAAe;IACvB;GACF;EACF,SAAA,SAAQ,CAER;EAIF,KAAA,UAAA,QAAA,UAAA,KAAA,IAAA,KAAA,IAAI,MAAO,aAAY,KAAA,GACrB,OAAO,SAAS,MAAM,SAAS,MAAM,OAAO;OAE5C,OAAO,SAAS,GAAG,CAAC;CAExB,GAAG;EAAC,aAAA,QAAA,aAAA,KAAA,IAAA,KAAA,IAAA,SAAU;EAAU,aAAA,QAAA,aAAA,KAAA,IAAA,KAAA,IAAA,SAAU;EAAM;CAAK,CAAC;CAE9C,OACE,oBAAC,cAAc,UAAf;EAAwB,OAAO;EAC7B,UAAA,oBAAC,gBAAgB,UAAjB;GAA0B,OAAO;GAC/B,UAAA,oBAAC,cAAc,UAAf;IAAwB,OAAO;IAC5B;GACqB,CAAA;EACA,CAAA;CACJ,CAAA;AAE5B"}
@@ -1,7 +1,7 @@
1
1
  "use client-entry";
2
2
  import { hydrate } from "@parcel/rsc/client";
3
3
  //#region src/client-entry.ts
4
- const updateRoot = hydrate({});
4
+ const updateRoot = hydrate();
5
5
  //#endregion
6
6
  export { updateRoot };
7
7
 
@@ -1 +1 @@
1
- {"version":3,"file":"client-entry.mjs","names":[],"sources":["../../src/client-entry.ts"],"sourcesContent":["\"use client-entry\";\n\nimport { hydrate } from \"@parcel/rsc/client\";\n\n//TODO https://github.com/microsoft/TypeScript/issues/42873#issuecomment-1416128545\nexport const updateRoot: ReturnType<typeof hydrate> = hydrate({\n // TODO - can't build due to reading window\n // onHmrReload() {},\n});\n"],"mappings":";;;AAKA,MAAa,aAAyC,QAAQ,EAG7D,CAAC"}
1
+ {"version":3,"file":"client-entry.mjs","names":[],"sources":["../../src/client-entry.ts"],"sourcesContent":["\"use client-entry\";\n\nimport { hydrate } from \"@parcel/rsc/client\";\nimport type { ReactNode } from \"react\";\n\nexport const updateRoot: (value: ReactNode, cb?: () => void) => void =\n hydrate();\n"],"mappings":";;;AAKA,MAAa,aACX,QAAQ"}
@@ -4,6 +4,10 @@ function createHistory() {
4
4
  const listeners = /* @__PURE__ */ new Set();
5
5
  let currentSnapshot;
6
6
  const getSnapshot = () => {
7
+ if (typeof window === "undefined") return {
8
+ location: null,
9
+ state: null
10
+ };
7
11
  const newSnapshot = {
8
12
  location: window.location,
9
13
  state: window.history.state
@@ -26,11 +30,11 @@ function createHistory() {
26
30
  };
27
31
  },
28
32
  push(url, state) {
29
- window.history.pushState(state, "", url);
33
+ if (typeof window !== "undefined") window.history.pushState(state, "", url);
30
34
  queueMicrotask(() => listeners.forEach((listener) => listener()));
31
35
  },
32
36
  replace(url, state) {
33
- window.history.replaceState(state, "", url);
37
+ if (typeof window !== "undefined") window.history.replaceState(state, "", url);
34
38
  }
35
39
  };
36
40
  }
@@ -1 +1 @@
1
- {"version":3,"file":"history.mjs","names":[],"sources":["../../src/history.ts"],"sourcesContent":["\"use client\";\n\n// basic history management\n\nexport type HistoryState = {\n key: string;\n scrollX: number;\n scrollY: number;\n};\n\nexport function createHistory() {\n const listeners = new Set<() => void>();\n let currentSnapshot: {\n location: Location | null;\n state: HistoryState | null;\n };\n\n const getSnapshot = () => {\n const newSnapshot = {\n location: window.location,\n state: window.history.state as HistoryState | null,\n };\n // Only update currentSnapshot if something actually changed to prevent infinite loops\n if (\n !currentSnapshot ||\n currentSnapshot.location !== newSnapshot.location ||\n currentSnapshot.state !== newSnapshot.state\n ) {\n currentSnapshot = newSnapshot;\n }\n return currentSnapshot;\n };\n\n if (typeof window !== \"undefined\") {\n window.addEventListener(\"popstate\", () => {\n // notify listeners - do it in a microtask to avoid scheduling react updates\n queueMicrotask(() => listeners.forEach((listener) => listener()));\n });\n }\n\n return {\n get snapshot() {\n return getSnapshot();\n },\n\n getSnapshot,\n\n subscribe(this: void, listener: () => void) {\n listeners.add(listener);\n return () => {\n listeners.delete(listener);\n };\n },\n\n push(url: string, state: HistoryState) {\n window.history.pushState(state, \"\", url);\n // notify listeners - do it in a microtask to avoid scheduling react updates\n queueMicrotask(() => listeners.forEach((listener) => listener()));\n },\n\n replace(url: string, state: HistoryState) {\n window.history.replaceState(state, \"\", url);\n // don't notify listeners on replace, as it's for non-navigation changes\n },\n };\n}\n\nexport type BrowserHistory = ReturnType<typeof createHistory>;\n"],"mappings":";;AAUA,SAAgB,gBAAgB;CAC9B,MAAM,4BAAY,IAAI,KAAiB;CACvC,IAAI;CAKJ,MAAM,oBAAoB;EACxB,MAAM,cAAc;GAClB,UAAU,OAAO;GACjB,OAAO,OAAO,QAAQ;GACvB;EAED,IACE,CAAC,mBACD,gBAAgB,aAAa,YAAY,YACzC,gBAAgB,UAAU,YAAY,OAEtC,kBAAkB;EAEpB,OAAO;;CAGT,IAAI,OAAO,WAAW,aACpB,OAAO,iBAAiB,kBAAkB;EAExC,qBAAqB,UAAU,SAAS,aAAa,UAAU,CAAC,CAAC;GACjE;CAGJ,OAAO;EACL,IAAI,WAAW;GACb,OAAO,aAAa;;EAGtB;EAEA,UAAsB,UAAsB;GAC1C,UAAU,IAAI,SAAS;GACvB,aAAa;IACX,UAAU,OAAO,SAAS;;;EAI9B,KAAK,KAAa,OAAqB;GACrC,OAAO,QAAQ,UAAU,OAAO,IAAI,IAAI;GAExC,qBAAqB,UAAU,SAAS,aAAa,UAAU,CAAC,CAAC;;EAGnE,QAAQ,KAAa,OAAqB;GACxC,OAAO,QAAQ,aAAa,OAAO,IAAI,IAAI;;EAG9C"}
1
+ {"version":3,"file":"history.mjs","names":[],"sources":["../../src/history.ts"],"sourcesContent":["\"use client\";\n\n// basic history management\n\nexport type HistoryState = {\n key: string;\n scrollX: number;\n scrollY: number;\n};\n\nexport function createHistory() {\n const listeners = new Set<() => void>();\n let currentSnapshot: {\n location: Location | null;\n state: HistoryState | null;\n };\n\n const getSnapshot = () => {\n if (typeof window === \"undefined\") {\n return {\n location: null,\n state: null,\n };\n }\n\n const newSnapshot = {\n location: window.location,\n state: window.history.state as HistoryState | null,\n };\n // Only update currentSnapshot if something actually changed to prevent infinite loops\n if (\n !currentSnapshot ||\n currentSnapshot.location !== newSnapshot.location ||\n currentSnapshot.state !== newSnapshot.state\n ) {\n currentSnapshot = newSnapshot;\n }\n return currentSnapshot;\n };\n\n if (typeof window !== \"undefined\") {\n window.addEventListener(\"popstate\", () => {\n // notify listeners - do it in a microtask to avoid scheduling react updates\n queueMicrotask(() => listeners.forEach((listener) => listener()));\n });\n }\n\n return {\n get snapshot() {\n return getSnapshot();\n },\n\n getSnapshot,\n\n subscribe(this: void, listener: () => void) {\n listeners.add(listener);\n return () => {\n listeners.delete(listener);\n };\n },\n\n push(url: string, state: HistoryState) {\n if (typeof window !== \"undefined\") {\n window.history.pushState(state, \"\", url);\n }\n // notify listeners - do it in a microtask to avoid scheduling react updates\n queueMicrotask(() => listeners.forEach((listener) => listener()));\n },\n\n replace(url: string, state: HistoryState) {\n if (typeof window !== \"undefined\") {\n window.history.replaceState(state, \"\", url);\n }\n // don't notify listeners on replace, as it's for non-navigation changes\n },\n };\n}\n\nexport type BrowserHistory = ReturnType<typeof createHistory>;\n"],"mappings":";;AAUA,SAAgB,gBAAgB;CAC9B,MAAM,4BAAY,IAAI,IAAgB;CACtC,IAAI;CAKJ,MAAM,oBAAoB;EACxB,IAAI,OAAO,WAAW,aACpB,OAAO;GACL,UAAU;GACV,OAAO;EACT;EAGF,MAAM,cAAc;GAClB,UAAU,OAAO;GACjB,OAAO,OAAO,QAAQ;EACxB;EAEA,IACE,CAAC,mBACD,gBAAgB,aAAa,YAAY,YACzC,gBAAgB,UAAU,YAAY,OAEtC,kBAAkB;EAEpB,OAAO;CACT;CAEA,IAAI,OAAO,WAAW,aACpB,OAAO,iBAAiB,kBAAkB;EAExC,qBAAqB,UAAU,SAAS,aAAa,SAAS,CAAC,CAAC;CAClE,CAAC;CAGH,OAAO;EACL,IAAI,WAAW;GACb,OAAO,YAAY;EACrB;EAEA;EAEA,UAAsB,UAAsB;GAC1C,UAAU,IAAI,QAAQ;GACtB,aAAa;IACX,UAAU,OAAO,QAAQ;GAC3B;EACF;EAEA,KAAK,KAAa,OAAqB;GACrC,IAAI,OAAO,WAAW,aACpB,OAAO,QAAQ,UAAU,OAAO,IAAI,GAAG;GAGzC,qBAAqB,UAAU,SAAS,aAAa,SAAS,CAAC,CAAC;EAClE;EAEA,QAAQ,KAAa,OAAqB;GACxC,IAAI,OAAO,WAAW,aACpB,OAAO,QAAQ,aAAa,OAAO,IAAI,GAAG;EAG9C;CACF;AACF"}
package/dist/esm/rsc.mjs CHANGED
@@ -4,7 +4,6 @@ import { getPathData } from "./util.mjs";
4
4
  import { fetchRSC } from "@parcel/rsc/client";
5
5
  //#region src/rsc.ts
6
6
  async function navigate(pathname, routes, onPush, { push = true } = {}) {
7
- console.debug("client navigating to:", pathname);
8
7
  let shouldPush = push;
9
8
  const path = getPathData(pathname, routes);
10
9
  if (!path) {
@@ -16,18 +15,16 @@ async function navigate(pathname, routes, onPush, { push = true } = {}) {
16
15
  }
17
16
  if (path.url === location.pathname) shouldPush = false;
18
17
  try {
19
- updateRoot(await fetchRSCWithPreloadCache(path.rsc), () => {
18
+ const root = await fetchRSCWithPreloadCache(path.rsc);
19
+ updateRoot(root, () => {
20
20
  if (shouldPush) onPush(path.url);
21
21
  });
22
22
  } catch (e) {
23
- console.log(`Error fetching ${path.path} RSC`, e);
23
+ console.error(`Error fetching ${path.path} RSC`, e);
24
24
  }
25
25
  }
26
26
  async function fetchRSCWithPreloadCache(url, options) {
27
- if (fetchCache.has(url)) {
28
- console.log("Cache hit", url);
29
- return fetchCache.get(url);
30
- }
27
+ if (fetchCache.has(url)) return fetchCache.get(url);
31
28
  const promise = fetchRSC(url, options);
32
29
  fetchCache.set(url, promise);
33
30
  while (fetchCache.size > 5) {
@@ -43,7 +40,20 @@ async function fetchRSCWithPreloadCache(url, options) {
43
40
  });
44
41
  }
45
42
  const fetchCache = /* @__PURE__ */ new Map();
43
+ async function prefetch(pathname, routes, signal) {
44
+ const path = getPathData(pathname, routes);
45
+ if (!path) return;
46
+ try {
47
+ await fetchRSCWithPreloadCache(path.rsc, { signal });
48
+ } catch (error) {
49
+ if ((signal === null || signal === void 0 ? void 0 : signal.aborted) || error instanceof Error && error.name === "AbortError") return;
50
+ if (error instanceof Error) {
51
+ console.error(`Error prefetching ${pathname} RSC`, error);
52
+ return;
53
+ }
54
+ }
55
+ }
46
56
  //#endregion
47
- export { navigate };
57
+ export { fetchCache, navigate, prefetch };
48
58
 
49
59
  //# sourceMappingURL=rsc.mjs.map
@@ -1 +1 @@
1
- {"version":3,"file":"rsc.mjs","names":[],"sources":["../../src/rsc.ts"],"sourcesContent":["\"use client\";\n\nimport { type RSCRequestInit, fetchRSC } from \"@parcel/rsc/client\";\nimport { type ReactNode } from \"react\";\nimport { updateRoot } from \"./client-entry.js\";\nimport { RouteData } from \"./types.js\";\nimport { getPathData } from \"./util.js\";\n\n// fetch and push an rsc route\nexport async function navigate(\n pathname: string,\n routes: RouteData[],\n /** callback for a successful navigation (use this to update the history) */\n onPush: (url: string) => void,\n { push = true }: { push?: boolean } = {}\n) {\n console.debug(\"client navigating to:\", pathname);\n\n let shouldPush = push;\n\n const path = getPathData(pathname, routes);\n\n if (!path) {\n console.warn(`No route found for ${pathname}`);\n\n if (routes.some((r) => r.path === \"/404\")) {\n // we have a 404 page, navigate there\n void navigate(\"/404\", routes, () => {\n // show the original not found path (rather than 404) in the URL\n onPush(pathname);\n });\n }\n\n return;\n }\n\n // Don't add to history if we're already on this page\n if (path.url === location.pathname) {\n shouldPush = false;\n }\n\n try {\n const root = await fetchRSCWithPreloadCache<ReactNode>(path.rsc);\n\n updateRoot(root, () => {\n if (shouldPush) {\n onPush(path.url);\n }\n });\n\n // after a successful navigation, we can clear the cache\n // note everything is static currently, we don't need to clear the cache\n // fetchCache.clear();\n } catch (e) {\n console.log(`Error fetching ${path.path} RSC`, e);\n }\n}\n\nasync function fetchRSCWithPreloadCache<T>(\n url: string | URL | Request,\n options?: RSCRequestInit\n): Promise<T> {\n if (fetchCache.has(url)) {\n console.log(\"Cache hit\", url);\n\n return fetchCache.get(url) as Promise<T>;\n }\n\n const promise = fetchRSC<T>(url, options);\n\n fetchCache.set(url, promise);\n\n // keep the cache small, removing the oldest entries\n while (fetchCache.size > 5) {\n const firstKey = fetchCache.keys().next().value;\n\n if (!firstKey) {\n break;\n }\n\n fetchCache.delete(firstKey);\n }\n\n return promise\n .then((data) => {\n return data;\n })\n .catch((error) => {\n fetchCache.delete(url);\n\n throw error;\n });\n}\n\nexport const fetchCache = new Map<string | URL | Request, Promise<unknown>>();\n\nexport async function prefetch(\n pathname: string,\n routes: RouteData[],\n signal?: AbortSignal\n) {\n const path = getPathData(pathname, routes);\n\n if (!path) {\n return;\n }\n\n try {\n await fetchRSCWithPreloadCache<ReactNode>(path.rsc, { signal });\n } catch (error) {\n if (error instanceof Error) {\n console.error(`Error fetching ${pathname} RSC`, error);\n\n return;\n }\n\n // don't throw if the signal is aborted - this is expected\n if (signal?.aborted) {\n console.log(signal.reason);\n\n return;\n }\n }\n}\n"],"mappings":";;;;;AASA,eAAsB,SACpB,UACA,QAEA,QACA,EAAE,OAAO,SAA6B,EAAE,EACxC;CACA,QAAQ,MAAM,yBAAyB,SAAS;CAEhD,IAAI,aAAa;CAEjB,MAAM,OAAO,YAAY,UAAU,OAAO;CAE1C,IAAI,CAAC,MAAM;EACT,QAAQ,KAAK,sBAAsB,WAAW;EAE9C,IAAI,OAAO,MAAM,MAAM,EAAE,SAAS,OAAO,EAEvC,SAAc,QAAQ,cAAc;GAElC,OAAO,SAAS;IAChB;EAGJ;;CAIF,IAAI,KAAK,QAAQ,SAAS,UACxB,aAAa;CAGf,IAAI;EAGF,WAAW,MAFQ,yBAAoC,KAAK,IAAI,QAEzC;GACrB,IAAI,YACF,OAAO,KAAK,IAAI;IAElB;UAKK,GAAG;EACV,QAAQ,IAAI,kBAAkB,KAAK,KAAK,OAAO,EAAE;;;AAIrD,eAAe,yBACb,KACA,SACY;CACZ,IAAI,WAAW,IAAI,IAAI,EAAE;EACvB,QAAQ,IAAI,aAAa,IAAI;EAE7B,OAAO,WAAW,IAAI,IAAI;;CAG5B,MAAM,UAAU,SAAY,KAAK,QAAQ;CAEzC,WAAW,IAAI,KAAK,QAAQ;CAG5B,OAAO,WAAW,OAAO,GAAG;EAC1B,MAAM,WAAW,WAAW,MAAM,CAAC,MAAM,CAAC;EAE1C,IAAI,CAAC,UACH;EAGF,WAAW,OAAO,SAAS;;CAG7B,OAAO,QACJ,MAAM,SAAS;EACd,OAAO;GACP,CACD,OAAO,UAAU;EAChB,WAAW,OAAO,IAAI;EAEtB,MAAM;GACN;;AAGN,MAAa,6BAAa,IAAI,KAA+C"}
1
+ {"version":3,"file":"rsc.mjs","names":[],"sources":["../../src/rsc.ts"],"sourcesContent":["\"use client\";\n\nimport { type RSCRequestInit, fetchRSC } from \"@parcel/rsc/client\";\nimport { type ReactNode } from \"react\";\nimport { updateRoot } from \"./client-entry.js\";\nimport { RouteData } from \"./types.js\";\nimport { getPathData } from \"./util.js\";\n\n// fetch and push an rsc route\nexport async function navigate(\n pathname: string,\n routes: RouteData[],\n /** callback for a successful navigation (use this to update the history) */\n onPush: (url: string) => void,\n { push = true }: { push?: boolean } = {}\n) {\n let shouldPush = push;\n\n const path = getPathData(pathname, routes);\n\n if (!path) {\n console.warn(`No route found for ${pathname}`);\n\n if (routes.some((r) => r.path === \"/404\")) {\n // we have a 404 page, navigate there\n void navigate(\"/404\", routes, () => {\n // show the original not found path (rather than 404) in the URL\n onPush(pathname);\n });\n }\n\n return;\n }\n\n // Don't add to history if we're already on this page\n if (path.url === location.pathname) {\n shouldPush = false;\n }\n\n try {\n const root = await fetchRSCWithPreloadCache<ReactNode>(path.rsc);\n\n updateRoot(root, () => {\n if (shouldPush) {\n onPush(path.url);\n }\n });\n\n // after a successful navigation, we can clear the cache\n // note everything is static currently, we don't need to clear the cache\n // fetchCache.clear();\n } catch (e) {\n console.error(`Error fetching ${path.path} RSC`, e);\n }\n}\n\nasync function fetchRSCWithPreloadCache<T>(\n url: string | URL | Request,\n options?: RSCRequestInit\n): Promise<T> {\n if (fetchCache.has(url)) {\n return fetchCache.get(url) as Promise<T>;\n }\n\n const promise = fetchRSC<T>(url, options);\n\n fetchCache.set(url, promise);\n\n // keep the cache small, removing the oldest entries\n while (fetchCache.size > 5) {\n const firstKey = fetchCache.keys().next().value;\n\n if (!firstKey) {\n break;\n }\n\n fetchCache.delete(firstKey);\n }\n\n return promise\n .then((data) => {\n return data;\n })\n .catch((error) => {\n fetchCache.delete(url);\n\n throw error;\n });\n}\n\nexport const fetchCache = new Map<string | URL | Request, Promise<unknown>>();\n\nexport async function prefetch(\n pathname: string,\n routes: RouteData[],\n signal?: AbortSignal\n) {\n const path = getPathData(pathname, routes);\n\n if (!path) {\n return;\n }\n\n try {\n await fetchRSCWithPreloadCache<ReactNode>(path.rsc, { signal });\n } catch (error) {\n // don't throw or log if the signal is aborted - this is expected\n if (\n signal?.aborted ||\n (error instanceof Error && error.name === \"AbortError\")\n ) {\n return;\n }\n\n if (error instanceof Error) {\n console.error(`Error prefetching ${pathname} RSC`, error);\n return;\n }\n }\n}\n"],"mappings":";;;;;AASA,eAAsB,SACpB,UACA,QAEA,QACA,EAAE,OAAO,SAA6B,CAAC,GACvC;CACA,IAAI,aAAa;CAEjB,MAAM,OAAO,YAAY,UAAU,MAAM;CAEzC,IAAI,CAAC,MAAM;EACT,QAAQ,KAAK,sBAAsB,UAAU;EAE7C,IAAI,OAAO,MAAM,MAAM,EAAE,SAAS,MAAM,GAEtC,SAAc,QAAQ,cAAc;GAElC,OAAO,QAAQ;EACjB,CAAC;EAGH;CACF;CAGA,IAAI,KAAK,QAAQ,SAAS,UACxB,aAAa;CAGf,IAAI;EACF,MAAM,OAAO,MAAM,yBAAoC,KAAK,GAAG;EAE/D,WAAW,YAAY;GACrB,IAAI,YACF,OAAO,KAAK,GAAG;EAEnB,CAAC;CAKH,SAAS,GAAG;EACV,QAAQ,MAAM,kBAAkB,KAAK,KAAK,OAAO,CAAC;CACpD;AACF;AAEA,eAAe,yBACb,KACA,SACY;CACZ,IAAI,WAAW,IAAI,GAAG,GACpB,OAAO,WAAW,IAAI,GAAG;CAG3B,MAAM,UAAU,SAAY,KAAK,OAAO;CAExC,WAAW,IAAI,KAAK,OAAO;CAG3B,OAAO,WAAW,OAAO,GAAG;EAC1B,MAAM,WAAW,WAAW,KAAK,CAAC,CAAC,KAAK,CAAC,CAAC;EAE1C,IAAI,CAAC,UACH;EAGF,WAAW,OAAO,QAAQ;CAC5B;CAEA,OAAO,QACJ,MAAM,SAAS;EACd,OAAO;CACT,CAAC,CAAC,CACD,OAAO,UAAU;EAChB,WAAW,OAAO,GAAG;EAErB,MAAM;CACR,CAAC;AACL;AAEA,MAAa,6BAAa,IAAI,IAA8C;AAE5E,eAAsB,SACpB,UACA,QACA,QACA;CACA,MAAM,OAAO,YAAY,UAAU,MAAM;CAEzC,IAAI,CAAC,MACH;CAGF,IAAI;EACF,MAAM,yBAAoC,KAAK,KAAK,EAAE,OAAO,CAAC;CAChE,SAAS,OAAO;EAEd,KAAA,WAAA,QAAA,WAAA,KAAA,IAAA,KAAA,IACE,OAAQ,YACP,iBAAiB,SAAS,MAAM,SAAS,cAE1C;EAGF,IAAI,iBAAiB,OAAO;GAC1B,QAAQ,MAAM,qBAAqB,SAAS,OAAO,KAAK;GACxD;EACF;CACF;AACF"}
@@ -1,18 +1,17 @@
1
1
  import { Page, TocNode } from "@parcel/rsc";
2
-
3
2
  //#region src/types.d.ts
4
- declare namespace App {
3
+ export declare namespace App {
5
4
  interface Routes {}
6
5
  }
7
- type RoutePath = keyof App.Routes extends never ? string : keyof App.Routes;
6
+ export type RoutePath = keyof App.Routes extends never ? string : keyof App.Routes;
8
7
  /**
9
8
  * Union of all valid HTML route paths, e.g. "/index.html" | "/components/button.html"
10
9
  */
11
- type RouteHtml = keyof App.Routes extends never ? `${string}.html` : App.Routes[keyof App.Routes]["html"];
12
- type RouteRsc = keyof App.Routes extends never ? `${string}.rsc` : App.Routes[keyof App.Routes]["rsc"];
13
- type RouteData<TPath extends string = RoutePath, THtml extends string = RouteHtml, TRsc extends string = RouteRsc> = Omit<RouteNode<TPath, THtml, TRsc>, "children">;
10
+ export type RouteHtml = keyof App.Routes extends never ? `${string}.html` : App.Routes[keyof App.Routes]["html"];
11
+ export type RouteRsc = keyof App.Routes extends never ? `${string}.rsc` : App.Routes[keyof App.Routes]["rsc"];
12
+ export type RouteData<TPath extends string = RoutePath, THtml extends string = RouteHtml, TRsc extends string = RouteRsc> = Omit<RouteNode<TPath, THtml, TRsc>, "children">;
14
13
  type RoutePathToSlug<T extends string> = T extends `/` ? "index" : T extends `${infer _Prefix}/${infer Slug}` ? RoutePathToSlug<Slug> : T;
15
- interface RouteNode<TPath extends string = RoutePath, THtml extends string = RouteHtml, TRsc extends string = RouteRsc> {
14
+ export interface RouteNode<TPath extends string = RoutePath, THtml extends string = RouteHtml, TRsc extends string = RouteRsc> {
16
15
  children: RouteNode<TPath, THtml, TRsc>[];
17
16
  path: TPath;
18
17
  slug: RoutePathToSlug<TPath>;
@@ -28,10 +27,10 @@ interface Page$1<TUrl extends string = RouteHtml> extends Omit<Page, "url"> {
28
27
  /**
29
28
  * Enhanced PageProps where `pages` and `currentPage` have typed `url`s.
30
29
  */
31
- interface PageProps<TUrl extends string = RouteHtml> {
30
+ export interface PageProps<TUrl extends string = RouteHtml> {
32
31
  pages: Page$1<RouteHtml>[];
33
32
  currentPage: Page$1<TUrl>;
34
33
  }
35
34
  //#endregion
36
- export { App, Page$1 as Page, PageProps, RouteData, RouteHtml, RouteNode, RoutePath, RouteRsc, type TocNode };
35
+ export { Page$1 as Page, type TocNode };
37
36
  //# sourceMappingURL=types.d.mts.map
@@ -1 +1 @@
1
- {"version":3,"file":"types.d.mts","names":[],"sources":["../../src/types.ts"],"mappings":";;;kBAIiB,GAAA;EAAA,UACE,MAAA;AAAA;AAAA,KAGP,SAAA,SAA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UACf,uBAAuB,WACvB,uBAAuB,WACvB,sBAAsB;EAEtB,UAAU,UAAU,OAAO,OAAO;EAClC,MAAM;EACN,MAAM,gBAAgB;EACtB,KAAK;EACL,MAAM;;;;;UAMSA,OAAK,sBAAsB,mBAAmB,KAC7DC;EAGA,KAAK;;;;;iBAMU,UAAU,sBAAsB;EAC/C,OAAOD,OAAK;EACZ,aAAaA,OAAK"}
package/dist/esm/util.mjs CHANGED
@@ -5,10 +5,14 @@ const normalizeRoutePath = (path) => {
5
5
  return path;
6
6
  };
7
7
  function getPathData(pathname, routes) {
8
- const normalizedPath = normalizeRoutePath(pathname.startsWith("/") ? pathname : `/${pathname}`);
9
- const routePathName = normalizeRoutePath(new URL(pathname, window.location.origin).pathname);
8
+ var _window$location;
9
+ const path = pathname.startsWith("/") ? pathname : `/${pathname}`;
10
+ const origin = typeof window !== "undefined" && ((_window$location = window.location) === null || _window$location === void 0 ? void 0 : _window$location.origin) ? window.location.origin : "http://localhost";
11
+ const url = new URL(path, origin);
12
+ const routePathName = normalizeRoutePath(url.pathname);
10
13
  const route = routes.find((route) => route.path === routePathName);
11
14
  if (!route) return null;
15
+ const normalizedPath = `${normalizeRoutePath(url.pathname)}${url.search}${url.hash}`;
12
16
  return {
13
17
  ...route,
14
18
  rsc: route.rsc,
@@ -16,6 +20,6 @@ function getPathData(pathname, routes) {
16
20
  };
17
21
  }
18
22
  //#endregion
19
- export { getPathData };
23
+ export { getPathData, normalizeRoutePath };
20
24
 
21
25
  //# sourceMappingURL=util.mjs.map
@@ -1 +1 @@
1
- {"version":3,"file":"util.mjs","names":[],"sources":["../../src/util.ts"],"sourcesContent":["\"use client\";\nimport { RouteData } from \"./types.js\";\n\n// remove trailing slashes and index from the path\nexport const normalizeRoutePath = (path: string) => {\n for (const suffix of [\"/\", \"/index\"]) {\n if (path.endsWith(suffix)) {\n return path.slice(0, -suffix.length) || \"/\";\n }\n }\n\n return path;\n};\n\n// convert a path back to a route path\nexport const denormalizeRoutePath = (path: string) => {\n if (path === \"/\") {\n return \"index\";\n }\n\n if (path.startsWith(\"/\")) {\n return path.substring(1);\n }\n\n return path;\n};\n\nexport function getPathData(pathname: string, routes: RouteData[]) {\n const path = pathname.startsWith(\"/\") ? pathname : `/${pathname}`;\n\n // path for the URL (including query string/hash)\n const normalizedPath = normalizeRoutePath(path);\n\n // we want the pathname without the query string/hash to match the route\n const url = new URL(pathname, window.location.origin);\n\n const routePathName = normalizeRoutePath(url.pathname);\n\n const route = routes.find((route) => route.path === routePathName);\n\n if (!route) {\n return null;\n }\n\n return {\n ...route,\n rsc: route.rsc,\n url: normalizedPath,\n };\n}\n"],"mappings":";;AAIA,MAAa,sBAAsB,SAAiB;CAClD,KAAK,MAAM,UAAU,CAAC,KAAK,SAAS,EAClC,IAAI,KAAK,SAAS,OAAO,EACvB,OAAO,KAAK,MAAM,GAAG,CAAC,OAAO,OAAO,IAAI;CAI5C,OAAO;;AAgBT,SAAgB,YAAY,UAAkB,QAAqB;CAIjE,MAAM,iBAAiB,mBAHV,SAAS,WAAW,IAAI,GAAG,WAAW,IAAI,WAGR;CAK/C,MAAM,gBAAgB,mBAAmB,IAFzB,IAAI,UAAU,OAAO,SAAS,OAEF,CAAC,SAAS;CAEtD,MAAM,QAAQ,OAAO,MAAM,UAAU,MAAM,SAAS,cAAc;CAElE,IAAI,CAAC,OACH,OAAO;CAGT,OAAO;EACL,GAAG;EACH,KAAK,MAAM;EACX,KAAK;EACN"}
1
+ {"version":3,"file":"util.mjs","names":[],"sources":["../../src/util.ts"],"sourcesContent":["\"use client\";\nimport { RouteData } from \"./types.js\";\n\n// remove trailing slashes and index from the path\nexport const normalizeRoutePath = (path: string) => {\n for (const suffix of [\"/\", \"/index\"]) {\n if (path.endsWith(suffix)) {\n return path.slice(0, -suffix.length) || \"/\";\n }\n }\n\n return path;\n};\n\n// convert a path back to a route path\nexport const denormalizeRoutePath = (path: string) => {\n if (path === \"/\") {\n return \"index\";\n }\n\n if (path.startsWith(\"/\")) {\n return path.substring(1);\n }\n\n return path;\n};\n\nexport function getPathData(pathname: string, routes: RouteData[]) {\n const path = pathname.startsWith(\"/\") ? pathname : `/${pathname}`;\n const origin =\n typeof window !== \"undefined\" && window.location?.origin\n ? window.location.origin\n : \"http://localhost\";\n\n // we want the pathname without the query string/hash to match the route\n const url = new URL(path, origin);\n const routePathName = normalizeRoutePath(url.pathname);\n\n const route = routes.find((route) => route.path === routePathName);\n\n if (!route) {\n return null;\n }\n\n // Preserve query string and hash while normalizing the path portion\n const normalizedPath = `${normalizeRoutePath(url.pathname)}${url.search}${url.hash}`;\n\n return {\n ...route,\n rsc: route.rsc,\n url: normalizedPath,\n };\n}\n"],"mappings":";;AAIA,MAAa,sBAAsB,SAAiB;CAClD,KAAK,MAAM,UAAU,CAAC,KAAK,QAAQ,GACjC,IAAI,KAAK,SAAS,MAAM,GACtB,OAAO,KAAK,MAAM,GAAG,CAAC,OAAO,MAAM,KAAK;CAI5C,OAAO;AACT;AAeA,SAAgB,YAAY,UAAkB,QAAqB;;CACjE,MAAM,OAAO,SAAS,WAAW,GAAG,IAAI,WAAW,IAAI;CACvD,MAAM,SACJ,OAAO,WAAW,iBAAA,mBAAe,OAAO,cAAA,QAAA,qBAAA,KAAA,IAAA,KAAA,IAAA,iBAAU,UAC9C,OAAO,SAAS,SAChB;CAGN,MAAM,MAAM,IAAI,IAAI,MAAM,MAAM;CAChC,MAAM,gBAAgB,mBAAmB,IAAI,QAAQ;CAErD,MAAM,QAAQ,OAAO,MAAM,UAAU,MAAM,SAAS,aAAa;CAEjE,IAAI,CAAC,OACH,OAAO;CAIT,MAAM,iBAAiB,GAAG,mBAAmB,IAAI,QAAQ,IAAI,IAAI,SAAS,IAAI;CAE9E,OAAO;EACL,GAAG;EACH,KAAK,MAAM;EACX,KAAK;CACP;AACF"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@renr/parcel-rsc-router",
3
- "version": "1.0.0-alpha.8",
3
+ "version": "1.0.0-beta.10",
4
4
  "author": "Ren Rizzolo",
5
5
  "license": "MIT",
6
6
  "description": "Parcel rsc router",
@@ -13,13 +13,16 @@
13
13
  "url": "https://github.com/renrizzolo/parcel-rsc-react.git"
14
14
  },
15
15
  "type": "module",
16
- "main": "./src/index.ts",
16
+ "main": "./dist/esm/index.mjs",
17
+ "module": "./dist/esm/index.mjs",
18
+ "types": "./dist/esm/index.d.mts",
17
19
  "files": [
18
20
  "dist"
19
21
  ],
20
22
  "exports": {
21
- "default": {
23
+ ".": {
22
24
  "types": "./dist/esm/index.d.mts",
25
+ "import": "./dist/esm/index.mjs",
23
26
  "default": "./dist/esm/index.mjs"
24
27
  }
25
28
  },
@@ -29,16 +32,16 @@
29
32
  "react-server-dom-parcel": "^19"
30
33
  },
31
34
  "devDependencies": {
32
- "react": "^19.2.6",
33
- "@types/react": "^19.2.14",
34
- "@parcel/rsc": "^2.16.1"
35
+ "react": "^19.3.0",
36
+ "@types/react": "^19.3.0",
37
+ "@parcel/rsc": "^2.16.4"
35
38
  },
36
39
  "sideEffects": false,
37
40
  "publishConfig": {
38
41
  "access": "public"
39
42
  },
40
43
  "scripts": {
41
- "type-check": "tsgo --noEmit",
44
+ "type-check": "tsc --noEmit",
42
45
  "build": "tsdown"
43
46
  }
44
47
  }
package/src/index.ts DELETED
@@ -1,18 +0,0 @@
1
- export type {
2
- App,
3
- Page,
4
- PageProps,
5
- RouteData,
6
- RouteHtml,
7
- RouteNode,
8
- RoutePath,
9
- RouteRsc,
10
- TocNode,
11
- } from "./types.js";
12
- export { Link } from "./Link.js";
13
- export {
14
- RouterProvider,
15
- useCurrentRoute,
16
- useLocation,
17
- useRouter,
18
- } from "./Router.js";