akanjs 3.2.0-rc.1 → 3.2.0-rc.3

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 (36) hide show
  1. package/CHANGELOG.md +48 -4
  2. package/common/abortSignals.ts +39 -3
  3. package/common/akanGraph.ts +2 -1
  4. package/common/types.ts +1 -0
  5. package/fetch/client/fetchClient.ts +7 -8
  6. package/fetch/client/httpClient.ts +7 -4
  7. package/fetch/client/wsClient.ts +18 -14
  8. package/package.json +1 -1
  9. package/server/akanServer.ts +1 -1
  10. package/server/artifact/builderRpc.ts +10 -5
  11. package/server/devtools/README.md +3 -3
  12. package/server/devtools/devtoolsRouter.ts +9 -5
  13. package/server/devtools/studio/studioRoute.ts +18 -11
  14. package/store/SliceRequest.ts +23 -2
  15. package/store/action.ts +16 -17
  16. package/store/rootStore.ts +2 -0
  17. package/store/storeInstance.ts +1 -1
  18. package/store/withSelector.ts +6 -4
  19. package/types/common/abortSignals.d.ts +3 -0
  20. package/types/common/akanGraph.d.ts +2 -1
  21. package/types/common/types.d.ts +1 -0
  22. package/types/dictionary/base.dictionary.d.ts +1 -1
  23. package/types/dictionary/dictionary.d.ts +8 -8
  24. package/types/fetch/client/fetchClient.d.ts +2 -0
  25. package/types/fetch/client/httpClient.d.ts +1 -0
  26. package/types/fetch/client/wsClient.d.ts +3 -2
  27. package/types/server/artifact/builderRpc.d.ts +4 -0
  28. package/types/server/devtools/devtoolsRouter.d.ts +4 -1
  29. package/types/server/devtools/studio/studioRoute.d.ts +2 -1
  30. package/types/store/SliceRequest.d.ts +6 -1
  31. package/types/store/baseSt.d.ts +1 -295
  32. package/types/store/rootStore.d.ts +6 -0
  33. package/types/store/withSelector.d.ts +1 -1
  34. package/types/webkit/McpAppBridge.d.ts +4 -2
  35. package/webkit/McpAppBridge.ts +28 -4
  36. package/webkit/McpAppFetchBridge.ts +32 -5
