akanjs 3.2.0-rc.12 → 3.2.0-rc.13

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 (86) hide show
  1. package/ARCHITECTURE.md +17 -17
  2. package/CHANGELOG.md +18 -0
  3. package/client/csrTypes.ts +2 -0
  4. package/client/index.ts +1 -0
  5. package/client/route/RouteDefinition.ts +24 -7
  6. package/client/route/routeArgs.ts +7 -0
  7. package/client/router.ts +12 -2
  8. package/package.json +1 -1
  9. package/server/akanApp.ts +103 -1270
  10. package/server/akanServer.ts +1 -1
  11. package/server/gateway/childSupervisor.ts +325 -0
  12. package/server/gateway/devHostChannel.ts +40 -0
  13. package/server/gateway/gatewayChildren.ts +135 -0
  14. package/server/gateway/gatewayConfig.ts +182 -0
  15. package/server/gateway/gatewayHttpProxy.ts +231 -0
  16. package/server/gateway/gatewayLogging.ts +111 -0
  17. package/server/gateway/gatewayRooms.ts +134 -0
  18. package/server/gateway/gatewayStatus.ts +116 -0
  19. package/server/gateway/gatewayStatusPage.ts +54 -0
  20. package/server/gateway/gatewayWebSocketRelay.ts +149 -0
  21. package/server/mcp/McpDispatcher.ts +6 -24
  22. package/signal/SignalFailure.ts +21 -0
  23. package/signal/agentTurnStream.ts +5 -2
  24. package/types/client/csrTypes.d.ts +2 -0
  25. package/types/client/index.d.ts +1 -1
  26. package/types/client/route/RouteDefinition.d.ts +2 -2
  27. package/types/client/route/routeArgs.d.ts +6 -0
  28. package/types/client/router.d.ts +2 -1
  29. package/types/server/akanApp.d.ts +2 -20
  30. package/types/server/gateway/childSupervisor.d.ts +33 -0
  31. package/types/server/gateway/devHostChannel.d.ts +13 -0
  32. package/types/server/gateway/gatewayChildren.d.ts +47 -0
  33. package/types/server/gateway/gatewayConfig.d.ts +82 -0
  34. package/types/server/gateway/gatewayHttpProxy.d.ts +22 -0
  35. package/types/server/gateway/gatewayLogging.d.ts +16 -0
  36. package/types/server/gateway/gatewayRooms.d.ts +22 -0
  37. package/types/server/gateway/gatewayStatus.d.ts +62 -0
  38. package/types/server/gateway/gatewayStatusPage.d.ts +9 -0
  39. package/types/server/gateway/gatewayWebSocketRelay.d.ts +17 -0
  40. package/types/server/logging/rotatingLogWriter.d.ts +1 -1
  41. package/types/signal/SignalFailure.d.ts +1 -0
  42. package/types/signal/agentTurnStream.d.ts +1 -0
  43. package/types/ui/Agent/Chat.d.ts +5 -2
  44. package/types/ui/Agent/ChatHeader.d.ts +13 -0
  45. package/types/ui/Agent/ChatPendingCards.d.ts +23 -0
  46. package/types/ui/overlayLayer.d.ts +6 -1
  47. package/types/vendor/@akanjs/native/packages/cli/src/lib/project.d.ts +4 -0
  48. package/types/vendor/@akanjs/native/packages/desktop/src/relaunch.d.ts +1 -0
  49. package/types/vendor/@akanjs/native/plugins/external-view/src/index.d.ts +14 -10
  50. package/types/vendor/use-agentic/failureCode.d.ts +4 -0
  51. package/types/vendor/use-agentic/types.d.ts +6 -0
  52. package/types/webkit/CsrGuards.d.ts +2 -0
  53. package/ui/Agent/Chat.tsx +96 -116
  54. package/ui/Agent/ChatHeader.tsx +59 -0
  55. package/ui/Agent/ChatPendingCards.tsx +49 -0
  56. package/ui/Agent/fetchRunner.ts +8 -1
  57. package/ui/BottomSheet.tsx +1 -1
  58. package/ui/Dialog/LegacyModal.tsx +1 -1
  59. package/ui/Dialog/Modal.tsx +1 -1
  60. package/ui/Popconfirm.tsx +1 -1
  61. package/ui/overlayLayer.ts +22 -1
  62. package/vendor/@akanjs/native/CHANGELOG.md +6 -1
  63. package/vendor/@akanjs/native/native/desktop/src/external.rs +213 -111
  64. package/vendor/@akanjs/native/native/desktop/src/lib.rs +12 -4
  65. package/vendor/@akanjs/native/native/desktop/src/linux/external.rs +275 -0
  66. package/vendor/@akanjs/native/native/desktop/src/linux/mod.rs +1 -0
  67. package/vendor/@akanjs/native/packages/cli/src/lib/native-plugins.ts +5 -3
  68. package/vendor/@akanjs/native/packages/cli/src/lib/project.ts +25 -1
  69. package/vendor/@akanjs/native/packages/desktop/src/deeplinks.ts +2 -2
  70. package/vendor/@akanjs/native/packages/desktop/src/host.ts +2 -2
  71. package/vendor/@akanjs/native/packages/desktop/src/relaunch.ts +8 -3
  72. package/vendor/@akanjs/native/plugins/app/src/desktop.ts +2 -2
  73. package/vendor/@akanjs/native/plugins/autostart/src/desktop.ts +2 -1
  74. package/vendor/@akanjs/native/plugins/external-view/native-plugin.json +4 -1
  75. package/vendor/@akanjs/native/plugins/external-view/src/index.ts +14 -10
  76. package/vendor/use-agentic/AgentSession.ts +11 -11
  77. package/vendor/use-agentic/CHANGELOG.md +6 -0
  78. package/vendor/use-agentic/Compaction.ts +2 -1
  79. package/vendor/use-agentic/ToolRunner.ts +3 -15
  80. package/vendor/use-agentic/Transcript.ts +6 -3
  81. package/vendor/use-agentic/WIRE.md +12 -1
  82. package/vendor/use-agentic/failureCode.ts +44 -0
  83. package/vendor/use-agentic/httpRunner.ts +14 -3
  84. package/vendor/use-agentic/types.ts +6 -0
  85. package/webkit/CsrGuards.ts +7 -2
  86. package/webkit/useLocation.ts +3 -2
