akanjs 3.2.0-rc.14 → 3.2.0-rc.16

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.
package/ARCHITECTURE.md CHANGED
@@ -88,6 +88,7 @@ Declared in [service/ipcTypes.ts](service/ipcTypes.ts).
88
88
  | `pubsub.publish` | `SolidPubSub` | `AkanApp` |
89
89
  | `pubsub.deliver` | `GatewayRooms` | `SolidPubSub` |
90
90
  | `pubsub.subscribe` | `SolidPubSub` | `AkanApp` |
91
+ | `pubsub.subscribed` | `GatewayRooms` | `SolidPubSub` |
91
92
  | `pubsub.unsubscribe` | `SolidPubSub` | `AkanApp` |
92
93
  | `pubsub.snapshot.request` | `GatewayRooms` | `SolidPubSub` |
93
94
  | `pubsub.snapshot` | `SolidPubSub` | `AkanApp` |
package/CHANGELOG.md CHANGED
@@ -115,6 +115,13 @@
115
115
 
116
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.
117
117
 
118
+ - d9f5ad5: Behind the gateway, a WebSocket subscribe is now acknowledged once the gateway routes the room to the replica that holds it. The gateway used to learn of the room in a message the replica sent without waiting, so an event or a live-list write handled by another replica right after the ack could reach the gateway first and be dropped.
119
+
120
+ - `SolidPubSub.joinRoom` sends its `pubsub.subscribe` with an `ack` number and resolves when the gateway answers `pubsub.subscribed`. A replica's messages reach the gateway in order, so the answer also covers the live models it reported before the subscribe.
121
+ - The wait ends after 3 s if the gateway does not answer, and at once on shutdown. A server that is not a gateway child (no `AKAN_CHILD_SOCKET`) does not wait: a solo server, a desktop one included.
122
+
123
+ No upgrade step is needed: `AkanIpcMessage` only gains the `pubsub.subscribed` message and an optional `ack` on `pubsub.subscribe`, and `SolidPubSub` an injected `behindGateway` flag it reads from the env.
124
+
118
125
  - 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.
119
126
  - 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`.
120
127
 
@@ -377,18 +384,34 @@
377
384
  - **`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.
378
385
  - **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.
379
386
  - **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.
380
- - **A model action no longer takes over what `view<Model>`, `edit<Model>` or `new<Model>` opened during its request.** A `Load.View` hydrating a record and an edit modal filling its form from a page payload count as opens too; an app's own `st.set` of those keys does not.
387
+ - **A model action no longer takes over what `view<Model>`, `edit<Model>` or `new<Model>` opened during its request.** A `Load.View` hydrating a record, an edit modal filling its form from a page payload, and a list's view modal coming back after an edit opened from it closes or fails to load count as opens too; an app's own `st.set` of those keys does not.
381
388
  - `merge<Model>`, `update<Model>` and `update<Model>InForm` write the answer as the open model only while that record is still open.
382
389
  - Creates and updates leave the modal alone.
383
390
  - `update<Model>InForm` and `create<Model>InForm` leave the form to an `edit<Model>`, a `new<Model>` or an edit modal's payload fill opened meanwhile. A `view<Model>` or a `Load.View` does not take the form, so the saved form is still reset and its draft dropped.
384
391
  - A `view<Model>` or `edit<Model>` overtaken by a later one no longer lands its record over the later one.
385
- - Before, a view of another record was replaced or closed when the write landed, and an edit opened during a save lost its form or closed.
392
+ - Before, a view of another record was replaced or closed when the write landed, an edit opened during a save lost its form or closed, and when an edit opened from a list's view was closed while saving, or failed to load while another write was in flight, the view came back only for that write to close it.
386
393
  - **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.
387
394
  - **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.
388
395
 
389
396
  - 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.
390
397
  - 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.
391
398
  - 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.
