@teyik0/furin 0.1.0-alpha.7 → 0.1.0-alpha.8

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/dist/link.d.ts CHANGED
@@ -109,7 +109,13 @@ export declare function shouldAutoRefreshPath(currentPath: string, invalidations
109
109
  type: "page" | "layout";
110
110
  }>): boolean;
111
111
  export interface RouterContextValue {
112
- /** Current pathname + search (no hash). Used by Link for active-state detection. */
112
+ /**
113
+ * Sub-path prefix for static deployments (e.g. "/furin").
114
+ * Empty string when the site is served from root.
115
+ * Used by `Link` to build correct physical hrefs for the `<a>` element.
116
+ */
117
+ basePath: string;
118
+ /** Current **logical** pathname + search (basePath stripped). Used by Link for active-state detection. */
113
119
  currentHref: string;
114
120
  defaultPreload: PreloadStrategy;
115
121
  defaultPreloadDelay: number;
@@ -185,6 +191,17 @@ export interface RouterProviderProps {
185
191
  * Set to `false` to opt out and call `router.refresh()` manually instead.
186
192
  */
187
193
  autoRefresh?: boolean;
194
+ /**
195
+ * Sub-path prefix for static deployments (e.g. "/furin").
196
+ * Must start with "/" and have no trailing slash.
197
+ * Default: "" (site served from root).
198
+ *
199
+ * When set:
200
+ * - `currentHref` stores **logical** paths (prefix stripped) for correct active-state detection.
201
+ * - `navigate(logicalHref)` pushes `basePath + logicalHref` to browser history.
202
+ * - `fetch` calls use the physical path `basePath + logicalHref`.
203
+ */
204
+ basePath?: string;
188
205
  defaultPreload?: PreloadStrategy;
189
206
  defaultPreloadDelay?: number;
190
207
  defaultPreloadStaleTime?: number;
@@ -212,6 +229,17 @@ export interface CacheEntry {
212
229
  export declare function shouldRefetch(entry: CacheEntry): boolean;
213
230
  /** @internal Exported for unit testing only. */
214
231
  export declare function buildPageElement(match: LoadedClientRoute, root: RuntimeRoute | null, data: Record<string, unknown>): React.ReactNode;
215
- export declare function RouterProvider({ routes, root, initialMatch, initialData, autoRefresh, defaultPreload, defaultPreloadDelay, defaultPreloadStaleTime, prefetchCacheSize, }: RouterProviderProps): React.ReactElement;
216
- export declare function Link<To extends RouteTo>({ to, search, hash, preload, preloadDelay, preloadStaleTime, replace, disabled, resetScroll, activeProps, inactiveProps, onClick, onMouseEnter, onMouseLeave, onFocus, children, ...anchorProps }: LinkProps<To>): React.ReactElement;
232
+ export declare function RouterProvider({ routes, root, initialMatch, initialData, autoRefresh, basePath, defaultPreload, defaultPreloadDelay, defaultPreloadStaleTime, prefetchCacheSize, }: RouterProviderProps): React.ReactElement;
233
+ /**
234
+ * SSR-aware Link component.
235
+ *
236
+ * - **Server (SSR):** uses `RouterContext.Consumer` (a render-prop, not a hook)
237
+ * to read basePath / currentHref from any enclosing RouterProvider, then
238
+ * falls back to `SSR_FALLBACK_ROUTER` when no provider is present.
239
+ * `Context.Consumer` bypasses `ReactCurrentDispatcher` entirely, so it is
240
+ * safe even when two React instances coexist in the module graph (Bun HMR).
241
+ * - **Client:** delegates to `LinkInteractive` which adds preloading, SPA
242
+ * navigation, active-state tracking and all other interactive features.
243
+ */
244
+ export declare function Link<To extends RouteTo>(props: LinkProps<To>): React.ReactElement;
217
245
  export {};
package/dist/link.js CHANGED
@@ -1,5 +1,5 @@
1
1
  // @bun
2
- // ../../node_modules/.bun/evlog@2.12.0+f7c24eab1d196b1d/node_modules/evlog/dist/utils.mjs
2
+ // ../../node_modules/.bun/evlog@2.13.0+449e6d239244fccb/node_modules/evlog/dist/utils.mjs
3
3
  function formatDuration(ms) {
4
4
  if (ms < 1000)
5
5
  return `${Math.round(ms)}ms`;
@@ -82,7 +82,7 @@ function escapeFormatString(str) {
82
82
  return str.replace(/%/g, "%%");
83
83
  }
84
84
 
85
- // ../../node_modules/.bun/evlog@2.12.0+f7c24eab1d196b1d/node_modules/evlog/dist/logger-DY0X5oQd.mjs
85
+ // ../../node_modules/.bun/evlog@2.13.0+449e6d239244fccb/node_modules/evlog/dist/logger-DnobymUQ.mjs
86
86
  var DEFAULT_REPLACEMENT = "[REDACTED]";
87
87
  var builtinPatterns = {
88
88
  creditCard: {
@@ -676,7 +676,8 @@ function shouldAutoRefreshPath(currentPath, invalidations) {
676
676
  var RouterContext = createContext(null);
677
677
  function useRouter() {
678
678
  return useContext(RouterContext) ?? {
679
- currentHref: typeof window === "undefined" ? "/" : window.location.pathname + window.location.search,
679
+ basePath: "",
680
+ currentHref: "/",
680
681
  navigate: (href) => {
681
682
  window.location.href = href;
682
683
  return Promise.resolve();
@@ -748,12 +749,19 @@ function handleScrollRestoration(href, navigationToken, navVersion) {
748
749
  window.scrollTo(0, 0);
749
750
  }
750
751
  }
752
+ function toLogical(physicalPathname, basePath) {
753
+ if (basePath && physicalPathname.startsWith(basePath) && (physicalPathname.length === basePath.length || physicalPathname[basePath.length] === "/")) {
754
+ return physicalPathname.slice(basePath.length) || "/";
755
+ }
756
+ return physicalPathname;
757
+ }
751
758
  function RouterProvider({
752
759
  routes,
753
760
  root,
754
761
  initialMatch,
755
762
  initialData,
756
763
  autoRefresh = true,
764
+ basePath = "",
757
765
  defaultPreload = "intent",
758
766
  defaultPreloadDelay = 50,
759
767
  defaultPreloadStaleTime = 30000,
@@ -764,34 +772,41 @@ function RouterProvider({
764
772
  data: initialData
765
773
  });
766
774
  const [isNavigating, setIsNavigating] = useState(false);
767
- const [currentHref, setCurrentHref] = useState(() => typeof window === "undefined" ? "/" : window.location.pathname + window.location.search);
775
+ const [currentHref, setCurrentHref] = useState(() => {
776
+ if (typeof window === "undefined") {
777
+ return "/";
778
+ }
779
+ return toLogical(window.location.pathname, basePath) + window.location.search;
780
+ });
768
781
  const prefetchCache = useRef(new Map);
769
782
  const navVersion = useRef(0);
770
- const fetchPageState = useCallback(async (href) => {
783
+ const fetchPageState = useCallback(async (logicalHref) => {
771
784
  try {
772
- const url = new URL(href, window.location.origin);
773
- const match = routes.find((r) => r.regex.test(url.pathname));
785
+ const physicalHref = basePath + logicalHref;
786
+ const url = new URL(physicalHref, window.location.origin);
787
+ const logicalPathname = toLogical(url.pathname, basePath);
788
+ const match = routes.find((r) => r.regex.test(logicalPathname));
774
789
  if (!match) {
775
790
  return null;
776
791
  }
777
- const [res, loadedMod] = await Promise.all([fetch(href), match.load()]);
792
+ const [res, loadedMod] = await Promise.all([fetch(physicalHref), match.load()]);
778
793
  const serverBuildId = res.headers.get("x-furin-build-id");
779
794
  if (serverBuildId) {
780
795
  const metaEl = typeof document === "undefined" ? null : document.querySelector('meta[name="furin-build-id"]');
781
796
  const clientBuildId = metaEl?.content;
782
797
  if (clientBuildId && serverBuildId !== clientBuildId) {
783
- window.location.href = href;
798
+ window.location.href = physicalHref;
784
799
  return null;
785
800
  }
786
801
  }
787
802
  if (!res.ok) {
788
- _log.warn({ action: "navigate_server_error", href, status: res.status });
803
+ _log.warn({ action: "navigate_server_error", href: physicalHref, status: res.status });
789
804
  return null;
790
805
  }
791
806
  let finalHref;
792
807
  if (res.redirected) {
793
808
  const final = new URL(res.url);
794
- finalHref = final.pathname + final.search;
809
+ finalHref = toLogical(final.pathname, basePath) + final.search;
795
810
  }
796
811
  const html = await res.text();
797
812
  const doc = new DOMParser().parseFromString(html, "text/html");
@@ -804,10 +819,10 @@ function RouterProvider({
804
819
  };
805
820
  return { match: loadedMatch, data, title: doc.title, finalHref };
806
821
  } catch (err) {
807
- _log.error({ action: "navigate_failed", href, error: String(err) });
822
+ _log.error({ action: "navigate_failed", href: basePath + logicalHref, error: String(err) });
808
823
  return null;
809
824
  }
810
- }, [routes]);
825
+ }, [routes, basePath]);
811
826
  const invalidatePrefetch = useCallback((path, type = "page") => {
812
827
  const normalizedPath = stripHashFromHref(path);
813
828
  if (type === "page") {
@@ -842,63 +857,75 @@ function RouterProvider({
842
857
  prefetchCache.current.delete(oldest);
843
858
  }
844
859
  }, [fetchPageState, defaultPreloadStaleTime, prefetchCacheSize]);
845
- const navigate = useCallback(async (href, opts) => {
846
- prefetch(href);
860
+ const navigate = useCallback(async (logicalHref, opts) => {
861
+ prefetch(logicalHref);
847
862
  const myVersion = ++navVersion.current;
848
863
  setIsNavigating(true);
849
864
  try {
850
- const newState = await prefetchCache.current.get(href)?.promise;
865
+ const newState = await prefetchCache.current.get(logicalHref)?.promise;
851
866
  if (navVersion.current !== myVersion) {
852
867
  return;
853
868
  }
854
869
  if (!newState) {
855
- _log.warn({ action: "navigate_fallback", href, reason: "prefetch_returned_null" });
856
- window.location.href = href;
870
+ _log.warn({
871
+ action: "navigate_fallback",
872
+ href: logicalHref,
873
+ reason: "prefetch_returned_null"
874
+ });
875
+ window.location.href = basePath + logicalHref;
857
876
  return;
858
877
  }
859
878
  setState(newState);
860
879
  if (newState.title) {
861
880
  document.title = newState.title;
862
881
  }
863
- const effectiveHref = newState.finalHref ?? href;
882
+ const effectiveLogical = newState.finalHref ?? logicalHref;
883
+ const physicalEffective = basePath + effectiveLogical;
864
884
  if (opts?.replace) {
865
- window.history.replaceState(null, "", effectiveHref);
885
+ window.history.replaceState(null, "", physicalEffective);
866
886
  } else {
867
- window.history.pushState(null, "", effectiveHref);
887
+ window.history.pushState(null, "", physicalEffective);
868
888
  }
869
- const effectiveUrl = new URL(effectiveHref, window.location.origin);
870
- setCurrentHref(effectiveUrl.pathname + effectiveUrl.search);
889
+ const effectiveUrl = new URL(physicalEffective, window.location.origin);
890
+ const logicalPath = toLogical(effectiveUrl.pathname, basePath);
891
+ setCurrentHref(logicalPath + effectiveUrl.search);
871
892
  if (opts?.resetScroll ?? true) {
872
- handleScrollRestoration(effectiveHref, myVersion, navVersion);
893
+ handleScrollRestoration(physicalEffective, myVersion, navVersion);
873
894
  }
874
895
  } finally {
875
896
  if (navVersion.current === myVersion) {
876
897
  setIsNavigating(false);
877
898
  }
878
899
  }
879
- }, [prefetch]);
900
+ }, [prefetch, basePath]);
880
901
  const refresh = useCallback(async (opts) => {
881
- const href = window.location.pathname + window.location.search;
882
- invalidatePrefetch(href, "page");
883
- await navigate(href, { replace: true, resetScroll: opts?.resetScroll ?? false });
884
- }, [navigate, invalidatePrefetch]);
902
+ const logicalPath = toLogical(window.location.pathname, basePath);
903
+ const logicalHref = logicalPath + window.location.search;
904
+ invalidatePrefetch(logicalHref, "page");
905
+ await navigate(logicalHref, { replace: true, resetScroll: opts?.resetScroll ?? false });
906
+ }, [navigate, invalidatePrefetch, basePath]);
885
907
  const handlePopState = useCallback(async () => {
886
- const href = window.location.pathname + window.location.search;
908
+ const logicalPath = toLogical(window.location.pathname, basePath);
909
+ const logicalHref = logicalPath + window.location.search;
887
910
  const myVersion = ++navVersion.current;
888
911
  setIsNavigating(true);
889
912
  try {
890
- const cached = prefetchCache.current.get(href);
913
+ const cached = prefetchCache.current.get(logicalHref);
891
914
  let newState;
892
915
  if (cached && !shouldRefetch(cached)) {
893
916
  newState = await cached.promise;
894
917
  } else {
895
- newState = await fetchPageState(href);
918
+ newState = await fetchPageState(logicalHref);
896
919
  }
897
920
  if (navVersion.current !== myVersion) {
898
921
  return;
899
922
  }
900
923
  if (!newState) {
901
- _log.warn({ action: "popstate_fallback", href, reason: "fetchPageState_returned_null" });
924
+ _log.warn({
925
+ action: "popstate_fallback",
926
+ href: logicalHref,
927
+ reason: "fetchPageState_returned_null"
928
+ });
902
929
  window.location.reload();
903
930
  return;
904
931
  }
@@ -906,18 +933,17 @@ function RouterProvider({
906
933
  if (newState.title) {
907
934
  document.title = newState.title;
908
935
  }
909
- const effectiveHref = newState.finalHref ?? href;
936
+ const effectiveLogical = newState.finalHref ?? logicalHref;
910
937
  if (newState.finalHref) {
911
- window.history.replaceState(null, "", effectiveHref);
938
+ window.history.replaceState(null, "", basePath + effectiveLogical);
912
939
  }
913
- const effectiveUrl = new URL(effectiveHref, window.location.origin);
914
- setCurrentHref(effectiveUrl.pathname + effectiveUrl.search);
940
+ setCurrentHref(effectiveLogical);
915
941
  } finally {
916
942
  if (navVersion.current === myVersion) {
917
943
  setIsNavigating(false);
918
944
  }
919
945
  }
920
- }, [fetchPageState]);
946
+ }, [fetchPageState, basePath]);
921
947
  useEffect(() => {
922
948
  window.addEventListener("popstate", handlePopState);
923
949
  return () => window.removeEventListener("popstate", handlePopState);
@@ -950,6 +976,7 @@ function RouterProvider({
950
976
  }, [invalidatePrefetch, refresh, autoRefresh]);
951
977
  return createElement(RouterContext.Provider, {
952
978
  value: {
979
+ basePath,
953
980
  currentHref,
954
981
  navigate,
955
982
  prefetch,
@@ -962,7 +989,26 @@ function RouterProvider({
962
989
  }
963
990
  }, buildPageElement(state.match, root, state.data));
964
991
  }
965
- function Link({
992
+ function computeLinkView({
993
+ to,
994
+ search,
995
+ hash,
996
+ children,
997
+ activeProps,
998
+ inactiveProps
999
+ }, router) {
1000
+ const logicalHref = buildHref(to, search, hash);
1001
+ const logicalHrefWithoutHash = buildHref(to, search, undefined);
1002
+ const href = router.basePath + logicalHref;
1003
+ const isActive = router.currentHref === logicalHrefWithoutHash;
1004
+ const resolvedChildren = typeof children === "function" ? children({ isActive }) : children;
1005
+ const extraProps = {
1006
+ ...inactiveProps && !isActive ? inactiveProps() : {},
1007
+ ...activeProps ? activeProps({ isActive }) : {}
1008
+ };
1009
+ return { logicalHref, href, isActive, resolvedChildren, extraProps };
1010
+ }
1011
+ function LinkInteractive({
966
1012
  to,
967
1013
  search,
968
1014
  hash,
@@ -984,15 +1030,13 @@ function Link({
984
1030
  const router = useRouter();
985
1031
  const anchorRef = useRef(null);
986
1032
  const intentTimerRef = useRef(null);
987
- const href = buildHref(to, search, hash);
988
- const hrefWithoutHash = buildHref(to, search, undefined);
989
- const isActive = router.currentHref === hrefWithoutHash;
1033
+ const { logicalHref, href, isActive, resolvedChildren, extraProps } = computeLinkView({ to, search, hash, children, activeProps, inactiveProps }, router);
990
1034
  const effectivePreload = preload ?? router.defaultPreload;
991
1035
  const effectiveDelay = preloadDelay ?? router.defaultPreloadDelay;
992
1036
  const effectiveStaleTime = preloadStaleTime ?? router.defaultPreloadStaleTime;
993
1037
  const triggerPrefetch = useCallback(() => {
994
- router.prefetch(href, { staleTime: effectiveStaleTime });
995
- }, [router, href, effectiveStaleTime]);
1038
+ router.prefetch(logicalHref, { staleTime: effectiveStaleTime });
1039
+ }, [router, logicalHref, effectiveStaleTime]);
996
1040
  useEffect(() => {
997
1041
  if (effectivePreload === "render") {
998
1042
  triggerPrefetch();
@@ -1033,7 +1077,7 @@ function Link({
1033
1077
  return;
1034
1078
  }
1035
1079
  e.preventDefault();
1036
- router.navigate(href, { replace, resetScroll: resetScroll ?? true });
1080
+ router.navigate(logicalHref, { replace, resetScroll: resetScroll ?? true });
1037
1081
  };
1038
1082
  const handleMouseEnter = (e) => {
1039
1083
  onMouseEnter?.(e);
@@ -1054,11 +1098,6 @@ function Link({
1054
1098
  triggerPrefetch();
1055
1099
  }
1056
1100
  };
1057
- const resolvedChildren = typeof children === "function" ? children({ isActive }) : children;
1058
- const extraProps = {
1059
- ...inactiveProps && !isActive ? inactiveProps() : {},
1060
- ...activeProps ? activeProps({ isActive }) : {}
1061
- };
1062
1101
  return createElement("a", {
1063
1102
  ref: anchorRef,
1064
1103
  href,
@@ -1072,6 +1111,55 @@ function Link({
1072
1111
  ...disabled ? { "aria-disabled": true } : {}
1073
1112
  }, resolvedChildren);
1074
1113
  }
1114
+ var SSR_FALLBACK_ROUTER = {
1115
+ basePath: "",
1116
+ currentHref: "/",
1117
+ navigate: () => Promise.resolve(),
1118
+ prefetch: () => {},
1119
+ invalidatePrefetch: () => {},
1120
+ refresh: () => Promise.resolve(),
1121
+ isNavigating: false,
1122
+ defaultPreload: "intent",
1123
+ defaultPreloadDelay: 50,
1124
+ defaultPreloadStaleTime: 30000
1125
+ };
1126
+ function renderLinkElement(props, router) {
1127
+ const { href, isActive, resolvedChildren, extraProps } = computeLinkView(props, router);
1128
+ const {
1129
+ to: _to,
1130
+ search: _search,
1131
+ hash: _hash,
1132
+ children: _children,
1133
+ activeProps: _ap,
1134
+ inactiveProps: _ip,
1135
+ disabled,
1136
+ preload: _p,
1137
+ preloadDelay: _pd,
1138
+ preloadStaleTime: _ps,
1139
+ replace: _r,
1140
+ resetScroll: _rs,
1141
+ onClick: _oc,
1142
+ onMouseEnter: _ome,
1143
+ onMouseLeave: _oml,
1144
+ onFocus: _of,
1145
+ ...anchorProps
1146
+ } = props;
1147
+ return createElement("a", {
1148
+ href,
1149
+ ...isActive ? { "data-status": "active" } : {},
1150
+ ...anchorProps,
1151
+ ...extraProps,
1152
+ ...disabled ? { "aria-disabled": true } : {}
1153
+ }, resolvedChildren);
1154
+ }
1155
+ function Link(props) {
1156
+ if (typeof window === "undefined") {
1157
+ return createElement(RouterContext.Consumer, {
1158
+ children: (routerCtx) => renderLinkElement(props, routerCtx ?? SSR_FALLBACK_ROUTER)
1159
+ });
1160
+ }
1161
+ return createElement(LinkInteractive, props);
1162
+ }
1075
1163
  export {
1076
1164
  useRouter,
1077
1165
  shouldRefetch,
@@ -11,7 +11,7 @@ interface RenderResult {
11
11
  }
12
12
  export declare function renderToHTML(route: ResolvedRoute, ctx: Context, root: RootLayout): Promise<RenderResult>;
13
13
  export declare function renderToStream(route: ResolvedRoute, ctx: Context, root: RootLayout): Promise<ReadableStream | Response>;
14
- export declare function prerenderSSG(route: ResolvedRoute, params: Record<string, string>, root: RootLayout, origin?: string): Promise<SsgCacheEntry | Response>;
14
+ export declare function prerenderSSG(route: ResolvedRoute, params: Record<string, string>, root: RootLayout, origin?: string, basePath?: string): Promise<SsgCacheEntry | Response>;
15
15
  export declare function renderSSR(route: ResolvedRoute, ctx: Context, root: RootLayout): Promise<Response>;
16
16
  export declare function handleISR(route: ResolvedRoute, ctx: Context, root: RootLayout, buildId?: string): Promise<string | Response | undefined>;
17
17
  /**
@@ -9,4 +9,4 @@ export type LoaderResult = {
9
9
  type: "redirect";
10
10
  response: Response;
11
11
  };
12
- export declare function runLoaders(route: ResolvedRoute, ctx: Context, rootLayout: RuntimeRoute): Promise<LoaderResult>;
12
+ export declare function runLoaders(route: ResolvedRoute, ctx: Context, _rootLayout: RuntimeRoute): Promise<LoaderResult>;
package/dist/router.js CHANGED
@@ -145,8 +145,21 @@ function assembleHTML(template, headData, reactHtml, data) {
145
145
  }
146
146
 
147
147
  // src/render/index.ts
148
+ import { createElement as createElement2 } from "react";
148
149
  import { renderToReadableStream } from "react-dom/server";
149
150
 
151
+ // src/link.tsx
152
+ import {
153
+ createContext,
154
+ createElement,
155
+ useCallback,
156
+ useContext,
157
+ useEffect,
158
+ useRef,
159
+ useState
160
+ } from "react";
161
+ var RouterContext = createContext(null);
162
+
150
163
  // src/render/cache.ts
151
164
  import { AsyncLocalStorage } from "async_hooks";
152
165
  var MAX_ISR_CACHE_SIZE = 1000;
@@ -218,21 +231,48 @@ function buildElement(route, data, rootLayout) {
218
231
  }
219
232
 
220
233
  // src/render/loaders.ts
221
- async function runLoaders(route, ctx, rootLayout) {
234
+ function createLoaderCtx(ctx, accumulatedParentPromise) {
235
+ const cache = new Map;
236
+ return new Proxy(ctx, {
237
+ get(target, prop) {
238
+ if (typeof prop !== "string") {
239
+ return Reflect.get(target, prop);
240
+ }
241
+ if (prop === "then" || prop === "catch" || prop === "finally" || prop === "toJSON") {
242
+ return Reflect.get(target, prop);
243
+ }
244
+ if (Object.hasOwn(target, prop)) {
245
+ return target[prop];
246
+ }
247
+ let entry = cache.get(prop);
248
+ if (!entry) {
249
+ entry = accumulatedParentPromise.then((data) => data[prop]);
250
+ cache.set(prop, entry);
251
+ }
252
+ return entry;
253
+ }
254
+ });
255
+ }
256
+ async function runLoaders(route, ctx, _rootLayout) {
222
257
  try {
258
+ const ctxRecord = ctx;
223
259
  const loaderMap = new Map;
224
- const deps = (routeRef) => loaderMap.get(routeRef) ?? Promise.resolve({});
225
- const rootPromise = rootLayout.loader ? Promise.resolve(rootLayout.loader({ ...ctx }, deps)).then((r) => r ?? {}) : Promise.resolve({});
226
- loaderMap.set(rootLayout, rootPromise);
227
- const rootData = await rootPromise;
228
- const ctxWithRoot = { ...ctx, ...rootData };
229
- for (let i = 1;i < route.routeChain.length; i++) {
230
- const ancestor = route.routeChain[i];
231
- if (ancestor?.loader) {
232
- loaderMap.set(ancestor, Promise.resolve(ancestor.loader(ctxWithRoot, deps)).then((r) => r ?? {}));
260
+ let accumulatedParentPromise = Promise.resolve({});
261
+ for (const r of route.routeChain) {
262
+ const parentAccum = accumulatedParentPromise;
263
+ if (r.loader) {
264
+ const loaderCtx = createLoaderCtx(ctxRecord, parentAccum);
265
+ const loaderPromise = Promise.resolve(r.loader(loaderCtx)).then((res) => res ?? {});
266
+ loaderMap.set(r, loaderPromise);
267
+ accumulatedParentPromise = Promise.all([parentAccum, loaderPromise]).then(([acc, own]) => ({
268
+ ...acc,
269
+ ...own
270
+ }));
271
+ accumulatedParentPromise.catch(() => {});
233
272
  }
234
273
  }
235
- const pagePromise = route.page?.loader ? Promise.resolve(route.page.loader(ctxWithRoot, deps)).then((r) => r ?? {}) : Promise.resolve({});
274
+ const pageCtx = createLoaderCtx(ctxRecord, accumulatedParentPromise);
275
+ const pagePromise = route.page?.loader ? Promise.resolve(route.page.loader(pageCtx)).then((r) => r ?? {}) : Promise.resolve({});
236
276
  const results = await Promise.all([...loaderMap.values(), pagePromise]);
237
277
  const data = Object.assign({}, ...results);
238
278
  const headers = {};
@@ -278,7 +318,7 @@ function getProductionTemplate() {
278
318
  return null;
279
319
  }
280
320
  }
281
- // ../../node_modules/.bun/evlog@2.12.0+f7c24eab1d196b1d/node_modules/evlog/dist/elysia/index.mjs
321
+ // ../../node_modules/.bun/evlog@2.13.0+449e6d239244fccb/node_modules/evlog/dist/elysia/index.mjs
282
322
  import { AsyncLocalStorage as AsyncLocalStorage2 } from "async_hooks";
283
323
  import { Elysia } from "elysia";
284
324
  var storage = new AsyncLocalStorage2;
@@ -294,7 +334,7 @@ function useLogger() {
294
334
  var IS_DEV = true;
295
335
 
296
336
  // src/render/index.ts
297
- async function prepareRender(route, ctx, root) {
337
+ async function prepareRender(route, ctx, root, basePath) {
298
338
  const loaderStart = Date.now();
299
339
  const loaderResult = await runLoaders(route, ctx, root.route);
300
340
  const loader_ms = Date.now() - loaderStart;
@@ -309,13 +349,29 @@ async function prepareRender(route, ctx, root) {
309
349
  path: ctx.path
310
350
  };
311
351
  const headData = buildHeadInjection(route.page?.head?.(componentProps));
312
- const template = IS_DEV ? await getDevTemplate(new URL(ctx.request.url).origin) : getProductionTemplate() ?? generateIndexHtml();
313
- const element = buildElement(route, componentProps, root.route);
352
+ const prodTemplate = getProductionTemplate();
353
+ const template = prodTemplate ?? (IS_DEV ? await getDevTemplate(new URL(ctx.request.url).origin) : generateIndexHtml());
354
+ let element = buildElement(route, componentProps, root.route);
355
+ if (basePath !== undefined) {
356
+ const ssrContext = {
357
+ basePath,
358
+ currentHref: ctx.path,
359
+ navigate: () => Promise.resolve(),
360
+ prefetch: () => {},
361
+ invalidatePrefetch: () => {},
362
+ refresh: () => Promise.resolve(),
363
+ isNavigating: false,
364
+ defaultPreload: "intent",
365
+ defaultPreloadDelay: 50,
366
+ defaultPreloadStaleTime: 30000
367
+ };
368
+ element = createElement2(RouterContext.Provider, { value: ssrContext }, element);
369
+ }
314
370
  return { componentProps, element, headData, headers, loader_ms, template };
315
371
  }
316
- async function renderForPath(route, params, root, origin) {
372
+ async function renderForPath(route, params, root, origin, basePath) {
317
373
  const resolvedPath = resolvePath(route.pattern, params);
318
- return await renderToHTML(route, {
374
+ const ctx = {
319
375
  params,
320
376
  query: {},
321
377
  request: new Request(`${origin}${resolvedPath}`),
@@ -324,10 +380,8 @@ async function renderForPath(route, params, root, origin) {
324
380
  redirect: (url, status = 302) => new Response(null, { status, headers: { Location: url } }),
325
381
  set: { headers: {} },
326
382
  path: resolvedPath
327
- }, root);
328
- }
329
- async function renderToHTML(route, ctx, root) {
330
- const prepared = await prepareRender(route, ctx, root);
383
+ };
384
+ const prepared = await prepareRender(route, ctx, root, basePath);
331
385
  if (prepared instanceof Response) {
332
386
  throw prepared;
333
387
  }
@@ -340,7 +394,7 @@ async function renderToHTML(route, ctx, root) {
340
394
  headers
341
395
  };
342
396
  }
343
- async function prerenderSSG(route, params, root, origin = "http://localhost:3000") {
397
+ async function prerenderSSG(route, params, root, origin = "http://localhost:3000", basePath) {
344
398
  const resolvedPath = resolvePath(route.pattern, params);
345
399
  const cached = getSSGCache(resolvedPath);
346
400
  if (cached && !IS_DEV) {
@@ -348,7 +402,7 @@ async function prerenderSSG(route, params, root, origin = "http://localhost:3000
348
402
  }
349
403
  let result;
350
404
  try {
351
- result = await renderForPath(route, params, root, origin);
405
+ result = await renderForPath(route, params, root, origin, basePath);
352
406
  } catch (err) {
353
407
  if (err instanceof Response) {
354
408
  return err;
@@ -646,11 +700,17 @@ function queryDefaultRedirectHook({ request, query, status, set }) {
646
700
  }
647
701
  async function handleDevRequest(route, ctx, root) {
648
702
  try {
703
+ let currentRoot = root;
704
+ const rootMod = await import(`${root.path}?furin-server&t=${Date.now()}`);
705
+ const rootExport = rootMod.route ?? rootMod.default;
706
+ if (rootExport && isFurinRoute(rootExport) && rootExport.layout) {
707
+ currentRoot = { path: root.path, route: rootExport };
708
+ }
649
709
  const pageMod = await import(`${route.path}?furin-server&t=${Date.now()}`);
650
710
  const page = pageMod.default;
651
711
  if (page && isFurinPage(page)) {
652
712
  const chain = collectRouteChainFromRoute(page._route);
653
- return renderSSR({ ...route, page, routeChain: chain }, ctx, root);
713
+ return renderSSR({ ...route, page, routeChain: chain }, ctx, currentRoot);
654
714
  }
655
715
  } catch (err) {
656
716
  console.error(`[furin] Dev page load error for ${route.path}:`, err);
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@teyik0/furin",
3
- "version": "0.1.0-alpha.7",
3
+ "version": "0.1.0-alpha.8",
4
4
  "type": "module",
5
5
  "files": [
6
6
  "dist",
@@ -55,12 +55,13 @@
55
55
  "scripts": {
56
56
  "test": "bun test",
57
57
  "test:types": "tsc --noEmit",
58
- "build": "bun run build.ts"
58
+ "build": "bun run build.ts",
59
+ "fix": "ultracite fix"
59
60
  },
60
61
  "dependencies": {
61
- "@elysiajs/static": "^1.4.7",
62
+ "@elysiajs/static": "^1.4.9",
62
63
  "magic-string": "^0.30.21",
63
- "oxc-parser": "^0.124.0"
64
+ "oxc-parser": "^0.126.0"
64
65
  },
65
66
  "devDependencies": {
66
67
  "@types/react": "^19.2.14",
@@ -69,7 +70,7 @@
69
70
  },
70
71
  "peerDependencies": {
71
72
  "elysia": "^1.4.28",
72
- "evlog": "^2.12.0",
73
+ "evlog": "^2.13.0",
73
74
  "react": "^19.2.5",
74
75
  "react-dom": "^19.2.5"
75
76
  }