akanjs 3.2.0-rc.2 → 3.2.0-rc.4

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 (130) hide show
  1. package/ARCHITECTURE.md +3 -3
  2. package/CHANGELOG.md +105 -1
  3. package/client/csrTypes.ts +13 -1
  4. package/client/frameConfig.ts +4 -2
  5. package/client/route/RouteHead.ts +11 -2
  6. package/client/router.ts +8 -4
  7. package/client/rscNavigation.ts +2 -3
  8. package/client/rscRoutePatch.ts +42 -0
  9. package/common/akanGraph.ts +1 -1
  10. package/common/types.ts +5 -0
  11. package/dictionary/base.dictionary.ts +1 -0
  12. package/fetch/client/fetchClient.ts +11 -16
  13. package/fetch/client/fetchHandle.ts +11 -1
  14. package/fetch/client/inflightQueries.ts +17 -0
  15. package/fetch/index.ts +1 -0
  16. package/fetch/staleReads.ts +27 -0
  17. package/fetch/streamedRead.ts +23 -0
  18. package/package.json +1 -1
  19. package/server/akanServer.ts +1 -1
  20. package/server/artifact/builderRpc.ts +22 -7
  21. package/server/artifact/ipcTypes.ts +9 -3
  22. package/server/devtools/README.md +4 -3
  23. package/server/devtools/devtoolsRouter.ts +9 -5
  24. package/server/devtools/studio/studioRoute.ts +18 -11
  25. package/server/head.tsx +4 -19
  26. package/server/routeElementComposer.tsx +86 -3
  27. package/server/routeState.ts +5 -1
  28. package/server/routeTreeBuilder.ts +1 -0
  29. package/server/rscClient.tsx +118 -21
  30. package/server/rscClientChunks.ts +62 -0
  31. package/server/rscClientFetch.ts +6 -1
  32. package/server/rscHeadPatch.ts +17 -56
  33. package/server/rscParkedRedirect.ts +23 -0
  34. package/server/rscPatchPlanner.ts +220 -0
  35. package/server/rscPrefetchCache.ts +39 -17
  36. package/server/rscResponse.ts +78 -0
  37. package/server/rscSegmentOutlet.tsx +24 -5
  38. package/server/rscSegmentOutletReference.ts +10 -12
  39. package/server/rscWorker.tsx +109 -154
  40. package/server/rscWorkerCache.ts +56 -0
  41. package/server/rscWorkerHost.ts +6 -8
  42. package/server/ssrTypes.ts +9 -0
  43. package/server/webRouter.ts +12 -89
  44. package/store/action.ts +282 -299
  45. package/store/actionErrorKey.ts +9 -0
  46. package/store/draftFlush.ts +5 -0
  47. package/store/draftStore.ts +2 -0
  48. package/store/formDrafts.ts +115 -0
  49. package/store/modelListPatch.ts +53 -0
  50. package/store/modelWriteGuard.ts +91 -0
  51. package/store/rootStore.ts +2 -0
  52. package/store/storeInstance.ts +9 -10
  53. package/store/uploadPoll.ts +52 -0
  54. package/store/withSelector.ts +6 -4
  55. package/types/client/csrTypes.d.ts +13 -1
  56. package/types/client/route/RouteHead.d.ts +5 -1
  57. package/types/client/router.d.ts +3 -2
  58. package/types/client/rscNavigation.d.ts +2 -2
  59. package/types/client/rscRoutePatch.d.ts +22 -0
  60. package/types/common/akanGraph.d.ts +1 -1
  61. package/types/common/types.d.ts +5 -0
  62. package/types/dictionary/base.dictionary.d.ts +1 -1
  63. package/types/dictionary/dictionary.d.ts +8 -8
  64. package/types/fetch/client/fetchHandle.d.ts +1 -0
  65. package/types/fetch/client/inflightQueries.d.ts +2 -0
  66. package/types/fetch/index.d.ts +1 -0
  67. package/types/fetch/staleReads.d.ts +8 -0
  68. package/types/fetch/streamedRead.d.ts +8 -0
  69. package/types/server/artifact/builderRpc.d.ts +8 -0
  70. package/types/server/artifact/ipcTypes.d.ts +8 -0
  71. package/types/server/devtools/devtoolsRouter.d.ts +4 -1
  72. package/types/server/devtools/studio/studioRoute.d.ts +2 -1
  73. package/types/server/head.d.ts +2 -2
  74. package/types/server/logging/rotatingLogWriter.d.ts +1 -1
  75. package/types/server/routeElementComposer.d.ts +24 -1
  76. package/types/server/routeState.d.ts +2 -0
  77. package/types/server/rscClient.d.ts +1 -0
  78. package/types/server/rscClientChunks.d.ts +10 -0
  79. package/types/server/rscHeadPatch.d.ts +5 -4
  80. package/types/server/rscParkedRedirect.d.ts +12 -0
  81. package/types/server/rscPatchPlanner.d.ts +49 -0
  82. package/types/server/rscPrefetchCache.d.ts +2 -2
  83. package/types/server/rscResponse.d.ts +9 -0
  84. package/types/server/rscSegmentOutlet.d.ts +5 -0
  85. package/types/server/rscSegmentOutletReference.d.ts +2 -1
  86. package/types/server/rscWorkerCache.d.ts +33 -1
  87. package/types/server/rscWorkerHost.d.ts +2 -6
  88. package/types/server/ssrTypes.d.ts +8 -0
  89. package/types/server/webRouter.d.ts +1 -7
  90. package/types/store/action.d.ts +10 -6
  91. package/types/store/actionErrorKey.d.ts +1 -0
  92. package/types/store/baseSt.d.ts +1 -295
  93. package/types/store/draftFlush.d.ts +4 -0
  94. package/types/store/formDrafts.d.ts +21 -0
  95. package/types/store/modelListPatch.d.ts +34 -0
  96. package/types/store/modelWriteGuard.d.ts +45 -0
  97. package/types/store/rootStore.d.ts +6 -0
  98. package/types/store/uploadPoll.d.ts +16 -0
  99. package/types/store/withSelector.d.ts +1 -1
  100. package/types/ui/Link/inputModality.d.ts +5 -0
  101. package/types/ui/Link/viewportPrefetch.d.ts +4 -0
  102. package/types/ui/Load/Edit_Client.d.ts +2 -0
  103. package/types/ui/Load/Pagination.d.ts +4 -1
  104. package/types/ui/Load/Stream.d.ts +7 -1
  105. package/types/ui/Load/StreamBoundary.d.ts +20 -0
  106. package/types/ui/Load/Units.d.ts +2 -0
  107. package/types/ui/Load/View.d.ts +2 -0
  108. package/types/webkit/nativeCore.d.ts +1 -0
  109. package/types/webkit/nativePurchase.d.ts +2 -1
  110. package/types/webkit/useFrameRuntime.d.ts +1 -0
  111. package/types/webkit/useGeoLocation.d.ts +1 -1
  112. package/types/webkit/usePurchase.d.ts +1 -1
  113. package/types/webkit/useTransitionStore.d.ts +1 -0
  114. package/ui/Button.tsx +1 -0
  115. package/ui/Link/inputModality.ts +21 -0
  116. package/ui/Link/prefetchIntent.ts +7 -25
  117. package/ui/Link/viewportPrefetch.ts +30 -0
  118. package/ui/Load/Edit_Client.tsx +7 -1
  119. package/ui/Load/Pagination.tsx +10 -2
  120. package/ui/Load/Stream.tsx +24 -4
  121. package/ui/Load/StreamBoundary.tsx +70 -0
  122. package/ui/Load/Units.tsx +3 -0
  123. package/ui/Load/View.tsx +3 -0
  124. package/ui/System/Client.tsx +28 -7
  125. package/webkit/nativeCore.ts +1 -0
  126. package/webkit/nativePurchase.ts +6 -3
  127. package/webkit/useCamera.tsx +22 -21
  128. package/webkit/useGeoLocation.tsx +4 -1
  129. package/webkit/usePurchase.tsx +4 -2
  130. package/webkit/useTransitionStore.ts +13 -0
