@teyik0/furin 0.6.0-alpha.1 → 0.7.0-alpha.1

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 (188) hide show
  1. package/dist/adapter/runtime-build.d.ts +1 -1
  2. package/dist/build/client.d.ts +4 -1
  3. package/dist/build/entry-template.d.ts +3 -0
  4. package/dist/build/entry-template.ts +7 -0
  5. package/dist/build/hydrate.d.ts +1 -1
  6. package/dist/build/index.js +1671 -276
  7. package/dist/build/preload-manifest.d.ts +17 -0
  8. package/dist/build/types.d.ts +6 -0
  9. package/dist/cli/index.js +1672 -286
  10. package/dist/client/client-module.d.ts +26 -0
  11. package/dist/client/define-route.d.ts +9 -0
  12. package/dist/client/document.d.ts +2 -0
  13. package/dist/client/internal/runtime-types.d.ts +2 -0
  14. package/dist/client/link.js +932 -118
  15. package/dist/client/mutation.d.ts +38 -0
  16. package/dist/client/query-store.d.ts +85 -0
  17. package/dist/client/query.d.ts +14 -0
  18. package/dist/client/route-api.d.ts +11 -0
  19. package/dist/client/router/context.d.ts +3 -2
  20. package/dist/client/router/index.d.ts +1 -1
  21. package/dist/client/router/link-utils.d.ts +8 -1
  22. package/dist/client/router/navigation.d.ts +2 -9
  23. package/dist/client/router/optimistic.d.ts +41 -0
  24. package/dist/client/router/search/index.d.ts +3 -3
  25. package/dist/client/router/search-store.d.ts +1 -0
  26. package/dist/client/router/sync-catch-up.d.ts +3 -0
  27. package/dist/client/router/types.d.ts +49 -7
  28. package/dist/client/sync.d.ts +39 -22
  29. package/dist/client.d.ts +11 -33
  30. package/dist/client.js +1219 -59
  31. package/dist/config.d.ts +7 -0
  32. package/dist/config.js +1 -0
  33. package/dist/define-route.d.ts +78 -32
  34. package/dist/env.d.ts +2 -2
  35. package/dist/furin.d.ts +1 -2
  36. package/dist/furin.js +2448 -710
  37. package/dist/plugin/hmr-dependencies.d.ts +2 -0
  38. package/dist/plugin/index.js +349 -18
  39. package/dist/plugin/transform-client-module.d.ts +16 -0
  40. package/dist/plugin/transform-client.d.ts +2 -0
  41. package/dist/plugin/transform-isomorphic.d.ts +1 -1
  42. package/dist/routes.d.ts +6 -0
  43. package/dist/rsc-client.js +87 -16
  44. package/dist/rsc.js +87 -16
  45. package/dist/server/auto-invalidate/registry.d.ts +1 -0
  46. package/dist/server/auto-invalidate/types.d.ts +2 -0
  47. package/dist/server/cache/isr.d.ts +2 -4
  48. package/dist/server/cache/route-cache.d.ts +5 -0
  49. package/dist/server/dev/graph.d.ts +1 -0
  50. package/dist/server/dev-page-plugin.d.ts +5 -19
  51. package/dist/server/internal.d.ts +3 -0
  52. package/dist/server/internal.js +55 -35
  53. package/dist/server/production-server.js +54 -34
  54. package/dist/server/render/loaders.d.ts +4 -2
  55. package/dist/server/render/react-stream.d.ts +3 -0
  56. package/dist/server/render/ssr.d.ts +2 -1
  57. package/dist/server/render/template.d.ts +4 -0
  58. package/dist/server/router/defined-route.d.ts +2 -0
  59. package/dist/server/router/hmr.d.ts +1 -1
  60. package/dist/server/sync/adapter.d.ts +25 -4
  61. package/dist/server/sync/atomic.d.ts +25 -0
  62. package/dist/server/sync/drizzle/index.d.ts +45 -0
  63. package/dist/server/sync/drizzle/index.js +540 -0
  64. package/dist/server/sync/execution-error.d.ts +2 -0
  65. package/dist/server/sync/index.d.ts +2 -1
  66. package/dist/server/sync/index.js +533 -105
  67. package/dist/server/sync/mutation-handler.d.ts +4 -0
  68. package/dist/server/sync/plugin.d.ts +34 -11
  69. package/dist/server/sync/postgres/execute.d.ts +3 -0
  70. package/dist/server/sync/postgres/index.d.ts +12 -1
  71. package/dist/server/sync/postgres/index.js +34 -13
  72. package/dist/server/sync/postgres/sql.d.ts +8 -0
  73. package/dist/server/sync/prisma/index.d.ts +24 -0
  74. package/dist/server/sync/prisma/index.js +340 -0
  75. package/dist/server/sync/queries.d.ts +21 -0
  76. package/dist/server/sync/query-context.d.ts +5 -0
  77. package/dist/server/sync/redis/index.js +3 -3
  78. package/dist/server/sync/redis/scripts.d.ts +1 -1
  79. package/dist/server/sync/response.d.ts +1 -0
  80. package/dist/server/sync/sqlite/index.d.ts +3 -0
  81. package/dist/server/sync/sqlite/index.js +10 -4
  82. package/dist/server/sync/stream.d.ts +2 -5
  83. package/dist/server/sync/validation.d.ts +4 -0
  84. package/dist/shared/defer.d.ts +31 -0
  85. package/dist/shared/error.d.ts +2 -2
  86. package/dist/shared/page-key.d.ts +7 -0
  87. package/dist/shared/query-bindings.d.ts +12 -0
  88. package/dist/shared/route-frame.d.ts +1 -0
  89. package/dist/shared/sync-query.d.ts +40 -0
  90. package/package.json +29 -6
  91. package/src/adapter/package.ts +12 -2
  92. package/src/adapter/runtime-build.ts +63 -12
  93. package/src/adapter/static.ts +7 -2
  94. package/src/adapter/vercel.ts +15 -13
  95. package/src/build/client.ts +23 -5
  96. package/src/build/entry-template.ts +7 -0
  97. package/src/build/hydrate.ts +17 -3
  98. package/src/build/preload-manifest.ts +100 -0
  99. package/src/build/production-instrumentation.ts +6 -3
  100. package/src/build/types.ts +4 -0
  101. package/src/cli/index.ts +1 -0
  102. package/src/client/browser-events-runtime.ts +4 -0
  103. package/src/client/client-module.ts +57 -0
  104. package/src/client/define-route.ts +11 -1
  105. package/src/client/document.tsx +28 -18
  106. package/src/client/hmr.ts +2 -1
  107. package/src/client/internal/runtime-types.ts +2 -0
  108. package/src/client/link.tsx +8 -8
  109. package/src/client/mutation.ts +136 -0
  110. package/src/client/query-store.ts +418 -0
  111. package/src/client/query.tsx +67 -0
  112. package/src/client/route-api.tsx +75 -0
  113. package/src/client/router/boundary-tree.tsx +7 -2
  114. package/src/client/router/context.ts +57 -4
  115. package/src/client/router/index.ts +3 -0
  116. package/src/client/router/link-utils.ts +29 -1
  117. package/src/client/router/navigation.ts +3 -50
  118. package/src/client/router/optimistic.ts +233 -0
  119. package/src/client/router/provider.tsx +304 -44
  120. package/src/client/router/search/index.ts +37 -17
  121. package/src/client/router/search-store.ts +4 -0
  122. package/src/client/router/sync-catch-up.ts +7 -0
  123. package/src/client/router/types.ts +71 -9
  124. package/src/client/sync.ts +438 -65
  125. package/src/client.ts +20 -60
  126. package/src/config.ts +5 -0
  127. package/src/define-route.ts +113 -55
  128. package/src/env.d.ts +2 -2
  129. package/src/furin.ts +75 -13
  130. package/src/plugin/hmr-dependencies.ts +58 -0
  131. package/src/plugin/index.ts +38 -2
  132. package/src/plugin/routes.ts +3 -3
  133. package/src/plugin/transform-client-module.ts +123 -0
  134. package/src/plugin/transform-client.ts +293 -13
  135. package/src/plugin/transform-isomorphic.ts +11 -5
  136. package/src/routes.ts +8 -0
  137. package/src/rsc/shared.tsx +104 -18
  138. package/src/server/auto-invalidate/registry.ts +4 -0
  139. package/src/server/auto-invalidate/runtime.ts +17 -0
  140. package/src/server/auto-invalidate/types.ts +6 -0
  141. package/src/server/cache/isr.ts +6 -34
  142. package/src/server/cache/route-cache.ts +40 -4
  143. package/src/server/dev/graph.ts +16 -2
  144. package/src/server/dev-page-plugin.ts +93 -59
  145. package/src/server/internal.ts +3 -0
  146. package/src/server/render/document.tsx +10 -1
  147. package/src/server/render/element.tsx +7 -2
  148. package/src/server/render/isr.ts +61 -29
  149. package/src/server/render/loaders.ts +118 -47
  150. package/src/server/render/mixed-cache.ts +33 -4
  151. package/src/server/render/not-found.ts +4 -7
  152. package/src/server/render/ppr-document.ts +2 -1
  153. package/src/server/render/ppr-route.ts +30 -10
  154. package/src/server/render/react-stream.ts +17 -0
  155. package/src/server/render/route-frame-transport.ts +3 -0
  156. package/src/server/render/ssg.ts +51 -18
  157. package/src/server/render/ssr.ts +53 -8
  158. package/src/server/render/template.ts +23 -0
  159. package/src/server/router/defined-route.ts +3 -0
  160. package/src/server/router/hmr.ts +3 -2
  161. package/src/server/router/plugin.ts +27 -12
  162. package/src/server/sync/adapter.ts +41 -4
  163. package/src/server/sync/atomic.ts +303 -0
  164. package/src/server/sync/drizzle/index.ts +145 -0
  165. package/src/server/sync/execution-error.ts +1 -0
  166. package/src/server/sync/fingerprint.ts +2 -6
  167. package/src/server/sync/index.ts +6 -0
  168. package/src/server/sync/mutation-handler.ts +69 -0
  169. package/src/server/sync/plugin.ts +177 -60
  170. package/src/server/sync/postgres/execute.ts +20 -0
  171. package/src/server/sync/postgres/index.ts +52 -16
  172. package/src/server/sync/postgres/sql.ts +20 -0
  173. package/src/server/sync/prisma/index.ts +70 -0
  174. package/src/server/sync/queries.ts +75 -0
  175. package/src/server/sync/query-context.ts +85 -0
  176. package/src/server/sync/redis/index.ts +7 -3
  177. package/src/server/sync/redis/scripts.ts +1 -1
  178. package/src/server/sync/response.ts +21 -0
  179. package/src/server/sync/sqlite/index.ts +19 -8
  180. package/src/server/sync/stream.ts +14 -22
  181. package/src/server/sync/validation.ts +34 -0
  182. package/src/shared/defer.ts +48 -0
  183. package/src/shared/error.ts +2 -2
  184. package/src/shared/page-key.ts +36 -0
  185. package/src/shared/query-bindings.ts +138 -0
  186. package/src/shared/route-frame.ts +13 -1
  187. package/src/shared/route-map.ts +12 -2
  188. package/src/shared/sync-query.ts +138 -0
@@ -1,6 +1,6 @@
1
1
  // @bun
2
2
  // src/client/link.tsx
3
- import { createElement as createElement5, useCallback as useCallback3, useEffect as useEffect2, useRef as useRef2 } from "react";
3
+ import { createElement as createElement7, useCallback as useCallback4, useEffect as useEffect3, useRef as useRef2 } from "react";
4
4
 
5
5
  // src/shared/search-params.ts