399
+ - 24dcb1e: A lazily loaded chunk the server no longer serves now reloads its page once, in Chromium and Firefox.
400
+
401
+ - **Before:** a chunk loaded through `import()` (`lazy` from `akanjs/webkit`, `React.lazy`, or a dynamic import in a client component) that a deploy had removed failed to fetch, and the page stayed on its error. This happens to a tab left open across a deploy, and during a rolling deploy when the chunk's request reaches a replica of the other build.
402
+ - **Now:** when such a failure reaches the React root or rejects an `import()` that nothing catches, the client asks the server for the chunk again with a `HEAD` request. Only a 404 reloads the address the tab shows. A network failure, a blocked request or a 5xx leaves the page as before. The check runs only when all of these hold:
403
+ - the error names a chunk under this origin's `/_akan/client/`. Chromium names it, and so does Firefox from 115. Safari and other WebKit browsers do not, so they keep the old behaviour;
404
+ - the browser is online;
405
+ - the tab is not on the path a reload loaded, whether the reload was this fallback's, the chunk fallback's, the user's or `Reconnect`'s. A refresh or a shallow update keeps the tab on that path; after a page navigation to another path, the check runs again;
406
+ - no navigation to another page is under way, and no other document load either;
407
+ - the error is not one the Flight client's chunk loader already handled.
408
+ - **The reload is skipped if anything happened while the request was out:**
409
+ - any client navigation, including a shallow update, a refresh (the token-refresh timer's too) or a back or forward move;
410
+ - a `beforeunload` or `pagehide`, which a document load the router never sees fires (a plain link, a form post, `location.assign`).
411
+ - **Unlike a link failure, this covers the document's own page too,** since a deploy removes the chunks of the build the tab was opened on.
412
+ - **At most one reload per chain of loads.** The reloaded document never reloads from here while it stays on that path, so chunks that keep answering 404 there show their error after one reload, however many there are and whether or not the tab's storage holds. A further reload needs a page navigation to another path. Each chunk is also recorded in the per-tab list the chunk fallback uses.
413
+ - This applies to `akan build` output only.
414
+
392
415
  - 256b6e3: A lazily loaded chunk that fails to link during a rolling deploy now reloads its page as a document.
393
416
 
394
417
  - **Before:** the chunk fallback covered only the chunks the Flight client loads. A chunk loaded through `import()` (`lazy` from `akanjs/webkit`, `React.lazy`, or a dynamic import in a client component) on a page from another build could fail to link against the document's import map. With no error boundary above it, the page went blank; with one, it showed that boundary's fallback. Nothing loaded the page again.
@@ -453,6 +476,11 @@
453
476
  - `akan preview` keeps an unprefixed path unprefixed under `"as-needed"`, except with `--csr`. The value reaches bundles as `AKAN_PUBLIC_LOCALE_PREFIX`, and the image env carries it when it is `"as-needed"`. `LocalePath` (`akanjs/common`) and a fourth `localePrefix` argument to `getPathInfo` build the same URLs in app code.
454
477
 
455
478
  - dfc3564: A server stopped while its log control socket was still starting no longer leaves that socket listening. `akan logs` then found a socket nothing owned, and it kept serving a closed log hub until the process exited. Starts and stops on one control socket path now take turns, so a start whose log hub was closed meanwhile binds nothing or closes what it bound before a restart's open looks, and the restarted server gets its own socket. A socket that fails after binding is closed before the error surfaces. Stopping a control socket that never bound no longer unlinks the live socket of another server in the same runtime folder.
479
+ - 24dcb1e: A missing file under `/_akan/client/`, `/_akan/styles/`, `/_akan/fonts/` or `/_akan/dict/` now answers its 404 with `Cache-Control: no-store` and the asset security headers.
480
+
481
+ - **Before:** the 404 named no cache policy. A CDN in front of the app may cache such a 404 (Cloudflare keeps one on a `.js` path for 3 minutes), so during a rolling deploy one replica's 404 for a chunk was served for the replicas that have it.
482
+ - **Now:** both the app server and the gateway send `no-store`, so a CDN that honours it asks the origin again. CloudFront may still keep an error response for its error caching minimum TTL (10 seconds by default); lower that on the distribution if it matters.
483
+
456
484
  - d12f556: `akanjs/signal`, `akanjs/client`, `akanjs/server`, `akanjs/constant` and `akanjs/store` now list every export by name instead of re-exporting whole files with `export *`. They export exactly the names they did before. A new export in one of those facets' files is no longer exported from `akanjs/<facet>` until its facet's `index.ts` names it. Files under `server/` and `client/native/` stay importable by their own subpath, as before.
457
485
  - 9b5bcee: Every SSR page now loads 72K less framework JavaScript (22K less after Brotli).
458
486
 
@@ -500,6 +528,11 @@
500
528
 
501
529
  The `infra/app` chart's readiness probe calls a new `readinessPath` value, `/_akan/app/health` unless set, because an image built with an earlier akanjs answers `/_akan/app/ready` with 404 and its pod would never become Ready. Set `readinessPath: /_akan/app/ready` once every image the chart deploys carries this release. The repository's own values set it, since its pipeline builds the image from the same commit as the chart. The startup and liveness probes stay on `/_akan/app/health`.
502
530
 
531
+ - cf5eeff: On the Redis WebSocket adaptor:
532
+
533
+ - **A PUBLISH a Redis ACL refuses (`NOPERM`) is dropped, not retried.** It used to be retried on a timer, and every event queued behind it waited with it, so one refused channel delayed all cross-server events. A refusal is logged as an error that names the family of channels whose events are being dropped (`<prefix>ws:room`, `<prefix>ws:change` or `<prefix>ws:broadcast`), at most once a minute per family. Other error replies are still retried.
534
+ - **A shutdown no longer logs the publisher's and subscriber's disconnect warnings.** A link that drops while the server runs still warns, and a dropped publisher now warns once rather than on every failed reconnect attempt.
535
+
503
536
  - 7f0de74: On the Redis WebSocket adaptor, each room's events and each live-synced model's changes now go out on channels of their own, and a server subscribes only to those of the rooms and models it holds. Both used to go to every server of the app on one channel, `<prefix>ws:broadcast`, which servers keep using for one more release so that a rolling deploy loses nothing (see the note on rolling deploys).
504
537
 
505
538
  - **A room's events** go out on one of 16,384 channels, picked by a hash of the room id (`<prefix>ws:room:<shard>`). A server subscribes to a shard while it holds a room on it.
@@ -547,7 +580,13 @@
547
580
  - `invalidConfig`: a `transformEnv` callback returns something other than the env object.
548
581
  - `notRegistered`: no WebSocket adaptor is registered.
549
582
 
583
+ - f8de6a7: A page whose server render streamed an error after its first byte is no longer replayed from the browser's navigation cache. Before, going back to it or following a link to it showed the same "This page could not be loaded." notice (or a `Load.*` section's failure) again without asking the server, and only "Try again" refetched. Now the next visit, a hover prefetch included, asks the server for the page. This covers the page a document loaded with, a page a navigation fetched, and, with `AKAN_PUBLIC_RSC_PARTIAL_COMMIT=1`, a cached patch. A not-found or redirect raised in the stream still counts as the page's answer and replays as before. A failure that recurs on every visit, such as a `Load.*` read refused for this viewer, now costs a server render on each visit. The server already renders such a page anew each time, since it never caches a render with a refused `Load.*` read. In development, a render error whose message is empty now carries the digest `AKAN_RENDER_ERROR` instead of an empty one.
584
+ - 1ed9f6a: With `AKAN_PUBLIC_RSC_PARTIAL_COMMIT=1`, a page reached by a patch is replayed from the browser's cache under any `#fragment`, as a page in the full-page cache already is: `/docs/x#a` and `/docs/x#b` now share one cached patch, and a link to another fragment of a page the patch cache would replay is not prefetched. A page that refuses prefetching (`.config({ prefetch: false })`) is no longer asked again after each full navigation: its 204 is kept for the prefetch lifetime under any page on screen, for the same account, as it already was with the flag off.
550
585
  - b0ccf6f: The browser's RSC client now throws coded errors instead of bare `Error`s, so a caller can branch on `error.code`. A route the server has no page for is `routeNotFound` (404), as a missing WebSocket route already is. A response with no RSC payload is `rscFetchFailed` (502). A patch missing its parts, or a full fallback that answers with a patch, is `invalidRscResponse`, the code `rscClientFetch` already throws for the latter. The redirect marker, which only a log line receives, is `rscRedirectStarted`. Each error keeps its `name` and its message, except the fallback's message, which is now `[rscClient] fallback is a patch`. The error-code reference lists the new codes.
