@teyik0/furin 0.8.0-alpha.0 → 0.9.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 (153) hide show
  1. package/README.md +37 -0
  2. package/dist/adapter/bun/app.d.ts +1 -0
  3. package/dist/adapter/bun.d.ts +3 -1
  4. package/dist/adapter/runtime-build.d.ts +8 -5
  5. package/dist/adapter/vercel.js +8 -8
  6. package/dist/build/client.d.ts +2 -2
  7. package/dist/build/discover-mounts-process.d.ts +1 -1
  8. package/dist/build/discover-pages-process.d.ts +1 -0
  9. package/dist/build/discover-pages.d.ts +11 -0
  10. package/dist/build/discovery-module.d.ts +3 -0
  11. package/dist/build/discovery-plugins.d.ts +34 -0
  12. package/dist/build/elysia-aot.d.ts +1 -1
  13. package/dist/build/entry-template.ts +6 -1
  14. package/dist/build/hydrate.d.ts +3 -2
  15. package/dist/build/index.js +7688 -8458
  16. package/dist/build/preload-manifest.d.ts +2 -2
  17. package/dist/build/route-metadata.d.ts +31 -0
  18. package/dist/build/route-types.d.ts +1 -1
  19. package/dist/build/shared.d.ts +2 -2
  20. package/dist/build/types.d.ts +11 -0
  21. package/dist/cli/dev-worker.d.ts +1 -0
  22. package/dist/cli/dev-worker.ts +129 -0
  23. package/dist/cli/dev.d.ts +1 -0
  24. package/dist/cli/index.js +7814 -8473
  25. package/dist/client/browser-events-runtime.d.ts +2 -2
  26. package/dist/client/browser-events.d.ts +2 -0
  27. package/dist/client/chunks/{client-brdfd773.js → client-rjhxgt64.js} +187 -4
  28. package/dist/client/dev-error-overlay.ts +18 -1
  29. package/dist/client/link.js +127 -170
  30. package/dist/client/query-store.d.ts +5 -0
  31. package/dist/client/router/navigation-controller.d.ts +2 -0
  32. package/dist/client/router/use-fetch-interception.d.ts +1 -1
  33. package/dist/client/router/use-sync-stream.d.ts +1 -1
  34. package/dist/client/{router/sync-catch-up.d.ts → sync-catch-up.d.ts} +5 -3
  35. package/dist/client/sync-client.d.ts +74 -0
  36. package/dist/client.d.ts +1 -0
  37. package/dist/client.js +533 -145
  38. package/dist/config.d.ts +6 -1
  39. package/dist/config.js +3 -1
  40. package/dist/define-route.d.ts +3 -3
  41. package/dist/furin.d.ts +2 -1
  42. package/dist/furin.js +1168 -393
  43. package/dist/plugin/index.js +5 -5
  44. package/dist/plugin/route-registry.d.ts +22 -2
  45. package/dist/rsc/build/index.d.ts +4 -3
  46. package/dist/server/dev/server-only-module.d.ts +5 -0
  47. package/dist/server/internal.js +241 -129
  48. package/dist/server/logging/ingest-plugin.d.ts +1 -2
  49. package/dist/server/production-server.js +36 -33
  50. package/dist/server/render/index.d.ts +0 -1
  51. package/dist/server/render/index.ts +0 -1
  52. package/dist/server/render/shell.d.ts +1 -13
  53. package/dist/server/render/shell.ts +1 -90
  54. package/dist/server/server-entry.d.ts +5 -0
  55. package/dist/server/server-entry.js +36 -0
  56. package/dist/server/static-export.js +241 -129
  57. package/dist/server/sync/adapter.d.ts +4 -3
  58. package/dist/server/sync/config.d.ts +7 -0
  59. package/dist/server/sync/connection.d.ts +13 -0
  60. package/dist/server/sync/drizzle/index.js +5 -4
  61. package/dist/server/sync/index.d.ts +3 -0
  62. package/dist/server/sync/index.js +1361 -243
  63. package/dist/server/sync/invalidate-sync.d.ts +6 -2
  64. package/dist/server/sync/local-client.d.ts +9 -0
  65. package/dist/server/sync/postgres/index.d.ts +1 -1
  66. package/dist/server/sync/postgres/index.js +2 -2
  67. package/dist/server/sync/prisma/index.js +2 -2
  68. package/dist/server/sync/redis/index.d.ts +1 -1
  69. package/dist/server/sync/redis/index.js +4 -3
  70. package/dist/server/sync/redis/scripts.d.ts +1 -1
  71. package/dist/server/sync/runtime.d.ts +3 -0
  72. package/dist/server/sync/sqlite/index.d.ts +1 -1
  73. package/dist/server/sync/sqlite/index.js +3 -2
  74. package/dist/shared/browser-events.d.ts +4 -0
  75. package/dist/shared/not-found.d.ts +1 -1
  76. package/dist/sync-client.d.ts +3 -0
  77. package/dist/sync-client.js +1600 -0
  78. package/package.json +14 -9
  79. package/src/adapter/README.md +7 -0
  80. package/src/adapter/build.ts +34 -33
  81. package/src/adapter/bun/app.ts +5 -0
  82. package/src/adapter/bun/server.ts +2 -2
  83. package/src/adapter/bun.ts +18 -2
  84. package/src/adapter/furin-app.d.ts +1 -0
  85. package/src/adapter/package.ts +1 -0
  86. package/src/adapter/runtime-build.ts +18 -12
  87. package/src/adapter/static.ts +17 -13
  88. package/src/build/client.ts +7 -5
  89. package/src/build/discover-mounts-process.ts +5 -1
  90. package/src/build/discover-pages-process.ts +151 -0
  91. package/src/build/discover-pages.ts +69 -0
  92. package/src/build/discovery-module.ts +70 -0
  93. package/src/build/discovery-plugins.ts +101 -0
  94. package/src/build/elysia-aot-worker.ts +9 -8
  95. package/src/build/elysia-aot.ts +110 -75
  96. package/src/build/entry-template.ts +6 -1
  97. package/src/build/hydrate.ts +11 -8
  98. package/src/build/index.ts +6 -50
  99. package/src/build/preload-manifest.ts +3 -3
  100. package/src/build/route-metadata.ts +90 -0
  101. package/src/build/route-types.ts +1 -1
  102. package/src/build/shared.ts +6 -8
  103. package/src/build/types.ts +9 -0
  104. package/src/cli/config.ts +4 -0
  105. package/src/cli/dev-worker.ts +129 -0
  106. package/src/cli/dev.ts +106 -0
  107. package/src/cli/index.ts +24 -1
  108. package/src/client/browser-events-runtime.ts +97 -23
  109. package/src/client/browser-events.ts +8 -0
  110. package/src/client/dev-error-overlay.ts +18 -1
  111. package/src/client/link.tsx +21 -22
  112. package/src/client/query-store.ts +54 -3
  113. package/src/client/router/context.ts +8 -7
  114. package/src/client/router/navigation-controller.ts +45 -12
  115. package/src/client/router/provider.tsx +11 -2
  116. package/src/client/router/use-fetch-interception.ts +1 -1
  117. package/src/client/router/use-sync-stream.ts +96 -44
  118. package/src/client/{router/sync-catch-up.ts → sync-catch-up.ts} +28 -12
  119. package/src/client/sync-client.ts +528 -0
  120. package/src/client/sync.ts +11 -4
  121. package/src/client.ts +10 -0
  122. package/src/config.ts +17 -10
  123. package/src/furin.ts +5 -0
  124. package/src/plugin/route-registry.ts +53 -7
  125. package/src/rsc/build/index.ts +6 -3
  126. package/src/server/browser-events/plugin.ts +79 -25
  127. package/src/server/dev/rewrite-module-specifiers.ts +2 -1
  128. package/src/server/dev/server-only-module.ts +23 -0
  129. package/src/server/dev/symbolicate.ts +4 -3
  130. package/src/server/dev-page-imports.ts +3 -1
  131. package/src/server/dev-page-plugin.ts +18 -1
  132. package/src/server/logging/ingest-plugin.ts +3 -9
  133. package/src/server/render/index.ts +0 -1
  134. package/src/server/render/shell.ts +1 -90
  135. package/src/server/server-entry.ts +39 -0
  136. package/src/server/sync/adapter.ts +7 -3
  137. package/src/server/sync/config.ts +12 -6
  138. package/src/server/sync/connection.ts +71 -0
  139. package/src/server/sync/index.ts +3 -0
  140. package/src/server/sync/invalidate-sync.ts +30 -5
  141. package/src/server/sync/local-client.ts +84 -0
  142. package/src/server/sync/plugin.ts +27 -20
  143. package/src/server/sync/postgres/index.ts +9 -2
  144. package/src/server/sync/redis/index.ts +5 -1
  145. package/src/server/sync/redis/scripts.ts +1 -1
  146. package/src/server/sync/runtime.ts +56 -18
  147. package/src/server/sync/sqlite/index.ts +6 -2
  148. package/src/server/sync/stream.ts +17 -5
  149. package/src/shared/browser-events.ts +1 -1
  150. package/src/shared/not-found.ts +1 -1
  151. package/src/sync-client.ts +14 -0
  152. package/dist/server/logger.d.ts +0 -10
  153. package/src/server/logger.ts +0 -34