package/ARCHITECTURE.md CHANGED
@@ -66,11 +66,11 @@ A facet loads values only from facets in lower layers. A type-only import loads
66
66
  | 4 | `service` | `base`, `common`, `constant`, `dictionary`, `document` | `signal` |
67
67
  | 5 | `signal` | `base`, `common`, `constant`, `dictionary`, `document`, `fetch`, `service` | — |
68
68
  | 5 | `store` | `base`, `client`, `common`, `constant`, `fetch` | `document`, `signal` |
69
- | 6 | `server` | `base`, `client`, `common`, `constant`, `dictionary`, `document`, `fetch`, `service`, `signal`, `store` | — |
70
69
  | 6 | `webkit` | `base`, `client`, `common`, `fetch`, `signal`, `store` | `ui` |
71
- | 7 | `@akanjs/devkit` | `base`, `client`, `common`, `server` | `native` |
72
- | 7 | `test` | `base`, `common`, `constant`, `fetch`, `server`, `service` | `signal` |
70
+ | 7 | `server` | `base`, `client`, `common`, `constant`, `dictionary`, `document`, `fetch`, `service`, `signal`, `store`, `webkit` | — |
73
71
  | 7 | `ui` | `base`, `client`, `common`, `constant`, `fetch`, `store`, `webkit` | `document`, `signal` |
72
+ | 8 | `@akanjs/devkit` | `base`, `client`, `common`, `server` | `native` |
73
+ | 8 | `test` | `base`, `common`, `constant`, `fetch`, `server`, `service` | `signal` |
74
74
 
75
75
  ## Process messages
76
76
 
package/CHANGELOG.md CHANGED
@@ -32,6 +32,17 @@
32
32
  - **`pkgs/akanjs/ARCHITECTURE.md`** pairs a hand-kept walk through the processes and a request with a generated part between markers. `akan sync-architecture` regenerates that part, and a devkit test fails when it is stale, when a channel is gone, when two facets load values from each other, when a message lacks a recognised sender or handler outside a short list whose other end lies beyond the framework source, or when the hand-kept part names a class the source no longer has.
33
33
  - **`AkanIpcMessage` no longer lists `backend-ready`.** The gateway sends it to the dev host, which reads it as a `BuilderMessage`, where it stays; no gateway or child ever handled it.
34
34
 
35
+ - 4d61170: The Akan Graph follows an app's adaptor wiring further. `applyAdaptor(LlmAdaptorRole, ChatCompletionsLlm)` in an app's or lib's `option.ts` draws a `binds` edge from the role, `adaptor::LlmAdaptorRole`, to the implementation it binds, labelled with the app or lib and located at the call, so a method that calls a plugged role reaches the class that answers it. `get_graph` scoped to an app keeps that app's own bindings, and a lib's binding of a role the app does not bind itself; scoped to a lib or a module it keeps every binding of a role it reaches. A Change Map carries every binding of a role it shows, changed or not, so the binding an app runs stays in view; a binding the app removed no longer hides the lib binding it now runs; and Studio's Change Map for one app keeps only the bindings that app runs. An app service holds the fields its module's lib services plug (`...user.services`), so `this.notifier.getMemo()` in an app method links to the `Notifier` a lib's `MemoService` plugs, where it linked to the `memo` model; a service whose own builder declares the field (`notifier: use<…>()`) inherits nothing. A plug imported from a package outside the workspace, `plug(Stripe)` from `stripe-sdk`, or through a lib's re-export of it (`export { Stripe }`, `export { default as Stripe }`, or `export * from "stripe-sdk"` where the lib declares no `Stripe` itself), is `adaptor:stripe-sdk:Stripe` with the package in `detail`, where it linked to a same-name adaptor the app declares or to an unlocated `adaptor:libs/util:Stripe`. Two adaptors with the same class name in one app or lib are two nodes, each with its own location, digest and `plugs`, and a plug reaches the one its import names. A job's `detail` lists only the options its kind honours: `once` on an `initialize` job, `unlocked` on an `interval` job (`Bun.cron` never overlaps a cron job, so `lock: false` changes nothing there); `cron("0 * * * *" as const)` reads `0 * * * *`.
36
+
37
+ Ids and details that change for a saved graph or a Change Map base:
38
+
39
+ - While two adaptors of one owner share a class name, each is keyed by its file, `adaptor:apps/demo:srvkit/clockB.ts#Clock`; an adaptor whose name no other adaptor of its owner shares keeps `adaptor:<owner>:<Name>`. The Change Map treats the two forms of one declaration as one node, so a second same-name adaptor shows as one added node, not a removal of the first.
40
+ - A plug from a non-workspace package is `adaptor:<package>:<Name>` with the package as `detail`, where it was `adaptor::<Name>` or a workspace adaptor of that name.
41
+ - A job's `detail` drops `once` and `unlocked` where the runtime ignores them, and `as const` from a cron expression.
42
+
43
+ - **`binds`** joins `AkanGraphEdgeKind` in `akanjs/common`.
44
+ - **`FileFacts.adaptorBindings`** in `@akanjs/language`: each `applyAdaptor(role, adaptor)` call a file makes; `AkanIndex.setFile` also reads non-test files whose text mentions `applyAdaptor`. **`ServiceClassFact.fields`**: the names a service's builder declares.
45
+
35
46
  - c723713: The Akan Graph keys a guard function by the file that declares it, locates more of a workspace's guards, and stops counting things that are not guards.
36
47
 
37
48
  A guard function a route or layout imports is keyed by its file, as one the page declares already was: `guard:libs/shared:webkit/signedIn.ts#signedIn`. A `canEdit` in `webkit/` and one in `common/` are two nodes, each at its own declaration, and an edit to either marks only that one changed in the Change Map. A guard called through a namespace import (`auth.signedIn()`), or imported under a name a file re-exports (`export { signedIn as hasSession } from "./auth"`), reaches its declaration. A function the guard declares, or a parameter it binds, shadows an import of the same name only inside its own scope, so `[1].forEach((signedIn) => …)` no longer hides a real `signedIn()` beside it. A guard declared after another declarator (`export const ready = true, signedIn = …`) is found, and an overloaded guard's digest covers every signature. Only a file whose text declares or re-exports the name is parsed, so a guard that calls `usePage()` from the generated client no longer parses every page that names it.
@@ -153,7 +164,7 @@
153
164
 
154
165
  - 96f9ff6: A `Binary` argument reaches `exec` typed as `Uint8Array<ArrayBuffer>`, so it can go straight to a service or a `fetch` body. Before, it was a copy of `Uint8Array` with every method stripped. A `Binary` return still takes any `Uint8Array`.
155
166
  - 1ebc57a: The `Err` an app imports in client code now has `Err.is(error, ...keys)`, as the `Err` from the app's dictionary (the one services throw) already did. It was missing on the client one, so client code that checked a caught error with it failed to typecheck, or threw a `TypeError` when typed loosely. `Err.is` is true for an `Err`, or for any error carrying a string `error` key, so one restored from a failed `fetch` call passes too; naming keys accepts only those and narrows the error's type to them. Both `Err` classes now run the same check.
156
- - c3b5b3c: A web page no longer loads `@akanjs/native/core`. `isNativeApp()` and the other host checks read the platform the shell writes before the bundle runs, and a native shell still starts core with the page. On the minimal app this takes 15 KB raw (5.6 KB brotli) off the vendor floor and 20 KB raw (6.6 KB brotli) off every route entry. `akan build` also resolves the `production` export condition for the browser, SSR-client, CSR and MCP App view bundles, so a package such as Lexical ships its production build alone. On the minimal app the Agent editor chunk drops from 91 KB to 63 KB brotli. `akan start` is unchanged.
167
+ - c3b5b3c: The framework no longer puts `@akanjs/native/core` on a web page. `isNativeApp()` and the other host checks read the platform the shell writes before the bundle runs, and a native shell still starts core with the page. A file that imports `akanjs/client/native` statically still brings core to every page that reaches it. On the minimal app this takes 15 KB raw (5.6 KB brotli) off the vendor floor and 20 KB raw (6.6 KB brotli) off every route entry. `akan build` also resolves the `production` export condition for the browser, SSR-client, CSR and MCP App view bundles, so a package such as Lexical ships its production build alone. On the minimal app the Agent editor chunk drops from 91 KB to 63 KB brotli. `akan start` is unchanged.
157
168
  - 6d5b544: A database service now has `create<Model>Many(rows)`. It creates the rows on the same path as `create<Model>`: `_preCreate` and `_postCreate`, the document's save and create hooks, and the live and pubsub events each row's commit fires. Every row's `_preCreate` and document pre hooks run first, so a check there that queries the table does not see the batch's own rows. The rows are then written in one transaction, joining the caller's when one is open, with one multi-row INSERT per 500 rows instead of one statement per row; if the database refuses one row, none is written. Every row's `_postCreate` runs once the transaction commits, as `create<Model>`'s runs once its row is stored, so a `_postCreate` that throws leaves the rows written. A service that already declares a method of that name, itself or in a lib service it extends, keeps its own at runtime, but its signature no longer typechecks against the generated one: rename it.