package/ARCHITECTURE.md CHANGED
@@ -86,23 +86,23 @@ Declared in [service/ipcTypes.ts](service/ipcTypes.ts).
86
86
  | --- | --- | --- |
87
87
  | `ready` | `AkanServer` | `AkanApp` |
88
88
  | `pubsub.publish` | `SolidPubSub` | `AkanApp` |
89
- | `pubsub.deliver` | `AkanApp` | `SolidPubSub` |
89
+ | `pubsub.deliver` | `GatewayRooms` | `SolidPubSub` |
90
90
  | `pubsub.subscribe` | `SolidPubSub` | `AkanApp` |
91
91
  | `pubsub.unsubscribe` | `SolidPubSub` | `AkanApp` |
92
- | `pubsub.snapshot.request` | `AkanApp` | `SolidPubSub` |
92
+ | `pubsub.snapshot.request` | `GatewayRooms` | `SolidPubSub` |
93
93
  | `pubsub.snapshot` | `SolidPubSub` | `AkanApp` |
94
94
  | `live.change` | `SolidPubSub` | `AkanApp`, `SolidPubSub` |
95
95
  | `live.models` | `SolidPubSub` | `AkanApp` |
96
96
  | `queue.enqueued` | `SolidQueue` | `AkanApp` |
97
97
  | `queue.wake` | `AkanApp` | `SolidQueue` |
98
- | `health.ping` | `AkanApp` | `AkanServer` |
98
+ | `health.ping` | `ChildSupervisor` | `AkanServer` |
99
99
  | `health.pong` | `AkanServer` | `AkanApp` |
100
100
  | `ws.opened` | — | — |
101
101
  | `ws.closed` | — | — |
102
102
  | `metrics.report` | `AkanServer` | `AkanApp` |
103
103
  | `log.records` | `LogForwarder` | `AkanApp` |
104
- | `log.level` | `AkanApp` | `AkanServer` |
105
- | `shutdown` | `AkanApp` | `AkanServer` |
104
+ | `log.level` | `ChildSupervisor`, `GatewayLogging` | `AkanServer` |
105
+ | `shutdown` | `ChildSupervisor` | `AkanServer` |
106
106
  | `file.resolve` | `NativeFile` | — |
107
107
  | `file.resolved` | — | `NativeFile` |
108
108
  | `secret.request` | `NativeSecret` | — |
