@teyik0/furin 0.1.0-alpha.9 → 0.2.0-alpha.2

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.
Files changed (130) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +33 -0
  3. package/package.json +61 -25
  4. package/src/adapter/bun.ts +90 -41
  5. package/src/adapter/static.ts +100 -40
  6. package/src/build/client.ts +13 -14
  7. package/src/build/compile-entry.ts +20 -14
  8. package/src/build/entry-template.ts +90 -8
  9. package/src/build/hydrate.ts +219 -36
  10. package/src/build/index.ts +10 -9
  11. package/src/build/route-types.ts +65 -9
  12. package/src/build/scan-server.ts +52 -67
  13. package/src/build/server-routes-entry.ts +7 -11
  14. package/src/build/shared.ts +2 -1
  15. package/src/build/ssg-cache.ts +32 -0
  16. package/src/build/types.ts +5 -1
  17. package/src/cli/index.ts +1 -0
  18. package/src/client/boundaries.tsx +259 -0
  19. package/src/client/default-screens.tsx +304 -0
  20. package/src/client/link.tsx +347 -0
  21. package/src/client/router/boundary-tree.tsx +116 -0
  22. package/src/client/router/context.ts +40 -0
  23. package/src/client/router/history.ts +41 -0
  24. package/src/client/router/index.ts +56 -0
  25. package/src/client/router/link-utils.ts +177 -0
  26. package/src/client/router/navigation.ts +61 -0
  27. package/src/client/router/provider.tsx +759 -0
  28. package/src/client/router/search/index.ts +99 -0
  29. package/src/client/router/search-store.ts +86 -0
  30. package/src/client/router/spa-response.ts +143 -0
  31. package/src/client/router/types.ts +271 -0
  32. package/src/client/server-error.ts +47 -0
  33. package/src/client.ts +80 -3
  34. package/src/config.ts +11 -3
  35. package/src/env.d.ts +1 -0
  36. package/src/furin.ts +114 -29
  37. package/src/plugin/index.ts +7 -8
  38. package/src/plugin/transform-client.ts +146 -120
  39. package/src/server/auto-invalidate/index.ts +10 -0
  40. package/src/server/auto-invalidate/plugin.ts +25 -0
  41. package/src/server/auto-invalidate/registry.ts +60 -0
  42. package/src/server/auto-invalidate/runtime.ts +133 -0
  43. package/src/server/auto-invalidate/types.ts +16 -0
  44. package/src/server/cache/dev-loader.ts +211 -0
  45. package/src/server/cache/index.ts +34 -0
  46. package/src/server/cache/invalidation.ts +111 -0
  47. package/src/server/cache/isr-ssg.ts +41 -0
  48. package/src/server/cache/isr.ts +17 -0
  49. package/src/server/cache/registry.ts +35 -0
  50. package/src/server/cache/route-cache.ts +124 -0
  51. package/src/server/cache/ssg.ts +15 -0
  52. package/src/{context-logger.ts → server/context-logger.ts} +5 -0
  53. package/src/server/dev-inspector.ts +60 -0
  54. package/src/{dev-page-plugin.ts → server/dev-page-plugin.ts} +15 -0
  55. package/src/{internal.ts → server/internal.ts} +17 -0
  56. package/src/server/lang-detect.ts +46 -0
  57. package/src/server/render/assemble.ts +133 -0
  58. package/src/server/render/element.tsx +113 -0
  59. package/src/server/render/index.ts +22 -0
  60. package/src/server/render/isr.ts +317 -0
  61. package/src/server/render/loaders.ts +328 -0
  62. package/src/server/render/not-found.ts +98 -0
  63. package/src/{render → server/render}/shell.ts +28 -13
  64. package/src/server/render/ssg.ts +148 -0
  65. package/src/server/render/ssr.ts +583 -0
  66. package/src/server/router/discovery.ts +474 -0
  67. package/src/server/router/hmr.ts +376 -0
  68. package/src/server/router/index.ts +28 -0
  69. package/src/server/router/patterns.ts +219 -0
  70. package/src/server/router/plugin.ts +384 -0
  71. package/src/server/router/schemas.ts +278 -0
  72. package/src/server/router/types.ts +59 -0
  73. package/src/shared/await.tsx +192 -0
  74. package/src/shared/deferred-ndjson.ts +244 -0
  75. package/src/shared/digest.ts +71 -0
  76. package/src/shared/error.ts +49 -0
  77. package/src/shared/not-found.ts +40 -0
  78. package/src/shared/search-params.ts +182 -0
  79. package/src/shared/utils/ast-walk.ts +51 -0
  80. package/src/{utils.ts → shared/utils/index.ts} +32 -1
  81. package/dist/adapter/bun.d.ts +0 -3
  82. package/dist/adapter/static.d.ts +0 -3
  83. package/dist/build/client.d.ts +0 -25
  84. package/dist/build/compile-entry.d.ts +0 -23
  85. package/dist/build/entry-template.d.ts +0 -14
  86. package/dist/build/hydrate.d.ts +0 -24
  87. package/dist/build/index.d.ts +0 -7
  88. package/dist/build/index.js +0 -3727
  89. package/dist/build/route-types.d.ts +0 -21
  90. package/dist/build/scan-server.d.ts +0 -8
  91. package/dist/build/server-routes-entry.d.ts +0 -23
  92. package/dist/build/shared.d.ts +0 -11
  93. package/dist/build/types.d.ts +0 -76
  94. package/dist/cli/config.d.ts +0 -9
  95. package/dist/cli/index.d.ts +0 -2
  96. package/dist/cli/index.js +0 -3762
  97. package/dist/client.d.ts +0 -195
  98. package/dist/client.js +0 -20
  99. package/dist/config.d.ts +0 -47
  100. package/dist/config.js +0 -28
  101. package/dist/context-logger.d.ts +0 -26
  102. package/dist/dev-page-plugin.d.ts +0 -109
  103. package/dist/furin.d.ts +0 -34
  104. package/dist/furin.js +0 -2744
  105. package/dist/internal.d.ts +0 -19
  106. package/dist/link.d.ts +0 -245
  107. package/dist/link.js +0 -1232
  108. package/dist/plugin/index.d.ts +0 -20
  109. package/dist/plugin/index.js +0 -1408
  110. package/dist/plugin/transform-client.d.ts +0 -9
  111. package/dist/render/assemble.d.ts +0 -15
  112. package/dist/render/cache.d.ts +0 -95
  113. package/dist/render/element.d.ts +0 -4
  114. package/dist/render/index.d.ts +0 -27
  115. package/dist/render/loaders.d.ts +0 -12
  116. package/dist/render/shell.d.ts +0 -29
  117. package/dist/render/template.d.ts +0 -6
  118. package/dist/router.d.ts +0 -45
  119. package/dist/router.js +0 -1671
  120. package/dist/runtime-env.d.ts +0 -3
  121. package/dist/utils.d.ts +0 -6
  122. package/src/link.tsx +0 -1120
  123. package/src/render/assemble.ts +0 -66
  124. package/src/render/cache.ts +0 -241
  125. package/src/render/element.tsx +0 -28
  126. package/src/render/index.ts +0 -483
  127. package/src/render/loaders.ts +0 -117
  128. package/src/router.ts +0 -439
  129. /package/src/{render → server/render}/template.ts +0 -0
  130. /package/src/{runtime-env.ts → server/runtime-env.ts} +0 -0