158
169
 
159
170
  A store can list actions in `static silent = ["refreshToken"] satisfies (keyof UserStore)[]`. When a silent action fails, it shows no toast and logs at verbose instead of error. It still rejects with the original error, so a background write such as a token refresh is awaited by its caller, which handles the failure. Generated actions can be listed, and a store built on a lib store keeps the lib's silent actions. A name in `static silent` that is not an action of the store is reported when the store registers.
@@ -174,6 +185,20 @@
174
185
  `FetchPolicy.cache` and `FetchPolicy.partial` are deprecated. Nothing has read them since v2 dropped GraphQL; an endpoint reuses its answer with its own `query(T, { cache })`. `FetchPolicy.onError` is deprecated too, since nothing calls it: catch the call's rejection instead.
175
186
 
176
187
  - c334caf: A root layout's fonts now preload one face per family instead of every face. By default that is the regular face: 400 normal, or the weight a browser draws regular text with when the family has no 400 (500, then lighter, then heavier). Every other weight still has its `@font-face` rule, with `font-display: swap`, and loads when text first uses it. A path set to `preload: true` is preloaded as well, and `preload: false` still never is. The app template's home page declares nine Pretendard weights and preloaded all of them, 166 KB; it now preloads one, 18 KB, and fetches the three other weights it shows when it draws them. To keep a weight the first screen shows preloaded, set `preload: true` on its path; the akanjs.com layout now does that for 700 and 900.
188
+ - 170be15: A form field setter now costs about one copy of the state, like any other store write. `set<Field>On<Model>`, `add<Field>On<Model>`, `sub<Field>On<Model>`, `writeOn<Model>` and the file upload setters used to hand `set` an updater, which ran immer over the whole state and then compared every key. A keystroke cost 284 µs at 1,740 keys and 600 µs at 3,480. They now produce the new form alone and write it as a patch: 42 µs at 1,740 keys and 79 µs at 3,480, against 37 µs and 74 µs for a bare copy of the state.
189
+
190
+ - **`merge<Model>` marks the open model loading under its own key.** It wrote a literal `modelLoading` key, so `<model>Loading` never showed the merge in flight and the state gained a stray key. The view modal now shows its loading state during a merge.
191
+ - **A failed model action ends the loading it started.** When `create<Model>`, `create<Model>InForm`, `update<Model>`, `update<Model>InForm`, `merge<Model>` or `view<Model>` fails, `<model>Loading` goes back to `false`; when `edit<Model>` fails, `<model>FormLoading` does. That also holds when the request succeeds but the write after it throws. Before, the flag stayed set and the view or edit modal stayed under its loading overlay.
192
+ - **A loading flag is cleared only by the action that set it last.** An action that another one overtook leaves the flag alone, even when both are on the same record. Before, a merge or update landing during a `view<Model>` of the same record showed that view as loaded early.
193
+ - **A model action no longer takes over what the store's own `view<Model>`, `edit<Model>` or `new<Model>` opened during its request.** A component that writes a record or form into the store itself, as the edit modal does from a page payload, does not count as an open.
194
+ - `merge<Model>`, `update<Model>` and `update<Model>InForm` write the answer as the open model only while that record is still open.
195
+ - Creates and updates leave the modal alone.
196
+ - `update<Model>InForm` and `create<Model>InForm` leave the form to an `edit<Model>` or `new<Model>` opened meanwhile. A `view<Model>` does not take the form, so the saved form is still reset and its draft dropped.
197
+ - A `view<Model>` or `edit<Model>` overtaken by a later one no longer lands its record over the later one.
198
+ - Before, a view of another record was replaced or closed when the write landed, and an edit opened during a save lost its form.
199
+ - **A form opened under the same draft scope while `create<Model>InForm` or `update<Model>InForm` waits for the server opens without that draft**, so a second new form is not refilled with what the first is creating. The draft stays in storage until the request succeeds, so a reload during the save still restores it, and it is kept when the request fails. On success it is deleted only while it still holds the saved form, so a draft that a form opened meanwhile wrote is kept. A form holding an `undefined` value now compares equal to its stored draft, which drops that value; before, the saved form's own draft was kept and refilled the next new form. A draft discarded or reset during the save stays gone when the save fails. A draft write still pending when the save starts is written first.
200
+ - **A failed `view<Model>` or `edit<Model>` that is still the latest open closes its modal**, unless the modal already shows that record, as when a page payload seeded it. Before, the modal stayed open over the previous record.
201
+
177
202
  - e143263: The optional `happy-dom` and `@happy-dom/global-registrator` peers now ask for `^21.0.4`. Versions 17.0.0 through 21.0.3 compile a `<script type="module">` import alias into code unchecked, so a page loaded into a happy-dom window could run code on the host (GHSA-834v-8h66-3h79). UI tests register one through `akanjs/test/registerDom`; run `bun update happy-dom @happy-dom/global-registrator` in a workspace that pins an older one.
178
203
  - e4f7876: A hidden field declared `.optional()` (`field.hidden(String).optional()`) is optional again in a service's `create<Model>` and `create<Model>Many` input, and in the document type `by()` makes of an input model or a scalar. It was typed there as a required, non-null value, though the model's own document already typed it optional, so a create that left it out needed a cast. A hidden field without `.optional()` stays required. Code that read such a field off a scalar's document as always present now handles its absence, as it already did on the model's document.
179
204
  - cb0fd5b: Reading the client address from a forwarded header no longer stalls the server on a crafted hop. `IpLiteral.parse` matched a bracketed IPv6 hop with a pattern that backtracked quadratically, so an `X-Forwarded-For` or `X-Real-IP` entry of `[` and a long run of colons kept the event loop busy for about 100 ms per 16 KB of header, on every request that carried it. The bracket is now matched in linear time and the colon checked apart; every address parses as before.
@@ -254,6 +279,20 @@
254
279
  - **The CSR build and its MCP App views** rewrite `akanjs/ui` imports to the components a file names, as the SSR route builds already did, so a page that imports `Link` no longer bundles every component.
255
280
  - **Animations use `@react-spring/web`** instead of the `react-spring` umbrella package, which also installed the native, three.js, konva and zdog renderers.
256
281
 