@@ -115,22 +115,22 @@ Declared in [server/artifact/ipcTypes.ts](server/artifact/ipcTypes.ts).
115
115
 
116
116
  | Message | Sent by | Handled by |
117
117
  | --- | --- | --- |
118
- | `build-route` | `BuilderRpc` | `AkanApp`, `AkanAppHost`, `IncrementalBuilder` |
119
- | `build-csr` | `BuilderRpc` | `AkanApp`, `AkanAppHost`, `IncrementalBuilder` |
120
- | `build-graph` | `BuilderRpc` | `AkanApp`, `AkanAppHost`, `IncrementalBuilder` |
121
- | `build-route-res` | `AkanAppHost`, `IncrementalBuilder` | `AkanApp`, `AkanAppHost`, `BuilderRpc`, `IncrementalBuilderHost` |
122
- | `build-csr-res` | `AkanAppHost`, `IncrementalBuilder` | `AkanApp`, `AkanAppHost`, `BuilderRpc`, `IncrementalBuilderHost` |
123
- | `build-graph-res` | `AkanAppHost`, `IncrementalBuilder` | `AkanApp`, `AkanAppHost`, `BuilderRpc`, `IncrementalBuilderHost` |
118
+ | `build-route` | `BuilderRpc` | `AkanApp`, `BuilderRequestRelay`, `DevBackend`, `IncrementalBuilder` |
119
+ | `build-csr` | `BuilderRpc` | `AkanApp`, `BuilderRequestRelay`, `DevBackend`, `IncrementalBuilder` |
120
+ | `build-graph` | `BuilderRpc` | `AkanApp`, `BuilderRequestRelay`, `DevBackend`, `IncrementalBuilder` |
121
+ | `build-route-res` | `BuilderRequestRelay`, `IncrementalBuilder` | `AkanApp`, `AkanAppHost`, `BuilderRpc`, `IncrementalBuilderHost` |
122
+ | `build-csr-res` | `BuilderRequestRelay`, `IncrementalBuilder` | `AkanApp`, `AkanAppHost`, `BuilderRpc`, `IncrementalBuilderHost` |
123
+ | `build-graph-res` | `BuilderRequestRelay`, `IncrementalBuilder` | `AkanApp`, `AkanAppHost`, `BuilderRpc`, `IncrementalBuilderHost` |
124
124
  | `builder-shutdown` | `IncrementalBuilderHost` | `IncrementalBuilder` |
125
125
  | `builder-ready` | `IncrementalBuilder` | `AkanApp`, `BuilderRpc`, `IncrementalBuilderHost` |
126
- | `backend-ready` | `AkanApp` | `AkanAppHost` |
127
- | `invalidate` | `AkanAppHost`, `prepareDevWatchBatch` | `AkanApp`, `AkanAppHost`, `BuilderRpc`, `IncrementalBuilderHost` |
128
- | `css-updated` | `BuildBatch`, `IncrementalBuilder` | `AkanApp`, `AkanAppHost`, `BuilderRpc`, `IncrementalBuilderHost`, `shouldRelayRecycledFrontendState` |
129
- | `pages-updated` | `BuildBatch`, `IncrementalBuilder` | `AkanApp`, `AkanAppHost`, `BuilderRpc`, `IncrementalBuilderHost`, `shouldRelayRecycledFrontendState` |
126
+ | `backend-ready` | `ChildSupervisor` | `DevBackend` |
127
+ | `invalidate` | `DevRecycler`, `prepareDevWatchBatch` | `AkanApp`, `AkanAppHost`, `BuilderRpc`, `DevBuilder`, `IncrementalBuilderHost` |
128
+ | `css-updated` | `BuildBatch`, `IncrementalBuilder` | `AkanApp`, `AkanAppHost`, `BuilderRpc`, `DevBuilder`, `IncrementalBuilderHost`, `shouldRelayRecycledFrontendState` |
129
+ | `pages-updated` | `BuildBatch`, `IncrementalBuilder` | `AkanApp`, `AkanAppHost`, `BuilderRpc`, `DevBuilder`, `IncrementalBuilderHost`, `shouldRelayRecycledFrontendState` |
130
130
  | `csr-updated` | `BuildBatch`, `IncrementalBuilder` | `AkanApp`, `BuilderRpc`, `IncrementalBuilderHost` |