package/CHANGELOG.md CHANGED
@@ -32,6 +32,43 @@
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
+
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.
47
+
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.
49
+
50
+ A function is a guard factory only when it returns a guard, a class that implements `Guard` (also one handed to a wrapper, `withName(class implements Guard {…}, field)`) or a call to a factory, so `const guardCount = countGuards()` is no longer a guard. An import from a package outside the workspace (`@vendor/auth`) resolves to no guard: it no longer links a same-name workspace guard, and a vendor's `Public` no longer reads as the framework's. A factory imported from akanjs or a package makes no guard. A lib's `export *` chain, walked from the path the import names, is followed only when it reaches exactly one workspace lib declaring the name, none of its `export *` names a package, and the lib does not declare, destructure or export the name itself; otherwise the guard stays `guard:<lib>:<Name>` without a location, so a vendor shim no longer links another lib's guard. A class extending a base that is not a known guard is no guard, even when a lib declares a guard of that name.
51
+
52
+ More guards carry their location: a name a lib re-exports under another name (`export { Admin as AdminGuard }`) reaches the class, and one it re-exports from akanjs is `guard::Public`; `srvkit.SSO.Kakao` reads through the namespace to the lib's map; a map entry a factory makes (`SSO = { Kakao: ssoGuardOf("kakao") }`) is the guard `SSO.Kakao`; a local wrapper of an imported factory, a factory called through a namespace (`srvkit.resourceGuard("pin")`) and a class that extends a guard (`class DemoAdmin extends Admin`) and a factory a lib re-exports under another name (`export { resourceGuard as rg }`) make guards; a guard made in place, `guards: [canEdit("memo")]`, is a node at the call, keyed by its member, callee and ordinal so an edit to its arguments, or to another member's guards, keeps the id. Of two same-name guards in one owner, an import reaches the one its path names. A wrapper's digest covers every factory it can return, and an edit to a factory in another file marks the guards it makes changed instead of listing the file as unmapped.
53
+
54
+ In the Change Map, a declaration whose id moves between `kind:owner:Name` and `kind:owner:<file>#Name` at the same file is one node, so a second same-name guard shows as one addition, not the first one removed and re-added.
55
+
56
+ `get_graph` past the node limit names owners by the nodes it would answer with, changed pages included, so 650 changed routes no longer hide behind one changed lib method. A guard on `const route = page()…; export default route` is no longer read: `RouteSourceValidator` rejects that shape.
57
+
58
+ Ids and details that change for a saved graph or a Change Map base:
59
+
60
+ - An imported guard function's id names its file: `guard:libs/shared:signedIn` is now `guard:libs/shared:webkit/signedIn.ts#signedIn`.
61
+ - A guard name two files of one owner declare is keyed by file, `guard:apps/demo:srvkit/admin.ts#Admin`.
62
+ - A guard made in place is `guard:<owner>:<file>#<model>.<key>:<callee>@<n>`, the `n`th in-place call of that callee in that slice or endpoint key (`…/memo.signal.ts#memo.shareMemo:resourceGuard@1`). Its label, an endpoint's `detail` and the editor hover name the call: `resourceGuard("memo")` where `detail` read `resourceGuard`, or `allow(…)` when the arguments run past 32 characters or a line. A guard read through a namespace's map reads `srvkit.SSO.Kakao` where it read `Kakao`.
63
+ - A map entry a factory makes is `guard:libs/shared:SSO.Kakao` where it was `guard::Kakao` or `guard:<lib>:Kakao`, and a local map's `Roles.Owner` is `guard:apps/demo:Roles.Owner` where it linked `guard:apps/demo:Owner`.
64
+ - A guard a lib re-exports, under its own name or another, or from akanjs, takes the declaring owner's id (`guard:libs/util:Admin`, `guard::Public`) where it took the re-exporting lib's.
65
+ - A guard imported from an unknown package draws no edge.
66
+ - A name the old "sole visible lib" fallback linked through a lib that does not declare it (`guard:libs/billing:Admin` behind a vendor `export *`) now reads `guard:<lib>:<Name>` without a location, unless the lib's `export *` chain reaches exactly one workspace lib declaring it.
67
+ - A class extending a base that is not a known guard (`class Thing extends Base` with an ordinary `Base`) no longer has a guard node; an endpoint naming it in `guards` links an unlocated `guard:<owner>:Thing`.
68
+
69
+ - **`AkanGraphNode.sources`** in `akanjs/common`: the files besides `at.file` that a node's digest reads, set only with digests. The Change Map uses it to map those files and leaves it out of its answer.
70
+ - **The fact reader** in `@akanjs/language`: `GuardFactoryFact.via` is a list and gains `direct`; `GuardCallFact` gains `kind` (`call` or `extends`) and `scope`; `FileFacts` gains `guardLabels`, an in-place guard's name to its call. A slice's or endpoint's guard made in place is read as `<model>.<key>:<callee>@<n>`, and every in-place call is a `GuardCallFact`.
71
+
35
72
  - 0351ad4: The Akan Graph keys each guard by the app or lib that declares it, `guard:libs/shared:Admin`, and follows the import that names it there, so `Admin as AdminGuard` reaches `Admin`, `srvkit.Admin` reaches the lib's class, and two libs' `Admin` stay two nodes. A guard read out of an object map, `SSO.Kakao`, resolves through the imports of the file that declares the map. A name a lib only re-exports reaches the class it re-exports. A guard a factory makes is a guard too, whether the factory sits in the same file, wraps another factory there, or is imported from another lib. A guard node carries its source location, `doc` (the comment above its declaration that says what it checks) and, in `detail`, its `scope` (`account` or `resource`). A factory-made guard takes the factory's scope, and takes its doc when no guard of that factory has its own. With digests, an edit to a guard or to the factory that makes it marks the guard changed in the Change Map. Every guard a workspace declares is a node, referenced or not. `Public` and `None` come from `akanjs`, carry no location and say what they do. Studio shows a node's `doc` in its tooltip.
36
73
 
37
74
  Ids and details that change for a saved graph or a Change Map base:
@@ -139,13 +176,13 @@
139
176
  `akan tunnel` and `akan start --share` keep working: the tunnel agent now dials the local app under the app's own address and leaves the public host name in `x-forwarded-host`, which is where the app already reads it. A redirect a page raises during SSR now sends a same-origin target as a relative `Location`, so a tunnel or proxy caller lands on the host it used rather than the one the server was dialed as; a target on another origin stays absolute.
140
177
 