586
+ - 7836476: In development, an edit to any framework module that the browser's RSC client runs now fully reloads the open tab. That is `rscClient.tsx` and the `server/` modules it loads, such as `rscClientCache.ts`, `rscClientPatch.ts`, `rscClientFetch.ts`, `rscNavigationState.ts` and `rscPrefetchCache.ts`. Only `rscClient.tsx` did before, so an edit to one of the others refreshed the page in place and the tab kept running the old client code.
587
+
588
+ The RSC client's caches move from `rscClient.tsx` into `rscClientCache.ts`, and its patch commit into `rscClientPatch.ts`, with no change in behaviour.
589
+
551
590
  - 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:
552
591
 
553
592
  - **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 })`.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "akanjs",
3
- "version": "3.2.0-rc.14",
3
+ "version": "3.2.0-rc.16",
4
4
  "sourceType": "module",
5
5
  "type": "module",
6
6
  "publishConfig": {
package/server/akanApp.ts CHANGED
@@ -255,7 +255,7 @@ export class AkanApp {
255
255
  this.#rooms.deliverPubsub(idx, message);
256
256
  return;
257
257
  case "pubsub.subscribe":
258
- this.#rooms.addRoomMembership(idx, message.roomId, message.socketId);
258
+ this.#rooms.subscribe(idx, message);
259
259
  return;
260
260
  case "pubsub.unsubscribe":
261
261
  this.#rooms.removeRoomMembership(idx, message.roomId, message.socketId);
@@ -36,3 +36,9 @@ export const assetHeaders = ({ contentType, cacheControl, anyOrigin }: AssetHead
36
36
  if (anyOrigin) headers.set("Access-Control-Allow-Origin", "*");
37
37
  return applySecurityHeaders(headers);
38
38
  };
39
+
40
+ export const missingAssetResponse = (): Response =>
41
+ new Response("Not Found", {
42
+ status: 404,
43
+ headers: assetHeaders({ contentType: "text/plain; charset=utf-8", cacheControl: "no-store" }),
44
+ });
@@ -2,7 +2,7 @@ import path from "node:path";
2
2
  import type { Logger } from "akanjs/common";
3
3
  import { isTraceEnabled } from "../../signal/trace";
4
4
  import { AKAN_CHILD_HOST, makeAkanChildProxyHeaders } from "../akanAppHeaders";
5
- import { type AssetHeaderOptions, assetHeaders } from "../assetHeaders";
5
+ import { type AssetHeaderOptions, assetHeaders, missingAssetResponse } from "../assetHeaders";
6
6
  import { compressResponse, compressStreamResponse, encodedFileResponse } from "../contentEncoding";
7
7
  import { ServerLimits } from "../routing/serverLimits";
8
8
  import { resolveStaticPath } from "../staticPath";
@@ -56,9 +56,9 @@ export class GatewayHttpProxy {
56
56
  path.join(this.#config.artifactDir, artifact.root),
57
57
  url.pathname.slice(artifact.strip),
58
58
  );
59
- if (!filePath) return new Response("Not Found", { status: 404 });
59
+ if (!filePath) return missingAssetResponse();
60
60
  const file = Bun.file(filePath);
61
- if (!(await file.exists())) return new Response("Not Found", { status: 404 });
61
+ if (!(await file.exists())) return missingAssetResponse();
62
62
  return this.#fileResponse(req, filePath, {
63
63
  contentType: file.type || artifact.type,
64
64
  cacheControl: "public, max-age=31536000, immutable",
@@ -52,6 +52,13 @@ export class GatewayRooms {
52
52
  }
53
53
  }
54
54
 
55
+ subscribe(childIdx: number, message: Extract<AkanIpcMessage, { type: "pubsub.subscribe" }>) {
56
+ this.addRoomMembership(childIdx, message.roomId, message.socketId);
57
+ const child = this.#children.get(childIdx);
58
+ if (child && message.ack !== undefined)
59
+ this.#children.send(child, { type: "pubsub.subscribed", ack: message.ack } satisfies AkanIpcMessage);
60
+ }
61
+
55
62
  addRoomMembership(childIdx: number, roomId: string, socketId?: string) {
56
63
  const roomChildren = this.#roomChildren.get(roomId) ?? new Set<number>();
57
64
  roomChildren.add(childIdx);
@@ -22,6 +22,10 @@ import { type ChangeKind, type HmrMessage, type HmrWsData, HmrWsHub } from "./ws
22
22
 
23
23
  export { isAkanRuntimeMetadataFile };
24
24
 
25
+ const BROWSER_RSC_MODULE_RE =
26
+ /^(?:rscClient\w*|rscHeadPatch|rscHttp|rscInlineStream|rscNavigationState|rscParkedRedirect|rscPrefetchCache|rscScrollRestoration|routeState|flightRowReader)\.tsx?$/;
27
+ const FRAMEWORK_SERVER_DIR = `${path.sep}pkgs${path.sep}akanjs${path.sep}server`;
28
+
25
29
  export function manifestClientEntriesForFiles(
26
30
  files: string[],
27
31
  clientManifest: ClientManifest,
@@ -597,14 +601,19 @@ export class DevHmrController {
597
601
  return this.#seedIndex.globalLayoutFiles.some((file) => normalized.has(path.resolve(file)));
598
602
  }
599
603
 
604
+ static #isBrowserRscModule(file: string): boolean {
605
+ const resolved = path.resolve(file);
606
+ return path.dirname(resolved).endsWith(FRAMEWORK_SERVER_DIR) && BROWSER_RSC_MODULE_RE.test(path.basename(resolved));
607
+ }
608
+
600
609
  #shouldFullReloadForFiles(files: string[], routeIds: string[] | undefined): boolean {
601
610
  if (files.length === 0) return false;
602
611
  const runtimeRoots = [
603
612
  `${path.sep}pkgs${path.sep}akanjs${path.sep}server${path.sep}hmr${path.sep}`,
604
- `${path.sep}pkgs${path.sep}akanjs${path.sep}server${path.sep}rscClient.tsx`,
605
613
  `${path.sep}pkgs${path.sep}akanjs${path.sep}server${path.sep}ssrFromRscRenderer.tsx`,
606
614
  ];
607
615
  if (files.some((file) => runtimeRoots.some((needle) => path.resolve(file).includes(needle)))) return true;
616
+ if (files.some((file) => DevHmrController.#isBrowserRscModule(file))) return true;
608
617
  if (files.some((file) => path.basename(file).endsWith(".signal.ts"))) return true;
609
618
 
610
619
  return (