131
131
  | `ssr-updated` | `BuildBatch`, `IncrementalBuilder` | `AkanApp`, `BuilderRpc`, `IncrementalBuilderHost` |
132
- | `build-status` | `AkanApp`, `AkanAppHost`, `BuildBatch`, `IncrementalBuilder` | `AkanApp`, `AkanAppHost`, `BuildBatchRunner`, `BuilderRpc`, `IncrementalBuilderHost` |
133
- | `builder-metrics` | `IncrementalBuilder` | `AkanAppHost`, `IncrementalBuilderHost` |
132
+ | `build-status` | `BuildBatch`, `DevBackend`, `DevHostChannel`, `IncrementalBuilder` | `AkanApp`, `AkanAppHost`, `BuildBatchRunner`, `BuilderRpc`, `DevBackend`, `DevBuilder`, `IncrementalBuilderHost` |
133
+ | `builder-metrics` | `IncrementalBuilder` | `AkanAppHost`, `DevBuilder`, `IncrementalBuilderHost` |
134
134
  | `boot-armed` | `IncrementalBuilder` | `AkanAppHost`, `IncrementalBuilderHost` |
135
135
 
136
136
  ### `InMsg`: server → RSC worker
package/CHANGELOG.md CHANGED
@@ -12,6 +12,15 @@
12
12
 
13
13
  **Upgrading.** A usage hook receives failed and aborted turns. Before, a streamed turn whose reader left ran to its end and was billed as finished; it now stops early and is billed at its estimate. To bill as before, bill every report except `outcome === "failed"`. Billing only `ok` would leave a stopped turn unbilled while the provider charged for it. Read `estimated` to treat estimated counts differently.
14
14
 
15
+ - ba81635: A modal opened from inside the floating `Agent.Chat` now stacks above the panel, and the panel's header takes a node for its title and names its parts.
16
+
17
+ - **Overlays opened from the floating panel stack above it.** A `Modal`, `BottomSheet`, `Popconfirm`, `Dropdown`, `Select` or `Tooltip` rendered anywhere inside the panel, the `header` slot included, portals into a layer just above the panel (`overlayZ.agentPanelOverlay`, 160). It used to land under the panel, whose z-index (150) tops a page's modals (120). One the page opens still stays under the panel. An `inline` chat hands down whichever portal it sits in, as before, so a modal around it still hosts what it opens. While the turn waits on an approval, a tool card or a question, a modal, sheet or popconfirm the panel opened sinks under the panel so the answer stays reachable, and comes back once answered; what a card opens stays above.
18
+ - **`title` takes a `ReactNode`**, so a mark can go before the name. A new `label` names the panel for screen readers when `title` is not plain text; without either, the name is `l("base.agent")`, and a string `title` names the panel as before.
19
+ - **The header's parts carry `data-slot` hooks**: `agent-header` on the bar, `agent-title` on the title and `agent-running` on the dot shown while a turn runs. Restyle one through them, for example `panelClassName="[&_[data-slot=agent-running]]:bg-accent"`, rather than through the markup's shape.
20
+ - **The header rule is `border-border`**, as other framework surfaces draw their rules, instead of `border-foreground/5`.
21
+
22
+ **Upgrading.** An `AgentChat` override that types `title` as `string` must take `ReactNode`. A modal an app mounted beside the Chat and opened from the panel's `header` still opens under the panel; mount it inside `header` to bring it above.
23
+
15
24
  - e9a2c7f: `this.agentService.loop(request)` runs a model over the `/mcp` tool catalogue in-process until it answers. It needs no browser, so a queued task, a scheduled run or a reply to a mention can use it.
16
25
 
17
26
  - **Events.** It returns an async iterable of `text`, `toolCall`, `toolResult`, `usage`, `compacted` and `awaiting` events. The stream ends with exactly one `done { stop, rounds }` or `error`. `stop` is one of `end`, `maxRounds`, `budget`, `aborted`, `length`, `quota`, `unauthorized` or `awaiting`. The loop waits for the consumer at every event.
@@ -63,6 +72,12 @@
63
72
  - **Cache writes reported separately.** `LlmUsage.cacheWriteTokens` is the part of `inputTokens` the provider wrote to its cache, which Anthropic bills above its input rate. `inputTokens` still counts the whole prompt.
64
73
  - **`AgentService.runTurn(request, { onDelta, preamble, signal })`.** `preamble` replaces the in-page preamble, and `false` sends none, for a turn with no screen behind it. Passing `onDelta` alone as the second argument still works.