@@ -5,14 +5,16 @@ import {
5
5
  mergeQuerySeeds,
6
6
  queryTag,
7
7
  queryTags,
8
- queryFromTag,
9
8
  QueryStore,
10
9
  SYNC_REQUEST,
11
10
  registerOptimisticRuntime,
12
11
  createOptimisticRuntime,
13
12
  QueryStoreContext,
14
- withRouteSnapshot
15
- } from "./chunks/client-brdfd773.js";
13
+ withRouteSnapshot,
14
+ isAbortError,
15
+ createInvalidationRefresh,
16
+ createSyncCatchUp
17
+ } from "./chunks/client-rjhxgt64.js";
16
18
  import {
17
19
  restoreRscSource2
18
20
  } from "./chunks/client-k88668k7.js";
@@ -23,7 +25,6 @@ import {
23
25
  import {
24
26
  physicalPath,
25
27
  isWithinPrefix,
26
- encodeInvalidationEntry,
27
28
  findSearchDefaultsForRouteTarget,
28
29
  TRAILING_SLASHES_RE,
29
30
  navigationHrefPolicy,
@@ -91,8 +92,9 @@ function useRouterStore() {
91
92
  return { getCurrentHref: () => value.currentHref, router: value, subscribe: subscribeNever };
92
93
  }
93
94
  function useTypedNavigation(context) {
95
+ const { navigate: navigateHref, prefetch: prefetchHref, searchRoutes } = context;
94
96
  const navigate = useCallback((next, opts) => {
95
- const href = typeof next === "string" ? next : resolveRouteTarget(next, context.searchRoutes);
97
+ const href = typeof next === "string" ? next : resolveRouteTarget(next, searchRoutes);
96
98
  const policy = navigationHrefPolicy(href, typeof window === "undefined" ? undefined : window.location.origin);
97
99
  if (policy === "blocked") {
98
100
  return Promise.reject(new Error("[furin] Unsafe navigation URL."));
@@ -102,19 +104,19 @@ function useTypedNavigation(context) {
102
104
  return Promise.resolve();
103
105
  }
104
106
  if (typeof next === "string") {
105
- return context.navigate(href, opts);
107
+ return navigateHref(href, opts);
106
108
  }
107
109
  const options = next.replace === undefined && next.resetScroll === undefined ? undefined : { replace: next.replace, resetScroll: next.resetScroll };
108
- return context.navigate(href, options);
109
- }, [context.navigate, context.searchRoutes]);
110
+ return navigateHref(href, options);
111
+ }, [navigateHref, searchRoutes]);
110
112
  const prefetch = useCallback((next, opts) => {
111
- const href = typeof next === "string" ? next : resolveRouteTarget(next, context.searchRoutes);
113
+ const href = typeof next === "string" ? next : resolveRouteTarget(next, searchRoutes);
112
114
  const policy = navigationHrefPolicy(href, typeof window === "undefined" ? undefined : window.location.origin);
113
115
  if (policy !== "internal") {
114
116
  return;
115
117
  }
116
- context.prefetch(href, typeof next === "string" ? opts : { staleTime: next.staleTime });
117
- }, [context.prefetch, context.searchRoutes]);
118
+ prefetchHref(href, typeof next === "string" ? opts : { staleTime: next.staleTime });
119
+ }, [prefetchHref, searchRoutes]);
118
120
  return { navigate, prefetch };
