@teyik0/furin 0.2.0-alpha.5 → 0.4.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 (282) hide show
  1. package/README.md +2 -3
  2. package/dist/adapter/bun.d.ts +1 -1
  3. package/dist/adapter/static.d.ts +1 -1
  4. package/dist/build/bun-build.d.ts +3 -0
  5. package/dist/build/client.d.ts +2 -2
  6. package/dist/build/entry-template.d.ts +6 -0
  7. package/dist/build/entry-template.ts +20 -3
  8. package/dist/build/hydrate.d.ts +1 -1
  9. package/dist/build/index.d.ts +1 -1
  10. package/dist/build/index.js +9363 -5827
  11. package/dist/build/production-instrumentation.d.ts +1 -0
  12. package/dist/build/route-types.d.ts +3 -23
  13. package/dist/build/shared.d.ts +1 -1
  14. package/dist/build/ssg-cache.d.ts +1 -1
  15. package/dist/build/types.d.ts +2 -1
  16. package/dist/cli/index.js +9467 -5870
  17. package/dist/client/boundaries.d.ts +6 -4
  18. package/dist/client/define-route.d.ts +35 -0
  19. package/dist/client/document.d.ts +26 -0
  20. package/dist/client/hmr.d.ts +10 -0
  21. package/dist/client/internal/runtime-types.d.ts +32 -0
  22. package/dist/client/link.d.ts +2 -1
  23. package/dist/client/link.js +1884 -1227
  24. package/dist/client/router/boundary-tree.d.ts +1 -1
  25. package/dist/client/router/index.d.ts +2 -2
  26. package/dist/client/router/link-utils.d.ts +14 -1
  27. package/dist/client/router/search/index.d.ts +3 -7
  28. package/dist/client/router/sync-catch-up.d.ts +4 -4
  29. package/dist/client/router/types.d.ts +34 -26
  30. package/dist/client-only.d.ts +1 -0
  31. package/dist/client-only.js +1 -0
  32. package/dist/client.d.ts +11 -169
  33. package/dist/client.js +197 -36
  34. package/dist/config.d.ts +8 -8
  35. package/dist/config.js +10 -10
  36. package/dist/define-route.d.ts +1355 -0
  37. package/dist/devtools/devtools-element.d.ts +1 -0
  38. package/dist/devtools/protocol.d.ts +119 -0
  39. package/dist/furin.d.ts +24 -39
  40. package/dist/furin.js +14432 -7929
  41. package/dist/isomorphic.d.ts +18 -0
  42. package/dist/plugin/binding-scope.d.ts +2 -0
  43. package/dist/plugin/dead-code-elimination.d.ts +3 -0
  44. package/dist/plugin/index.js +1708 -489
  45. package/dist/plugin/route-config-autofix.d.ts +31 -0
  46. package/dist/plugin/routes.d.ts +27 -0
  47. package/dist/plugin/transform-client.d.ts +0 -2
  48. package/dist/plugin/transform-isomorphic.d.ts +9 -0
  49. package/dist/routes.d.ts +6 -0
  50. package/dist/routes.js +1 -0
  51. package/dist/rsc/build/environment.d.ts +2 -0
  52. package/dist/rsc/build/index.d.ts +15 -0
  53. package/dist/rsc/client-codec.d.ts +1 -0
  54. package/dist/rsc/codec.d.ts +4 -0
  55. package/dist/rsc/flight-drain.d.ts +11 -0
  56. package/dist/rsc/render-error.d.ts +17 -0
  57. package/dist/rsc/server-codec.d.ts +2 -0
  58. package/dist/rsc/server-codec.js +24 -0
  59. package/dist/rsc/shared.d.ts +30 -0
  60. package/dist/rsc/symbols.d.ts +2 -0
  61. package/dist/rsc/transport-benchmark.d.ts +13 -0
  62. package/dist/rsc/version.d.ts +7 -0
  63. package/dist/rsc-client.d.ts +4 -0
  64. package/dist/rsc-client.js +166 -0
  65. package/dist/rsc-server.d.ts +11 -0
  66. package/dist/rsc.d.ts +11 -0
  67. package/dist/rsc.js +353 -0
  68. package/dist/server/cache/index.d.ts +2 -2
  69. package/dist/server/cache/invalidation.d.ts +2 -3
  70. package/dist/server/cache/isr-ssg.d.ts +5 -1
  71. package/dist/server/cache/isr.d.ts +9 -0
  72. package/dist/server/cache/route-cache.d.ts +10 -8
  73. package/dist/server/cache/store-view.d.ts +7 -7
  74. package/dist/server/dev-page-plugin.d.ts +11 -5
  75. package/dist/server/devtools/hub.d.ts +11 -0
  76. package/dist/server/devtools/instrumentation.d.ts +22 -0
  77. package/dist/server/devtools/instrumentation.production.d.ts +44 -0
  78. package/dist/server/devtools/plugin.d.ts +3 -0
  79. package/dist/server/devtools/request-context.d.ts +6 -0
  80. package/dist/server/internal.d.ts +5 -0
  81. package/dist/server/internal.js +3 -3
  82. package/dist/server/lang-detect.d.ts +1 -0
  83. package/dist/server/logger.d.ts +4 -0
  84. package/dist/server/render/assemble.d.ts +4 -9
  85. package/dist/server/render/document.d.ts +4 -0
  86. package/dist/server/render/element.d.ts +3 -2
  87. package/dist/server/render/index.d.ts +2 -2
  88. package/dist/server/render/index.ts +6 -3
  89. package/dist/server/render/isr.d.ts +1 -1
  90. package/dist/server/render/loaders.d.ts +9 -1
  91. package/dist/server/render/not-found.d.ts +2 -2
  92. package/dist/server/render/ppr-route.d.ts +8 -0
  93. package/dist/server/render/route-frame-transport.d.ts +2 -0
  94. package/dist/server/render/shell.ts +0 -1
  95. package/dist/server/render/ssg.d.ts +1 -1
  96. package/dist/server/render/ssr.d.ts +9 -9
  97. package/dist/server/render/template.d.ts +4 -0
  98. package/dist/server/router/defined-route.d.ts +24 -0
  99. package/dist/server/router/discovery.d.ts +1 -1
  100. package/dist/server/router/hmr.d.ts +17 -9
  101. package/dist/server/router/patterns.d.ts +7 -1
  102. package/dist/server/router/plugin.d.ts +8 -10
  103. package/dist/server/router/schema-merge.d.ts +3 -0
  104. package/dist/server/router/schemas.d.ts +14 -9
  105. package/dist/server/router/source-version.d.ts +2 -0
  106. package/dist/server/router/types.d.ts +2 -1
  107. package/dist/server/runtime-env.js +2 -2
  108. package/dist/server/sync/adapter.d.ts +45 -26
  109. package/dist/server/sync/config.d.ts +5 -9
  110. package/dist/server/sync/fingerprint.d.ts +2 -1
  111. package/dist/server/sync/index.d.ts +15 -4
  112. package/dist/server/sync/index.js +3023 -0
  113. package/dist/server/sync/notifier.d.ts +18 -0
  114. package/dist/server/sync/plugin.d.ts +53 -54
  115. package/dist/server/sync/postgres/index.d.ts +19 -0
  116. package/dist/server/sync/postgres/index.js +252 -0
  117. package/dist/server/sync/postgres/migrate.d.ts +2 -0
  118. package/dist/server/sync/postgres/migrate.js +17 -0
  119. package/dist/server/sync/postgres/migration.sql +66 -0
  120. package/dist/server/sync/redis/index.d.ts +30 -0
  121. package/dist/server/sync/redis/index.js +336 -0
  122. package/dist/server/sync/redis/scripts.d.ts +4 -0
  123. package/dist/server/sync/response.d.ts +10 -1
  124. package/dist/server/sync/runtime.d.ts +6 -0
  125. package/dist/server/sync/sqlite/index.d.ts +20 -0
  126. package/dist/server/sync/sqlite/index.js +250 -0
  127. package/dist/server/sync/stream.d.ts +12 -11
  128. package/dist/server-only.d.ts +1 -0
  129. package/dist/server-only.js +1 -0
  130. package/dist/shared/await.d.ts +6 -7
  131. package/dist/shared/elysia-contract.d.ts +41 -0
  132. package/dist/shared/parser.d.ts +2 -0
  133. package/dist/shared/route-frame.d.ts +49 -0
  134. package/dist/shared/route-map.d.ts +5 -0
  135. package/dist/shared/utils/index.d.ts +1 -3
  136. package/package.json +86 -41
  137. package/src/adapter/bun.ts +113 -36
  138. package/src/adapter/package.ts +23 -15
  139. package/src/adapter/static.ts +97 -50
  140. package/src/build/bun-build.ts +11 -0
  141. package/src/build/client.ts +41 -26
  142. package/src/build/entry-template.ts +20 -3
  143. package/src/build/hydrate.ts +128 -33
  144. package/src/build/index.ts +14 -2
  145. package/src/build/production-instrumentation.ts +14 -0
  146. package/src/build/route-types.ts +20 -116
  147. package/src/build/scan-server.ts +3 -2
  148. package/src/build/shared.ts +1 -1
  149. package/src/build/ssg-cache.ts +4 -2
  150. package/src/build/types.ts +2 -1
  151. package/src/cli/config.ts +3 -3
  152. package/src/cli/index.ts +58 -27
  153. package/src/client/boundaries.tsx +51 -19
  154. package/src/client/default-screens.tsx +4 -4
  155. package/src/client/define-route.ts +48 -0
  156. package/src/client/document.tsx +165 -0
  157. package/src/client/hmr.ts +40 -0
  158. package/src/client/internal/runtime-types.ts +33 -0
  159. package/src/client/link.tsx +51 -38
  160. package/src/client/router/boundary-tree.tsx +2 -2
  161. package/src/client/router/context.ts +13 -9
  162. package/src/client/router/index.ts +4 -0
  163. package/src/client/router/link-utils.ts +92 -3
  164. package/src/client/router/navigation.ts +9 -15
  165. package/src/client/router/provider.tsx +98 -53
  166. package/src/client/router/search/index.ts +9 -19
  167. package/src/client/router/search-store.ts +5 -1
  168. package/src/client/router/spa-response.ts +3 -4
  169. package/src/client/router/sync-catch-up.ts +9 -8
  170. package/src/client/router/types.ts +52 -26
  171. package/src/client/sync.ts +3 -2
  172. package/src/client-only.ts +1 -0
  173. package/src/client.ts +28 -283
  174. package/src/config.ts +10 -10
  175. package/src/define-route.ts +959 -0
  176. package/src/devtools/devtools-element.js +885 -0
  177. package/src/devtools/protocol.ts +139 -0
  178. package/src/furin.ts +475 -136
  179. package/src/isomorphic.ts +66 -0
  180. package/src/plugin/binding-scope.ts +158 -0
  181. package/src/plugin/dead-code-elimination.ts +202 -0
  182. package/src/plugin/index.ts +14 -18
  183. package/src/plugin/route-config-autofix.ts +1140 -0
  184. package/src/plugin/routes.ts +891 -0
  185. package/src/plugin/transform-client.ts +160 -330
  186. package/src/plugin/transform-isomorphic.ts +464 -0
  187. package/src/routes.ts +6 -0
  188. package/src/rsc/build/environment.ts +30 -0
  189. package/src/rsc/build/index.ts +94 -0
  190. package/src/rsc/client-codec.ts +11 -0
  191. package/src/rsc/codec.ts +85 -0
  192. package/src/rsc/flight-drain.ts +68 -0
  193. package/src/rsc/react-server-dom-webpack.d.ts +23 -0
  194. package/src/rsc/render-error.ts +120 -0
  195. package/src/rsc/server-codec.ts +25 -0
  196. package/src/rsc/shared.tsx +113 -0
  197. package/src/rsc/symbols.ts +2 -0
  198. package/src/rsc/transport-benchmark.ts +73 -0
  199. package/src/rsc/version.ts +57 -0
  200. package/src/rsc-client.ts +12 -0
  201. package/src/rsc-server.tsx +91 -0
  202. package/src/rsc.tsx +75 -0
  203. package/src/server/auto-invalidate/registry.ts +2 -2
  204. package/src/server/auto-invalidate/runtime.ts +32 -6
  205. package/src/server/cache/dev-loader.ts +70 -10
  206. package/src/server/cache/index.ts +7 -3
  207. package/src/server/cache/invalidation.ts +33 -15
  208. package/src/server/cache/isr-ssg.ts +12 -3
  209. package/src/server/cache/isr.ts +84 -9
  210. package/src/server/cache/route-cache.ts +49 -36
  211. package/src/server/cache/store-view.ts +7 -7
  212. package/src/server/context-logger.ts +7 -7
  213. package/src/server/dev-page-plugin.ts +38 -17
  214. package/src/server/devtools/hub.ts +64 -0
  215. package/src/server/devtools/instrumentation.production.ts +80 -0
  216. package/src/server/devtools/instrumentation.ts +72 -0
  217. package/src/server/devtools/plugin.ts +269 -0
  218. package/src/server/devtools/request-context.ts +76 -0
  219. package/src/server/instance.ts +4 -4
  220. package/src/server/internal.ts +5 -0
  221. package/src/server/lang-detect.ts +14 -10
  222. package/src/server/logger.ts +21 -0
  223. package/src/server/render/assemble.ts +58 -36
  224. package/src/server/render/document.tsx +25 -0
  225. package/src/server/render/element.tsx +24 -9
  226. package/src/server/render/index.ts +6 -3
  227. package/src/server/render/isr.ts +182 -117
  228. package/src/server/render/loaders.ts +289 -50
  229. package/src/server/render/not-found.ts +57 -38
  230. package/src/server/render/ppr-route.ts +146 -0
  231. package/src/server/render/route-frame-transport.ts +62 -0
  232. package/src/server/render/shell.ts +0 -1
  233. package/src/server/render/ssg.ts +7 -6
  234. package/src/server/render/ssr.ts +412 -166
  235. package/src/server/render/template.ts +93 -2
  236. package/src/server/router/defined-route.ts +110 -0
  237. package/src/server/router/discovery.ts +165 -48
  238. package/src/server/router/hmr.ts +126 -53
  239. package/src/server/router/patterns.ts +56 -27
  240. package/src/server/router/plugin.ts +210 -200
  241. package/src/server/router/schema-merge.ts +42 -0
  242. package/src/server/router/schemas.ts +61 -76
  243. package/src/server/router/source-version.ts +16 -0
  244. package/src/server/router/types.ts +3 -1
  245. package/src/server/sync/adapter.ts +44 -28
  246. package/src/server/sync/config.ts +9 -27
  247. package/src/server/sync/fingerprint.ts +8 -3
  248. package/src/server/sync/index.ts +37 -13
  249. package/src/server/sync/notifier.ts +109 -0
  250. package/src/server/sync/plugin.ts +184 -89
  251. package/src/server/sync/postgres/index.ts +301 -0
  252. package/src/server/sync/postgres/migrate.ts +16 -0
  253. package/src/server/sync/postgres/migration.sql +66 -0
  254. package/src/server/sync/redis/index.ts +342 -0
  255. package/src/server/sync/redis/scripts.ts +74 -0
  256. package/src/server/sync/response.ts +145 -16
  257. package/src/server/sync/runtime.ts +27 -0
  258. package/src/server/sync/sql.d.ts +4 -0
  259. package/src/server/sync/sqlite/index.ts +337 -0
  260. package/src/server/sync/sqlite/migration.sql +70 -0
  261. package/src/server/sync/stream.ts +137 -81
  262. package/src/server-only.ts +1 -0
  263. package/src/shared/await.tsx +10 -11
  264. package/src/shared/deferred-ndjson.ts +34 -6
  265. package/src/shared/digest.ts +2 -2
  266. package/src/shared/elysia-contract.ts +63 -0
  267. package/src/shared/parser.ts +5 -0
  268. package/src/shared/route-frame.ts +429 -0
  269. package/src/shared/route-map.ts +37 -0
  270. package/src/shared/search-params.ts +7 -7
  271. package/src/shared/utils/index.ts +6 -22
  272. package/dist/build/server-routes-entry.d.ts +0 -13
  273. package/dist/build/server-routes-entry.ts +0 -30
  274. package/dist/server/dev-inspector.d.ts +0 -89
  275. package/dist/server/router/index.d.ts +0 -6
  276. package/dist/server/router/index.js +0 -27
  277. package/dist/server/router/index.ts +0 -28
  278. package/dist/server/sync/memory-adapter.d.ts +0 -17
  279. package/src/build/server-routes-entry.ts +0 -30
  280. package/src/server/dev-inspector.ts +0 -60
  281. package/src/server/router/index.ts +0 -28
  282. 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 createElement5, 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,25 +121,222 @@ 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");
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;
126
177
  } catch {
178
+ return false;
179
+ }
180
+ }
181
+ function applyLinkParams(to, params) {
182
+ if (!params) {
183
+ return to;
184
+ }
185
+ let url = to.replaceAll(/:([a-zA-Z0-9_]+)/g, (match, name) => (name in params) ? encodeURIComponent(String(params[name])) : match);
186
+ const wildcard = params["*"];
187
+ if (wildcard !== undefined && url.includes("/*")) {
188
+ const encodedWildcard = String(wildcard).split("/").map(encodeURIComponent).join("/");
189
+ url = url.replace("/*", () => `/${encodedWildcard}`);
190
+ }
191
+ return url;
192
+ }
193
+ function buildHref(to, search, hash, searchDefaults) {
194
+ let url = to;
195
+ if (search && Object.keys(search).length > 0) {
196
+ const params = buildSearchParams(search, searchDefaults);
197
+ const qs = params.toString();
198
+ if (qs) {
199
+ url += `?${qs}`;
200
+ }
201
+ }
202
+ if (hash) {
203
+ url += `#${hash}`;
204
+ }
205
+ return url;
206
+ }
207
+ function applyRevalidateHeader(headers, invalidate) {
208
+ const headerValue = headers.get("x-furin-revalidate");
209
+ if (!headerValue) {
127
210
  return;
128
211
  }
212
+ applyRevalidateEntries(headerValue.split(","), invalidate);
213
+ }
214
+ function applyRevalidateEntries(entries, invalidate) {
215
+ for (const entry of entries) {
216
+ const trimmed = entry.trim();
217
+ if (!trimmed) {
218
+ continue;
219
+ }
220
+ if (trimmed.endsWith(":layout")) {
221
+ invalidate(trimmed.slice(0, -":layout".length), "layout");
222
+ } else {
223
+ invalidate(trimmed, "page");
224
+ }
225
+ }
226
+ }
227
+ function shouldAutoRefreshPath(currentPath, invalidations) {
228
+ const normalizedCurrent = currentPath.split("?")[0] ?? currentPath;
229
+ return invalidations.some(({ path, type }) => {
230
+ if (type === "page") {
231
+ return path === normalizedCurrent;
232
+ }
233
+ const prefix = path === "/" || path.endsWith("/") ? path : `${path}/`;
234
+ return normalizedCurrent === path || normalizedCurrent.startsWith(prefix);
235
+ });
236
+ }
237
+ function stripHashFromHref(href) {
238
+ return href.replace(HASH_FRAGMENT_RE, "");
239
+ }
240
+ function normalizeHref(href) {
241
+ const url = new URL(href, "http://localhost");
242
+ let { pathname } = url;
243
+ if (pathname !== "/") {
244
+ pathname = pathname.replace(/\/+$/g, "");
245
+ }
246
+ return pathname + url.search + url.hash;
247
+ }
248
+ function normalizePath(path) {
249
+ if (path === "/" || path === "") {
250
+ return path;
251
+ }
252
+ return path.endsWith("/") ? path.slice(0, -1) : path;
253
+ }
254
+ function shouldRefetch(entry) {
255
+ return Date.now() - entry.createdAt > entry.staleTime;
256
+ }
257
+ function shouldInterceptClick(anchor, event, basePath, currentOrigin, currentPathname) {
258
+ if (event.metaKey || event.ctrlKey || event.shiftKey || event.altKey) {
259
+ return null;
260
+ }
261
+ if (anchor.target && anchor.target !== "_self") {
262
+ return null;
263
+ }
264
+ if (anchor.hasAttribute("download")) {
265
+ return null;
266
+ }
267
+ const { href } = anchor;
268
+ if (!href) {
269
+ return null;
270
+ }
271
+ let url;
272
+ try {
273
+ url = new URL(href, currentOrigin);
274
+ } catch {
275
+ return null;
276
+ }
277
+ if (url.origin !== currentOrigin) {
278
+ return null;
279
+ }
280
+ if (normalizePath(url.pathname) === normalizePath(currentPathname) && url.hash) {
281
+ return null;
282
+ }
283
+ const logicalPath = normalizeHref(toLogical(url.pathname, basePath));
284
+ const normalizedBase = normalizePath(basePath);
285
+ const normalizedPathname = normalizePath(url.pathname);
286
+ if (normalizedBase && normalizedPathname !== normalizedBase && !normalizedPathname.startsWith(`${normalizedBase}/`)) {
287
+ return null;
288
+ }
289
+ return logicalPath + url.search + url.hash;
290
+ }
291
+ function toLogical(physicalPathname, basePath) {
292
+ if (basePath && physicalPathname.startsWith(basePath) && (physicalPathname.length === basePath.length || physicalPathname[basePath.length] === "/")) {
293
+ return physicalPathname.slice(basePath.length) || "/";
294
+ }
295
+ return physicalPathname;
296
+ }
297
+
298
+ // src/client/router/context.ts
299
+ var RouterContext = createContext(null);
300
+ var CLIENT_FALLBACK_ROUTER = {
301
+ basePath: "",
302
+ currentHref: "/",
303
+ defaultPreload: "intent",
304
+ defaultPreloadDelay: 50,
305
+ defaultPreloadStaleTime: 30000,
306
+ invalidatePrefetch: (_path, _type) => {},
307
+ isNavigating: false,
308
+ navigate: (href, _opts) => {
309
+ if (navigationHrefPolicy(href, window.location.origin) === "blocked") {
310
+ return Promise.reject(new Error("[furin] Unsafe navigation URL."));
311
+ }
312
+ window.location.href = href;
313
+ return Promise.resolve();
314
+ },
315
+ prefetch: (_href, _opts) => {},
316
+ refresh: (_opts) => {
317
+ window.location.reload();
318
+ return Promise.resolve();
319
+ },
320
+ search: {},
321
+ searchRoutes: []
322
+ };
323
+ function useRouter() {
324
+ const ctx = useContext(RouterContext);
325
+ return ctx ?? CLIENT_FALLBACK_ROUTER;
129
326
  }
130
327
 
131
328
  // src/client/router/boundary-tree.tsx
132
- import { createElement } from "react";
329
+ import { createElement as createElement2 } from "react";
133
330
 
134
331
  // src/client/boundaries.tsx
135
- import { Component, Fragment } from "react";
332
+ import { Component, Fragment as Fragment2 } from "react";
136
333
 
137
334
  // src/shared/digest.ts