65
74
 
75
+ - 8c70603: A failed agent turn now names a code a host can branch on, beside the message it already sent, which is unchanged. No upgrade step is needed: the fields are new.
76
+
77
+ - The relay's `error` event and `AgentTurnStream.failure` carry `code`, named the way a failed MCP tool call is. That is the `Err`'s dictionary key, else an `AkanError`'s own code, else the status's name. A guard's 401 or 403 is named by its status alone, and a 5xx never takes a duck-typed body's code. `SignalFailure.codeOf(error, status)` holds that rule, and a failed MCP tool call is now named through it too.
78
+ - `use-agentic`'s `RunnerEvent` error gains an optional `code`. `httpRunner` reads it from a stream's error event and keeps it only when it is a dictionary key or one camelCase token. A failure answered before the stream opens is named by its body's bounded code, else by its status. A 401 or 403 takes no dictionary key there either, so a refusal reads the same before and after the stream opens.
79
+ - The in-page chat keeps the key as `code` after translating the message. The session records it on the failed assistant message as `ChatMessage.errorCode`, which a host reads and the transcript never sends back.
80
+
66
81
  - dcb7e61: The signal and service facets throw coded failures instead of a bare `Error`. Each one keeps its message, so a test or a log matching the text still matches. Each one carries a `code` that a caller, an agent or an MCP client can branch on, for example `DocumentStoreError.is(error, "invalidQuery")`.
67
82
 
68
83
  | Class | Codes | Status |
@@ -100,6 +115,7 @@
100
115
 
101
116
  **`Exception.<Status>.is(error)` type-checks.** `StatusException` now declares `is`, so `Exception.BadRequest.is(error)` narrows `error` to an `Exception` and checks its own class.
102
117
 
118
+ - f314eba: A route guard gets a second argument, `{ path }`: the requested in-app path with its search, in the form `router.push` takes, on the server and in CSR (`undefined` while MCP lists a screen). `signedIn({ path })` from `@libs/shared/webkit` adds `?redirect=<path>` to the sign-in URL, and `signedIn("/login")` still works. Use `path` to build a redirect target only. It must never decide admission: CSR asks a guard again only when the route or an argument it declared changes.
103
119
  - d6b3619: Every `Err` is now one class, `Err` from `akanjs/common`. That covers the one an app's or lib's `lib/dict` builds, the one `useClient` returns, `akanjs/dictionary`'s own, and an error restored off the wire. Each is that class typed with its own dictionary's keys, so `Err.is` and the status classes behave the same in the browser and on the server. `instanceof Err` holds within one copy of the module. A page bundle and the framework each carry one, so check across them with `Err.is`.
104
120
 
105
121
  - **`Err` is an `AkanError`.** `AkanError.is(err)` is true for every `Err`, and `err.forwarded` is true unless it was restored with a `code`, so the request path still sends its `toJSON()` as it is.
@@ -745,6 +761,7 @@
745
761
  - **A new `akanApi` guideline** lists every import path and the exact signatures of the route stages, `router`, `Link`, `serve`, `adapt`, the endpoint builders, `SignalOption`, `serviceDictionary`, and the keys of `akan.config.ts` with the `web` and `i18n` shapes. It is generated from the akanjs types of the same release, and a test fails when the two drift apart. `akan agent install` ships it as a reference of both skills, and `get_guideline` / `akan guideline show akanApi` print it.
746
762
  - **`ServiceOptions.serverMode`** carries a doc comment, so an editor shows the same explanation on hover.
747
763
 
764
+ - 2bf769f: Internal: the `AkanApp` gateway is composed from one collaborator per concern under `server/gateway/` instead of one 155-member class. Child supervision and restarts, the HTTP and WebSocket relays, rooms, status endpoints, logging and the dev-host channel behave as before, and `AkanApp` and `AkanAppOptions` are unchanged.
748
765
  - 91ccf38: Internal: `makeActions` and `useCsrValues` are composed from one file per action set and hook instead of two monoliths. Store actions, hook order, effects and their dependencies are unchanged.
749
766
  - c2af76a: Internal: the web router's route table is built by one collaborator per route family instead of one 437-line method. Routes, their order, headers, caching and error answers are unchanged. The framework map now follows a send through a field that hands out its receiver (`this.#hub()?.broadcast(...)`), so `ARCHITECTURE.md` still names who sends each HMR message.
