@teyik0/furin 0.2.0-alpha.5 → 0.3.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 (238) hide show
  1. package/README.md +2 -3
  2. package/dist/adapter/static.d.ts +1 -1
  3. package/dist/build/bun-build.d.ts +3 -0
  4. package/dist/build/entry-template.d.ts +2 -0
  5. package/dist/build/entry-template.ts +3 -0
  6. package/dist/build/hydrate.d.ts +1 -1
  7. package/dist/build/index.js +6944 -5067
  8. package/dist/build/production-instrumentation.d.ts +1 -0
  9. package/dist/build/route-types.d.ts +1 -1
  10. package/dist/build/types.d.ts +1 -0
  11. package/dist/cli/index.js +7874 -5971
  12. package/dist/client/boundaries.d.ts +4 -4
  13. package/dist/client/internal/runtime-types.d.ts +30 -0
  14. package/dist/client/link.d.ts +2 -1
  15. package/dist/client/link.js +712 -338
  16. package/dist/client/router/boundary-tree.d.ts +1 -1
  17. package/dist/client/router/index.d.ts +1 -1
  18. package/dist/client/router/link-utils.d.ts +5 -1
  19. package/dist/client/router/sync-catch-up.d.ts +4 -4
  20. package/dist/client/router/types.d.ts +2 -2
  21. package/dist/client-only.d.ts +1 -0
  22. package/dist/client-only.js +1 -0
  23. package/dist/client.d.ts +108 -111
  24. package/dist/client.js +16 -17
  25. package/dist/config.d.ts +1 -1
  26. package/dist/config.js +2 -2
  27. package/dist/devtools/devtools-element.d.ts +1 -0
  28. package/dist/devtools/protocol.d.ts +119 -0
  29. package/dist/furin.d.ts +7 -6
  30. package/dist/furin.js +6547 -3187
  31. package/dist/isomorphic.d.ts +18 -0
  32. package/dist/plugin/binding-scope.d.ts +2 -0
  33. package/dist/plugin/dead-code-elimination.d.ts +3 -0
  34. package/dist/plugin/index.js +933 -423
  35. package/dist/plugin/transform-client.d.ts +0 -2
  36. package/dist/plugin/transform-isomorphic.d.ts +9 -0
  37. package/dist/rsc/build/environment.d.ts +2 -0
  38. package/dist/rsc/build/index.d.ts +15 -0
  39. package/dist/rsc/client-codec.d.ts +1 -0
  40. package/dist/rsc/codec.d.ts +4 -0
  41. package/dist/rsc/flight-drain.d.ts +11 -0
  42. package/dist/rsc/render-error.d.ts +17 -0
  43. package/dist/rsc/server-codec.d.ts +2 -0
  44. package/dist/rsc/server-codec.js +24 -0
  45. package/dist/rsc/shared.d.ts +30 -0
  46. package/dist/rsc/symbols.d.ts +2 -0
  47. package/dist/rsc/transport-benchmark.d.ts +13 -0
  48. package/dist/rsc/version.d.ts +7 -0
  49. package/dist/rsc-client.d.ts +4 -0
  50. package/dist/rsc-client.js +166 -0
  51. package/dist/rsc-server.d.ts +11 -0
  52. package/dist/rsc.d.ts +11 -0
  53. package/dist/rsc.js +353 -0
  54. package/dist/server/cache/index.d.ts +2 -2
  55. package/dist/server/cache/invalidation.d.ts +2 -3
  56. package/dist/server/cache/isr-ssg.d.ts +5 -1
  57. package/dist/server/cache/isr.d.ts +9 -0
  58. package/dist/server/cache/route-cache.d.ts +10 -8
  59. package/dist/server/cache/store-view.d.ts +7 -7
  60. package/dist/server/dev-page-plugin.d.ts +4 -0
  61. package/dist/server/devtools/hub.d.ts +11 -0
  62. package/dist/server/devtools/instrumentation.d.ts +22 -0
  63. package/dist/server/devtools/instrumentation.production.d.ts +44 -0
  64. package/dist/server/devtools/plugin.d.ts +3 -0
  65. package/dist/server/devtools/request-context.d.ts +6 -0
  66. package/dist/server/internal.d.ts +2 -0
  67. package/dist/server/internal.js +3 -3
  68. package/dist/server/lang-detect.d.ts +1 -0
  69. package/dist/server/render/assemble.d.ts +4 -0
  70. package/dist/server/render/element.d.ts +1 -1
  71. package/dist/server/render/index.d.ts +2 -2
  72. package/dist/server/render/index.ts +6 -2
  73. package/dist/server/render/loaders.d.ts +8 -0
  74. package/dist/server/render/not-found.d.ts +1 -1
  75. package/dist/server/render/ppr-route.d.ts +8 -0
  76. package/dist/server/render/route-frame-transport.d.ts +2 -0
  77. package/dist/server/render/shell.ts +0 -1
  78. package/dist/server/render/ssr.d.ts +2 -3
  79. package/dist/server/router/discovery.d.ts +1 -1
  80. package/dist/server/router/hmr.d.ts +1 -1
  81. package/dist/server/router/index.d.ts +2 -1
  82. package/dist/server/router/index.js +23 -23
  83. package/dist/server/router/index.ts +1 -1
  84. package/dist/server/router/patterns.d.ts +1 -1
  85. package/dist/server/router/plugin.d.ts +4 -7
  86. package/dist/server/router/schema-merge.d.ts +3 -0
  87. package/dist/server/router/schemas.d.ts +12 -7
  88. package/dist/server/router/types.d.ts +1 -1
  89. package/dist/server/runtime-env.js +2 -2
  90. package/dist/server/sync/adapter.d.ts +45 -26
  91. package/dist/server/sync/config.d.ts +5 -9
  92. package/dist/server/sync/fingerprint.d.ts +2 -1
  93. package/dist/server/sync/index.d.ts +15 -4
  94. package/dist/server/sync/index.js +2868 -0
  95. package/dist/server/sync/notifier.d.ts +18 -0
  96. package/dist/server/sync/plugin.d.ts +53 -54
  97. package/dist/server/sync/postgres/index.d.ts +19 -0
  98. package/dist/server/sync/postgres/index.js +252 -0
  99. package/dist/server/sync/postgres/migrate.d.ts +2 -0
  100. package/dist/server/sync/postgres/migrate.js +16 -0
  101. package/dist/server/sync/postgres/migration.sql +66 -0
  102. package/dist/server/sync/redis/index.d.ts +30 -0
  103. package/dist/server/sync/redis/index.js +336 -0
  104. package/dist/server/sync/redis/scripts.d.ts +4 -0
  105. package/dist/server/sync/response.d.ts +10 -1
  106. package/dist/server/sync/runtime.d.ts +6 -0
  107. package/dist/server/sync/sqlite/index.d.ts +20 -0
  108. package/dist/server/sync/sqlite/index.js +250 -0
  109. package/dist/server/sync/stream.d.ts +12 -11
  110. package/dist/server-only.d.ts +1 -0
  111. package/dist/server-only.js +1 -0
  112. package/dist/shared/parser.d.ts +2 -0
  113. package/dist/shared/route-frame.d.ts +49 -0
  114. package/dist/shared/utils/index.d.ts +1 -1
  115. package/package.json +54 -12
  116. package/src/adapter/bun.ts +73 -16
  117. package/src/adapter/package.ts +3 -1
  118. package/src/adapter/static.ts +94 -48
  119. package/src/build/bun-build.ts +11 -0
  120. package/src/build/client.ts +22 -24
  121. package/src/build/entry-template.ts +3 -0
  122. package/src/build/hydrate.ts +33 -8
  123. package/src/build/index.ts +12 -0
  124. package/src/build/production-instrumentation.ts +14 -0
  125. package/src/build/route-types.ts +7 -8
  126. package/src/build/scan-server.ts +3 -2
  127. package/src/build/ssg-cache.ts +7 -2
  128. package/src/build/types.ts +1 -0
  129. package/src/cli/index.ts +53 -22
  130. package/src/client/boundaries.tsx +42 -18
  131. package/src/client/default-screens.tsx +4 -4
  132. package/src/client/internal/runtime-types.ts +31 -0
  133. package/src/client/link.tsx +35 -37
  134. package/src/client/router/boundary-tree.tsx +2 -2
  135. package/src/client/router/context.ts +13 -9
  136. package/src/client/router/index.ts +3 -0
  137. package/src/client/router/link-utils.ts +66 -3
  138. package/src/client/router/navigation.ts +9 -15
  139. package/src/client/router/provider.tsx +74 -52
  140. package/src/client/router/search/index.ts +5 -7
  141. package/src/client/router/search-store.ts +5 -1
  142. package/src/client/router/spa-response.ts +3 -4
  143. package/src/client/router/sync-catch-up.ts +9 -8
  144. package/src/client/router/types.ts +2 -2
  145. package/src/client/sync.ts +3 -2
  146. package/src/client-only.ts +1 -0
  147. package/src/client.ts +221 -174
  148. package/src/devtools/devtools-element.js +884 -0
  149. package/src/devtools/protocol.ts +139 -0
  150. package/src/furin.ts +185 -96
  151. package/src/isomorphic.ts +66 -0
  152. package/src/plugin/binding-scope.ts +158 -0
  153. package/src/plugin/dead-code-elimination.ts +202 -0
  154. package/src/plugin/index.ts +14 -18
  155. package/src/plugin/transform-client.ts +237 -273
  156. package/src/plugin/transform-isomorphic.ts +464 -0
  157. package/src/rsc/build/environment.ts +30 -0
  158. package/src/rsc/build/index.ts +94 -0
  159. package/src/rsc/client-codec.ts +11 -0
  160. package/src/rsc/codec.ts +85 -0
  161. package/src/rsc/flight-drain.ts +68 -0
  162. package/src/rsc/react-server-dom-webpack.d.ts +23 -0
  163. package/src/rsc/render-error.ts +120 -0
  164. package/src/rsc/server-codec.ts +25 -0
  165. package/src/rsc/shared.tsx +113 -0
  166. package/src/rsc/symbols.ts +2 -0
  167. package/src/rsc/transport-benchmark.ts +73 -0
  168. package/src/rsc/version.ts +57 -0
  169. package/src/rsc-client.ts +12 -0
  170. package/src/rsc-server.tsx +91 -0
  171. package/src/rsc.tsx +75 -0
  172. package/src/server/auto-invalidate/runtime.ts +32 -6
  173. package/src/server/cache/dev-loader.ts +70 -10
  174. package/src/server/cache/index.ts +7 -3
  175. package/src/server/cache/invalidation.ts +33 -15
  176. package/src/server/cache/isr-ssg.ts +12 -3
  177. package/src/server/cache/isr.ts +84 -9
  178. package/src/server/cache/route-cache.ts +49 -36
  179. package/src/server/cache/store-view.ts +7 -7
  180. package/src/server/context-logger.ts +7 -7
  181. package/src/server/dev-page-plugin.ts +8 -6
  182. package/src/server/devtools/hub.ts +64 -0
  183. package/src/server/devtools/instrumentation.production.ts +80 -0
  184. package/src/server/devtools/instrumentation.ts +72 -0
  185. package/src/server/devtools/plugin.ts +267 -0
  186. package/src/server/devtools/request-context.ts +76 -0
  187. package/src/server/instance.ts +1 -1
  188. package/src/server/internal.ts +2 -0
  189. package/src/server/lang-detect.ts +14 -10
  190. package/src/server/render/assemble.ts +73 -10
  191. package/src/server/render/element.tsx +11 -8
  192. package/src/server/render/index.ts +6 -2
  193. package/src/server/render/isr.ts +154 -110
  194. package/src/server/render/loaders.ts +259 -45
  195. package/src/server/render/not-found.ts +10 -15
  196. package/src/server/render/ppr-route.ts +146 -0
  197. package/src/server/render/route-frame-transport.ts +62 -0
  198. package/src/server/render/shell.ts +0 -1
  199. package/src/server/render/ssg.ts +6 -5
  200. package/src/server/render/ssr.ts +155 -67
  201. package/src/server/render/template.ts +2 -1
  202. package/src/server/router/discovery.ts +39 -22
  203. package/src/server/router/hmr.ts +15 -13
  204. package/src/server/router/index.ts +1 -1
  205. package/src/server/router/patterns.ts +16 -15
  206. package/src/server/router/plugin.ts +151 -158
  207. package/src/server/router/schema-merge.ts +52 -0
  208. package/src/server/router/schemas.ts +55 -73
  209. package/src/server/router/types.ts +1 -1
  210. package/src/server/sync/adapter.ts +44 -28
  211. package/src/server/sync/config.ts +9 -27
  212. package/src/server/sync/fingerprint.ts +8 -3
  213. package/src/server/sync/index.ts +37 -13
  214. package/src/server/sync/notifier.ts +109 -0
  215. package/src/server/sync/plugin.ts +184 -89
  216. package/src/server/sync/postgres/index.ts +301 -0
  217. package/src/server/sync/postgres/migrate.ts +15 -0
  218. package/src/server/sync/postgres/migration.sql +66 -0
  219. package/src/server/sync/redis/index.ts +342 -0
  220. package/src/server/sync/redis/scripts.ts +74 -0
  221. package/src/server/sync/response.ts +141 -16
  222. package/src/server/sync/runtime.ts +27 -0
  223. package/src/server/sync/sql.d.ts +4 -0
  224. package/src/server/sync/sqlite/index.ts +337 -0
  225. package/src/server/sync/sqlite/migration.sql +70 -0
  226. package/src/server/sync/stream.ts +137 -81
  227. package/src/server-only.ts +1 -0
  228. package/src/shared/await.tsx +4 -4
  229. package/src/shared/deferred-ndjson.ts +34 -6
  230. package/src/shared/digest.ts +2 -2
  231. package/src/shared/parser.ts +5 -0
  232. package/src/shared/route-frame.ts +429 -0
  233. package/src/shared/search-params.ts +7 -7
  234. package/src/shared/utils/index.ts +5 -3
  235. package/dist/server/dev-inspector.d.ts +0 -89
  236. package/dist/server/sync/memory-adapter.d.ts +0 -17
  237. package/src/server/dev-inspector.ts +0 -60
  238. package/src/server/sync/memory-adapter.ts +0 -196