6
6
  function routeSegmentSpecificity(segment) {
@@ -127,7 +127,7 @@ function findSearchDefaultsForRouteTarget(to, routes) {
127
127
  }
128
128
 
129
129
  // src/client/router/context.ts
130
- import { createContext, useContext } from "react";
130
+ import { createContext, useCallback, useContext, useMemo } from "react";
131
131
 
132
132
  // src/client/router/link-utils.ts
133
133
  var HASH_FRAGMENT_RE = /#.*$/;
@@ -190,6 +190,10 @@ function applyLinkParams(to, params) {
190
190
  }
191
191
  return url;
192
192
  }
193
+ function resolveRouteTarget(target, routes) {
194
+ const path = applyLinkParams(target.to, target.params);
195
+ return buildHref(path, target.search, target.hash, findSearchDefaultsForRouteTarget(path, routes));
196
+ }
193
197
  function buildHref(to, search, hash, searchDefaults) {
194
198
  let url = to;
195
199
  if (search && Object.keys(search).length > 0) {
@@ -320,13 +324,66 @@ var CLIENT_FALLBACK_ROUTER = {
320
324
  search: {},
321
325
  searchRoutes: []
322
326
  };
323
- function useRouter() {
327
+ function useRouterContext() {
324
328
  const ctx = useContext(RouterContext);
325
329
  return ctx ?? CLIENT_FALLBACK_ROUTER;
326
330
  }
331
+ function useRouter() {
332
+ const context = useRouterContext();
333
+ const navigate = useCallback((next, opts) => {
334
+ const href = typeof next === "string" ? next : resolveRouteTarget(next, context.searchRoutes);
335
+ const policy = navigationHrefPolicy(href, typeof window === "undefined" ? undefined : window.location.origin);
336
+ if (policy === "blocked") {
337
+ return Promise.reject(new Error("[furin] Unsafe navigation URL."));
338
+ }
339
+ if (policy === "external" && typeof window !== "undefined") {
340
+ window.location.assign(href);
341
+ return Promise.resolve();
342
+ }
343
+ if (typeof next === "string") {
344
+ return context.navigate(href, opts);
345
+ }
346
+ const options = next.replace === undefined && next.resetScroll === undefined ? undefined : { replace: next.replace, resetScroll: next.resetScroll };
347
+ return context.navigate(href, options);
348
+ }, [context.navigate, context.searchRoutes]);
349
+ const prefetch = useCallback((next, opts) => {
350
+ const href = typeof next === "string" ? next : resolveRouteTarget(next, context.searchRoutes);
351
+ const policy = navigationHrefPolicy(href, typeof window === "undefined" ? undefined : window.location.origin);
352
+ if (policy !== "internal") {
353
+ return;
354
+ }
355
+ context.prefetch(href, typeof next === "string" ? opts : { staleTime: next.staleTime });
356
+ }, [context.prefetch, context.searchRoutes]);
357
+ return useMemo(() => ({ ...context, navigate, prefetch }), [context, navigate, prefetch]);
358
+ }
327
359
 
328
360
  // src/client/router/boundary-tree.tsx
329
- import { createElement as createElement2 } from "react";
361
+ import { createElement as createElement3 } from "react";
362
+
363
+ // src/shared/page-key.ts
364
+ function identityValue(value) {
365
+ return Object.is(value, -0) ? "-0" : String(value);
366
+ }
367
+ function pageKey(pattern, data, remountDeps) {
368
+ const { params, query } = data;
369
+ if (remountDeps) {
370
+ const deps = remountDeps({ params: params ?? {}, query: query ?? {} });
371
+ return JSON.stringify([pattern, deps.map((value) => [typeof value, identityValue(value)])]);
372
+ }
373
+ const entries = Object.entries(params ?? {}).sort(([left], [right]) => {
374
+ if (left < right) {
375
+ return -1;
376
+ }
377
+ return left > right ? 1 : 0;
378
+ });
379
+ return JSON.stringify([
380
+ pattern,
381
+ entries.map(([name, value]) => [
382
+ name,
383
+ Array.isArray(value) ? value.map(identityValue) : identityValue(value)
384
+ ])
385
+ ]);
386
+ }
330
387
 
331
388
  // src/client/boundaries.tsx
332
389
  import { Component, Fragment as Fragment2 } from "react";
@@ -667,6 +724,7 @@ var DefaultNotFoundFallback = ({ error }) => /* @__PURE__ */ jsxDEV(DefaultNotFo
667
724
 
668
725
  // src/client/document.tsx
669
726
  import { createContext as createContext2, createElement, useContext as useContext2 } from "react";
727
+ import { preloadModule } from "react-dom";
670
728
  import { jsxDEV as jsxDEV2, Fragment } from "react/jsx-dev-runtime";
671
729
  var DocumentContext = createContext2(null);
672
730
  function serializeJson(value) {
@@ -684,29 +742,39 @@ function DocumentProvider({
684
742
  function useDocumentState() {
685
743
  return useContext2(DocumentContext);
686
744
  }
687
- function renderMeta(meta, index) {
745
+ function renderMeta(meta, key) {
688
746
  if ("title" in meta) {
689
747
  return /* @__PURE__ */ jsxDEV2("title", {
690
748
  children: meta.title
691
- }, `title:${index}`, false, undefined, this);
749
+ }, key, false, undefined, this);
692
750
  }
693
751
  if ("script:ld+json" in meta) {
694
752
  return /* @__PURE__ */ jsxDEV2("script", {
695
753
  dangerouslySetInnerHTML: { __html: serializeJson(meta["script:ld+json"]) },
696
754
  type: "application/ld+json"
697
- }, `json-ld:${index}`, false, undefined, this);
755
+ }, key, false, undefined, this);
698
756
  }
699
757
  if ("tagName" in meta) {
700
758
  const { tagName, ...attributes } = meta;
701
- return createElement(tagName, { ...attributes, key: `${tagName}:${index}` });
759
+ return createElement(tagName, { ...attributes, key });
702
760
  }
703
- return createElement("meta", { ...meta, key: `meta:${index}` });
761
+ return createElement("meta", { ...meta, key });
704
762
  }
705
763
  function HeadContent() {
706
764
  const state = useContext2(DocumentContext);
707
765
  if (state === null) {
708
766
  throw new Error("[furin] <HeadContent /> must be rendered inside the root layout.");
709
767
  }
768
+ for (const href of state.assets.modulePreloads ?? []) {
769
+ preloadModule(href, { as: "script", nonce: state.nonce });
770
+ }
771
+ const occurrences = new Map;
772
+ const descriptorKey = (descriptor) => {
773
+ const identity = JSON.stringify(descriptor);
774
+ const occurrence = occurrences.get(identity) ?? 0;
775
+ occurrences.set(identity, occurrence + 1);
776
+ return `${identity}:${occurrence}`;
777
+ };
710
778
  return /* @__PURE__ */ jsxDEV2(Fragment, {
711
779
  children: [
712
780
  state.assets.extensionErrorFilterScript === undefined ? null : /* @__PURE__ */ jsxDEV2("script", {
@@ -739,20 +807,20 @@ function HeadContent() {
739
807
  href,
740
808
  rel: "stylesheet"
741
809
  }, href, false, undefined, this)),
742
- state.head?.meta?.map(renderMeta),
743
- state.head?.links?.map((link, index) => /* @__PURE__ */ jsxDEV2("link", {
810
+ state.head?.meta?.map((meta) => renderMeta(meta, descriptorKey(meta))),
811
+ state.head?.links?.map((link) => /* @__PURE__ */ jsxDEV2("link", {
744
812
  ...link
745
- }, `${link.rel}:${link.href}:${index}`, false, undefined, this)),
746
- state.head?.scripts?.map(({ children, ...attributes }, index) => /* @__PURE__ */ jsxDEV2("script", {
813
+ }, descriptorKey(link), false, undefined, this)),
814
+ state.head?.scripts?.map(({ children, ...attributes }) => /* @__PURE__ */ jsxDEV2("script", {
747
815
  ...attributes,
748
- dangerouslySetInnerHTML: children === undefined ? undefined : { __html: children },
749
- nonce: state.nonce ?? attributes.nonce
750
- }, `script:${index}`, false, undefined, this)),
751
- state.head?.styles?.map(({ children, type }, index) => /* @__PURE__ */ jsxDEV2("style", {
816
+ nonce: state.nonce ?? attributes.nonce,
817
+ children
818
+ }, descriptorKey({ children, ...attributes }), false, undefined, this)),
819
+ state.head?.styles?.map(({ children, type }) => /* @__PURE__ */ jsxDEV2("style", {
752
820
  dangerouslySetInnerHTML: { __html: children },
753
821
  nonce: state.nonce,
754
822
  type
755
- }, `style:${index}`, false, undefined, this))
823
+ }, descriptorKey({ children, type }), false, undefined, this))
756
824
  ]
757
825
  }, undefined, true, undefined, this);
758
826
  }
@@ -961,6 +1029,31 @@ function wrapSegmentBoundaries(inner, segment, options) {
961
1029
  return wrapped;
962
1030
  }
963
1031
 
1032
+ // src/client/route-api.tsx
1033
+ import { createContext as createContext3, createElement as createElement2, useContext as useContext3 } from "react";
1034
+ var RESERVED_RENDER_KEYS = new Set([
1035
+ "catch",
1036
+ "children",
1037
+ "finally",
1038
+ "key",
1039
+ "ref",
1040
+ "then",
1041
+ "toJSON"
1042
+ ]);
1043
+ var ROUTE_CONTEXT = Symbol.for("furin.route.context.v1");
1044
+ var contextGlobal = globalThis;
1045
+ var RouteContext = contextGlobal[ROUTE_CONTEXT] ??= createContext3(null);
1046
+ function withRouteSnapshot(element, pattern, props) {
1047
+ const {
1048
+ params,
1049
+ path: _path,
1050
+ query: _query,
1051
+ ...data
1052
+ } = props;
1053
+ const loaderData = Object.fromEntries(Object.entries(data).filter(([key]) => !(RESERVED_RENDER_KEYS.has(key) || key.startsWith("__furin"))));
1054
+ return createElement2(RouteContext.Provider, { value: { data: loaderData, params: params ?? {}, pattern } }, element);
1055
+ }
1056
+
964
1057
  // src/client/router/boundary-tree.tsx
965
1058
  import { jsxDEV as jsxDEV4 } from "react/jsx-dev-runtime";
966
1059
  function buildRouterTree(context, pageElement, options) {
@@ -978,7 +1071,10 @@ function RouteErrorThrower({
978
1071
  throw new FurinServerError(error);
979
1072
  }
980
1073
  function buildPageElement(match, root, data, options, error) {
981
- let element = error ? createElement2(RouteErrorThrower, { error }) : createElement2(match.component, data);
1074
+ let element = error ? createElement3(RouteErrorThrower, { error }) : createElement3(match.component, {
1075
+ ...data,
1076
+ key: pageKey(match.pattern, data, match.pageRoute.remountDeps)
1077
+ });
982
1078
  const chain = [];
983
1079
  let current = match.pageRoute;
984
1080
  while (current) {
@@ -994,16 +1090,16 @@ function buildPageElement(match, root, data, options, error) {
994
1090
  element = wrapSegmentBoundaries(element, byDepth.get(i), options);
995
1091
  const Layout = chain[i]?.layout;
996
1092
  if (Layout) {
997
- element = createElement2(Layout, data, element);
1093
+ element = createElement3(Layout, data, element);
998
1094
  }
999
1095
  }
1000
1096
  if (root) {
1001
1097
  element = wrapSegmentBoundaries(element, byDepth.get(0), options);
1002
1098
  if (root.layout) {
1003
- element = createElement2(root.layout, data, element);
1099
+ element = createElement3(root.layout, data, element);
1004
1100
  }
1005
1101
  }
1006
- return element;
1102
+ return error ? element : withRouteSnapshot(element, match.pattern, data);
1007
1103
  }
1008
1104
  // src/client/router/history.ts
1009
1105
  var SCROLL_STORAGE_KEY = "__furin_scroll__";
@@ -1035,25 +1131,10 @@ function isStaleDeployResponse(res) {
1035
1131
  return Boolean(clientBuildId && serverBuildId !== clientBuildId);
1036
1132
  }
1037
1133
  // src/client/router/navigation.ts
1038
- import { useCallback } from "react";
1039
1134
  function useNavigate() {
1040
- const router = useRouter();
1041
- return useCallback((next) => {
1042
- const searchDefaults = findSearchDefaultsForRouteTarget(next.to, router.searchRoutes);
1043
- const href = buildHref(next.to, next.search, next.hash, searchDefaults);
1044
- const policy = navigationHrefPolicy(href, typeof window === "undefined" ? undefined : window.location.origin);
1045
- if (policy === "blocked") {
1046
- return Promise.reject(new Error("[furin] Unsafe navigation URL."));
1047
- }
1048
- if (policy === "external" && typeof window !== "undefined") {
1049
- window.location.assign(href);
1050
- return Promise.resolve();
1051
- }
1052
- const opts = next.replace === undefined && next.resetScroll === undefined ? undefined : { replace: next.replace, resetScroll: next.resetScroll };
1053
- return router.navigate(href, opts);
1054
- }, [router]);
1135
+ return useRouter().navigate;
1055
1136
  }
1056
- // ../../node_modules/.bun/evlog@2.29.0+dbd53f8719b7cf53/node_modules/evlog/dist/utils.mjs
1137
+ // ../../node_modules/.bun/evlog@2.29.0+e419d84a67dec76a/node_modules/evlog/dist/utils.mjs
1057
1138
  function formatDuration(ms) {
1058
1139
  if (ms < 1000)
1059
1140
  return `${Math.round(ms)}ms`;
@@ -1180,7 +1261,7 @@ function isoNow() {
1180
1261
  return `${_isoCachedPrefix}.${String(now % 1000).padStart(3, "0")}Z`;
1181
1262
  }
1182
1263
 
1183
- // ../../node_modules/.bun/evlog@2.29.0+dbd53f8719b7cf53/node_modules/evlog/dist/redact-C7FmdhwI.mjs
1264
+ // ../../node_modules/.bun/evlog@2.29.0+e419d84a67dec76a/node_modules/evlog/dist/redact-C7FmdhwI.mjs
1184
1265
  var DEFAULT_REPLACEMENT = "[REDACTED]";
1185
1266
  function normalizeRedactPathPattern(pattern) {
1186
1267
  if (!pattern.includes("*") && !pattern.includes("."))
@@ -1483,7 +1564,7 @@ function applyMaskers(value, maskers) {
1483
1564
  return result;
1484
1565
  }
1485
1566
 
1486
- // ../../node_modules/.bun/evlog@2.29.0+dbd53f8719b7cf53/node_modules/evlog/dist/globalRegistry-Bh3bIGwA.mjs
1567
+ // ../../node_modules/.bun/evlog@2.29.0+e419d84a67dec76a/node_modules/evlog/dist/globalRegistry-Bh3bIGwA.mjs
1487
1568
  function logPluginError(name, hook, err) {
1488
1569
  console.error(`[evlog/${name}] ${hook} failed:`, err);
1489
1570
  }
@@ -1641,7 +1722,7 @@ function getRegistry() {
1641
1722
  }
1642
1723
  var globalConfig = getRegistry().config;
1643
1724
 
1644
- // ../../node_modules/.bun/evlog@2.29.0+dbd53f8719b7cf53/node_modules/evlog/dist/pretty-error-D8rlWNL1.mjs
1725
+ // ../../node_modules/.bun/evlog@2.29.0+e419d84a67dec76a/node_modules/evlog/dist/pretty-error-D8rlWNL1.mjs
1645
1726
  var snippetReader = null;
1646
1727
  var PRETTY_ERROR_TREE_SPACER = "__EVLOG_TREE_SPACER__";
1647
1728
  function pushTreeSpacer(children) {
@@ -1942,7 +2023,7 @@ function buildErrorEntries(error, options = {}) {
1942
2023
  }];
1943
2024
  }
1944
2025
 
1945
- // ../../node_modules/.bun/evlog@2.29.0+dbd53f8719b7cf53/node_modules/evlog/dist/dev-terminal-Brarc6vc.mjs
2026
+ // ../../node_modules/.bun/evlog@2.29.0+e419d84a67dec76a/node_modules/evlog/dist/dev-terminal-Brarc6vc.mjs
1946
2027
  var DEV_PRESETS = {
1947
2028
  evlog: {
1948
2029
  frameworkOverlay: false,
@@ -1991,7 +2072,7 @@ function resolveDevTerminal(input = {}) {
1991
2072
  };
1992
2073
  }
1993
2074
 
1994
- // ../../node_modules/.bun/evlog@2.29.0+dbd53f8719b7cf53/node_modules/evlog/dist/wideEventChannel-BUDW48oP.mjs
2075
+ // ../../node_modules/.bun/evlog@2.29.0+e419d84a67dec76a/node_modules/evlog/dist/wideEventChannel-BUDW48oP.mjs
1995
2076
  var publisher = null;
1996
2077
  function publishWideEvent(event) {
1997
2078
  if (!publisher)
@@ -2003,13 +2084,13 @@ function publishWideEvent(event) {
2003
2084
  }
2004
2085
  }
2005
2086
 
2006
- // ../../node_modules/.bun/evlog@2.29.0+dbd53f8719b7cf53/node_modules/evlog/dist/error-brand-D0-DCPvr.mjs
2087
+ // ../../node_modules/.bun/evlog@2.29.0+e419d84a67dec76a/node_modules/evlog/dist/error-brand-D0-DCPvr.mjs
2007
2088
  var evlogErrorBrand = Symbol.for("evlog.error.brand");
2008
2089
  function isEvlogError(error) {
2009
2090
  return typeof error === "object" && error !== null && error[evlogErrorBrand] === true;
2010
2091
  }
2011
2092
 
2012
- // ../../node_modules/.bun/evlog@2.29.0+dbd53f8719b7cf53/node_modules/evlog/dist/error.mjs
2093
+ // ../../node_modules/.bun/evlog@2.29.0+e419d84a67dec76a/node_modules/evlog/dist/error.mjs
2013
2094
  var evlogErrorInternalKey = Symbol.for("evlog.error.internal");
2014
2095
  var evlogErrorDataKey = Symbol.for("evlog.error.data");
2015
2096
  var EvlogError = class EvlogError extends Error {
@@ -2113,7 +2194,7 @@ Object.defineProperty(EvlogError.prototype, evlogErrorBrand, {
2113
2194
  enumerable: false
2114
2195
  });
2115
2196
 
2116
- // ../../node_modules/.bun/evlog@2.29.0+dbd53f8719b7cf53/node_modules/evlog/dist/audit-C8euLMvu.mjs
2197
+ // ../../node_modules/.bun/evlog@2.29.0+e419d84a67dec76a/node_modules/evlog/dist/audit-C8euLMvu.mjs
2117
2198
  var nativeStdoutWrite = typeof process !== "undefined" && typeof process.stdout?.write === "function" ? process.stdout.write.bind(process.stdout) : undefined;
2118
2199
  function writePrettyStdout(text) {
2119
2200
  (globalThis.__evlogNativeStdoutWrite ?? nativeStdoutWrite)?.(text);
@@ -2787,7 +2868,16 @@ function finalizeAudit(event) {
2787
2868
  _testCollector?.(decorated, event);
2788
2869
  }
2789
2870
  // src/client/router/provider.tsx
2790
- import { useCallback as useCallback2, useEffect, useLayoutEffect, useMemo, useRef, useState } from "react";
2871
+ import {
2872
+ createElement as createElement6,
2873
+ useCallback as useCallback3,
2874
+ useEffect as useEffect2,
2875
+ useLayoutEffect,
2876
+ useMemo as useMemo2,
2877
+ useRef,
2878
+ useState,
2879
+ useSyncExternalStore as useSyncExternalStore2
2880
+ } from "react";
2791
2881
 
2792
2882
  // ../../node_modules/.bun/seroval@1.6.7/node_modules/seroval/dist/dev/index.js
2793
2883
  var SYM_ASYNC_ITERATOR = Symbol.asyncIterator;
@@ -3843,7 +3933,7 @@ function parseCompactJsonLine(value) {
3843
3933
  import {
3844
3934
  Children,
3845
3935
  cloneElement,
3846
- createElement as createElement3,
3936
+ createElement as createElement4,
3847
3937
  isValidElement,
3848
3938
  use
3849
3939
  } from "react";
@@ -3876,7 +3966,7 @@ function decodeFlightBytes(bytes) {
3876
3966
  }));
3877
3967
  }
3878
3968
  function createRenderableSource(state) {
3879
- const element = createElement3(RscNode, { state });
3969
+ const element = createElement4(RscNode, { state });
3880
3970
  return new Proxy(element, {
3881
3971
  get(target, property, receiver) {
3882
3972
  if (property === RSC_SOURCE) {
@@ -3894,6 +3984,50 @@ function restoreRscSource(kind, bytes) {
3894
3984
  return kind === "renderable" ? createRenderableSource(state) : { [RSC_SOURCE]: state };
3895
3985
  }
3896
3986
 
3987
+ // src/shared/sync-query.ts
3988
+ function mergeQuerySeeds(target, incoming) {
3989
+ for (const seed of incoming) {
3990
+ const index = target.findIndex((existing) => existing.url === seed.url);
3991
+ const previous = target[index];
3992
+ const bindings = [...seed.bindings ?? []];
3993
+ if (previous?.identity.session === seed.identity.session && queryTag(previous.identity) === queryTag(seed.identity)) {
3994
+ for (const binding of previous.bindings ?? []) {
3995
+ if (!bindings.some((next) => JSON.stringify(next.target) === JSON.stringify(binding.target))) {
3996
+ bindings.push(binding);
3997
+ }
3998
+ }
3999
+ }
4000
+ const merged = { ...seed, bindings };
4001
+ if (index < 0) {
4002
+ target.push(merged);
4003
+ } else {
4004
+ target[index] = merged;
4005
+ }
4006
+ }
4007
+ }
4008
+ var PREFIX = "__furin.query:";
4009
+ function queryTag(identity) {
4010
+ for (const [key, value] of Object.entries(identity.scope)) {
4011
+ if (value === undefined) {
4012
+ throw new Error(`[furin] Query scope "${key}" is undefined for "${identity.id}".`);
4013
+ }
4014
+ }
4015
+ return PREFIX + JSON.stringify([
4016
+ identity.id,
4017
+ Object.entries(identity.scope).sort(([a], [b]) => {
4018
+ if (a === b) {
4019
+ return 0;
4020
+ }
4021
+ return a < b ? -1 : 1;
4022
+ })
4023
+ ]);
4024
+ }
4025
+ function queryUrl(url, origin) {
4026
+ const parsed = new URL(url, origin);
4027
+ parsed.searchParams.sort();
4028
+ return (parsed.origin === origin ? "" : parsed.origin) + parsed.pathname + parsed.search;
4029
+ }
4030
+
3897
4031
  // src/shared/route-frame.ts
3898
4032
  var FRAME_VERSION = 3;
3899
4033
  var MAX_FRAME_BYTES = 1024 * 1024;
@@ -4004,6 +4138,10 @@ async function parseRouteFrameLines(firstLine, readLine) {
4004
4138
  const { frame } = envelope;
4005
4139
  if (frame.type === "data") {
4006
4140
  dataValue = fromCrossJSON(frame.value, {});
4141
+ if (frame.deferredKeys.length > 0 && dataValue && typeof dataValue === "object") {
4142
+ const data = dataValue;
4143
+ data.__furinQueries ??= [];
4144
+ }
4007
4145
  for (const key of frame.deferredKeys) {
4008
4146
  deferredPromises[key] = new Promise((resolve, reject) => {
4009
4147
  resolvers.set(key, { reject, resolve });
@@ -4038,6 +4176,10 @@ async function parseRouteFrameLines(firstLine, readLine) {
4038
4176
  } else if (frame.type === "rsc-error") {
4039
4177
  throw new Error(`[furin] RSC stream failed (${frame.digest})`);
4040
4178
  } else if (frame.type === "defer-resolve") {
4179
+ if (frame.queries && dataValue && typeof dataValue === "object") {
4180
+ const data = dataValue;
4181
+ mergeQuerySeeds(data.__furinQueries ??= [], fromCrossJSON(frame.queries, {}));
4182
+ }
4041
4183
  const value = fromCrossJSON(frame.value, {});
4042
4184
  const ids = new Set;
4043
4185
  collectRscDescriptorIds(value, ids);
@@ -4289,6 +4431,87 @@ async function readDeferredLines(readLine, resolvers) {
4289
4431
  }
4290
4432
  }
4291
4433
 
4434
+ // src/shared/query-bindings.ts
4435
+ function isContainer(value) {
4436
+ if (!value || typeof value !== "object") {
4437
+ return false;
4438
+ }
4439
+ const prototype = Object.getPrototypeOf(value);
4440
+ return Array.isArray(value) || prototype === Object.prototype || prototype === null;
4441
+ }
4442
+ function replace(value, path, next) {
4443
+ const [key, ...rest] = path;
4444
+ if (key === undefined) {
4445
+ return next;
4446
+ }
4447
+ if (!(isContainer(value) && Object.hasOwn(value, key))) {
4448
+ return value;
4449
+ }
4450
+ const child = replace(value[key], rest, next);
4451
+ if (child === value[key]) {
4452
+ return value;
4453
+ }
4454
+ const copy = Array.isArray(value) ? [...value] : { ...value };
4455
+ Object.defineProperty(copy, key, {
4456
+ configurable: true,
4457
+ enumerable: true,
4458
+ value: child,
4459
+ writable: true
4460
+ });
4461
+ return copy;
4462
+ }
4463
+ function isDeferredTarget(data, target) {
4464
+ const [key] = target;
4465
+ return key !== undefined && isContainer(data) && data[key] instanceof Promise;
4466
+ }
4467
+ function projectQueryData(data, seeds, read) {
4468
+ let projected = data;
4469
+ for (const seed of seeds) {
4470
+ const snapshot = read(seed);
4471
+ if (snapshot === undefined) {
4472
+ continue;
4473
+ }
4474
+ for (const binding of seed.bindings ?? []) {
4475
+ if (isDeferredTarget(data, binding.target)) {
4476
+ continue;
4477
+ }
4478
+ let value = snapshot;
4479
+ for (const key of binding.source) {
4480
+ value = isContainer(value) && Object.hasOwn(value, key) ? value[key] : undefined;
4481
+ }
4482
+ projected = replace(projected, binding.target, value);
4483
+ }
4484
+ }
4485
+ return projected;
4486
+ }
4487
+ function projectDeferredQueryData(data, seeds, read, resolved) {
4488
+ let base = data;
4489
+ const deferred = new Map;
4490
+ for (const [key, promise] of Object.entries(data)) {
4491
+ if (!(promise instanceof Promise)) {
4492
+ continue;
4493
+ }
4494
+ const state = resolved.get(promise);
4495
+ if (state) {
4496
+ deferred.set(key, { promise, state });
4497
+ base = replace(base, [key], state.value);
4498
+ }
4499
+ }
4500
+ let projected = projectQueryData(base, seeds, read);
4501
+ for (const [key, { promise, state }] of deferred) {
4502
+ const value = isContainer(projected) ? projected[key] : undefined;
4503
+ if (value === state.value) {
4504
+ projected = replace(projected, [key], promise);
4505
+ continue;
4506
+ }
4507
+ if (!state.projection || state.projection.value !== value) {
4508
+ state.projection = { value, promise: Promise.resolve(value) };
4509
+ }
4510
+ projected = replace(projected, [key], state.projection.promise);
4511
+ }
4512
+ return projected;
4513
+ }
4514
+
4292
4515
  // src/client/browser-events.ts
4293
4516
  var BROWSER_EVENT_RUNTIME_KEY = Symbol.for("furin.browser-events.runtime");
4294
4517
  function subscribeBrowserEvent(channel, listener) {
@@ -4296,15 +4519,425 @@ function subscribeBrowserEvent(channel, listener) {
4296
4519
  return runtime?.subscribe(channel, listener);
4297
4520
  }
4298
4521
 
4522
+ // src/client/query.tsx
4523
+ import {
4524
+ createContext as createContext4,
4525
+ useCallback as useCallback2,
4526
+ useContext as useContext4,
4527
+ useEffect,
4528
+ useSyncExternalStore
4529
+ } from "react";
4530
+
4531
+ // src/client/query-store.ts
4532
+ var QUERY_REFERENCE = Symbol.for("furin.query.reference.v1");
4533
+ var SERVER_ENVIRONMENT = Symbol.for("furin.query.environment.v1");
4534
+ class QueryStore {
4535
+ entries = new Map;
4536
+ listeners = new Set;
4537
+ revisionValue = 0;
4538
+ projections = new Set;
4539
+ session;
4540
+ epoch = 0;
4541
+ origin;
4542
+ constructor(origin) {
4543
+ this.origin = origin;
4544
+ }
4545
+ key(url) {
4546
+ const absolute = new URL(url, this.origin).href;
4547
+ return queryUrl(absolute, undefined);
4548
+ }
4549
+ entry(url) {
4550
+ const key = this.key(url);
4551
+ let entry = this.entries.get(key);
4552
+ if (!entry) {
4553
+ entry = {
4554
+ base: undefined,
4555
+ listeners: new Set,
4556
+ snapshot: { data: undefined, error: null, isFetching: false },
4557
+ stale: true,
4558
+ version: 0
4559
+ };
4560
+ this.entries.set(key, entry);
4561
+ }
4562
+ return entry;
4563
+ }
4564
+ publish(entry) {
4565
+ let data = entry.base;
4566
+ for (const projection of this.projections) {
4567
+ const transform = projection.transforms.get(entry);
4568
+ if (transform && data !== undefined) {
4569
+ data = transform(data);
4570
+ }
4571
+ }
4572
+ entry.snapshot = { ...entry.snapshot, data };
4573
+ for (const listener of entry.listeners) {
4574
+ listener();
4575
+ }
4576
+ this.revisionValue += 1;
4577
+ for (const listener of this.listeners) {
4578
+ listener();
4579
+ }
4580
+ }
4581
+ revision = () => this.revisionValue;
4582
+ subscribeAll = (listener) => {
4583
+ this.listeners.add(listener);
4584
+ return () => this.listeners.delete(listener);
4585
+ };
4586
+ observe(url, result, epoch, version) {
4587
+ const existing = this.entries.get(this.key(url));
4588
+ if (epoch !== this.epoch || result.error !== null || existing && (this.pending(existing) || version !== undefined && existing.version !== version)) {
4589
+ return;
4590
+ }
4591
+ const header = result.response?.headers.get("x-furin-query");
4592
+ const identity = result.identity ?? (header ? JSON.parse(header) : undefined);
4593
+ if (identity) {
4594
+ this.setSession(identity.session);
4595
+ }
4596
+ const entry = this.entry(url);
4597
+ entry.base = result.data;
4598
+ entry.version += 1;
4599
+ entry.identity = identity;
4600
+ entry.local = result.local ?? result.response?.url === "";
4601
+ entry.stale = false;
4602
+ entry.snapshot = { data: result.data, error: null, isFetching: false };
4603
+ for (const projection of this.projections) {
4604
+ if (!projection.pending) {
4605
+ projection.transforms.delete(entry);
4606
+ if (projection.transforms.size === 0) {
4607
+ this.projections.delete(projection);
4608
+ projection.onRemove?.();
4609
+ }
4610
+ }
4611
+ }
4612
+ this.publish(entry);
4613
+ if (this.entries.size > 100) {
4614
+ const oldest = [...this.entries].find(([, item]) => item !== entry && item.listeners.size === 0 && !item.promise && !this.pending(item));
4615
+ if (oldest) {
4616
+ this.entries.delete(oldest[0]);
4617
+ }
4618
+ }
4619
+ }
4620
+ setSession(session) {
4621
+ if (this.session !== undefined && this.session !== session) {
4622
+ this.epoch += 1;
4623
+ for (const projection of this.projections) {
4624
+ projection.onRemove?.();
4625
+ }
4626
+ this.projections.clear();
4627
+ for (const entry of this.entries.values()) {
4628
+ entry.base = undefined;
4629
+ entry.identity = undefined;
4630
+ entry.stale = true;
4631
+ entry.version += 1;
4632
+ entry.snapshot = { data: undefined, error: null, isFetching: false };
4633
+ this.publish(entry);
4634
+ }
4635
+ }
4636
+ this.session = session;
4637
+ }
4638
+ generation() {
4639
+ return this.epoch;
4640
+ }
4641
+ version(url) {
4642
+ return this.entry(url).version;
4643
+ }
4644
+ snapshot(url) {
4645
+ return this.entry(url).snapshot;
4646
+ }
4647
+ subscribe(url, listener) {
4648
+ const entry = this.entry(url);
4649
+ entry.listeners.add(listener);
4650
+ return () => entry.listeners.delete(listener);
4651
+ }
4652
+ bind(url, load, client) {
4653
+ const entry = this.entry(url);
4654
+ if (client && entry.client && client !== entry.client) {
4655
+ entry.base = undefined;
4656
+ entry.identity = undefined;
4657
+ entry.stale = true;
4658
+ entry.version += 1;
4659
+ entry.snapshot = { data: undefined, error: null, isFetching: false };
4660
+ for (const projection of this.projections) {
4661
+ projection.transforms.delete(entry);
4662
+ }
4663
+ }
4664
+ entry.client = client ?? entry.client;
4665
+ entry.load = load;
4666
+ }
4667
+ pending(entry) {
4668
+ return [...this.projections].some((projection) => projection.pending && projection.transforms.has(entry));
4669
+ }
4670
+ fetch(url) {
4671
+ const entry = this.entry(url);
4672
+ if (entry.promise) {
4673
+ return entry.promise;
4674
+ }
4675
+ if (!(entry.stale && entry.load) || this.pending(entry)) {
4676
+ return Promise.resolve();
4677
+ }
4678
+ const { version } = entry;
4679
+ const { epoch } = this;
4680
+ entry.snapshot = { ...entry.snapshot, isFetching: true };
4681
+ this.publish(entry);
4682
+ entry.promise = Promise.resolve().then(() => entry.load?.()).then((result) => {
4683
+ if (!result || epoch !== this.epoch || version !== entry.version || this.pending(entry)) {
4684
+ return;
4685
+ }
4686
+ if (result.error === null) {
4687
+ this.observe(url, result, epoch);
4688
+ } else {
4689
+ entry.snapshot = { ...entry.snapshot, error: result.error };
4690
+ }
4691
+ }).catch((error) => {
4692
+ if (epoch === this.epoch && version === entry.version) {
4693
+ entry.snapshot = { ...entry.snapshot, error };
4694
+ }
4695
+ }).finally(() => {
4696
+ entry.promise = undefined;
4697
+ entry.snapshot = { ...entry.snapshot, isFetching: false };
4698
+ this.publish(entry);
4699
+ if (entry.stale && version !== entry.version && entry.listeners.size > 0) {
4700
+ this.fetch(url);
4701
+ }
4702
+ });
4703
+ return entry.promise;
4704
+ }
4705
+ invalidate(identities) {
4706
+ const tags = new Set(identities.map(queryTag));
4707
+ let affected = false;
4708
+ for (const [url, entry] of this.entries) {
4709
+ if (entry.identity && tags.has(queryTag(entry.identity))) {
4710
+ affected = true;
4711
+ this.invalidateEntry(url, entry);
4712
+ }
4713
+ }
4714
+ return affected;
4715
+ }
4716
+ invalidateEntry(url, entry) {
4717
+ entry.stale = true;
4718
+ entry.version += 1;
4719
+ if (entry.listeners.size > 0) {
4720
+ this.fetch(url);
4721
+ }
4722
+ }
4723
+ invalidateAll() {
4724
+ for (const [url, entry] of this.entries) {
4725
+ this.invalidateEntry(url, entry);
4726
+ }
4727
+ }
4728
+ begin() {
4729
+ return { pending: true, transforms: new Map };
4730
+ }
4731
+ update(projection, url, transform) {
4732
+ const entry = this.entries.get(this.key(url));
4733
+ if (!entry || entry.base === undefined) {
4734
+ return;
4735
+ }
4736
+ const previous = projection.transforms.get(entry);
4737
+ projection.transforms.set(entry, previous ? (data) => transform(previous(data)) : transform);
4738
+ entry.version += 1;
4739
+ this.projections.add(projection);
4740
+ this.publish(entry);
4741
+ }
4742
+ finish(projection, outcome) {
4743
+ projection.pending = false;
4744
+ const entries = [...projection.transforms.keys()];
4745
+ if (outcome === "error") {
4746
+ this.projections.delete(projection);
4747
+ projection.onRemove?.();
4748
+ }
4749
+ for (const entry of entries) {
4750
+ this.publish(entry);
4751
+ if (outcome !== "error") {
4752
+ entry.stale = true;
4753
+ }
4754
+ const url = [...this.entries].find(([, candidate]) => candidate === entry)?.[0];
4755
+ if (url && entry.stale) {
4756
+ this.fetch(url);
4757
+ }
4758
+ }
4759
+ }
4760
+ dehydrate() {
4761
+ return [...this.entries].flatMap(([url, entry]) => entry.identity && entry.base !== undefined ? [{ url, data: entry.base, identity: entry.identity, local: entry.local }] : []);
4762
+ }
4763
+ seedUrl(seed, localOrigin) {
4764
+ const original = new URL(seed.url, this.origin);
4765
+ return seed.local && localOrigin ? new URL(original.pathname + original.search, localOrigin).href : original.href;
4766
+ }
4767
+ captureHydration() {
4768
+ const { epoch } = this;
4769
+ const versions = new Map([...this.entries].map(([key, entry]) => [key, entry.version]));
4770
+ return (seeds, localOrigin) => {
4771
+ if (epoch === this.epoch) {
4772
+ this.hydrate(seeds.filter((seed) => {
4773
+ const url = this.seedUrl(seed, localOrigin);
4774
+ return this.version(url) === (versions.get(this.key(url)) ?? 0);
4775
+ }), localOrigin);
4776
+ }
4777
+ };
4778
+ }
4779
+ hydrate(seeds, localOrigin) {
4780
+ for (const seed of seeds) {
4781
+ const url = this.seedUrl(seed, localOrigin);
4782
+ this.observe(url, {
4783
+ data: seed.data,
4784
+ error: null,
4785
+ identity: seed.identity,
4786
+ local: seed.local ?? false
4787
+ }, this.epoch);
4788
+ }
4789
+ }
4790
+ }
4791
+
4792
+ // src/client/query.tsx
4793
+ var QUERY_CONTEXT = Symbol.for("furin.query.context.v1");
4794
+ var contextGlobal2 = globalThis;
4795
+ var QueryStoreContext = contextGlobal2[QUERY_CONTEXT] ??= createContext4(null);
4796
+
4299
4797
  // src/client/router/abort.ts
4300
4798
  function isAbortError(error) {
4301
4799
  return error !== null && typeof error === "object" && "name" in error && error.name === "AbortError";
4302
4800
  }
4303
4801
 
4802
+ // src/client/router/optimistic.ts
4803
+ var SYNC_REQUEST = Symbol.for("furin.sync.request.v1");
4804
+ function identity(href) {
4805
+ const url = new URL(href, "http://furin.local");
4806
+ url.searchParams.sort();
4807
+ return url.pathname + url.search;
4808
+ }
4809
+ var RUNTIMES = Symbol.for("furin.optimistic.runtimes.v1");
4810
+ var runtimeGlobal = globalThis;
4811
+ var runtimes = runtimeGlobal[RUNTIMES] ??= new Set;
4812
+ function registerOptimisticRuntime(runtime) {
4813
+ runtimes.add(runtime);
4814
+ return () => {
4815
+ runtimes.delete(runtime);
4816
+ };
4817
+ }
4818
+ function createOptimisticRuntime(options) {
4819
+ const operations = new Set;
4820
+ const listeners = new Set;
4821
+ const revisions = new Map;
4822
+ let version = 0;
4823
+ const notify = (operation) => {
4824
+ version += 1;
4825
+ for (const { href } of operation.transforms) {
4826
+ revisions.set(href, (revisions.get(href) ?? 0) + 1);
4827
+ }
4828
+ if (operation.queryHref) {
4829
+ revisions.set(operation.queryHref, (revisions.get(operation.queryHref) ?? 0) + 1);
4830
+ }
4831
+ for (const listener of listeners) {
4832
+ listener();
4833
+ }
4834
+ };
4835
+ const pending = (href) => [...operations].some((operation) => operation.pending && (operation.queryHref === identity(href) || operation.transforms.some((transform) => transform.href === identity(href))));
4836
+ return {
4837
+ basePath: options.basePath,
4838
+ queries: options.queries,
4839
+ begin(optimistic, onRemove, hasQueries) {
4840
+ const operation = { onRemove, pending: true, transforms: [] };
4841
+ const cache = {
4842
+ update(target, transform) {
4843
+ const snapshot = options.snapshot();
4844
+ const path = typeof target === "string" ? target : buildHref(target.path, target.search, undefined);
4845
+ const href = identity(typeof target === "string" && target === snapshot.pattern ? snapshot.href : path);
4846
+ if (snapshot.loaded && href === identity(snapshot.href)) {
4847
+ operation.transforms.push({ href, transform });
4848
+ }
4849
+ }
4850
+ };
4851
+ optimistic?.(cache);
4852
+ if (hasQueries?.() && options.snapshot().loaded) {
4853
+ operation.queryHref = identity(options.snapshot().href);
4854
+ }
4855
+ if (operation.transforms.length > 0 || operation.queryHref !== undefined) {
4856
+ operations.add(operation);
4857
+ notify(operation);
4858
+ }
4859
+ return operation;
4860
+ },
4861
+ commit(href) {
4862
+ for (const operation of operations) {
4863
+ if (!operation.pending) {
4864
+ if (operation.queryHref === identity(href)) {
4865
+ operation.queryHref = undefined;
4866
+ }
4867
+ operation.transforms = operation.transforms.filter((transform) => transform.href !== identity(href));
4868
+ if (operation.transforms.length === 0 && operation.queryHref === undefined) {
4869
+ operations.delete(operation);
4870
+ operation.onRemove?.();
4871
+ }
4872
+ }
4873
+ }
4874
+ },
4875
+ finish(operation, outcome, response) {
4876
+ operation.pending = false;
4877
+ if (outcome === "error") {
4878
+ operations.delete(operation);
4879
+ }
4880
+ if (outcome === "error" || operation.transforms.length === 0 && operation.queryHref === undefined) {
4881
+ operation.onRemove?.();
4882
+ }
4883
+ if (operation.transforms.length > 0 || operation.queryHref !== undefined) {
4884
+ notify(operation);
4885
+ }
4886
+ options.onResponse(response, outcome !== "error" && (operation.transforms.length > 0 || operation.queryHref !== undefined));
4887
+ },
4888
+ has: (href) => [...operations].some((operation) => operation.queryHref === identity(href) || operation.transforms.some((transform) => transform.href === identity(href))),
4889
+ project(data, href) {
4890
+ let projected = data;
4891
+ for (const operation of operations) {
4892
+ for (const transformation of operation.transforms) {
4893
+ if (transformation.href === identity(href)) {
4894
+ projected = { ...projected, ...transformation.transform(projected) };
4895
+ }
4896
+ }
4897
+ }
4898
+ return projected;
4899
+ },
4900
+ publishable: (href, revision) => !pending(href) && (revisions.get(identity(href)) ?? 0) === revision,
4901
+ revision: (href) => href === undefined ? version : revisions.get(identity(href)) ?? 0,
4902
+ subscribe(listener) {
4903
+ listeners.add(listener);
4904
+ return () => {
4905
+ listeners.delete(listener);
4906
+ };
4907
+ },
4908
+ wait(href, signal) {
4909
+ if (signal?.aborted) {
4910
+ return Promise.reject(signal.reason);
4911
+ }
4912
+ if (!pending(href)) {
4913
+ return Promise.resolve();
4914
+ }
4915
+ return new Promise((resolve, reject) => {
4916
+ const cleanup = () => {
4917
+ listeners.delete(check);
4918
+ signal?.removeEventListener("abort", abort);
4919
+ };
4920
+ const abort = () => {
4921
+ cleanup();
4922
+ reject(signal?.reason);
4923
+ };
4924
+ const check = () => {
4925
+ if (!pending(href)) {
4926
+ cleanup();
4927
+ resolve();
4928
+ }
4929
+ };
4930
+ listeners.add(check);
4931
+ signal?.addEventListener("abort", abort, { once: true });
4932
+ });
4933
+ }
4934
+ };
4935
+ }
4936
+
4304
4937
  // src/client/router/search-store.ts
4305
- import { createContext as createContext3 } from "react";
4938
+ import { createContext as createContext5 } from "react";
4306
4939
  function searchSnapshotChanged(a, b) {
4307
- return a.currentHref !== b.currentHref || a.navigate !== b.navigate || a.search !== b.search || a.searchRoutes !== b.searchRoutes;
4940
+ return a.currentHref !== b.currentHref || a.currentPattern !== b.currentPattern || a.navigate !== b.navigate || a.search !== b.search || a.searchRoutes !== b.searchRoutes;
4308
4941
  }
4309
4942
  function createSearchStore(initialSnapshot) {
4310
4943
  let snapshot = initialSnapshot;
@@ -4341,6 +4974,7 @@ function createSearchStore(initialSnapshot) {
4341
4974
  function searchSnapshotFromRouterContext(context) {
4342
4975
  return {
4343
4976
  currentHref: context.currentHref,
4977
+ currentPattern: context.currentPattern,
4344
4978
  navigate: context.navigate,
4345
4979
  search: context.search,
4346
4980
  searchRoutes: context.searchRoutes
@@ -4348,6 +4982,7 @@ function searchSnapshotFromRouterContext(context) {
4348
4982
  }
4349
4983
  var FALLBACK_SEARCH_STORE = createSearchStore({
4350
4984
  currentHref: "/",
4985
+ currentPattern: undefined,
4351
4986
  navigate: (href, _opts) => {
4352
4987
  if (typeof window !== "undefined") {
4353
4988
  if (navigationHrefPolicy(href, window.location.origin) === "blocked") {
@@ -4360,10 +4995,10 @@ var FALLBACK_SEARCH_STORE = createSearchStore({
4360
4995
  search: {},
4361
4996
  searchRoutes: []
4362
4997
  });
4363
- var SearchStoreContext = createContext3(null);
4998
+ var SearchStoreContext = createContext5(null);
4364
4999
 
4365
5000
  // src/client/router/spa-response.ts
4366
- import { createElement as createElement4 } from "react";
5001
+ import { createElement as createElement5 } from "react";
4367
5002
  function isFurinErrorPayload(value) {
4368
5003
  if (!value || typeof value !== "object") {
4369
5004
  return false;
@@ -4398,10 +5033,10 @@ function pickDeepestNotFound(boundaries) {
4398
5033
  }
4399
5034
  }
4400
5035
  }
4401
- var DefaultClientNotFoundFallback = ({ error }) => createElement4(DefaultNotFoundScreen, { message: error.message });
5036
+ var DefaultClientNotFoundFallback = ({ error }) => createElement5(DefaultNotFoundScreen, { message: error.message });
4402
5037
  function buildNotFoundPageElement(boundaries, error) {
4403
5038
  const Fallback = pickDeepestNotFound(boundaries) ?? DefaultClientNotFoundFallback;
4404
- return createElement4(Fallback, { error });
5039
+ return createElement5(Fallback, { error });
4405
5040
  }
4406
5041
  async function parsePageResponse(res, basePath) {
4407
5042
  let finalHref;
@@ -4474,12 +5109,16 @@ function createSyncCatchUp(options) {
4474
5109
  do {
4475
5110
  page = await options.fetchPage(currentCursor ?? "0");
4476
5111
  if (page.reset) {
5112
+ options.onReset?.();
4477
5113
  options.onInvalidations(["/:layout"]);
4478
5114
  currentCursor = page.cursor;
4479
5115
  break;
4480
5116
  }
4481
5117
  for (const change of page.changes) {
4482
5118
  options.onInvalidations(change.invalidations);
5119
+ if (change.queries) {
5120
+ options.onQueries?.(change.queries);
5121
+ }
4483
5122
  }
4484
5123
  currentCursor = page.cursor;
4485
5124
  } while (page.hasMore);
@@ -4561,8 +5200,15 @@ function RouterProvider({
4561
5200
  syncPath
4562
5201
  }) {
4563
5202
  const initialDocumentState = useDocumentState();
5203
+ const [queries] = useState(() => {
5204
+ const store = new QueryStore(typeof window === "undefined" ? undefined : window.location.origin);
5205
+ store.hydrate(initialData.__furinQueries ?? [], typeof window === "undefined" ? undefined : window.location.origin);
5206
+ return store;
5207
+ });
4564
5208
  const [state, setState] = useState(() => ({
4565
- data: initialData,
5209
+ data: Object.fromEntries(Object.entries(initialData).filter(([key]) => key !== "__furinQueries")),
5210
+ querySeeds: initialData.__furinQueries,
5211
+ hydrateQueries: queries.captureHydration(),
4566
5212
  error: initialError ? {
4567
5213
  ...initialError,
4568
5214
  message: initialError.message || "Something went wrong"
@@ -4572,6 +5218,42 @@ function RouterProvider({
4572
5218
  notFound: initialNotFound
4573
5219
  }));
4574
5220
  const [boundaryResetVersion, setBoundaryResetVersion] = useState(0);
5221
+ const currentState = useRef(state);
5222
+ useLayoutEffect(() => {
5223
+ currentState.current = state;
5224
+ }, [state]);
5225
+ useLayoutEffect(() => {
5226
+ state.hydrateQueries?.(state.querySeeds ?? [], typeof window === "undefined" ? undefined : window.location.origin);
5227
+ }, [state.hydrateQueries, state.querySeeds]);
5228
+ const resolvedQueries = useRef(new WeakMap);
5229
+ const [deferredRevision, setDeferredRevision] = useState(0);
5230
+ useEffect2(() => {
5231
+ const snapshot = currentState.current;
5232
+ const hydrated = new Set(snapshot.querySeeds?.map((seed) => seed.url));
5233
+ let disposed = false;
5234
+ for (const promise of Object.values(state.data)) {
5235
+ if (!(promise instanceof Promise)) {
5236
+ continue;
5237
+ }
5238
+ promise.then((value) => {
5239
+ if (disposed) {
5240
+ return;
5241
+ }
5242
+ resolvedQueries.current.set(promise, { value });
5243
+ const seeds = (snapshot.querySeeds ?? []).filter((seed) => !hydrated.has(seed.url));
5244
+ snapshot.hydrateQueries?.(seeds, window.location.origin);
5245
+ for (const seed of seeds) {
5246
+ hydrated.add(seed.url);
5247
+ }
5248
+ setDeferredRevision((revision) => revision + 1);
5249
+ }, () => {
5250
+ return;
5251
+ });
5252
+ }
5253
+ return () => {
5254
+ disposed = true;
5255
+ };
5256
+ }, [queries, state.data]);
4575
5257
  const [isNavigating, setIsNavigating] = useState(false);
4576
5258
  const [currentHref, setCurrentHref] = useState(() => {
4577
5259
  if (typeof window === "undefined") {
@@ -4579,6 +5261,29 @@ function RouterProvider({
4579
5261
  }
4580
5262
  return normalizeHref(toLogical(window.location.pathname, basePath)) + window.location.search;
4581
5263
  });
5264
+ const optimisticSnapshot = useRef({
5265
+ href: currentHref,
5266
+ loaded: state.match !== null,
5267
+ pattern: state.match?.pattern
5268
+ });
5269
+ useLayoutEffect(() => {
5270
+ optimisticSnapshot.current = {
5271
+ href: currentHref,
5272
+ loaded: state.match !== null && !(state.error || state.notFound),
5273
+ pattern: state.match?.pattern
5274
+ };
5275
+ }, [currentHref, state.match, state.error, state.notFound]);
5276
+ const syncResponse = useRef(undefined);
5277
+ const [optimisticRuntime] = useState(() => createOptimisticRuntime({
5278
+ basePath,
5279
+ queries,
5280
+ snapshot: () => optimisticSnapshot.current,
5281
+ onResponse: (response, optimistic) => syncResponse.current?.(response, optimistic)
5282
+ }));
5283
+ useSyncExternalStore2(optimisticRuntime.subscribe, optimisticRuntime.revision, () => 0);
5284
+ const queryRevision = useSyncExternalStore2(queries.subscribeAll, queries.revision, () => 0);
5285
+ useEffect2(() => registerOptimisticRuntime(optimisticRuntime), [optimisticRuntime]);
5286
+ const snapshotVersions = useRef(new WeakMap);
4582
5287
  const prefetchCache = useRef(new Map);
4583
5288
  const navVersion = useRef(0);
4584
5289
  const hmrVersion = useRef(0);
@@ -4586,10 +5291,11 @@ function RouterProvider({
4586
5291
  const pendingUserNavigation = useRef(null);
4587
5292
  const navAbortRef = useRef(null);
4588
5293
  const pendingScrollRef = useRef(null);
5294
+ const renderedHistoryKey = useRef(undefined);
4589
5295
  const currentMatchRef = useRef(initialMatch);
4590
5296
  const [staticMode] = useState(detectStaticMode);
4591
5297
  const resolvedSearch = state.data.query ?? EMPTY_SEARCH;
4592
- const rootBoundaries = useMemo(() => {
5298
+ const rootBoundaries = useMemo2(() => {
4593
5299
  for (const route of routes) {
4594
5300
  const depth0 = route.segmentBoundaries?.find((b) => b.depth === 0);
4595
5301
  if (depth0) {
@@ -4597,7 +5303,7 @@ function RouterProvider({
4597
5303
  }
4598
5304
  }
4599
5305
  }, [routes]);
4600
- const resolveNoMatchState = useCallback2(async (physicalHref, signal) => {
5306
+ const resolveNoMatchState = useCallback3(async (physicalHref, signal) => {
4601
5307
  const res = await fetch(physicalHref, { signal });
4602
5308
  if (isStaleDeployResponse(res)) {
4603
5309
  return null;
@@ -4617,7 +5323,8 @@ function RouterProvider({
4617
5323
  title
4618
5324
  };
4619
5325
  }, [basePath, rootBoundaries]);
4620
- const fetchPageState = useCallback2(async (rawLogicalHref, signal, hmrRefresh) => {
5326
+ const fetchPageState = useCallback3(async (rawLogicalHref, signal, hmrRefresh) => {
5327
+ const hydrateQueries = queries.captureHydration();
4621
5328
  const logicalHref = normalizeHref(rawLogicalHref);
4622
5329
  try {
4623
5330
  const physicalHref = basePath + logicalHref;
@@ -4665,6 +5372,7 @@ function RouterProvider({
4665
5372
  __furinRedirect,
4666
5373
  __furinError,
4667
5374
  __furinTitle,
5375
+ __furinQueries,
4668
5376
  ...cleanSyncData
4669
5377
  } = syncData;
4670
5378
  if (typeof __furinRedirect === "string") {
@@ -4716,7 +5424,14 @@ function RouterProvider({
4716
5424
  title
4717
5425
  };
4718
5426
  }
4719
- return { data, head: __furinHead, match: loadedMatch, title };
5427
+ return {
5428
+ data,
5429
+ head: __furinHead,
5430
+ match: loadedMatch,
5431
+ querySeeds: __furinQueries,
5432
+ hydrateQueries,
5433
+ title
5434
+ };
4720
5435
  } catch (err) {
4721
5436
  if (!isAbortError(err)) {
4722
5437
  _log.error({
@@ -4727,26 +5442,38 @@ function RouterProvider({
4727
5442
  }
4728
5443
  return null;
4729
5444
  }
4730
- }, [routes, basePath, resolveNoMatchState]);
4731
- const invalidatePrefetch = useCallback2((path, type) => {
4732
- const normalizedPath = stripHashFromHref(path);
4733
- if (type === "page") {
4734
- for (const key of [...prefetchCache.current.keys()]) {
4735
- if (stripHashFromHref(key) === normalizedPath) {
4736
- prefetchCache.current.delete(key);
5445
+ }, [routes, basePath, resolveNoMatchState, queries]);
5446
+ const fetchConfirmedPageState = useCallback3(async (href, signal, hmrRefresh) => {
5447
+ for (;; ) {
5448
+ try {
5449
+ await optimisticRuntime.wait(href, signal);
5450
+ } catch (error) {
5451
+ if (signal?.aborted) {
5452
+ return null;
5453
+ }
5454
+ throw error;
5455
+ }
5456
+ const version = optimisticRuntime.revision(href);
5457
+ const snapshot = await fetchPageState(href, signal, hmrRefresh);
5458
+ if (optimisticRuntime.publishable(href, version)) {
5459
+ if (snapshot) {
5460
+ snapshotVersions.current.set(snapshot, version);
4737
5461
  }
5462
+ return snapshot;
4738
5463
  }
4739
- return;
4740
5464
  }
4741
- const prefix = normalizedPath === "/" || normalizedPath.endsWith("/") ? normalizedPath : `${normalizedPath}/`;
5465
+ }, [fetchPageState, optimisticRuntime]);
5466
+ const invalidatePrefetch = useCallback3((path, type) => {
5467
+ const normalizedPath = normalizeHref(new URL(path, "http://furin.local").pathname);
4742
5468
  for (const key of [...prefetchCache.current.keys()]) {
4743
- const normalizedKey = stripHashFromHref(key);
4744
- if (normalizedKey === normalizedPath || normalizedKey.startsWith(prefix)) {
5469
+ if (shouldAutoRefreshPath(normalizeHref(stripHashFromHref(key)), [
5470
+ { path: normalizedPath, type }
5471
+ ])) {
4745
5472
  prefetchCache.current.delete(key);
4746
5473
  }
4747
5474
  }
4748
5475
  }, []);
4749
- const prefetch = useCallback2((href, opts) => {
5476
+ const prefetch = useCallback3((href, opts) => {
4750
5477
  const staleTime = opts?.staleTime ?? defaultPreloadStaleTime;
4751
5478
  const existing = prefetchCache.current.get(href);
4752
5479
  if (existing && !shouldRefetch(existing)) {
@@ -4760,13 +5487,13 @@ function RouterProvider({
4760
5487
  }, [fetchPageState, defaultPreloadStaleTime, prefetchCacheSize]);
4761
5488
  async function resolveRedirectState(redirectLogical, myVersion, signal) {
4762
5489
  const cached = prefetchCache.current.get(redirectLogical);
4763
- const useCached = cached !== undefined && !shouldRefetch(cached);
4764
- let redirectState = useCached && cached ? await cached.promise : await fetchPageState(redirectLogical, signal, false);
5490
+ const useCached = cached !== undefined && !shouldRefetch(cached) && !optimisticRuntime.has(redirectLogical);
5491
+ let redirectState = useCached && cached ? await cached.promise : await fetchConfirmedPageState(redirectLogical, signal, false);
4765
5492
  if (navVersion.current !== myVersion) {
4766
5493
  return null;
4767
5494
  }
4768
- if (useCached && isRedirectState(redirectState)) {
4769
- redirectState = await fetchPageState(redirectLogical, signal, false);
5495
+ if (useCached && (isRedirectState(redirectState) || redirectState && !optimisticRuntime.publishable(redirectLogical, snapshotVersions.current.get(redirectState) ?? optimisticRuntime.revision(redirectLogical)))) {
5496
+ redirectState = await fetchConfirmedPageState(redirectLogical, signal, false);
4770
5497
  }
4771
5498
  return navVersion.current === myVersion ? redirectState : null;
4772
5499
  }
@@ -4788,8 +5515,9 @@ function RouterProvider({
4788
5515
  }
4789
5516
  return { href, state: redirectState };
4790
5517
  }
4791
- const navigate = useCallback2(async function navigateTo(rawLogicalHref, opts) {
5518
+ const navigate = useCallback3(async function navigateTo(rawLogicalHref, opts) {
4792
5519
  const logicalHref = normalizeHref(rawLogicalHref);
5520
+ const beforeCommit = opts?.beforeCommit;
4793
5521
  const finishUserNavigation = opts?.hmrRefresh === true ? undefined : beginUserNavigation(pendingUserNavigation);
4794
5522
  navVersion.current += 1;
4795
5523
  const myVersion = navVersion.current;
@@ -4800,11 +5528,11 @@ function RouterProvider({
4800
5528
  setIsNavigating(true);
4801
5529
  try {
4802
5530
  const cached = prefetchCache.current.get(logicalHref);
4803
- const useCached = cached !== undefined && !shouldRefetch(cached);
4804
- let newState = useCached && cached ? await cached.promise : await fetchPageState(logicalHref, navSignal, opts?.hmrRefresh === true);
4805
- const cachedRedirect = useCached && isRedirectState(newState);
5531
+ const useCached = cached !== undefined && !shouldRefetch(cached) && !optimisticRuntime.has(logicalHref);
5532
+ let newState = useCached && cached ? await cached.promise : await fetchConfirmedPageState(logicalHref, navSignal, opts?.hmrRefresh === true);
5533
+ const cachedRedirect = useCached && (isRedirectState(newState) || newState && !optimisticRuntime.publishable(logicalHref, snapshotVersions.current.get(newState) ?? optimisticRuntime.revision(logicalHref)));
4806
5534
  if (cachedRedirect) {
4807
- newState = await fetchPageState(logicalHref, navSignal, opts?.hmrRefresh === true);
5535
+ newState = await fetchConfirmedPageState(logicalHref, navSignal, opts?.hmrRefresh === true);
4808
5536
  }
4809
5537
  if (navVersion.current !== myVersion || opts?.shouldCommit?.() === false) {
4810
5538
  return;
@@ -4839,7 +5567,14 @@ function RouterProvider({
4839
5567
  if (opts?.shouldCommit?.() === false) {
4840
5568
  return;
4841
5569
  }
4842
- opts?.beforeCommit?.();
5570
+ const publicationHref = newState.finalHref ?? resolved.href;
5571
+ if (!optimisticRuntime.publishable(publicationHref, snapshotVersions.current.get(newState) ?? optimisticRuntime.revision(publicationHref))) {
5572
+ return;
5573
+ }
5574
+ if (!(newState.error || newState.notFound)) {
5575
+ optimisticRuntime.commit(publicationHref);
5576
+ }
5577
+ beforeCommit?.();
4843
5578
  const effectiveLogical = newState.finalHref ?? resolved.href;
4844
5579
  const physicalEffective = basePath + effectiveLogical;
4845
5580
  if (opts?.resetScroll ?? true) {
@@ -4859,12 +5594,13 @@ function RouterProvider({
4859
5594
  _furinKey: getHistoryKey(history.state) ?? generateHistoryKey()
4860
5595
  }, "", physicalEffective);
4861
5596
  } else {
4862
- const currentKey = getHistoryKey(history.state);
5597
+ const currentKey = renderedHistoryKey.current;
4863
5598
  if (currentKey) {
4864
5599
  saveScrollPosition(currentKey);
4865
5600
  }
4866
5601
  window.history.pushState({ _furinKey: generateHistoryKey() }, "", physicalEffective);
4867
5602
  }
5603
+ renderedHistoryKey.current = getHistoryKey(history.state);
4868
5604
  const effectiveUrl = new URL(physicalEffective, window.location.origin);
4869
5605
  const logicalPath = normalizeHref(toLogical(effectiveUrl.pathname, basePath));
4870
5606
  setCurrentHref(logicalPath + effectiveUrl.search);
@@ -4874,24 +5610,32 @@ function RouterProvider({
4874
5610
  setIsNavigating(false);
4875
5611
  }
4876
5612
  }
4877
- }, [basePath, fetchPageState, defaultPreloadStaleTime, prefetchCacheSize]);
5613
+ }, [
5614
+ basePath,
5615
+ fetchConfirmedPageState,
5616
+ defaultPreloadStaleTime,
5617
+ prefetchCacheSize,
5618
+ optimisticRuntime
5619
+ ]);
4878
5620
  const [searchStore] = useState(() => createSearchStore({
4879
5621
  currentHref,
5622
+ currentPattern: state.match?.pattern,
4880
5623
  navigate,
4881
5624
  search: resolvedSearch,
4882
5625
  searchRoutes: routes
4883
5626
  }));
4884
- const searchSnapshot = useMemo(() => ({
5627
+ const searchSnapshot = useMemo2(() => ({
4885
5628
  currentHref,
5629
+ currentPattern: state.match?.pattern,
4886
5630
  navigate,
4887
5631
  search: resolvedSearch,
4888
5632
  searchRoutes: routes
4889
- }), [currentHref, navigate, resolvedSearch, routes]);
5633
+ }), [currentHref, state.match?.pattern, navigate, resolvedSearch, routes]);
4890
5634
  useLayoutEffect(() => {
4891
5635
  searchStore.setSnapshot(searchSnapshot);
4892
5636
  searchStore.flush();
4893
5637
  }, [searchStore, searchSnapshot]);
4894
- const refresh = useCallback2(async (opts) => {
5638
+ const refresh = useCallback3(async (opts) => {
4895
5639
  const logicalPath = toLogical(window.location.pathname, basePath);
4896
5640
  const logicalHref = logicalPath + window.location.search;
4897
5641
  invalidatePrefetch(logicalHref, "page");
@@ -4903,13 +5647,34 @@ function RouterProvider({
4903
5647
  shouldCommit: opts?.shouldCommit
4904
5648
  });
4905
5649
  }, [navigate, invalidatePrefetch, basePath]);
4906
- const invalidationRefresh = useMemo(() => createInvalidationRefresh({
5650
+ const invalidationRefresh = useMemo2(() => createInvalidationRefresh({
4907
5651
  onError: (error) => {
4908
5652
  _log.warn({ action: "sync_refresh_failed", error: String(error) });
4909
5653
  },
4910
- refresh: () => refresh(undefined)
5654
+ refresh: async () => {
5655
+ await waitForUserNavigation(pendingUserNavigation);
5656
+ await refresh(undefined);
5657
+ }
4911
5658
  }), [refresh]);
4912
- useEffect(() => {
5659
+ useLayoutEffect(() => {
5660
+ syncResponse.current = (response, optimistic) => {
5661
+ const invalidated = [];
5662
+ if (response && (response.url === "" || new URL(response.url).origin === window.location.origin)) {
5663
+ applyRevalidateHeader(response.headers, (path, type) => {
5664
+ const resolvedType = type ?? "page";
5665
+ invalidatePrefetch(path, resolvedType);
5666
+ invalidated.push({ path, type: resolvedType });
5667
+ });
5668
+ }
5669
+ if (optimistic || autoRefresh && shouldAutoRefreshPath(optimisticSnapshot.current.href, invalidated)) {
5670
+ invalidationRefresh.run();
5671
+ }
5672
+ };
5673
+ return () => {
5674
+ syncResponse.current = undefined;
5675
+ };
5676
+ }, [autoRefresh, invalidatePrefetch, invalidationRefresh]);
5677
+ useEffect2(() => {
4913
5678
  if (typeof window !== "undefined") {
4914
5679
  window.__FURIN_HMR_REFRESH__ = async (beforeCommit, dataChanged) => {
4915
5680
  hmrVersion.current += 1;
@@ -4943,8 +5708,11 @@ function RouterProvider({
4943
5708
  };
4944
5709
  }
4945
5710
  }, [refresh]);
4946
- const handlePopState = useCallback2(() => {
5711
+ const handlePopState = useCallback3(() => {
4947
5712
  const finishUserNavigation = beginUserNavigation(pendingUserNavigation);
5713
+ if (renderedHistoryKey.current) {
5714
+ saveScrollPosition(renderedHistoryKey.current);
5715
+ }
4948
5716
  const destKey = getHistoryKey(history.state);
4949
5717
  const logicalPath = normalizeHref(toLogical(window.location.pathname, basePath));
4950
5718
  const logicalHref = logicalPath + window.location.search;
@@ -4959,13 +5727,13 @@ function RouterProvider({
4959
5727
  try {
4960
5728
  const cached = prefetchCache.current.get(logicalHref);
4961
5729
  let newState;
4962
- if (cached && !shouldRefetch(cached)) {
5730
+ if (cached && !shouldRefetch(cached) && !optimisticRuntime.has(logicalHref)) {
4963
5731
  newState = await cached.promise;
4964
- if (isRedirectState(newState)) {
4965
- newState = await fetchPageState(logicalHref, navSignal, false);
5732
+ if (isRedirectState(newState) || newState && !optimisticRuntime.publishable(logicalHref, snapshotVersions.current.get(newState) ?? optimisticRuntime.revision(logicalHref))) {
5733
+ newState = await fetchConfirmedPageState(logicalHref, navSignal, false);
4966
5734
  }
4967
5735
  } else {
4968
- newState = await fetchPageState(logicalHref, navSignal, false);
5736
+ newState = await fetchConfirmedPageState(logicalHref, navSignal, false);
4969
5737
  }
4970
5738
  if (navVersion.current !== myVersion) {
4971
5739
  return;
@@ -4990,6 +5758,13 @@ function RouterProvider({
4990
5758
  return;
4991
5759
  }
4992
5760
  newState = resolved.state;
5761
+ const publicationHref = newState.finalHref ?? resolved.href;
5762
+ if (!optimisticRuntime.publishable(publicationHref, snapshotVersions.current.get(newState) ?? optimisticRuntime.revision(publicationHref))) {
5763
+ return;
5764
+ }
5765
+ if (!(newState.error || newState.notFound)) {
5766
+ optimisticRuntime.commit(publicationHref);
5767
+ }
4993
5768
  currentMatchRef.current = newState.match;
4994
5769
  if (!newState.error) {
4995
5770
  setBoundaryResetVersion((version) => version + 1);
@@ -5002,6 +5777,7 @@ function RouterProvider({
5002
5777
  if (effectiveLogical !== logicalHref) {
5003
5778
  window.history.replaceState(history.state, "", basePath + effectiveLogical);
5004
5779
  }
5780
+ renderedHistoryKey.current = destKey;
5005
5781
  setCurrentHref(normalizeHref(effectiveLogical));
5006
5782
  if (destKey) {
5007
5783
  pendingScrollRef.current = { key: destKey, type: "restore" };
@@ -5015,12 +5791,13 @@ function RouterProvider({
5015
5791
  }
5016
5792
  }
5017
5793
  })();
5018
- }, [fetchPageState, basePath]);
5019
- useEffect(() => {
5794
+ }, [fetchConfirmedPageState, basePath, optimisticRuntime]);
5795
+ useEffect2(() => {
5020
5796
  history.scrollRestoration = "manual";
5021
5797
  if (!getHistoryKey(history.state)) {
5022
5798
  history.replaceState({ ...getHistoryStateObject(), _furinKey: generateHistoryKey() }, "");
5023
5799
  }
5800
+ renderedHistoryKey.current = getHistoryKey(history.state);
5024
5801
  }, []);
5025
5802
  useLayoutEffect(() => {
5026
5803
  const instruction = pendingScrollRef.current;
@@ -5050,11 +5827,11 @@ function RouterProvider({
5050
5827
  window.scrollTo({ behavior: "instant", top: 0 });
5051
5828
  }
5052
5829
  }, [currentHref, state]);
5053
- useEffect(() => {
5830
+ useEffect2(() => {
5054
5831
  window.addEventListener("popstate", handlePopState);
5055
5832
  return () => window.removeEventListener("popstate", handlePopState);
5056
5833
  }, [handlePopState]);
5057
- useEffect(() => {
5834
+ useEffect2(() => {
5058
5835
  if (typeof window === "undefined") {
5059
5836
  return;
5060
5837
  }
@@ -5079,18 +5856,21 @@ function RouterProvider({
5079
5856
  return;
5080
5857
  }
5081
5858
  e.preventDefault();
5082
- navigate(logicalHref, { resetScroll: !logicalHref.includes("#") });
5859
+ navigate(logicalHref, undefined);
5083
5860
  };
5084
5861
  document.addEventListener("click", handler);
5085
5862
  return () => document.removeEventListener("click", handler);
5086
5863
  }, [navigate, basePath, routes]);
5087
- useEffect(() => {
5864
+ useEffect2(() => {
5088
5865
  if (typeof window === "undefined") {
5089
5866
  return;
5090
5867
  }
5091
5868
  const originalFetch = window.fetch;
5092
5869
  const wrapped = async (...args) => {
5093
5870
  const response = await originalFetch.apply(window, args);
5871
+ if (args[1] && SYNC_REQUEST in args[1]) {
5872
+ return response;
5873
+ }
5094
5874
  if (!isSameOriginFetchResult(args[0], response.url, window.location.origin)) {
5095
5875
  return response;
5096
5876
  }
@@ -5114,7 +5894,7 @@ function RouterProvider({
5114
5894
  window.fetch = originalFetch;
5115
5895
  };
5116
5896
  }, [invalidatePrefetch, invalidationRefresh, autoRefresh, basePath]);
5117
- useEffect(() => {
5897
+ useEffect2(() => {
5118
5898
  if (!syncPath || typeof window === "undefined") {
5119
5899
  return;
5120
5900
  }
@@ -5150,7 +5930,25 @@ function RouterProvider({
5150
5930
  }
5151
5931
  return await response.json();
5152
5932
  },
5153
- onInvalidations: applyInvalidations
5933
+ onInvalidations: applyInvalidations,
5934
+ onReset: () => queries.invalidateAll(),
5935
+ onQueries: (identities) => {
5936
+ queries.invalidate(identities);
5937
+ const tags = new Set(identities.map(queryTag));
5938
+ const affected = (snapshot) => snapshot.querySeeds?.some((seed) => tags.has(queryTag(seed.identity)));
5939
+ for (const [href, entry] of prefetchCache.current) {
5940
+ entry.promise.then((snapshot) => {
5941
+ if (snapshot && affected(snapshot) && prefetchCache.current.get(href) === entry) {
5942
+ prefetchCache.current.delete(href);
5943
+ }
5944
+ }).catch(() => {
5945
+ return;
5946
+ });
5947
+ }
5948
+ if (autoRefresh && affected(currentState.current)) {
5949
+ invalidationRefresh.run();
5950
+ }
5951
+ }
5154
5952
  });
5155
5953
  const recover = () => {
5156
5954
  if (disposed) {
@@ -5184,12 +5982,21 @@ function RouterProvider({
5184
5982
  disposed = true;
5185
5983
  unsubscribe?.();
5186
5984
  };
5187
- }, [syncPath, basePath, invalidatePrefetch, invalidationRefresh, autoRefresh]);
5985
+ }, [syncPath, basePath, invalidatePrefetch, invalidationRefresh, autoRefresh, queries]);
5986
+ const queryData = useMemo2(() => projectDeferredQueryData(state.data, state.querySeeds ?? [], (seed) => {
5987
+ if (seed.local && typeof window !== "undefined") {
5988
+ const original = new URL(seed.url);
5989
+ return queries.snapshot(new URL(original.pathname + original.search, window.location.origin).href).data;
5990
+ }
5991
+ return queries.snapshot(seed.url).data;
5992
+ }, resolvedQueries.current), [queries, state.data, state.querySeeds, queryRevision, deferredRevision]);
5993
+ const renderedData = optimisticRuntime.project(queryData, currentHref);
5188
5994
  let pageElement;
5189
5995
  if (state.notFound || !state.match) {
5190
- pageElement = buildNotFoundPageElement(state.notFoundBoundaries ?? state.match?.segmentBoundaries ?? rootBoundaries, state.notFound ?? {});
5996
+ const notFoundElement = buildNotFoundPageElement(state.notFoundBoundaries ?? state.match?.segmentBoundaries ?? rootBoundaries, state.notFound ?? {});
5997
+ pageElement = root?.layout ? createElement6(root.layout, renderedData, notFoundElement) : notFoundElement;
5191
5998
  } else {
5192
- pageElement = buildPageElement(state.match, root, state.data, {
5999
+ pageElement = buildPageElement(state.match, root, renderedData, {
5193
6000
  onReset: () => {
5194
6001
  refresh(undefined).catch((err) => {
5195
6002
  _log.error({ action: "boundary_reset_failed", error: String(err) });
@@ -5203,6 +6010,7 @@ function RouterProvider({
5203
6010
  children: buildRouterTree({
5204
6011
  basePath,
5205
6012
  currentHref,
6013
+ currentPattern: state.match?.pattern,
5206
6014
  defaultPreload,
5207
6015
  defaultPreloadDelay,
5208
6016
  defaultPreloadStaleTime,
@@ -5225,14 +6033,20 @@ function RouterProvider({
5225
6033
  })
5226
6034
  }, undefined, false, undefined, this);
5227
6035
  if (initialDocumentState === null) {
5228
- return routerTree;
6036
+ return /* @__PURE__ */ jsxDEV5(QueryStoreContext.Provider, {
6037
+ value: queries,
6038
+ children: routerTree
6039
+ }, undefined, false, undefined, this);
5229
6040
  }
5230
6041
  return /* @__PURE__ */ jsxDEV5(DocumentProvider, {
5231
6042
  value: {
5232
6043
  ...initialDocumentState,
5233
6044
  head: state.head
5234
6045
  },
5235
- children: routerTree
6046
+ children: /* @__PURE__ */ jsxDEV5(QueryStoreContext.Provider, {
6047
+ value: queries,
6048
+ children: routerTree
6049
+ }, undefined, false, undefined, this)
5236
6050
  }, undefined, false, undefined, this);
5237
6051
  }
5238
6052
  // src/client/link.tsx
@@ -5284,7 +6098,7 @@ function LinkInteractive({
5284
6098
  href: _href,
5285
6099
  ...anchorProps
5286
6100
  }) {
5287
- const router2 = useRouter();
6101
+ const router2 = useRouterContext();
5288
6102
  const anchorRef = useRef2(null);
5289
6103
  const intentTimerRef = useRef2(null);
5290
6104
  const { logicalHref, href, isActive, resolvedChildren, extraProps } = computeLinkView({ activeProps, children, hash, inactiveProps, params, search, to }, router2);
@@ -5292,15 +6106,15 @@ function LinkInteractive({
5292
6106
  const effectiveDelay = preloadDelay ?? router2.defaultPreloadDelay;
5293
6107
  const effectiveStaleTime = preloadStaleTime ?? router2.defaultPreloadStaleTime;
5294
6108
  const { prefetch } = router2;
5295
- const triggerPrefetch = useCallback3(() => {
6109
+ const triggerPrefetch = useCallback4(() => {
5296
6110
  prefetch(logicalHref, { staleTime: effectiveStaleTime });
5297
6111
  }, [prefetch, logicalHref, effectiveStaleTime]);
5298
- useEffect2(() => {
6112
+ useEffect3(() => {
5299
6113
  if (effectivePreload === "render") {
5300
6114
  triggerPrefetch();
5301
6115
  }
5302
6116
  }, [effectivePreload, triggerPrefetch]);
5303
- useEffect2(() => {
6117
+ useEffect3(() => {
5304
6118
  if (effectivePreload !== "viewport" || !anchorRef.current) {
5305
6119
  return;
5306
6120
  }
@@ -5313,7 +6127,7 @@ function LinkInteractive({
5313
6127
  observer.observe(anchorRef.current);
5314
6128
  return () => observer.disconnect();
5315
6129
  }, [effectivePreload, triggerPrefetch]);
5316
- useEffect2(() => () => {
6130
+ useEffect3(() => () => {
5317
6131
  if (intentTimerRef.current !== null) {
5318
6132
  clearTimeout(intentTimerRef.current);
5319
6133
  intentTimerRef.current = null;
@@ -5367,7 +6181,7 @@ function LinkInteractive({
5367
6181
  triggerPrefetch();
5368
6182
  }
5369
6183
  };
5370
- return createElement5("a", {
6184
+ return createElement7("a", {
5371
6185
  "data-furin-link": true,
5372
6186
  href,
5373
6187
  onClick: handleClick,
@@ -5418,7 +6232,7 @@ function renderLinkElement(props, router2) {
5418
6232
  href: _href,
5419
6233
  ...anchorProps
5420
6234
  } = props;
5421
- return createElement5("a", {
6235
+ return createElement7("a", {
5422
6236
  "data-furin-link": true,
5423
6237
  href,
5424
6238
  ...isActive ? { "data-status": "active" } : {},
@@ -5429,11 +6243,11 @@ function renderLinkElement(props, router2) {
5429
6243
  }
5430
6244
  function Link(props) {
5431
6245
  if (typeof window === "undefined") {
5432
- return createElement5(RouterContext.Consumer, {
6246
+ return createElement7(RouterContext.Consumer, {
5433
6247
  children: (routerCtx) => renderLinkElement(props, routerCtx ?? SSR_FALLBACK_ROUTER)
5434
6248
  });
5435
6249
  }
5436
- return createElement5(LinkInteractive, props);
6250
+ return createElement7(LinkInteractive, props);
5437
6251
  }
5438
6252
  export {
5439
6253
  CLIENT_FALLBACK_ROUTER,