750
767
  - df32c46: On SQLite, work outside an open `this.transaction()` no longer sees it or joins it. A read from another request ran on the one shared connection, inside the transaction, so it returned rows the transaction had not committed, including rows it then rolled back. It now runs on a second, read-only connection to the same WAL file and sees what is committed, as on Postgres, without waiting for the transaction; code inside the transaction still reads its own writes. A write from another request already waited for the open transaction, but when a second transaction began as the first committed, the waiting write could run inside the second one and be rolled back with it after its caller was told it had succeeded. It now runs between the two.
@@ -758,6 +775,7 @@
758
775
  - **`ssr: "block"` writes every boundary in place,** so a blocking page never shows its `.loading()` fallback.
759
776
  - **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.
760
777
 
778
+ - a5c476a: A gateway stopped while `AkanApp.start()` was still preparing its runtime folder, logs or ops route no longer spawns replicas or listens afterwards, and its `start()` now returns instead of waiting for a stop that has already happened. A server without a gateway stopped while `AkanServer.start({ listen: false })` was opening its log control socket no longer runs its init schedules afterwards.
761
779
  - 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.
762
780
  - 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.
763
781
 
@@ -121,6 +121,8 @@ export interface RouteGuardProps {
121
121
  searchParams: Record<string, string | string[]>;
122
122
  /** MCP is listing the screen, so no argument is known: a guard reading one throws `RouteArgPending`. */
123
123
  listing?: boolean;
124
+ /** The CSR target's in-app path; a server request's own URL gives it when this is left off. */
125
+ path?: string;
124
126
  }
125
127
  export type RouteGuard = (props: RouteGuardProps) => Promise<void>;