141
178
  - 9f30e93: A dev page no longer loses its styles after a stylesheet change arrives together with a pages rebuild. The most common case was the first save after `akan start` released its builder for being idle: the waking builder announces a new pages bundle and a new stylesheet at once, and the SSR worker that had started importing the bundle put the old stylesheet back when the import finished. Pages kept linking that stylesheet, whose file the dev server had already deleted, so they rendered unstyled with a 404 until `akan start` was restarted. The same update also reaches an SSR worker that is still booting after a recycle, which used to keep the stylesheet it was started with.
142
- - d9eaacc: A query takes `signal` in its `FetchPolicy`, joined with its deadline: an abort rejects the call with the signal's reason, stops the request, and ends the retries, including one waiting between tries. A signal from `AbortSignal.timeout` rejects with the slow-server error (`base.error.gatewayTimeout`, 408), as the query's own deadline does. A mutation ignores it, since one already sent may have run.
179
+ - d9eaacc: A query takes `signal` in its `FetchPolicy`, joined with its deadline: an abort rejects the call with the signal's reason, stops the request, and ends the retries, including one waiting between tries. A signal already aborted sends nothing, over HTTP, inside a server render or through an MCP App view's host. A signal from `AbortSignal.timeout` rejects with the slow-server error (`base.error.gatewayTimeout`, 408), as the query's own deadline does. A mutation ignores it, since one already sent may have run. In an MCP App view an abort, or the query's own deadline running out, also asks the host to cancel the call it relayed (`notifications/cancelled`); a mutation that runs out of time is only given up on. A custom `FetchBridge` receives the signal as `signal`.
143
180
 
144
- A slice's list loads (`init`, `refresh`, `setPage`, `setLimit`, `setSort`, `setQueryArgs`, `loadMore`) abort the request a newer load of the same slice supersedes, instead of letting it run to the end and dropping its answer. The superseded load writes nothing and shows no error, and so does one aborted by a `signal` its caller passed. A store action that rejects with an abort no longer shows an error toast.
181
+ A slice's list loads (`init`, `refresh`, `setPage`, `setLimit`, `setSort`, `setQueryArgs`, `loadMore`) abort the request a newer load of the same slice supersedes, instead of letting it run to the end and dropping its answer. The superseded load writes nothing and shows no error, and so does one aborted by a `signal` its caller passed, which resolves; `init` still applies its `default` at once unless the signal was already aborted, and an `init` aborted mid-flight, or one with nothing to change, leaves a loaded-more list whole, so the next refresh still reloads every row shown. A caller's `AbortSignal.timeout` is the exception: the load rejects with the slow-server error and shows it, as a query does. A store action that rejects with the abort of a signal it was given no longer shows an error toast, whatever reason that signal was aborted with, except an app or server error (one with a dictionary key or a status) and a timeout, which still show.
145
182
 
146
183
  - d9eaacc: Identical queries a browser tab has in flight at once share one request: same endpoint, arguments, credential, timeout and retry. The caller that started it parses the answer, and the others parse a copy. One caller's abort leaves the request running for the rest, and it stops only when every caller waiting on it has aborted. A write (a mutation, a file upload, a socket message) or a sign-in or sign-out ends the sharing: a call made after it sends a request of its own, while a caller already waiting keeps its answer. A server still memoizes a request's queries for the whole render, and outside a request it sends each call.
147
184
 
148
- `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 })`.
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.
149
186
 
150
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.
151
188
  - 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.
@@ -403,6 +440,7 @@
403
440
  - **`ssr: "block"` writes every boundary in place,** so a blocking page never shows its `.loading()` fallback.
404
441
  - **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.
405
442
 
443
+ - 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.
406
444
  - 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.
407
445
 
408
446
  - **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.
@@ -410,13 +448,19 @@
410
448
  - **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.
411
449
  - **`set` with a `search()` or `computed()` key** now throws before it writes anything. Before, the state was already replaced when it threw.
412
450
 
451
+ - 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.
452
+
453
+ - **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.
454
+ - **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.
455
+ - **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.
456
+
413
457
  - 6291fec: Akan Studio opens without a dev builder, and names every job in full.
414
458
 