138
335
  function computeErrorDigest(err) {
139
336
  let message = "";
140
337
  let stack = "";
141
338
  if (err instanceof Error) {
142
- message = err.message;
339
+ ({ message } = err);
143
340
  stack = err.stack ?? "";
144
341
  } else if (typeof err === "string") {
145
342
  message = err;
@@ -159,7 +356,7 @@ ${stack}`;
159
356
  function cyrb53(input) {
160
357
  let h1 = 3735928559;
161
358
  let h2 = 1103547991;
162
- for (let i = 0;i < input.length; i++) {
359
+ for (let i = 0;i < input.length; i += 1) {
163
360
  const ch = input.charCodeAt(i);
164
361
  h1 = Math.imul(h1 ^ ch, 2654435761);
165
362
  h2 = Math.imul(h2 ^ ch, 1597334677);
@@ -304,22 +501,22 @@ var ACTIONS_STYLE = {
304
501
  justifyContent: "center"
305
502
  };
306
503
  var BUTTON_BASE = {
504
+ alignItems: "center",
505
+ appearance: "none",
307
506
  border: 0,
507
+ boxSizing: "border-box",
308
508
  cursor: "pointer",
309
509
  display: "inline-flex",
310
510
  fontFamily: FONT_SANS,
311
511
  fontSize: "14px",
312
512
  fontWeight: 500,
513
+ justifyContent: "center",
313
514
  lineHeight: 1,
314
515
  minWidth: "120px",
315
516
  padding: "10px 16px",
316
517
  textAlign: "center",
317
518
  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"
519
+ transition: "background-color 120ms ease, color 120ms ease, opacity 120ms ease"
323
520
  };
324
521
  var BUTTON_PRIMARY = {
325
522
  ...BUTTON_BASE,
@@ -468,6 +665,144 @@ var DefaultNotFoundFallback = ({ error }) => /* @__PURE__ */ jsxDEV(DefaultNotFo
468
665
  message: error.message
469
666
  }, undefined, false, undefined, this);
470
667
 
668
+ // src/client/document.tsx
669
+ import { createContext as createContext2, createElement, useContext as useContext2 } from "react";
670
+ import { jsxDEV as jsxDEV2, Fragment } from "react/jsx-dev-runtime";
671
+ var DocumentContext = createContext2(null);
672
+ function serializeJson(value) {
673
+ return JSON.stringify(value).replaceAll("<", "\\u003c").replaceAll(">", "\\u003e").replaceAll("\u2028", "\\u2028").replaceAll("\u2029", "\\u2029");
674
+ }
675
+ function DocumentProvider({
676
+ children,
677
+ value
678
+ }) {
679
+ return /* @__PURE__ */ jsxDEV2(DocumentContext.Provider, {
680
+ value,
681
+ children
682
+ }, undefined, false, undefined, this);
683
+ }
684
+ function useDocumentState() {
685
+ return useContext2(DocumentContext);
686
+ }
687
+ function renderMeta(meta, index) {
688
+ if ("title" in meta) {
689
+ return /* @__PURE__ */ jsxDEV2("title", {
690
+ children: meta.title
691
+ }, `title:${index}`, false, undefined, this);
692
+ }
693
+ if ("script:ld+json" in meta) {
694
+ return /* @__PURE__ */ jsxDEV2("script", {
695
+ dangerouslySetInnerHTML: { __html: serializeJson(meta["script:ld+json"]) },
696
+ type: "application/ld+json"
697
+ }, `json-ld:${index}`, false, undefined, this);
698
+ }
699
+ if ("tagName" in meta) {
700
+ const { tagName, ...attributes } = meta;
701
+ return createElement(tagName, { ...attributes, key: `${tagName}:${index}` });
702
+ }
703
+ return createElement("meta", { ...meta, key: `meta:${index}` });
704
+ }
705
+ function HeadContent() {
706
+ const state = useContext2(DocumentContext);
707
+ if (state === null) {
708
+ throw new Error("[furin] <HeadContent /> must be rendered inside the root layout.");
709
+ }
710
+ return /* @__PURE__ */ jsxDEV2(Fragment, {
711
+ children: [
712
+ /* @__PURE__ */ jsxDEV2("meta", {
713
+ charSet: "utf-8",
714
+ "data-furin-head": ""
715
+ }, undefined, false, undefined, this),
716
+ /* @__PURE__ */ jsxDEV2("meta", {
717
+ content: "width=device-width, initial-scale=1.0",
718
+ name: "viewport"
719
+ }, undefined, false, undefined, this),
720
+ /* @__PURE__ */ jsxDEV2("script", {
721
+ dangerouslySetInnerHTML: {
722
+ __html: 'try{var __t=localStorage.getItem("furin-theme");document.documentElement.classList.add(__t==="light"?"light":"dark")}catch(e){document.documentElement.classList.add("dark")}'
723
+ }
724
+ }, undefined, false, undefined, this),
725
+ state.assets.buildId ? /* @__PURE__ */ jsxDEV2("meta", {
726
+ content: state.assets.buildId,
727
+ name: "furin-build-id"
728
+ }, undefined, false, undefined, this) : null,
729
+ state.assets.staticMode ? /* @__PURE__ */ jsxDEV2("meta", {
730
+ content: "static",
731
+ name: "furin-mode"
732
+ }, undefined, false, undefined, this) : null,
733
+ state.assets.faviconHref ? /* @__PURE__ */ jsxDEV2("link", {
734
+ href: state.assets.faviconHref,
735
+ rel: "icon"
736
+ }, undefined, false, undefined, this) : null,
737
+ state.assets.stylesheets.map((href) => /* @__PURE__ */ jsxDEV2("link", {
738
+ crossOrigin: "",
739
+ href,
740
+ rel: "stylesheet"
741
+ }, href, false, undefined, this)),
742
+ state.head?.meta?.map(renderMeta),
743
+ state.head?.links?.map((link, index) => /* @__PURE__ */ jsxDEV2("link", {
744
+ ...link
745
+ }, `${link.rel}:${link.href}:${index}`, false, undefined, this)),
746
+ state.head?.scripts?.map(({ children, ...attributes }, index) => /* @__PURE__ */ jsxDEV2("script", {
747
+ ...attributes,
748
+ dangerouslySetInnerHTML: children === undefined ? undefined : { __html: children }
749
+ }, `script:${index}`, false, undefined, this)),
750
+ state.head?.styles?.map(({ children, type }, index) => /* @__PURE__ */ jsxDEV2("style", {
751
+ dangerouslySetInnerHTML: { __html: children },
752
+ type
753
+ }, `style:${index}`, false, undefined, this))
754
+ ]
755
+ }, undefined, true, undefined, this);
756
+ }
757
+ function Scripts() {
758
+ const state = useContext2(DocumentContext);
759
+ if (state === null) {
760
+ throw new Error("[furin] <Scripts /> must be rendered inside the root layout.");
761
+ }
762
+ return /* @__PURE__ */ jsxDEV2(Fragment, {
763
+ children: [
764
+ state.syncJson === undefined ? null : /* @__PURE__ */ jsxDEV2("script", {
765
+ dangerouslySetInnerHTML: { __html: state.syncJson },
766
+ id: "__FURIN_SYNC__",
767
+ type: "application/json"
768
+ }, undefined, false, undefined, this),
769
+ state.dataJson === undefined ? null : /* @__PURE__ */ jsxDEV2("script", {
770
+ dangerouslySetInnerHTML: { __html: state.dataJson },
771
+ id: "__FURIN_DATA__",
772
+ type: "application/json"
773
+ }, undefined, false, undefined, this),
774
+ /* @__PURE__ */ jsxDEV2("script", {
775
+ dangerouslySetInnerHTML: { __html: serializeJson(state.head ?? {}) },
776
+ "data-furin-scripts": "",
777
+ id: "__FURIN_HEAD__",
778
+ type: "application/json"
779
+ }, undefined, false, undefined, this),
780
+ state.assets.entryModule === undefined ? null : /* @__PURE__ */ jsxDEV2("script", {
781
+ crossOrigin: "",
782
+ "data-furin-entry": "",
783
+ src: state.assets.entryModule,
784
+ type: "module"
785
+ }, undefined, false, undefined, this)
786
+ ]
787
+ }, undefined, true, undefined, this);
788
+ }
789
+ function FurinDocumentFallback({ children }) {
790
+ return /* @__PURE__ */ jsxDEV2("html", {
791
+ lang: "en",
792
+ children: [
793
+ /* @__PURE__ */ jsxDEV2("head", {
794
+ children: /* @__PURE__ */ jsxDEV2(HeadContent, {}, undefined, false, undefined, this)
795
+ }, undefined, false, undefined, this),
796
+ /* @__PURE__ */ jsxDEV2("body", {
797
+ children: [
798
+ children,
799
+ /* @__PURE__ */ jsxDEV2(Scripts, {}, undefined, false, undefined, this)
800
+ ]
801
+ }, undefined, true, undefined, this)
802
+ ]
803
+ }, undefined, true, undefined, this);
804
+ }
805
+
471
806
  // src/client/server-error.ts
472
807
  var SERVER_ERROR_BRAND = "FURIN_SERVER_ERROR";
473
808
 
@@ -486,9 +821,29 @@ function isFurinServerError(err) {
486
821
  }
487
822
 
488
823
  // src/client/boundaries.tsx
489
- import { jsxDEV as jsxDEV2 } from "react/jsx-dev-runtime";
824
+ import { jsxDEV as jsxDEV3 } from "react/jsx-dev-runtime";
490
825
  var DEFAULT_ERROR_STATUS = 500;
491
826
  var SERVER_RESET_NOOP = () => {};
827
+ function getServerDigest(error) {
828
+ if (isFurinServerError(error)) {
829
+ return error.digest;
830
+ }
831
+ if (typeof error !== "object" && typeof error !== "function" || error === null) {
832
+ return;
833
+ }
834
+ const digest = error.__furinDigest;
835
+ return typeof digest === "string" ? digest : undefined;
836
+ }
837
+ function normalizeCaughtError(error) {
838
+ if (error instanceof Error) {
839
+ return error;
840
+ }
841
+ const normalized = new Error(String(error));
842
+ if (typeof error === "object" && error !== null || typeof error === "function") {
843
+ Object.defineProperties(normalized, Object.getOwnPropertyDescriptors(error));
844
+ }
845
+ return normalized;
846
+ }
492
847
 
493
848
  class FurinErrorBoundary extends Component {
494
849
  state = {
@@ -497,7 +852,10 @@ class FurinErrorBoundary extends Component {
497
852
  error: null
498
853
  };
499
854
  static getDerivedStateFromError(error) {
500
- return { digest: computeErrorDigest(error), error };
855
+ return {
856
+ digest: getServerDigest(error) ?? computeErrorDigest(error),
857
+ error: normalizeCaughtError(error)
858
+ };
501
859
  }
502
860
  componentDidUpdate(prevProps) {
503
861
  if (prevProps.resetKey !== this.props.resetKey && this.state.error) {
@@ -516,16 +874,19 @@ class FurinErrorBoundary extends Component {
516
874
  throw error;
517
875
  }
518
876
  const Fallback = this.props.fallback ?? DefaultErrorFallback;
519
- const serverDigest = isFurinServerError(error) ? error.digest : undefined;
877
+ const serverDigest = getServerDigest(error);
520
878
  const finalDigest = serverDigest ?? digest ?? this.props.digest ?? computeErrorDigest(error);
521
879
  const message = this.props.fallback ? error.message : getPublicErrorMessage(error);
522
880
  const status = isFurinServerError(error) ? error.status : DEFAULT_ERROR_STATUS;
523
- return /* @__PURE__ */ jsxDEV2(Fallback, {
524
- error: { message, digest: finalDigest, status },
881
+ const fallback = /* @__PURE__ */ jsxDEV3(Fallback, {
882
+ error: { digest: finalDigest, message, status },
525
883
  reset: typeof window === "undefined" ? SERVER_RESET_NOOP : this.reset
526
884
  }, undefined, false, undefined, this);
885
+ return this.props.document ? /* @__PURE__ */ jsxDEV3(FurinDocumentFallback, {
886
+ children: fallback
887
+ }, undefined, false, undefined, this) : fallback;
527
888
  }
528
- return /* @__PURE__ */ jsxDEV2(Fragment, {
889
+ return /* @__PURE__ */ jsxDEV3(Fragment2, {
529
890
  children: this.props.children
530
891
  }, epoch, false, undefined, this);
531
892
  }
@@ -538,7 +899,7 @@ class FurinNotFoundBoundary extends Component {
538
899
  }
539
900
  componentDidUpdate(prevProps) {
540
901
  if (prevProps.resetKey !== this.props.resetKey && this.state.error) {
541
- this.setState((s) => ({ error: null, epoch: s.epoch + 1 }));
902
+ this.setState((s) => ({ epoch: s.epoch + 1, error: null }));
542
903
  }
543
904
  }
544
905
  render() {
@@ -548,11 +909,11 @@ class FurinNotFoundBoundary extends Component {
548
909
  throw error;
549
910
  }
550
911
  const Fallback = this.props.fallback ?? DefaultNotFoundFallback;
551
- return /* @__PURE__ */ jsxDEV2(Fallback, {
552
- error: { message: error.message, data: error.data }
912
+ return /* @__PURE__ */ jsxDEV3(Fallback, {
913
+ error: { data: error.data, message: error.message }
553
914
  }, undefined, false, undefined, this);
554
915
  }
555
- return /* @__PURE__ */ jsxDEV2(Fragment, {
916
+ return /* @__PURE__ */ jsxDEV3(Fragment2, {
556
917
  children: this.props.children
557
918
  }, epoch, false, undefined, this);
558
919
  }
@@ -563,14 +924,14 @@ function wrapSegmentBoundaries(inner, segment, options) {
563
924
  }
564
925
  let wrapped = inner;
565
926
  if (segment.notFound) {
566
- wrapped = /* @__PURE__ */ jsxDEV2(FurinNotFoundBoundary, {
927
+ wrapped = /* @__PURE__ */ jsxDEV3(FurinNotFoundBoundary, {
567
928
  fallback: segment.notFound,
568
929
  resetKey: options?.resetKey,
569
930
  children: wrapped
570
931
  }, undefined, false, undefined, this);
571
932
  }
572
933
  if (segment.error) {
573
- wrapped = /* @__PURE__ */ jsxDEV2(FurinErrorBoundary, {
934
+ wrapped = /* @__PURE__ */ jsxDEV3(FurinErrorBoundary, {
574
935
  fallback: segment.error,
575
936
  onReset: options?.onReset,
576
937
  resetKey: options?.resetKey,
@@ -580,40 +941,12 @@ function wrapSegmentBoundaries(inner, segment, options) {
580
941
  return wrapped;
581
942
  }
582
943
 
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
944
  // src/client/router/boundary-tree.tsx
612
- import { jsxDEV as jsxDEV3 } from "react/jsx-dev-runtime";
945
+ import { jsxDEV as jsxDEV4 } from "react/jsx-dev-runtime";
613
946
  function buildRouterTree(context, pageElement, options) {
614
- return /* @__PURE__ */ jsxDEV3(RouterContext.Provider, {
947
+ return /* @__PURE__ */ jsxDEV4(RouterContext.Provider, {
615
948
  value: context,
616
- children: /* @__PURE__ */ jsxDEV3(FurinErrorBoundary, {
949
+ children: /* @__PURE__ */ jsxDEV4(FurinErrorBoundary, {
617
950
  ...options,
618
951
  children: pageElement
619
952
  }, undefined, false, undefined, this)
@@ -625,7 +958,7 @@ function RouteErrorThrower({
625
958
  throw new FurinServerError(error);
626
959
  }
627
960
  function buildPageElement(match, root, data, options, error) {
628
- let element = error ? createElement(RouteErrorThrower, { error }) : createElement(match.component, data);
961
+ let element = error ? createElement2(RouteErrorThrower, { error }) : createElement2(match.component, data);
629
962
  const chain = [];
630
963
  let current = match.pageRoute;
631
964
  while (current) {
@@ -637,17 +970,17 @@ function buildPageElement(match, root, data, options, error) {
637
970
  byDepth.set(segment.depth, segment);
638
971
  }
639
972
  const rootOffset = root ? 1 : 0;
640
- for (let i = chain.length - 1;i >= rootOffset; i--) {
973
+ for (let i = chain.length - 1;i >= rootOffset; i -= 1) {
641
974
  element = wrapSegmentBoundaries(element, byDepth.get(i), options);
642
975
  const Layout = chain[i]?.layout;
643
976
  if (Layout) {
644
- element = createElement(Layout, { ...data }, element);
977
+ element = createElement2(Layout, { ...data }, element);
645
978
  }
646
979
  }
647
980
  if (root) {
648
981
  element = wrapSegmentBoundaries(element, byDepth.get(0), options);
649
982
  if (root.layout) {
650
- element = createElement(root.layout, { ...data }, element);
983
+ element = createElement2(root.layout, { ...data }, element);
651
984
  }
652
985
  }
653
986
  return element;
@@ -681,133 +1014,18 @@ function isStaleDeployResponse(res) {
681
1014
  const clientBuildId = metaEl?.content;
682
1015
  return Boolean(clientBuildId && serverBuildId !== clientBuildId);
683
1016
  }
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
1017
  // src/client/router/navigation.ts
792
1018
  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
1019
  function useNavigate() {
806
1020
  const router = useRouter();
807
1021
  return useCallback((next) => {
808
1022
  const searchDefaults = findSearchDefaultsForRouteTarget(next.to, router.searchRoutes);
809
1023
  const href = buildHref(next.to, next.search, next.hash, searchDefaults);
810
- if (isExternalAbsoluteHref(href) && typeof window !== "undefined") {
1024
+ const policy = navigationHrefPolicy(href, typeof window === "undefined" ? undefined : window.location.origin);
1025
+ if (policy === "blocked") {
1026
+ return Promise.reject(new Error("[furin] Unsafe navigation URL."));
1027
+ }
1028
+ if (policy === "external" && typeof window !== "undefined") {
811
1029
  window.location.assign(href);
812
1030
  return Promise.resolve();
813
1031
  }
@@ -815,7 +1033,7 @@ function useNavigate() {
815
1033
  return router.navigate(href, opts);
816
1034
  }, [router]);
817
1035
  }
818
- // ../../node_modules/.bun/evlog@2.19.2+7724ce3de6b3bca4/node_modules/evlog/dist/utils.mjs
1036
+ // ../../node_modules/.bun/evlog@2.28.1+4cac44d0f5802a4d/node_modules/evlog/dist/utils.mjs
819
1037
  function formatDuration(ms) {
820
1038
  if (ms < 1000)
821
1039
  return `${Math.round(ms)}ms`;
@@ -925,589 +1143,326 @@ function globToRegExp(pattern, separator = "/") {
925
1143
  }
926
1144
  return regex;
927
1145
  }
928
-
929
- // ../../node_modules/.bun/evlog@2.19.2+7724ce3de6b3bca4/node_modules/evlog/dist/pretty-error-THg0U0w9.mjs
930
- var snippetReader = null;
931
- var PRETTY_ERROR_TREE_SPACER = "__EVLOG_TREE_SPACER__";
932
- function pushTreeSpacer(children) {
933
- children.push(PRETTY_ERROR_TREE_SPACER);
934
- }
935
- var SKIP_PATH_RE = /(?:^|[/\\])(?:node_modules|\.nuxt|\.next|\.output)(?:[/\\]|$)/;
936
- var SKIP_FRAME_PATH_RE = /(?:^|[/\\])(?:packages[/\\]evlog|evlog[/\\](?:dist|src))(?:[/\\]|$)/;
937
- var SKIP_FRAME_FN_RE = /^(?:createError|EvlogError|new EvlogError)$/;
938
- function isPlainObject(val) {
939
- return val !== null && typeof val === "object" && !Array.isArray(val);
940
- }
941
- function pickString(obj, key) {
942
- const val = obj[key];
943
- return typeof val === "string" && val.length > 0 ? val : undefined;
1146
+ var _isoDate = /* @__PURE__ */ new Date;
1147
+ var _isoCachedSecond = -1;
1148
+ var _isoCachedPrefix = "";
1149
+ function isoNow() {
1150
+ const now = Date.now();
1151
+ const sec = Math.floor(now / 1000);
1152
+ if (sec !== _isoCachedSecond) {
1153
+ _isoCachedSecond = sec;
1154
+ _isoDate.setTime(now);
1155
+ _isoCachedPrefix = _isoDate.toISOString().slice(0, 19);
1156
+ }
1157
+ return `${_isoCachedPrefix}.${String(now % 1000).padStart(3, "0")}Z`;
944
1158
  }
945
- function pickNumber(obj, key) {
946
- const val = obj[key];
947
- return typeof val === "number" ? val : undefined;
1159
+
1160
+ // ../../node_modules/.bun/evlog@2.28.1+4cac44d0f5802a4d/node_modules/evlog/dist/redact-C7FmdhwI.mjs
1161
+ var DEFAULT_REPLACEMENT = "[REDACTED]";
1162
+ function normalizeRedactPathPattern(pattern) {
1163
+ if (!pattern.includes("*") && !pattern.includes("."))
1164
+ return `**.${pattern}`;
1165
+ return pattern;
948
1166
  }
949
- function extractGuidance(data) {
1167
+ function compileRedactPathMatchers(patterns) {
1168
+ if (!patterns?.length)
1169
+ return;
1170
+ const exactPaths = /* @__PURE__ */ new Set;
1171
+ const pathGlobs = [];
1172
+ const keyGlobs = [];
1173
+ const caseInsensitiveLeaves = /* @__PURE__ */ new Set;
1174
+ for (const raw of patterns) {
1175
+ if (!raw.includes("*")) {
1176
+ if (raw.includes("."))
1177
+ exactPaths.add(raw);
1178
+ else
1179
+ addPathGlobPattern(normalizeRedactPathPattern(raw), exactPaths, pathGlobs, caseInsensitiveLeaves);
1180
+ continue;
1181
+ }
1182
+ if (!raw.includes("."))
1183
+ keyGlobs.push(globToRegExp(raw, "."));
1184
+ else
1185
+ addPathGlobPattern(raw, exactPaths, pathGlobs, caseInsensitiveLeaves);
1186
+ }
1187
+ if (exactPaths.size === 0 && pathGlobs.length === 0 && keyGlobs.length === 0 && caseInsensitiveLeaves.size === 0)
1188
+ return;
950
1189
  return {
951
- code: pickString(data, "code"),
952
- why: pickString(data, "why"),
953
- fix: pickString(data, "fix"),
954
- link: pickString(data, "link")
1190
+ exactPaths,
1191
+ pathGlobs,
1192
+ keyGlobs,
1193
+ caseInsensitiveLeaves
955
1194
  };
956
1195
  }
957
- function normalizeErrorContext(error) {
958
- if (error === null || error === undefined)
959
- return null;
960
- if (typeof error === "string")
961
- return { message: error };
962
- if (!isPlainObject(error))
963
- return { message: String(error) };
964
- const result = {
965
- message: pickString(error, "message") ?? pickString(error, "statusText") ?? pickString(error, "statusMessage") ?? "Unknown error",
966
- name: pickString(error, "name"),
967
- code: pickString(error, "code"),
968
- why: pickString(error, "why"),
969
- fix: pickString(error, "fix"),
970
- link: pickString(error, "link"),
971
- status: pickNumber(error, "status") ?? pickNumber(error, "statusCode"),
972
- stack: pickString(error, "stack")
973
- };
974
- const { data, cause } = error;
975
- if (isPlainObject(data)) {
976
- const guidance = extractGuidance(data);
977
- if (!result.code)
978
- result.code = guidance.code;
979
- if (!result.why)
980
- result.why = guidance.why;
981
- if (!result.fix)
982
- result.fix = guidance.fix;
983
- if (!result.link)
984
- result.link = guidance.link;
1196
+ function addPathGlobPattern(pattern, exactPaths, pathGlobs, caseInsensitiveLeaves) {
1197
+ pathGlobs.push(globToRegExp(pattern, "."));
1198
+ const leaf = pattern.match(/^\*\*\.([^.?*]+)$/);
1199
+ if (leaf) {
1200
+ exactPaths.add(leaf[1]);
1201
+ caseInsensitiveLeaves.add(leaf[1].toLowerCase());
985
1202
  }
986
- if (cause instanceof Error)
987
- result.cause = cause.message;
988
- else if (isPlainObject(cause) && pickString(cause, "message"))
989
- result.cause = pickString(cause, "message");
990
- return result;
991
- }
992
- function decodeFileUrl(file) {
993
- if (file.startsWith("file://"))
994
- try {
995
- return decodeURIComponent(new URL(file).pathname);
996
- } catch {
997
- return file.slice(7);
998
- }
999
- return file;
1000
1203
  }
1001
- function isAppPath(file) {
1002
- const normalized = decodeFileUrl(file).replace(/\\/g, "/");
1003
- if (normalized.startsWith("node:"))
1004
- return false;
1005
- if (SKIP_PATH_RE.test(normalized))
1006
- return false;
1007
- if (normalized.includes("/node_modules/"))
1008
- return false;
1009
- if (isFrameworkRuntimePath(normalized))
1010
- return false;
1011
- return true;
1204
+ function matchesRedactPath(fullPath, leafKey, matchers) {
1205
+ if (matchers.exactPaths.has(fullPath))
1206
+ return true;
1207
+ if (matchers.caseInsensitiveLeaves.has(leafKey.toLowerCase()))
1208
+ return true;
1209
+ for (const glob of matchers.pathGlobs) {
1210
+ glob.lastIndex = 0;
1211
+ if (glob.test(fullPath))
1212
+ return true;
1213
+ }
1214
+ for (const glob of matchers.keyGlobs) {
1215
+ glob.lastIndex = 0;
1216
+ if (glob.test(leafKey))
1217
+ return true;
1218
+ }
1219
+ return false;
1012
1220
  }
1013
- function formatDisplayPath(file, cwd) {
1014
- const decoded = decodeFileUrl(file).replace(/\\/g, "/");
1015
- const cwdNorm = cwd.replace(/\\/g, "/").replace(/\/$/, "");
1016
- if (cwdNorm && decoded.startsWith(`${cwdNorm}/`)) {
1017
- const rel = decoded.slice(cwdNorm.length + 1);
1018
- return rel.startsWith("./") ? rel.slice(2) : rel;
1221
+ function resolveReplacement(replacement, matched, ctx) {
1222
+ if (typeof replacement === "string")
1223
+ return replacement;
1224
+ try {
1225
+ const result = replacement(matched, ctx);
1226
+ if (typeof result !== "string") {
1227
+ console.error(`[evlog] redact replacement returned ${typeof result} for "${ctx.path}", expected string \u2014 using ${DEFAULT_REPLACEMENT}`);
1228
+ return DEFAULT_REPLACEMENT;
1229
+ }
1230
+ return result;
1231
+ } catch (err) {
1232
+ console.error(`[evlog] redact replacement failed for "${ctx.path}":`, err);
1233
+ return DEFAULT_REPLACEMENT;
1019
1234
  }
1020
- const serverIdx = decoded.indexOf("/server/");
1021
- if (serverIdx >= 0)
1022
- return decoded.slice(serverIdx + 1);
1023
- const srcIdx = decoded.indexOf("/src/");
1024
- if (srcIdx >= 0)
1025
- return decoded.slice(srcIdx + 1);
1026
- return decoded;
1027
1235
  }
1028
- function parseStackFrames(stack) {
1029
- if (!stack)
1030
- return [];
1031
- const lines = stack.split(`
1032
- `);
1033
- const frames = [];
1034
- for (const line of lines) {
1035
- const trimmed = line.trim();
1036
- if (!trimmed.startsWith("at "))
1037
- continue;
1038
- const withFn = trimmed.match(/^at (.+?) \((.+):(\d+):(\d+)\)$/);
1039
- if (withFn) {
1040
- const [, fn, file, lineStr, colStr] = withFn;
1041
- frames.push({
1042
- raw: trimmed,
1043
- fn,
1044
- file,
1045
- line: Number(lineStr),
1046
- column: Number(colStr),
1047
- isApp: isAppPath(file)
1048
- });
1049
- continue;
1050
- }
1051
- const withoutFn = trimmed.match(/^at (.+):(\d+):(\d+)$/);
1052
- if (withoutFn) {
1053
- const [, file, lineStr, colStr] = withoutFn;
1054
- frames.push({
1055
- raw: trimmed,
1056
- file,
1057
- line: Number(lineStr),
1058
- column: Number(colStr),
1059
- isApp: isAppPath(file)
1060
- });
1061
- continue;
1236
+ function redactPathsInTree(obj, matchers, replacement, prefix = "") {
1237
+ if (obj === null || obj === undefined)
1238
+ return;
1239
+ if (Array.isArray(obj)) {
1240
+ for (let i = 0;i < obj.length; i++) {
1241
+ const segment = String(i);
1242
+ const fullPath = prefix ? `${prefix}.${segment}` : segment;
1243
+ redactPathsInTree(obj[i], matchers, replacement, fullPath);
1062
1244
  }
1063
- const asyncFn = trimmed.match(/^at async (.+?) \((.+):(\d+):(\d+)\)$/);
1064
- if (asyncFn) {
1065
- const [, fn, file, lineStr, colStr] = asyncFn;
1066
- frames.push({
1067
- raw: trimmed,
1068
- fn: `async ${fn}`,
1069
- file,
1070
- line: Number(lineStr),
1071
- column: Number(colStr),
1072
- isApp: isAppPath(file)
1073
- });
1245
+ return;
1246
+ }
1247
+ if (typeof obj === "object") {
1248
+ const record = obj;
1249
+ for (const key of redactableKeys(record)) {
1250
+ const fullPath = prefix ? `${prefix}.${key}` : key;
1251
+ if (matchesRedactPath(fullPath, key, matchers))
1252
+ setRedacted(record, key, resolveReplacement(replacement, record[key], {
1253
+ path: fullPath,
1254
+ key
1255
+ }), fullPath);
1256
+ else
1257
+ redactPathsInTree(record[key], matchers, replacement, fullPath);
1074
1258
  }
1075
1259
  }
1076
- return frames;
1077
1260
  }
1078
- function isFrameworkRuntimePath(path) {
1079
- const normalized = path.replace(/\\/g, "/");
1080
- return normalized.includes("route-modules/") || normalized.includes("webpack://next/") || normalized.includes("/next/dist/") || normalized.includes("/compiled/next-server/");
1261
+ function redactableKeys(record) {
1262
+ return Object.keys(record);
1081
1263
  }
1082
- function isFrameworkRuntimeFrame(frame) {
1083
- if (!frame.file)
1084
- return false;
1085
- return isFrameworkRuntimePath(decodeFileUrl(frame.file));
1264
+ function setRedacted(record, key, value, path) {
1265
+ if (Reflect.set(record, key, value))
1266
+ return;
1267
+ const desc = Object.getOwnPropertyDescriptor(record, key);
1268
+ if (desc && "value" in desc && desc.configurable) {
1269
+ Object.defineProperty(record, key, {
1270
+ ...desc,
1271
+ value
1272
+ });
1273
+ return;
1274
+ }
1275
+ console.warn(`[evlog] redact could not rewrite read-only field "${path}" \u2014 value left as-is`);
1086
1276
  }
1087
- function isInternalErrorFrame(frame) {
1088
- if (isFrameworkRuntimeFrame(frame))
1089
- return true;
1090
- if (frame.fn) {
1091
- const fn = frame.fn.replace(/^async /, "");
1092
- if (SKIP_FRAME_FN_RE.test(fn))
1093
- return true;
1277
+ var builtinPatterns = {
1278
+ creditCard: {
1279
+ pattern: /\b\d{4}[\s-]?\d{4}[\s-]?\d{4}[\s-]?\d{4}\b/g,
1280
+ mask: (m) => `****${m.replace(/[\s-]/g, "").slice(-4)}`
1281
+ },
1282
+ email: {
1283
+ pattern: /[\w.+-]+@[\w-]+\.[\w.]+/g,
1284
+ mask: (m) => {
1285
+ if (m.indexOf("@") < 1)
1286
+ return "***@***";
1287
+ const tld = m.slice(m.lastIndexOf("."));
1288
+ return `${m[0]}***@***${tld}`;
1289
+ }
1290
+ },
1291
+ ipv4: {
1292
+ pattern: /\b(?!0\.0\.0\.0\b)(?!127\.0\.0\.1\b)\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}\b/g,
1293
+ mask: (m) => `***.***.***.${m.split(".").pop()}`
1294
+ },
1295
+ phone: {
1296
+ pattern: /(?:\+\d{1,3}[\s.-]?\(?\d{1,4}\)?|\(\d{1,4}\))(?:[\s.-]?\d{2,4}){2,4}\b/g,
1297
+ mask: (m) => {
1298
+ const digits = m.replace(/[^\d]/g, "");
1299
+ if (m.startsWith("+") && digits.length > 4) {
1300
+ const ccMatch = m.match(/^\+\d{1,3}/);
1301
+ return `${ccMatch ? ccMatch[0] : "+"}******${digits.slice(-2)}`;
1302
+ }
1303
+ if (digits.length > 2)
1304
+ return `${"*".repeat(digits.length - 2)}${digits.slice(-2)}`;
1305
+ return "***";
1306
+ }
1307
+ },
1308
+ jwt: {
1309
+ pattern: /\beyJ[\w-]*\.[\w-]*\.[\w-]*\b/g,
1310
+ mask: () => "eyJ***.***"
1311
+ },
1312
+ bearer: {
1313
+ pattern: /\bBearer\s+[\w\-.~+/]{8,}=*/gi,
1314
+ mask: () => "Bearer ***"
1315
+ },
1316
+ iban: {
1317
+ pattern: /\b[A-Z]{2}\d{2}[\s-]?[\dA-Z]{4}[\s-]?[\dA-Z]{4}[\s-]?[\dA-Z]{4}[\s-]?[\dA-Z]{0,4}[\s-]?[\dA-Z]{0,4}[\s-]?[\dA-Z]{0,4}\b/g,
1318
+ mask: (m) => {
1319
+ const clean = m.replace(/[\s-]/g, "");
1320
+ return `${clean.slice(0, 4)}****${clean.slice(-3)}`;
1321
+ }
1094
1322
  }
1095
- if (!frame.file)
1096
- return true;
1097
- const path = decodeFileUrl(frame.file).replace(/\\/g, "/");
1098
- if (SKIP_FRAME_PATH_RE.test(path))
1099
- return true;
1100
- if (path.includes(".nuxt/"))
1101
- return true;
1102
- if (path.includes(".next/"))
1103
- return true;
1104
- return false;
1323
+ };
1324
+ function resolveRedactConfig(input) {
1325
+ if (input === undefined || input === false)
1326
+ return;
1327
+ if (input === true)
1328
+ return { _maskers: allBuiltinMaskers() };
1329
+ if (input.builtins === false)
1330
+ return {
1331
+ ...input,
1332
+ _pathMatchers: compileRedactPathMatchers(input.paths)
1333
+ };
1334
+ const maskers = Array.isArray(input.builtins) ? input.builtins.map((name) => builtinPatterns[name]).filter(Boolean).map((b) => [cloneRegex(b.pattern), b.mask]) : allBuiltinMaskers();
1335
+ return {
1336
+ ...input,
1337
+ _maskers: maskers,
1338
+ _pathMatchers: compileRedactPathMatchers(input.paths)
1339
+ };
1105
1340
  }
1106
- function pickPrimaryFrame(frames) {
1107
- for (const frame of frames)
1108
- if (frame.isApp && frame.file && frame.line && !isInternalErrorFrame(frame))
1109
- return frame;
1341
+ function allBuiltinMaskers() {
1342
+ return Object.values(builtinPatterns).map((b) => [cloneRegex(b.pattern), b.mask]);
1110
1343
  }
1111
- function readCodeSnippet(file, line, contextLines = 2) {
1112
- if (!isDev() || isBrowser() || !snippetReader)
1113
- return null;
1114
- const path = decodeFileUrl(file).replace(/\\/g, "/");
1115
- if (path.includes(".next/") || path.includes(".nuxt/") || path.includes(".output/"))
1116
- return null;
1117
- return snippetReader(file, line, contextLines);
1344
+ function cloneRegex(re) {
1345
+ return new RegExp(re.source, re.flags);
1118
1346
  }
1119
- function formatSnippetLines(snippet) {
1120
- const width = String(snippet[snippet.length - 1]?.line ?? 0).length;
1121
- return snippet.map(({ line, content, isErrorLine }) => {
1122
- const marker = isErrorLine ? `${colors.red}\u276F${colors.reset}` : `${colors.dim} ${colors.reset}`;
1123
- const numColor = isErrorLine ? colors.red : colors.gray;
1124
- const trimmed = content.length > 120 ? `${content.slice(0, 117)}\u2026` : content;
1125
- return `${marker} ${numColor}${String(line).padStart(width, " ")}${colors.reset} ${colors.dim}\u2503${colors.reset} ${colors.dim}${trimmed}${colors.reset}`;
1347
+ var globallyRedacted = Symbol.for("evlog.globallyRedacted");
1348
+ function markGloballyRedacted(event) {
1349
+ Object.defineProperty(event, globallyRedacted, {
1350
+ value: true,
1351
+ enumerable: false,
1352
+ configurable: true
1126
1353
  });
1127
1354
  }
1128
- function formatFrameLocation(frame, cwd) {
1129
- const file = frame.file ? formatDisplayPath(frame.file, cwd) : "unknown";
1130
- const loc = frame.line ? `${file}:${frame.line}` : file;
1131
- const fn = frame.fn && frame.fn !== "<unknown>" ? frame.fn : undefined;
1132
- return fn ? `at ${fn} (${loc})` : `at ${loc}`;
1355
+ function cloneForRedaction(event) {
1356
+ try {
1357
+ return structuredClone(event);
1358
+ } catch {
1359
+ try {
1360
+ return JSON.parse(JSON.stringify(event));
1361
+ } catch {
1362
+ console.warn("[cloneForRedaction] Shallow clone used \u2014 nested objects may be mutated by redactPath, redactPatterns, and applyMaskersToTree");
1363
+ return { ...event };
1364
+ }
1365
+ }
1133
1366
  }
1134
- function formatCollapsedFrame(frame, cwd) {
1135
- const file = frame.file ? formatDisplayPath(frame.file, cwd) : "unknown";
1136
- const loc = frame.line ? `${file}:${frame.line}` : file;
1137
- const prefix = frame.fn?.startsWith("async") ? "at async " : "at ";
1138
- const fn = frame.fn?.replace(/^async /, "");
1139
- if (fn && fn !== "<unknown>" && fn !== loc)
1140
- return `${prefix}${fn} (${loc})`;
1141
- return `${prefix}${loc}`;
1367
+ function redactEvent(event, config) {
1368
+ const clone = cloneForRedaction(event);
1369
+ const replacement = config.replacement ?? DEFAULT_REPLACEMENT;
1370
+ if (config.transform)
1371
+ try {
1372
+ config.transform(clone);
1373
+ } catch (err) {
1374
+ console.error("[evlog] redact transform failed:", err);
1375
+ }
1376
+ const pathMatchers = config._pathMatchers ?? compileRedactPathMatchers(config.paths);
1377
+ if (pathMatchers)
1378
+ redactPathsInTree(clone, pathMatchers, replacement);
1379
+ if (config._maskers?.length)
1380
+ applyMaskersToTree(clone, config._maskers);
1381
+ if (config.patterns?.length)
1382
+ redactPatterns(clone, config.patterns, replacement);
1383
+ return clone;
1142
1384
  }
1143
- var GUIDANCE_WRAP_WIDTH = 76;
1144
- var GUIDANCE_CONTINUATION = " ";
1145
- function formatGuidanceLine(label, text, labelColor) {
1146
- const prefix = `${labelColor}${label}:${colors.reset} `;
1147
- const lines = [];
1148
- let remaining = text.trim();
1149
- let first = true;
1150
- while (remaining.length > 0) {
1151
- const budget = first ? Math.max(24, GUIDANCE_WRAP_WIDTH - prefix.length) : Math.max(24, GUIDANCE_WRAP_WIDTH - 5);
1152
- if (remaining.length <= budget) {
1153
- lines.push(first ? `${prefix}${remaining}` : `${GUIDANCE_CONTINUATION}${remaining}`);
1154
- break;
1385
+ function redactPatterns(obj, patterns, replacement, prefix = "") {
1386
+ if (obj === null || obj === undefined)
1387
+ return;
1388
+ if (Array.isArray(obj)) {
1389
+ for (let i = 0;i < obj.length; i++) {
1390
+ const key = String(i);
1391
+ const fullPath = prefix ? `${prefix}.${key}` : key;
1392
+ if (typeof obj[i] === "string")
1393
+ obj[i] = applyPatterns(obj[i], patterns, replacement, fullPath, key);
1394
+ else if (typeof obj[i] === "object")
1395
+ redactPatterns(obj[i], patterns, replacement, fullPath);
1396
+ }
1397
+ return;
1398
+ }
1399
+ if (typeof obj === "object") {
1400
+ const record = obj;
1401
+ for (const key of redactableKeys(record)) {
1402
+ const val = record[key];
1403
+ const fullPath = prefix ? `${prefix}.${key}` : key;
1404
+ if (typeof val === "string")
1405
+ setRedacted(record, key, applyPatterns(val, patterns, replacement, fullPath, key), fullPath);
1406
+ else if (typeof val === "object")
1407
+ redactPatterns(val, patterns, replacement, fullPath);
1155
1408
  }
1156
- let split = remaining.lastIndexOf(" ", budget);
1157
- if (split <= 0)
1158
- split = budget;
1159
- const chunk = remaining.slice(0, split).trimEnd();
1160
- lines.push(first ? `${prefix}${chunk}` : `${GUIDANCE_CONTINUATION}${chunk}`);
1161
- remaining = remaining.slice(split).trimStart();
1162
- first = false;
1163
1409
  }
1164
- return lines;
1165
1410
  }
1166
- function buildErrorEntries(error, options = {}) {
1167
- const normalized = normalizeErrorContext(error);
1168
- if (!normalized)
1169
- return [];
1170
- const cwd = options.cwd ?? (typeof process !== "undefined" && typeof process.cwd === "function" ? process.cwd() : ".");
1171
- const compact = options.compact ?? isDev();
1172
- const guidanceOnly = (options.detail ?? "full") === "guidance";
1173
- const showFrames = !guidanceOnly && !isBrowser() && (options.snippet ?? isDev());
1174
- const stackDepth = guidanceOnly ? 0 : options.stackDepth ?? (compact ? 2 : 3);
1175
- const snippetContextLines = compact ? 1 : 2;
1176
- const children = [];
1177
- const frames = guidanceOnly ? [] : parseStackFrames(normalized.stack);
1178
- const primary = guidanceOnly ? undefined : pickPrimaryFrame(frames);
1179
- if (!guidanceOnly && primary?.file && primary.line) {
1180
- pushTreeSpacer(children);
1181
- if (showFrames) {
1182
- const snippet = readCodeSnippet(primary.file, primary.line, snippetContextLines);
1183
- children.push(`${colors.dim} ${formatFrameLocation(primary, cwd)}${colors.reset}`);
1184
- if (snippet)
1185
- children.push(...formatSnippetLines(snippet));
1186
- } else
1187
- children.push(`${colors.dim} ${formatFrameLocation(primary, cwd)}${colors.reset}`);
1188
- }
1189
- if (normalized.code)
1190
- children.push(`${colors.dim}Code:${colors.reset} ${normalized.code}`);
1191
- if (Boolean(normalized.why || normalized.fix || normalized.link))
1192
- pushTreeSpacer(children);
1193
- if (normalized.why)
1194
- children.push(...formatGuidanceLine("Why", normalized.why, colors.yellow));
1195
- if (normalized.fix)
1196
- children.push(...formatGuidanceLine("Fix", normalized.fix, colors.cyan));
1197
- if (normalized.link)
1198
- children.push(`${colors.dim}More:${colors.reset} ${normalized.link}`);
1199
- if (normalized.cause && normalized.cause !== normalized.message)
1200
- children.push(`${colors.dim}Caused by:${colors.reset} ${normalized.cause}`);
1201
- const hiddenCount = guidanceOnly ? 0 : frames.filter((f) => !f.isApp || isInternalErrorFrame(f)).length;
1202
- const tailFrames = stackDepth > 0 ? frames.filter((f) => f !== primary && !isInternalErrorFrame(f)).slice(0, stackDepth) : [];
1203
- if (!guidanceOnly && (hiddenCount > 0 || tailFrames.length > 0)) {
1204
- pushTreeSpacer(children);
1205
- if (hiddenCount > 0)
1206
- children.push(`${colors.gray}stack (${hiddenCount} frame${hiddenCount === 1 ? "" : "s"} hidden in node_modules)${colors.reset}`);
1207
- else
1208
- children.push(`${colors.gray}stack${colors.reset}`);
1209
- for (const frame of tailFrames)
1210
- children.push(`${colors.gray} ${formatCollapsedFrame(frame, cwd)}${colors.reset}`);
1211
- }
1212
- return [{
1213
- key: "error",
1214
- value: `${colors.red}${colors.bold}${normalized.message}${colors.reset}`,
1215
- children: children.length > 0 ? children : undefined
1216
- }];
1217
- }
1218
-
1219
- // ../../node_modules/.bun/evlog@2.19.2+7724ce3de6b3bca4/node_modules/evlog/dist/dev-terminal-D4UaEm17.mjs
1220
- var DEV_PRESETS = {
1221
- evlog: {
1222
- frameworkOverlay: false,
1223
- detail: "full"
1224
- },
1225
- nitro: {
1226
- frameworkOverlay: true,
1227
- detail: "guidance"
1228
- },
1229
- both: {
1230
- frameworkOverlay: true,
1231
- detail: "full"
1232
- }
1233
- };
1234
- function finalizePrettyError(partial, frameworkOverlay, pretty, inDev) {
1235
- const compact = partial.compact ?? (inDev && pretty);
1236
- const detail = partial.detail ?? (frameworkOverlay ? "guidance" : "full");
1237
- const stackDepth = detail === "guidance" ? 0 : partial.stackDepth ?? (compact ? 2 : 3);
1238
- return {
1239
- snippet: partial.snippet ?? (detail === "full" && pretty && inDev),
1240
- stackDepth,
1241
- compact,
1242
- detail
1243
- };
1244
- }
1245
- function resolveDevTerminal(input = {}) {
1246
- const pretty = input.pretty ?? isDev();
1247
- const inDev = isDev();
1248
- let frameworkOverlay;
1249
- let prettyError = {};
1250
- if (typeof input.dev === "string" && input.dev in DEV_PRESETS) {
1251
- const { frameworkOverlay: presetOverlay, detail } = DEV_PRESETS[input.dev];
1252
- frameworkOverlay = presetOverlay;
1253
- prettyError = { detail };
1254
- } else if (input.dev && typeof input.dev === "object") {
1255
- const { frameworkOverlay: devOverlay, prettyError: devPrettyError } = input.dev;
1256
- frameworkOverlay = devOverlay;
1257
- if (devPrettyError)
1258
- prettyError = devPrettyError;
1259
- }
1260
- if (frameworkOverlay === undefined)
1261
- frameworkOverlay = !(pretty && inDev);
1262
- return {
1263
- frameworkOverlay,
1264
- prettyError: finalizePrettyError(prettyError, frameworkOverlay, pretty, inDev)
1265
- };
1266
- }
1267
-
1268
- // ../../node_modules/.bun/evlog@2.19.2+7724ce3de6b3bca4/node_modules/evlog/dist/audit-CL0q7GJU.mjs
1269
- var DEFAULT_REPLACEMENT = "[REDACTED]";
1270
- function normalizeRedactPathPattern(pattern) {
1271
- if (!pattern.includes("*") && !pattern.includes("."))
1272
- return `**.${pattern}`;
1273
- return pattern;
1274
- }
1275
- function compileRedactPathMatchers(patterns) {
1276
- if (!patterns?.length)
1277
- return;
1278
- const exactPaths = /* @__PURE__ */ new Set;
1279
- const pathGlobs = [];
1280
- const keyGlobs = [];
1281
- const caseInsensitiveLeaves = /* @__PURE__ */ new Set;
1282
- for (const raw of patterns) {
1283
- if (!raw.includes("*")) {
1284
- if (raw.includes("."))
1285
- exactPaths.add(raw);
1286
- else
1287
- addPathGlobPattern(normalizeRedactPathPattern(raw), exactPaths, pathGlobs, caseInsensitiveLeaves);
1411
+ function applyPatterns(value, patterns, replacement, path, key) {
1412
+ let result = value;
1413
+ for (const pattern of patterns) {
1414
+ if (typeof replacement === "string") {
1415
+ result = result.replace(pattern, replacement);
1288
1416
  continue;
1289
1417
  }
1290
- if (!raw.includes("."))
1291
- keyGlobs.push(globToRegExp(raw, "."));
1292
- else
1293
- addPathGlobPattern(raw, exactPaths, pathGlobs, caseInsensitiveLeaves);
1294
- }
1295
- if (exactPaths.size === 0 && pathGlobs.length === 0 && keyGlobs.length === 0 && caseInsensitiveLeaves.size === 0)
1296
- return;
1297
- return {
1298
- exactPaths,
1299
- pathGlobs,
1300
- keyGlobs,
1301
- caseInsensitiveLeaves
1302
- };
1303
- }
1304
- function addPathGlobPattern(pattern, exactPaths, pathGlobs, caseInsensitiveLeaves) {
1305
- pathGlobs.push(globToRegExp(pattern, "."));
1306
- const leaf = pattern.match(/^\*\*\.([^.?*]+)$/);
1307
- if (leaf) {
1308
- exactPaths.add(leaf[1]);
1309
- caseInsensitiveLeaves.add(leaf[1].toLowerCase());
1418
+ result = result.replace(pattern, (...args) => {
1419
+ const match = args[0];
1420
+ return resolveReplacement(replacement, match, {
1421
+ path,
1422
+ key,
1423
+ groups: captureGroups(args)
1424
+ });
1425
+ });
1310
1426
  }
1427
+ return result;
1311
1428
  }
1312
- function matchesRedactPath(fullPath, leafKey, matchers) {
1313
- if (matchers.exactPaths.has(fullPath))
1314
- return true;
1315
- if (matchers.caseInsensitiveLeaves.has(leafKey.toLowerCase()))
1316
- return true;
1317
- for (const glob of matchers.pathGlobs) {
1318
- glob.lastIndex = 0;
1319
- if (glob.test(fullPath))
1320
- return true;
1321
- }
1322
- for (const glob of matchers.keyGlobs) {
1323
- glob.lastIndex = 0;
1324
- if (glob.test(leafKey))
1325
- return true;
1326
- }
1327
- return false;
1429
+ function captureGroups(args) {
1430
+ const last = args.at(-1);
1431
+ const trailing = typeof last === "object" && last !== null ? 3 : 2;
1432
+ return args.slice(1, Math.max(1, args.length - trailing));
1328
1433
  }
1329
- function redactPathsInTree(obj, matchers, replacement, prefix = "") {
1434
+ function applyMaskersToTree(obj, maskers) {
1330
1435
  if (obj === null || obj === undefined)
1331
1436
  return;
1332
1437
  if (Array.isArray(obj)) {
1333
- for (let i = 0;i < obj.length; i++) {
1334
- const segment = String(i);
1335
- const fullPath = prefix ? `${prefix}.${segment}` : segment;
1336
- redactPathsInTree(obj[i], matchers, replacement, fullPath);
1337
- }
1438
+ for (let i = 0;i < obj.length; i++)
1439
+ if (typeof obj[i] === "string")
1440
+ obj[i] = applyMaskers(obj[i], maskers);
1441
+ else if (typeof obj[i] === "object")
1442
+ applyMaskersToTree(obj[i], maskers);
1338
1443
  return;
1339
1444
  }
1340
1445
  if (typeof obj === "object") {
1341
1446
  const record = obj;
1342
- for (const key in record) {
1343
- const fullPath = prefix ? `${prefix}.${key}` : key;
1344
- if (matchesRedactPath(fullPath, key, matchers))
1345
- record[key] = replacement;
1346
- else
1347
- redactPathsInTree(record[key], matchers, replacement, fullPath);
1348
- }
1349
- }
1350
- }
1351
- var builtinPatterns = {
1352
- creditCard: {
1353
- pattern: /\b\d{4}[\s-]?\d{4}[\s-]?\d{4}[\s-]?\d{4}\b/g,
1354
- mask: (m) => `****${m.replace(/[\s-]/g, "").slice(-4)}`
1355
- },
1356
- email: {
1357
- pattern: /[\w.+-]+@[\w-]+\.[\w.]+/g,
1358
- mask: (m) => {
1359
- if (m.indexOf("@") < 1)
1360
- return "***@***";
1361
- const tld = m.slice(m.lastIndexOf("."));
1362
- return `${m[0]}***@***${tld}`;
1363
- }
1364
- },
1365
- ipv4: {
1366
- pattern: /\b(?!0\.0\.0\.0\b)(?!127\.0\.0\.1\b)\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}\b/g,
1367
- mask: (m) => `***.***.***.${m.split(".").pop()}`
1368
- },
1369
- phone: {
1370
- pattern: /(?:\+\d{1,3}[\s.-]?\(?\d{1,4}\)?|\(\d{1,4}\))(?:[\s.-]?\d{2,4}){2,4}\b/g,
1371
- mask: (m) => {
1372
- const digits = m.replace(/[^\d]/g, "");
1373
- if (m.startsWith("+") && digits.length > 4) {
1374
- const ccMatch = m.match(/^\+\d{1,3}/);
1375
- return `${ccMatch ? ccMatch[0] : "+"}******${digits.slice(-2)}`;
1376
- }
1377
- if (digits.length > 2)
1378
- return `${"*".repeat(digits.length - 2)}${digits.slice(-2)}`;
1379
- return "***";
1380
- }
1381
- },
1382
- jwt: {
1383
- pattern: /\beyJ[\w-]*\.[\w-]*\.[\w-]*\b/g,
1384
- mask: () => "eyJ***.***"
1385
- },
1386
- bearer: {
1387
- pattern: /\bBearer\s+[\w\-.~+/]{8,}=*/gi,
1388
- mask: () => "Bearer ***"
1389
- },
1390
- iban: {
1391
- pattern: /\b[A-Z]{2}\d{2}[\s-]?[\dA-Z]{4}[\s-]?[\dA-Z]{4}[\s-]?[\dA-Z]{4}[\s-]?[\dA-Z]{0,4}[\s-]?[\dA-Z]{0,4}[\s-]?[\dA-Z]{0,4}\b/g,
1392
- mask: (m) => {
1393
- const clean = m.replace(/[\s-]/g, "");
1394
- return `${clean.slice(0, 4)}****${clean.slice(-3)}`;
1447
+ for (const key of redactableKeys(record)) {
1448
+ const val = record[key];
1449
+ if (typeof val === "string")
1450
+ setRedacted(record, key, applyMaskers(val, maskers), key);
1451
+ else if (typeof val === "object")
1452
+ applyMaskersToTree(val, maskers);
1395
1453
  }
1396
1454
  }
1397
- };
1398
- function resolveRedactConfig(input) {
1399
- if (input === undefined || input === false)
1400
- return;
1401
- if (input === true)
1402
- return { _maskers: allBuiltinMaskers() };
1403
- if (input.builtins === false)
1404
- return {
1405
- ...input,
1406
- _pathMatchers: compileRedactPathMatchers(input.paths)
1407
- };
1408
- const maskers = Array.isArray(input.builtins) ? input.builtins.map((name) => builtinPatterns[name]).filter(Boolean).map((b) => [cloneRegex(b.pattern), b.mask]) : allBuiltinMaskers();
1409
- return {
1410
- ...input,
1411
- _maskers: maskers,
1412
- _pathMatchers: compileRedactPathMatchers(input.paths)
1413
- };
1414
- }
1415
- function allBuiltinMaskers() {
1416
- return Object.values(builtinPatterns).map((b) => [cloneRegex(b.pattern), b.mask]);
1417
1455
  }
1418
- function cloneRegex(re) {
1419
- return new RegExp(re.source, re.flags);
1456
+ function applyMaskers(value, maskers) {
1457
+ let result = value;
1458
+ for (const [pattern, mask] of maskers)
1459
+ result = result.replace(pattern, mask);
1460
+ return result;
1420
1461
  }
1421
- var globallyRedacted = Symbol.for("evlog.globallyRedacted");
1422
- function markGloballyRedacted(event) {
1423
- Object.defineProperty(event, globallyRedacted, {
1424
- value: true,
1425
- enumerable: false,
1426
- configurable: true
1427
- });
1428
- }
1429
- function cloneForRedaction(event) {
1430
- try {
1431
- return structuredClone(event);
1432
- } catch {
1433
- try {
1434
- return JSON.parse(JSON.stringify(event));
1435
- } catch {
1436
- console.warn("[cloneForRedaction] Shallow clone used \u2014 nested objects may be mutated by redactPath, redactPatterns, and applyMaskersToTree");
1437
- return { ...event };
1438
- }
1439
- }
1440
- }
1441
- function redactEvent(event, config) {
1442
- const clone = cloneForRedaction(event);
1443
- const replacement = config.replacement ?? DEFAULT_REPLACEMENT;
1444
- const pathMatchers = config._pathMatchers ?? compileRedactPathMatchers(config.paths);
1445
- if (pathMatchers)
1446
- redactPathsInTree(clone, pathMatchers, replacement);
1447
- if (config._maskers?.length)
1448
- applyMaskersToTree(clone, config._maskers);
1449
- if (config.patterns?.length)
1450
- redactPatterns(clone, config.patterns, replacement);
1451
- return clone;
1452
- }
1453
- function redactPatterns(obj, patterns, replacement) {
1454
- if (obj === null || obj === undefined)
1455
- return;
1456
- if (Array.isArray(obj)) {
1457
- for (let i = 0;i < obj.length; i++)
1458
- if (typeof obj[i] === "string")
1459
- obj[i] = applyPatterns(obj[i], patterns, replacement);
1460
- else if (typeof obj[i] === "object")
1461
- redactPatterns(obj[i], patterns, replacement);
1462
- return;
1463
- }
1464
- if (typeof obj === "object") {
1465
- const record = obj;
1466
- for (const key in record) {
1467
- const val = record[key];
1468
- if (typeof val === "string")
1469
- record[key] = applyPatterns(val, patterns, replacement);
1470
- else if (typeof val === "object")
1471
- redactPatterns(val, patterns, replacement);
1472
- }
1473
- }
1474
- }
1475
- function applyPatterns(value, patterns, replacement) {
1476
- let result = value;
1477
- for (const pattern of patterns)
1478
- result = result.replace(pattern, replacement);
1479
- return result;
1480
- }
1481
- function applyMaskersToTree(obj, maskers) {
1482
- if (obj === null || obj === undefined)
1483
- return;
1484
- if (Array.isArray(obj)) {
1485
- for (let i = 0;i < obj.length; i++)
1486
- if (typeof obj[i] === "string")
1487
- obj[i] = applyMaskers(obj[i], maskers);
1488
- else if (typeof obj[i] === "object")
1489
- applyMaskersToTree(obj[i], maskers);
1490
- return;
1491
- }
1492
- if (typeof obj === "object") {
1493
- const record = obj;
1494
- for (const key in record) {
1495
- const val = record[key];
1496
- if (typeof val === "string")
1497
- record[key] = applyMaskers(val, maskers);
1498
- else if (typeof val === "object")
1499
- applyMaskersToTree(val, maskers);
1500
- }
1501
- }
1502
- }
1503
- function applyMaskers(value, maskers) {
1504
- let result = value;
1505
- for (const [pattern, mask] of maskers)
1506
- result = result.replace(pattern, mask);
1507
- return result;
1508
- }
1509
- function logPluginError(name, hook, err) {
1510
- console.error(`[evlog/${name}] ${hook} failed:`, err);
1462
+
1463
+ // ../../node_modules/.bun/evlog@2.28.1+4cac44d0f5802a4d/node_modules/evlog/dist/globalRegistry-Bh3bIGwA.mjs
1464
+ function logPluginError(name, hook, err) {
1465
+ console.error(`[evlog/${name}] ${hook} failed:`, err);
1511
1466
  }
1512
1467
  function createPluginRunner(plugins = []) {
1513
1468
  const byName = /* @__PURE__ */ new Map;
@@ -1613,10 +1568,408 @@ function createPluginRunner(plugins = []) {
1613
1568
  }
1614
1569
  };
1615
1570
  }
1616
- var emptyRunner = createPluginRunner([]);
1617
- function getEmptyPluginRunner() {
1618
- return emptyRunner;
1571
+ var emptyRunner = createPluginRunner([]);
1572
+ function getEmptyPluginRunner() {
1573
+ return emptyRunner;
1574
+ }
1575
+ var EVLOG_MAJOR = 2;
1576
+ var REGISTRY_KEY = Symbol.for(`evlog.registry.v${EVLOG_MAJOR}`);
1577
+ var MAJORS_KEY = Symbol.for("evlog.majors");
1578
+ function createConfig() {
1579
+ return {
1580
+ env: {
1581
+ service: "app",
1582
+ environment: "development"
1583
+ },
1584
+ pretty: isDev(),
1585
+ prettyError: {
1586
+ snippet: isDev(),
1587
+ stackDepth: 2,
1588
+ compact: isDev(),
1589
+ detail: "full"
1590
+ },
1591
+ sampling: {},
1592
+ stringify: true,
1593
+ drain: undefined,
1594
+ redact: undefined,
1595
+ enabled: true,
1596
+ silent: false,
1597
+ minLevel: "debug",
1598
+ locked: false,
1599
+ initialized: false,
1600
+ pluginRunner: getEmptyPluginRunner()
1601
+ };
1602
+ }
1603
+ function warnOnMultiMajor(host) {
1604
+ const majors = host[MAJORS_KEY] ??= /* @__PURE__ */ new Set;
1605
+ if (majors.has(EVLOG_MAJOR))
1606
+ return;
1607
+ majors.add(EVLOG_MAJOR);
1608
+ if (majors.size > 1)
1609
+ console.warn(`[evlog] Multiple major versions of evlog are loaded in this process (${[...majors].map((m) => `${m}.x`).join(", ")}). They cannot share request scope or logger configuration: events emitted through the other copy will be undrained and unredacted, and useLogger() may throw. Deduplicate evlog to a single major.`);
1610
+ }
1611
+ function getRegistry() {
1612
+ const host = globalThis;
1613
+ warnOnMultiMajor(host);
1614
+ return host[REGISTRY_KEY] ??= {
1615
+ config: createConfig(),
1616
+ storages: /* @__PURE__ */ new Map
1617
+ };
1618
+ }
1619
+ var globalConfig = getRegistry().config;
1620
+
1621
+ // ../../node_modules/.bun/evlog@2.28.1+4cac44d0f5802a4d/node_modules/evlog/dist/pretty-error-DTIHxnBN.mjs
1622
+ var snippetReader = null;
1623
+ var PRETTY_ERROR_TREE_SPACER = "__EVLOG_TREE_SPACER__";
1624
+ function pushTreeSpacer(children) {
1625
+ children.push(PRETTY_ERROR_TREE_SPACER);
1626
+ }
1627
+ var SKIP_PATH_RE = /(?:^|[/\\])(?:node_modules|\.nuxt|\.next|\.output)(?:[/\\]|$)/;
1628
+ var SKIP_FRAME_PATH_RE = /(?:^|[/\\])(?:packages[/\\]evlog|evlog[/\\](?:dist|src))(?:[/\\]|$)/;
1629
+ var SKIP_FRAME_FN_RE = /^(?:createError|EvlogError|new EvlogError)$/;
1630
+ function isPlainObject(val) {
1631
+ return val !== null && typeof val === "object" && !Array.isArray(val);
1632
+ }
1633
+ function pickString(obj, key) {
1634
+ const val = obj[key];
1635
+ return typeof val === "string" && val.length > 0 ? val : undefined;
1636
+ }
1637
+ function pickNumber(obj, key) {
1638
+ const val = obj[key];
1639
+ return typeof val === "number" ? val : undefined;
1640
+ }
1641
+ function extractGuidance(data) {
1642
+ return {
1643
+ code: pickString(data, "code"),
1644
+ why: pickString(data, "why"),
1645
+ fix: pickString(data, "fix"),
1646
+ link: pickString(data, "link")
1647
+ };
1648
+ }
1649
+ function normalizeErrorContext(error) {
1650
+ if (error === null || error === undefined)
1651
+ return null;
1652
+ if (typeof error === "string")
1653
+ return { message: error };
1654
+ if (!isPlainObject(error))
1655
+ return { message: String(error) };
1656
+ const result = {
1657
+ message: pickString(error, "message") ?? pickString(error, "statusText") ?? pickString(error, "statusMessage") ?? "Unknown error",
1658
+ name: pickString(error, "name"),
1659
+ code: pickString(error, "code"),
1660
+ why: pickString(error, "why"),
1661
+ fix: pickString(error, "fix"),
1662
+ link: pickString(error, "link"),
1663
+ status: pickNumber(error, "status") ?? pickNumber(error, "statusCode"),
1664
+ stack: pickString(error, "stack")
1665
+ };
1666
+ const { data, cause } = error;
1667
+ if (isPlainObject(data)) {
1668
+ const guidance = extractGuidance(data);
1669
+ if (!result.code)
1670
+ result.code = guidance.code;
1671
+ if (!result.why)
1672
+ result.why = guidance.why;
1673
+ if (!result.fix)
1674
+ result.fix = guidance.fix;
1675
+ if (!result.link)
1676
+ result.link = guidance.link;
1677
+ }
1678
+ if (cause instanceof Error)
1679
+ result.cause = cause.message;
1680
+ else if (isPlainObject(cause) && pickString(cause, "message"))
1681
+ result.cause = pickString(cause, "message");
1682
+ return result;
1683
+ }
1684
+ function decodeFileUrl(file) {
1685
+ if (file.startsWith("file://"))
1686
+ try {
1687
+ return decodeURIComponent(new URL(file).pathname);
1688
+ } catch {
1689
+ return file.slice(7);
1690
+ }
1691
+ return file;
1692
+ }
1693
+ function isAppPath(file) {
1694
+ const normalized = decodeFileUrl(file).replace(/\\/g, "/");
1695
+ if (normalized.startsWith("node:"))
1696
+ return false;
1697
+ if (SKIP_PATH_RE.test(normalized))
1698
+ return false;
1699
+ if (normalized.includes("/node_modules/"))
1700
+ return false;
1701
+ if (isFrameworkRuntimePath(normalized))
1702
+ return false;
1703
+ return true;
1704
+ }
1705
+ function formatDisplayPath(file, cwd) {
1706
+ const decoded = decodeFileUrl(file).replace(/\\/g, "/");
1707
+ const cwdNorm = cwd.replace(/\\/g, "/").replace(/\/$/, "");
1708
+ if (cwdNorm && decoded.startsWith(`${cwdNorm}/`)) {
1709
+ const rel = decoded.slice(cwdNorm.length + 1);
1710
+ return rel.startsWith("./") ? rel.slice(2) : rel;
1711
+ }
1712
+ const serverIdx = decoded.indexOf("/server/");
1713
+ if (serverIdx >= 0)
1714
+ return decoded.slice(serverIdx + 1);
1715
+ const srcIdx = decoded.indexOf("/src/");
1716
+ if (srcIdx >= 0)
1717
+ return decoded.slice(srcIdx + 1);
1718
+ return decoded;
1719
+ }
1720
+ function parseStackFrames(stack) {
1721
+ if (!stack)
1722
+ return [];
1723
+ const lines = stack.split(`
1724
+ `);
1725
+ const frames = [];
1726
+ for (const line of lines) {
1727
+ const trimmed = line.trim();
1728
+ if (!trimmed.startsWith("at "))
1729
+ continue;
1730
+ const withFn = trimmed.match(/^at (.+?) \((.+):(\d+):(\d+)\)$/);
1731
+ if (withFn) {
1732
+ const [, fn, file, lineStr, colStr] = withFn;
1733
+ frames.push({
1734
+ raw: trimmed,
1735
+ fn,
1736
+ file,
1737
+ line: Number(lineStr),
1738
+ column: Number(colStr),
1739
+ isApp: isAppPath(file)
1740
+ });
1741
+ continue;
1742
+ }
1743
+ const withoutFn = trimmed.match(/^at (.+):(\d+):(\d+)$/);
1744
+ if (withoutFn) {
1745
+ const [, file, lineStr, colStr] = withoutFn;
1746
+ frames.push({
1747
+ raw: trimmed,
1748
+ file,
1749
+ line: Number(lineStr),
1750
+ column: Number(colStr),
1751
+ isApp: isAppPath(file)
1752
+ });
1753
+ continue;
1754
+ }
1755
+ const asyncFn = trimmed.match(/^at async (.+?) \((.+):(\d+):(\d+)\)$/);
1756
+ if (asyncFn) {
1757
+ const [, fn, file, lineStr, colStr] = asyncFn;
1758
+ frames.push({
1759
+ raw: trimmed,
1760
+ fn: `async ${fn}`,
1761
+ file,
1762
+ line: Number(lineStr),
1763
+ column: Number(colStr),
1764
+ isApp: isAppPath(file)
1765
+ });
1766
+ }
1767
+ }
1768
+ return frames;
1769
+ }
1770
+ function isFrameworkRuntimePath(path) {
1771
+ const normalized = path.replace(/\\/g, "/");
1772
+ return normalized.includes("route-modules/") || normalized.includes("webpack://next/") || normalized.includes("/next/dist/") || normalized.includes("/compiled/next-server/");
1773
+ }
1774
+ function isFrameworkRuntimeFrame(frame) {
1775
+ if (!frame.file)
1776
+ return false;
1777
+ return isFrameworkRuntimePath(decodeFileUrl(frame.file));
1778
+ }
1779
+ function isInternalErrorFrame(frame) {
1780
+ if (isFrameworkRuntimeFrame(frame))
1781
+ return true;
1782
+ if (frame.fn) {
1783
+ const fn = frame.fn.replace(/^async /, "");
1784
+ if (SKIP_FRAME_FN_RE.test(fn))
1785
+ return true;
1786
+ }
1787
+ if (!frame.file)
1788
+ return true;
1789
+ const path = decodeFileUrl(frame.file).replace(/\\/g, "/");
1790
+ if (SKIP_FRAME_PATH_RE.test(path))
1791
+ return true;
1792
+ if (path.includes(".nuxt/"))
1793
+ return true;
1794
+ if (path.includes(".next/"))
1795
+ return true;
1796
+ return false;
1797
+ }
1798
+ function pickPrimaryFrame(frames) {
1799
+ for (const frame of frames)
1800
+ if (frame.isApp && frame.file && frame.line && !isInternalErrorFrame(frame))
1801
+ return frame;
1802
+ }
1803
+ function readCodeSnippet(file, line, contextLines = 2) {
1804
+ if (!isDev() || isBrowser() || !snippetReader)
1805
+ return null;
1806
+ const path = decodeFileUrl(file).replace(/\\/g, "/");
1807
+ if (path.includes(".next/") || path.includes(".nuxt/") || path.includes(".output/"))
1808
+ return null;
1809
+ return snippetReader(file, line, contextLines);
1810
+ }
1811
+ function formatSnippetLines(snippet) {
1812
+ const width = String(snippet[snippet.length - 1]?.line ?? 0).length;
1813
+ return snippet.map(({ line, content, isErrorLine }) => {
1814
+ const marker = isErrorLine ? `${colors.red}\u276F${colors.reset}` : `${colors.dim} ${colors.reset}`;
1815
+ const numColor = isErrorLine ? colors.red : colors.gray;
1816
+ const trimmed = content.length > 120 ? `${content.slice(0, 117)}\u2026` : content;
1817
+ return `${marker} ${numColor}${String(line).padStart(width, " ")}${colors.reset} ${colors.dim}\u2503${colors.reset} ${colors.dim}${trimmed}${colors.reset}`;
1818
+ });
1819
+ }
1820
+ function formatFrameLocation(frame, cwd) {
1821
+ const file = frame.file ? formatDisplayPath(frame.file, cwd) : "unknown";
1822
+ const loc = frame.line ? `${file}:${frame.line}` : file;
1823
+ const fn = frame.fn && frame.fn !== "<unknown>" ? frame.fn : undefined;
1824
+ return fn ? `at ${fn} (${loc})` : `at ${loc}`;
1825
+ }
1826
+ function formatCollapsedFrame(frame, cwd) {
1827
+ const file = frame.file ? formatDisplayPath(frame.file, cwd) : "unknown";
1828
+ const loc = frame.line ? `${file}:${frame.line}` : file;
1829
+ const prefix = frame.fn?.startsWith("async") ? "at async " : "at ";
1830
+ const fn = frame.fn?.replace(/^async /, "");
1831
+ if (fn && fn !== "<unknown>" && fn !== loc)
1832
+ return `${prefix}${fn} (${loc})`;
1833
+ return `${prefix}${loc}`;
1834
+ }
1835
+ var GUIDANCE_WRAP_WIDTH = 76;
1836
+ var GUIDANCE_CONTINUATION = " ";
1837
+ function formatGuidanceLine(label, text, labelColor) {
1838
+ const prefix = `${labelColor}${label}:${colors.reset} `;
1839
+ const lines = [];
1840
+ let remaining = text.trim();
1841
+ let first = true;
1842
+ while (remaining.length > 0) {
1843
+ const budget = first ? Math.max(24, GUIDANCE_WRAP_WIDTH - prefix.length) : Math.max(24, GUIDANCE_WRAP_WIDTH - 5);
1844
+ if (remaining.length <= budget) {
1845
+ lines.push(first ? `${prefix}${remaining}` : `${GUIDANCE_CONTINUATION}${remaining}`);
1846
+ break;
1847
+ }
1848
+ let split = remaining.lastIndexOf(" ", budget);
1849
+ if (split <= 0)
1850
+ split = budget;
1851
+ const chunk = remaining.slice(0, split).trimEnd();
1852
+ lines.push(first ? `${prefix}${chunk}` : `${GUIDANCE_CONTINUATION}${chunk}`);
1853
+ remaining = remaining.slice(split).trimStart();
1854
+ first = false;
1855
+ }
1856
+ return lines;
1857
+ }
1858
+ function buildErrorEntries(error, options = {}) {
1859
+ const normalized = normalizeErrorContext(error);
1860
+ if (!normalized)
1861
+ return [];
1862
+ const cwd = options.cwd ?? (typeof process !== "undefined" && typeof process.cwd === "function" ? process.cwd() : ".");
1863
+ const compact = options.compact ?? isDev();
1864
+ const guidanceOnly = (options.detail ?? "full") === "guidance";
1865
+ const showFrames = !guidanceOnly && !isBrowser() && (options.snippet ?? isDev());
1866
+ const stackDepth = guidanceOnly ? 0 : options.stackDepth ?? (compact ? 2 : 3);
1867
+ const snippetContextLines = compact ? 1 : 2;
1868
+ const children = [];
1869
+ const frames = guidanceOnly ? [] : parseStackFrames(normalized.stack);
1870
+ const primary = guidanceOnly ? undefined : pickPrimaryFrame(frames);
1871
+ if (!guidanceOnly && primary?.file && primary.line) {
1872
+ pushTreeSpacer(children);
1873
+ if (showFrames) {
1874
+ const snippet = readCodeSnippet(primary.file, primary.line, snippetContextLines);
1875
+ children.push(`${colors.dim} ${formatFrameLocation(primary, cwd)}${colors.reset}`);
1876
+ if (snippet)
1877
+ children.push(...formatSnippetLines(snippet));
1878
+ } else
1879
+ children.push(`${colors.dim} ${formatFrameLocation(primary, cwd)}${colors.reset}`);
1880
+ }
1881
+ if (normalized.code)
1882
+ children.push(`${colors.dim}Code:${colors.reset} ${normalized.code}`);
1883
+ if (Boolean(normalized.why || normalized.fix || normalized.link))
1884
+ pushTreeSpacer(children);
1885
+ if (normalized.why)
1886
+ children.push(...formatGuidanceLine("Why", normalized.why, colors.yellow));
1887
+ if (normalized.fix)
1888
+ children.push(...formatGuidanceLine("Fix", normalized.fix, colors.cyan));
1889
+ if (normalized.link)
1890
+ children.push(`${colors.dim}More:${colors.reset} ${normalized.link}`);
1891
+ if (normalized.cause && normalized.cause !== normalized.message)
1892
+ children.push(`${colors.dim}Caused by:${colors.reset} ${normalized.cause}`);
1893
+ const hiddenCount = guidanceOnly ? 0 : frames.filter((f) => !f.isApp || isInternalErrorFrame(f)).length;
1894
+ const tailFrames = stackDepth > 0 ? frames.filter((f) => f !== primary && !isInternalErrorFrame(f)).slice(0, stackDepth) : [];
1895
+ if (!guidanceOnly && (hiddenCount > 0 || tailFrames.length > 0)) {
1896
+ pushTreeSpacer(children);
1897
+ if (hiddenCount > 0)
1898
+ children.push(`${colors.gray}stack (${hiddenCount} frame${hiddenCount === 1 ? "" : "s"} hidden in node_modules)${colors.reset}`);
1899
+ else
1900
+ children.push(`${colors.gray}stack${colors.reset}`);
1901
+ for (const frame of tailFrames)
1902
+ children.push(`${colors.gray} ${formatCollapsedFrame(frame, cwd)}${colors.reset}`);
1903
+ }
1904
+ return [{
1905
+ key: "error",
1906
+ value: `${colors.red}${colors.bold}${normalized.message}${colors.reset}`,
1907
+ children: children.length > 0 ? children : undefined
1908
+ }];
1909
+ }
1910
+
1911
+ // ../../node_modules/.bun/evlog@2.28.1+4cac44d0f5802a4d/node_modules/evlog/dist/dev-terminal-Brarc6vc.mjs
1912
+ var DEV_PRESETS = {
1913
+ evlog: {
1914
+ frameworkOverlay: false,
1915
+ detail: "full"
1916
+ },
1917
+ nitro: {
1918
+ frameworkOverlay: true,
1919
+ detail: "guidance"
1920
+ },
1921
+ both: {
1922
+ frameworkOverlay: true,
1923
+ detail: "full"
1924
+ }
1925
+ };
1926
+ function finalizePrettyError(partial, frameworkOverlay, pretty, inDev) {
1927
+ const compact = partial.compact ?? (inDev && pretty);
1928
+ const detail = partial.detail ?? (frameworkOverlay ? "guidance" : "full");
1929
+ const stackDepth = detail === "guidance" ? 0 : partial.stackDepth ?? (compact ? 2 : 3);
1930
+ return {
1931
+ snippet: partial.snippet ?? (detail === "full" && pretty && inDev),
1932
+ stackDepth,
1933
+ compact,
1934
+ detail
1935
+ };
1936
+ }
1937
+ function resolveDevTerminal(input = {}) {
1938
+ const pretty = input.pretty ?? isDev();
1939
+ const inDev = isDev();
1940
+ let frameworkOverlay;
1941
+ let prettyError = {};
1942
+ if (typeof input.dev === "string" && input.dev in DEV_PRESETS) {
1943
+ const { frameworkOverlay: presetOverlay, detail } = DEV_PRESETS[input.dev];
1944
+ frameworkOverlay = presetOverlay;
1945
+ prettyError = { detail };
1946
+ } else if (input.dev && typeof input.dev === "object") {
1947
+ const { frameworkOverlay: devOverlay, prettyError: devPrettyError } = input.dev;
1948
+ frameworkOverlay = devOverlay;
1949
+ if (devPrettyError)
1950
+ prettyError = devPrettyError;
1951
+ }
1952
+ if (frameworkOverlay === undefined)
1953
+ frameworkOverlay = !(pretty && inDev);
1954
+ return {
1955
+ frameworkOverlay,
1956
+ prettyError: finalizePrettyError(prettyError, frameworkOverlay, pretty, inDev)
1957
+ };
1958
+ }
1959
+
1960
+ // ../../node_modules/.bun/evlog@2.28.1+4cac44d0f5802a4d/node_modules/evlog/dist/wideEventChannel-BUDW48oP.mjs
1961
+ var publisher = null;
1962
+ function publishWideEvent(event) {
1963
+ if (!publisher)
1964
+ return;
1965
+ try {
1966
+ publisher(event);
1967
+ } catch (err) {
1968
+ console.error("[evlog] diagnostics channel publish failed:", err);
1969
+ }
1619
1970
  }
1971
+
1972
+ // ../../node_modules/.bun/evlog@2.28.1+4cac44d0f5802a4d/node_modules/evlog/dist/audit-CW8wdQDm.mjs
1620
1973
  var nativeStdoutWrite = typeof process !== "undefined" && typeof process.stdout?.write === "function" ? process.stdout.write.bind(process.stdout) : undefined;
1621
1974
  function writePrettyStdout(text) {
1622
1975
  (globalThis.__evlogNativeStdoutWrite ?? nativeStdoutWrite)?.(text);
@@ -1624,57 +1977,35 @@ function writePrettyStdout(text) {
1624
1977
  function isPlainObject$1(val) {
1625
1978
  return val !== null && typeof val === "object" && !Array.isArray(val);
1626
1979
  }
1627
- var _tsDate = /* @__PURE__ */ new Date;
1628
- function isoNow() {
1629
- _tsDate.setTime(Date.now());
1630
- return _tsDate.toISOString();
1631
- }
1632
- var globalEnv = {
1633
- service: "app",
1634
- environment: "development"
1635
- };
1636
- var globalPretty = isDev();
1637
- var globalPrettyError = {
1638
- snippet: isDev(),
1639
- stackDepth: 2,
1640
- compact: isDev(),
1641
- detail: "full"
1642
- };
1643
- var globalSampling = {};
1644
- var globalStringify = true;
1645
- var globalDrain;
1646
- var globalRedact;
1647
- var globalEnabled = true;
1648
- var globalSilent = false;
1649
- var globalMinLevel = "debug";
1650
- var globalPluginRunner = getEmptyPluginRunner();
1980
+ var state = globalConfig;
1651
1981
  function initLogger(config = {}) {
1652
- globalEnabled = config.enabled ?? true;
1982
+ state.enabled = config.enabled ?? true;
1653
1983
  const detected = detectEnvironment();
1654
- globalEnv = {
1984
+ state.env = {
1655
1985
  service: config.env?.service ?? detected.service ?? "app",
1656
1986
  environment: config.env?.environment ?? detected.environment ?? "development",
1657
1987
  version: config.env?.version ?? detected.version,
1658
1988
  commitHash: config.env?.commitHash ?? detected.commitHash,
1659
1989
  region: config.env?.region ?? detected.region
1660
1990
  };
1661
- globalPretty = config.pretty ?? isDev();
1662
- globalPrettyError = resolveDevTerminal(config).prettyError;
1663
- globalSampling = config.sampling ?? {};
1664
- globalStringify = config.stringify ?? true;
1665
- globalDrain = config.drain;
1666
- globalRedact = resolveRedactConfig(config.redact ?? !isDev());
1667
- globalSilent = config.silent ?? false;
1668
- globalMinLevel = config.minLevel ?? "debug";
1669
- globalPluginRunner = config.plugins?.length ? createPluginRunner(config.plugins) : getEmptyPluginRunner();
1670
- if (globalPluginRunner.plugins.length > 0)
1671
- globalPluginRunner.runSetup({ env: { ...globalEnv } });
1672
- const hasAnyDrain = !!globalDrain || globalPluginRunner.hasDrain;
1673
- if (globalSilent && !hasAnyDrain && !config._suppressDrainWarning)
1991
+ state.pretty = config.pretty ?? isDev();
1992
+ state.prettyError = resolveDevTerminal(config).prettyError;
1993
+ state.sampling = config.sampling ?? {};
1994
+ state.stringify = config.stringify ?? true;
1995
+ state.drain = config.drain;
1996
+ state.redact = resolveRedactConfig(config.redact ?? !isDev());
1997
+ state.silent = config.silent ?? false;
1998
+ state.minLevel = config.minLevel ?? "debug";
1999
+ state.pluginRunner = config.plugins?.length ? createPluginRunner(config.plugins) : getEmptyPluginRunner();
2000
+ if (state.pluginRunner.plugins.length > 0)
2001
+ state.pluginRunner.runSetup({ env: { ...state.env } });
2002
+ const hasAnyDrain = !!state.drain || state.pluginRunner.hasDrain;
2003
+ if (state.silent && !hasAnyDrain && !config._suppressDrainWarning)
1674
2004
  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).");
2005
+ state.initialized = true;
1675
2006
  }
1676
2007
  function shouldSample(level) {
1677
- const { rates } = globalSampling;
2008
+ const { rates } = state.sampling;
1678
2009
  if (!rates)
1679
2010
  return true;
1680
2011
  const percentage = level === "error" && rates.error === undefined ? 100 : rates[level] ?? 100;
@@ -1686,10 +2017,10 @@ function shouldSample(level) {
1686
2017
  }
1687
2018
  function emitWideEvent(level, event, options = {}) {
1688
2019
  const { deferDrain = false, ownsEvent = false, waitUntil } = options;
1689
- if (!globalEnabled)
2020
+ if (!state.enabled)
1690
2021
  return null;
1691
2022
  if (!ownsEvent) {
1692
- if (!isLevelEnabled(level, globalMinLevel))
2023
+ if (!isLevelEnabled(level, state.minLevel))
1693
2024
  return null;
1694
2025
  if (!shouldSample(level))
1695
2026
  return null;
@@ -1699,57 +2030,58 @@ function emitWideEvent(level, event, options = {}) {
1699
2030
  event.timestamp = isoNow();
1700
2031
  event.level = level;
1701
2032
  if (event.service === undefined)
1702
- event.service = globalEnv.service;
2033
+ event.service = state.env.service;
1703
2034
  if (event.environment === undefined)
1704
- event.environment = globalEnv.environment;
1705
- if (globalEnv.version !== undefined && event.version === undefined)
1706
- event.version = globalEnv.version;
1707
- if (globalEnv.commitHash !== undefined && event.commitHash === undefined)
1708
- event.commitHash = globalEnv.commitHash;
1709
- if (globalEnv.region !== undefined && event.region === undefined)
1710
- event.region = globalEnv.region;
2035
+ event.environment = state.env.environment;
2036
+ if (state.env.version !== undefined && event.version === undefined)
2037
+ event.version = state.env.version;
2038
+ if (state.env.commitHash !== undefined && event.commitHash === undefined)
2039
+ event.commitHash = state.env.commitHash;
2040
+ if (state.env.region !== undefined && event.region === undefined)
2041
+ event.region = state.env.region;
1711
2042
  formatted = event;
1712
2043
  } else
1713
2044
  formatted = {
1714
2045
  timestamp: isoNow(),
1715
2046
  level,
1716
- ...globalEnv,
2047
+ ...state.env,
1717
2048
  ...event
1718
2049
  };
1719
2050
  finalizeAudit(formatted);
1720
- if (globalRedact) {
1721
- formatted = redactEvent(formatted, globalRedact);
2051
+ if (state.redact) {
2052
+ formatted = redactEvent(formatted, state.redact);
1722
2053
  markGloballyRedacted(formatted);
1723
2054
  }
1724
- if (!globalSilent)
1725
- if (globalPretty)
2055
+ if (!state.silent)
2056
+ if (state.pretty)
1726
2057
  prettyPrintWideEvent(formatted);
1727
- else if (globalStringify)
2058
+ else if (state.stringify)
1728
2059
  console[getConsoleMethod(level)](JSON.stringify(formatted));
1729
2060
  else
1730
2061
  console[getConsoleMethod(level)](formatted);
1731
2062
  if (!deferDrain) {
2063
+ publishWideEvent(formatted);
1732
2064
  const drainPromises = [];
1733
- if (globalDrain)
2065
+ if (state.drain)
1734
2066
  drainPromises.push((async () => {
1735
2067
  try {
1736
- await globalDrain({ event: formatted });
2068
+ await state.drain({ event: formatted });
1737
2069
  } catch (err) {
1738
2070
  console.error("[evlog] drain failed:", err);
1739
2071
  }
1740
2072
  })());
1741
- if (globalPluginRunner.hasDrain)
1742
- drainPromises.push(globalPluginRunner.runDrain({ event: formatted }));
2073
+ if (state.pluginRunner.hasDrain)
2074
+ drainPromises.push(state.pluginRunner.runDrain({ event: formatted }));
1743
2075
  if (drainPromises.length > 0 && waitUntil)
1744
2076
  waitUntil(Promise.all(drainPromises));
1745
2077
  }
1746
2078
  return formatted;
1747
2079
  }
1748
2080
  function emitTaggedLog(level, tag, message) {
1749
- if (!globalEnabled)
2081
+ if (!state.enabled)
1750
2082
  return;
1751
- if (globalPretty && !globalSilent) {
1752
- if (!isLevelEnabled(level, globalMinLevel))
2083
+ if (state.pretty && !state.silent) {
2084
+ if (!isLevelEnabled(level, state.minLevel))
1753
2085
  return;
1754
2086
  if (!shouldSample(level))
1755
2087
  return;
@@ -1772,6 +2104,8 @@ function emitTaggedLog(level, tag, message) {
1772
2104
  function formatValue(value) {
1773
2105
  if (value === null || value === undefined)
1774
2106
  return String(value);
2107
+ if (Array.isArray(value))
2108
+ return JSON.stringify(value);
1775
2109
  if (isPlainObject$1(value)) {
1776
2110
  const pairs = [];
1777
2111
  for (const [k, v] of Object.entries(value))
@@ -2037,10 +2371,7 @@ function prettyPrintWideEvent(event) {
2037
2371
  styles.push(cssColors.dim, cssColors.reset, lc, cssColors.reset, cssColors.cyan, cssColors.reset);
2038
2372
  } else {
2039
2373
  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}`);
2374
+ parts.push(`${colors.dim}${ts}${colors.reset} ${lc}${levelLabel.toUpperCase()}${colors.reset} ${colors.cyan}[${service}]${colors.reset}`);
2044
2375
  }