119
121
  }
120
122
  function useRouter() {
@@ -715,6 +717,16 @@ function collectRouteChainFromRoute(route) {
715
717
  return chain;
716
718
  }
717
719
 
720
+ // src/client/browser-events.ts
721
+ var BROWSER_EVENT_RUNTIME_KEY = Symbol.for("furin.browser-events.runtime");
722
+ function setBrowserSyncAuthentication(authorized) {
723
+ globalThis[BROWSER_EVENT_RUNTIME_KEY]?.setSyncAuthentication?.(authorized);
724
+ }
725
+ function subscribeBrowserEvent(channel, listener) {
726
+ const runtime = globalThis[BROWSER_EVENT_RUNTIME_KEY];
727
+ return runtime?.subscribe(channel, listener);
728
+ }
729
+
718
730
  // src/client/route-element.tsx
719
731
  import { createElement } from "react";
720
732
 
@@ -894,6 +906,7 @@ class NavigationController {
894
906
  #version = 0;
895
907
  #pendingAbort = null;
896
908
  #committedAbort = null;
909
+ #contextAbort = new AbortController;
897
910
  #pendingUserNavigation = null;
898
911
  #renderedHistoryKey;
899
912
  #pendingScroll = null;
@@ -942,7 +955,12 @@ class NavigationController {
942
955
  const generation = this.#generation.current;
943
956
  const entry = {
944
957
  createdAt: Date.now(),
945
- promise: this.#config.fetchPage({ currentMatch: this.#currentMatch, hmrRefresh: false, href, signal: undefined }).then((result) => ({ generation, result, revision: undefined })),
958
+ promise: this.#config.fetchPage({
959
+ currentMatch: this.#currentMatch,
960
+ hmrRefresh: false,
961
+ href,
962
+ signal: this.#contextAbort.signal
963
+ }).then((result) => ({ generation, result, revision: undefined })),
946
964
  staleTime: staleTime ?? this.#config.defaultStaleTime
947
965
  };
948
966
  this.#store(href, entry);
@@ -964,6 +982,23 @@ class NavigationController {
964
982
  }
965
983
  }
966
984
  };
