toiljs 0.0.116 → 0.0.117

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 (325) hide show
  1. package/CHANGELOG.md +5 -0
  2. package/README.md +16 -7
  3. package/build/backend/.tsbuildinfo +1 -1
  4. package/build/cli/.tsbuildinfo +1 -1
  5. package/build/cli/index.js +2375 -258
  6. package/build/client/.tsbuildinfo +1 -1
  7. package/build/client/dev/devtools.js +1 -1
  8. package/build/client/dev/error-overlay.js +1 -1
  9. package/build/client/routing/mount.js +1 -1
  10. package/build/compiler/.tsbuildinfo +1 -1
  11. package/build/compiler/auth-emails.js +7 -3
  12. package/build/compiler/emails.js +1 -1
  13. package/build/compiler/index.d.ts +1 -0
  14. package/build/compiler/index.js +25 -4
  15. package/build/compiler/pages.js +2 -3
  16. package/build/compiler/prerender.d.ts +3 -8
  17. package/build/compiler/prerender.js +88 -127
  18. package/build/compiler/ssg.js +3 -4
  19. package/build/compiler/template-build.js +3 -4
  20. package/build/compiler/toil-docs.generated.js +6 -5
  21. package/build/compiler/vite.js +3 -6
  22. package/build/devserver/.tsbuildinfo +1 -1
  23. package/build/devserver/db/database.js +7 -3
  24. package/build/devserver/db/types.js +1 -1
  25. package/build/devserver/production.js +4 -3
  26. package/build/devserver/runtime/crypto.d.ts +1 -1
  27. package/build/io/.tsbuildinfo +1 -1
  28. package/build/logger/.tsbuildinfo +1 -1
  29. package/build/shared/.tsbuildinfo +1 -1
  30. package/examples/basic/client/routes/analytics.tsx +7 -5
  31. package/examples/basic/server/tsconfig.json +1 -3
  32. package/package.json +45 -44
  33. package/presets/no-uint8array-tostring.js +120 -153
  34. package/presets/oxlint.d.ts +5 -0
  35. package/presets/oxlint.js +224 -0
  36. package/server/runtime/tsconfig.json +1 -3
  37. package/tsconfig.json +2 -11
  38. package/.github/ISSUE_TEMPLATE/bug_report.md +0 -38
  39. package/.github/ISSUE_TEMPLATE/bug_report.yml +0 -90
  40. package/.github/ISSUE_TEMPLATE/config.yml +0 -8
  41. package/.github/ISSUE_TEMPLATE/feature_request.md +0 -20
  42. package/.github/PULL_REQUEST_TEMPLATE.md +0 -43
  43. package/.github/changelog-config.json +0 -45
  44. package/.github/dependabot.yml +0 -27
  45. package/.github/workflows/ci.yml +0 -222
  46. package/.vscode/settings.json +0 -10
  47. package/docs/README.md +0 -107
  48. package/docs/auth/README.md +0 -104
  49. package/docs/auth/configuration.md +0 -105
  50. package/docs/auth/emails.md +0 -92
  51. package/docs/auth/extending.md +0 -202
  52. package/docs/auth/how-it-works.md +0 -138
  53. package/docs/auth/usage.md +0 -188
  54. package/docs/backend/README.md +0 -143
  55. package/docs/backend/data.md +0 -351
  56. package/docs/backend/rest.md +0 -402
  57. package/docs/backend/rpc.md +0 -226
  58. package/docs/background/README.md +0 -114
  59. package/docs/background/daemons.md +0 -276
  60. package/docs/background/derive.md +0 -179
  61. package/docs/cli/README.md +0 -379
  62. package/docs/concepts/ai-guide.md +0 -132
  63. package/docs/concepts/config.md +0 -416
  64. package/docs/concepts/decorators.md +0 -127
  65. package/docs/concepts/security.md +0 -108
  66. package/docs/concepts/tiers.md +0 -166
  67. package/docs/concepts/types.md +0 -216
  68. package/docs/database/README.md +0 -143
  69. package/docs/database/capacity.md +0 -350
  70. package/docs/database/counters.md +0 -174
  71. package/docs/database/documents.md +0 -277
  72. package/docs/database/events.md +0 -307
  73. package/docs/database/membership.md +0 -246
  74. package/docs/database/setup.md +0 -155
  75. package/docs/database/unique.md +0 -216
  76. package/docs/database/views.md +0 -246
  77. package/docs/frontend/README.md +0 -104
  78. package/docs/frontend/components.md +0 -286
  79. package/docs/frontend/data-fetching.md +0 -260
  80. package/docs/frontend/images.md +0 -148
  81. package/docs/frontend/metadata.md +0 -344
  82. package/docs/frontend/navigation.md +0 -296
  83. package/docs/frontend/rendering.md +0 -236
  84. package/docs/frontend/routing.md +0 -346
  85. package/docs/frontend/scripts.md +0 -118
  86. package/docs/frontend/search.md +0 -191
  87. package/docs/frontend/styling.md +0 -147
  88. package/docs/frontend/toil-global.md +0 -216
  89. package/docs/getting-started/README.md +0 -81
  90. package/docs/getting-started/create-project.md +0 -131
  91. package/docs/getting-started/deploy.md +0 -101
  92. package/docs/getting-started/first-app.md +0 -215
  93. package/docs/getting-started/installation.md +0 -124
  94. package/docs/getting-started/migrating.md +0 -125
  95. package/docs/getting-started/project-structure.md +0 -163
  96. package/docs/introduction/README.md +0 -66
  97. package/docs/introduction/design-principles.md +0 -81
  98. package/docs/introduction/distributed.md +0 -91
  99. package/docs/introduction/how-it-works.md +0 -121
  100. package/docs/introduction/hyperscale.md +0 -70
  101. package/docs/introduction/modern-stack.md +0 -85
  102. package/docs/introduction/vs-other-frameworks.md +0 -64
  103. package/docs/introduction/why-toil.md +0 -99
  104. package/docs/llms.txt +0 -95
  105. package/docs/realtime/README.md +0 -102
  106. package/docs/realtime/channels.md +0 -211
  107. package/docs/realtime/streams.md +0 -369
  108. package/docs/services/README.md +0 -60
  109. package/docs/services/analytics.md +0 -279
  110. package/docs/services/caching.md +0 -175
  111. package/docs/services/cookies.md +0 -235
  112. package/docs/services/crypto.md +0 -209
  113. package/docs/services/email.md +0 -289
  114. package/docs/services/environment.md +0 -141
  115. package/docs/services/ratelimit.md +0 -174
  116. package/docs/services/time.md +0 -85
  117. package/eslint.config.js +0 -57
  118. package/examples/basic/client/routes/docs/[...slug].tsx +0 -12
  119. package/presets/eslint.js +0 -88
  120. package/src/backend/index.ts +0 -204
  121. package/src/cli/configure.ts +0 -363
  122. package/src/cli/create.ts +0 -924
  123. package/src/cli/db.ts +0 -158
  124. package/src/cli/diagnostics.ts +0 -665
  125. package/src/cli/doctor.ts +0 -982
  126. package/src/cli/features.ts +0 -170
  127. package/src/cli/index.ts +0 -326
  128. package/src/cli/notify.ts +0 -120
  129. package/src/cli/proc.ts +0 -56
  130. package/src/cli/ui.ts +0 -169
  131. package/src/cli/update.ts +0 -248
  132. package/src/cli/updates.ts +0 -92
  133. package/src/cli/validate.ts +0 -31
  134. package/src/cli/version-check.ts +0 -125
  135. package/src/client/auth.ts +0 -869
  136. package/src/client/channel/channel.ts +0 -146
  137. package/src/client/components/Form.tsx +0 -65
  138. package/src/client/components/Image.tsx +0 -160
  139. package/src/client/components/Script.tsx +0 -113
  140. package/src/client/components/Slot.tsx +0 -21
  141. package/src/client/dev/devtools.tsx +0 -1089
  142. package/src/client/dev/error-overlay.tsx +0 -225
  143. package/src/client/errors.ts +0 -11
  144. package/src/client/head/head.ts +0 -182
  145. package/src/client/head/metadata.ts +0 -110
  146. package/src/client/index.ts +0 -130
  147. package/src/client/navigation/Link.tsx +0 -108
  148. package/src/client/navigation/NavLink.tsx +0 -86
  149. package/src/client/navigation/navigation.ts +0 -235
  150. package/src/client/navigation/prefetch.ts +0 -169
  151. package/src/client/navigation/scroll.ts +0 -53
  152. package/src/client/routing/Router.tsx +0 -216
  153. package/src/client/routing/action.ts +0 -122
  154. package/src/client/routing/error-boundary.tsx +0 -43
  155. package/src/client/routing/hooks.ts +0 -140
  156. package/src/client/routing/lazy.ts +0 -77
  157. package/src/client/routing/loader.ts +0 -381
  158. package/src/client/routing/match.ts +0 -47
  159. package/src/client/routing/mount.tsx +0 -90
  160. package/src/client/routing/params-context.ts +0 -10
  161. package/src/client/routing/slot-context.ts +0 -7
  162. package/src/client/rpc.ts +0 -97
  163. package/src/client/search/search.ts +0 -189
  164. package/src/client/search/use-page-search.ts +0 -73
  165. package/src/client/ssr/markers.tsx +0 -172
  166. package/src/client/stream/client.ts +0 -237
  167. package/src/client/types.ts +0 -73
  168. package/src/compiler/auth-emails.ts +0 -312
  169. package/src/compiler/config.ts +0 -369
  170. package/src/compiler/docs.ts +0 -127
  171. package/src/compiler/email-preview.ts +0 -314
  172. package/src/compiler/emails.ts +0 -404
  173. package/src/compiler/fonts.ts +0 -89
  174. package/src/compiler/generate.ts +0 -471
  175. package/src/compiler/image-blur.ts +0 -42
  176. package/src/compiler/image-report.ts +0 -88
  177. package/src/compiler/index.ts +0 -1362
  178. package/src/compiler/pages.ts +0 -49
  179. package/src/compiler/plugin.ts +0 -391
  180. package/src/compiler/prerender.ts +0 -263
  181. package/src/compiler/routes.ts +0 -170
  182. package/src/compiler/seo.ts +0 -415
  183. package/src/compiler/sri.ts +0 -144
  184. package/src/compiler/ssg.ts +0 -177
  185. package/src/compiler/ssr-codegen.ts +0 -85
  186. package/src/compiler/template-build.ts +0 -676
  187. package/src/compiler/template.ts +0 -262
  188. package/src/compiler/toil-docs.generated.ts +0 -77
  189. package/src/compiler/vite.ts +0 -245
  190. package/src/devserver/analytics/index.ts +0 -317
  191. package/src/devserver/config/dotenv.ts +0 -102
  192. package/src/devserver/config/env.ts +0 -30
  193. package/src/devserver/config/ratelimit.ts +0 -123
  194. package/src/devserver/daemon/catalog.ts +0 -120
  195. package/src/devserver/daemon/cron.ts +0 -87
  196. package/src/devserver/daemon/host.ts +0 -134
  197. package/src/devserver/daemon/index.ts +0 -369
  198. package/src/devserver/daemon/runtime.ts +0 -48
  199. package/src/devserver/db/catalog.ts +0 -109
  200. package/src/devserver/db/database.ts +0 -1834
  201. package/src/devserver/db/derives.ts +0 -121
  202. package/src/devserver/db/index.ts +0 -20
  203. package/src/devserver/db/routeKinds.ts +0 -191
  204. package/src/devserver/db/types.ts +0 -168
  205. package/src/devserver/email/caps.ts +0 -0
  206. package/src/devserver/email/config.ts +0 -141
  207. package/src/devserver/email/console.ts +0 -348
  208. package/src/devserver/email/index.ts +0 -155
  209. package/src/devserver/email/providers.ts +0 -131
  210. package/src/devserver/email/status.ts +0 -23
  211. package/src/devserver/email/validate.ts +0 -37
  212. package/src/devserver/email/wire.ts +0 -55
  213. package/src/devserver/http/cache.ts +0 -0
  214. package/src/devserver/http/envelope.ts +0 -157
  215. package/src/devserver/http/proxy.ts +0 -172
  216. package/src/devserver/http/runtime.ts +0 -387
  217. package/src/devserver/index.ts +0 -43
  218. package/src/devserver/production-ipc.ts +0 -63
  219. package/src/devserver/production-worker.ts +0 -83
  220. package/src/devserver/production.ts +0 -718
  221. package/src/devserver/runtime/crypto.ts +0 -587
  222. package/src/devserver/runtime/host.ts +0 -427
  223. package/src/devserver/runtime/module.ts +0 -442
  224. package/src/devserver/server.ts +0 -251
  225. package/src/devserver/ssr.ts +0 -208
  226. package/src/devserver/stream/catalog.ts +0 -106
  227. package/src/devserver/stream/host.ts +0 -42
  228. package/src/devserver/stream/index.ts +0 -301
  229. package/src/devserver/stream/manager.ts +0 -167
  230. package/src/devserver/stream/router.ts +0 -101
  231. package/src/devserver/stream/wire.ts +0 -58
  232. package/src/devserver/stream/ws.ts +0 -78
  233. package/src/devserver/wasm/sections.ts +0 -59
  234. package/src/devserver/wasm/surface.ts +0 -115
  235. package/src/io/FastMap.ts +0 -151
  236. package/src/io/FastSet.ts +0 -113
  237. package/src/io/codec.ts +0 -362
  238. package/src/io/index.ts +0 -10
  239. package/src/io/lengths.ts +0 -14
  240. package/src/io/types.ts +0 -19
  241. package/src/logger/index.ts +0 -22
  242. package/src/shared/index.ts +0 -46
  243. package/test/analytics-dev.test.ts +0 -113
  244. package/test/assembly/aspect-shim.ts +0 -33
  245. package/test/assembly/cookie.spec.ts +0 -303
  246. package/test/assembly/example.spec.ts +0 -22
  247. package/test/assembly/ssr.spec.ts +0 -95
  248. package/test/assembly.test.ts +0 -59
  249. package/test/auth-emails.test.ts +0 -118
  250. package/test/built-ssr.test.ts +0 -148
  251. package/test/channel.test.ts +0 -21
  252. package/test/config-host-port.test.ts +0 -59
  253. package/test/configure.test.ts +0 -94
  254. package/test/daemon-build.test.ts +0 -278
  255. package/test/daemon-catalog.test.ts +0 -349
  256. package/test/daemon-emulation.test.ts +0 -256
  257. package/test/db.test.ts +0 -0
  258. package/test/devserver-database.test.ts +0 -1102
  259. package/test/devserver-email.test.ts +0 -306
  260. package/test/devserver-pqauth.test.ts +0 -93
  261. package/test/devserver-secrets.test.ts +0 -63
  262. package/test/devserver.test.ts +0 -259
  263. package/test/doctor.test.ts +0 -298
  264. package/test/dom/Image.test.tsx +0 -144
  265. package/test/dom/Link.test.tsx +0 -67
  266. package/test/dom/NavLink.test.tsx +0 -37
  267. package/test/dom/Script.test.tsx +0 -48
  268. package/test/dom/action.test.tsx +0 -146
  269. package/test/dom/error-overlay.test.tsx +0 -44
  270. package/test/dom/loader.test.tsx +0 -121
  271. package/test/dom/navigation.test.ts +0 -59
  272. package/test/dom/revalidate.test.tsx +0 -38
  273. package/test/dom/route-head.test.tsx +0 -56
  274. package/test/dom/router-loading.test.tsx +0 -44
  275. package/test/dom/scroll.test.ts +0 -56
  276. package/test/dom/slot.test.tsx +0 -131
  277. package/test/dom/use-metadata.test.tsx +0 -58
  278. package/test/dom/view-transitions.test.tsx +0 -53
  279. package/test/dynamic-routing.test.ts +0 -132
  280. package/test/email-console.test.ts +0 -86
  281. package/test/email-preview.test.ts +0 -73
  282. package/test/emails.test.ts +0 -58
  283. package/test/errors.test.ts +0 -21
  284. package/test/example-guestbook.test.ts +0 -123
  285. package/test/features.test.ts +0 -149
  286. package/test/fixtures/bignum-wire/spec.ts +0 -25
  287. package/test/fixtures/daemon-app.ts +0 -65
  288. package/test/fixtures/stream-echo.ts +0 -26
  289. package/test/fixtures/stream-gate.ts +0 -28
  290. package/test/fixtures/stream-trap.ts +0 -18
  291. package/test/fixtures/stream-typed.ts +0 -41
  292. package/test/fonts.test.ts +0 -28
  293. package/test/global-setup.ts +0 -17
  294. package/test/head.test.ts +0 -42
  295. package/test/image-blur.test.ts +0 -50
  296. package/test/io.test.ts +0 -117
  297. package/test/metadata.test.ts +0 -40
  298. package/test/navlink.test.ts +0 -28
  299. package/test/pages.test.ts +0 -105
  300. package/test/placeholder.test.ts +0 -9
  301. package/test/pqauth-e2e.test.ts +0 -216
  302. package/test/pqauth-email.test.ts +0 -801
  303. package/test/prerender.test.ts +0 -116
  304. package/test/prettier-plugin.test.ts +0 -46
  305. package/test/routes.test.ts +0 -76
  306. package/test/rpc-bignum-wire.test.ts +0 -164
  307. package/test/rpc-dispatch.test.ts +0 -132
  308. package/test/rpc-kinds.test.ts +0 -18
  309. package/test/rpc.test.ts +0 -66
  310. package/test/search.test.ts +0 -114
  311. package/test/seo.test.ts +0 -175
  312. package/test/slot-layouts.test.ts +0 -69
  313. package/test/sri.test.ts +0 -129
  314. package/test/ssg.test.ts +0 -36
  315. package/test/ssr-hydration.test.tsx +0 -122
  316. package/test/ssr-render.test.ts +0 -197
  317. package/test/ssr-template.test.tsx +0 -482
  318. package/test/stream-emulation.test.ts +0 -479
  319. package/test/ui.test.ts +0 -40
  320. package/test/update.test.ts +0 -58
  321. package/test/validate.test.ts +0 -42
  322. package/test/version-check.test.ts +0 -130
  323. package/tests/data-parity/generated-parity.ts +0 -99
  324. package/tests/data-parity/parity.ts +0 -80
  325. package/tests/data-parity/spec.ts +0 -46