2045
2376
  if (rest.method && rest.path) {
2046
2377
  parts.push(browser ? ` ${escapeFormatString(String(rest.method))} ${escapeFormatString(String(rest.path))}` : ` ${rest.method} ${rest.path}`);
@@ -2065,6 +2396,7 @@ function prettyPrintWideEvent(event) {
2065
2396
  parts.push(` ${colors.dim}in ${rest.duration}${colors.reset}`);
2066
2397
  delete rest.duration;
2067
2398
  }
2399
+ delete rest.durationMs;
2068
2400
  writeLine(parts.join(""), ...styles);
2069
2401
  const aiData = isPlainObject$1(rest.ai) ? rest.ai : undefined;
2070
2402
  if (aiData)
@@ -2074,7 +2406,7 @@ function prettyPrintWideEvent(event) {
2074
2406
  delete rest.error;
2075
2407
  const restEntries = Object.entries(rest).filter(([_, v]) => v !== undefined);
2076
2408
  const aiEntries = aiData ? buildAIEntries(aiData) : [];
2077
- const errorEntries = errorData !== undefined ? buildErrorEntries(errorData, globalPrettyError) : [];
2409
+ const errorEntries = errorData !== undefined ? buildErrorEntries(errorData, state.prettyError) : [];
2078
2410
  const contextEntries = [...restEntries.map(([key, value]) => ({
2079
2411
  key,
2080
2412
  value: formatValue(value)
@@ -2210,9 +2542,15 @@ function decorateAudit(audit, timestamp) {
2210
2542
  idempotencyKey: computeIdempotencyKey(audit, timestamp)
2211
2543
  };
2212
2544
  }
2545
+ function isCompleteAuditFields(a) {
2546
+ if (!a || typeof a !== "object")
2547
+ return false;
2548
+ const audit = a;
2549
+ return typeof audit.action === "string" && typeof audit.actor?.type === "string" && typeof audit.actor?.id === "string";
2550
+ }
2213
2551
  function finalizeAudit(event) {
2214
2552
  const a = event.audit;
2215
- if (!a)
2553
+ if (!isCompleteAuditFields(a))
2216
2554
  return;
2217
2555
  const decorated = decorateAudit(a, String(event.timestamp));
2218
2556
  event.audit = decorated;
@@ -2221,8 +2559,7 @@ function finalizeAudit(event) {
2221
2559
  // src/client/router/provider.tsx
2222
2560
  import { useCallback as useCallback2, useEffect, useLayoutEffect, useMemo, useRef, useState } from "react";
2223
2561
 
2224
- // ../../node_modules/.bun/seroval@1.5.4/node_modules/seroval/dist/esm/development/index.mjs
2225
- var ALL_ENABLED = 1 | 2 | 4 | 8 | 16 | 32;
2562
+ // ../../node_modules/.bun/seroval@1.6.5/node_modules/seroval/dist/dev/index.js
2226
2563
  var SYM_ASYNC_ITERATOR = Symbol.asyncIterator;
2227
2564
  var SYM_HAS_INSTANCE = Symbol.hasInstance;
2228
2565
  var SYM_IS_CONCAT_SPREADABLE = Symbol.isConcatSpreadable;
@@ -2266,16 +2603,15 @@ var SYMBOL_REF = {
2266
2603
  [11]: SYM_TO_STRING_TAG,
2267
2604
  [12]: SYM_UNSCOPABLES
2268
2605
  };
2269
- var NIL = undefined;
2270
2606
  var CONSTANT_VAL = {
2271
2607
  [2]: true,
2272
2608
  [3]: false,
2273
- [1]: NIL,
2609
+ [1]: undefined,
2274
2610
  [0]: null,
2275
2611
  [4]: -0,
2276
2612
  [5]: Number.POSITIVE_INFINITY,
2277
2613
  [6]: Number.NEGATIVE_INFINITY,
2278
- [7]: Number.NaN
2614
+ [7]: NaN
2279
2615
  };
2280
2616
  var ERROR_CONSTRUCTOR = {
2281
2617
  [0]: Error,
@@ -2310,7 +2646,7 @@ function serializeChar(str) {
2310
2646
  case "\u2029":
2311
2647
  return "\\u2029";
2312
2648
  default:
2313
- return NIL;
2649
+ return;
2314
2650
  }
2315
2651
  }
2316
2652
  function serializeString(str) {
@@ -2324,11 +2660,10 @@ function serializeString(str) {
2324
2660
  lastPos = i + 1;
2325
2661
  }
2326
2662
  }
2327
- if (lastPos === 0) {
2663
+ if (lastPos === 0)
2328
2664
  result = str;
2329
- } else {
2665
+ else
2330
2666
  result += str.slice(lastPos);
2331
- }
2332
2667
  return result;
2333
2668
  }
2334
2669
  function deserializeReplacer(str) {
@@ -2361,51 +2696,9 @@ function deserializeReplacer(str) {
2361
2696
  function deserializeString(str) {
2362
2697
  return str.replace(/(\\\\|\\"|\\n|\\r|\\b|\\t|\\f|\\u2028|\\u2029|\\x3C)/g, deserializeReplacer);
2363
2698
  }
2364
- var REFERENCES_KEY = "__SEROVAL_REFS__";
2365
- var GLOBAL_CONTEXT_REFERENCES = "$R";
2366
- var GLOBAL_CONTEXT_R = `self.${GLOBAL_CONTEXT_REFERENCES}`;
2367
- var INV_REFERENCE = /* @__PURE__ */ new Map;
2368
- function hasReference(id) {
2369
- return INV_REFERENCE.has(id);
2370
- }
2371
- function getReference(id) {
2372
- if (hasReference(id)) {
2373
- return INV_REFERENCE.get(id);
2374
- }
2375
- throw new SerovalMissingReferenceForIdError(id);
2376
- }
2377
- if (typeof globalThis !== "undefined") {
2378
- Object.defineProperty(globalThis, REFERENCES_KEY, {
2379
- value: INV_REFERENCE,
2380
- configurable: true,
2381
- writable: false,
2382
- enumerable: false
2383
- });
2384
- } else if (typeof window !== "undefined") {
2385
- Object.defineProperty(window, REFERENCES_KEY, {
2386
- value: INV_REFERENCE,
2387
- configurable: true,
2388
- writable: false,
2389
- enumerable: false
2390
- });
2391
- } else if (typeof self !== "undefined") {
2392
- Object.defineProperty(self, REFERENCES_KEY, {
2393
- value: INV_REFERENCE,
2394
- configurable: true,
2395
- writable: false,
2396
- enumerable: false
2397
- });
2398
- } else if (typeof global !== "undefined") {
2399
- Object.defineProperty(global, REFERENCES_KEY, {
2400
- value: INV_REFERENCE,
2401
- configurable: true,
2402
- writable: false,
2403
- enumerable: false
2404
- });
2405
- }
2406
2699
  var { toString: objectToString } = Object.prototype;
2407
2700
  function getErrorMessageDev(type, cause) {
2408
- if (cause instanceof Error) {
2701
+ if (cause instanceof Error)
2409
2702
  return `Seroval caught an error during the ${type} process.
2410
2703
 
2411
2704
  ${cause.name}
@@ -2413,7 +2706,6 @@ ${cause.message}
2413
2706
 
2414
2707
  - For more information, please check the "cause" property of this error.
2415
2708
  - If you believe this is an error in Seroval, please submit an issue at https://github.com/lxsmnsyc/seroval/issues/new`;
2416
- }
2417
2709
  return `Seroval caught an error during the ${type} process.
2418
2710
 
2419
2711
  "${objectToString.call(cause)}"
@@ -2467,6 +2759,44 @@ var SerovalDepthLimitError = class extends Error {
2467
2759
  super("Depth limit of " + limit + " reached");
2468
2760
  }
2469
2761
  };
2762
+ var REFERENCES_KEY = "__SEROVAL_REFS__";
2763
+ var INV_REFERENCE = /* @__PURE__ */ new Map;
2764
+ function hasReference(id) {
2765
+ return INV_REFERENCE.has(id);
2766
+ }
2767
+ function getReference(id) {
2768
+ if (hasReference(id))
2769
+ return INV_REFERENCE.get(id);
2770
+ throw new SerovalMissingReferenceForIdError(id);
2771
+ }
2772
+ if (typeof globalThis !== "undefined")
2773
+ Object.defineProperty(globalThis, REFERENCES_KEY, {
2774
+ value: INV_REFERENCE,
2775
+ configurable: true,
2776
+ writable: false,
2777
+ enumerable: false
2778
+ });
2779
+ else if (typeof window !== "undefined")
2780
+ Object.defineProperty(window, REFERENCES_KEY, {
2781
+ value: INV_REFERENCE,
2782
+ configurable: true,
2783
+ writable: false,
2784
+ enumerable: false
2785
+ });
2786
+ else if (typeof self !== "undefined")
2787
+ Object.defineProperty(self, REFERENCES_KEY, {
2788
+ value: INV_REFERENCE,
2789
+ configurable: true,
2790
+ writable: false,
2791
+ enumerable: false
2792
+ });
2793
+ else if (typeof global !== "undefined")
2794
+ Object.defineProperty(global, REFERENCES_KEY, {
2795
+ value: INV_REFERENCE,
2796
+ configurable: true,
2797
+ writable: false,
2798
+ enumerable: false
2799
+ });
2470
2800
  var PROMISE_CONSTRUCTOR = () => {
2471
2801
  const resolver = {
2472
2802
  p: 0,
@@ -2485,58 +2815,59 @@ var STREAM_CONSTRUCTOR = () => {
2485
2815
  let alive = true;
2486
2816
  let success = false;
2487
2817
  let count = 0;
2488
- const flush = (value, mode, x) => {
2489
- for (x = 0;x < count; x++) {
2490
- if (listeners[x]) {
2491
- listeners[x][mode](value);
2492
- }
2493
- }
2494
- };
2495
- const up = (listener, x, z, current) => {
2496
- for (x = 0, z = buffer.length;x < z; x++) {
2497
- current = buffer[x];
2498
- if (!alive && x === z - 1) {
2499
- listener[success ? "return" : "throw"](current);
2500
- } else {
2501
- listener.next(current);
2818
+ const internal = {
2819
+ flush(value, mode, x) {
2820
+ for (x = 0;x < count; x++)
2821
+ if (listeners[x])
2822
+ listeners[x][mode](value);
2823
+ },
2824
+ up(listener, x, z, current) {
2825
+ for (x = 0, z = buffer.length;x < z; x++) {
2826
+ current = buffer[x];
2827
+ if (!alive && x === z - 1)
2828
+ listener[success ? "return" : "throw"](current);
2829
+ else
2830
+ listener.next(current);
2502
2831
  }
2503
- }
2504
- };
2505
- const on = (listener, temp) => {
2506
- if (alive) {
2507
- temp = count++;
2508
- listeners[temp] = listener;
2509
- }
2510
- up(listener);
2511
- return () => {
2832
+ },
2833
+ on(listener, temp) {
2512
2834
  if (alive) {
2513
- listeners[temp] = listeners[count];
2514
- listeners[count--] = undefined;
2835
+ temp = count++;
2836
+ listeners[temp] = listener;
2515
2837
  }
2516
- };
2838
+ internal.up(listener);
2839
+ return () => {
2840
+ if (alive) {
2841
+ listeners[temp] = listeners[count];
2842
+ listeners[count--] = undefined;
2843
+ }
2844
+ };
2845
+ }
2517
2846
  };
2518
2847
  return {
2519
2848
  __SEROVAL_STREAM__: true,
2520
- on: (listener) => on(listener),
2521
- next: (value) => {
2849
+ on(listener) {
2850
+ return internal.on(listener);
2851
+ },
2852
+ next(value) {
2522
2853
  if (alive) {
2523
2854
  buffer.push(value);
2524
- flush(value, "next");
2855
+ internal.flush(value, "next");
2525
2856
  }
2526
2857
  },
2527
- throw: (value) => {
2858
+ throw(value) {
2528
2859
  if (alive) {
2529
2860
  buffer.push(value);
2530
- flush(value, "throw");
2861
+ internal.flush(value, "throw");
2531
2862
  alive = false;
2532
2863
  success = false;
2533
2864
  listeners.length = 0;
2534
2865
  }
2535
2866
  },
2536
- return: (value) => {
2867
+ return(value) {
2537
2868
  if (alive) {
2538
2869
  buffer.push(value);
2539
- flush(value, "return");
2870
+ internal.flush(value, "return");
2540
2871
  alive = false;
2541
2872
  success = true;
2542
2873
  listeners.length = 0;
@@ -2547,19 +2878,19 @@ var STREAM_CONSTRUCTOR = () => {
2547
2878
  var ITERATOR_CONSTRUCTOR = (symbol) => (sequence) => () => {
2548
2879
  let index = 0;
2549
2880
  const instance = {
2550
- [symbol]: () => instance,
2551
- next: () => {
2552
- if (index > sequence.d) {
2881
+ [symbol]() {
2882
+ return instance;
2883
+ },
2884
+ next() {
2885
+ if (index > sequence.d)
2553
2886
  return {
2554
2887
  done: true,
2555
2888
  value: undefined
2556
2889
  };
2557
- }
2558
2890
  const currentIndex = index++;
2559
2891
  const data = sequence.v[currentIndex];
2560
- if (currentIndex === sequence.t) {
2892
+ if (currentIndex === sequence.t)
2561
2893
  throw data;
2562
- }
2563
2894
  return {
2564
2895
  done: currentIndex === sequence.d,
2565
2896
  value: data
@@ -2574,74 +2905,75 @@ var ASYNC_ITERATOR_CONSTRUCTOR = (symbol, createPromise) => (stream) => () => {
2574
2905
  let isThrow = false;
2575
2906
  const buffer = [];
2576
2907
  const pending = [];
2577
- const finalize = (i = 0, len = pending.length) => {
2578
- for (;i < len; i++) {
2908
+ const internal = { finalize(i = 0, len = pending.length) {
2909
+ for (;i < len; i++)
2579
2910
  pending[i].s({
2580
2911
  done: true,
2581
2912
  value: undefined
2582
2913
  });
2583
- }
2584
- };
2914
+ } };
2585
2915
  stream.on({
2586
- next: (value) => {
2916
+ next(value) {
2587
2917
  const temp = pending.shift();
2588
- if (temp) {
2589
- temp.s({ done: false, value });
2590
- }
2918
+ if (temp)
2919
+ temp.s({
2920
+ done: false,
2921
+ value
2922
+ });
2591
2923
  buffer.push(value);
2592
2924
  },
2593
- throw: (value) => {
2925
+ throw(value) {
2594
2926
  const temp = pending.shift();
2595
- if (temp) {
2927
+ if (temp)
2596
2928
  temp.f(value);
2597
- }
2598
- finalize();
2929
+ internal.finalize();
2599
2930
  doneAt = buffer.length;
2600
2931
  isThrow = true;
2601
2932
  buffer.push(value);
2602
2933
  },
2603
- return: (value) => {
2934
+ return(value) {
2604
2935
  const temp = pending.shift();
2605
- if (temp) {
2606
- temp.s({ done: true, value });
2607
- }
2608
- finalize();
2936
+ if (temp)
2937
+ temp.s({
2938
+ done: true,
2939
+ value
2940
+ });
2941
+ internal.finalize();
2609
2942
  doneAt = buffer.length;
2610
2943
  buffer.push(value);
2611
2944
  }
2612
2945
  });
2613
2946
  const instance = {
2614
- [symbol]: () => instance,
2615
- next: () => {
2947
+ [symbol]() {
2948
+ return instance;
2949
+ },
2950
+ next() {
2616
2951
  if (doneAt === -1) {
2617
- const index2 = count++;
2618
- if (index2 >= buffer.length) {
2952
+ const index = count++;
2953
+ if (index >= buffer.length) {
2619
2954
  const temp = createPromise();
2620
2955
  pending.push(temp);
2621
2956
  return temp.p;
2622
2957
  }
2623
2958
  return {
2624
2959
  done: false,
2625
- value: buffer[index2]
2960
+ value: buffer[index]
2626
2961
  };
2627
2962
  }
2628
- if (count > doneAt) {
2963
+ if (count > doneAt)
2629
2964
  return {
2630
2965
  done: true,
2631
2966
  value: undefined
2632
2967
  };
2633
- }
2634
2968
  const index = count++;
2635
2969
  const value = buffer[index];
2636
- if (index !== doneAt) {
2970
+ if (index !== doneAt)
2637
2971
  return {
2638
2972
  done: false,
2639
2973
  value
2640
2974
  };
2641
- }
2642
- if (isThrow) {
2975
+ if (isThrow)
2643
2976
  throw value;
2644
- }
2645
2977
  return {
2646
2978
  done: true,
2647
2979
  value
@@ -2654,9 +2986,8 @@ var ARRAY_BUFFER_CONSTRUCTOR = (b64) => {
2654
2986
  const decoded = atob(b64);
2655
2987
  const length = decoded.length;
2656
2988
  const arr = new Uint8Array(length);
2657
- for (let i = 0;i < length; i++) {
2989
+ for (let i = 0;i < length; i++)
2658
2990
  arr[i] = decoded.charCodeAt(i);
2659
- }
2660
2991
  return arr.buffer;
2661
2992
  };
2662
2993
  function createSequence(values, throwAt, doneAt) {
@@ -2683,9 +3014,8 @@ function dedupePlugins(deduped, plugins) {
2683
3014
  const current = plugins[i];
2684
3015
  if (!deduped.has(current)) {
2685
3016
  deduped.add(current);
2686
- if (current.extends) {
3017
+ if (current.extends)
2687
3018
  dedupePlugins(deduped, current.extends);
2688
- }
2689
3019
  }
2690
3020
  }
2691
3021
  }
@@ -2695,7 +3025,6 @@ function resolvePlugins(plugins) {
2695
3025
  dedupePlugins(deduped, plugins);
2696
3026
  return [...deduped];
2697
3027
  }
2698
- return;
2699
3028
  }
2700
3029
  function getTypedArrayConstructor(name) {
2701
3030
  switch (name) {
@@ -2725,6 +3054,31 @@ function getTypedArrayConstructor(name) {
2725
3054
  throw new SerovalUnknownTypedArrayError(name);
2726
3055
  }
2727
3056
  }
3057
+ function isValidKey(key) {
3058
+ switch (key) {
3059
+ case "constructor":
3060
+ case "__proto__":
3061
+ case "prototype":
3062
+ case "__defineGetter__":
3063
+ case "__defineSetter__":
3064
+ case "__lookupGetter__":
3065
+ case "__lookupSetter__":
3066
+ return false;
3067
+ default:
3068
+ return true;
3069
+ }
3070
+ }
3071
+ function isValidSymbol(symbol) {
3072
+ switch (symbol) {
3073
+ case SYM_ASYNC_ITERATOR:
3074
+ case SYM_IS_CONCAT_SPREADABLE:
3075
+ case SYM_TO_STRING_TAG:
3076
+ case SYM_ITERATOR:
3077
+ return true;
3078
+ default:
3079
+ return false;
3080
+ }
3081
+ }
2728
3082
  var MAX_BASE64_LENGTH = 1e6;
2729
3083
  var MAX_BIGINT_LENGTH = 1e4;
2730
3084
  var MAX_REGEXP_SOURCE_LENGTH = 20000;
@@ -2742,18 +3096,15 @@ function applyObjectFlag(obj, flag) {
2742
3096
  }
2743
3097
  var DEFAULT_DEPTH_LIMIT = 1000;
2744
3098
  function createBaseDeserializerContext(mode, options) {
2745
- var _a;
3099
+ var _options$features;
2746
3100
  const refs = options.refs || /* @__PURE__ */ new Map;
2747
- if (!("types" in refs)) {
2748
- Object.assign(refs, {
2749
- types: /* @__PURE__ */ new Map
2750
- });
2751
- }
3101
+ if (!("types" in refs))
3102
+ Object.assign(refs, { types: /* @__PURE__ */ new Map });
2752
3103
  return {
2753
3104
  mode,
2754
3105
  plugins: options.plugins,
2755
3106
  refs,
2756
- features: (_a = options.features) != null ? _a : ALL_ENABLED ^ (options.disabledFeatures || 0),
3107
+ features: (_options$features = options.features) !== null && _options$features !== undefined ? _options$features : 127 ^ (options.disabledFeatures || 0),
2757
3108
  depthLimit: options.depthLimit || DEFAULT_DEPTH_LIMIT
2758
3109
  };
2759
3110
  }
@@ -2761,7 +3112,7 @@ function createCrossDeserializerContext(options) {
2761
3112
  return {
2762
3113
  mode: 2,
2763
3114
  base: createBaseDeserializerContext(2, options),
2764
- child: NIL
3115
+ child: undefined
2765
3116
  };
2766
3117
  }
2767
3118
  var DeserializePluginContext = class {
@@ -2770,25 +3121,25 @@ var DeserializePluginContext = class {
2770
3121
  this.depth = depth;
2771
3122
  }
2772
3123
  deserialize(node) {
2773
- return deserialize(this._p, this.depth, node);
3124
+ return deserialize$1(this._p, this.depth, node);
2774
3125
  }
2775
3126
  };
2776
3127
  function guardIndexedValue(ctx, id) {
2777
- if (id < 0 || !Number.isFinite(id) || !Number.isInteger(id)) {
3128
+ if (id < 0 || !Number.isFinite(id) || !Number.isInteger(id))
2778
3129
  throw new SerovalMalformedNodeError({
2779
3130
  t: 4,
2780
3131
  i: id
2781
3132
  });
2782
- }
2783
- if (ctx.refs.has(id)) {
3133
+ if (ctx.refs.has(id))
2784
3134
  throw new Error("Conflicted ref id: " + id);
2785
- }
3135
+ }
3136
+ function isThennable(value) {
3137
+ return !!value && typeof value === "object" && "then" in value && typeof value.then === "function";
2786
3138
  }
2787
3139
  function assignIndexedValueVanilla(ctx, id, value) {
2788
3140
  guardIndexedValue(ctx.base, id);
2789
- if (ctx.state.marked.has(id)) {
3141
+ if (ctx.state.marked.has(id))
2790
3142
  ctx.base.refs.set(id, value);
2791
- }
2792
3143
  return value;
2793
3144
  }
2794
3145
  function assignIndexedValueCross(ctx, id, value) {
@@ -2796,81 +3147,52 @@ function assignIndexedValueCross(ctx, id, value) {
2796
3147
  ctx.base.refs.set(id, value);
2797
3148
  return value;
2798
3149
  }
2799
- function assignIndexedValue(ctx, id, value) {
3150
+ function assignIndexedValue$1(ctx, id, value) {
2800
3151
  return ctx.mode === 1 ? assignIndexedValueVanilla(ctx, id, value) : assignIndexedValueCross(ctx, id, value);
2801
3152
  }
2802
3153
  function deserializeKnownValue(node, record, key) {
2803
- if (Object.hasOwn(record, key)) {
3154
+ if (Object.hasOwn(record, key))
2804
3155
  return record[key];
2805
- }
2806
3156
  throw new SerovalMalformedNodeError(node);
2807
3157
  }
2808
3158
  function deserializeReference(ctx, node) {
2809
- return assignIndexedValue(ctx, node.i, getReference(deserializeString(node.s)));
3159
+ return assignIndexedValue$1(ctx, node.i, getReference(deserializeString(node.s)));
2810
3160
  }
2811
3161
  function deserializeArray(ctx, depth, node) {
2812
3162
  const items = node.a;
2813
3163
  const len = items.length;
2814
- const result = assignIndexedValue(ctx, node.i, new Array(len));
3164
+ const result = assignIndexedValue$1(ctx, node.i, new Array(len));
2815
3165
  for (let i = 0, item;i < len; i++) {
2816
3166
  item = items[i];
2817
- if (item) {
2818
- result[i] = deserialize(ctx, depth, item);
2819
- }
3167
+ if (item)
3168
+ result[i] = deserialize$1(ctx, depth, item);
2820
3169
  }
2821
3170
  applyObjectFlag(result, node.o);
2822
3171
  return result;
2823
3172
  }
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
3173
  function assignStringProperty(object, key, value) {
2850
- if (isValidKey(key)) {
3174
+ if (isValidKey(key))
2851
3175
  object[key] = value;
2852
- } else {
3176
+ else
2853
3177
  Object.defineProperty(object, key, {
2854
3178
  value,
2855
3179
  configurable: true,
2856
3180
  enumerable: true,
2857
3181
  writable: true
2858
3182
  });
2859
- }
2860
3183
  }
2861
3184
  function assignProperty(ctx, depth, object, key, value) {
2862
- if (typeof key === "string") {
2863
- assignStringProperty(object, deserializeString(key), deserialize(ctx, depth, value));
2864
- } else {
2865
- const actual = deserialize(ctx, depth, key);
3185
+ if (typeof key === "string")
3186
+ assignStringProperty(object, deserializeString(key), deserialize$1(ctx, depth, value));
3187
+ else {
3188
+ const actual = deserialize$1(ctx, depth, key);
2866
3189
  switch (typeof actual) {
2867
3190
  case "string":
2868
- assignStringProperty(object, actual, deserialize(ctx, depth, value));
3191
+ assignStringProperty(object, actual, deserialize$1(ctx, depth, value));
2869
3192
  break;
2870
3193
  case "symbol":
2871
- if (isValidSymbol(actual)) {
2872
- object[actual] = deserialize(ctx, depth, value);
2873
- }
3194
+ if (isValidSymbol(actual))
3195
+ object[actual] = deserialize$1(ctx, depth, value);
2874
3196
  break;
2875
3197
  default:
2876
3198
  throw new SerovalMalformedNodeError(key);
@@ -2881,80 +3203,105 @@ function assignNodeType(ctx, id, type) {
2881
3203
  ctx.base.refs.types.set(id, type);
2882
3204
  }
2883
3205
  function validateNodeType(ctx, node, id, type) {
2884
- if (ctx.base.refs.types.get(id) !== type) {
3206
+ if (ctx.base.refs.types.get(id) !== type)
2885
3207
  throw new SerovalMalformedNodeError(node);
2886
- }
2887
3208
  }
2888
3209
  function deserializeProperties(ctx, depth, node, result) {
2889
3210
  const keys = node.k;
2890
- const len = keys.length;
2891
- if (len > 0) {
2892
- for (let i = 0, vals = node.v, len2 = keys.length;i < len2; i++) {
3211
+ if (keys.length > 0)
3212
+ for (let i = 0, vals = node.v, len = keys.length;i < len; i++)
2893
3213
  assignProperty(ctx, depth, result, keys[i], vals[i]);
2894
- }
2895
- }
2896
3214
  return result;
2897
3215
  }
2898
3216
  function deserializeObject(ctx, depth, node) {
2899
- const result = assignIndexedValue(ctx, node.i, node.t === 10 ? {} : /* @__PURE__ */ Object.create(null));
3217
+ const result = assignIndexedValue$1(ctx, node.i, node.t === 10 ? {} : Object.create(null));
2900
3218
  deserializeProperties(ctx, depth, node.p, result);
2901
3219
  applyObjectFlag(result, node.o);
2902
3220
  return result;
2903
3221
  }
2904
3222
  function deserializeDate(ctx, node) {
2905
- return assignIndexedValue(ctx, node.i, new Date(node.s));
3223
+ return assignIndexedValue$1(ctx, node.i, new Date(node.s));
3224
+ }
3225
+ function deserializeTemporal(ctx, node) {
3226
+ if (!(ctx.base.features & 64))
3227
+ throw new SerovalUnsupportedNodeError(node);
3228
+ let value;
3229
+ switch (node.c) {
3230
+ case 0:
3231
+ value = Temporal.Instant.from(node.s);
3232
+ break;
3233
+ case 1:
3234
+ value = Temporal.Duration.from(node.s);
3235
+ break;
3236
+ case 2:
3237
+ value = Temporal.PlainDate.from(node.s);
3238
+ break;
3239
+ case 3:
3240
+ value = Temporal.PlainDateTime.from(node.s);
3241
+ break;
3242
+ case 4:
3243
+ value = Temporal.PlainMonthDay.from(node.s);
3244
+ break;
3245
+ case 5:
3246
+ value = Temporal.PlainTime.from(node.s);
3247
+ break;
3248
+ case 6:
3249
+ value = Temporal.PlainYearMonth.from(node.s);
3250
+ break;
3251
+ case 7:
3252
+ value = Temporal.ZonedDateTime.from(node.s);
3253
+ break;
3254
+ default:
3255
+ throw new SerovalMalformedNodeError(node);
3256
+ }
3257
+ return assignIndexedValue$1(ctx, node.i, value);
2906
3258
  }
2907
3259
  function deserializeRegExp(ctx, node) {
2908
3260
  if (ctx.base.features & 32) {
2909
3261
  const source = deserializeString(node.c);
2910
- if (source.length > MAX_REGEXP_SOURCE_LENGTH) {
3262
+ if (source.length > MAX_REGEXP_SOURCE_LENGTH)
2911
3263
  throw new SerovalMalformedNodeError(node);
2912
- }
2913
- return assignIndexedValue(ctx, node.i, new RegExp(source, node.m));
3264
+ return assignIndexedValue$1(ctx, node.i, new RegExp(source, node.m));
2914
3265
  }
2915
3266
  throw new SerovalUnsupportedNodeError(node);
2916
3267
  }
2917
3268
  function deserializeSet(ctx, depth, node) {
2918
- const result = assignIndexedValue(ctx, node.i, /* @__PURE__ */ new Set);
2919
- for (let i = 0, items = node.a, len = items.length;i < len; i++) {
2920
- result.add(deserialize(ctx, depth, items[i]));
2921
- }
3269
+ const result = assignIndexedValue$1(ctx, node.i, /* @__PURE__ */ new Set);
3270
+ for (let i = 0, items = node.a, len = items.length;i < len; i++)
3271
+ result.add(deserialize$1(ctx, depth, items[i]));
2922
3272
  return result;
2923
3273
  }
2924
3274
  function deserializeMap(ctx, depth, node) {
2925
- const result = assignIndexedValue(ctx, node.i, /* @__PURE__ */ new Map);
2926
- for (let i = 0, keys = node.e.k, vals = node.e.v, len = keys.length;i < len; i++) {
2927
- result.set(deserialize(ctx, depth, keys[i]), deserialize(ctx, depth, vals[i]));
2928
- }
3275
+ const result = assignIndexedValue$1(ctx, node.i, /* @__PURE__ */ new Map);
3276
+ for (let i = 0, keys = node.e.k, vals = node.e.v, len = keys.length;i < len; i++)
3277
+ result.set(deserialize$1(ctx, depth, keys[i]), deserialize$1(ctx, depth, vals[i]));
2929
3278
  return result;
2930
3279
  }
2931
3280
  function deserializeArrayBuffer(ctx, node) {
2932
- if (node.s.length > MAX_BASE64_LENGTH) {
3281
+ if (node.s.length > MAX_BASE64_LENGTH)
2933
3282
  throw new SerovalMalformedNodeError(node);
2934
- }
2935
- const result = assignIndexedValue(ctx, node.i, ARRAY_BUFFER_CONSTRUCTOR(deserializeString(node.s)));
2936
- return result;
3283
+ return assignIndexedValue$1(ctx, node.i, ARRAY_BUFFER_CONSTRUCTOR(deserializeString(node.s)));
2937
3284
  }
2938
3285
  function deserializeTypedArray(ctx, depth, node) {
2939
- var _a;
3286
+ var _node$b;
2940
3287
  const construct = getTypedArrayConstructor(node.c);
2941
- const source = deserialize(ctx, depth, node.f);
2942
- const offset = (_a = node.b) != null ? _a : 0;
2943
- if (offset < 0 || offset > source.byteLength) {
3288
+ const source = deserialize$1(ctx, depth, node.f);
3289
+ if (!(source instanceof ArrayBuffer))
3290
+ throw new SerovalMalformedNodeError(node);
3291
+ const offset = (_node$b = node.b) !== null && _node$b !== undefined ? _node$b : 0;
3292
+ if (offset < 0 || offset > source.byteLength || node.l > MAX_BASE64_LENGTH)
2944
3293
  throw new SerovalMalformedNodeError(node);
2945
- }
2946
- const result = assignIndexedValue(ctx, node.i, new construct(source, offset, node.l));
2947
- return result;
3294
+ return assignIndexedValue$1(ctx, node.i, new construct(source, offset, node.l));
2948
3295
  }
2949
3296
  function deserializeDataView(ctx, depth, node) {
2950
- var _a;
2951
- const source = deserialize(ctx, depth, node.f);
2952
- const offset = (_a = node.b) != null ? _a : 0;
2953
- if (offset < 0 || offset > source.byteLength) {
3297
+ var _node$b2;
3298
+ const source = deserialize$1(ctx, depth, node.f);
3299
+ if (!(source instanceof ArrayBuffer))
2954
3300
  throw new SerovalMalformedNodeError(node);
2955
- }
2956
- const result = assignIndexedValue(ctx, node.i, new DataView(source, offset, node.l));
2957
- return result;
3301
+ const offset = (_node$b2 = node.b) !== null && _node$b2 !== undefined ? _node$b2 : 0;
3302
+ if (offset < 0 || offset > source.byteLength || node.l > MAX_BASE64_LENGTH)
3303
+ throw new SerovalMalformedNodeError(node);
3304
+ return assignIndexedValue$1(ctx, node.i, new DataView(source, offset, node.l));
2958
3305
  }
2959
3306
  function deserializeDictionary(ctx, depth, node, result) {
2960
3307
  if (node.p) {
@@ -2964,27 +3311,26 @@ function deserializeDictionary(ctx, depth, node, result) {
2964
3311
  return result;
2965
3312
  }
2966
3313
  function deserializeAggregateError(ctx, depth, node) {
2967
- const result = assignIndexedValue(ctx, node.i, new AggregateError([], deserializeString(node.m)));
2968
- return deserializeDictionary(ctx, depth, node, result);
3314
+ return deserializeDictionary(ctx, depth, node, assignIndexedValue$1(ctx, node.i, new AggregateError([], deserializeString(node.m))));
2969
3315
  }
2970
3316
  function deserializeError(ctx, depth, node) {
2971
3317
  const construct = deserializeKnownValue(node, ERROR_CONSTRUCTOR, node.s);
2972
- const result = assignIndexedValue(ctx, node.i, new construct(deserializeString(node.m)));
2973
- return deserializeDictionary(ctx, depth, node, result);
3318
+ return deserializeDictionary(ctx, depth, node, assignIndexedValue$1(ctx, node.i, new construct(deserializeString(node.m))));
2974
3319
  }
2975
3320
  function deserializePromise(ctx, depth, node) {
2976
3321
  const deferred = PROMISE_CONSTRUCTOR();
2977
- const result = assignIndexedValue(ctx, node.i, deferred.p);
2978
- const deserialized = deserialize(ctx, depth, node.f);
2979
- if (node.s) {
3322
+ const result = assignIndexedValue$1(ctx, node.i, deferred.p);
3323
+ const deserialized = deserialize$1(ctx, depth, node.f);
3324
+ if (isThennable(deserialized))
3325
+ throw new SerovalMalformedNodeError(node.f);
3326
+ if (node.s)
2980
3327
  deferred.s(deserialized);
2981
- } else {
3328
+ else
2982
3329
  deferred.f(deserialized);
2983
- }
2984
3330
  return result;
2985
3331
  }
2986
3332
  function deserializeBoxed(ctx, depth, node) {
2987
- return assignIndexedValue(ctx, node.i, Object(deserialize(ctx, depth, node.f)));
3333
+ return assignIndexedValue$1(ctx, node.i, Object(deserialize$1(ctx, depth, node.f)));
2988
3334
  }
2989
3335
  function deserializePlugin(ctx, depth, node) {
2990
3336
  const currentPlugins = ctx.base.plugins;
@@ -2992,66 +3338,64 @@ function deserializePlugin(ctx, depth, node) {
2992
3338
  const tag = deserializeString(node.c);
2993
3339
  for (let i = 0, len = currentPlugins.length;i < len; i++) {
2994
3340
  const plugin = currentPlugins[i];
2995
- if (plugin.tag === tag) {
2996
- return assignIndexedValue(ctx, node.i, plugin.deserialize(node.s, new DeserializePluginContext(ctx, depth), {
2997
- id: node.i
2998
- }));
2999
- }
3341
+ if (plugin.tag === tag)
3342
+ return assignIndexedValue$1(ctx, node.i, plugin.deserialize(node.s, new DeserializePluginContext(ctx, depth), { id: node.i }));
3000
3343
  }
3001
3344
  }
3002
3345
  throw new SerovalMissingPluginError(node.c);
3003
3346
  }
3004
3347
  function deserializePromiseConstructor(ctx, node) {
3005
- const value = assignIndexedValue(ctx, node.i, assignIndexedValue(ctx, node.s, PROMISE_CONSTRUCTOR()).p);
3348
+ const value = assignIndexedValue$1(ctx, node.i, assignIndexedValue$1(ctx, node.s, PROMISE_CONSTRUCTOR()).p);
3006
3349
  assignNodeType(ctx, node.s, 22);
3007
3350
  return value;
3008
3351
  }
3009
- function deserializePromiseResolve(ctx, depth, node) {
3352
+ function deserializePromiseFulfill(ctx, depth, node) {
3010
3353
  const deferred = ctx.base.refs.get(node.i);
3011
3354
  if (deferred) {
3012
3355
  validateNodeType(ctx, node, node.i, 22);
3013
- deferred.s(deserialize(ctx, depth, node.a[1]));
3014
- return NIL;
3015
- }
3016
- throw new SerovalMissingInstanceError("Promise");
3017
- }
3018
- function deserializePromiseReject(ctx, depth, node) {
3019
- const deferred = ctx.base.refs.get(node.i);
3020
- if (deferred) {
3021
- validateNodeType(ctx, node, node.i, 22);
3022
- deferred.f(deserialize(ctx, depth, node.a[1]));
3023
- return NIL;
3356
+ const deserialized = deserialize$1(ctx, depth, node.a[1]);
3357
+ if (isThennable(deserialized))
3358
+ throw new SerovalMalformedNodeError(node.a[1]);
3359
+ if (node.t === 23)
3360
+ deferred.s(deserialized);
3361
+ else
3362
+ deferred.f(deserialized);
3363
+ return;
3024
3364
  }
3025
3365
  throw new SerovalMissingInstanceError("Promise");
3026
3366
  }
3027
3367
  function deserializeIteratorFactoryInstance(ctx, depth, node) {
3028
- deserialize(ctx, depth, node.a[0]);
3029
- const source = deserialize(ctx, depth, node.a[1]);
3368
+ deserialize$1(ctx, depth, node.a[0]);
3369
+ const source = deserialize$1(ctx, depth, node.a[1]);
3370
+ validateNodeType(ctx, node, node.a[1].i, 35);
3371
+ if (!source)
3372
+ throw new SerovalMalformedNodeError(node.a[1]);
3030
3373
  return sequenceToIterator(source);
3031
3374
  }
3032
3375
  function deserializeAsyncIteratorFactoryInstance(ctx, depth, node) {
3033
- deserialize(ctx, depth, node.a[0]);
3034
- const source = deserialize(ctx, depth, node.a[1]);
3376
+ deserialize$1(ctx, depth, node.a[0]);
3377
+ const source = deserialize$1(ctx, depth, node.a[1]);
3378
+ validateNodeType(ctx, node, node.a[1].i, 31);
3379
+ if (!source)
3380
+ throw new SerovalMalformedNodeError(node.a[1]);
3035
3381
  return streamToAsyncIterable(source);
3036
3382
  }
3037
3383
  function deserializeStreamConstructor(ctx, depth, node) {
3038
- const result = assignIndexedValue(ctx, node.i, createStream());
3384
+ const result = assignIndexedValue$1(ctx, node.i, createStream());
3039
3385
  assignNodeType(ctx, node.i, 31);
3040
3386
  const items = node.a;
3041
3387
  const len = items.length;
3042
- if (len) {
3043
- for (let i = 0;i < len; i++) {
3044
- deserialize(ctx, depth, items[i]);
3045
- }
3046
- }
3388
+ if (len)
3389
+ for (let i = 0;i < len; i++)
3390
+ deserialize$1(ctx, depth, items[i]);
3047
3391
  return result;
3048
3392
  }
3049
3393
  function deserializeStreamNext(ctx, depth, node) {
3050
3394
  const deferred = ctx.base.refs.get(node.i);
3051
3395
  if (deferred) {
3052
3396
  validateNodeType(ctx, node, node.i, 31);
3053
- deferred.next(deserialize(ctx, depth, node.f));
3054
- return NIL;
3397
+ deferred.next(deserialize$1(ctx, depth, node.f));
3398
+ return;
3055
3399
  }
3056
3400
  throw new SerovalMissingInstanceError("Stream");
3057
3401
  }
@@ -3059,8 +3403,8 @@ function deserializeStreamThrow(ctx, depth, node) {
3059
3403
  const deferred = ctx.base.refs.get(node.i);
3060
3404
  if (deferred) {
3061
3405
  validateNodeType(ctx, node, node.i, 31);
3062
- deferred.throw(deserialize(ctx, depth, node.f));
3063
- return NIL;
3406
+ deferred.throw(deserialize$1(ctx, depth, node.f));
3407
+ return;
3064
3408
  }
3065
3409
  throw new SerovalMissingInstanceError("Stream");
3066
3410
  }
@@ -3068,30 +3412,27 @@ function deserializeStreamReturn(ctx, depth, node) {
3068
3412
  const deferred = ctx.base.refs.get(node.i);
3069
3413
  if (deferred) {
3070
3414
  validateNodeType(ctx, node, node.i, 31);
3071
- deferred.return(deserialize(ctx, depth, node.f));
3072
- return NIL;
3415
+ deferred.return(deserialize$1(ctx, depth, node.f));
3416
+ return;
3073
3417
  }
3074
3418
  throw new SerovalMissingInstanceError("Stream");
3075
3419
  }
3076
3420
  function deserializeIteratorFactory(ctx, depth, node) {
3077
- deserialize(ctx, depth, node.f);
3078
- return NIL;
3421
+ deserialize$1(ctx, depth, node.f);
3079
3422
  }
3080
3423
  function deserializeAsyncIteratorFactory(ctx, depth, node) {
3081
- deserialize(ctx, depth, node.a[1]);
3082
- return NIL;
3424
+ deserialize$1(ctx, depth, node.a[1]);
3083
3425
  }
3084
3426
  function deserializeSequence(ctx, depth, node) {
3085
- const result = assignIndexedValue(ctx, node.i, createSequence([], node.s, node.l));
3086
- for (let i = 0, len = node.a.length;i < len; i++) {
3087
- result.v[i] = deserialize(ctx, depth, node.a[i]);
3088
- }
3427
+ const result = assignIndexedValue$1(ctx, node.i, createSequence([], node.s, node.l));
3428
+ assignNodeType(ctx, node.i, 35);
3429
+ for (let i = 0, len = node.a.length;i < len; i++)
3430
+ result.v[i] = deserialize$1(ctx, depth, node.a[i]);
3089
3431
  return result;
3090
3432
  }
3091
- function deserialize(ctx, depth, node) {
3092
- if (depth > ctx.base.depthLimit) {
3433
+ function deserialize$1(ctx, depth, node) {
3434
+ if (depth > ctx.base.depthLimit)
3093
3435
  throw new SerovalDepthLimitError(ctx.base.depthLimit);
3094
- }
3095
3436
  depth += 1;
3096
3437
  switch (node.t) {
3097
3438
  case 2:
@@ -3101,9 +3442,8 @@ function deserialize(ctx, depth, node) {
3101
3442
  case 1:
3102
3443
  return deserializeString(String(node.s));
3103
3444
  case 3:
3104
- if (String(node.s).length > MAX_BIGINT_LENGTH) {
3445
+ if (String(node.s).length > MAX_BIGINT_LENGTH)
3105
3446
  throw new SerovalMalformedNodeError(node);
3106
- }
3107
3447
  return BigInt(node.s);
3108
3448
  case 4:
3109
3449
  return ctx.base.refs.get(node.i);
@@ -3144,9 +3484,8 @@ function deserialize(ctx, depth, node) {
3144
3484
  case 22:
3145
3485
  return deserializePromiseConstructor(ctx, node);
3146
3486
  case 23:
3147
- return deserializePromiseResolve(ctx, depth, node);
3148
3487
  case 24:
3149
- return deserializePromiseReject(ctx, depth, node);
3488
+ return deserializePromiseFulfill(ctx, depth, node);
3150
3489
  case 28:
3151
3490
  return deserializeIteratorFactoryInstance(ctx, depth, node);
3152
3491
  case 30:
@@ -3165,31 +3504,287 @@ function deserialize(ctx, depth, node) {
3165
3504
  return deserializeAsyncIteratorFactory(ctx, depth, node);
3166
3505
  case 35:
3167
3506
  return deserializeSequence(ctx, depth, node);
3507
+ case 36:
3508
+ return deserializeTemporal(ctx, node);
3168
3509
  default:
3169
3510
  throw new SerovalUnsupportedNodeError(node);
3170
3511
  }
3171
3512
  }
3172
3513
  function deserializeTop(ctx, node) {
3173
3514
  try {
3174
- return deserialize(ctx, 0, node);
3515
+ return deserialize$1(ctx, 0, node);
3175
3516
  } catch (error) {
3176
3517
  throw new SerovalDeserializationError(error);
3177
3518
  }
3178
3519
  }
3179
- var REF_START_CHARS = "hjkmoquxzABCDEFGHIJKLNPQRTUVWXYZ$_";
3180
- var REF_START_CHARS_LEN = REF_START_CHARS.length;
3181
- var REF_CHARS = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789$_";
3182
- var REF_CHARS_LEN = REF_CHARS.length;
3183
3520
  function fromCrossJSON(source, options) {
3184
- const plugins = resolvePlugins(options.plugins);
3185
- const ctx = createCrossDeserializerContext({
3186
- plugins,
3521
+ return deserializeTop(createCrossDeserializerContext({
3522
+ plugins: resolvePlugins(options.plugins),
3187
3523
  refs: options.refs,
3188
3524
  features: options.features,
3189
3525
  disabledFeatures: options.disabledFeatures,
3190
3526
  depthLimit: options.depthLimit
3527
+ }), source);
3528
+ }
3529
+
3530
+ // src/rsc/shared.tsx
3531
+ import {
3532
+ Children,
3533
+ cloneElement,
3534
+ createElement as createElement3,
3535
+ isValidElement,
3536
+ use
3537
+ } from "react";
3538
+
3539
+ // src/rsc/client-codec.ts
3540
+ import { createFromReadableStream } from "react-server-dom-webpack/client.edge";
3541
+ function decodeFlight(stream) {
3542
+ return createFromReadableStream(stream, {
3543
+ serverConsumerManifest: {
3544
+ moduleLoading: null,
3545
+ moduleMap: {},
3546
+ serverModuleMap: {}
3547
+ }
3548
+ });
3549
+ }
3550
+
3551
+ // src/rsc/symbols.ts
3552
+ var RSC_SOURCE = Symbol.for("furin.rsc.source");
3553
+
3554
+ // src/rsc/shared.tsx
3555
+ function RscNode({ state }) {
3556
+ return use(state.tree);
3557
+ }
3558
+ function decodeFlightBytes(bytes) {
3559
+ return decodeFlight(new ReadableStream({
3560
+ start(controller) {
3561
+ controller.enqueue(bytes);
3562
+ controller.close();
3563
+ }
3564
+ }));
3565
+ }
3566
+ function createRenderableSource(state) {
3567
+ const element = createElement3(RscNode, { state });
3568
+ return new Proxy(element, {
3569
+ get(target, property, receiver) {
3570
+ if (property === RSC_SOURCE) {
3571
+ return state;
3572
+ }
3573
+ return Reflect.get(target, property, receiver);
3574
+ },
3575
+ has(target, property) {
3576
+ return property === RSC_SOURCE || Reflect.has(target, property);
3577
+ }
3578
+ });
3579
+ }
3580
+ function restoreRscSource(kind, bytes) {
3581
+ const state = { bytes, kind, tree: decodeFlightBytes(bytes) };
3582
+ return kind === "renderable" ? createRenderableSource(state) : { [RSC_SOURCE]: state };
3583
+ }
3584
+
3585
+ // src/shared/route-frame.ts
3586
+ var FRAME_VERSION = 3;
3587
+ var MAX_FRAME_BYTES = 1024 * 1024;
3588
+ var MAX_ROUTE_FRAME_STREAM_BYTES = 8 * 1024 * 1024;
3589
+ function isPlainObject3(value) {
3590
+ const prototype = Object.getPrototypeOf(value);
3591
+ return prototype === Object.prototype || prototype === null;
3592
+ }
3593
+ function frameValueToBytes(value) {
3594
+ if (value.startsWith("utf8:")) {
3595
+ return new TextEncoder().encode(value.slice(5));
3596
+ }
3597
+ if (!value.startsWith("base64:")) {
3598
+ throw new Error("[furin] malformed RSC route frame encoding");
3599
+ }
3600
+ const binary = atob(value.slice(7));
3601
+ return Uint8Array.from(binary, (character) => character.charCodeAt(0));
3602
+ }
3603
+ function isRouteFrameLine(line) {
3604
+ try {
3605
+ const parsed = JSON.parse(line);
3606
+ return parsed.__furinRouteFrame === FRAME_VERSION;
3607
+ } catch {
3608
+ return false;
3609
+ }
3610
+ }
3611
+ function hydrateRscDescriptors(value, sources, seen = new WeakMap) {
3612
+ if (value === null || typeof value !== "object") {
3613
+ return value;
3614
+ }
3615
+ if (isPlainObject3(value) && typeof value.__furinRsc === "string") {
3616
+ const id = value.__furinRsc;
3617
+ const source = sources.get(id);
3618
+ if (source === undefined) {
3619
+ throw new Error(`[furin] RSC route frame "${id}" is missing`);
3620
+ }
3621
+ return source;
3622
+ }
3623
+ const previous = seen.get(value);
3624
+ if (previous !== undefined) {
3625
+ return previous;
3626
+ }
3627
+ if (Array.isArray(value)) {
3628
+ seen.set(value, value);
3629
+ for (let i = 0;i < value.length; i += 1) {
3630
+ value[i] = hydrateRscDescriptors(value[i], sources, seen);
3631
+ }
3632
+ return value;
3633
+ }
3634
+ if (!isPlainObject3(value)) {
3635
+ return value;
3636
+ }
3637
+ seen.set(value, value);
3638
+ for (const [key, entry] of Object.entries(value)) {
3639
+ Reflect.set(value, key, hydrateRscDescriptors(entry, sources, seen));
3640
+ }
3641
+ return value;
3642
+ }
3643
+ function collectRscDescriptorIds(value, ids, seen = new WeakSet) {
3644
+ if (value === null || typeof value !== "object") {
3645
+ return;
3646
+ }
3647
+ if (seen.has(value)) {
3648
+ return;
3649
+ }
3650
+ seen.add(value);
3651
+ if (isPlainObject3(value) && typeof value.__furinRsc === "string") {
3652
+ ids.add(value.__furinRsc);
3653
+ return;
3654
+ }
3655
+ for (const entry of Array.isArray(value) ? value : Object.values(value)) {
3656
+ collectRscDescriptorIds(entry, ids, seen);
3657
+ }
3658
+ }
3659
+ async function parseRouteFrameLines(firstLine, readLine) {
3660
+ let byteLength = 0;
3661
+ let dataValue;
3662
+ const pending = new Map;
3663
+ const sources = new Map;
3664
+ const deferredPromises = {};
3665
+ const resolvers = new Map;
3666
+ const rejectPending = (reason) => {
3667
+ for (const resolver of resolvers.values()) {
3668
+ resolver.reject(reason);
3669
+ }
3670
+ resolvers.clear();
3671
+ };
3672
+ const deferredRscValues = new Map;
3673
+ const tryResolveDeferredRscValues = () => {
3674
+ for (const [key, deferred] of deferredRscValues) {
3675
+ if ([...deferred.ids].some((id) => !sources.has(id))) {
3676
+ continue;
3677
+ }
3678
+ resolvers.get(key)?.resolve(hydrateRscDescriptors(deferred.value, sources));
3679
+ resolvers.delete(key);
3680
+ deferredRscValues.delete(key);
3681
+ }
3682
+ };
3683
+ const processLine = (line) => {
3684
+ byteLength += new TextEncoder().encode(line).byteLength + 1;
3685
+ if (byteLength > MAX_ROUTE_FRAME_STREAM_BYTES) {
3686
+ throw new Error(`[furin] route frame stream exceeds the ${MAX_ROUTE_FRAME_STREAM_BYTES}-byte limit`);
3687
+ }
3688
+ const envelope = JSON.parse(line);
3689
+ if (envelope.__furinRouteFrame !== FRAME_VERSION) {
3690
+ throw new Error("[furin] unsupported route frame version");
3691
+ }
3692
+ const { frame } = envelope;
3693
+ if (frame.type === "data") {
3694
+ dataValue = fromCrossJSON(frame.value, {});
3695
+ for (const key of frame.deferredKeys) {
3696
+ deferredPromises[key] = new Promise((resolve, reject) => {
3697
+ resolvers.set(key, { reject, resolve });
3698
+ });
3699
+ deferredPromises[key]?.catch(() => {
3700
+ return;
3701
+ });
3702
+ }
3703
+ } else if (frame.type === "rsc-start") {
3704
+ pending.set(frame.id, { chunks: [], kind: frame.kind });
3705
+ } else if (frame.type === "rsc-chunk") {
3706
+ const source = pending.get(frame.id);
3707
+ if (source === undefined) {
3708
+ throw new Error(`[furin] RSC chunk received before start for "${frame.id}"`);
3709
+ }
3710
+ source.chunks.push(frameValueToBytes(frame.value));
3711
+ } else if (frame.type === "rsc-end") {
3712
+ const source = pending.get(frame.id);
3713
+ if (source === undefined) {
3714
+ throw new Error(`[furin] RSC end received before start for "${frame.id}"`);
3715
+ }
3716
+ const length = source.chunks.reduce((total, chunk) => total + chunk.byteLength, 0);
3717
+ const bytes = new Uint8Array(length);
3718
+ let offset = 0;
3719
+ for (const chunk of source.chunks) {
3720
+ bytes.set(chunk, offset);
3721
+ offset += chunk.byteLength;
3722
+ }
3723
+ sources.set(frame.id, restoreRscSource(source.kind, bytes));
3724
+ pending.delete(frame.id);
3725
+ tryResolveDeferredRscValues();
3726
+ } else if (frame.type === "rsc-error") {
3727
+ throw new Error(`[furin] RSC stream failed (${frame.digest})`);
3728
+ } else if (frame.type === "defer-resolve") {
3729
+ const value = fromCrossJSON(frame.value, {});
3730
+ const ids = new Set;
3731
+ collectRscDescriptorIds(value, ids);
3732
+ if ([...ids].some((id) => !sources.has(id))) {
3733
+ deferredRscValues.set(frame.key, { ids, value });
3734
+ } else {
3735
+ resolvers.get(frame.key)?.resolve(hydrateRscDescriptors(value, sources));
3736
+ resolvers.delete(frame.key);
3737
+ }
3738
+ } else if (frame.type === "defer-reject") {
3739
+ resolvers.get(frame.key)?.reject(fromCrossJSON(frame.value, {}));
3740
+ resolvers.delete(frame.key);
3741
+ }
3742
+ };
3743
+ processLine(firstLine);
3744
+ if (dataValue === undefined) {
3745
+ throw new Error("[furin] route frame stream has no data frame");
3746
+ }
3747
+ const expectedSources = new Set;
3748
+ collectRscDescriptorIds(dataValue, expectedSources);
3749
+ while ([...expectedSources].some((id) => !sources.has(id))) {
3750
+ const line = await readLine();
3751
+ if (line === undefined) {
3752
+ throw new Error("[furin] route frame stream ended before an RSC source completed");
3753
+ }
3754
+ processLine(line);
3755
+ }
3756
+ const data = hydrateRscDescriptors(dataValue, sources);
3757
+ if (data === null || typeof data !== "object" || Array.isArray(data)) {
3758
+ throw new Error("[furin] route data frame must decode to an object");
3759
+ }
3760
+ const completion = (async () => {
3761
+ for (;; ) {
3762
+ const line = await readLine();
3763
+ if (line === undefined) {
3764
+ break;
3765
+ }
3766
+ processLine(line);
3767
+ }
3768
+ if (pending.size > 0) {
3769
+ throw new Error("[furin] route frame stream ended before an RSC source completed");
3770
+ }
3771
+ if (deferredRscValues.size > 0) {
3772
+ throw new Error("[furin] route frame stream ended before an RSC source completed");
3773
+ }
3774
+ for (const [key, resolver] of resolvers) {
3775
+ resolver.reject(new Error(`[furin] deferred stream closed before "${key}" was resolved`));
3776
+ }
3777
+ resolvers.clear();
3778
+ })().catch((error) => {
3779
+ rejectPending(error);
3780
+ throw error;
3191
3781
  });
3192
- return deserializeTop(ctx, source);
3782
+ return {
3783
+ abort: rejectPending,
3784
+ completion,
3785
+ deferredPromises,
3786
+ syncData: data
3787
+ };
3193
3788
  }
3194
3789
 
3195
3790
  // src/shared/deferred-ndjson.ts
@@ -3213,7 +3808,7 @@ async function parseDeferredNdjson(stream, signal) {
3213
3808
  try {
3214
3809
  reader.releaseLock();
3215
3810
  } catch {}
3216
- return { syncData: {}, deferredPromises: {} };
3811
+ return { deferredPromises: {}, syncData: {} };
3217
3812
  }
3218
3813
  if (signal !== undefined && !signal.aborted) {
3219
3814
  abortHandler = () => cancelReader(makeAbortError(signal.reason));
@@ -3253,7 +3848,30 @@ async function parseDeferredNdjson(stream, signal) {
3253
3848
  try {
3254
3849
  reader.releaseLock();
3255
3850
  } catch {}
3256
- return { syncData: {}, deferredPromises: {} };
3851
+ return { deferredPromises: {}, syncData: {} };
3852
+ }
3853
+ if (isRouteFrameLine(firstLine)) {
3854
+ const result = await parseRouteFrameLines(firstLine, readLine);
3855
+ if (signal !== undefined) {
3856
+ cleanupAbortHandler();
3857
+ abortHandler = () => {
3858
+ const error = makeAbortError(signal.reason);
3859
+ result.abort(error);
3860
+ cancelReader(error);
3861
+ };
3862
+ if (signal.aborted) {
3863
+ abortHandler();
3864
+ } else {
3865
+ signal.addEventListener("abort", abortHandler, { once: true });
3866
+ }
3867
+ }
3868
+ result.completion.finally(() => {
3869
+ cleanupAbortHandler();
3870
+ try {
3871
+ reader.releaseLock();
3872
+ } catch {}
3873
+ });
3874
+ return { deferredPromises: result.deferredPromises, syncData: result.syncData };
3257
3875
  }
3258
3876
  const node = JSON.parse(firstLine);
3259
3877
  const deserialized = fromCrossJSON(node, {});
@@ -3274,7 +3892,7 @@ async function parseDeferredNdjson(stream, signal) {
3274
3892
  for (const key of deferredKeys) {
3275
3893
  if (!(key in deferredPromises)) {
3276
3894
  deferredPromises[key] = new Promise((resolve, reject) => {
3277
- resolvers[key] = { resolve, reject };
3895
+ resolvers[key] = { reject, resolve };
3278
3896
  });
3279
3897
  }
3280
3898
  }
@@ -3288,7 +3906,7 @@ async function parseDeferredNdjson(stream, signal) {
3288
3906
  try {
3289
3907
  reader.releaseLock();
3290
3908
  } catch {}
3291
- return { syncData, deferredPromises };
3909
+ return { deferredPromises, syncData };
3292
3910
  }
3293
3911
  const rejectAllPending = (reason) => {
3294
3912
  for (const key of Object.keys(resolvers)) {
@@ -3300,7 +3918,7 @@ async function parseDeferredNdjson(stream, signal) {
3300
3918
  if (signal !== undefined) {
3301
3919
  if (signal.aborted) {
3302
3920
  rejectAllPending(makeAbortError(signal.reason));
3303
- return { syncData, deferredPromises };
3921
+ return { deferredPromises, syncData };
3304
3922
  }
3305
3923
  cleanupAbortHandler();
3306
3924
  abortHandler = () => {
@@ -3324,7 +3942,7 @@ async function parseDeferredNdjson(stream, signal) {
3324
3942
  reader.releaseLock();
3325
3943
  } catch {}
3326
3944
  });
3327
- return { syncData, deferredPromises };
3945
+ return { deferredPromises, syncData };
3328
3946
  }
3329
3947
  async function readDeferredLines(readLine, resolvers) {
3330
3948
  for (;; ) {
@@ -3356,7 +3974,7 @@ function isAbortError(error) {
3356
3974
  }
3357
3975
 
3358
3976
  // src/client/router/search-store.ts
3359
- import { createContext as createContext2 } from "react";
3977
+ import { createContext as createContext3 } from "react";
3360
3978
  function searchSnapshotChanged(a, b) {
3361
3979
  return a.currentHref !== b.currentHref || a.navigate !== b.navigate || a.search !== b.search || a.searchRoutes !== b.searchRoutes;
3362
3980
  }
@@ -3382,7 +4000,7 @@ function createSearchStore(initialSnapshot) {
3382
4000
  return;
3383
4001
  }
3384
4002
  snapshot = next;
3385
- version++;
4003
+ version += 1;
3386
4004
  },
3387
4005
  subscribe: (listener) => {
3388
4006
  listeners.add(listener);
@@ -3404,6 +4022,9 @@ var FALLBACK_SEARCH_STORE = createSearchStore({
3404
4022
  currentHref: "/",
3405
4023
  navigate: (href, _opts) => {
3406
4024
  if (typeof window !== "undefined") {
4025
+ if (navigationHrefPolicy(href, window.location.origin) === "blocked") {
4026
+ return Promise.reject(new Error("[furin] Unsafe navigation URL."));
4027
+ }
3407
4028
  window.location.href = href;
3408
4029
  }
3409
4030
  return Promise.resolve();
@@ -3411,10 +4032,10 @@ var FALLBACK_SEARCH_STORE = createSearchStore({
3411
4032
  search: {},
3412
4033
  searchRoutes: []
3413
4034
  });
3414
- var SearchStoreContext = createContext2(null);
4035
+ var SearchStoreContext = createContext3(null);
3415
4036
 
3416
4037
  // src/client/router/spa-response.ts
3417
- import { createElement as createElement2 } from "react";
4038
+ import { createElement as createElement4 } from "react";
3418
4039
  function isFurinErrorPayload(value) {
3419
4040
  if (!value || typeof value !== "object") {
3420
4041
  return false;
@@ -3427,11 +4048,11 @@ function classifySpaResponse(status, data) {
3427
4048
  return { kind: "bail" };
3428
4049
  }
3429
4050
  if (isFurinErrorPayload(data.__furinError)) {
3430
- return { kind: "error", error: data.__furinError };
4051
+ return { error: data.__furinError, kind: "error" };
3431
4052
  }
3432
4053
  if ((status >= 200 && status < 300 || status === 404) && data.__furinStatus === 404) {
3433
4054
  const notFound = data.__furinNotFound;
3434
- return { kind: "not-found", error: notFound ?? {} };
4055
+ return { error: notFound ?? {}, kind: "not-found" };
3435
4056
  }
3436
4057
  if (status >= 200 && status < 300) {
3437
4058
  return { kind: "ok" };
@@ -3442,18 +4063,17 @@ function pickDeepestNotFound(boundaries) {
3442
4063
  if (!boundaries) {
3443
4064
  return;
3444
4065
  }
3445
- for (let i = boundaries.length - 1;i >= 0; i--) {
4066
+ for (let i = boundaries.length - 1;i >= 0; i -= 1) {
3446
4067
  const seg = boundaries[i];
3447
4068
  if (seg?.notFound) {
3448
4069
  return seg.notFound;
3449
4070
  }
3450
4071
  }
3451
- return;
3452
4072
  }
3453
- var DefaultClientNotFoundFallback = ({ error }) => createElement2(DefaultNotFoundScreen, { message: error.message });
4073
+ var DefaultClientNotFoundFallback = ({ error }) => createElement4(DefaultNotFoundScreen, { message: error.message });
3454
4074
  function buildNotFoundPageElement(boundaries, error) {
3455
4075
  const Fallback = pickDeepestNotFound(boundaries) ?? DefaultClientNotFoundFallback;
3456
- return createElement2(Fallback, { error });
4076
+ return createElement4(Fallback, { error });
3457
4077
  }
3458
4078
  async function parsePageResponse(res, basePath) {
3459
4079
  let finalHref;
@@ -3538,10 +4158,6 @@ function createSyncCatchUp(options) {
3538
4158
  } while (requested);
3539
4159
  };
3540
4160
  return {
3541
- async initialize() {
3542
- const page = await options.fetchPage(undefined);
3543
- currentCursor = page.cursor;
3544
- },
3545
4161
  catchUp() {
3546
4162
  requested = true;
3547
4163
  if (!running) {
@@ -3551,13 +4167,21 @@ function createSyncCatchUp(options) {
3551
4167
  }
3552
4168
  return running;
3553
4169
  },
3554
- cursor: () => currentCursor
4170
+ cursor: () => currentCursor,
4171
+ async initialize() {
4172
+ const page = await options.fetchPage(undefined);
4173
+ currentCursor = page.cursor;
4174
+ }
3555
4175
  };
3556
4176
  }
3557
4177
 
3558
4178
  // src/client/router/provider.tsx
3559
- import { jsxDEV as jsxDEV4 } from "react/jsx-dev-runtime";
4179
+ import { jsxDEV as jsxDEV5 } from "react/jsx-dev-runtime";
3560
4180
  var EMPTY_SEARCH = {};
4181
+ function getHistoryStateObject() {
4182
+ const value = history.state;
4183
+ return value !== null && typeof value === "object" ? value : {};
4184
+ }
3561
4185
  function setPrefetchCacheEntry(cache, href, entry, maxSize) {
3562
4186
  if (cache.has(href)) {
3563
4187
  cache.delete(href);
@@ -3585,9 +4209,11 @@ function RouterProvider({
3585
4209
  prefetchCacheSize,
3586
4210
  syncStream
3587
4211
  }) {
4212
+ const initialDocumentState = useDocumentState();
3588
4213
  const [state, setState] = useState(() => ({
3589
- match: initialMatch,
3590
4214
  data: initialData,
4215
+ head: initialDocumentState?.head,
4216
+ match: initialMatch,
3591
4217
  notFound: initialNotFound
3592
4218
  }));
3593
4219
  const [isNavigating, setIsNavigating] = useState(false);
@@ -3602,9 +4228,8 @@ function RouterProvider({
3602
4228
  const navAbortRef = useRef(null);
3603
4229
  const pendingScrollRef = useRef(null);
3604
4230
  const currentMatchRef = useRef(initialMatch);
3605
- const staticModeRef = useRef(detectStaticMode());
4231
+ const [staticMode] = useState(detectStaticMode);
3606
4232
  const resolvedSearch = state.data.query ?? EMPTY_SEARCH;
3607
- const searchStoreRef = useRef(null);
3608
4233
  const rootBoundaries = useMemo(() => {
3609
4234
  for (const route of routes) {
3610
4235
  const depth0 = route.segmentBoundaries?.find((b) => b.depth === 0);
@@ -3612,7 +4237,6 @@ function RouterProvider({
3612
4237
  return [depth0];
3613
4238
  }
3614
4239
  }
3615
- return;
3616
4240
  }, [routes]);
3617
4241
  const resolveNoMatchState = useCallback2(async (physicalHref, signal) => {
3618
4242
  const res = await fetch(physicalHref, { signal });
@@ -3627,12 +4251,12 @@ function RouterProvider({
3627
4251
  }
3628
4252
  const { __furinStatus: _s, __furinNotFound: _n, ...cleanData } = data ?? {};
3629
4253
  return {
3630
- match: currentMatchRef.current,
3631
4254
  data: cleanData,
3632
- title,
3633
4255
  finalHref,
4256
+ match: currentMatchRef.current,
3634
4257
  notFound: kind.error,
3635
- notFoundBoundaries: rootBoundaries
4258
+ notFoundBoundaries: rootBoundaries,
4259
+ title
3636
4260
  };
3637
4261
  }, [basePath, rootBoundaries]);
3638
4262
  const fetchPageState = useCallback2(async (rawLogicalHref, signal) => {
@@ -3645,7 +4269,7 @@ function RouterProvider({
3645
4269
  if (!match) {
3646
4270
  return await resolveNoMatchState(physicalHref, signal);
3647
4271
  }
3648
- const dataEndpoint = buildDataEndpoint(basePath, logicalHref, staticModeRef.current);
4272
+ const dataEndpoint = buildDataEndpoint(basePath, logicalHref, staticMode);
3649
4273
  const [res, loadedMod] = await Promise.all([fetch(dataEndpoint, { signal }), match.load()]);
3650
4274
  if (isStaleDeployResponse(res)) {
3651
4275
  window.location.href = physicalHref;
@@ -3658,14 +4282,15 @@ function RouterProvider({
3658
4282
  } catch (parseErr) {
3659
4283
  _log.warn({
3660
4284
  action: "navigate_server_error",
4285
+ error: String(parseErr),
3661
4286
  href: physicalHref,
3662
- status: res.status,
3663
- error: String(parseErr)
4287
+ status: res.status
3664
4288
  });
3665
4289
  return null;
3666
4290
  }
3667
4291
  const { syncData, deferredPromises } = parsed;
3668
4292
  const {
4293
+ __furinHead,
3669
4294
  __furinStatus,
3670
4295
  __furinNotFound,
3671
4296
  __furinRedirect,
@@ -3684,11 +4309,12 @@ function RouterProvider({
3684
4309
  };
3685
4310
  if (__furinError) {
3686
4311
  return {
3687
- match: loadedMatch,
3688
4312
  data: {},
3689
- title,
4313
+ error: __furinError,
3690
4314
  finalHref,
3691
- error: __furinError
4315
+ head: __furinHead,
4316
+ match: loadedMatch,
4317
+ title
3692
4318
  };
3693
4319
  }
3694
4320
  if (!res.ok && res.status !== 404) {
@@ -3696,24 +4322,26 @@ function RouterProvider({
3696
4322
  return null;
3697
4323
  }
3698
4324
  if (__furinStatus === 404) {
4325
+ const notFound = __furinNotFound !== null && typeof __furinNotFound === "object" ? __furinNotFound : {};
3699
4326
  return {
3700
- match: loadedMatch,
3701
4327
  data,
3702
- title,
3703
4328
  finalHref,
3704
- notFound: __furinNotFound ?? {}
4329
+ head: __furinHead,
4330
+ match: loadedMatch,
4331
+ notFound,
4332
+ title
3705
4333
  };
3706
4334
  }
3707
4335
  if (finalHref) {
3708
- return { match: null, data, title, finalHref };
4336
+ return { data, finalHref, match: null, title };
3709
4337
  }
3710
- return { match: loadedMatch, data, title, finalHref };
4338
+ return { data, finalHref, head: __furinHead, match: loadedMatch, title };
3711
4339
  } catch (err) {
3712
4340
  if (!isAbortError(err)) {
3713
4341
  _log.error({
3714
4342
  action: "navigate_failed",
3715
- href: basePath + logicalHref,
3716
- error: String(err)
4343
+ error: String(err),
4344
+ href: basePath + logicalHref
3717
4345
  });
3718
4346
  }
3719
4347
  return null;
@@ -3744,22 +4372,23 @@ function RouterProvider({
3744
4372
  return;
3745
4373
  }
3746
4374
  setPrefetchCacheEntry(prefetchCache.current, href, {
3747
- promise: fetchPageState(href, undefined),
3748
4375
  createdAt: Date.now(),
4376
+ promise: fetchPageState(href, undefined),
3749
4377
  staleTime
3750
4378
  }, prefetchCacheSize);
3751
4379
  }, [fetchPageState, defaultPreloadStaleTime, prefetchCacheSize]);
3752
4380
  async function resolveRedirectState(redirectLogical, myVersion, signal) {
3753
4381
  const cached = prefetchCache.current.get(redirectLogical);
3754
- const state2 = cached && !shouldRefetch(cached) ? await cached.promise : await fetchPageState(redirectLogical, signal);
4382
+ const redirectState = cached && !shouldRefetch(cached) ? await cached.promise : await fetchPageState(redirectLogical, signal);
3755
4383
  if (navVersion.current !== myVersion) {
3756
4384
  return null;
3757
4385
  }
3758
- return state2;
4386
+ return redirectState;
3759
4387
  }
3760
4388
  const navigate = useCallback2(async function navigateTo(rawLogicalHref, opts) {
3761
4389
  const logicalHref = normalizeHref(rawLogicalHref);
3762
- const myVersion = ++navVersion.current;
4390
+ navVersion.current += 1;
4391
+ const myVersion = navVersion.current;
3763
4392
  navAbortRef.current?.abort();
3764
4393
  const navAbort = new AbortController;
3765
4394
  navAbortRef.current = navAbort;
@@ -3773,8 +4402,8 @@ function RouterProvider({
3773
4402
  }
3774
4403
  if (newState && (!cached || shouldRefetch(cached))) {
3775
4404
  setPrefetchCacheEntry(prefetchCache.current, logicalHref, {
3776
- promise: Promise.resolve(newState),
3777
4405
  createdAt: Date.now(),
4406
+ promise: Promise.resolve(newState),
3778
4407
  staleTime: defaultPreloadStaleTime
3779
4408
  }, prefetchCacheSize);
3780
4409
  }
@@ -3792,7 +4421,7 @@ function RouterProvider({
3792
4421
  redirectLogical = normalizeHref(newState.finalHref);
3793
4422
  const redirectPhysical = basePath + redirectLogical;
3794
4423
  window.history.replaceState({
3795
- ...history.state ?? {},
4424
+ ...getHistoryStateObject(),
3796
4425
  _furinKey: getHistoryKey(history.state) ?? generateHistoryKey()
3797
4426
  }, "", redirectPhysical);
3798
4427
  setCurrentHref(redirectLogical);
@@ -3814,7 +4443,7 @@ function RouterProvider({
3814
4443
  const physicalEffective = basePath + effectiveLogical;
3815
4444
  if (opts?.replace) {
3816
4445
  window.history.replaceState({
3817
- ...history.state ?? {},
4446
+ ...getHistoryStateObject(),
3818
4447
  _furinKey: getHistoryKey(history.state) ?? generateHistoryKey()
3819
4448
  }, "", physicalEffective);
3820
4449
  } else {
@@ -3828,7 +4457,7 @@ function RouterProvider({
3828
4457
  const logicalPath = normalizeHref(toLogical(effectiveUrl.pathname, basePath));
3829
4458
  setCurrentHref(logicalPath + effectiveUrl.search);
3830
4459
  if (opts?.resetScroll ?? true) {
3831
- pendingScrollRef.current = { type: "reset", href: physicalEffective };
4460
+ pendingScrollRef.current = { href: physicalEffective, type: "reset" };
3832
4461
  }
3833
4462
  } finally {
3834
4463
  if (navVersion.current === myVersion) {
@@ -3836,15 +4465,12 @@ function RouterProvider({
3836
4465
  }
3837
4466
  }
3838
4467
  }, [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;
4468
+ const [searchStore] = useState(() => createSearchStore({
4469
+ currentHref,
4470
+ navigate,
4471
+ search: resolvedSearch,
4472
+ searchRoutes: routes
4473
+ }));
3848
4474
  const searchSnapshot = useMemo(() => ({
3849
4475
  currentHref,
3850
4476
  navigate,
@@ -3879,7 +4505,8 @@ function RouterProvider({
3879
4505
  const destKey = getHistoryKey(history.state);
3880
4506
  const logicalPath = normalizeHref(toLogical(window.location.pathname, basePath));
3881
4507
  const logicalHref = logicalPath + window.location.search;
3882
- const myVersion = ++navVersion.current;
4508
+ navVersion.current += 1;
4509
+ const myVersion = navVersion.current;
3883
4510
  navAbortRef.current?.abort();
3884
4511
  const navAbort = new AbortController;
3885
4512
  navAbortRef.current = navAbort;
@@ -3931,9 +4558,9 @@ function RouterProvider({
3931
4558
  }
3932
4559
  setCurrentHref(normalizeHref(effectiveLogical));
3933
4560
  if (destKey) {
3934
- pendingScrollRef.current = { type: "restore", key: destKey };
4561
+ pendingScrollRef.current = { key: destKey, type: "restore" };
3935
4562
  } else {
3936
- window.scrollTo({ top: 0, behavior: "instant" });
4563
+ window.scrollTo({ behavior: "instant", top: 0 });
3937
4564
  }
3938
4565
  } finally {
3939
4566
  if (navVersion.current === myVersion) {
@@ -3945,7 +4572,7 @@ function RouterProvider({
3945
4572
  useEffect(() => {
3946
4573
  history.scrollRestoration = "manual";
3947
4574
  if (!getHistoryKey(history.state)) {
3948
- history.replaceState({ ...history.state ?? {}, _furinKey: generateHistoryKey() }, "");
4575
+ history.replaceState({ ...getHistoryStateObject(), _furinKey: generateHistoryKey() }, "");
3949
4576
  }
3950
4577
  }, []);
3951
4578
  useLayoutEffect(() => {
@@ -3959,21 +4586,21 @@ function RouterProvider({
3959
4586
  const raw = sessionStorage.getItem(SCROLL_STORAGE_KEY);
3960
4587
  const positions = raw ? JSON.parse(raw) : {};
3961
4588
  const y = positions[instruction.key] ?? 0;
3962
- window.scrollTo({ top: y, behavior: "instant" });
4589
+ window.scrollTo({ behavior: "instant", top: y });
3963
4590
  } catch {
3964
- window.scrollTo({ top: 0, behavior: "instant" });
4591
+ window.scrollTo({ behavior: "instant", top: 0 });
3965
4592
  }
3966
4593
  return;
3967
4594
  }
3968
4595
  const destUrl = new URL(instruction.href, window.location.origin);
3969
4596
  if (destUrl.hash) {
3970
- const id = decodeURIComponent(destUrl.hash.slice(1));
4597
+ const id = decodeHashFragment(destUrl.hash.slice(1));
3971
4598
  const element = document.getElementById(id);
3972
4599
  if (element) {
3973
4600
  element.scrollIntoView({ behavior: "instant", block: "start" });
3974
4601
  }
3975
4602
  } else {
3976
- window.scrollTo({ top: 0, behavior: "instant" });
4603
+ window.scrollTo({ behavior: "instant", top: 0 });
3977
4604
  }
3978
4605
  }, [currentHref]);
3979
4606
  useEffect(() => {
@@ -3999,12 +4626,17 @@ function RouterProvider({
3999
4626
  if (logicalHref === null) {
4000
4627
  return;
4001
4628
  }
4629
+ const logicalPathname = new URL(logicalHref, window.location.origin).pathname;
4630
+ const hasConcreteMatch = routes.some((route) => !route.pattern.split("/").includes("*") && route.regex.test(logicalPathname));
4631
+ if (!hasConcreteMatch) {
4632
+ return;
4633
+ }
4002
4634
  e.preventDefault();
4003
4635
  navigate(logicalHref, { resetScroll: !logicalHref.includes("#") });
4004
4636
  };
4005
4637
  document.addEventListener("click", handler);
4006
4638
  return () => document.removeEventListener("click", handler);
4007
- }, [navigate, basePath]);
4639
+ }, [navigate, basePath, routes]);
4008
4640
  useEffect(() => {
4009
4641
  if (typeof window === "undefined") {
4010
4642
  return;
@@ -4012,6 +4644,9 @@ function RouterProvider({
4012
4644
  const originalFetch = window.fetch;
4013
4645
  const wrapped = async (...args) => {
4014
4646
  const response = await originalFetch.apply(window, args);
4647
+ if (!isSameOriginFetchResult(args[0], response.url, window.location.origin)) {
4648
+ return response;
4649
+ }
4015
4650
  const invalidated = [];
4016
4651
  applyRevalidateHeader(response.headers, (path, type) => {
4017
4652
  const resolvedType = type ?? "page";
@@ -4080,6 +4715,7 @@ function RouterProvider({
4080
4715
  }
4081
4716
  });
4082
4717
  };
4718
+ const onOpen = () => recover();
4083
4719
  const onSync = (event) => {
4084
4720
  try {
4085
4721
  const payload = JSON.parse(event.data);
@@ -4097,6 +4733,7 @@ function RouterProvider({
4097
4733
  return;
4098
4734
  }
4099
4735
  source = new EventSource(streamUrl);
4736
+ source.addEventListener("open", onOpen);
4100
4737
  source.addEventListener("furin.sync", onSync);
4101
4738
  };
4102
4739
  catchUp.initialize().then(() => {
@@ -4104,7 +4741,6 @@ function RouterProvider({
4104
4741
  return;
4105
4742
  }
4106
4743
  connect();
4107
- recover();
4108
4744
  }).catch((error) => {
4109
4745
  if (disposed) {
4110
4746
  return;
@@ -4114,6 +4750,7 @@ function RouterProvider({
4114
4750
  });
4115
4751
  return () => {
4116
4752
  disposed = true;
4753
+ source?.removeEventListener("open", onOpen);
4117
4754
  source?.removeEventListener("furin.sync", onSync);
4118
4755
  source?.close();
4119
4756
  };
@@ -4131,23 +4768,24 @@ function RouterProvider({
4131
4768
  resetKey: currentHref
4132
4769
  }, state.error);
4133
4770
  }
4134
- return /* @__PURE__ */ jsxDEV4(SearchStoreContext.Provider, {
4771
+ const routerTree = /* @__PURE__ */ jsxDEV5(SearchStoreContext.Provider, {
4135
4772
  value: searchStore,
4136
4773
  children: buildRouterTree({
4137
4774
  basePath,
4138
4775
  currentHref,
4139
- search: resolvedSearch,
4140
- searchRoutes: routes,
4776
+ defaultPreload,
4777
+ defaultPreloadDelay,
4778
+ defaultPreloadStaleTime,
4779
+ invalidatePrefetch,
4780
+ isNavigating,
4141
4781
  navigate,
4142
4782
  prefetch,
4143
4783
  refresh,
4144
- invalidatePrefetch,
4145
- isNavigating,
4146
- defaultPreload,
4147
- defaultPreloadDelay,
4148
- defaultPreloadStaleTime
4784
+ search: resolvedSearch,
4785
+ searchRoutes: routes
4149
4786
  }, pageElement, {
4150
4787
  digest: initialDigest,
4788
+ document: initialDocumentState !== null,
4151
4789
  onReset: () => {
4152
4790
  refresh(undefined).catch((err) => {
4153
4791
  _log.error({ action: "boundary_reset_failed", error: String(err) });
@@ -4156,31 +4794,48 @@ function RouterProvider({
4156
4794
  resetKey: currentHref
4157
4795
  })
4158
4796
  }, undefined, false, undefined, this);
4797
+ if (initialDocumentState === null) {
4798
+ return routerTree;
4799
+ }
4800
+ return /* @__PURE__ */ jsxDEV5(DocumentProvider, {
4801
+ value: {
4802
+ ...initialDocumentState,
4803
+ head: state.head
4804
+ },
4805
+ children: routerTree
4806
+ }, undefined, false, undefined, this);
4159
4807
  }
4160
4808
  // src/client/link.tsx
4161
4809
  function computeLinkView({
4162
4810
  to,
4811
+ params,
4163
4812
  search,
4164
4813
  hash,
4165
4814
  children,
4166
4815
  activeProps,
4167
4816
  inactiveProps
4168
4817
  }, router2) {
4169
- const searchDefaults = findSearchDefaultsForRouteTarget(to, router2.searchRoutes);
4170
- const logicalHref = buildHref(to, search, hash, searchDefaults);
4171
- const logicalHrefWithoutHash = buildHref(to, search, undefined, searchDefaults);
4818
+ const resolvedTo = applyLinkParams(to, params);
4819
+ const searchDefaults = findSearchDefaultsForRouteTarget(resolvedTo, router2.searchRoutes);
4820
+ const logicalHref = buildHref(resolvedTo, search, hash, searchDefaults);
4821
+ const logicalHrefWithoutHash = buildHref(resolvedTo, search, undefined, searchDefaults);
4172
4822
  const isAbsolute = logicalHref.startsWith("http://") || logicalHref.startsWith("https://") || logicalHref.startsWith("//");
4173
- const href = isAbsolute ? logicalHref : router2.basePath + logicalHref;
4823
+ const candidateHref = isAbsolute ? logicalHref : router2.basePath + logicalHref;
4824
+ const href = navigationHrefPolicy(candidateHref, undefined) === "blocked" ? "#" : candidateHref;
4174
4825
  const isActive = !isAbsolute && router2.currentHref === normalizeHref(logicalHrefWithoutHash);
4175
4826
  const resolvedChildren = typeof children === "function" ? children({ isActive }) : children;
4176
4827
  const extraProps = {
4177
4828
  ...inactiveProps && !isActive ? inactiveProps() : {},
4178
4829
  ...activeProps ? activeProps({ isActive }) : {}
4179
4830
  };
4180
- return { logicalHref, href, isActive, resolvedChildren, extraProps };
4831
+ return { extraProps, href, isActive, logicalHref, resolvedChildren };
4832
+ }
4833
+ function isSameOriginUrl(url) {
4834
+ return navigationHrefPolicy(url, window.location.origin) === "internal";
4181
4835
  }
4182
4836
  function LinkInteractive({
4183
4837
  to,
4838
+ params,
4184
4839
  search,
4185
4840
  hash,
4186
4841
  preload,
@@ -4202,7 +4857,7 @@ function LinkInteractive({
4202
4857
  const router2 = useRouter();
4203
4858
  const anchorRef = useRef2(null);
4204
4859
  const intentTimerRef = useRef2(null);
4205
- const { logicalHref, href, isActive, resolvedChildren, extraProps } = computeLinkView({ to, search, hash, children, activeProps, inactiveProps }, router2);
4860
+ const { logicalHref, href, isActive, resolvedChildren, extraProps } = computeLinkView({ activeProps, children, hash, inactiveProps, params, search, to }, router2);
4206
4861
  const effectivePreload = preload ?? router2.defaultPreload;
4207
4862
  const effectiveDelay = preloadDelay ?? router2.defaultPreloadDelay;
4208
4863
  const effectiveStaleTime = preloadStaleTime ?? router2.defaultPreloadStaleTime;
@@ -4234,13 +4889,6 @@ function LinkInteractive({
4234
4889
  intentTimerRef.current = null;
4235
4890
  }
4236
4891
  }, []);
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
4892
  const handleClick = (e) => {
4245
4893
  onClick?.(e);
4246
4894
  if (e.defaultPrevented) {
@@ -4256,7 +4904,11 @@ function LinkInteractive({
4256
4904
  if (anchorProps.target && anchorProps.target !== "_self") {
4257
4905
  return;
4258
4906
  }
4259
- if (!isInternal(href)) {
4907
+ if (navigationHrefPolicy(logicalHref, window.location.origin) === "blocked") {
4908
+ e.preventDefault();
4909
+ return;
4910
+ }
4911
+ if (!isSameOriginUrl(href)) {
4260
4912
  return;
4261
4913
  }
4262
4914
  e.preventDefault();
@@ -4268,7 +4920,7 @@ function LinkInteractive({
4268
4920
  };
4269
4921
  const handleMouseEnter = (e) => {
4270
4922
  onMouseEnter?.(e);
4271
- if (!disabled && effectivePreload === "intent" && isInternal(href)) {
4923
+ if (!disabled && effectivePreload === "intent" && isSameOriginUrl(href)) {
4272
4924
  intentTimerRef.current = setTimeout(triggerPrefetch, effectiveDelay);
4273
4925
  }
4274
4926
  };
@@ -4281,18 +4933,18 @@ function LinkInteractive({
4281
4933
  };
4282
4934
  const handleFocus = (e) => {
4283
4935
  onFocus?.(e);
4284
- if (!disabled && effectivePreload === "intent" && isInternal(href)) {
4936
+ if (!disabled && effectivePreload === "intent" && isSameOriginUrl(href)) {
4285
4937
  triggerPrefetch();
4286
4938
  }
4287
4939
  };
4288
- return createElement3("a", {
4289
- ref: anchorRef,
4290
- href,
4940
+ return createElement5("a", {
4291
4941
  "data-furin-link": true,
4942
+ href,
4292
4943
  onClick: handleClick,
4944
+ onFocus: handleFocus,
4293
4945
  onMouseEnter: handleMouseEnter,
4294
4946
  onMouseLeave: handleMouseLeave,
4295
- onFocus: handleFocus,
4947
+ ref: anchorRef,
4296
4948
  ...isActive ? { "data-status": "active" } : {},
4297
4949
  ...anchorProps,
4298
4950
  ...extraProps,
@@ -4302,21 +4954,22 @@ function LinkInteractive({
4302
4954
  var SSR_FALLBACK_ROUTER = {
4303
4955
  basePath: "",
4304
4956
  currentHref: "/",
4305
- search: {},
4306
- searchRoutes: [],
4957
+ defaultPreload: "intent",
4958
+ defaultPreloadDelay: 50,
4959
+ defaultPreloadStaleTime: 30000,
4960
+ invalidatePrefetch: (_path, _type) => {},
4961
+ isNavigating: false,
4307
4962
  navigate: (_href, _opts) => Promise.resolve(),
4308
4963
  prefetch: (_href, _opts) => {},
4309
- invalidatePrefetch: (_path, _type) => {},
4310
4964
  refresh: (_opts) => Promise.resolve(),
4311
- isNavigating: false,
4312
- defaultPreload: "intent",
4313
- defaultPreloadDelay: 50,
4314
- defaultPreloadStaleTime: 30000
4965
+ search: {},
4966
+ searchRoutes: []
4315
4967
  };
4316
4968
  function renderLinkElement(props, router2) {
4317
4969
  const { href, isActive, resolvedChildren, extraProps } = computeLinkView(props, router2);
4318
4970
  const {
4319
4971
  to: _to,
4972
+ params: _params,
4320
4973
  search: _search,
4321
4974
  hash: _hash,
4322
4975
  children: _children,
@@ -4335,9 +4988,9 @@ function renderLinkElement(props, router2) {
4335
4988
  href: _href,
4336
4989
  ...anchorProps
4337
4990
  } = props;
4338
- return createElement3("a", {
4339
- href,
4991
+ return createElement5("a", {
4340
4992
  "data-furin-link": true,
4993
+ href,
4341
4994
  ...isActive ? { "data-status": "active" } : {},
4342
4995
  ...anchorProps,
4343
4996
  ...extraProps,
@@ -4346,46 +4999,50 @@ function renderLinkElement(props, router2) {
4346
4999
  }
4347
5000
  function Link(props) {
4348
5001
  if (typeof window === "undefined") {
4349
- return createElement3(RouterContext.Consumer, {
5002
+ return createElement5(RouterContext.Consumer, {
4350
5003
  children: (routerCtx) => renderLinkElement(props, routerCtx ?? SSR_FALLBACK_ROUTER)
4351
5004
  });
4352
5005
  }
4353
- return createElement3(LinkInteractive, props);
5006
+ return createElement5(LinkInteractive, props);
4354
5007
  }
4355
5008
  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,
5009
+ CLIENT_FALLBACK_ROUTER,
4389
5010
  FALLBACK_SEARCH_STORE,
4390
- CLIENT_FALLBACK_ROUTER
5011
+ Link,
5012
+ RouterContext,
5013
+ RouterProvider,
5014
+ SCROLL_STORAGE_KEY,
5015
+ SSR_FALLBACK_ROUTER,
5016
+ SearchStoreContext,
5017
+ TRAILING_SLASHES_RE,
5018
+ applyRevalidateHeader,
5019
+ buildDataEndpoint,
5020
+ buildHref,
5021
+ buildNotFoundPageElement,
5022
+ buildPageElement,
5023
+ buildRouterTree,
5024
+ classifySpaResponse,
5025
+ createSearchStore,
5026
+ decodeHashFragment,
5027
+ detectStaticMode,
5028
+ fromCrossJSON,
5029
+ generateHistoryKey,
5030
+ getHistoryKey,
5031
+ isSameOriginFetchResult,
5032
+ isStaleDeployResponse,
5033
+ navigationHrefPolicy,
5034
+ normalizeHref,
5035
+ normalizePath,
5036
+ parseDeferredNdjson,
5037
+ parsePageResponse,
5038
+ pickDeepestNotFound,
5039
+ saveScrollPosition,
5040
+ searchSnapshotFromRouterContext,
5041
+ shouldAutoRefreshPath,
5042
+ shouldInterceptClick,
5043
+ shouldRefetch,
5044
+ stripHashFromHref,
5045
+ toLogical,
5046
+ useNavigate,
5047
+ useRouter
4391
5048
  };