415
459
  - **`/_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.
416
460
  - **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.
417
461
 
418
462
  - 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.
419
- - 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, and `0` keeps none. Room subscriptions never queue there and are sent again on every open, as before.
463
+ - 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.
420
464
 
421
465
  ## 3.1.1
422
466
 
@@ -1,5 +1,6 @@
1
1
  export class AbortSignals {
2
2
  static readonly #noop = () => undefined;
3
+ static readonly #reasons = new WeakSet<object>();
3
4
 
4
5
  static join(signals: (AbortSignal | null | undefined)[]): { signal?: AbortSignal; dispose: () => void } {
5
6
  const live = signals.filter((signal): signal is AbortSignal => !!signal);
@@ -29,16 +30,51 @@ export class AbortSignals {
29
30
  if (!signal) return promise;
30
31
  if (signal.aborted) {
31
32
  void promise.catch(() => undefined);
32
- return Promise.reject(signal.reason);
33
+ return Promise.reject(AbortSignals.reasonOf(signal));
33
34
  }
34
35
  return new Promise<T>((resolve, reject) => {
35
- const abort = () => reject(signal.reason);
36
+ const abort = () => reject(AbortSignals.reasonOf(signal));
36
37
  signal.addEventListener("abort", abort, { once: true });
37
38
  promise.then(resolve, reject).finally(() => signal.removeEventListener("abort", abort));
38
39
  });
39
40
  }
40
41
 
42
+ static reasonOf(signal: AbortSignal): unknown {
43
+ const reason: unknown = signal.reason;
44
+ if (typeof reason === "object" && reason !== null && AbortSignals.#isQuiet(reason, signal))
45
+ AbortSignals.#reasons.add(reason);
46
+ return reason;
47
+ }
48
+
49
+ static isTimeout(signal: AbortSignal) {
50
+ const reason: unknown = signal.reason;
51
+ return reason instanceof Error && reason.name === "TimeoutError";
52
+ }
53
+
41
54
  static isAbort(error: unknown) {
42
- return typeof error === "object" && error !== null && (error as { name?: unknown }).name === "AbortError";
55
+ if (typeof error !== "object" || error === null) return false;
56
+ return (error as { name?: unknown }).name === "AbortError" || AbortSignals.#reasons.has(error);
57
+ }
58
+
59
+ static isAbortOf(error: unknown, callArgs: unknown[]) {
60
+ if (AbortSignals.isAbort(error)) return true;
61
+ return callArgs.some((arg) => {
62
+ const signal = AbortSignals.#signalIn(arg);
63
+ return !!signal?.aborted && Object.is(signal.reason, error) && AbortSignals.#isQuiet(error, signal);
64
+ });
65
+ }
66
+
67
+ static #isQuiet(reason: unknown, signal: AbortSignal) {
68
+ if (AbortSignals.isTimeout(signal)) return false;
69
+ if (typeof reason !== "object" || reason === null) return true;
70
+ const { error, statusCode } = reason as { error?: unknown; statusCode?: unknown };
71
+ return typeof error !== "string" && statusCode === undefined;
72
+ }
73
+
74
+ static #signalIn(arg: unknown): AbortSignal | undefined {
75
+ if (typeof AbortSignal === "undefined" || typeof arg !== "object" || arg === null) return undefined;
76
+ if (arg instanceof AbortSignal) return arg;
77
+ const signal = (arg as { signal?: unknown }).signal;
78
+ return signal instanceof AbortSignal ? signal : undefined;
43
79
  }
44
80
  }
@@ -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
 
@@ -49,6 +49,7 @@ export interface AkanGraphNode {
49
49
  values?: string[];
50
50
  doc?: string;
51
51
  digest?: string;
52
+ sources?: string[];
52
53
  change?: AkanGraphChange;
53
54
  }
54
55
 
package/common/types.ts CHANGED
@@ -11,6 +11,7 @@ export interface FetchPolicy<_Returns = unknown> {
11
11
  cache?: boolean | number;
12
12
  crystalize?: boolean;
13
13
  origin?: string;
14
+ /** @deprecated Read by nothing; catch the call's rejection instead. */
14
15
  onError?: (error: string) => void;
15
16
  token?: string;
16
17
  /** @deprecated Read by nothing; a query always answers its whole return. */
@@ -82,6 +82,8 @@ export interface FetchBridgeCall {
82
82
  args: UnknownRecord;
83
83
  returns: SerializedReturns;
84
84
  timeout?: number | false;
85
+ /** A query's; the call rejects on abort whether or not the bridge stops what it relayed. */
86
+ signal?: AbortSignal;
85
87
  }
86
88
 
87
89
  /** A transport that is not HTTP: a view inside an MCP host has no network, and reaches the server through the host. */
@@ -473,9 +475,10 @@ export class FetchClient {
473
475
  return async (...argData: unknown[]) => {
474
476
  const { option, argMap, url } = requestOf(argData);
475
477
  const signal = option?.signal;
478
+ if (signal?.aborted) throw this.http.abortError(signal);
476
479
  const bridge = this.#bridgeOf(option?.origin);
477
480
  if (bridge) {
478
- const call = this.#viaBridge(bridge, { key, type: "query", endpoint, option, argMap });
481
+ const call = this.#viaBridge(bridge, { key, type: "query", endpoint, option, argMap, signal });
479
482
  return parseReturn(await this.#untilAborted(call, signal), { crystalize: option?.crystalize ?? true });
480
483
  }
481
484
  const headers = this.#makeRequestHeaders(option);
@@ -644,14 +647,11 @@ export class FetchClient {
644
647
  async #viaBridge(
645
648
  bridge: FetchBridge,
646
649
  {
647
- key,
648
- type,
649
650
  endpoint,
650
651
  option,
651
652
  argMap,
652
- }: {
653
- key: string;
654
- type: FetchBridgeCall["type"];
653
+ ...call
654
+ }: Pick<FetchBridgeCall, "key" | "type" | "signal"> & {
655
655
  endpoint: SerializedEndpoint;
656
656
  option?: FetchPolicy;
657
657
  argMap: Map<string, unknown>;
@@ -659,8 +659,7 @@ export class FetchClient {
659
659
  ) {
660
660
  try {
661
661
  return await bridge.call({
662
- key,
663
- type,
662
+ ...call,
664
663
  args: Object.fromEntries(argMap),
665
664
  returns: endpoint.returns,
666
665
  timeout: option?.timeout ?? endpoint.timeout ?? this.http.timeout,
@@ -171,10 +171,13 @@ export class HttpClient {
171
171
  }
172
172
 
173
173
  abortError(signal: AbortSignal): unknown {
174
- const reason: unknown = signal.reason;
175
- if (reason instanceof Error && reason.name === "TimeoutError")
176
- return this.#restoreError({ error: transportErrorKeyMap[408], data: { status: 408 } }, 408);
177
- return reason;
174
+ return HttpClient.abortErrorOf(signal, this.ErrorCls);
175
+ }
176
+
177
+ static abortErrorOf(signal: AbortSignal, ErrorCls?: ErrorConstructor): unknown {
178
+ if (AbortSignals.isTimeout(signal))
179
+ return restoreRemoteError({ error: transportErrorKeyMap[408], data: { status: 408 } }, 408, ErrorCls);
180
+ return AbortSignals.reasonOf(signal);
178
181
  }
179
182
 
180
183
  static #uuid(): string {
@@ -44,8 +44,9 @@ export interface WsClientOptions {
44
44
  */
45
45
  onCredentialExpired?: () => unknown;
46
46
  /**
47
- * Messages kept while the socket is down, the oldest dropped past it; 100 unless named, `0` keeps none. Subscribes
48
- * never queue here: every room is sent again on open.
47
+ * Messages kept while the socket is down, the oldest dropped past it; 100 unless named, `0` keeps none and says so
48
+ * once, and a negative limit or `Infinity` keeps every one. Subscribes never queue here: every room is sent again
49
+ * on open.
49
50
  */
50
51
  outboxLimit?: number;
51
52
  }
@@ -102,7 +103,7 @@ export class WsClient {
102
103
  /** Whether this client has been connected before, so the first open is a start rather than a recovery. */
103
104
  #hadConnection = false;
104
105
  #outbox: string[] = [];
105
- #outboxDropped = 0;
106
+ #outboxDrops = { count: 0, noneWarned: false };
106
107
  #unconnectedWarnTimers = new Map<string, ReturnType<typeof setTimeout>>();
107
108
  #jwt: string | null = null;
108
109
  #renewing: Promise<unknown> | null = null;
@@ -203,9 +204,12 @@ export class WsClient {
203
204
  });
204
205
  const queued = this.#outbox;
205
206
  this.#outbox = [];
206
- if (this.#outboxDropped > 0)
207
- this.logger.warn(`WebSocket dropped ${this.#outboxDropped} oldest queued message(s) while disconnected`);
208
- this.#outboxDropped = 0;
207
+ const keepsNone = outboxLimitOf(this.#options.outboxLimit) === 0;
208
+ if (this.#outboxDrops.count > 0 && !(keepsNone && this.#outboxDrops.noneWarned)) {
209
+ this.logger.warn(`WebSocket dropped ${this.#outboxDrops.count} oldest queued message(s) while disconnected`);
210
+ this.#outboxDrops.noneWarned ||= keepsNone;
211
+ }
212
+ this.#outboxDrops.count = 0;
209
213
  for (const frame of queued) this.#ws?.send(frame);
210
214
  this.#handleMessage("connect", undefined);
211
215
  };
@@ -459,7 +463,7 @@ export class WsClient {
459
463
  for (const timer of this.#unconnectedWarnTimers.values()) clearTimeout(timer);
460
464
  this.#unconnectedWarnTimers.clear();
461
465
  this.#outbox = [];
462
- this.#outboxDropped = 0;
466
+ this.#outboxDrops.count = 0;
463
467
  this.#roomAliasMap.clear();
464
468
  this.#ws?.close();
465
469
  this.#ws = null;
@@ -528,16 +532,11 @@ export class WsClient {
528
532
  return this;
529
533
  }
530
534
  #enqueue(frame: string) {
531
- const { outboxLimit } = this.#options;
532
- const limit =
533
- outboxLimit !== undefined && Number.isFinite(outboxLimit)
534
- ? Math.max(0, Math.floor(outboxLimit))
535
- : WsClient.defaultOutboxLimit;
536
535
  this.#outbox.push(frame);
537
- const overflow = this.#outbox.length - limit;
536
+ const overflow = this.#outbox.length - outboxLimitOf(this.#options.outboxLimit);
538
537
  if (overflow <= 0) return;
539
538
  this.#outbox.splice(0, overflow);
540
- this.#outboxDropped += overflow;
539
+ this.#outboxDrops.count += overflow;
541
540
  }
542
541
  subscribe(option: RoomSubscription) {
543
542
  const roomId = WsClient.makeRoomId(option.key, option.data);
@@ -581,3 +580,8 @@ export class WsClient {
581
580
  this.#ws?.send(JSON.stringify(payload));
582
581
  }
583
582
  }
583
+
584
+ const outboxLimitOf = (outboxLimit: number | undefined) => {
585
+ if (outboxLimit === undefined || Number.isNaN(outboxLimit)) return WsClient.defaultOutboxLimit;
586
+ return outboxLimit < 0 ? Number.POSITIVE_INFINITY : Math.floor(outboxLimit);
587
+ };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "akanjs",
3
- "version": "3.2.0-rc.1",
3
+ "version": "3.2.0-rc.3",
4
4
  "sourceType": "module",
5
5
  "type": "module",
6
6
  "publishConfig": {
@@ -787,7 +787,7 @@ export class AkanServer {
787
787
  websocketPrefix: this.websocketPrefix,
788
788
  openapi: this.openapi,
789
789
  getStatus: () => this.status,
790
- ...(webRouter ? DevtoolsRouter.buildsFrom(() => webRouter.builderRpc) : {}),
790
+ ...DevtoolsRouter.buildsFrom(webRouter),
791
791
  }).createRoutes();
792
792
  return { ...openapiRoutes, ...mcpRoutes, ...devtoolsRoutes, ...soloRoutes };
793
793
  }
@@ -27,6 +27,10 @@ export interface BuilderRpcEventHandlers {
27
27
  onBuildStatus?: (status: DevBuildStatus) => void;
28
28
  }
29
29
 
30
+ export interface BuilderRpcTimeout extends Error {
31
+ timeoutMs: number;
32
+ }
33
+
30
34
  /** One per backend process: subscribes to the IPC channel on construction and unsubscribes on `dispose()`. */
31
35
  export class BuilderRpc {
32
36
  readonly #logger = new Logger("BuilderRpc");
@@ -131,6 +135,10 @@ export class BuilderRpc {
131
135
  );
132
136
  }
133
137
 
138
+ static isTimeout(error: unknown): error is BuilderRpcTimeout {
139
+ return error instanceof Error && "timeoutMs" in error;
140
+ }
141
+
134
142
  static #timeoutMs(): number {
135
143
  const configured = Number(process.env.AKAN_BUILDER_RPC_TIMEOUT_MS);
136
144
  if (Number.isFinite(configured) && configured > 0) return configured;
@@ -144,11 +152,8 @@ export class BuilderRpc {
144
152
  return await new Promise<T>((resolve, reject) => {
145
153
  const timer = setTimeout(() => {
146
154
  this.#pending.delete(id);
147
- reject(
148
- new Error(
149
- `[builder] ${label} got no answer in ${timeoutMs}ms; the builder was likely recycled or restarted mid-request — reload to retry`,
150
- ),
151
- );
155
+ const message = `[builder] ${label} got no answer in ${timeoutMs}ms; the builder was likely recycled or restarted mid-request — reload to retry`;
156
+ reject(Object.assign(new Error(message), { timeoutMs }));
152
157
  }, timeoutMs);
153
158
 
154
159
  timer.unref?.();
@@ -676,9 +676,9 @@ for it to be added.
676
676
  `/_akan/studio?view=runtime` draws `/_akan/deps` and `/_akan/signal` as one picture, next to Studio's
677
677
  source-built views (ERD, Signals, Changes, Framework). It calls the same serializers in process, so it reads the
678
678
  container of the process that answered and needs that server running; the header says which (`pid`,
679
- `serverMode`, `replicaIdx`). It needs no dev builder, so `/_akan/studio` with no `view` lands on it when no
680
- builder answers; a source-built view asked for then answers 503 inside Studio's nav, saying to open it under
681
- `akan start`.
679
+ `serverMode`, `replicaIdx`). It needs no dev builder, so `/_akan/studio` without a known `view` lands on it when
680
+ the server has no builder or the builder RPC times out (`AKAN_BUILDER_RPC_TIMEOUT_MS`, 120 s by default); a
681
+ source-built view asked for then, like a failed build, answers 503 inside Studio's nav with the reason.
682
682
 
683
683
  - **Columns.** Jobs, then services by boot stage, then adaptors by boot stage. An injection always targets
684
684
  an earlier stage, so the latest stage stands leftmost and every arrow points from what injects to what it
@@ -19,6 +19,7 @@ export interface DevtoolsRouterContext {
19
19
  prefix: string;
20
20
  websocketPrefix: string;
21
21
  openapi: boolean;
22
+ web?: boolean;
22
23
  getStatus: () => string;
23
24
  buildGraph?: () => Promise<BuildGraphPayload | null>;
24
25
  buildChanges?: (since: string | null) => Promise<BuildChangesPayload | null>;
@@ -39,12 +40,14 @@ export class DevtoolsRouter {
39
40
  }
40
41
 
41
42
  static buildsFrom(
42
- builderRpc: () => BuilderRpc | null,
43
- ): Pick<DevtoolsRouterContext, "buildGraph" | "buildChanges" | "buildFramework"> {
43
+ webRouter: { readonly builderRpc: BuilderRpc | null } | null,
44
+ ): Pick<DevtoolsRouterContext, "web" | "buildGraph" | "buildChanges" | "buildFramework"> {
45
+ if (!webRouter) return { web: false };
44
46
  return {
45
- buildGraph: async () => (await builderRpc()?.buildGraph()) ?? null,
46
- buildChanges: async (since) => (await builderRpc()?.buildChanges(since)) ?? null,
47
- buildFramework: async () => (await builderRpc()?.buildFramework()) ?? null,
47
+ web: true,
48
+ buildGraph: async () => (await webRouter.builderRpc?.buildGraph()) ?? null,
49
+ buildChanges: async (since) => (await webRouter.builderRpc?.buildChanges(since)) ?? null,
50
+ buildFramework: async () => (await webRouter.builderRpc?.buildFramework()) ?? null,
48
51
  };
49
52
  }
50
53
 
@@ -59,6 +62,7 @@ export class DevtoolsRouter {
59
62
  const studio = new StudioRoute({
60
63
  basePath: `${DevtoolsRouter.basePath}/studio`,
61
64
  appName: this.#context.env.appName,
65
+ web: this.#context.web ?? true,
62
66
  buildGraph: this.#context.buildGraph ?? null,
63
67
  buildChanges: this.#context.buildChanges ?? null,
64
68
  buildFramework: this.#context.buildFramework ?? null,
@@ -1,6 +1,11 @@
1
1
  import { Logger } from "akanjs/common";
2
2
  import type { ReactNode } from "react";
3
- import type { BuildChangesPayload, BuildFrameworkPayload, BuildGraphPayload } from "../../artifact";
3
+ import {
4
+ type BuildChangesPayload,
5
+ BuilderRpc,
6
+ type BuildFrameworkPayload,
7
+ type BuildGraphPayload,
8
+ } from "../../artifact";
4
9
  import { createSystemPageHeaders } from "../../systemPages";
5
10
  import { StudioDocument, type StudioEditor, type StudioPayload, type StudioQuery } from "./studioDocument";
6
11
  import type { StudioView } from "./studioLayout";
@@ -9,6 +14,7 @@ import type { StudioRuntimePayload } from "./studioRuntimeGraph";
9
14
  export interface StudioRouteContext {
10
15
  basePath: string;
11
16
  appName: string;
17
+ web: boolean;
12
18
  buildGraph: (() => Promise<BuildGraphPayload | null>) | null;
13
19
  buildChanges: ((since: string | null) => Promise<BuildChangesPayload | null>) | null;
14
20
  buildFramework: (() => Promise<BuildFrameworkPayload | null>) | null;
@@ -42,7 +48,7 @@ export class StudioRoute {
42
48
  const url = new URL(req.url);
43
49
  const asked = StudioRoute.queryOf(url);
44
50
  const loaded = await this.#load(asked);
45
- const landed = "error" in loaded && loaded.builderless && !url.searchParams.has("view");
51
+ const landed = "error" in loaded && loaded.unanswered && !views.has(url.searchParams.get("view") as StudioView);
46
52
  const query: StudioQuery = landed ? { ...asked, view: "runtime" } : asked;
47
53
  const shown = landed ? await this.#load(query) : loaded;
48
54
  if ("error" in shown)
@@ -67,24 +73,25 @@ export class StudioRoute {
67
73
  return buildGraph ? await buildGraph() : null;
68
74
  }
69
75
 
70
- async #load(query: StudioQuery): Promise<{ payload: StudioPayload } | { error: string; builderless: boolean }> {
76
+ async #load(query: StudioQuery): Promise<{ payload: StudioPayload } | { error: string; unanswered: boolean }> {
71
77
  if (query.view === "runtime") return { payload: this.#context.runtime() };
72
78
  try {
73
79
  const payload = await this.#payloadOf(query);
74
- return payload
75
- ? { payload }
76
- : {
77
- error:
78
- "Akan Studio reads this view from the dev builder; open it under `akan start`. Runtime (live) reads this running server and needs no builder.",
79
- builderless: true,
80
- };
80
+ return payload ? { payload } : { error: this.#builderless(), unanswered: true };
81
81
  } catch (error) {
82
82
  const message = error instanceof Error ? error.message : String(error);
83
83
  StudioRoute.logger.warn(`Failed to build the Akan Graph: ${message}`);
84
- return { error: message, builderless: false };
84
+ return { error: message, unanswered: BuilderRpc.isTimeout(error) };
85
85
  }
86
86
  }
87
87
 
88
+ #builderless(): string {
89
+ const reach = this.#context.web
90
+ ? "Akan Studio reads this view from the dev builder; open it under `akan start`."
91
+ : "Akan Studio reads this view from the dev builder, which a server reaches only with its web surface on, and this one serves the API only (`AKAN_SSR=false` or `setWeb(false)`).";
92
+ return `${reach} Runtime (live) reads this running server and needs no builder.`;
93
+ }
94
+
88
95
  static #headers(): Headers {
89
96
  const headers = createSystemPageHeaders();
90
97
  headers.delete("X-Frame-Options");
@@ -1,16 +1,37 @@
1
+ import { AbortSignals } from "akanjs/common";
2
+ import { HttpClient } from "akanjs/fetch";
3
+
1
4
  /** Which of a slice's list requests is current: claiming a new one aborts the older, whose answer would be dropped. */
2
5
  export class SliceRequest {
3
6
  #latest = 0;
4
7
  #controller: AbortController | null = null;
8
+ readonly #httpOf: () => HttpClient | undefined;
9
+
10
+ constructor(httpOf: () => HttpClient | undefined = () => undefined) {
11
+ this.#httpOf = httpOf;
12
+ }
5
13
 
6
- claim() {
14
+ claim(callerSignal?: AbortSignal) {
7
15
  this.#controller?.abort();
8
16
  this.#controller = new AbortController();
9
17
  this.#latest += 1;
10
- return { ticket: this.#latest, signal: this.#controller.signal };
18
+ const ownSignal = this.#controller.signal;
19
+ const joined = AbortSignals.join([ownSignal, callerSignal]);
20
+ return {
21
+ ticket: this.#latest,
22
+ signal: joined.signal ?? ownSignal,
23
+ dispose: joined.dispose,
24
+
25
+ endsQuietly: () => ownSignal.aborted || (!!callerSignal?.aborted && !AbortSignals.isTimeout(callerSignal)),
26
+ };
11
27
  }
12
28
 
13
29
  isCurrent(ticket: number): boolean {
14
30
  return ticket === this.#latest;
15
31
  }
32
+
33
+ endSpent(callerSignal: AbortSignal) {
34
+ if (!AbortSignals.isTimeout(callerSignal)) return;
35
+ throw this.#httpOf()?.abortError(callerSignal) ?? HttpClient.abortErrorOf(callerSignal);
36
+ }
16
37
  }