@@ -1,216 +0,0 @@
1
- import { createElement, type ReactNode, Suspense, useLayoutEffect } from 'react';
2
-
3
- import { ErrorBoundary } from './error-boundary.js';
4
- import { useLocation } from './hooks.js';
5
- import {
6
- errorComponent,
7
- loadingComponent,
8
- nestedLayout,
9
- resolveLayout,
10
- resolveNotFound,
11
- } from './lazy.js';
12
- import { LoaderDataContext, loaderKey, readRouteData } from './loader.js';
13
- import { matchRoute, type RouteParams } from './match.js';
14
- import { useRouteHead } from '../head/head.js';
15
- import { ParamsContext } from './params-context.js';
16
- import { SlotContext } from './slot-context.js';
17
- import {
18
- isSoftNavigation,
19
- navigationEpoch,
20
- previousPathname,
21
- settleNavigation,
22
- } from '../navigation/navigation.js';
23
- import { applyScroll } from '../navigation/scroll.js';
24
- import type { ErrorComponentLoader, LayoutLoader, NotFoundLoader, RouteDef } from '../types.js';
25
-
26
- /** Loads a matched route's module + loader data (suspending), then renders it with the data in context. */
27
- function RoutePage(props: {
28
- route: RouteDef;
29
- params: RouteParams;
30
- dataKey: string;
31
- epoch: number;
32
- }): ReactNode {
33
- const { Component, data, head } = readRouteData(
34
- props.route,
35
- props.params,
36
- props.dataKey,
37
- props.epoch,
38
- );
39
- useRouteHead(head);
40
- return (
41
- <LoaderDataContext.Provider value={data}>
42
- {createElement(Component)}
43
- </LoaderDataContext.Provider>
44
- );
45
- }
46
-
47
- /**
48
- * Wraps a matched route's page in its loading boundary, templates, nested layouts, and error
49
- * boundary. `keyPrefix` namespaces the loader-cache key and boundary keys so a parallel slot and the
50
- * main route can match the same URL without colliding.
51
- */
52
- function renderMatched(
53
- matched: RouteDef,
54
- params: RouteParams,
55
- pathname: string,
56
- epoch: number,
57
- keyPrefix: string,
58
- ): ReactNode {
59
- const search = typeof window === 'undefined' ? '' : window.location.search;
60
- const dataKey = keyPrefix + loaderKey(pathname, search);
61
- const fallback: ReactNode = matched.loading
62
- ? createElement(
63
- Suspense,
64
- { fallback: null },
65
- createElement(loadingComponent(matched.loading)),
66
- )
67
- : null;
68
-
69
- // A route with a `loading.tsx` keys its boundary per URL *and* navigation epoch, so its fallback
70
- // shows even inside the transition, on first nav and on an in-place revalidate of the same URL
71
- // (the epoch bumps). A route without one keeps a STABLE boundary (key `undefined`): the Suspense
72
- // must NOT be remounted on navigation, or it becomes a freshly-mounted boundary with no committed
73
- // content and React shows its (null) fallback during the next route's chunk/loader load, i.e. a
74
- // blank flash, even inside the transition. With a stable boundary the transition holds the old
75
- // page until the next one is ready. The loader cache key stays the bare URL, so reused data hits.
76
- // The page itself is keyed by URL so each route mounts fresh (no state bleed between routes); it
77
- // lives INSIDE the boundary so that re-mount doesn't tear down the boundary above it.
78
- let content: ReactNode = (
79
- <Suspense
80
- key={matched.loading ? `${dataKey}:${String(epoch)}` : undefined}
81
- fallback={fallback}>
82
- <RoutePage
83
- key={dataKey}
84
- route={matched}
85
- params={params}
86
- dataKey={dataKey}
87
- epoch={epoch}
88
- />
89
- </Suspense>
90
- );
91
- // Templates wrap inside the layouts and re-mount on every navigation (keyed by URL).
92
- const templates = matched.templates ?? [];
93
- for (let i = templates.length - 1; i >= 0; i--) {
94
- const Template = nestedLayout(templates[i]);
95
- content = (
96
- <Suspense
97
- key={`${keyPrefix}${pathname}:${String(i)}`}
98
- fallback={null}>
99
- <Template>{content}</Template>
100
- </Suspense>
101
- );
102
- }
103
- // Nested layouts, deepest first so the shallowest ends up outermost.
104
- const chain = matched.layouts ?? [];
105
- for (let i = chain.length - 1; i >= 0; i--) {
106
- const NestedLayout = nestedLayout(chain[i]);
107
- content = (
108
- <Suspense fallback={null}>
109
- <NestedLayout>{content}</NestedLayout>
110
- </Suspense>
111
- );
112
- }
113
- if (matched.errorComponent) {
114
- content = (
115
- <ErrorBoundary fallback={errorComponent(matched.errorComponent)}>
116
- {content}
117
- </ErrorBoundary>
118
- );
119
- }
120
- return content;
121
- }
122
-
123
- /**
124
- * Finds the first route (already specificity-sorted) matching `pathname`. Intercepting routes are
125
- * skipped unless `allowIntercept`, they only apply on soft navigation.
126
- */
127
- function match(
128
- routes: RouteDef[],
129
- pathname: string,
130
- allowIntercept = true,
131
- ): { route: RouteDef; params: RouteParams } | null {
132
- for (const route of routes) {
133
- if (route.intercept && !allowIntercept) continue;
134
- const params = matchRoute(route.pattern, pathname);
135
- if (params) return { route, params };
136
- }
137
- return null;
138
- }
139
-
140
- /** Matches the current location to a route and renders it, optionally wrapped in the root layout. */
141
- export function Router(props: {
142
- routes: RouteDef[];
143
- layout?: LayoutLoader;
144
- notFound?: NotFoundLoader;
145
- globalError?: ErrorComponentLoader;
146
- slots?: Record<string, RouteDef[]>;
147
- }): ReactNode {
148
- const { routes, layout = null, notFound = null, globalError = null, slots = {} } = props;
149
- const pathname = useLocation();
150
-
151
- // After each navigation commits, apply the planned scroll (top / restore / #hash) and mark the
152
- // navigation settled. A layout effect runs before paint, so the scroll lands without a flash.
153
- useLayoutEffect(() => {
154
- applyScroll();
155
- settleNavigation();
156
- });
157
-
158
- const epoch = navigationEpoch();
159
- const soft = isSoftNavigation();
160
-
161
- // Parallel slots: each `@slot` tree matches the current URL independently (intercepting routes
162
- // only on soft navigation). Each match is exposed by name via SlotContext and rendered wherever a
163
- // layout/page places a `Slot`. If an intercepting route matches, the main view holds the previous
164
- // page (the backdrop) while the slot shows the intercepted route, i.e. a modal overlay.
165
- const slotElements: Record<string, ReactNode> = {};
166
- let intercepting = false;
167
- for (const [name, defs] of Object.entries(slots)) {
168
- const slotMatch = match(defs, pathname, soft);
169
- if (!slotMatch) continue;
170
- if (slotMatch.route.intercept) intercepting = true;
171
- slotElements[name] = (
172
- <ParamsContext.Provider value={slotMatch.params}>
173
- {renderMatched(slotMatch.route, slotMatch.params, pathname, epoch, `@${name} `)}
174
- </ParamsContext.Provider>
175
- );
176
- }
177
-
178
- const mainPath = intercepting ? previousPathname() : pathname;
179
- const matched = match(routes, mainPath);
180
- const params: RouteParams = matched?.params ?? {};
181
-
182
- let content: ReactNode;
183
- if (matched) {
184
- content = renderMatched(matched.route, matched.params, mainPath, epoch, '');
185
- } else if (notFound) {
186
- const NotFound = resolveNotFound(notFound);
187
- content = (
188
- <Suspense fallback={null}>
189
- <NotFound />
190
- </Suspense>
191
- );
192
- } else {
193
- content = <div style={{ padding: 24, fontFamily: 'system-ui' }}>404, Not found</div>;
194
- }
195
-
196
- if (layout) {
197
- const Layout = resolveLayout(layout);
198
- content = (
199
- <Suspense fallback={null}>
200
- <Layout>{content}</Layout>
201
- </Suspense>
202
- );
203
- }
204
-
205
- // The root error boundary (global-error.tsx) sits outside the root layout, so it catches
206
- // errors thrown by the layout itself, the last line of defense before a blank screen.
207
- if (globalError) {
208
- content = <ErrorBoundary fallback={errorComponent(globalError)}>{content}</ErrorBoundary>;
209
- }
210
-
211
- return (
212
- <ParamsContext.Provider value={params}>
213
- <SlotContext.Provider value={slotElements}>{content}</SlotContext.Provider>
214
- </ParamsContext.Provider>
215
- );
216
- }
@@ -1,122 +0,0 @@
1
- /**
2
- * Mutations (writes), the counterpart to loaders (reads). A loader fetches data on navigation;
3
- * an action performs a write (save, delete, a server/WASM call) on demand, then revalidates the
4
- * affected loader data so the UI reflects the change. `useAction` tracks pending/error/result state;
5
- * `<Form>` is sugar over it for the form case.
6
- */
7
- import { useCallback, useEffect, useRef, useState } from 'react';
8
-
9
- import { invalidateLoaderData } from './loader.js';
10
- import { refresh } from '../navigation/navigation.js';
11
- import type { Href } from '../types.js';
12
-
13
- /**
14
- * Which loader data to refetch after an action succeeds:
15
- * - `true` (default), the current route.
16
- * - an `Href` (or array), those specific routes.
17
- * - `false`, nothing.
18
- */
19
- export type RevalidateTarget = boolean | Href | readonly Href[];
20
-
21
- /** Options for {@link useAction}. */
22
- export interface UseActionOptions<TData> {
23
- /** Loader data to revalidate after success. Default `true` (the current route). */
24
- readonly revalidate?: RevalidateTarget;
25
- /** Called after a successful run, with the action's return value. */
26
- readonly onSuccess?: (data: TData) => void;
27
- /** Called when the action throws. */
28
- readonly onError?: (error: unknown) => void;
29
- }
30
-
31
- /** Live state of an action. */
32
- export interface ActionState<TData> {
33
- /** True while a run is in flight. */
34
- readonly pending: boolean;
35
- /** The error from the last failed run, or `undefined`. */
36
- readonly error: unknown;
37
- /** The value returned by the last successful run, or `undefined`. */
38
- readonly data: TData | undefined;
39
- }
40
-
41
- /** Handle returned by {@link useAction}: current state plus `run` / `reset`. */
42
- export interface ActionHandle<TInput, TData> extends ActionState<TData> {
43
- /**
44
- * Run the action. Resolves to the result on success, or `undefined` if it threw (the error is
45
- * captured in `error` instead of rejecting, so a fire-and-forget `onClick` can't leak an
46
- * unhandled rejection).
47
- */
48
- run: (input: TInput) => Promise<TData | undefined>;
49
- /** Reset back to idle (clears `pending` / `error` / `data`). */
50
- reset: () => void;
51
- }
52
-
53
- /** Refetches loader data per a {@link RevalidateTarget}, then re-renders once. */
54
- function applyRevalidate(target: RevalidateTarget | undefined): void {
55
- if (target === false) return;
56
- if (target === undefined || target === true) {
57
- invalidateLoaderData();
58
- } else {
59
- const hrefs = typeof target === 'string' ? [target] : target;
60
- for (const href of hrefs) invalidateLoaderData(href);
61
- }
62
- refresh();
63
- }
64
-
65
- /**
66
- * Runs a mutation with pending/error/result tracking, revalidating loader data on success. Example:
67
- *
68
- * ```ts
69
- * const save = useAction((title: string) => api.save(title), { revalidate: true });
70
- * <button disabled={save.pending} onClick={() => void save.run(title)}>Save</button>
71
- * ```
72
- */
73
- export function useAction<TInput = void, TData = unknown>(
74
- fn: (input: TInput) => TData | Promise<TData>,
75
- options: UseActionOptions<TData> = {},
76
- ): ActionHandle<TInput, TData> {
77
- const [state, setState] = useState<ActionState<TData>>({
78
- pending: false,
79
- error: undefined,
80
- data: undefined,
81
- });
82
-
83
- // Hold the latest fn/options so `run` keeps a stable identity across renders.
84
- const latest = useRef({ fn, options });
85
- latest.current = { fn, options };
86
- const runId = useRef(0);
87
- const mounted = useRef(true);
88
- useEffect(
89
- () => () => {
90
- mounted.current = false;
91
- },
92
- [],
93
- );
94
-
95
- const run = useCallback(async (input: TInput): Promise<TData | undefined> => {
96
- const id = ++runId.current;
97
- setState((s) => ({ ...s, pending: true, error: undefined }));
98
- try {
99
- const data = await latest.current.fn(input);
100
- // Ignore a stale run that a newer one (or unmount) has superseded.
101
- if (mounted.current && id === runId.current) {
102
- setState({ pending: false, error: undefined, data });
103
- }
104
- applyRevalidate(latest.current.options.revalidate);
105
- latest.current.options.onSuccess?.(data);
106
- return data;
107
- } catch (error) {
108
- if (mounted.current && id === runId.current) {
109
- setState({ pending: false, error, data: undefined });
110
- }
111
- latest.current.options.onError?.(error);
112
- return undefined;
113
- }
114
- }, []);
115
-
116
- const reset = useCallback(() => {
117
- runId.current += 1;
118
- setState({ pending: false, error: undefined, data: undefined });
119
- }, []);
120
-
121
- return { ...state, run, reset };
122
- }
@@ -1,43 +0,0 @@
1
- import { Component, type ComponentType, type ReactNode, Suspense } from 'react';
2
-
3
- import type { RouteErrorProps } from '../types.js';
4
-
5
- interface ErrorBoundaryProps {
6
- readonly fallback: ComponentType<RouteErrorProps>;
7
- readonly children: ReactNode;
8
- }
9
- interface ErrorBoundaryState {
10
- readonly error: Error | null;
11
- }
12
-
13
- /**
14
- * Catches render errors in its subtree and shows the route's `error.tsx` (with a `reset` to retry).
15
- * Error boundaries must be class components, React has no hook equivalent.
16
- */
17
- export class ErrorBoundary extends Component<ErrorBoundaryProps, ErrorBoundaryState> {
18
- state: ErrorBoundaryState = { error: null };
19
-
20
- static getDerivedStateFromError(error: Error): ErrorBoundaryState {
21
- return { error };
22
- }
23
-
24
- reset = (): void => {
25
- this.setState({ error: null });
26
- };
27
-
28
- render(): ReactNode {
29
- const { error } = this.state;
30
- if (error) {
31
- const Fallback = this.props.fallback;
32
- return (
33
- <Suspense fallback={null}>
34
- <Fallback
35
- error={error}
36
- reset={this.reset}
37
- />
38
- </Suspense>
39
- );
40
- }
41
- return this.props.children;
42
- }
43
- }
@@ -1,140 +0,0 @@
1
- /**
2
- * Router hooks for user route components: read the params / pathname / search params, navigate
3
- * imperatively, and grab a router handle.
4
- */
5
- import {
6
- startTransition,
7
- useContext,
8
- useEffect,
9
- useMemo,
10
- useReducer,
11
- useSyncExternalStore,
12
- } from 'react';
13
-
14
- import type { RouteParams } from './match.js';
15
- import {
16
- back,
17
- forward,
18
- isNavigationPending,
19
- navigate,
20
- type NavigateOptions,
21
- refresh,
22
- subscribeLocation,
23
- subscribePending,
24
- } from '../navigation/navigation.js';
25
- import { clearLoaderData, revalidate as revalidateData } from './loader.js';
26
- import { ParamsContext } from './params-context.js';
27
- import { prefetch } from '../navigation/prefetch.js';
28
- import type { Href } from '../types.js';
29
-
30
- /** Imperative router handle returned by {@link useRouter}. */
31
- export interface RouterInstance {
32
- /** Navigate to `href`, pushing a new history entry (or replacing with `{ replace: true }`). */
33
- push(href: Href, options?: NavigateOptions): void;
34
- /** Navigate to `href`, replacing the current history entry. */
35
- replace(href: Href): void;
36
- /** Go back one history entry. */
37
- back(): void;
38
- /** Go forward one history entry. */
39
- forward(): void;
40
- /** Re-render the current route and re-run its loader (clears all cached loader data). */
41
- refresh(): void;
42
- /**
43
- * Invalidate cached loader data and re-render so it refetches. No argument refetches the active
44
- * route; pass an `href` to target a specific route. Use after a mutation.
45
- */
46
- revalidate(href?: Href): void;
47
- /** Prefetch a route's chunk ahead of navigation. */
48
- prefetch(href: Href): void;
49
- }
50
-
51
- const ROUTER: RouterInstance = {
52
- push: (href, options) => {
53
- navigate(href, options);
54
- },
55
- replace: (href) => {
56
- navigate(href, { replace: true });
57
- },
58
- back,
59
- forward,
60
- refresh: () => {
61
- clearLoaderData();
62
- refresh();
63
- },
64
- revalidate: (href) => {
65
- revalidateData(href);
66
- },
67
- prefetch,
68
- };
69
-
70
- /** Current dynamic route params, e.g. `{ id }` inside `/blog/:id`. Pass a shape: `useParams<{ id: string }>()`. */
71
- export function useParams<T extends RouteParams = RouteParams>(): T {
72
- return useContext(ParamsContext) as T;
73
- }
74
-
75
- /** Returns the imperative `navigate(href, { replace })` function. */
76
- export function useNavigate(): typeof navigate {
77
- return navigate;
78
- }
79
-
80
- /** Returns the router handle (`push` / `replace` / `back` / `forward` / `refresh` / `prefetch`). */
81
- export function useRouter(): RouterInstance {
82
- return ROUTER;
83
- }
84
-
85
- /**
86
- * Subscribes to location changes and reads the live `window.location` on render. The re-render runs
87
- * inside `startTransition` so React keeps the current page visible while the next route's chunk and
88
- * loader resolve (committing the new tree only once it's ready), instead of committing a suspended
89
- * tree and flashing an empty page on every link click.
90
- */
91
- function useLocationSubscription(): void {
92
- const [, forceUpdate] = useReducer((n: number): number => n + 1, 0);
93
- useEffect(
94
- () =>
95
- subscribeLocation(() => {
96
- startTransition(() => {
97
- forceUpdate();
98
- });
99
- }),
100
- [],
101
- );
102
- }
103
-
104
- /** Build-only override for the SSR pathname, set by the template extractor per route via
105
- * {@link __setSsrLocation}. Lets location-dependent markup (a `NavLink`'s active class /
106
- * `aria-current`) render as the route's own URL so it matches what the client computes on
107
- * hydration, instead of the `/` default. Ignored in the browser (the live URL wins). */
108
- let ssrLocationOverride: string | null = null;
109
-
110
- /** Build-only: set the pathname the extractor is currently rendering (or `null` to clear).
111
- * No effect in the browser. Exported through `toiljs/client` for the compiler. */
112
- export function __setSsrLocation(path: string | null): void {
113
- ssrLocationOverride = path;
114
- }
115
-
116
- /** Subscribes to and returns the current `location.pathname`. SSR-safe: during a
117
- * server render there is no `window`, so it reports the extractor's override (the route
118
- * being rendered) or `/`; the client recomputes on hydration. */
119
- export function useLocation(): string {
120
- useLocationSubscription();
121
- if (typeof window === 'undefined') return ssrLocationOverride ?? '/';
122
- return window.location.pathname;
123
- }
124
-
125
- /** Alias of {@link useLocation}: the current `location.pathname`. */
126
- export function usePathname(): string {
127
- return useLocation();
128
- }
129
-
130
- /** The current query string as a `URLSearchParams`, re-read on every navigation. */
131
- export function useSearchParams(): URLSearchParams {
132
- useLocationSubscription();
133
- const search = typeof window === 'undefined' ? '' : window.location.search;
134
- return useMemo(() => new URLSearchParams(search), [search]);
135
- }
136
-
137
- /** True while a navigation is in flight (started but not yet committed), e.g. for a loading bar. */
138
- export function useNavigationPending(): boolean {
139
- return useSyncExternalStore(subscribePending, isNavigationPending, () => false);
140
- }
@@ -1,77 +0,0 @@
1
- /**
2
- * Lazy-component resolution and caching. Each page/layout/not-found loader is wrapped in
3
- * `React.lazy` exactly once and memoized, so re-renders reuse the same component (and React's
4
- * Suspense cache) instead of re-creating it. Keyed by loader identity.
5
- */
6
- import { type ComponentType, lazy, type ReactNode } from 'react';
7
-
8
- import type {
9
- LayoutComponentLoader,
10
- LayoutLoader,
11
- NotFoundLoader,
12
- RouteErrorProps,
13
- } from '../types.js';
14
-
15
- type Loader<P> = () => Promise<{ default: ComponentType<P> }>;
16
-
17
- /** Memoizes `lazy()` per loader identity in `cache`. */
18
- function memoLazy<P>(cache: Map<Loader<P>, ComponentType<P>>, loader: Loader<P>): ComponentType<P> {
19
- let component = cache.get(loader);
20
- if (!component) {
21
- component = lazy(loader);
22
- cache.set(loader, component);
23
- }
24
- return component;
25
- }
26
-
27
- const loadingCache = new Map<Loader<object>, ComponentType<object>>();
28
- /** Memoized lazy component for a route's `loading.tsx`. */
29
- export function loadingComponent(loader: Loader<object>): ComponentType<object> {
30
- return memoLazy(loadingCache, loader);
31
- }
32
-
33
- const errorCache = new Map<Loader<RouteErrorProps>, ComponentType<RouteErrorProps>>();
34
- /** Memoized lazy component for a route's `error.tsx`. */
35
- export function errorComponent(loader: Loader<RouteErrorProps>): ComponentType<RouteErrorProps> {
36
- return memoLazy(errorCache, loader);
37
- }
38
-
39
- let layoutComponent: ComponentType<{ children?: ReactNode }> | null = null;
40
- let layoutLoader: LayoutLoader = null;
41
-
42
- /** Returns the memoized lazy root-layout component, rebuilding only if the loader identity changes. */
43
- export function resolveLayout(
44
- loader: NonNullable<LayoutLoader>,
45
- ): ComponentType<{ children?: ReactNode }> {
46
- if (layoutLoader !== loader || !layoutComponent) {
47
- layoutComponent = lazy(loader);
48
- layoutLoader = loader;
49
- }
50
- return layoutComponent;
51
- }
52
-
53
- const nestedLayoutCache = new Map<LayoutComponentLoader, ComponentType<{ children?: ReactNode }>>();
54
-
55
- /** Returns the memoized lazy component for a nested layout loader, keyed by loader identity. */
56
- export function nestedLayout(
57
- loader: LayoutComponentLoader,
58
- ): ComponentType<{ children?: ReactNode }> {
59
- let component = nestedLayoutCache.get(loader);
60
- if (!component) {
61
- component = lazy(loader);
62
- nestedLayoutCache.set(loader, component);
63
- }
64
- return component;
65
- }
66
-
67
- let notFoundComponent: ComponentType | null = null;
68
- let notFoundLoader: NotFoundLoader = null;
69
-
70
- /** Returns the memoized lazy not-found component, rebuilding only if the loader identity changes. */
71
- export function resolveNotFound(loader: NonNullable<NotFoundLoader>): ComponentType {
72
- if (notFoundLoader !== loader || !notFoundComponent) {
73
- notFoundComponent = lazy(loader);
74
- notFoundLoader = loader;
75
- }
76
- return notFoundComponent;
77
- }