@@ -1,6 +1,6 @@
1
1
  // @bun
2
2
  // src/client/link.tsx
3
- import { createElement as createElement3, useCallback as useCallback3, useEffect as useEffect2, useRef as useRef2 } from "react";
3
+ import { createElement as createElement4, useCallback as useCallback3, useEffect as useEffect2, useRef as useRef2 } from "react";
4
4
 
5
5
  // src/shared/search-params.ts
6
6
  function routeSegmentSpecificity(segment) {
@@ -16,7 +16,7 @@ function compareSearchRouteSpecificity(a, b) {
16
16
  const aSegments = a.split("/").filter((segment) => segment.length > 0);
17
17
  const bSegments = b.split("/").filter((segment) => segment.length > 0);
18
18
  const length = Math.max(aSegments.length, bSegments.length);
19
- for (let i = 0;i < length; i++) {
19
+ for (let i = 0;i < length; i += 1) {
20
20
  const aSegment = aSegments[i];
21
21
  const bSegment = bSegments[i];
22
22
  if (aSegment === undefined) {
@@ -39,7 +39,7 @@ function arraysDeepEqual(a, b) {
39
39
  if (a.length !== b.length) {
40
40
  return false;
41
41
  }
42
- for (let i = 0;i < a.length; i++) {
42
+ for (let i = 0;i < a.length; i += 1) {
43
43
  if (!deepEqual(a[i], b[i])) {
44
44
  return false;
45
45
  }
@@ -84,12 +84,12 @@ function stripSearchDefaults(search, defaults) {
84
84
  return stripped;
85
85
  }
86
86
  function appendSearchParamValue(params, key, value) {
87
- if (value == null) {
87
+ if (value === null || value === undefined) {
88
88
  return;
89
89
  }
90
90
  if (Array.isArray(value)) {
91
91
  for (const item of value) {
92
- if (item != null) {
92
+ if (item !== null && item !== undefined) {
93
93
  params.append(key, typeof item === "object" ? JSON.stringify(item) : String(item));
94
94
  }
95
95
  }
@@ -121,11 +121,196 @@ function findSearchDefaultsForRouteTarget(to, routes) {
121
121
  return;
122
122
  }
123
123
  try {
124
- const pathname = new URL(to, "http://furin.local").pathname;
124
+ const { pathname } = new URL(to, "http://furin.local");
125
125
  return findSearchDefaults(pathname, routes);
126
+ } catch {}
127
+ }
128
+
129
+ // src/client/router/context.ts
130
+ import { createContext, useContext } from "react";
131
+
132
+ // src/client/router/link-utils.ts
133
+ var HASH_FRAGMENT_RE = /#.*$/;
134
+ var TRAILING_SLASHES_RE = /\/+$/;
135
+ function navigationHrefPolicy(href, currentOrigin) {
136
+ for (let index = 0;index < href.length; index += 1) {
137
+ const code = href.charCodeAt(index);
138
+ if (code <= 31 || code === 127) {
139
+ return "blocked";
140
+ }
141
+ }
142
+ let url;
143
+ try {
144
+ url = new URL(href, currentOrigin ?? "http://localhost");
126
145
  } catch {
146
+ return "blocked";
147
+ }
148
+ if (url.protocol !== "http:" && url.protocol !== "https:") {
149
+ return "blocked";
150
+ }
151
+ if (currentOrigin === undefined) {
152
+ return href.startsWith("http://") || href.startsWith("https://") || href.startsWith("//") ? "external" : "internal";
153
+ }
154
+ return url.origin === currentOrigin ? "internal" : "external";
155
+ }
156
+ function decodeHashFragment(fragment) {
157
+ try {
158
+ return decodeURIComponent(fragment);
159
+ } catch {
160
+ return fragment;
161
+ }
162
+ }
163
+ function isSameOriginFetchResult(input, responseUrl, currentOrigin) {
164
+ if (responseUrl.length === 0) {
165
+ return false;
166
+ }
167
+ try {
168
+ let inputUrl;
169
+ if (typeof input === "string") {
170
+ inputUrl = input;
171
+ } else if (input instanceof URL) {
172
+ inputUrl = input.href;
173
+ } else {
174
+ inputUrl = input.url;
175
+ }
176
+ return new URL(inputUrl, currentOrigin).origin === currentOrigin && new URL(responseUrl, currentOrigin).origin === currentOrigin;
177
+ } catch {
178
+ return false;
179
+ }
180
+ }
181
+ function buildHref(to, search, hash, searchDefaults) {
182
+ let url = to;
183
+ if (search && Object.keys(search).length > 0) {
184
+ const params = buildSearchParams(search, searchDefaults);
185
+ const qs = params.toString();
186
+ if (qs) {
187
+ url += `?${qs}`;
188
+ }
189
+ }
190
+ if (hash) {
191
+ url += `#${hash}`;
192
+ }
193
+ return url;
194
+ }
195
+ function applyRevalidateHeader(headers, invalidate) {
196
+ const headerValue = headers.get("x-furin-revalidate");
197
+ if (!headerValue) {
127
198
  return;
128
199
  }
200
+ applyRevalidateEntries(headerValue.split(","), invalidate);
201
+ }
202
+ function applyRevalidateEntries(entries, invalidate) {
203
+ for (const entry of entries) {
204
+ const trimmed = entry.trim();
205
+ if (!trimmed) {
206
+ continue;
207
+ }
208
+ if (trimmed.endsWith(":layout")) {
209
+ invalidate(trimmed.slice(0, -":layout".length), "layout");
210
+ } else {
211
+ invalidate(trimmed, "page");
212
+ }
213
+ }
214
+ }
215
+ function shouldAutoRefreshPath(currentPath, invalidations) {
216
+ const normalizedCurrent = currentPath.split("?")[0] ?? currentPath;
217
+ return invalidations.some(({ path, type }) => {
218
+ if (type === "page") {
219
+ return path === normalizedCurrent;
220
+ }
221
+ const prefix = path === "/" || path.endsWith("/") ? path : `${path}/`;
222
+ return normalizedCurrent === path || normalizedCurrent.startsWith(prefix);
223
+ });
224
+ }
225
+ function stripHashFromHref(href) {
226
+ return href.replace(HASH_FRAGMENT_RE, "");
227
+ }
228
+ function normalizeHref(href) {
229
+ const url = new URL(href, "http://localhost");
230
+ let { pathname } = url;
231
+ if (pathname !== "/") {
232
+ pathname = pathname.replace(/\/+$/g, "");
233
+ }
234
+ return pathname + url.search + url.hash;
235
+ }
236
+ function normalizePath(path) {
237
+ if (path === "/" || path === "") {
238
+ return path;
239
+ }
240
+ return path.endsWith("/") ? path.slice(0, -1) : path;
241
+ }
242
+ function shouldRefetch(entry) {
243
+ return Date.now() - entry.createdAt > entry.staleTime;
244
+ }
245
+ function shouldInterceptClick(anchor, event, basePath, currentOrigin, currentPathname) {
246
+ if (event.metaKey || event.ctrlKey || event.shiftKey || event.altKey) {
247
+ return null;
248
+ }
249
+ if (anchor.target && anchor.target !== "_self") {
250
+ return null;
251
+ }
252
+ if (anchor.hasAttribute("download")) {
253
+ return null;
254
+ }
255
+ const { href } = anchor;
256
+ if (!href) {
257
+ return null;
258
+ }
259
+ let url;
260
+ try {
261
+ url = new URL(href, currentOrigin);
262
+ } catch {
263
+ return null;
264
+ }
265
+ if (url.origin !== currentOrigin) {
266
+ return null;
267
+ }
268
+ if (normalizePath(url.pathname) === normalizePath(currentPathname) && url.hash) {
269
+ return null;
270
+ }
271
+ const logicalPath = normalizeHref(toLogical(url.pathname, basePath));
272
+ const normalizedBase = normalizePath(basePath);
273
+ const normalizedPathname = normalizePath(url.pathname);
274
+ if (normalizedBase && normalizedPathname !== normalizedBase && !normalizedPathname.startsWith(`${normalizedBase}/`)) {
275
+ return null;
276
+ }
277
+ return logicalPath + url.search + url.hash;
278
+ }
279
+ function toLogical(physicalPathname, basePath) {
280
+ if (basePath && physicalPathname.startsWith(basePath) && (physicalPathname.length === basePath.length || physicalPathname[basePath.length] === "/")) {
281
+ return physicalPathname.slice(basePath.length) || "/";
282
+ }
283
+ return physicalPathname;
284
+ }
285
+
286
+ // src/client/router/context.ts
287
+ var RouterContext = createContext(null);
288
+ var CLIENT_FALLBACK_ROUTER = {
289
+ basePath: "",
290
+ currentHref: "/",
291
+ defaultPreload: "intent",
292
+ defaultPreloadDelay: 50,
293
+ defaultPreloadStaleTime: 30000,
294
+ invalidatePrefetch: (_path, _type) => {},
295
+ isNavigating: false,
296
+ navigate: (href, _opts) => {
297
+ if (navigationHrefPolicy(href, window.location.origin) === "blocked") {
298
+ return Promise.reject(new Error("[furin] Unsafe navigation URL."));
299
+ }
300
+ window.location.href = href;
301
+ return Promise.resolve();
302
+ },
303
+ prefetch: (_href, _opts) => {},
304
+ refresh: (_opts) => {
305
+ window.location.reload();
306
+ return Promise.resolve();
307
+ },
308
+ search: {},
309
+ searchRoutes: []
310
+ };
311
+ function useRouter() {
312
+ const ctx = useContext(RouterContext);
313
+ return ctx ?? CLIENT_FALLBACK_ROUTER;
129
314
  }
130
315
 
131
316
  // src/client/router/boundary-tree.tsx
@@ -139,7 +324,7 @@ function computeErrorDigest(err) {
139
324
  let message = "";
140
325
  let stack = "";
141
326
  if (err instanceof Error) {
142
- message = err.message;
327
+ ({ message } = err);
143
328
  stack = err.stack ?? "";
144
329
  } else if (typeof err === "string") {
145
330
  message = err;
@@ -159,7 +344,7 @@ ${stack}`;
159
344
  function cyrb53(input) {
160
345
  let h1 = 3735928559;
161
346
  let h2 = 1103547991;
162
- for (let i = 0;i < input.length; i++) {
347
+ for (let i = 0;i < input.length; i += 1) {
163
348
  const ch = input.charCodeAt(i);
164
349
  h1 = Math.imul(h1 ^ ch, 2654435761);
165
350
  h2 = Math.imul(h2 ^ ch, 1597334677);
@@ -304,22 +489,22 @@ var ACTIONS_STYLE = {
304
489
  justifyContent: "center"
305
490
  };
306
491
  var BUTTON_BASE = {
492
+ alignItems: "center",
493
+ appearance: "none",
307
494
  border: 0,
495
+ boxSizing: "border-box",
308
496
  cursor: "pointer",
309
497
  display: "inline-flex",
310
498
  fontFamily: FONT_SANS,
311
499
  fontSize: "14px",
312
500
  fontWeight: 500,
501
+ justifyContent: "center",
313
502
  lineHeight: 1,
314
503
  minWidth: "120px",
315
504
  padding: "10px 16px",
316
505
  textAlign: "center",
317
506
  textDecoration: "none",
318
- transition: "background-color 120ms ease, color 120ms ease, opacity 120ms ease",
319
- appearance: "none",
320
- alignItems: "center",
321
- justifyContent: "center",
322
- boxSizing: "border-box"
507
+ transition: "background-color 120ms ease, color 120ms ease, opacity 120ms ease"
323
508
  };
324
509
  var BUTTON_PRIMARY = {
325
510
  ...BUTTON_BASE,
@@ -489,6 +674,26 @@ function isFurinServerError(err) {
489
674
  import { jsxDEV as jsxDEV2 } from "react/jsx-dev-runtime";
490
675
  var DEFAULT_ERROR_STATUS = 500;
491
676
  var SERVER_RESET_NOOP = () => {};
677
+ function getServerDigest(error) {
678
+ if (isFurinServerError(error)) {
679
+ return error.digest;
680
+ }
681
+ if (typeof error !== "object" && typeof error !== "function" || error === null) {
682
+ return;
683
+ }
684
+ const digest = error.__furinDigest;
685
+ return typeof digest === "string" ? digest : undefined;
686
+ }
687
+ function normalizeCaughtError(error) {
688
+ if (error instanceof Error) {
689
+ return error;
690
+ }
691
+ const normalized = new Error(String(error));
692
+ if (typeof error === "object" && error !== null || typeof error === "function") {
693
+ Object.defineProperties(normalized, Object.getOwnPropertyDescriptors(error));
694
+ }
695
+ return normalized;
696
+ }
492
697
 
493
698
  class FurinErrorBoundary extends Component {
494
699
  state = {
@@ -497,7 +702,10 @@ class FurinErrorBoundary extends Component {
497
702
  error: null
498
703
  };
499
704
  static getDerivedStateFromError(error) {
500
- return { digest: computeErrorDigest(error), error };
705
+ return {
706
+ digest: getServerDigest(error) ?? computeErrorDigest(error),
707
+ error: normalizeCaughtError(error)
708
+ };
501
709
  }
502
710
  componentDidUpdate(prevProps) {
503
711
  if (prevProps.resetKey !== this.props.resetKey && this.state.error) {
@@ -516,12 +724,12 @@ class FurinErrorBoundary extends Component {
516
724
  throw error;
517
725
  }
518
726
  const Fallback = this.props.fallback ?? DefaultErrorFallback;
519
- const serverDigest = isFurinServerError(error) ? error.digest : undefined;
727
+ const serverDigest = getServerDigest(error);
520
728
  const finalDigest = serverDigest ?? digest ?? this.props.digest ?? computeErrorDigest(error);
521
729
  const message = this.props.fallback ? error.message : getPublicErrorMessage(error);
522
730
  const status = isFurinServerError(error) ? error.status : DEFAULT_ERROR_STATUS;
523
731
  return /* @__PURE__ */ jsxDEV2(Fallback, {
524
- error: { message, digest: finalDigest, status },
732
+ error: { digest: finalDigest, message, status },
525
733
  reset: typeof window === "undefined" ? SERVER_RESET_NOOP : this.reset
526
734
  }, undefined, false, undefined, this);
527
735
  }
@@ -538,7 +746,7 @@ class FurinNotFoundBoundary extends Component {
538
746
  }
539
747
  componentDidUpdate(prevProps) {
540
748
  if (prevProps.resetKey !== this.props.resetKey && this.state.error) {
541
- this.setState((s) => ({ error: null, epoch: s.epoch + 1 }));
749
+ this.setState((s) => ({ epoch: s.epoch + 1, error: null }));
542
750
  }
543
751
  }
544
752
  render() {
@@ -549,7 +757,7 @@ class FurinNotFoundBoundary extends Component {
549
757
  }
550
758
  const Fallback = this.props.fallback ?? DefaultNotFoundFallback;
551
759
  return /* @__PURE__ */ jsxDEV2(Fallback, {
552
- error: { message: error.message, data: error.data }
760
+ error: { data: error.data, message: error.message }
553
761
  }, undefined, false, undefined, this);
554
762
  }
555
763
  return /* @__PURE__ */ jsxDEV2(Fragment, {
@@ -580,34 +788,6 @@ function wrapSegmentBoundaries(inner, segment, options) {
580
788
  return wrapped;
581
789
  }
582
790
 
583
- // src/client/router/context.ts
584
- import { createContext, useContext } from "react";
585
- var RouterContext = createContext(null);
586
- var CLIENT_FALLBACK_ROUTER = {
587
- basePath: "",
588
- currentHref: "/",
589
- search: {},
590
- searchRoutes: [],
591
- navigate: (href, _opts) => {
592
- window.location.href = href;
593
- return Promise.resolve();
594
- },
595
- prefetch: (_href, _opts) => {},
596
- invalidatePrefetch: (_path, _type) => {},
597
- refresh: (_opts) => {
598
- window.location.reload();
599
- return Promise.resolve();
600
- },
601
- isNavigating: false,
602
- defaultPreload: "intent",
603
- defaultPreloadDelay: 50,
604
- defaultPreloadStaleTime: 30000
605
- };
606
- function useRouter() {
607
- const ctx = useContext(RouterContext);
608
- return ctx ?? CLIENT_FALLBACK_ROUTER;
609
- }
610
-
611
791
  // src/client/router/boundary-tree.tsx
612
792
  import { jsxDEV as jsxDEV3 } from "react/jsx-dev-runtime";
613
793
  function buildRouterTree(context, pageElement, options) {
@@ -637,7 +817,7 @@ function buildPageElement(match, root, data, options, error) {
637
817
  byDepth.set(segment.depth, segment);
638
818
  }
639
819
  const rootOffset = root ? 1 : 0;
640
- for (let i = chain.length - 1;i >= rootOffset; i--) {
820
+ for (let i = chain.length - 1;i >= rootOffset; i -= 1) {
641
821
  element = wrapSegmentBoundaries(element, byDepth.get(i), options);
642
822
  const Layout = chain[i]?.layout;
643
823
  if (Layout) {
@@ -681,133 +861,18 @@ function isStaleDeployResponse(res) {
681
861
  const clientBuildId = metaEl?.content;
682
862
  return Boolean(clientBuildId && serverBuildId !== clientBuildId);
683
863
  }
684
- // src/client/router/link-utils.ts
685
- var HASH_FRAGMENT_RE = /#.*$/;
686
- var TRAILING_SLASHES_RE = /\/+$/;
687
- function buildHref(to, search, hash, searchDefaults) {
688
- let url = to;
689
- if (search && Object.keys(search).length > 0) {
690
- const params = buildSearchParams(search, searchDefaults);
691
- const qs = params.toString();
692
- if (qs) {
693
- url += `?${qs}`;
694
- }
695
- }
696
- if (hash) {
697
- url += `#${hash}`;
698
- }
699
- return url;
700
- }
701
- function applyRevalidateHeader(headers, invalidate) {
702
- const headerValue = headers.get("x-furin-revalidate");
703
- if (!headerValue) {
704
- return;
705
- }
706
- applyRevalidateEntries(headerValue.split(","), invalidate);
707
- }
708
- function applyRevalidateEntries(entries, invalidate) {
709
- for (const entry of entries) {
710
- const trimmed = entry.trim();
711
- if (!trimmed) {
712
- continue;
713
- }
714
- if (trimmed.endsWith(":layout")) {
715
- invalidate(trimmed.slice(0, -":layout".length), "layout");
716
- } else {
717
- invalidate(trimmed, "page");
718
- }
719
- }
720
- }
721
- function shouldAutoRefreshPath(currentPath, invalidations) {
722
- const normalizedCurrent = currentPath.split("?")[0] ?? currentPath;
723
- return invalidations.some(({ path, type }) => {
724
- if (type === "page") {
725
- return path === normalizedCurrent;
726
- }
727
- const prefix = path === "/" || path.endsWith("/") ? path : `${path}/`;
728
- return normalizedCurrent === path || normalizedCurrent.startsWith(prefix);
729
- });
730
- }
731
- function stripHashFromHref(href) {
732
- return href.replace(HASH_FRAGMENT_RE, "");
733
- }
734
- function normalizeHref(href) {
735
- const url = new URL(href, "http://localhost");
736
- let pathname = url.pathname;
737
- if (pathname !== "/") {
738
- pathname = pathname.replace(/\/+$/g, "");
739
- }
740
- return pathname + url.search + url.hash;
741
- }
742
- function normalizePath(path) {
743
- if (path === "/" || path === "") {
744
- return path;
745
- }
746
- return path.endsWith("/") ? path.slice(0, -1) : path;
747
- }
748
- function shouldRefetch(entry) {
749
- return Date.now() - entry.createdAt > entry.staleTime;
750
- }
751
- function shouldInterceptClick(anchor, event, basePath, currentOrigin, currentPathname) {
752
- if (event.metaKey || event.ctrlKey || event.shiftKey || event.altKey) {
753
- return null;
754
- }
755
- if (anchor.target && anchor.target !== "_self") {
756
- return null;
757
- }
758
- if (anchor.hasAttribute("download")) {
759
- return null;
760
- }
761
- const href = anchor.href;
762
- if (!href) {
763
- return null;
764
- }
765
- let url;
766
- try {
767
- url = new URL(href, currentOrigin);
768
- } catch {
769
- return null;
770
- }
771
- if (url.origin !== currentOrigin) {
772
- return null;
773
- }
774
- if (normalizePath(url.pathname) === normalizePath(currentPathname) && url.hash) {
775
- return null;
776
- }
777
- const logicalPath = normalizeHref(toLogical(url.pathname, basePath));
778
- const normalizedBase = normalizePath(basePath);
779
- const normalizedPathname = normalizePath(url.pathname);
780
- if (normalizedBase && normalizedPathname !== normalizedBase && !normalizedPathname.startsWith(`${normalizedBase}/`)) {
781
- return null;
782
- }
783
- return logicalPath + url.search + url.hash;
784
- }
785
- function toLogical(physicalPathname, basePath) {
786
- if (basePath && physicalPathname.startsWith(basePath) && (physicalPathname.length === basePath.length || physicalPathname[basePath.length] === "/")) {
787
- return physicalPathname.slice(basePath.length) || "/";
788
- }
789
- return physicalPathname;
790
- }
791
864
  // src/client/router/navigation.ts
792
865
  import { useCallback } from "react";
793
- function isExternalAbsoluteHref(href) {
794
- if (href.startsWith("//")) {
795
- return true;
796
- }
797
- if (!(href.startsWith("http://") || href.startsWith("https://"))) {
798
- return false;
799
- }
800
- if (typeof window === "undefined") {
801
- return true;
802
- }
803
- return new URL(href).origin !== window.location.origin;
804
- }
805
866
  function useNavigate() {
806
867
  const router = useRouter();
807
868
  return useCallback((next) => {
808
869
  const searchDefaults = findSearchDefaultsForRouteTarget(next.to, router.searchRoutes);
809
870
  const href = buildHref(next.to, next.search, next.hash, searchDefaults);
810
- if (isExternalAbsoluteHref(href) && typeof window !== "undefined") {
871
+ const policy = navigationHrefPolicy(href, typeof window === "undefined" ? undefined : window.location.origin);
872
+ if (policy === "blocked") {
873
+ return Promise.reject(new Error("[furin] Unsafe navigation URL."));
874
+ }
875
+ if (policy === "external" && typeof window !== "undefined") {
811
876
  window.location.assign(href);
812
877
  return Promise.resolve();
813
878
  }
@@ -815,7 +880,7 @@ function useNavigate() {
815
880
  return router.navigate(href, opts);
816
881
  }, [router]);
817
882
  }
818
- // ../../node_modules/.bun/evlog@2.19.2+7724ce3de6b3bca4/node_modules/evlog/dist/utils.mjs
883
+ // ../../node_modules/.bun/evlog@2.22.3+6e5ab44a2bca2113/node_modules/evlog/dist/utils.mjs
819
884
  function formatDuration(ms) {
820
885
  if (ms < 1000)
821
886
  return `${Math.round(ms)}ms`;
@@ -926,7 +991,7 @@ function globToRegExp(pattern, separator = "/") {
926
991
  return regex;
927
992
  }
928
993
 
929
- // ../../node_modules/.bun/evlog@2.19.2+7724ce3de6b3bca4/node_modules/evlog/dist/pretty-error-THg0U0w9.mjs
994
+ // ../../node_modules/.bun/evlog@2.22.3+6e5ab44a2bca2113/node_modules/evlog/dist/pretty-error-DTIHxnBN.mjs
930
995
  var snippetReader = null;
931
996
  var PRETTY_ERROR_TREE_SPACER = "__EVLOG_TREE_SPACER__";
932
997
  function pushTreeSpacer(children) {
@@ -1216,7 +1281,7 @@ function buildErrorEntries(error, options = {}) {
1216
1281
  }];
1217
1282
  }
1218
1283
 
1219
- // ../../node_modules/.bun/evlog@2.19.2+7724ce3de6b3bca4/node_modules/evlog/dist/dev-terminal-D4UaEm17.mjs
1284
+ // ../../node_modules/.bun/evlog@2.22.3+6e5ab44a2bca2113/node_modules/evlog/dist/dev-terminal-Brarc6vc.mjs
1220
1285
  var DEV_PRESETS = {
1221
1286
  evlog: {
1222
1287
  frameworkOverlay: false,
@@ -1265,7 +1330,7 @@ function resolveDevTerminal(input = {}) {
1265
1330
  };
1266
1331
  }
1267
1332
 
1268
- // ../../node_modules/.bun/evlog@2.19.2+7724ce3de6b3bca4/node_modules/evlog/dist/audit-CL0q7GJU.mjs
1333
+ // ../../node_modules/.bun/evlog@2.22.3+6e5ab44a2bca2113/node_modules/evlog/dist/audit-CPODPtOL.mjs
1269
1334
  var DEFAULT_REPLACEMENT = "[REDACTED]";
1270
1335
  function normalizeRedactPathPattern(pattern) {
1271
1336
  if (!pattern.includes("*") && !pattern.includes("."))
@@ -1647,6 +1712,7 @@ var globalRedact;
1647
1712
  var globalEnabled = true;
1648
1713
  var globalSilent = false;
1649
1714
  var globalMinLevel = "debug";
1715
+ var _loggerInitialized = false;
1650
1716
  var globalPluginRunner = getEmptyPluginRunner();
1651
1717
  function initLogger(config = {}) {
1652
1718
  globalEnabled = config.enabled ?? true;
@@ -1672,6 +1738,7 @@ function initLogger(config = {}) {
1672
1738
  const hasAnyDrain = !!globalDrain || globalPluginRunner.hasDrain;
1673
1739
  if (globalSilent && !hasAnyDrain && !config._suppressDrainWarning)
1674
1740
  console.warn("[evlog] silent mode is enabled but no drain is configured. Events will be built and sampled but not output anywhere. Set a drain via initLogger({ drain }) or a framework hook (evlog:drain).");
1741
+ _loggerInitialized = true;
1675
1742
  }
1676
1743
  function shouldSample(level) {
1677
1744
  const { rates } = globalSampling;
@@ -1772,6 +1839,8 @@ function emitTaggedLog(level, tag, message) {
1772
1839
  function formatValue(value) {
1773
1840
  if (value === null || value === undefined)
1774
1841
  return String(value);
1842
+ if (Array.isArray(value))
1843
+ return JSON.stringify(value);
1775
1844
  if (isPlainObject$1(value)) {
1776
1845
  const pairs = [];
1777
1846
  for (const [k, v] of Object.entries(value))
@@ -2037,10 +2106,7 @@ function prettyPrintWideEvent(event) {
2037
2106
  styles.push(cssColors.dim, cssColors.reset, lc, cssColors.reset, cssColors.cyan, cssColors.reset);
2038
2107
  } else {
2039
2108
  const lc = getLevelColor(levelLabel);
2040
- if (isDev())
2041
- parts.push(`${lc}${levelLabel.toUpperCase()}${colors.reset} ${colors.cyan}[${service}]${colors.reset}`);
2042
- else
2043
- parts.push(`${colors.dim}${ts}${colors.reset} ${lc}${levelLabel.toUpperCase()}${colors.reset} ${colors.cyan}[${service}]${colors.reset}`);
2109
+ parts.push(`${colors.dim}${ts}${colors.reset} ${lc}${levelLabel.toUpperCase()}${colors.reset} ${colors.cyan}[${service}]${colors.reset}`);
2044
2110
  }
2045
2111
  if (rest.method && rest.path) {
2046
2112
  parts.push(browser ? ` ${escapeFormatString(String(rest.method))} ${escapeFormatString(String(rest.path))}` : ` ${rest.method} ${rest.path}`);
@@ -2210,9 +2276,15 @@ function decorateAudit(audit, timestamp) {
2210
2276
  idempotencyKey: computeIdempotencyKey(audit, timestamp)
2211
2277
  };
2212
2278
  }
2279
+ function isCompleteAuditFields(a) {
2280
+ if (!a || typeof a !== "object")
2281
+ return false;
2282
+ const audit = a;
2283
+ return typeof audit.action === "string" && typeof audit.actor?.type === "string" && typeof audit.actor?.id === "string";
2284
+ }
2213
2285
  function finalizeAudit(event) {
2214
2286
  const a = event.audit;
2215
- if (!a)
2287
+ if (!isCompleteAuditFields(a))
2216
2288
  return;
2217
2289
  const decorated = decorateAudit(a, String(event.timestamp));
2218
2290
  event.audit = decorated;
@@ -2221,7 +2293,7 @@ function finalizeAudit(event) {
2221
2293
  // src/client/router/provider.tsx
2222
2294
  import { useCallback as useCallback2, useEffect, useLayoutEffect, useMemo, useRef, useState } from "react";
2223
2295
 
2224
- // ../../node_modules/.bun/seroval@1.5.4/node_modules/seroval/dist/esm/development/index.mjs
2296
+ // ../../node_modules/.bun/seroval@1.5.6/node_modules/seroval/dist/esm/development/index.mjs
2225
2297
  var ALL_ENABLED = 1 | 2 | 4 | 8 | 16 | 32;
2226
2298
  var SYM_ASYNC_ITERATOR = Symbol.asyncIterator;
2227
2299
  var SYM_HAS_INSTANCE = Symbol.hasInstance;
@@ -2722,7 +2794,32 @@ function getTypedArrayConstructor(name) {
2722
2794
  case "BigUint64Array":
2723
2795
  return BigUint64Array;
2724
2796
  default:
2725
- throw new SerovalUnknownTypedArrayError(name);
2797
+ throw new SerovalUnknownTypedArrayError(name);
2798
+ }
2799
+ }
2800
+ function isValidKey(key) {
2801
+ switch (key) {
2802
+ case "constructor":
2803
+ case "__proto__":
2804
+ case "prototype":
2805
+ case "__defineGetter__":
2806
+ case "__defineSetter__":
2807
+ case "__lookupGetter__":
2808
+ case "__lookupSetter__":
2809
+ return false;
2810
+ default:
2811
+ return true;
2812
+ }
2813
+ }
2814
+ function isValidSymbol(symbol) {
2815
+ switch (symbol) {
2816
+ case SYM_ASYNC_ITERATOR:
2817
+ case SYM_IS_CONCAT_SPREADABLE:
2818
+ case SYM_TO_STRING_TAG:
2819
+ case SYM_ITERATOR:
2820
+ return true;
2821
+ default:
2822
+ return false;
2726
2823
  }
2727
2824
  }
2728
2825
  var MAX_BASE64_LENGTH = 1e6;
@@ -2821,31 +2918,6 @@ function deserializeArray(ctx, depth, node) {
2821
2918
  applyObjectFlag(result, node.o);
2822
2919
  return result;
2823
2920
  }
2824
- function isValidKey(key) {
2825
- switch (key) {
2826
- case "constructor":
2827
- case "__proto__":
2828
- case "prototype":
2829
- case "__defineGetter__":
2830
- case "__defineSetter__":
2831
- case "__lookupGetter__":
2832
- case "__lookupSetter__":
2833
- return false;
2834
- default:
2835
- return true;
2836
- }
2837
- }
2838
- function isValidSymbol(symbol) {
2839
- switch (symbol) {
2840
- case SYM_ASYNC_ITERATOR:
2841
- case SYM_IS_CONCAT_SPREADABLE:
2842
- case SYM_TO_STRING_TAG:
2843
- case SYM_ITERATOR:
2844
- return true;
2845
- default:
2846
- return false;
2847
- }
2848
- }
2849
2921
  function assignStringProperty(object, key, value) {
2850
2922
  if (isValidKey(key)) {
2851
2923
  object[key] = value;
@@ -3192,6 +3264,266 @@ function fromCrossJSON(source, options) {
3192
3264
  return deserializeTop(ctx, source);
3193
3265
  }
3194
3266
 
3267
+ // src/rsc/shared.tsx
3268
+ import {
3269
+ Children,
3270
+ cloneElement,
3271
+ createElement as createElement2,
3272
+ isValidElement,
3273
+ use
3274
+ } from "react";
3275
+
3276
+ // src/rsc/client-codec.ts
3277
+ import { createFromReadableStream } from "react-server-dom-webpack/client.edge";
3278
+ function decodeFlight(stream) {
3279
+ return createFromReadableStream(stream, {
3280
+ serverConsumerManifest: {
3281
+ moduleLoading: null,
3282
+ moduleMap: {},
3283
+ serverModuleMap: {}
3284
+ }
3285
+ });
3286
+ }
3287
+
3288
+ // src/rsc/symbols.ts
3289
+ var RSC_SOURCE = Symbol.for("furin.rsc.source");
3290
+
3291
+ // src/rsc/shared.tsx
3292
+ function RscNode({ state }) {
3293
+ return use(state.tree);
3294
+ }
3295
+ function decodeFlightBytes(bytes) {
3296
+ return decodeFlight(new ReadableStream({
3297
+ start(controller) {
3298
+ controller.enqueue(bytes);
3299
+ controller.close();
3300
+ }
3301
+ }));
3302
+ }
3303
+ function createRenderableSource(state) {
3304
+ const element = createElement2(RscNode, { state });
3305
+ return new Proxy(element, {
3306
+ get(target, property, receiver) {
3307
+ if (property === RSC_SOURCE) {
3308
+ return state;
3309
+ }
3310
+ return Reflect.get(target, property, receiver);
3311
+ },
3312
+ has(target, property) {
3313
+ return property === RSC_SOURCE || Reflect.has(target, property);
3314
+ }
3315
+ });
3316
+ }
3317
+ function restoreRscSource(kind, bytes) {
3318
+ const state = { bytes, kind, tree: decodeFlightBytes(bytes) };
3319
+ return kind === "renderable" ? createRenderableSource(state) : { [RSC_SOURCE]: state };
3320
+ }
3321
+
3322
+ // src/shared/route-frame.ts
3323
+ var FRAME_VERSION = 3;
3324
+ var MAX_FRAME_BYTES = 1024 * 1024;
3325
+ var MAX_ROUTE_FRAME_STREAM_BYTES = 8 * 1024 * 1024;
3326
+ function isPlainObject3(value) {
3327
+ const prototype = Object.getPrototypeOf(value);
3328
+ return prototype === Object.prototype || prototype === null;
3329
+ }
3330
+ function frameValueToBytes(value) {
3331
+ if (value.startsWith("utf8:")) {
3332
+ return new TextEncoder().encode(value.slice(5));
3333
+ }
3334
+ if (!value.startsWith("base64:")) {
3335
+ throw new Error("[furin] malformed RSC route frame encoding");
3336
+ }
3337
+ const binary = atob(value.slice(7));
3338
+ return Uint8Array.from(binary, (character) => character.charCodeAt(0));
3339
+ }
3340
+ function isRouteFrameLine(line) {
3341
+ try {
3342
+ const parsed = JSON.parse(line);
3343
+ return parsed.__furinRouteFrame === FRAME_VERSION;
3344
+ } catch {
3345
+ return false;
3346
+ }
3347
+ }
3348
+ function hydrateRscDescriptors(value, sources, seen = new WeakMap) {
3349
+ if (value === null || typeof value !== "object") {
3350
+ return value;
3351
+ }
3352
+ if (isPlainObject3(value) && typeof value.__furinRsc === "string") {
3353
+ const id = value.__furinRsc;
3354
+ const source = sources.get(id);
3355
+ if (source === undefined) {
3356
+ throw new Error(`[furin] RSC route frame "${id}" is missing`);
3357
+ }
3358
+ return source;
3359
+ }
3360
+ const previous = seen.get(value);
3361
+ if (previous !== undefined) {
3362
+ return previous;
3363
+ }
3364
+ if (Array.isArray(value)) {
3365
+ seen.set(value, value);
3366
+ for (let i = 0;i < value.length; i += 1) {
3367
+ value[i] = hydrateRscDescriptors(value[i], sources, seen);
3368
+ }
3369
+ return value;
3370
+ }
3371
+ if (!isPlainObject3(value)) {
3372
+ return value;
3373
+ }
3374
+ seen.set(value, value);
3375
+ for (const [key, entry] of Object.entries(value)) {
3376
+ Reflect.set(value, key, hydrateRscDescriptors(entry, sources, seen));
3377
+ }
3378
+ return value;
3379
+ }
3380
+ function collectRscDescriptorIds(value, ids, seen = new WeakSet) {
3381
+ if (value === null || typeof value !== "object") {
3382
+ return;
3383
+ }
3384
+ if (seen.has(value)) {
3385
+ return;
3386
+ }
3387
+ seen.add(value);
3388
+ if (isPlainObject3(value) && typeof value.__furinRsc === "string") {
3389
+ ids.add(value.__furinRsc);
3390
+ return;
3391
+ }
3392
+ for (const entry of Array.isArray(value) ? value : Object.values(value)) {
3393
+ collectRscDescriptorIds(entry, ids, seen);
3394
+ }
3395
+ }
3396
+ async function parseRouteFrameLines(firstLine, readLine) {
3397
+ let byteLength = 0;
3398
+ let dataValue;
3399
+ const pending = new Map;
3400
+ const sources = new Map;
3401
+ const deferredPromises = {};
3402
+ const resolvers = new Map;
3403
+ const rejectPending = (reason) => {
3404
+ for (const resolver of resolvers.values()) {
3405
+ resolver.reject(reason);
3406
+ }
3407
+ resolvers.clear();
3408
+ };
3409
+ const deferredRscValues = new Map;
3410
+ const tryResolveDeferredRscValues = () => {
3411
+ for (const [key, deferred] of deferredRscValues) {
3412
+ if ([...deferred.ids].some((id) => !sources.has(id))) {
3413
+ continue;
3414
+ }
3415
+ resolvers.get(key)?.resolve(hydrateRscDescriptors(deferred.value, sources));
3416
+ resolvers.delete(key);
3417
+ deferredRscValues.delete(key);
3418
+ }
3419
+ };
3420
+ const processLine = (line) => {
3421
+ byteLength += new TextEncoder().encode(line).byteLength + 1;
3422
+ if (byteLength > MAX_ROUTE_FRAME_STREAM_BYTES) {
3423
+ throw new Error(`[furin] route frame stream exceeds the ${MAX_ROUTE_FRAME_STREAM_BYTES}-byte limit`);
3424
+ }
3425
+ const envelope = JSON.parse(line);
3426
+ if (envelope.__furinRouteFrame !== FRAME_VERSION) {
3427
+ throw new Error("[furin] unsupported route frame version");
3428
+ }
3429
+ const { frame } = envelope;
3430
+ if (frame.type === "data") {
3431
+ dataValue = fromCrossJSON(frame.value, {});
3432
+ for (const key of frame.deferredKeys) {
3433
+ deferredPromises[key] = new Promise((resolve, reject) => {
3434
+ resolvers.set(key, { reject, resolve });
3435
+ });
3436
+ deferredPromises[key]?.catch(() => {
3437
+ return;
3438
+ });
3439
+ }
3440
+ } else if (frame.type === "rsc-start") {
3441
+ pending.set(frame.id, { chunks: [], kind: frame.kind });
3442
+ } else if (frame.type === "rsc-chunk") {
3443
+ const source = pending.get(frame.id);
3444
+ if (source === undefined) {
3445
+ throw new Error(`[furin] RSC chunk received before start for "${frame.id}"`);
3446
+ }
3447
+ source.chunks.push(frameValueToBytes(frame.value));
3448
+ } else if (frame.type === "rsc-end") {
3449
+ const source = pending.get(frame.id);
3450
+ if (source === undefined) {
3451
+ throw new Error(`[furin] RSC end received before start for "${frame.id}"`);
3452
+ }
3453
+ const length = source.chunks.reduce((total, chunk) => total + chunk.byteLength, 0);
3454
+ const bytes = new Uint8Array(length);
3455
+ let offset = 0;
3456
+ for (const chunk of source.chunks) {
3457
+ bytes.set(chunk, offset);
3458
+ offset += chunk.byteLength;
3459
+ }
3460
+ sources.set(frame.id, restoreRscSource(source.kind, bytes));
3461
+ pending.delete(frame.id);
3462
+ tryResolveDeferredRscValues();
3463
+ } else if (frame.type === "rsc-error") {
3464
+ throw new Error(`[furin] RSC stream failed (${frame.digest})`);
3465
+ } else if (frame.type === "defer-resolve") {
3466
+ const value = fromCrossJSON(frame.value, {});
3467
+ const ids = new Set;
3468
+ collectRscDescriptorIds(value, ids);
3469
+ if ([...ids].some((id) => !sources.has(id))) {
3470
+ deferredRscValues.set(frame.key, { ids, value });
3471
+ } else {
3472
+ resolvers.get(frame.key)?.resolve(hydrateRscDescriptors(value, sources));
3473
+ resolvers.delete(frame.key);
3474
+ }
3475
+ } else if (frame.type === "defer-reject") {
3476
+ resolvers.get(frame.key)?.reject(fromCrossJSON(frame.value, {}));
3477
+ resolvers.delete(frame.key);
3478
+ }
3479
+ };
3480
+ processLine(firstLine);
3481
+ if (dataValue === undefined) {
3482
+ throw new Error("[furin] route frame stream has no data frame");
3483
+ }
3484
+ const expectedSources = new Set;
3485
+ collectRscDescriptorIds(dataValue, expectedSources);
3486
+ while ([...expectedSources].some((id) => !sources.has(id))) {
3487
+ const line = await readLine();
3488
+ if (line === undefined) {
3489
+ throw new Error("[furin] route frame stream ended before an RSC source completed");
3490
+ }
3491
+ processLine(line);
3492
+ }
3493
+ const data = hydrateRscDescriptors(dataValue, sources);
3494
+ if (data === null || typeof data !== "object" || Array.isArray(data)) {
3495
+ throw new Error("[furin] route data frame must decode to an object");
3496
+ }
3497
+ const completion = (async () => {
3498
+ for (;; ) {
3499
+ const line = await readLine();
3500
+ if (line === undefined) {
3501
+ break;
3502
+ }
3503
+ processLine(line);
3504
+ }
3505
+ if (pending.size > 0) {
3506
+ throw new Error("[furin] route frame stream ended before an RSC source completed");
3507
+ }
3508
+ if (deferredRscValues.size > 0) {
3509
+ throw new Error("[furin] route frame stream ended before an RSC source completed");
3510
+ }
3511
+ for (const [key, resolver] of resolvers) {
3512
+ resolver.reject(new Error(`[furin] deferred stream closed before "${key}" was resolved`));
3513
+ }
3514
+ resolvers.clear();
3515
+ })().catch((error) => {
3516
+ rejectPending(error);
3517
+ throw error;
3518
+ });
3519
+ return {
3520
+ abort: rejectPending,
3521
+ completion,
3522
+ deferredPromises,
3523
+ syncData: data
3524
+ };
3525
+ }
3526
+
3195
3527
  // src/shared/deferred-ndjson.ts
3196
3528
  function makeAbortError(reason) {
3197
3529
  const message = reason instanceof Error ? reason.message || "The operation was aborted." : "aborted";
@@ -3213,7 +3545,7 @@ async function parseDeferredNdjson(stream, signal) {
3213
3545
  try {
3214
3546
  reader.releaseLock();
3215
3547
  } catch {}
3216
- return { syncData: {}, deferredPromises: {} };
3548
+ return { deferredPromises: {}, syncData: {} };
3217
3549
  }
3218
3550
  if (signal !== undefined && !signal.aborted) {
3219
3551
  abortHandler = () => cancelReader(makeAbortError(signal.reason));
@@ -3253,7 +3585,30 @@ async function parseDeferredNdjson(stream, signal) {
3253
3585
  try {
3254
3586
  reader.releaseLock();
3255
3587
  } catch {}
3256
- return { syncData: {}, deferredPromises: {} };
3588
+ return { deferredPromises: {}, syncData: {} };
3589
+ }
3590
+ if (isRouteFrameLine(firstLine)) {
3591
+ const result = await parseRouteFrameLines(firstLine, readLine);
3592
+ if (signal !== undefined) {
3593
+ cleanupAbortHandler();
3594
+ abortHandler = () => {
3595
+ const error = makeAbortError(signal.reason);
3596
+ result.abort(error);
3597
+ cancelReader(error);
3598
+ };
3599
+ if (signal.aborted) {
3600
+ abortHandler();
3601
+ } else {
3602
+ signal.addEventListener("abort", abortHandler, { once: true });
3603
+ }
3604
+ }
3605
+ result.completion.finally(() => {
3606
+ cleanupAbortHandler();
3607
+ try {
3608
+ reader.releaseLock();
3609
+ } catch {}
3610
+ });
3611
+ return { deferredPromises: result.deferredPromises, syncData: result.syncData };
3257
3612
  }
3258
3613
  const node = JSON.parse(firstLine);
3259
3614
  const deserialized = fromCrossJSON(node, {});
@@ -3274,7 +3629,7 @@ async function parseDeferredNdjson(stream, signal) {
3274
3629
  for (const key of deferredKeys) {
3275
3630
  if (!(key in deferredPromises)) {
3276
3631
  deferredPromises[key] = new Promise((resolve, reject) => {
3277
- resolvers[key] = { resolve, reject };
3632
+ resolvers[key] = { reject, resolve };
3278
3633
  });
3279
3634
  }
3280
3635
  }
@@ -3288,7 +3643,7 @@ async function parseDeferredNdjson(stream, signal) {
3288
3643
  try {
3289
3644
  reader.releaseLock();
3290
3645
  } catch {}
3291
- return { syncData, deferredPromises };
3646
+ return { deferredPromises, syncData };
3292
3647
  }
3293
3648
  const rejectAllPending = (reason) => {
3294
3649
  for (const key of Object.keys(resolvers)) {
@@ -3300,7 +3655,7 @@ async function parseDeferredNdjson(stream, signal) {
3300
3655
  if (signal !== undefined) {
3301
3656
  if (signal.aborted) {
3302
3657
  rejectAllPending(makeAbortError(signal.reason));
3303
- return { syncData, deferredPromises };
3658
+ return { deferredPromises, syncData };
3304
3659
  }
3305
3660
  cleanupAbortHandler();
3306
3661
  abortHandler = () => {
@@ -3324,7 +3679,7 @@ async function parseDeferredNdjson(stream, signal) {
3324
3679
  reader.releaseLock();
3325
3680
  } catch {}
3326
3681
  });
3327
- return { syncData, deferredPromises };
3682
+ return { deferredPromises, syncData };
3328
3683
  }
3329
3684
  async function readDeferredLines(readLine, resolvers) {
3330
3685
  for (;; ) {
@@ -3382,7 +3737,7 @@ function createSearchStore(initialSnapshot) {
3382
3737
  return;
3383
3738
  }
3384
3739
  snapshot = next;
3385
- version++;
3740
+ version += 1;
3386
3741
  },
3387
3742
  subscribe: (listener) => {
3388
3743
  listeners.add(listener);
@@ -3404,6 +3759,9 @@ var FALLBACK_SEARCH_STORE = createSearchStore({
3404
3759
  currentHref: "/",
3405
3760
  navigate: (href, _opts) => {
3406
3761
  if (typeof window !== "undefined") {
3762
+ if (navigationHrefPolicy(href, window.location.origin) === "blocked") {
3763
+ return Promise.reject(new Error("[furin] Unsafe navigation URL."));
3764
+ }
3407
3765
  window.location.href = href;
3408
3766
  }
3409
3767
  return Promise.resolve();
@@ -3414,7 +3772,7 @@ var FALLBACK_SEARCH_STORE = createSearchStore({
3414
3772
  var SearchStoreContext = createContext2(null);
3415
3773
 
3416
3774
  // src/client/router/spa-response.ts
3417
- import { createElement as createElement2 } from "react";
3775
+ import { createElement as createElement3 } from "react";
3418
3776
  function isFurinErrorPayload(value) {
3419
3777
  if (!value || typeof value !== "object") {
3420
3778
  return false;
@@ -3427,11 +3785,11 @@ function classifySpaResponse(status, data) {
3427
3785
  return { kind: "bail" };
3428
3786
  }
3429
3787
  if (isFurinErrorPayload(data.__furinError)) {
3430
- return { kind: "error", error: data.__furinError };
3788
+ return { error: data.__furinError, kind: "error" };
3431
3789
  }
3432
3790
  if ((status >= 200 && status < 300 || status === 404) && data.__furinStatus === 404) {
3433
3791
  const notFound = data.__furinNotFound;
3434
- return { kind: "not-found", error: notFound ?? {} };
3792
+ return { error: notFound ?? {}, kind: "not-found" };
3435
3793
  }
3436
3794
  if (status >= 200 && status < 300) {
3437
3795
  return { kind: "ok" };
@@ -3442,18 +3800,17 @@ function pickDeepestNotFound(boundaries) {
3442
3800
  if (!boundaries) {
3443
3801
  return;
3444
3802
  }
3445
- for (let i = boundaries.length - 1;i >= 0; i--) {
3803
+ for (let i = boundaries.length - 1;i >= 0; i -= 1) {
3446
3804
  const seg = boundaries[i];
3447
3805
  if (seg?.notFound) {
3448
3806
  return seg.notFound;
3449
3807
  }
3450
3808
  }
3451
- return;
3452
3809
  }
3453
- var DefaultClientNotFoundFallback = ({ error }) => createElement2(DefaultNotFoundScreen, { message: error.message });
3810
+ var DefaultClientNotFoundFallback = ({ error }) => createElement3(DefaultNotFoundScreen, { message: error.message });
3454
3811
  function buildNotFoundPageElement(boundaries, error) {
3455
3812
  const Fallback = pickDeepestNotFound(boundaries) ?? DefaultClientNotFoundFallback;
3456
- return createElement2(Fallback, { error });
3813
+ return createElement3(Fallback, { error });
3457
3814
  }
3458
3815
  async function parsePageResponse(res, basePath) {
3459
3816
  let finalHref;
@@ -3538,10 +3895,6 @@ function createSyncCatchUp(options) {
3538
3895
  } while (requested);
3539
3896
  };
3540
3897
  return {
3541
- async initialize() {
3542
- const page = await options.fetchPage(undefined);
3543
- currentCursor = page.cursor;
3544
- },
3545
3898
  catchUp() {
3546
3899
  requested = true;
3547
3900
  if (!running) {
@@ -3551,13 +3904,21 @@ function createSyncCatchUp(options) {
3551
3904
  }
3552
3905
  return running;
3553
3906
  },
3554
- cursor: () => currentCursor
3907
+ cursor: () => currentCursor,
3908
+ async initialize() {
3909
+ const page = await options.fetchPage(undefined);
3910
+ currentCursor = page.cursor;
3911
+ }
3555
3912
  };
3556
3913
  }
3557
3914
 
3558
3915
  // src/client/router/provider.tsx
3559
3916
  import { jsxDEV as jsxDEV4 } from "react/jsx-dev-runtime";
3560
3917
  var EMPTY_SEARCH = {};
3918
+ function getHistoryStateObject() {
3919
+ const value = history.state;
3920
+ return value !== null && typeof value === "object" ? value : {};
3921
+ }
3561
3922
  function setPrefetchCacheEntry(cache, href, entry, maxSize) {
3562
3923
  if (cache.has(href)) {
3563
3924
  cache.delete(href);
@@ -3586,8 +3947,8 @@ function RouterProvider({
3586
3947
  syncStream
3587
3948
  }) {
3588
3949
  const [state, setState] = useState(() => ({
3589
- match: initialMatch,
3590
3950
  data: initialData,
3951
+ match: initialMatch,
3591
3952
  notFound: initialNotFound
3592
3953
  }));
3593
3954
  const [isNavigating, setIsNavigating] = useState(false);
@@ -3602,9 +3963,8 @@ function RouterProvider({
3602
3963
  const navAbortRef = useRef(null);
3603
3964
  const pendingScrollRef = useRef(null);
3604
3965
  const currentMatchRef = useRef(initialMatch);
3605
- const staticModeRef = useRef(detectStaticMode());
3966
+ const [staticMode] = useState(detectStaticMode);
3606
3967
  const resolvedSearch = state.data.query ?? EMPTY_SEARCH;
3607
- const searchStoreRef = useRef(null);
3608
3968
  const rootBoundaries = useMemo(() => {
3609
3969
  for (const route of routes) {
3610
3970
  const depth0 = route.segmentBoundaries?.find((b) => b.depth === 0);
@@ -3612,7 +3972,6 @@ function RouterProvider({
3612
3972
  return [depth0];
3613
3973
  }
3614
3974
  }
3615
- return;
3616
3975
  }, [routes]);
3617
3976
  const resolveNoMatchState = useCallback2(async (physicalHref, signal) => {
3618
3977
  const res = await fetch(physicalHref, { signal });
@@ -3627,12 +3986,12 @@ function RouterProvider({
3627
3986
  }
3628
3987
  const { __furinStatus: _s, __furinNotFound: _n, ...cleanData } = data ?? {};
3629
3988
  return {
3630
- match: currentMatchRef.current,
3631
3989
  data: cleanData,
3632
- title,
3633
3990
  finalHref,
3991
+ match: currentMatchRef.current,
3634
3992
  notFound: kind.error,
3635
- notFoundBoundaries: rootBoundaries
3993
+ notFoundBoundaries: rootBoundaries,
3994
+ title
3636
3995
  };
3637
3996
  }, [basePath, rootBoundaries]);
3638
3997
  const fetchPageState = useCallback2(async (rawLogicalHref, signal) => {
@@ -3645,7 +4004,7 @@ function RouterProvider({
3645
4004
  if (!match) {
3646
4005
  return await resolveNoMatchState(physicalHref, signal);
3647
4006
  }
3648
- const dataEndpoint = buildDataEndpoint(basePath, logicalHref, staticModeRef.current);
4007
+ const dataEndpoint = buildDataEndpoint(basePath, logicalHref, staticMode);
3649
4008
  const [res, loadedMod] = await Promise.all([fetch(dataEndpoint, { signal }), match.load()]);
3650
4009
  if (isStaleDeployResponse(res)) {
3651
4010
  window.location.href = physicalHref;
@@ -3658,9 +4017,9 @@ function RouterProvider({
3658
4017
  } catch (parseErr) {
3659
4018
  _log.warn({
3660
4019
  action: "navigate_server_error",
4020
+ error: String(parseErr),
3661
4021
  href: physicalHref,
3662
- status: res.status,
3663
- error: String(parseErr)
4022
+ status: res.status
3664
4023
  });
3665
4024
  return null;
3666
4025
  }
@@ -3684,11 +4043,11 @@ function RouterProvider({
3684
4043
  };
3685
4044
  if (__furinError) {
3686
4045
  return {
3687
- match: loadedMatch,
3688
4046
  data: {},
3689
- title,
4047
+ error: __furinError,
3690
4048
  finalHref,
3691
- error: __furinError
4049
+ match: loadedMatch,
4050
+ title
3692
4051
  };
3693
4052
  }
3694
4053
  if (!res.ok && res.status !== 404) {
@@ -3696,24 +4055,25 @@ function RouterProvider({
3696
4055
  return null;
3697
4056
  }
3698
4057
  if (__furinStatus === 404) {
4058
+ const notFound = __furinNotFound !== null && typeof __furinNotFound === "object" ? __furinNotFound : {};
3699
4059
  return {
3700
- match: loadedMatch,
3701
4060
  data,
3702
- title,
3703
4061
  finalHref,
3704
- notFound: __furinNotFound ?? {}
4062
+ match: loadedMatch,
4063
+ notFound,
4064
+ title
3705
4065
  };
3706
4066
  }
3707
4067
  if (finalHref) {
3708
- return { match: null, data, title, finalHref };
4068
+ return { data, finalHref, match: null, title };
3709
4069
  }
3710
- return { match: loadedMatch, data, title, finalHref };
4070
+ return { data, finalHref, match: loadedMatch, title };
3711
4071
  } catch (err) {
3712
4072
  if (!isAbortError(err)) {
3713
4073
  _log.error({
3714
4074
  action: "navigate_failed",
3715
- href: basePath + logicalHref,
3716
- error: String(err)
4075
+ error: String(err),
4076
+ href: basePath + logicalHref
3717
4077
  });
3718
4078
  }
3719
4079
  return null;
@@ -3744,22 +4104,23 @@ function RouterProvider({
3744
4104
  return;
3745
4105
  }
3746
4106
  setPrefetchCacheEntry(prefetchCache.current, href, {
3747
- promise: fetchPageState(href, undefined),
3748
4107
  createdAt: Date.now(),
4108
+ promise: fetchPageState(href, undefined),
3749
4109
  staleTime
3750
4110
  }, prefetchCacheSize);
3751
4111
  }, [fetchPageState, defaultPreloadStaleTime, prefetchCacheSize]);
3752
4112
  async function resolveRedirectState(redirectLogical, myVersion, signal) {
3753
4113
  const cached = prefetchCache.current.get(redirectLogical);
3754
- const state2 = cached && !shouldRefetch(cached) ? await cached.promise : await fetchPageState(redirectLogical, signal);
4114
+ const redirectState = cached && !shouldRefetch(cached) ? await cached.promise : await fetchPageState(redirectLogical, signal);
3755
4115
  if (navVersion.current !== myVersion) {
3756
4116
  return null;
3757
4117
  }
3758
- return state2;
4118
+ return redirectState;
3759
4119
  }
3760
4120
  const navigate = useCallback2(async function navigateTo(rawLogicalHref, opts) {
3761
4121
  const logicalHref = normalizeHref(rawLogicalHref);
3762
- const myVersion = ++navVersion.current;
4122
+ navVersion.current += 1;
4123
+ const myVersion = navVersion.current;
3763
4124
  navAbortRef.current?.abort();
3764
4125
  const navAbort = new AbortController;
3765
4126
  navAbortRef.current = navAbort;
@@ -3773,8 +4134,8 @@ function RouterProvider({
3773
4134
  }
3774
4135
  if (newState && (!cached || shouldRefetch(cached))) {
3775
4136
  setPrefetchCacheEntry(prefetchCache.current, logicalHref, {
3776
- promise: Promise.resolve(newState),
3777
4137
  createdAt: Date.now(),
4138
+ promise: Promise.resolve(newState),
3778
4139
  staleTime: defaultPreloadStaleTime
3779
4140
  }, prefetchCacheSize);
3780
4141
  }
@@ -3792,7 +4153,7 @@ function RouterProvider({
3792
4153
  redirectLogical = normalizeHref(newState.finalHref);
3793
4154
  const redirectPhysical = basePath + redirectLogical;
3794
4155
  window.history.replaceState({
3795
- ...history.state ?? {},
4156
+ ...getHistoryStateObject(),
3796
4157
  _furinKey: getHistoryKey(history.state) ?? generateHistoryKey()
3797
4158
  }, "", redirectPhysical);
3798
4159
  setCurrentHref(redirectLogical);
@@ -3814,7 +4175,7 @@ function RouterProvider({
3814
4175
  const physicalEffective = basePath + effectiveLogical;
3815
4176
  if (opts?.replace) {
3816
4177
  window.history.replaceState({
3817
- ...history.state ?? {},
4178
+ ...getHistoryStateObject(),
3818
4179
  _furinKey: getHistoryKey(history.state) ?? generateHistoryKey()
3819
4180
  }, "", physicalEffective);
3820
4181
  } else {
@@ -3828,7 +4189,7 @@ function RouterProvider({
3828
4189
  const logicalPath = normalizeHref(toLogical(effectiveUrl.pathname, basePath));
3829
4190
  setCurrentHref(logicalPath + effectiveUrl.search);
3830
4191
  if (opts?.resetScroll ?? true) {
3831
- pendingScrollRef.current = { type: "reset", href: physicalEffective };
4192
+ pendingScrollRef.current = { href: physicalEffective, type: "reset" };
3832
4193
  }
3833
4194
  } finally {
3834
4195
  if (navVersion.current === myVersion) {
@@ -3836,15 +4197,12 @@ function RouterProvider({
3836
4197
  }
3837
4198
  }
3838
4199
  }, [basePath, fetchPageState, defaultPreloadStaleTime, prefetchCacheSize]);
3839
- if (searchStoreRef.current === null) {
3840
- searchStoreRef.current = createSearchStore({
3841
- currentHref,
3842
- navigate,
3843
- search: resolvedSearch,
3844
- searchRoutes: routes
3845
- });
3846
- }
3847
- const searchStore = searchStoreRef.current;
4200
+ const [searchStore] = useState(() => createSearchStore({
4201
+ currentHref,
4202
+ navigate,
4203
+ search: resolvedSearch,
4204
+ searchRoutes: routes
4205
+ }));
3848
4206
  const searchSnapshot = useMemo(() => ({
3849
4207
  currentHref,
3850
4208
  navigate,
@@ -3879,7 +4237,8 @@ function RouterProvider({
3879
4237
  const destKey = getHistoryKey(history.state);
3880
4238
  const logicalPath = normalizeHref(toLogical(window.location.pathname, basePath));
3881
4239
  const logicalHref = logicalPath + window.location.search;
3882
- const myVersion = ++navVersion.current;
4240
+ navVersion.current += 1;
4241
+ const myVersion = navVersion.current;
3883
4242
  navAbortRef.current?.abort();
3884
4243
  const navAbort = new AbortController;
3885
4244
  navAbortRef.current = navAbort;
@@ -3931,9 +4290,9 @@ function RouterProvider({
3931
4290
  }
3932
4291
  setCurrentHref(normalizeHref(effectiveLogical));
3933
4292
  if (destKey) {
3934
- pendingScrollRef.current = { type: "restore", key: destKey };
4293
+ pendingScrollRef.current = { key: destKey, type: "restore" };
3935
4294
  } else {
3936
- window.scrollTo({ top: 0, behavior: "instant" });
4295
+ window.scrollTo({ behavior: "instant", top: 0 });
3937
4296
  }
3938
4297
  } finally {
3939
4298
  if (navVersion.current === myVersion) {
@@ -3945,7 +4304,7 @@ function RouterProvider({
3945
4304
  useEffect(() => {
3946
4305
  history.scrollRestoration = "manual";
3947
4306
  if (!getHistoryKey(history.state)) {
3948
- history.replaceState({ ...history.state ?? {}, _furinKey: generateHistoryKey() }, "");
4307
+ history.replaceState({ ...getHistoryStateObject(), _furinKey: generateHistoryKey() }, "");
3949
4308
  }
3950
4309
  }, []);
3951
4310
  useLayoutEffect(() => {
@@ -3959,21 +4318,21 @@ function RouterProvider({
3959
4318
  const raw = sessionStorage.getItem(SCROLL_STORAGE_KEY);
3960
4319
  const positions = raw ? JSON.parse(raw) : {};
3961
4320
  const y = positions[instruction.key] ?? 0;
3962
- window.scrollTo({ top: y, behavior: "instant" });
4321
+ window.scrollTo({ behavior: "instant", top: y });
3963
4322
  } catch {
3964
- window.scrollTo({ top: 0, behavior: "instant" });
4323
+ window.scrollTo({ behavior: "instant", top: 0 });
3965
4324
  }
3966
4325
  return;
3967
4326
  }
3968
4327
  const destUrl = new URL(instruction.href, window.location.origin);
3969
4328
  if (destUrl.hash) {
3970
- const id = decodeURIComponent(destUrl.hash.slice(1));
4329
+ const id = decodeHashFragment(destUrl.hash.slice(1));
3971
4330
  const element = document.getElementById(id);
3972
4331
  if (element) {
3973
4332
  element.scrollIntoView({ behavior: "instant", block: "start" });
3974
4333
  }
3975
4334
  } else {
3976
- window.scrollTo({ top: 0, behavior: "instant" });
4335
+ window.scrollTo({ behavior: "instant", top: 0 });
3977
4336
  }
3978
4337
  }, [currentHref]);
3979
4338
  useEffect(() => {
@@ -3999,12 +4358,17 @@ function RouterProvider({
3999
4358
  if (logicalHref === null) {
4000
4359
  return;
4001
4360
  }
4361
+ const logicalPathname = new URL(logicalHref, window.location.origin).pathname;
4362
+ const hasConcreteMatch = routes.some((route) => !route.pattern.split("/").includes("*") && route.regex.test(logicalPathname));
4363
+ if (!hasConcreteMatch) {
4364
+ return;
4365
+ }
4002
4366
  e.preventDefault();
4003
4367
  navigate(logicalHref, { resetScroll: !logicalHref.includes("#") });
4004
4368
  };
4005
4369
  document.addEventListener("click", handler);
4006
4370
  return () => document.removeEventListener("click", handler);
4007
- }, [navigate, basePath]);
4371
+ }, [navigate, basePath, routes]);
4008
4372
  useEffect(() => {
4009
4373
  if (typeof window === "undefined") {
4010
4374
  return;
@@ -4012,6 +4376,9 @@ function RouterProvider({
4012
4376
  const originalFetch = window.fetch;
4013
4377
  const wrapped = async (...args) => {
4014
4378
  const response = await originalFetch.apply(window, args);
4379
+ if (!isSameOriginFetchResult(args[0], response.url, window.location.origin)) {
4380
+ return response;
4381
+ }
4015
4382
  const invalidated = [];
4016
4383
  applyRevalidateHeader(response.headers, (path, type) => {
4017
4384
  const resolvedType = type ?? "page";
@@ -4080,6 +4447,7 @@ function RouterProvider({
4080
4447
  }
4081
4448
  });
4082
4449
  };
4450
+ const onOpen = () => recover();
4083
4451
  const onSync = (event) => {
4084
4452
  try {
4085
4453
  const payload = JSON.parse(event.data);
@@ -4097,6 +4465,7 @@ function RouterProvider({
4097
4465
  return;
4098
4466
  }
4099
4467
  source = new EventSource(streamUrl);
4468
+ source.addEventListener("open", onOpen);
4100
4469
  source.addEventListener("furin.sync", onSync);
4101
4470
  };
4102
4471
  catchUp.initialize().then(() => {
@@ -4104,7 +4473,6 @@ function RouterProvider({
4104
4473
  return;
4105
4474
  }
4106
4475
  connect();
4107
- recover();
4108
4476
  }).catch((error) => {
4109
4477
  if (disposed) {
4110
4478
  return;
@@ -4114,6 +4482,7 @@ function RouterProvider({
4114
4482
  });
4115
4483
  return () => {
4116
4484
  disposed = true;
4485
+ source?.removeEventListener("open", onOpen);
4117
4486
  source?.removeEventListener("furin.sync", onSync);
4118
4487
  source?.close();
4119
4488
  };
@@ -4136,16 +4505,16 @@ function RouterProvider({
4136
4505
  children: buildRouterTree({
4137
4506
  basePath,
4138
4507
  currentHref,
4139
- search: resolvedSearch,
4140
- searchRoutes: routes,
4508
+ defaultPreload,
4509
+ defaultPreloadDelay,
4510
+ defaultPreloadStaleTime,
4511
+ invalidatePrefetch,
4512
+ isNavigating,
4141
4513
  navigate,
4142
4514
  prefetch,
4143
4515
  refresh,
4144
- invalidatePrefetch,
4145
- isNavigating,
4146
- defaultPreload,
4147
- defaultPreloadDelay,
4148
- defaultPreloadStaleTime
4516
+ search: resolvedSearch,
4517
+ searchRoutes: routes
4149
4518
  }, pageElement, {
4150
4519
  digest: initialDigest,
4151
4520
  onReset: () => {
@@ -4170,14 +4539,18 @@ function computeLinkView({
4170
4539
  const logicalHref = buildHref(to, search, hash, searchDefaults);
4171
4540
  const logicalHrefWithoutHash = buildHref(to, search, undefined, searchDefaults);
4172
4541
  const isAbsolute = logicalHref.startsWith("http://") || logicalHref.startsWith("https://") || logicalHref.startsWith("//");
4173
- const href = isAbsolute ? logicalHref : router2.basePath + logicalHref;
4542
+ const candidateHref = isAbsolute ? logicalHref : router2.basePath + logicalHref;
4543
+ const href = navigationHrefPolicy(candidateHref, undefined) === "blocked" ? "#" : candidateHref;
4174
4544
  const isActive = !isAbsolute && router2.currentHref === normalizeHref(logicalHrefWithoutHash);
4175
4545
  const resolvedChildren = typeof children === "function" ? children({ isActive }) : children;
4176
4546
  const extraProps = {
4177
4547
  ...inactiveProps && !isActive ? inactiveProps() : {},
4178
4548
  ...activeProps ? activeProps({ isActive }) : {}
4179
4549
  };
4180
- return { logicalHref, href, isActive, resolvedChildren, extraProps };
4550
+ return { extraProps, href, isActive, logicalHref, resolvedChildren };
4551
+ }
4552
+ function isSameOriginUrl(url) {
4553
+ return navigationHrefPolicy(url, window.location.origin) === "internal";
4181
4554
  }
4182
4555
  function LinkInteractive({
4183
4556
  to,
@@ -4202,7 +4575,7 @@ function LinkInteractive({
4202
4575
  const router2 = useRouter();
4203
4576
  const anchorRef = useRef2(null);
4204
4577
  const intentTimerRef = useRef2(null);
4205
- const { logicalHref, href, isActive, resolvedChildren, extraProps } = computeLinkView({ to, search, hash, children, activeProps, inactiveProps }, router2);
4578
+ const { logicalHref, href, isActive, resolvedChildren, extraProps } = computeLinkView({ activeProps, children, hash, inactiveProps, search, to }, router2);
4206
4579
  const effectivePreload = preload ?? router2.defaultPreload;
4207
4580
  const effectiveDelay = preloadDelay ?? router2.defaultPreloadDelay;
4208
4581
  const effectiveStaleTime = preloadStaleTime ?? router2.defaultPreloadStaleTime;
@@ -4234,13 +4607,6 @@ function LinkInteractive({
4234
4607
  intentTimerRef.current = null;
4235
4608
  }
4236
4609
  }, []);
4237
- const isInternal = (url) => {
4238
- try {
4239
- return new URL(url, window.location.origin).origin === window.location.origin;
4240
- } catch {
4241
- return false;
4242
- }
4243
- };
4244
4610
  const handleClick = (e) => {
4245
4611
  onClick?.(e);
4246
4612
  if (e.defaultPrevented) {
@@ -4256,7 +4622,11 @@ function LinkInteractive({
4256
4622
  if (anchorProps.target && anchorProps.target !== "_self") {
4257
4623
  return;
4258
4624
  }
4259
- if (!isInternal(href)) {
4625
+ if (navigationHrefPolicy(logicalHref, window.location.origin) === "blocked") {
4626
+ e.preventDefault();
4627
+ return;
4628
+ }
4629
+ if (!isSameOriginUrl(href)) {
4260
4630
  return;
4261
4631
  }
4262
4632
  e.preventDefault();
@@ -4268,7 +4638,7 @@ function LinkInteractive({
4268
4638
  };
4269
4639
  const handleMouseEnter = (e) => {
4270
4640
  onMouseEnter?.(e);
4271
- if (!disabled && effectivePreload === "intent" && isInternal(href)) {
4641
+ if (!disabled && effectivePreload === "intent" && isSameOriginUrl(href)) {
4272
4642
  intentTimerRef.current = setTimeout(triggerPrefetch, effectiveDelay);
4273
4643
  }
4274
4644
  };
@@ -4281,18 +4651,18 @@ function LinkInteractive({
4281
4651
  };
4282
4652
  const handleFocus = (e) => {
4283
4653
  onFocus?.(e);
4284
- if (!disabled && effectivePreload === "intent" && isInternal(href)) {
4654
+ if (!disabled && effectivePreload === "intent" && isSameOriginUrl(href)) {
4285
4655
  triggerPrefetch();
4286
4656
  }
4287
4657
  };
4288
- return createElement3("a", {
4289
- ref: anchorRef,
4290
- href,
4658
+ return createElement4("a", {
4291
4659
  "data-furin-link": true,
4660
+ href,
4292
4661
  onClick: handleClick,
4662
+ onFocus: handleFocus,
4293
4663
  onMouseEnter: handleMouseEnter,
4294
4664
  onMouseLeave: handleMouseLeave,
4295
- onFocus: handleFocus,
4665
+ ref: anchorRef,
4296
4666
  ...isActive ? { "data-status": "active" } : {},
4297
4667
  ...anchorProps,
4298
4668
  ...extraProps,
@@ -4302,16 +4672,16 @@ function LinkInteractive({
4302
4672
  var SSR_FALLBACK_ROUTER = {
4303
4673
  basePath: "",
4304
4674
  currentHref: "/",
4305
- search: {},
4306
- searchRoutes: [],
4675
+ defaultPreload: "intent",
4676
+ defaultPreloadDelay: 50,
4677
+ defaultPreloadStaleTime: 30000,
4678
+ invalidatePrefetch: (_path, _type) => {},
4679
+ isNavigating: false,
4307
4680
  navigate: (_href, _opts) => Promise.resolve(),
4308
4681
  prefetch: (_href, _opts) => {},
4309
- invalidatePrefetch: (_path, _type) => {},
4310
4682
  refresh: (_opts) => Promise.resolve(),
4311
- isNavigating: false,
4312
- defaultPreload: "intent",
4313
- defaultPreloadDelay: 50,
4314
- defaultPreloadStaleTime: 30000
4683
+ search: {},
4684
+ searchRoutes: []
4315
4685
  };
4316
4686
  function renderLinkElement(props, router2) {
4317
4687
  const { href, isActive, resolvedChildren, extraProps } = computeLinkView(props, router2);
@@ -4335,9 +4705,9 @@ function renderLinkElement(props, router2) {
4335
4705
  href: _href,
4336
4706
  ...anchorProps
4337
4707
  } = props;
4338
- return createElement3("a", {
4339
- href,
4708
+ return createElement4("a", {
4340
4709
  "data-furin-link": true,
4710
+ href,
4341
4711
  ...isActive ? { "data-status": "active" } : {},
4342
4712
  ...anchorProps,
4343
4713
  ...extraProps,
@@ -4346,46 +4716,50 @@ function renderLinkElement(props, router2) {
4346
4716
  }
4347
4717
  function Link(props) {
4348
4718
  if (typeof window === "undefined") {
4349
- return createElement3(RouterContext.Consumer, {
4719
+ return createElement4(RouterContext.Consumer, {
4350
4720
  children: (routerCtx) => renderLinkElement(props, routerCtx ?? SSR_FALLBACK_ROUTER)
4351
4721
  });
4352
4722
  }
4353
- return createElement3(LinkInteractive, props);
4723
+ return createElement4(LinkInteractive, props);
4354
4724
  }
4355
4725
  export {
4356
- useRouter,
4357
- useNavigate,
4358
- toLogical,
4359
- stripHashFromHref,
4360
- shouldRefetch,
4361
- shouldInterceptClick,
4362
- shouldAutoRefreshPath,
4363
- searchSnapshotFromRouterContext,
4364
- saveScrollPosition,
4365
- pickDeepestNotFound,
4366
- parsePageResponse,
4367
- normalizePath,
4368
- normalizeHref,
4369
- isStaleDeployResponse,
4370
- getHistoryKey,
4371
- generateHistoryKey,
4372
- fromCrossJSON,
4373
- detectStaticMode,
4374
- createSearchStore,
4375
- classifySpaResponse,
4376
- buildRouterTree,
4377
- buildPageElement,
4378
- buildNotFoundPageElement,
4379
- buildHref,
4380
- buildDataEndpoint,
4381
- applyRevalidateHeader,
4382
- TRAILING_SLASHES_RE,
4383
- SearchStoreContext,
4384
- SSR_FALLBACK_ROUTER,
4385
- SCROLL_STORAGE_KEY,
4386
- RouterProvider,
4387
- RouterContext,
4388
- Link,
4726
+ CLIENT_FALLBACK_ROUTER,
4389
4727
  FALLBACK_SEARCH_STORE,
4390
- CLIENT_FALLBACK_ROUTER
4728
+ Link,
4729
+ RouterContext,
4730
+ RouterProvider,
4731
+ SCROLL_STORAGE_KEY,
4732
+ SSR_FALLBACK_ROUTER,
4733
+ SearchStoreContext,
4734
+ TRAILING_SLASHES_RE,
4735
+ applyRevalidateHeader,
4736
+ buildDataEndpoint,
4737
+ buildHref,
4738
+ buildNotFoundPageElement,
4739
+ buildPageElement,
4740
+ buildRouterTree,
4741
+ classifySpaResponse,
4742
+ createSearchStore,
4743
+ decodeHashFragment,
4744
+ detectStaticMode,
4745
+ fromCrossJSON,
4746
+ generateHistoryKey,
4747
+ getHistoryKey,
4748
+ isSameOriginFetchResult,
4749
+ isStaleDeployResponse,
4750
+ navigationHrefPolicy,
4751
+ normalizeHref,
4752
+ normalizePath,
4753
+ parseDeferredNdjson,
4754
+ parsePageResponse,
4755
+ pickDeepestNotFound,
4756
+ saveScrollPosition,
4757
+ searchSnapshotFromRouterContext,
4758
+ shouldAutoRefreshPath,
4759
+ shouldInterceptClick,
4760
+ shouldRefetch,
4761
+ stripHashFromHref,
4762
+ toLogical,
4763
+ useNavigate,
4764
+ useRouter
4391
4765
  };