985
+ invalidateContext() {
986
+ this.#version += 1;
987
+ const pendingAbort = this.#pendingAbort;
988
+ const committedAbort = this.#committedAbort;
989
+ const contextAbort = this.#contextAbort;
990
+ const pendingNavigation = this.#pendingUserNavigation;
991
+ this.#pendingAbort = null;
992
+ this.#committedAbort = null;
993
+ this.#contextAbort = new AbortController;
994
+ this.#pendingUserNavigation = null;
995
+ this.invalidatePath("/", "layout");
996
+ this.#setNavigating(false);
997
+ pendingAbort?.abort();
998
+ committedAbort?.abort();
999
+ contextAbort.abort();
1000
+ pendingNavigation?.resolve();
1001
+ }
967
1002
  invalidateQueries(affected) {
968
1003
  this.#generation.bump((_href, state) => affected(state));
969
1004
  for (const [href, entry] of this.#cache) {
@@ -981,7 +1016,7 @@ class NavigationController {
981
1016
  }
982
1017
  async waitForUserNavigation() {
983
1018
  while (this.#pendingUserNavigation) {
984
- await this.#pendingUserNavigation;
1019
+ await this.#pendingUserNavigation.promise;
985
1020
  }
986
1021
  }
987
1022
  adoptHistoryEntry() {
@@ -1019,18 +1054,14 @@ class NavigationController {
1019
1054
  }
1020
1055
  }
1021
1056
  #beginUserNavigation() {
1022
- let resolve = () => {
1023
- return;
1024
- };
1025
- const promise = new Promise((settle) => {
1026
- resolve = settle;
1027
- });
1028
- this.#pendingUserNavigation = promise;
1057
+ this.#pendingUserNavigation?.resolve();
1058
+ const navigation = Promise.withResolvers();
1059
+ this.#pendingUserNavigation = navigation;
1029
1060
  return () => {
1030
- if (this.#pendingUserNavigation === promise) {
1061
+ if (this.#pendingUserNavigation === navigation) {
1031
1062
  this.#pendingUserNavigation = null;
1032
1063
  }
1033
- resolve();
1064
+ navigation.resolve();
1034
1065
  };
1035
1066
  }
1036
1067
  #startAbort() {
@@ -1056,11 +1087,21 @@ class NavigationController {
1056
1087
  this.#version += 1;
1057
1088
  const version = this.#version;
1058
1089
  const abort = this.#startAbort();
1090
+ const cancelled = Promise.withResolvers();
1091
+ const onAbort = () => cancelled.resolve(false);
1092
+ abort.signal.addEventListener("abort", onAbort, { once: true });
1059
1093
  let committed = false;
1060
1094
  this.#setNavigating(true);
1061
1095
  try {
1062
- committed = await this.#load(href, kind, version, abort.signal);
1096
+ if (abort.signal.aborted) {
1097
+ return;
1098
+ }
1099
+ committed = await Promise.race([
1100
+ this.#load(href, kind, version, abort.signal),
1101
+ cancelled.promise
1102
+ ]);
1063
1103
  } finally {
1104
+ abort.signal.removeEventListener("abort", onAbort);
1064
1105
  this.#settleAbort(abort, committed);
1065
1106
  finishUserNavigation?.();
1066
1107
  if (this.#version === version) {
@@ -2734,11 +2775,6 @@ async function readDeferredLines(readLine, resolvers) {
2734
2775
  }
2735
2776
  }
2736
2777
 
2737
- // src/client/router/abort.ts
2738
- function isAbortError(error) {
2739
- return error !== null && typeof error === "object" && "name" in error && error.name === "AbortError";
2740
- }
2741
-
2742
2778
  // src/shared/navigation-data.ts
2743
2779
  var NAVIGATION_DATA_TOKEN = "_furin=data";
2744
2780
  function navigationDataHref(href) {
@@ -2949,126 +2985,6 @@ async function fetchPageState(context, rawLogicalHref, signal, hmrRefresh) {
2949
2985
  }
2950
2986
  }
2951
2987
 
2952
- // src/client/router/sync-catch-up.ts
2953
- var LAYOUT_SUFFIX_RE = /:layout$/;
2954
- var RESET_REFRESH_INTERVAL_MS = 1000;
2955
- function changeInvalidations(change) {
2956
- const paths = [];
2957
- const queries = [...change.queries ?? []];
2958
- for (const entry of change.invalidations) {
2959
- if (typeof entry === "string") {
2960
- const trimmed = entry.trim();
2961
- const type = trimmed.endsWith(":layout") ? "layout" : "page";
2962
- const path = trimmed.replace(LAYOUT_SUFFIX_RE, "");
2963
- paths.push(encodeInvalidationEntry(path, type));
2964
- } else if (entry.kind === "path") {
2965
- paths.push(encodeInvalidationEntry(entry.path, entry.type));
2966
- } else {
2967
- for (const tag of entry.tags) {
2968
- const identity = queryFromTag(tag);
2969
- if (identity) {
2970
- queries.push(identity);
2971
- } else {
2972
- paths.push("/:layout");
2973
- }
2974
- }
2975
- }
2976
- }
2977
- return { paths, queries };
2978
- }
2979
- function createInvalidationRefresh(options) {
2980
- let running;
2981
- let requested = false;
2982
- const refreshUntilCurrent = async () => {
2983
- do {
2984
- requested = false;
2985
- try {
2986
- await options.refresh();
2987
- } catch (error) {
2988
- if (!isAbortError(error)) {
2989
- throw error;
2990
- }
2991
- }
2992
- } while (requested);
2993
- };
2994
- return {
2995
- run() {
2996
- requested = true;
2997
- if (!running) {
2998
- running = refreshUntilCurrent().catch((error) => {
2999
- if (!isAbortError(error)) {
3000
- options.onError(error);
3001
- }
3002
- }).finally(() => {
3003
- running = undefined;
3004
- });
3005
- }
3006
- return running;
3007
- }
3008
- };
3009
- }
3010
- function createSyncCatchUp(options) {
3011
- let currentCursor;
3012
- let running;
3013
- let requested = false;
3014
- let lastReset = Number.NEGATIVE_INFINITY;
3015
- let pendingReset;
3016
- const refreshAfterReset = () => {
3017
- pendingReset = undefined;
3018
- lastReset = Date.now();
3019
- options.onReset?.();
3020
- options.onInvalidations(["/:layout"]);
3021
- };
3022
- const scheduleResetRefresh = () => {
3023
- if (pendingReset) {
3024
- return;
3025
- }
3026
- const wait = lastReset + RESET_REFRESH_INTERVAL_MS - Date.now();
3027
- if (wait <= 0) {
3028
- refreshAfterReset();
3029
- } else {
3030
- pendingReset = setTimeout(refreshAfterReset, wait);
3031
- }
3032
- };
3033
- const readUntilCurrent = async () => {
3034
- do {
3035
- requested = false;
3036
- let page;
3037
- do {
3038
- page = await options.fetchPage(currentCursor ?? "0");
3039
- if (page.reset) {
3040
- currentCursor = page.cursor;
3041
- scheduleResetRefresh();
3042
- break;
3043
- }
3044
- for (const change of page.changes) {
3045
- const { paths, queries } = changeInvalidations(change);
3046
- options.onInvalidations(paths);
3047
- if (queries.length > 0) {
3048
- options.onQueries?.(queries);
3049
- }
3050
- }
3051
- currentCursor = page.cursor;
3052
- } while (page.hasMore);
3053
- } while (requested);
3054
- };
3055
- return {
3056
- catchUp() {
3057
- requested = true;
3058
- if (!running) {
3059
- running = readUntilCurrent().finally(() => {
3060
- running = undefined;
3061
- });
3062
- }
3063
- return running;
3064
- },
3065
- cursor: () => currentCursor,
3066
- seed(cursor) {
3067
- currentCursor ??= cursor;
3068
- }
3069
- };
3070
- }
3071
-
3072
2988
  // src/client/router/use-fetch-interception.ts
3073
2989
  import { useEffect } from "react";
3074
2990
 
@@ -3248,15 +3164,6 @@ function useHmrRefresh(controller) {
3248
3164
  // src/client/router/use-sync-stream.ts
3249
3165
  import { log as log3 } from "evlog";
3250
3166
  import { useEffect as useEffect4 } from "react";
3251
-
3252
- // src/client/browser-events.ts
3253
- var BROWSER_EVENT_RUNTIME_KEY = Symbol.for("furin.browser-events.runtime");
3254
- function subscribeBrowserEvent(channel, listener) {
3255
- const runtime = globalThis[BROWSER_EVENT_RUNTIME_KEY];
3256
- return runtime?.subscribe(channel, listener);
3257
- }
3258
-
3259
- // src/client/router/use-sync-stream.ts
3260
3167
  function useSyncStream(options) {
3261
3168
  const { autoRefresh, basePath, controller, invalidationRefresh, queries, syncPath } = options;
3262
3169
  useEffect4(() => {
@@ -3266,6 +3173,24 @@ function useSyncStream(options) {
3266
3173
  const changesUrl = syncPath.startsWith("/") ? `${basePath}${syncPath}` : `${basePath}/${syncPath}`;
3267
3174
  let unsubscribe;
3268
3175
  let disposed = false;
3176
+ let requestController = new AbortController;
3177
+ let contextChanged = false;
3178
+ let session;
3179
+ const clearContext = () => {
3180
+ contextChanged = true;
3181
+ queries.clear();
3182
+ controller.invalidateContext();
3183
+ };
3184
+ const observeSession = (response) => {
3185
+ const identity = response.headers.get("x-furin-sync-session");
3186
+ if (identity === null) {
3187
+ return;
3188
+ }
3189
+ if (session !== undefined && identity !== session) {
3190
+ clearContext();
3191
+ }
3192
+ session = identity;
3193
+ };
3269
3194
  const applyInvalidations = (entries) => {
3270
3195
  if (disposed) {
3271
3196
  return;
@@ -3283,17 +3208,26 @@ function useSyncStream(options) {
3283
3208
  }
3284
3209
  }
3285
3210
  };
3286
- const catchUp = createSyncCatchUp({
3211
+ const createRecovery = () => createSyncCatchUp({
3287
3212
  fetchPage: async (after) => {
3288
3213
  const url = new URL(`${changesUrl}/changes`, window.location.origin);
3289
3214
  if (after !== undefined) {
3290
3215
  url.searchParams.set("after", after);
3291
3216
  }
3292
- const response = await window.fetch(url);
3217
+ const { signal } = requestController;
3218
+ const response = await window.fetch(url, { signal });
3219
+ signal.throwIfAborted();
3220
+ if (response.status === 401 || response.status === 403) {
3221
+ clearContext();
3222
+ setBrowserSyncAuthentication(false);
3223
+ }
3293
3224
  if (!response.ok) {
3294
3225
  throw new Error(`Sync catch-up failed with status ${response.status}`);
3295
3226
  }
3296
- return await response.json();
3227
+ const page = await response.json();
3228
+ signal.throwIfAborted();
3229
+ observeSession(response);
3230
+ return page;
3297
3231
  },
3298
3232
  onInvalidations: applyInvalidations,
3299
3233
  onReset: () => {
@@ -3311,22 +3245,38 @@ function useSyncStream(options) {
3311
3245
  }
3312
3246
  }
3313
3247
  });
3248
+ let catchUp = createRecovery();
3314
3249
  const recover = () => {
3315
3250
  if (disposed) {
3316
3251
  return;
3317
3252
  }
3318
- catchUp.catchUp().catch((error) => {
3253
+ const current = catchUp;
3254
+ current.catchUp().then(() => {
3255
+ if (!disposed && catchUp === current && contextChanged) {
3256
+ contextChanged = false;
3257
+ queries.invalidateAll();
3258
+ applyInvalidations(["/:layout"]);
3259
+ }
3260
+ }).catch((error) => {
3319
3261
  if (!disposed) {
3320
3262
  log3.warn({ action: "sync_catch_up_failed", error: String(error) });
3321
3263
  }
3322
3264
  });
3323
3265
  };
3324
3266
  const onSync = (event) => {
3267
+ if (event.data.context === "changed") {
3268
+ requestController.abort();
3269
+ requestController = new AbortController;
3270
+ catchUp.close();
3271
+ catchUp = createRecovery();
3272
+ clearContext();
3273
+ recover();
3274
+ return;
3275
+ }
3325
3276
  if (typeof event.data.cursor !== "string") {
3326
3277
  log3.warn({ action: "sync_invalid_event", event: "browser-events.sync" });
3327
3278
  return;
3328
3279
  }
3329
- catchUp.seed(event.data.cursor);
3330
3280
  recover();
3331
3281
  };
3332
3282
  const connect = () => {
@@ -3341,6 +3291,8 @@ function useSyncStream(options) {
3341
3291
  connect();
3342
3292
  return () => {
3343
3293
  disposed = true;
3294
+ requestController.abort();
3295
+ catchUp.close();
3344
3296
  unsubscribe?.();
3345
3297
  };
3346
3298
  }, [syncPath, basePath, invalidationRefresh, autoRefresh, queries, controller]);
@@ -3606,7 +3558,10 @@ function RouterProvider({
3606
3558
  invalidatePrefetch,
3607
3559
  navigate,
3608
3560
  prefetch,
3609
- refresh,
3561
+ refresh: (options) => {
3562
+ setBrowserSyncAuthentication(true);
3563
+ return refresh(options);
3564
+ },
3610
3565
  searchRoutes: routes
3611
3566
  }), [
3612
3567
  basePath,
@@ -3665,6 +3620,7 @@ function RouterProvider({
3665
3620
  });
3666
3621
  }
3667
3622
  // src/client/link.tsx
3623
+ import { jsx as jsx5 } from "react/jsx-runtime";
3668
3624
  "use client";
3669
3625
  function resolveLinkHref({ to, params, search, hash }, router2) {
3670
3626
  const resolvedTo = applyLinkParams(to, params);
@@ -3733,12 +3689,12 @@ function LinkInteractive({
3733
3689
  if (target !== null) {
3734
3690
  prefetch(target, { staleTime: effectiveStaleTime });
3735
3691
  }
3736
- }, [prefetch, logicalHref, effectiveStaleTime, router2.basePath]);
3692
+ }, [prefetch, effectiveStaleTime, router2.basePath]);
3737
3693
  useEffect6(() => {
3738
3694
  if (effectivePreload === "render") {
3739
3695
  triggerPrefetch();
3740
3696
  }
3741
- }, [effectivePreload, triggerPrefetch]);
3697
+ }, [effectivePreload, triggerPrefetch, logicalHref]);
3742
3698
  useEffect6(() => {
3743
3699
  if (effectivePreload !== "viewport" || !anchorRef.current) {
3744
3700
  return;
@@ -3751,7 +3707,7 @@ function LinkInteractive({
3751
3707
  }, { rootMargin: "200px" });
3752
3708
  observer.observe(anchorRef.current);
3753
3709
  return () => observer.disconnect();
3754
- }, [effectivePreload, triggerPrefetch]);
3710
+ }, [effectivePreload, triggerPrefetch, logicalHref]);
3755
3711
  useEffect6(() => () => {
3756
3712
  if (intentTimerRef.current !== null) {
3757
3713
  clearTimeout(intentTimerRef.current);
@@ -3780,7 +3736,7 @@ function LinkInteractive({
3780
3736
  }
3781
3737
  e.preventDefault();
3782
3738
  if (typeof window !== "undefined" && router2.navigate === CLIENT_FALLBACK_ROUTER.navigate) {
3783
- window.location.href = href;
3739
+ window.location.assign(href);
3784
3740
  return;
3785
3741
  }
3786
3742
  router2.navigate(target, { replace, resetScroll: resetScroll ?? true });
@@ -3804,7 +3760,7 @@ function LinkInteractive({
3804
3760
  triggerPrefetch();
3805
3761
  }
3806
3762
  };
3807
- return createElement2("a", {
3763
+ return /* @__PURE__ */ jsx5("a", {
3808
3764
  "data-furin-link": true,
3809
3765
  href,
3810
3766
  onClick: handleClick,
@@ -3815,8 +3771,9 @@ function LinkInteractive({
3815
3771
  ...isActive ? { "data-status": "active" } : {},
3816
3772
  ...anchorProps,
3817
3773
  ...extraProps,
3818
- ...disabled ? { "aria-disabled": true } : {}
3819
- }, resolvedChildren);
3774
+ ...disabled ? { "aria-disabled": true } : {},
3775
+ children: resolvedChildren
3776
+ });
3820
3777
  }
3821
3778
  var SSR_FALLBACK_ROUTER = {
3822
3779
  basePath: "",
@@ -8,6 +8,7 @@ export interface ReadResult {
8
8
  response?: Response;
9
9
  }
10
10
  export interface ReadReference {
11
+ application?: object;
11
12
  client: QueryStore;
12
13
  load: (options: unknown) => Promise<ReadResult>;
13
14
  url: string;
@@ -75,6 +76,10 @@ export declare class QueryStore {
75
76
  observe(url: string, result: ReadResult, epoch: number, version?: number): void;
76
77
  private setSession;
77
78
  generation(): number;
79
+ /** Fence in-flight responses without removing active observers or their loaders. */
80
+ clear(preserveData?: boolean): void;
81
+ dispose(): void;
82
+ setError(url: string, error: unknown): void;
78
83
  version(url: string): number;
79
84
  snapshot(url: string): QuerySnapshot;
80
85
  subscribe(url: string, listener: () => void): () => void;
@@ -63,6 +63,8 @@ export declare class NavigationController {
63
63
  readonly prefetch: (href: string, staleTime: number | undefined) => void;
64
64
  /** Drops cached pages under `path` and marks in-flight ones stale. */
65
65
  readonly invalidatePath: (path: string, type: "page" | "layout") => void;
66
+ /** Access changes must also prevent old navigations and deferred streams from publishing. */
67
+ invalidateContext(): void;
66
68
  /** Drops cached pages whose state reads an invalidated query. */
67
69
  invalidateQueries(affected: (state: RouterState) => boolean): void;
68
70
  /** Republishes the current page so hot-swapped components render. */
@@ -1,4 +1,4 @@
1
- import type { InvalidationRefresh } from "./sync-catch-up.ts";
1
+ import type { InvalidationRefresh } from "../sync-catch-up.ts";
2
2
  /**
3
3
  * Processes `X-Furin-Revalidate` headers on every same-origin `window.fetch`
4
4
  * response: evicts the named pages and refreshes the current one when
@@ -1,6 +1,6 @@
1
1
  import type { QueryStore } from "../query-store.ts";
2
+ import { type InvalidationRefresh } from "../sync-catch-up.ts";
2
3
  import type { NavigationController } from "./navigation-controller.ts";
3
- import { type InvalidationRefresh } from "./sync-catch-up.ts";
4
4
  /**
5
5
  * Listens for sync cursor notifications and recovers the changes over HTTP,
6
6
  * invalidating cached pages and queries and refreshing the current page when
@@ -1,8 +1,9 @@
1
- import type { SyncInvalidation } from "../../server/sync/adapter.ts";
1
+ import type { SyncInvalidation } from "../server/sync/adapter.ts";
2
+ import { type QueryIdentity } from "../shared/sync-query.ts";
2
3
  interface SyncChangePayload {
3
4
  cursor: string;
4
5
  invalidations: readonly (string | SyncInvalidation)[];
5
- queries?: readonly import("../../shared/sync-query.ts").QueryIdentity[];
6
+ queries?: readonly QueryIdentity[];
6
7
  }
7
8
  export interface SyncChangePagePayload {
8
9
  changes: readonly SyncChangePayload[];
@@ -13,11 +14,12 @@ export interface SyncChangePagePayload {
13
14
  interface SyncCatchUpOptions {
14
15
  fetchPage: (after: string | undefined) => Promise<SyncChangePagePayload>;
15
16
  onInvalidations: (invalidations: readonly string[]) => void;
16
- onQueries?: (identities: readonly import("../../shared/sync-query.ts").QueryIdentity[]) => void;
17
+ onQueries?: (identities: readonly QueryIdentity[]) => void;
17
18
  onReset?: () => void;
18
19
  }
19
20
  export interface SyncCatchUp {
20
21
  catchUp: () => Promise<void>;
22
+ close: () => void;
21
23
  cursor: () => string | undefined;
22
24
  seed: (cursor: string) => void;
23
25
  }
@@ -0,0 +1,74 @@
1
+ import { type LiveQuery, type ReadReference, type ReadResult } from "./query-store.ts";
2
+ interface SyncSocketEvents {
3
+ close: {
4
+ code: number;
5
+ };
6
+ error: unknown;
7
+ message: {
8
+ data: unknown;
9
+ };
10
+ }
11
+ /** The common event API implemented by native WebSocket and runtime socket adapters. */
12
+ export interface SyncSocket {
13
+ addEventListener: <Event extends keyof SyncSocketEvents>(type: Event, listener: (event: SyncSocketEvents[Event]) => void) => void;
14
+ close: () => void;
15
+ readonly readyState: number;
16
+ removeEventListener: <Event extends keyof SyncSocketEvents>(type: Event, listener: (event: SyncSocketEvents[Event]) => void) => void;
17
+ }
18
+ export declare class SyncClientError extends Error {
19
+ readonly status: number | undefined;
20
+ static [Symbol.hasInstance](error: unknown): boolean;
21
+ constructor(message: string, status: number | undefined, cause?: unknown);
22
+ }
23
+ export interface SyncConnectionState {
24
+ error: SyncClientError | null;
25
+ /** Why a connection is being restarted; absent when idle or connected. */
26
+ reason?: "network" | "credentials" | "context";
27
+ status: "idle" | "connecting" | "connected" | "reconnecting" | "unauthorized" | "closed";
28
+ }
29
+ export interface SyncClientOptions {
30
+ /** Runtime adapter only: Furin handles envelopes, recovery and reconnection. */
31
+ createWebSocket?: (url: string, headers: Headers) => SyncSocket | Promise<SyncSocket>;
32
+ fetch?: Omit<RequestInit, "headers" | "signal" | "method" | "body">;
33
+ fetcher?: typeof fetch;
34
+ headers?: HeadersInit | (() => HeadersInit | Promise<HeadersInit>);
35
+ /** Relative to the application URL. Defaults to _furin/sync. */
36
+ syncPath?: string;
37
+ /** Absolute Furin application URL, including its mount path. */
38
+ url: string;
39
+ }
40
+ export interface SyncQueryState<Result extends ReadResult> {
41
+ data: NonNullable<Result["data"]> | undefined;
42
+ error: Result["error"] | SyncClientError | null;
43
+ isFetching: boolean;
44
+ }
45
+ export interface SyncClient {
46
+ close: () => void;
47
+ getConnectionState: () => SyncConnectionState;
48
+ /** Reauthenticate and reevaluate reads; clears snapshots and cursor unless preservation is explicit. */
49
+ reconnect: (options?: SyncReconnectOptions) => void;
50
+ subscribe: <Result extends ReadResult>(query: LiveQuery<Result>, listener: (state: SyncQueryState<Result>) => void) => () => void;
51
+ subscribeConnection: (listener: (state: SyncConnectionState) => void) => () => void;
52
+ }
53
+ export interface SyncReconnectOptions {
54
+ /** Only retain snapshots for renewal within the same identity and access scope. */
55
+ preserveCache?: boolean;
56
+ }
57
+ interface SyncTransportSubscription {
58
+ headers: Headers;
59
+ onContextChange: () => void;
60
+ onCursor: () => void;
61
+ onError: (error: unknown) => void;
62
+ signal: AbortSignal;
63
+ }
64
+ /** @internal The local and remote adapters share one cache and recovery lifecycle. */
65
+ export interface SyncTransport {
66
+ accepts: (reference: ReadReference) => boolean;
67
+ fetchChanges: (after: string | undefined, headers: Headers, signal: AbortSignal) => Promise<Response>;
68
+ subscribe: (options: SyncTransportSubscription) => Promise<() => void>;
69
+ }
70
+ /** One server and authentication context, with one socket shared by all subscribers. */
71
+ export declare function createSyncClient(options: SyncClientOptions): SyncClient;
72
+ /** @internal Constructed by the public local and remote factories. */
73
+ export declare function createSyncClientRuntime(options: Pick<SyncClientOptions, "headers" | "fetch">, transport: SyncTransport): SyncClient;
74
+ export {};
package/dist/client.d.ts CHANGED
@@ -7,6 +7,7 @@ export { useQuery } from "./client/query.tsx";
7
7
  export type { LiveQuery } from "./client/query-store.ts";
8
8
  export { getRouteApi } from "./client/route-api.tsx";
9
9
  export { furinSync, type OptimisticCache, type SyncCallOptions } from "./client/sync.ts";
10
+ export { createSyncClient, type SyncClient, SyncClientError, type SyncClientOptions, type SyncConnectionState, type SyncQueryState, type SyncReconnectOptions, type SyncSocket, } from "./client/sync-client.ts";
10
11
  export { Await, useAsyncError, useAsyncValue } from "./shared/await.tsx";
11
12
  export { type DeferredData, defer, isDeferred } from "./shared/defer.ts";
12
13
  export type RenderingMode = "ssr" | "ssg" | "isr";