126
128
  export interface RouteRender {
package/client/index.ts CHANGED
@@ -177,6 +177,7 @@ export {
177
177
  type RouteArgValue,
178
178
  type RouteBaseArgs,
179
179
  RouteDefinition,
180
+ type RouteGuardRequest,
180
181
  RouteGuards,
181
182
  RouteHead,
182
183
  type RouteKind,
@@ -11,9 +11,16 @@ import { deserialize } from "akanjs/constant";
11
11
  import { RenderScope } from "akanjs/fetch";
12
12
  import type { ReactNode } from "react";
13
13
  import type { Head, LayoutModule, PageConfig, PageModule, RouteGuardProps } from "../csrTypes";
14
- import { AkanNotFoundError } from "../router";
14
+ import { AkanNotFoundError, getRequestRoutePath } from "../router";
15
15
  import { Translator } from "../translator";
16
- import { RouteArgError, type RouteArgInfo, type RouteArgInput, RouteArgPending, type RouteBaseArgs } from "./routeArgs";
16
+ import {
17
+ RouteArgError,
18
+ type RouteArgInfo,
19
+ type RouteArgInput,
20
+ RouteArgPending,
21
+ type RouteBaseArgs,
22
+ type RouteGuardRequest,
23
+ } from "./routeArgs";
17
24
 
18
25
  export type RouteArgsShape = Record<string, unknown>;
19
26
  export type RouteKind = "page" | "layout" | "rootLayout";
@@ -23,6 +30,7 @@ export const routeDefinitionMarker = Symbol.for("akan.routeDefinition");
23
30
  export const routeArgsMarker = Symbol.for("akan.routeArgs");
24
31
 
25
32
  type HeadStage<Args> = Head | ((args: Args) => PromiseOrObject<Head | null | undefined>);
33
+ type GuardStage<Args> = (args: Args, request: RouteGuardRequest) => void | Promise<void>;
26
34
 
27
35
  interface RouteRenderProps {
28
36
  params: Record<string, string>;
@@ -46,7 +54,7 @@ export abstract class RouteDefinition<
46
54
  #config?: PageConfig;
47
55
 
48
56
  #head?: HeadStage<never>;
49
- #guard?: (args: never) => void | Promise<void>;
57
+ #guard?: GuardStage<never>;
50
58
  #loading?: (args: never) => PromiseOrObject<ReactNode>;
51
59
  #render?: (args: never) => PromiseOrObject<ReactNode>;
52
60
  #renderRoute?: {
@@ -64,10 +72,10 @@ export abstract class RouteDefinition<
64
72
  return this;
65
73
  }
66
74
  /** Runs before any layout body; refuses with `router.redirect()` or `router.notFound()`. */
67
- guard(guard: (args: RouteBaseArgs & Args) => void | Promise<void>) {
75
+ guard(guard: (args: RouteBaseArgs & Args, request: RouteGuardRequest) => void | Promise<void>) {
68
76
  if (this.#guard)
69
77
  throw new Error(`[route-convention] ${this.kind}() declares .guard() twice; run every check from one guard`);
70
- this.#guard = guard as (args: never) => void | Promise<void>;
78
+ this.#guard = guard as GuardStage<never>;
71
79
  return this;
72
80
  }
73
81
  loading(render: (args: RouteBaseArgs & Args & Extra) => PromiseOrObject<ReactNode>) {
@@ -170,9 +178,18 @@ export abstract class RouteDefinition<
170
178
  return args;
171
179
  }
172
180
 
173
- #guardRouteOf(guard: (args: never) => void | Promise<void>) {
181
+ #guardRouteOf(guard: GuardStage<never>) {
174
182
  const route = async (props: RouteGuardProps) =>
175
- await RenderScope.run(() => guard(this.#guardArgsOf(props) as never));
183
+ await RenderScope.run(() => {
184
+ const args = this.#guardArgsOf(props);
185
+
186
+ const request: RouteGuardRequest = {
187
+ get path() {
188
+ return props.listing ? undefined : (props.path ?? getRequestRoutePath(args.lang));
189
+ },
190
+ };
191
+ return guard(args as never, request);
192
+ });
176
193
  Object.defineProperty(route, routeArgsMarker, { value: this.args.map(({ kind, name }) => ({ kind, name })) });
177
194
  return route;
178
195
  }
@@ -16,6 +16,13 @@ export interface RouteBaseArgs {
16
16
  lang: string;
17
17
  }
18
18
 
19
+ /** A guard's second argument. `path` is a target to send the visitor back to, never a reason to let them in: CSR asks
20
+ * a guard again only when the route or an arg it declared moves, so a query it did not declare can move on. */
21
+ export interface RouteGuardRequest {
22
+ /** The requested in-app path with its search, as `router.push` takes it; `undefined` while MCP lists the screen. */
23
+ path?: string;
24
+ }
25
+
19
26
  export interface RouteArgInfo {
20
27
  kind: "param" | "search";
21
28
  name: string;
package/client/router.ts CHANGED
@@ -115,6 +115,16 @@ const getServerPublicOrigin = () => {
115
115
 
116
116
  const getConfiguredBasePaths = () => new Set(parseBasePaths(process.env.AKAN_PUBLIC_BASE_PATHS));
117
117
 
118
+ export const getRequestRoutePath = (lang: string): string | undefined => {
119
+ const request = getEnv().side === "server" ? getServerRequestContext().getRequest() : undefined;
120
+ if (!request) return undefined;
121
+ const { pathname, search } = new URL(request.url);
122
+ const headers = getServerRequestContext().headers();
123
+ const locale = headers.get("x-locale") ?? lang;
124
+ const basePath = getServerBasePath(pathname, locale, headers.get("x-base-path") ?? undefined, "");
125
+ return `${getPathInfo(pathname, locale, basePath).path}${search}`;
126
+ };
127
+
118
128
  const shouldExposeBasePath = () => getEnv().operationMode === "local";
119
129
  const CSR_RUNTIME_SEARCH_PARAMS = ["csr", "akanMobileTarget", "akanMobileBasePath", "akanMobileIndexPath"] as const;
120
130
 
@@ -727,8 +737,8 @@ class Router {
727
737
  return undefined as never;
728
738
  }
729
739
  /** A pathname without its locale and base-path segments; unlike `getPath`, it needs no browser. */
730
- routeOf(pathname: string) {
731
- return getPathInfo(pathname, this.#lang, this.#prefix).path;
740
+ routeOf(pathname: string, lang = this.#lang) {
741
+ return getPathInfo(pathname, lang, this.#prefix).path;
732
742
  }
733
743
  getPath(pathname = csrLocation.pathname) {
734
744
  if (getEnv().side === "server") throw new Error("getPath is only available in client side");
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "akanjs",
3
- "version": "3.2.0-rc.12",
3
+ "version": "3.2.0-rc.13",
4
4
  "sourceType": "module",
5
5
  "type": "module",
6
6
  "publishConfig": {