@@ -0,0 +1,116 @@
1
+ import type React from "react";
2
+ import { createElement } from "react";
3
+ import type { RuntimeRoute } from "../../client.ts";
4
+ import { type BoundaryOptions, FurinErrorBoundary, wrapSegmentBoundaries } from "../boundaries.tsx";
5
+ import { FurinServerError } from "../server-error.ts";
6
+ import { RouterContext } from "./context.ts";
7
+ import type {
8
+ ClientSegmentBoundary,
9
+ LoadedClientRoute,
10
+ RootBoundaryOptions,
11
+ RouterContextValue,
12
+ } from "./types.ts";
13
+
14
+ /**
15
+ * Composes the outermost tree produced by `RouterProvider`:
16
+ *
17
+ * <RouterContext.Provider value={context}>
18
+ * <FurinErrorBoundary digest onReset resetKey>
19
+ * {pageElement}
20
+ * </FurinErrorBoundary>
21
+ * </RouterContext.Provider>
22
+ *
23
+ * `RouterContext.Provider` is the OUTERMOST element so that a root-level
24
+ * `error.tsx` rendered by the boundary can still call `useRouter()` / render
25
+ * `<Link>` (the context is in scope above the boundary).
26
+ *
27
+ * @internal Exported for unit testing only.
28
+ */
29
+ export function buildRouterTree(
30
+ context: RouterContextValue,
31
+ pageElement: React.ReactNode,
32
+ options: RootBoundaryOptions
33
+ ): React.ReactElement {
34
+ return (
35
+ <RouterContext.Provider value={context}>
36
+ <FurinErrorBoundary {...options}>{pageElement}</FurinErrorBoundary>
37
+ </RouterContext.Provider>
38
+ );
39
+ }
40
+
41
+ /**
42
+ * Internal helper component that throws a `FurinServerError` during render
43
+ * so the nearest `<FurinErrorBoundary>` catches it and renders the user's
44
+ * `error.tsx` (or the built-in default) — without forcing a full-page reload.
45
+ */
46
+ function RouteErrorThrower({
47
+ error,
48
+ }: {
49
+ error: { digest: string; message: string; status: number };
50
+ }): React.ReactElement {
51
+ throw new FurinServerError(error);
52
+ }
53
+
54
+ /** @internal Exported for unit testing only. */
55
+ export function buildPageElement(
56
+ match: LoadedClientRoute,
57
+ root: RuntimeRoute | null,
58
+ data: Record<string, unknown>,
59
+ options: BoundaryOptions | undefined,
60
+ error: { digest: string; message: string; status: number } | undefined
61
+ ): React.ReactNode {
62
+ let element: React.ReactNode = error
63
+ ? createElement(RouteErrorThrower, { error })
64
+ : createElement(match.component, data);
65
+
66
+ // Reconstruct the FULL route chain (shallow→deep, index 0 = root) by walking
67
+ // parents. We keep every route — not only the ones declaring a layout — so a
68
+ // route's chain index equals its directory depth. This mirrors the server's
69
+ // `buildElement` exactly, which is what guarantees the per-segment boundaries
70
+ // and layouts attach at the same depths on both sides (hydration parity).
71
+ // Compacting to layouts-only (the previous approach) misaligned boundaries
72
+ // and dropped the first nested layout whenever an ancestor lacked a layout.
73
+ const chain: RuntimeRoute[] = [];
74
+ let current: RuntimeRoute | undefined = match.pageRoute;
75
+ while (current) {
76
+ chain.unshift(current);
77
+ current = current.parent;
78
+ }
79
+
80
+ // Index boundaries by depth for O(1) lookup. A boundary's `depth` maps 1:1 to
81
+ // the route-chain index (depth 0 = root layout, handled separately below).
82
+ const byDepth = new Map<number, ClientSegmentBoundary>();
83
+ for (const segment of match.segmentBoundaries ?? []) {
84
+ byDepth.set(segment.depth, segment);
85
+ }
86
+
87
+ // When a root route is present it occupies chain index 0 and is wrapped
88
+ // separately below (root layout + depth-0 boundary), mirroring the server's
89
+ // `buildElement`. When `root` is null there is no separate root, so chain
90
+ // index 0 is an ordinary route whose layout + boundary participate in the
91
+ // loop too.
92
+ const rootOffset = root ? 1 : 0;
93
+
94
+ // Inside-out: at each non-root depth wrap the subtree with its same-depth
95
+ // boundary (so the boundary sits INSIDE the layout), then wrap with the
96
+ // layout itself when this route declares one.
97
+ for (let i = chain.length - 1; i >= rootOffset; i--) {
98
+ element = wrapSegmentBoundaries(element, byDepth.get(i), options);
99
+ const Layout = chain[i]?.layout;
100
+ if (Layout) {
101
+ // biome-ignore lint/suspicious/noExplicitAny: spread loses `children` type info for createElement
102
+ element = createElement(Layout, { ...data } as any, element);
103
+ }
104
+ }
105
+
106
+ if (root) {
107
+ // Depth 0 boundary wraps EVERYTHING below the root layout.
108
+ element = wrapSegmentBoundaries(element, byDepth.get(0), options);
109
+ if (root.layout) {
110
+ // biome-ignore lint/suspicious/noExplicitAny: spread loses `children` type info for createElement
111
+ element = createElement(root.layout, { ...data } as any, element);
112
+ }
113
+ }
114
+
115
+ return element;
116
+ }
@@ -0,0 +1,40 @@
1
+ import { createContext, useContext } from "react";
2
+ import type { RouterContextValue } from "./types.ts";
3
+
4
+ export const RouterContext = createContext<RouterContextValue | null>(null);
5
+
6
+ export const CLIENT_FALLBACK_ROUTER: RouterContextValue = {
7
+ basePath: "",
8
+ // Use the same "/" as SSR_FALLBACK_ROUTER so SSR and client render the
9
+ // same active-state when no RouterProvider is present, avoiding hydration mismatches.
10
+ currentHref: "/",
11
+ search: {},
12
+ searchRoutes: [],
13
+ navigate: (href, _opts) => {
14
+ window.location.href = href;
15
+ return Promise.resolve();
16
+ },
17
+ prefetch: (_href, _opts) => {
18
+ /* noop fallback */
19
+ },
20
+ invalidatePrefetch: (_path, _type) => {
21
+ /* noop fallback */
22
+ },
23
+ refresh: (_opts) => {
24
+ window.location.reload();
25
+ return Promise.resolve();
26
+ },
27
+ isNavigating: false,
28
+ defaultPreload: "intent",
29
+ defaultPreloadDelay: 50,
30
+ defaultPreloadStaleTime: 30_000,
31
+ };
32
+
33
+ /**
34
+ * Returns the current router context.
35
+ * Provides a graceful fallback (full-page navigation) when used outside RouterProvider.
36
+ */
37
+ export function useRouter(): RouterContextValue {
38
+ const ctx = useContext(RouterContext);
39
+ return ctx ?? CLIENT_FALLBACK_ROUTER;
40
+ }
@@ -0,0 +1,41 @@
1
+ export const SCROLL_STORAGE_KEY = "__furin_scroll__";
2
+
3
+ export function getHistoryKey(state: unknown): string | undefined {
4
+ return (state as { _furinKey?: string } | null)?._furinKey;
5
+ }
6
+
7
+ export function generateHistoryKey(): string {
8
+ return Math.random().toString(36).slice(2, 9);
9
+ }
10
+
11
+ export function saveScrollPosition(key: string): void {
12
+ try {
13
+ const raw = sessionStorage.getItem(SCROLL_STORAGE_KEY);
14
+ const positions: Record<string, number> = raw ? JSON.parse(raw) : {};
15
+ positions[key] = window.scrollY;
16
+ const keys = Object.keys(positions);
17
+ if (keys.length > 50) {
18
+ delete positions[keys[0] as string];
19
+ }
20
+ sessionStorage.setItem(SCROLL_STORAGE_KEY, JSON.stringify(positions));
21
+ } catch {
22
+ // sessionStorage unavailable (private mode, quota exceeded, etc.)
23
+ }
24
+ }
25
+
26
+ /**
27
+ * Returns `true` when the server reports a different build-id from the one
28
+ * embedded in the initial HTML (`<meta name="furin-build-id">`).
29
+ */
30
+ export function isStaleDeployResponse(res: Response): boolean {
31
+ const serverBuildId = res.headers.get("x-furin-build-id");
32
+ if (!serverBuildId) {
33
+ return false;
34
+ }
35
+ const metaEl =
36
+ typeof document === "undefined"
37
+ ? null
38
+ : document.querySelector<HTMLMetaElement>('meta[name="furin-build-id"]');
39
+ const clientBuildId = metaEl?.content;
40
+ return Boolean(clientBuildId && serverBuildId !== clientBuildId);
41
+ }
@@ -0,0 +1,56 @@
1
+ // biome-ignore-all lint/performance/noBarrelFile: client/router barrel — public surface of the SPA router
2
+ export { buildPageElement, buildRouterTree } from "./boundary-tree.tsx";
3
+ export { CLIENT_FALLBACK_ROUTER, RouterContext, useRouter } from "./context.ts";
4
+ export {
5
+ generateHistoryKey,
6
+ getHistoryKey,
7
+ isStaleDeployResponse,
8
+ SCROLL_STORAGE_KEY,
9
+ saveScrollPosition,
10
+ } from "./history.ts";
11
+ export {
12
+ applyRevalidateHeader,
13
+ buildHref,
14
+ normalizeHref,
15
+ normalizePath,
16
+ shouldAutoRefreshPath,
17
+ shouldInterceptClick,
18
+ shouldRefetch,
19
+ stripHashFromHref,
20
+ TRAILING_SLASHES_RE,
21
+ toLogical,
22
+ } from "./link-utils.ts";
23
+ export type { Navigate, NavigateInput } from "./navigation.ts";
24
+ export { useNavigate } from "./navigation.ts";
25
+ export { RouterProvider } from "./provider.tsx";
26
+ export type { SearchStore, SearchStoreSnapshot } from "./search-store.ts";
27
+ export {
28
+ createSearchStore,
29
+ FALLBACK_SEARCH_STORE,
30
+ SearchStoreContext,
31
+ searchSnapshotFromRouterContext,
32
+ } from "./search-store.ts";
33
+ export {
34
+ buildDataEndpoint,
35
+ buildNotFoundPageElement,
36
+ classifySpaResponse,
37
+ detectStaticMode,
38
+ parsePageResponse,
39
+ pickDeepestNotFound,
40
+ } from "./spa-response.ts";
41
+ export type {
42
+ CacheEntry,
43
+ ClientRoute,
44
+ ClientSegmentBoundary,
45
+ LinkProps,
46
+ LoadedClientRoute,
47
+ PreloadStrategy,
48
+ RootBoundaryOptions,
49
+ RouteManifest,
50
+ RouterContextValue,
51
+ RouterProviderProps,
52
+ RouterState,
53
+ RouteSearch,
54
+ RouteTo,
55
+ SpaResponseKind,
56
+ } from "./types.ts";
@@ -0,0 +1,177 @@
1
+ import { buildSearchParams, type SearchParamsInput } from "../../shared/search-params.ts";
2
+ import type { CacheEntry } from "./types.ts";
3
+
4
+ const HASH_FRAGMENT_RE = /#.*$/;
5
+ /** Strips one or more trailing slashes — used by `buildDataEndpoint` in static mode. */
6
+ export const TRAILING_SLASHES_RE = /\/+$/;
7
+
8
+ /**
9
+ * Builds a full href string from a pathname, optional search params, and optional hash.
10
+ * Null/undefined search values are omitted.
11
+ *
12
+ * @internal Exported for unit testing only.
13
+ */
14
+ export function buildHref(
15
+ to: string,
16
+ search: SearchParamsInput | null | undefined,
17
+ hash: string | undefined,
18
+ searchDefaults?: SearchParamsInput
19
+ ): string {
20
+ let url = to;
21
+ if (search && Object.keys(search).length > 0) {
22
+ const params = buildSearchParams(search, searchDefaults);
23
+ const qs = params.toString();
24
+ if (qs) {
25
+ url += `?${qs}`;
26
+ }
27
+ }
28
+ if (hash) {
29
+ url += `#${hash}`;
30
+ }
31
+ return url;
32
+ }
33
+
34
+ /**
35
+ * Parses the `X-Furin-Revalidate` response header and calls `invalidate` for
36
+ * each path entry. Header format: `"/path1,/path2:layout,/path3"`
37
+ */
38
+ export function applyRevalidateHeader(
39
+ headers: Headers,
40
+ invalidate: (path: string, type: "page" | "layout" | undefined) => void
41
+ ): void {
42
+ const headerValue = headers.get("x-furin-revalidate");
43
+ if (!headerValue) {
44
+ return;
45
+ }
46
+ for (const entry of headerValue.split(",")) {
47
+ const trimmed = entry.trim();
48
+ if (!trimmed) {
49
+ continue;
50
+ }
51
+ if (trimmed.endsWith(":layout")) {
52
+ invalidate(trimmed.slice(0, -":layout".length), "layout");
53
+ } else {
54
+ invalidate(trimmed, "page");
55
+ }
56
+ }
57
+ }
58
+
59
+ /**
60
+ * Returns `true` when `currentPath` is targeted by at least one invalidation entry.
61
+ *
62
+ * @internal Exported for unit testing only.
63
+ */
64
+ export function shouldAutoRefreshPath(
65
+ currentPath: string,
66
+ invalidations: ReadonlyArray<{ path: string; type: "page" | "layout" }>
67
+ ): boolean {
68
+ const normalizedCurrent = currentPath.split("?")[0] ?? currentPath;
69
+ return invalidations.some(({ path, type }) => {
70
+ if (type === "page") {
71
+ return path === normalizedCurrent;
72
+ }
73
+ const prefix = path === "/" || path.endsWith("/") ? path : `${path}/`;
74
+ return normalizedCurrent === path || normalizedCurrent.startsWith(prefix);
75
+ });
76
+ }
77
+
78
+ export function stripHashFromHref(href: string): string {
79
+ return href.replace(HASH_FRAGMENT_RE, "");
80
+ }
81
+
82
+ /** Strips trailing slashes from a pathname or href. Root `/` is preserved.
83
+ * Query strings and hashes are preserved and re-attached after normalization. */
84
+ export function normalizeHref(href: string): string {
85
+ const url = new URL(href, "http://localhost");
86
+ let pathname = url.pathname;
87
+ if (pathname !== "/") {
88
+ pathname = pathname.replace(/\/+$/g, "");
89
+ }
90
+ return pathname + url.search + url.hash;
91
+ }
92
+
93
+ /** Strips a single trailing slash from a pathname. Root `/` and empty string are preserved. */
94
+ export function normalizePath(path: string): string {
95
+ if (path === "/" || path === "") {
96
+ return path;
97
+ }
98
+ return path.endsWith("/") ? path.slice(0, -1) : path;
99
+ }
100
+
101
+ /** @internal Exported for unit testing only. */
102
+ export function shouldRefetch(entry: CacheEntry): boolean {
103
+ return Date.now() - entry.createdAt > entry.staleTime;
104
+ }
105
+
106
+ /**
107
+ * Decides whether a native `<a>` click should be intercepted and converted
108
+ * to an SPA navigation. Returns the logical href to navigate to, or `null`
109
+ * when the browser should handle the click normally.
110
+ *
111
+ * @internal Exported for unit testing only.
112
+ */
113
+ export function shouldInterceptClick(
114
+ anchor: { href: string; target: string; hasAttribute(name: string): boolean },
115
+ event: { metaKey: boolean; ctrlKey: boolean; shiftKey: boolean; altKey: boolean },
116
+ basePath: string,
117
+ currentOrigin: string,
118
+ currentPathname: string
119
+ ): string | null {
120
+ if (event.metaKey || event.ctrlKey || event.shiftKey || event.altKey) {
121
+ return null;
122
+ }
123
+
124
+ if (anchor.target && anchor.target !== "_self") {
125
+ return null;
126
+ }
127
+
128
+ if (anchor.hasAttribute("download")) {
129
+ return null;
130
+ }
131
+
132
+ const href = anchor.href;
133
+ if (!href) {
134
+ return null;
135
+ }
136
+
137
+ let url: URL;
138
+ try {
139
+ url = new URL(href, currentOrigin);
140
+ } catch {
141
+ return null;
142
+ }
143
+
144
+ if (url.origin !== currentOrigin) {
145
+ return null;
146
+ }
147
+
148
+ // Hash-only navigation on the same page — let the browser handle scrolling.
149
+ if (normalizePath(url.pathname) === normalizePath(currentPathname) && url.hash) {
150
+ return null;
151
+ }
152
+
153
+ const logicalPath = normalizeHref(toLogical(url.pathname, basePath));
154
+ const normalizedBase = normalizePath(basePath);
155
+ const normalizedPathname = normalizePath(url.pathname);
156
+ if (
157
+ normalizedBase &&
158
+ normalizedPathname !== normalizedBase &&
159
+ !normalizedPathname.startsWith(`${normalizedBase}/`)
160
+ ) {
161
+ return null;
162
+ }
163
+ return logicalPath + url.search + url.hash;
164
+ }
165
+
166
+ /** Strips basePath prefix from a physical pathname, returning the logical path. */
167
+ export function toLogical(physicalPathname: string, basePath: string): string {
168
+ if (
169
+ basePath &&
170
+ physicalPathname.startsWith(basePath) &&
171
+ // Require a path boundary after the prefix so "/furin" doesn't match "/furinity/foo"
172
+ (physicalPathname.length === basePath.length || physicalPathname[basePath.length] === "/")
173
+ ) {
174
+ return physicalPathname.slice(basePath.length) || "/";
175
+ }
176
+ return physicalPathname;
177
+ }
@@ -0,0 +1,61 @@
1
+ import { useCallback } from "react";
2
+ import {
3
+ findSearchDefaultsForRouteTarget,
4
+ type SearchParamsInput,
5
+ } from "../../shared/search-params.ts";
6
+ import { useRouter } from "./context.ts";
7
+ import { buildHref } from "./link-utils.ts";
8
+ import type { RouteSearch, RouteTo } from "./types.ts";
9
+
10
+ export interface NavigateInput<To extends RouteTo> {
11
+ hash?: string;
12
+ replace?: boolean;
13
+ resetScroll?: boolean;
14
+ search?: RouteSearch<To>;
15
+ to: To;
16
+ }
17
+
18
+ export type Navigate = <To extends RouteTo>(next: NavigateInput<To>) => Promise<void>;
19
+ type NavigateOptions = Parameters<ReturnType<typeof useRouter>["navigate"]>[1];
20
+
21
+ function isExternalAbsoluteHref(href: string): boolean {
22
+ if (href.startsWith("//")) {
23
+ return true;
24
+ }
25
+ if (!(href.startsWith("http://") || href.startsWith("https://"))) {
26
+ return false;
27
+ }
28
+ if (typeof window === "undefined") {
29
+ return true;
30
+ }
31
+ return new URL(href).origin !== window.location.origin;
32
+ }
33
+
34
+ export function useNavigate(): Navigate {
35
+ const router = useRouter();
36
+
37
+ return useCallback<Navigate>(
38
+ (next) => {
39
+ const searchDefaults = findSearchDefaultsForRouteTarget(
40
+ next.to as string,
41
+ router.searchRoutes
42
+ );
43
+ const href = buildHref(
44
+ next.to as string,
45
+ next.search as SearchParamsInput | null | undefined,
46
+ next.hash,
47
+ searchDefaults
48
+ );
49
+ if (isExternalAbsoluteHref(href) && typeof window !== "undefined") {
50
+ window.location.assign(href);
51
+ return Promise.resolve();
52
+ }
53
+ const opts: NavigateOptions =
54
+ next.replace === undefined && next.resetScroll === undefined
55
+ ? undefined
56
+ : { replace: next.replace, resetScroll: next.resetScroll };
57
+ return router.navigate(href, opts);
58
+ },
59
+ [router]
60
+ );
61
+ }