282
+ - 513e48d: A page whose render has a side effect, such as counting a view, can now refuse every Link prefetch itself with `.config({ prefetch: false })`; on a `_layout` it covers every page below, and a page there can opt back in with `prefetch: true`. The server runs the route's guards and then answers such a prefetch with an empty 204, rendering nothing, cached or not: a guard's redirect still answers as a redirect, and a refusal as it would for the click, so a prefetch tells a visitor no more than a click about the paths behind a guard. The browser keeps that answer as nothing for the prefetch lifetime, so hovering the link again asks no more, and the click renders the page as usual.
283
+
284
+ A page prefetched before this tab's own write is no longer shown as current: a mutation, a file upload, a socket message sent or a changed credential drops every prefetched page, as it already ended in-flight query sharing. Only this tab's own writes through `fetch` count: a write from another tab or device, or a server push, leaves a prefetched page as it is for the rest of its 15-second lifetime, and a socket message drops them as it is sent, not once the server has acted on it. A write that changes nothing a page reads, such as a typing notice, passes `{ keepsReads: true }` to keep both its in-flight queries and its prefetched pages.
285
+
286
+ In production, an RSC navigation's answer no longer carries the headers that explain a render to its developer (`X-Akan-Rsc-Route`, `-Pathname`, `-Nav-Id`, `-Cache`, `-Cache-Reason`, `-Cache-Key`, `-Partial-Reason`, `-Partial-Common-Prefix`, and `X-Akan-Rsc-Partial` other than a patch's): a missing path carried them where one a guard refused did not, telling a visitor which paths exist behind the guard. `akan start` still sends them.
287
+
288
+ Link prefetch fixes:
289
+
290
+ - A link's focus prefetches it after a key press, and until the first pointer press on the page, so focus moved by a screen reader's cursor, switch access or voice control still does; the focus a mouse press, a tap or a pen tap gives a link does not, until the next key press.
291
+ - A late redirect from the page on screen, raised while another navigation loads, now runs once that navigation ends keeping the page (a bare 404 refusal, a refresh that finds no page, or a shallow update or a Back between the page's shallow entries that cancels it) instead of being dropped; a navigation that replaces the page still drops it.
292
+ - A page the navigation cache holds under another `#fragment` is neither prefetched again nor fetched on the click: the fragment never reaches the server, so the cached payload serves it.
293
+ - When more `prefetch="viewport"` links come into view than the queue holds, the first to show are kept, as a page lists its links top down, instead of the last. A link stays watched: one still queued is withdrawn as it leaves the view, and asks again when it comes back.
294
+ - `router.prefetch(href)` returns a call that withdraws the request while it still waits.
295
+
257
296
  - 5cd1fc3: Disposing a pubsub subscription or a message listener now removes that subscription's own listener. When one handler function served two subscriptions, such as two rooms or a re-subscribe before the previous cleanup ran, disposing the first one removed nothing: the first room stayed subscribed on the server and kept calling the handler after unmount. Each dispose now removes exactly one listener, and a room is unsubscribed on the socket once its last listener leaves.
258
297
  - f47cc82: A server now answers `/_akan/app/ready`, a readiness route that returns 503 while it cannot serve and 200 once it can. A gateway is ready while at least one replica that takes traffic is ready, and a gateway that runs only batch replicas once one of them is; it turns unready again when the last one exits or stops answering. A solo server, the desktop server included, is ready once it runs and its RSC worker can render, so it answers 503 while the pages bundle loads at boot and while the worker restarts; a server with no pages waits for nothing else. The route follows the access rules of `/_akan/app/health`: a caller without `AKAN_STATUS_TOKEN` or `AKAN_LOG_STREAM_TOKEN` gets `{ "status": "ready" }` or `{ "status": "unavailable" }` alone, and the token holder also gets each replica's state. `/_akan/app/health` is unchanged and stays the liveness check, answering 200 while the process is up.
259
298
 
@@ -271,6 +310,27 @@
271
310
  - **A boundary that resolves after the shell** still loads its chunks when its flight rows arrive. `akan start` preloads nothing new, because a dev page loads its client code from the SSR dev registry.
272
311
  - `routes-manifest.json` carries the preload table as `modulePreloads`: the runtime chunks, each vendor's chunks, and the vendors each browser chunk imports.
273
312
 
313
+ - 9055634: Partial RSC commit can now patch a real page, and it patches cleanly. It is still off by default behind `AKAN_PUBLIC_RSC_PARTIAL_COMMIT=1`. With the flag on:
314
+
315
+ - **Which pages render their head through `AkanRouteHead`.** Every page whose head is plain `title`, `meta` and `link` tags now renders it through a client component instead of plain head tags. That way any page can be the one a patch starts from. Patches still only land on pages that set `.config({ rscPatchHeadSafe: true })`.
316
+ - **A plain `.head()` is its own head snapshot.** A page no longer needs a hand-written snapshot. A head with anything else, such as a script or a component, keeps the full render.
317
+ - **React renders the head.** The old patch swapped `<head>` nodes behind React's back. That left a stale or broken head after the next full navigation or a back navigation.
318
+ - **A patch carries only the page's part of the head.** The layouts' part stays on the client, under the layouts the patch keeps. The page's part travels in the `X-Akan-Rsc-Patch-Head-Snapshot` header, which is now capped at 2 KB encoded, down from 12 KB. A larger page head renders whole, and the server logs that once per route.
319
+ - The cap leaves room under nginx's default 4 KB `proxy_buffer_size`, but it doesn't guarantee a fit: router state, trace headers and `Set-Cookie` share that buffer.
320
+ - The docs pages' part is about 1.1 KB, against about 5.7 KB for their whole head.
321
+ - **The layouts a patch keeps follow the new page.** `usePathCtx()` under an SSR page gives the patched page's path, pathname and query, so a menu's active item and a pager move with it.
322
+ - **A full commit after a patch goes straight to the new page's head, path and body.** It no longer shows the last full page for a frame first.
323
+ - **A patch falls back to a full render when the kept layouts would be wrong:**
324
+ - another route group's layout sits at the same URL prefix (`(guest)/account/login` to `(member)/account/settings`);
325
+ - the layouts' head would be different for the target, for example a layout `.head()` that reads a search arg. The router state carries a key of the layouts head its page rendered (`headKey`), and the server compares it with the target's. The key changes together with the rest of the router state, so a navigation started while the previous page is still committing sends that page's key;
326
+ - a route param differs (`/en` to `/ko`);
327
+ - a frame setting differs, such as `transition`;
328
+ - the page navigated from has no patchable head;
329
+ - its frame cannot be resolved.
330
+ - **A client built without the flag no longer asks for patches it cannot apply.** Before, a server running with the flag answered such a client with patches, and every sibling navigation made a second request. Such a client leaves the head key out of the router state it sends.
331
+ - **A refused head-safe patch runs each `.head()` once.** When a patch is refused after its head resolved, the full render reuses that head. Before, it ran every `.head()` a second time.
332
+ - **`@akanjs/devkit`: the SSR runtime manifest keeps every client export of the segment outlet module.** Before, it kept only one.
333
+
274
334
  - 3537448: A navigation that a newer one overtakes before its page commits now cuts its `/__rsc` request once the response headers are in, so the server stops streaming it and the browser stops reading it. Before, it ran to the end and was only kept from committing. The cut waits for the headers because a session refresh may answer with a rotated single-use refresh token in `Set-Cookie`, and a request aborted before it lands leaves the browser holding the spent token. A refresh, a shallow push and a move back or forward overtake it the same way. A page that has already committed is never cut, so the Suspense content it still streams keeps arriving while the next navigation loads.
275
335
  - 6c3a303: A page that renders a string of 1024 characters or more, such as a post body or a long comment, now renders and hydrates whatever its lines say. React sends such a string, and every typed array or `ArrayBuffer`, as a length-prefixed Flight row whose raw bytes may hold newlines. The SSR sanitizer, the client navigation redirect guard and the partial-navigation patch check all split the stream on every newline, so they read lines inside the text as rows of their own. A line shaped like a debug row was dropped and a line shaped like a redirect row was rewritten, which broke the render. On a client navigation the guard could act on such a line as a redirect, and a partial navigation fell back to a full one.
276
336
 
@@ -412,6 +472,14 @@
412
472
  - It first awaits `onCredentialExpired`, set through `configure`, for up to `WsClient.renewTimeoutMs` (10 s). Renew the session cookie there, or call `setJwt`.
413
473
  - The new handshake then carries the current credential, and every room is resubscribed under it.
414
474
 
475
+ - db5b284: An app using the `shared` and `util` libraries no longer loads `@akanjs/native/core` on its web pages. Their stores imported `akanjs/client/native` for `isNativeShell()` and for the push installation id. That put core and every native plugin wrapper on every page. Native SSO and `usePushNotification` now load the plugin they call on first use inside a shell. The `useCamera`, `useGeoLocation` and `usePurchase` hooks in `akanjs/webkit`, which `shared`'s `Field` and `User.Template` reach, import their plugin and the few core exports they use dynamically, when first called; inside a shell `useCamera` still reads the camera permission at mount. On the minimal app with `shared` merged into its store:
476
+
477
+ - a Link route drops from 148.7 KB raw (38.5 KB brotli) to 101.5 KB raw (23.3 KB brotli);
478
+ - a route drawing `Field` drops from 416.6 KB (113.8 KB brotli) to 370.2 KB (99.8 KB brotli);
479
+ - a route drawing `User.Template` drops from 526.8 KB (140.2 KB brotli) to 481.2 KB (126.3 KB brotli).
480
+
481
+ The runtime guideline and the `no-web-only-api-outside-webkit` message now name `akanjs/client` for `isNativeApp()`, and the native subpaths for push and haptics.
482
+
415
483
  - 5e08722: A coding agent now finds the imports and signatures a first app needs in its skills, instead of reading the akanjs sources.
416
484
 
417
485
  - **The `akan-service` and `akan-page` recipes** start each file with its import lines, and the `akan-service` rules say what `serverMode: "batch"` does: the module, endpoints included, mounts only in a `batch` or `all` process, so a page-facing service leaves it off.
@@ -429,6 +497,7 @@
429
497
  - **`ssr: "block"` writes every boundary in place,** so a blocking page never shows its `.loading()` fallback.
430
498
  - **Fragments land on their target.** A document opened at a fragment scrolls to the target when React reveals it, if the target was not on the page yet and the visitor has not scrolled; a reload or a back/forward visit keeps the offset the browser restored. A client navigation to another page's fragment lands on the target instead of the top.
431
499
 
500
+ - 76705dd: `StoreRegistry.build` now reads a root store's state, actions and slices from the merged type rather than inferring them back out of it. That inference grew quadratically with the number of stores. In an app merging about 70 stores, `build` took most of the typecheck, and adding a few more stores failed it with TS2589 ("Type instantiation is excessively deep"). With this change the typecheck cost grows linearly with the store count, and the `st` type is unchanged.
432
501
  - 206bb69: A store write now costs about one copy of the state, whatever else the root holds. Before, every `set` copied the state twice, compared every key, re-read every `search()` value, and walked every persisted key and every model form. That came to 173 µs at 1,740 keys and 364 µs at 3,480. Now `set` works out the changed keys from the patch and copies the state once. It then recomputes only the `search()` values (when `searchParams` changed) and the `computed()` values whose dependencies changed, and syncs only the persisted keys and form drafts the write touched. That is 38 µs at 1,740 keys and 78 µs at 3,480, the cost of the copy itself.
433
502
 
434
503
  - **One `set` per model write.** `update<Model>`, `update<Model>InForm`, `merge<Model>`, `set<Model>`, `remove<Model>`, `create<Model>` and `create<Model>InForm` now write the model, every slice list that holds the row, and the stale stamps in one `set`. Before, they called `set` once per slice, plus once more. An update at 1,640 keys went from 488 µs to 47 µs.
@@ -436,12 +505,47 @@
436
505
  - **A write leaves untouched `search()` values as they were.** An array `search()` value used to be parsed again on every write, as a new array, so a component reading it rendered again on writes it did not read.
437
506
  - **`set` with a `search()` or `computed()` key** now throws before it writes anything. Before, the state was already replaced when it threw.
438
507
 
508
+ - 170be15: A store's generated writes and loads that take `onError` (`create<Model>InForm`, `update<Model>InForm`, `create<Model>`, `update<Model>`, `merge<Model>`, `remove<Model>`, `submit<Model>`, `edit<Model>`, `view<Model>`) now call it with the failed request's dictionary key before they reject, as a `Button`'s `onError` takes it. Before, they handed it to the fetch call, which never called it, and `merge<Model>` took no `onError` at all. The rejection and its error toast are unchanged. An abort calls nothing, and neither does a failure in the store's own write after the server took the request, since the request did not fail.
509
+
510
+ - **A `Button` keeps the error its `onError` reported.** When the `onClick` promise then rejected, the button went back to idle and dropped the error line under it, so an edit modal's submit or a remove showed only the toast. Now the error line stays until the next click.
511
+
512
+ - cfe50cb: A `Load.Stream` whose promise rejects now renders a short notice ("This could not be loaded.") with a "Try again" button in its own place, and the rest of the page stays. Before, a rejection that reached the browser after the page had started streaming was rethrown outside any error boundary, so React unmounted the whole page (production error #441, a blank screen). `Load.Units`, `Load.View`, `Load.Edit` and `Load.Pagination` stream through it, so a list whose `init` the server refuses, such as a role-guarded slice or an expired session, keeps its page around it.
513
+
514
+ - "Try again" calls `router.refresh()`. A new promise after a failure clears the notice, so a refresh that loads renders the value.
515
+ - Outside production the notice also shows the error's message.
516
+ - `Load.Stream`, `Load.Units`, `Load.View`, `Load.Edit` and `Load.Pagination` take `error`: a node to render instead of the notice, or, where they render on the client, `(error, retry) => ReactNode`. `Load.Pagination` renders nothing by default, since the list sharing its `init` shows the notice.
517
+ - A not-found or redirect raised below the route after the page started streaming renders nothing in its place, as the host answers it.
518
+ - **Propagation change:** a rejection now stops at its `Load.*`. An error boundary an app put above one no longer sees it; pass `error` to replace the notice.
519
+ - A field of a fetch handle that a page hands to a `Load.*` unawaited (`const { memoInitInPublic } = fetch.initMemoInPublic()`) no longer turns the page into the nearest layout's `.error()` or the 500 page when it is refused before the first byte has left. The page answers 200 and the browser draws the notice in that section. Such a render is never stored in the RSC or HTML result cache, so the next visitor and "Try again" render it anew.
520
+ - A page or layout body that awaits the field, or a layout's `.notFound()` view that does, still gets its `.error()`. So does an awaited handle (`await fetch.initMemoInPublic()`) and any promise that is not a handle's field.
521
+ - **Limit:** the server cannot see where a field ends up, so a refused field is excused wherever it goes. One that reaches no `Load.*` used to take `.error()` or the 500 page when it was refused before the first byte. Now the page answers 200 and the browser blanks it (#441), as it already did when the refusal came later. That covers a server component below the page awaiting the field, the field rendered as a child, and a client component `use()`-ing it outside `Load.*`. Hand a field only to a `Load.*`, directly or through a Zone, or await the handle.
522
+
523
+ - 94d3673: Akan Studio lands on the Runtime view when `akan start`'s builder is stopped, not only when there is none or it never answers.
524
+
525
+ - **The dev host marks a reply no builder answered.** A builder request the dev host answers itself carries `kind: "unavailable"`: the builder is stopped, not started yet, failed to start, or exited or was stopped before answering. A failure the builder reports, such as a broken build, carries no kind and reads as before.
526
+ - **`BuilderRpc.isUnavailable(error)`** tells such a failure apart, as `BuilderRpc.isTimeout` does for a request that times out. A bare, empty or unknown `/_akan/studio` view then lands on Runtime, and a view asked for by name still answers 503 with the reason.
527
+ - **Mixed versions keep working.** A server reading a reply from an older dev host, with no kind, answers 503 as before, and an older server ignores the new field.
528
+
529
+ - e4c7e5c: Akan Studio lands on the Runtime view in two more cases where no dev builder can draw the others, and says the right thing when web is off.
530
+
531
+ - **An empty or unknown `view`** (`/_akan/studio?view=`, `?view=bogus`) lands on Runtime when the server has no dev builder, as a bare `/_akan/studio` already did. It used to answer the ERD's 503.
532
+ - **A builder that never answers.** When the builder RPC times out, a bare `/_akan/studio` lands on Runtime instead of answering 503. A view asked for by name still answers 503 inside Studio's nav with the timeout, and a failed build still shows its error without landing.
533
+ - **Web off.** On a server that serves the API only (`AKAN_SSR=false` or `setWeb(false)`), a builder view says the builder is reached only with the web surface on, instead of telling you to open it under `akan start`, which does not change that.
534
+
439
535
  - 6291fec: Akan Studio opens without a dev builder, and names every job in full.
440
536
 
441
537
  - **`/_akan/studio` with no dev builder** lands on the Runtime view, which reads the running server, instead of answering 503 with nothing to click. A view that needs the builder (ERD, Signals, Changes, Framework) still answers 503, now inside Studio's header and nav, saying to open it under `akan start` and that Runtime needs no builder. A failed build shows its error the same way.
442
538
  - **Each job row** carries its full name and schedule as a tooltip (`cron syncAccountBalances · 0 * * * *`), with the skip reason below it for a job this server does not run, so two long names clipped alike can be told apart.
443
539
 
444
540
  - 0c480c6: The signal-test harness clears the env cache once it has set the test port, so a fetch client built after setup reaches the test server even when a module read `getEnv()` before the harness ran.
541
+ - e4c3009: In the `util` library that `akan install-library` copies, `security` and `security.jwtSecret` are now optional in `ModulesOptions`. A fresh clone of an app on `util` typechecks and builds with the empty env files `akan sync` writes. Before, `akan typecheck`, `akan build` and `akan verify` failed with TS2322 (`Property 'security' is missing`) until someone wrote real env files. The runtime already worked without both keys: a local server derives the JWT secret, and outside `local` the server still refuses to boot with `util.error.jwtSecretRequired` unless `JWT_SECRET` or `security.jwtSecret` is set.
542
+ - 0d7294c: Narrowed vendor entries hold up during a rolling deploy and on very large builds.
543
+
544
+ - **A route chunk that fails to load during a rolling deploy now loads its page as a document.** A document from the new build can get a page from a replica the deploy has not reached yet, and that page's chunks can import a name the document's narrowed vendor entries lack. Before, the page broke, and React's Flight client kept the failed load, so retrying in the tab failed the same way. Now, if a navigation to another page has not committed, the tab loads its target as a document, which brings a matching import map. If the page is already on screen (a refresh of it counts), the tab reloads it at its current address, fragment and any later query-only change included, and only when the error is a module link or resolve error and the browser is online. A network, ad-blocker or evaluation error leaves the page in place. Only chunks that the latest page navigation's response imports count. The document's own chunks, an overtaken navigation's and a replaced response's do not trigger it. The exception is a refresh of the same page that imports a chunk the document is still loading, which takes that chunk over. Each chunk starts at most one document load per tab, so a chunk that always fails shows its error instead of reloading in a loop. While one document load is under way, another failure does not start a second; the page's next navigation, or its return from the back-forward cache, ends that wait. This applies to `akan build` output only.
545
+ - **A document fallback to the address the tab already shows now reloads it.** A failed refresh, or a back or forward move to a URL with a `#fragment`, fell back with `location.replace` to that same URL, which only scrolls to the fragment and loads nothing. It now calls `location.reload()`.
546
+ - **`akan build` fails when the vendor scan cannot find a route's client entry**, and names the entry. Before, a build that wrote its route bundles somewhere the scan did not look narrowed every vendor entry to nothing. The build passed, and pages threw in the browser.
547
+ - **The vendor scan no longer overflows the stack on large minified chunks.** A function body of about 20,000 statements, which a minifier folds into one comma chain, used to fail `akan build` with `Maximum call stack size exceeded`.
548
+
445
549
  - d9eaacc: A socket that is down keeps at most 100 messages emitted meanwhile, dropping the oldest, and says how many it dropped when it reconnects. Before, the outbox grew without end, so a stream of emits (a cursor, a typing signal) on a tab offline for minutes held every one of them and sent them all at once on reconnect. `configureWs({ outboxLimit })` sets the cap: `0` keeps none and says so once rather than on every reconnect, and a negative limit or `Infinity` keeps every one. Room subscriptions never queue there and are sent again on every open, as before.
446
550
 
447
551
  ## 3.1.1
@@ -38,8 +38,15 @@ export interface PageConfig {
38
38
  cache?: boolean;
39
39
  /** Initial full-document SSR strategy. Defaults to `"stream"`. */
40
40
  ssr?: SsrRenderMode;
41
- /** Opt-in suffix-only RSC commits, for a page needing no head update under a layout head its siblings share. */
41
+ /**
42
+ * Opt-in suffix-only RSC commits under `AKAN_PUBLIC_RSC_PARTIAL_COMMIT=1`: the page's `.head()` is plain `title`,
43
+ * `meta` and `link` tags, and the layouts above it render the same for each sibling page, apart from what they
44
+ * read through `usePathCtx()`.
45
+ */
42
46
  rscPatchHeadSafe?: boolean;
47
+ /** `false` answers a `Link` prefetch of the page (on a layout, of every page under it) without rendering it, for a
48
+ * render with a side effect such as counting a view; the click renders it as usual. */
49
+ prefetch?: boolean;
43
50
  topSafeAreaColor?: string;
44
51
  bottomSafeAreaColor?: string;
45
52
  /** Keeps the route (on a `_layout`, its whole directory) out of `akan build` while `akan start` serves it. Write a
@@ -399,6 +406,11 @@ export interface PathRoute {
399
406
  renderRootLayouts: RouteRender[];
400
407
  renderLayouts: RouteRender[];
401
408
  resolveHead?: ResolveHead;
409
+ /**
410
+ * The layouts' part of `resolveHead`, which a partial commit keeps on screen while it swaps the page's part;
411
+ * `resolveHead` must equal this merged with the page's own head by `RouteHead.mergePage`.
412
+ */
413
+ resolveLayoutsHead?: ResolveHead;
402
414
  }
403
415
 
404
416
  export type FrameSlotScope = "page" | "layout";
@@ -42,6 +42,7 @@ const pageConfigKeys = new Set<keyof PageConfig>([
42
42
  "cache",
43
43
  "ssr",
44
44
  "rscPatchHeadSafe",
45
+ "prefetch",
45
46
  "topSafeAreaColor",
46
47
  "bottomSafeAreaColor",
47
48
  ]);
@@ -61,8 +62,9 @@ export const validatePageConfig = (routeKey: string, config?: PageConfig) => {
61
62
  throw new Error(`[route-convention] unsupported pageConfig option "${key}" in ${routeKey}`);
62
63
  }
63
64
  }
64
- if (pageConfig.devOnly !== undefined && typeof pageConfig.devOnly !== "boolean") {
65
- throw new Error(`[route-convention] pageConfig.devOnly in ${routeKey} must be a boolean.`);
65
+ for (const key of ["devOnly", "prefetch"] as const) {
66
+ if (pageConfig[key] !== undefined && typeof pageConfig[key] !== "boolean")
67
+ throw new Error(`[route-convention] pageConfig.${key} in ${routeKey} must be a boolean.`);
66
68
  }
67
69
  if (pageConfig.transition !== undefined && !transitionTypes.includes(pageConfig.transition)) {
68
70
  throw new Error(`[route-convention] unsupported pageConfig.transition "${pageConfig.transition}" in ${routeKey}`);
@@ -29,7 +29,7 @@ export class RouteHead {
29
29
  if (!nodes) return node;
30
30
  snapshotLevels.push(nodes);
31
31
  }
32
- return { node, headSnapshot: RouteHead.#mergeSnapshots(snapshotLevels) } satisfies ResolvedHead;
32
+ return { node, headSnapshot: RouteHead.mergeSnapshots(snapshotLevels) } satisfies ResolvedHead;
33
33
  }
34
34
 
35
35
  /** `merge` of a page's head over its layouts': a canonical or `og:url` comes from the page or not at all. */
@@ -37,6 +37,14 @@ export class RouteHead {
37
37
  return RouteHead.merge([RouteHead.#withoutPageIdentity(layouts), page]);
38
38
  }
39
39
 
40
+ /** `head` as the title, meta and link data a navigation swaps in, or `undefined` if any tag it holds has no such form. */
41
+ static snapshotOf(head: ResolveHeadResult): AkanHeadSnapshotV1 | undefined {
42
+ const snapshot = RouteHead.#snapshotOf(head);
43
+ if (snapshot) return snapshot;
44
+ const nodes = RouteHead.#snapshotNodesOf(RouteHead.#nodeOf(head));
45
+ return nodes ? { version: 1, nodes } : undefined;
46
+ }
47
+
40
48
  /** The tags at the top of `node` that a head merges by identity, apart from the rest, which is `node` if none. */
41
49
  static split(node: ReactNode): { tags: ReactNode[]; rest: ReactNode } {
42
50
  const children = RouteHead.#flatten(node);
@@ -123,7 +131,8 @@ export class RouteHead {
123
131
  return { node: keptNode, headSnapshot: { ...snapshot, nodes } };
124
132
  }
125
133
 
126
- static #mergeSnapshots(levels: AkanHeadSnapshotNode[][]): AkanHeadSnapshotV1 {
134
+ /** `merge` for snapshot nodes, root first. */
135
+ static mergeSnapshots(levels: AkanHeadSnapshotNode[][]): AkanHeadSnapshotV1 {
127
136
  const kept = RouteHead.#keepDeepest(levels, (node: AkanHeadSnapshotNode) =>
128
137
  RouteHead.keyOf(node.tag, node.attrs ?? {}),
129
138
  );
package/client/router.ts CHANGED
@@ -44,7 +44,8 @@ export interface RouterInstance {
44
44
  refresh: () => void;
45
45
  /** Whether `back` has a page to return to; left out, the router reads the index stamped on the history entry. */
46
46
  canGoBack?: () => boolean;
47
- prefetch?: (href: string, priority?: PrefetchPriority) => void;
47
+
48
+ prefetch?: (href: string, priority?: PrefetchPriority) => (() => void) | void;
48
49
  }
49
50
  interface RouterOptions {
50
51
  prefix?: string;
@@ -547,9 +548,12 @@ class Router {
547
548
  return undefined as never;
548
549
  }
549
550
 
550
- prefetch(href: string, { priority }: { priority?: PrefetchPriority } = {}) {
551
- if (process.env.NODE_ENV !== "production" || !this.isInitialized || this.#leavesOrigin(href)) return;
552
- this.#instance.prefetch?.(href, priority);
551
+ /** Returns the call that withdraws the request while it still waits behind others. */
552
+ prefetch(href: string, { priority }: { priority?: PrefetchPriority } = {}): () => void {
553
+ if (process.env.NODE_ENV !== "production" || !this.isInitialized || this.#leavesOrigin(href))
554
+ return () => undefined;
555
+ const withdraw = this.#instance.prefetch?.(href, priority);
556
+ return typeof withdraw === "function" ? withdraw : () => undefined;
553
557
  }
554
558
  #move(kind: "push" | "replace", href: string, routeOptions?: RouteOptions) {
555
559
  this.#navigations += 1;
@@ -5,7 +5,7 @@ declare global {
5
5
  var __AKAN_RSC_CLEAR_CACHE__: (() => void) | undefined;
6
6
  var __AKAN_RSC_IS_FROM_CACHE__: (() => boolean) | undefined;
7
7
  var __AKAN_RSC_REFRESH__: ((options?: { buildId?: number }) => Promise<void>) | undefined;
8
- var __AKAN_RSC_PREFETCH__: ((href: string, priority?: PrefetchPriority) => void) | undefined;
8
+ var __AKAN_RSC_PREFETCH__: ((href: string, priority?: PrefetchPriority) => () => void) | undefined;
9
9
  var __AKAN_RSC_NAVIGATE__:
10
10
  | ((
11
11
  href: string,
@@ -31,9 +31,8 @@ export const navigateRsc = (
31
31
  return globalThis.__AKAN_RSC_NAVIGATE__?.(href, options);
32
32
  };
33
33
 
34
- export const prefetchRsc = (href: string, priority?: PrefetchPriority) => {
34
+ export const prefetchRsc = (href: string, priority?: PrefetchPriority) =>
35
35
  globalThis.__AKAN_RSC_PREFETCH__?.(href, priority);
36
- };
37
36
 
38
37
  export const refreshRsc = () => {
39
38
  return globalThis.__AKAN_RSC_REFRESH__?.();
@@ -0,0 +1,42 @@
1
+ import type { AkanHeadSnapshotV1 } from "./csrTypes";
2
+
3
+ /** What a partial commit put on screen under the layouts the last full commit rendered, until the next full one. */
4
+ export interface RscRoutePatch {
5
+ href: string;
6
+ /** The page's part of the head; the layouts' part is the one the last full commit rendered. */
7
+ head: AkanHeadSnapshotV1;
8
+ }
9
+
10
+ interface RscRoutePatchStore {
11
+ current: RscRoutePatch | null;
12
+ listeners: Set<() => void>;
13
+ heads: Set<() => void>;
14
+ }
15
+
16
+ declare global {
17
+ var __AKAN_RSC_ROUTE_PATCH__: RscRoutePatchStore | undefined;
18
+ }
19
+
20
+ const routePatchStore = () => {
21
+ globalThis.__AKAN_RSC_ROUTE_PATCH__ ??= { current: null, listeners: new Set(), heads: new Set() };
22
+ return globalThis.__AKAN_RSC_ROUTE_PATCH__;
23
+ };
24
+
25
+ export const readRscRoutePatch = () => routePatchStore().current;
26
+
27
+ export const writeRscRoutePatch = (patch: RscRoutePatch | null) => {
28
+ const store = routePatchStore();
29
+ if (store.current === patch) return;
30
+ store.current = patch;
31
+ for (const listener of [...store.listeners, ...store.heads]) listener();
32
+ };
33
+
34
+ export const subscribeRscRoutePatch = (listener: () => void, { head = false }: { head?: boolean } = {}) => {
35
+ const listeners = head ? routePatchStore().heads : routePatchStore().listeners;
36
+ listeners.add(listener);
37
+ return () => {
38
+ listeners.delete(listener);
39
+ };
40
+ };
41
+
42
+ export const hasRscRouteHead = () => routePatchStore().heads.size > 0;
@@ -14,7 +14,7 @@ export type AkanGraphNodeKind =
14
14
  | "internal"
15
15
  | "adaptor";
16
16
 
17
- export type AkanGraphEdgeKind = "field" | "guard" | "calls" | "fetches" | "uses" | "wraps" | "plugs";
17
+ export type AkanGraphEdgeKind = "field" | "guard" | "calls" | "fetches" | "uses" | "wraps" | "plugs" | "binds";
18
18
 
19
19
  export type AkanGraphChange = "added" | "removed" | "changed";
20
20
 
package/common/types.ts CHANGED
@@ -38,6 +38,11 @@ export interface FetchPolicy<_Returns = unknown> {
38
38
  * it, so only a write that is harmless to repeat and safe for anyone to trigger may pass it.
39
39
  */
40
40
  duringRender?: boolean;
41
+ /**
42
+ * Marks a write that changes nothing a query reads back, such as a typing notice: queries already in flight and the
43
+ * pages a link prefetched survive it, where any other write sends them again.
44
+ */
45
+ keepsReads?: boolean;
41
46
  }
42
47
 
43
48
  export type SnakeCase<S extends string> = S extends `${infer T}_${infer U}` ? `${Lowercase<T>}_${SnakeCase<U>}` : S;
@@ -109,6 +109,7 @@ export const baseDictionary = serviceDictionary(["en", "ko"])
109
109
  retry: ["Try again", "다시 시도"],
110
110
  copy: ["Copy", "복사"],
111
111
  pageLoadFailed: ["This page could not be loaded.", "이 화면을 불러오지 못했습니다."],
112
+ loadFailed: ["This could not be loaded.", "불러오지 못했습니다."],
112
113
  pageNotFound: ["This page does not exist.", "없는 화면입니다."],
113
114
  goBack: ["Go back", "돌아가기"],
114
115
  unauthorized: ["Unauthorized", "권한 없음"],
@@ -385,7 +385,8 @@ export class FetchClient {
385
385
  Object.entries(this.handler).forEach(([key, handler]) => {
386
386
  if (!(key in instance.handler)) instance.handler[key] = handler;
387
387
  });
388
- instance.setJwt(jwt ?? (FetchClient.#sameOrigin(instance.origin, this.origin) ? this.jwt : null));
388
+ instance.jwt = jwt ?? (FetchClient.#sameOrigin(instance.origin, this.origin) ? this.jwt : null);
389
+ instance.ws.setJwt(instance.jwt);
389
390
  if (connect) instance.connect();
390
391
  return FetchClient.#makeProxy(instance);
391
392
  }
@@ -396,9 +397,11 @@ export class FetchClient {
396
397
  for (const ws of this.#originWs.values()) ws.configure(options);
397
398
  }
398
399
  setJwt(jwt: string | null) {
400
+ const changed = jwt !== this.jwt;
399
401
  this.jwt = jwt;
400
402
  this.ws.setJwt(jwt);
401
- this.#inflight.detach();
403
+ if (changed) this.#inflight.forget();
404
+ else this.#inflight.detach();
402
405
  }
403
406
 
404
407
  #resolveWs(origin?: string) {
@@ -520,9 +523,10 @@ export class FetchClient {
520
523
  };
521
524
 
522
525
  return (...argData: unknown[]) => {
526
+ const option = argData[argLength] as FetchPolicy | undefined;
523
527
  this.#refuseInApp(key);
524
- this.#refuseInRender(key, argData[argLength] as FetchPolicy | undefined);
525
- return this.#writing(() => send(...argData));
528
+ this.#refuseInRender(key, option);
529
+ return this.#inflight.writing(() => send(...argData), option?.keepsReads);
526
530
  };
527
531
  }
528
532
  default:
@@ -540,15 +544,6 @@ export class FetchClient {
540
544
  const inflightKey = `${cacheKey}\n${JSON.stringify([timeout ?? null, retry ?? null])}`;
541
545
  return { value: this.#inflight.claim(inflightKey, requestQuery, signal), owned: true };
542
546
  }
543
-
544
- async #writing<T>(write: () => Promise<T>) {
545
- this.#inflight.detach();
546
- try {
547
- return await write();
548
- } finally {
549
- this.#inflight.detach();
550
- }
551
- }
552
547
  #untilAborted<T>(promise: Promise<T>, signal?: AbortSignal) {
553
548
  return AbortSignals.race(promise, signal).catch((error: unknown) => {
554
549
  throw signal?.aborted ? this.http.abortError(signal) : error;
@@ -605,7 +600,7 @@ export class FetchClient {
605
600
  if (FetchClient.bridged) return;
606
601
  const args = argData.slice(0, msgArgLength);
607
602
  const data = msgArgs.map((arg, idx) => serializerMap.get(arg.name)?.(args[idx]) ?? null);
608
- this.#inflight.detach();
603
+ if (!fetchPolicy?.keepsReads) this.#inflight.forget();
609
604
  this.#resolveWs(fetchPolicy?.origin).emit(key, data);
610
605
  };
611
606
  });
@@ -863,7 +858,7 @@ export class FetchClient {
863
858
  return ((fileList: FileList | File[], parentId?: string, option?: FetchPolicy) => {
864
859
  this.#refuseInApp(names.addModelFiles);
865
860
  this.#refuseInRender(names.addModelFiles, option);
866
- return this.#writing(() => upload(fileList, parentId, option));
861
+ return this.#inflight.writing(() => upload(fileList, parentId, option), option?.keepsReads);
867
862
  }) as FetchHandler;
868
863
  });
869
864
  }
@@ -990,7 +985,7 @@ export class FetchClient {
990
985
  names.init,
991
986
  names.getInit,
992
987
  );
993
- return await initFn(...args)[names.initResult];
988
+ return (await initFn(...args))[names.initResult];
994
989
  });
995
990
  }
996
991
  #makeArgSerializer(args: SerializedArg[]) {
@@ -1,3 +1,5 @@
1
+ import { StreamedRead } from "../streamedRead";
2
+
1
3
  type FieldFactories<Handle> = { [Key in keyof Handle]: () => Handle[Key] };
2
4
 
3
5
  /** Awaitable as the shape a helper always gave, and destructurable into one promise per field. */
@@ -26,7 +28,7 @@ export class FetchHandle {
26
28
  Object.defineProperty(handle, key, {
27
29
  enumerable: true,
28
30
  get: () => {
29
- if (!read.has(key)) read.set(key, factories[key]());
31
+ if (!read.has(key)) read.set(key, FetchHandle.#streamed(factories[key]()));
30
32
  return read.get(key);
31
33
  },
32
34
  });
@@ -40,6 +42,14 @@ export class FetchHandle {
40
42
  }) as PromiseLike<Awaited> & Handle;
41
43
  }
42
44
 
45
+ static #streamed(field: unknown): unknown {
46
+ if (!(field instanceof Promise)) return field;
47
+ return field.catch((reason: unknown) => {
48
+ StreamedRead.mark(reason);
49
+ throw reason;
50
+ });
51
+ }
52
+
43
53
  /** The awaited shape's fields stay lazy for the same reason the handle's do: a caller reads one, not all. */
44
54
  static lazy<Target extends object>(target: Target, fields: { [key: string]: () => unknown }): Target {
45
55
  for (const [key, factory] of Object.entries(fields))
@@ -1,3 +1,5 @@
1
+ import { StaleReads } from "../staleReads";
2
+
1
3
  interface InflightQuery {
2
4
  value: Promise<unknown>;
3
5
  controller: AbortController;
@@ -25,6 +27,21 @@ export class InflightQueries {
25
27
  this.#entries.clear();
26
28
  }
27
29
 
30
+ forget() {
31
+ this.detach();
32
+ StaleReads.mark();
33
+ }
34
+
35
+ async writing<T>(write: () => Promise<T>, keepsReads?: boolean): Promise<T> {
36
+ if (keepsReads) return await write();
37
+ this.forget();
38
+ try {
39
+ return await write();
40
+ } finally {
41
+ this.forget();
42
+ }
43
+ }
44
+
28
45
  #start(key: string, start: (signal: AbortSignal) => Promise<unknown>): InflightQuery {
29
46
  const controller = new AbortController();
30
47
  const settle = () => {
package/fetch/index.ts CHANGED
@@ -5,4 +5,5 @@ export * from "./fetchType";
5
5
  export * from "./renderScope";
6
6
  export * from "./requestStorage";
7
7
  export * from "./sessionCookie";
8
+ export * from "./streamedRead";
8
9
  export * from "./types";
@@ -0,0 +1,27 @@
1
+ declare global {
2
+ var __AKAN_STALE_READS__: Set<() => void> | undefined;
3
+ }
4
+
5
+ export class StaleReads {
6
+ static readonly #listeners: Set<() => void> = StaleReads.#shared();
7
+
8
+ static subscribe(listener: () => void): () => void {
9
+ StaleReads.#listeners.add(listener);
10
+ return () => StaleReads.#listeners.delete(listener);
11
+ }
12
+
13
+ static mark(): void {
14
+ for (const listener of StaleReads.#listeners) {
15
+ try {
16
+ listener();
17
+ } catch (error) {
18
+ console.error(`[StaleReads] a listener failed: ${String(error)}`);
19
+ }
20
+ }
21
+ }
22
+
23
+ static #shared(): Set<() => void> {
24
+ globalThis.__AKAN_STALE_READS__ ??= new Set();
25
+ return globalThis.__AKAN_STALE_READS__;
26
+ }
27
+ }
@@ -0,0 +1,23 @@
1
+ import { updateRequestPolicy } from "./requestStorage";
2
+
3
+ declare global {
4
+ var __AKAN_STREAMED_READS__: WeakSet<object> | undefined;
5
+ }
6
+
7
+ export class StreamedRead {
8
+ static readonly #reasons: WeakSet<object> = StreamedRead.#shared();
9
+
10
+ static mark(reason: unknown): void {
11
+ updateRequestPolicy({ cacheable: false });
12
+ if (typeof reason === "object" && reason !== null) StreamedRead.#reasons.add(reason);
13
+ }
14
+
15
+ static is(reason: unknown): boolean {
16
+ return typeof reason === "object" && reason !== null && StreamedRead.#reasons.has(reason);
17
+ }
18
+
19
+ static #shared(): WeakSet<object> {
20
+ globalThis.__AKAN_STREAMED_READS__ ??= new WeakSet();
21
+ return globalThis.__AKAN_STREAMED_READS__;
22
+ }
23
+ }