akanjs 3.2.0-rc.24 → 3.2.0-rc.26

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 (46) hide show
  1. package/CHANGELOG.md +24 -0
  2. package/client/route/RouteHead.ts +4 -1
  3. package/client/viewportMeta.ts +54 -4
  4. package/fetch/client/fetchClient.ts +3 -11
  5. package/fetch/client/httpClient.ts +1 -2
  6. package/fetch/client/requestScope.ts +11 -2
  7. package/package.json +1 -1
  8. package/server/di/stageFailedError.ts +10 -0
  9. package/server/di/utils.ts +2 -1
  10. package/server/index.ts +2 -0
  11. package/server/migration/migrationCommand.ts +31 -2
  12. package/server/migration/migrationRunner.ts +36 -1
  13. package/server/ops/migrateJobs.ts +2 -2
  14. package/server/ops/opsCommand.ts +1 -1
  15. package/server/rscDocumentHead.tsx +19 -12
  16. package/server/rscRouteDocument.tsx +20 -3
  17. package/service/predefinedAdaptor/database.adaptor.ts +2 -0
  18. package/service/predefinedAdaptor/sql/SqlDocumentStore.ts +10 -0
  19. package/service/predefinedAdaptor/sql/SqlTableSchema.ts +54 -16
  20. package/service/predefinedAdaptor/sql/dialect/postgres.ts +1 -1
  21. package/service/predefinedAdaptor/sql/dialect/sqlite.ts +1 -1
  22. package/service/predefinedAdaptor/sql/types.ts +12 -2
  23. package/types/client/viewportMeta.d.ts +2 -1
  24. package/types/fetch/client/requestScope.d.ts +6 -1
  25. package/types/server/di/stageFailedError.d.ts +5 -0
  26. package/types/server/index.d.ts +2 -1
  27. package/types/server/migration/migrationCommand.d.ts +1 -1
  28. package/types/server/migration/migrationRunner.d.ts +9 -1
  29. package/types/server/rscDocumentHead.d.ts +4 -3
  30. package/types/service/predefinedAdaptor/database.adaptor.d.ts +1 -1
  31. package/types/service/predefinedAdaptor/sql/SqlDocumentStore.d.ts +3 -1
  32. package/types/service/predefinedAdaptor/sql/SqlTableSchema.d.ts +3 -1
  33. package/types/service/predefinedAdaptor/sql/types.d.ts +10 -2
  34. package/types/ui/overlayLayer.d.ts +2 -1
  35. package/types/vendor/@akanjs/native/plugins/external-view/src/index.d.ts +2 -2
  36. package/types/vendor/@akanjs/native/plugins/single-instance/src/socket.d.ts +15 -2
  37. package/ui/Agent/Chat.tsx +12 -2
  38. package/ui/overlayLayer.ts +4 -2
  39. package/vendor/@akanjs/native/CHANGELOG.md +3 -0
  40. package/vendor/@akanjs/native/native/desktop/Cargo.lock +1 -0
  41. package/vendor/@akanjs/native/native/desktop/Cargo.toml +2 -0
  42. package/vendor/@akanjs/native/native/desktop/src/external.rs +27 -3
  43. package/vendor/@akanjs/native/native/desktop/src/json.rs +14 -1
  44. package/vendor/@akanjs/native/native/desktop/src/linux/external.rs +107 -7
  45. package/vendor/@akanjs/native/plugins/external-view/src/index.ts +2 -2
  46. package/vendor/@akanjs/native/plugins/single-instance/src/socket.ts +113 -24
package/CHANGELOG.md CHANGED
@@ -205,6 +205,14 @@
205
205
  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.
206
206
 
207
207
  - 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.
208
+ - 4a4c62b: A boot no longer drops an index akan built that the release no longer declares. Since 3.1.0 the first instance of a new release to boot, `akan migrate` included, dropped those indexes while instances of the previous release were still serving queries from them. An older instance that restarted during the rollout, or after a rollback, built the index again (on SQLite a blocking build inside its boot), and the next new boot dropped it again.
209
+
210
+ - Each boot keeps such an index and warns about each one. A unique one is named as unique, because it keeps refusing a duplicate of its key that the new release would write.
211
+ - `akan migrate <app> indexes` (`bun main.js ops migrate indexes` in a built image) lists them. `akan migrate <app> prune-indexes` drops them, concurrently on Postgres. Run it once no instance of an earlier release is serving. An index made by hand, outside akan, is never listed or dropped.
212
+ - Through the ops channel, `prune-indexes` needs a token with a `sub`, like `apply` and `rollback`.
213
+
214
+ Upgrade step: after every instance runs this release, run `prune-indexes` once to drop what earlier releases left; until then the warnings at boot list those indexes. `migrationActions` and `MigrationAction` gain `indexes` and `prune-indexes`, so code that switches over every action needs the two new cases; nothing else changes for a caller.
215
+
208
216
  - 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`.
209
217
 
210
218
  - **`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.
@@ -236,6 +244,14 @@
236
244
 
237
245
  Upgrading: `WebsocketAdaptor.onRecovered` now hands its handler the rooms held on the server, `(rooms: string[]) => void`. A custom adaptor that implements `onRecovered` must call the handler with every room a socket on the server is still in, live rooms included, and only once events published to those rooms reach the server again, since each room refetches on it. Code that only reads `WebsocketResData` needs no change beyond handling, or ignoring, `type: "resync"`.
238
246
 
247
+ - ce90ad0: A page's `.head()` can now set its own `theme-color`, and a level that writes an image no longer inherits the image tags of the one above it.
248
+
249
+ - A `<meta name="theme-color">` a `.head()` writes replaces the root `.viewport({ themeColor })`'s tags, in the server render, after hydration and across client navigation. A page without its own gets the root's back.
250
+ - A level that writes `og:image` drops the `og:image:*` tags (`width`, `height`, `alt`, `type`) it inherits and keeps its own. `twitter:image` and its `twitter:image:*` tags merge the same way.
251
+ - Only `.head()` merges. A `<title>` or `<meta>` written inside a component renders beside the merged head, so a second `<title>` can reach the document. The `pageRule` guideline now says so.
252
+
253
+ Behaviour is unchanged for a page that sets neither a theme-color nor an image. The api report lists one new `ViewportMeta` static; no upgrade step is needed.
254
+
239
255
  - bc5fdb0: `--akan-theme-color` on the root now drives the browser's `theme-color`, and a native app's status bar icons when the app names the `appearance` plugin.
240
256
 
241
257
  - **The variable outranks the root layout's `.viewport({ themeColor })`.** Set it per theme beside the tokens (`--akan-theme-color: var(--background)`), or at run time on `document.documentElement.style`. The page reads it again when the root's `style`, `class` or `data-theme` changes, or the OS scheme flips. With neither the variable nor a `themeColor`, no tag is written, as before.
@@ -281,6 +297,12 @@
281
297
  - **The `akan-service` skill** carries a recipe for pages backed by an external HTTP API: an `adapt()` adapter in `srvkit/` that reads its base URL at boot, a `lib/_<service>` service, a `Public` `query(Any, { nullable: true })` endpoint and its dictionary label, and the page that calls it.
282
298
  - **The README's "Inside an existing repository"** runs the creator through `npx -y bun@1.4.4 x …` on a host with only Node and npm, so nothing global is written. It also gives copy-ready `build` and `start` scripts, says a fresh clone builds without a committed env file, and says which environment a `.env`-less build is for and what a deployed host sets instead.
283
299
 
300
+ - 6fc8a60: A toast now shows above a modal the floating `Agent.Chat` opened, and a question from the agent leaves focus and Escape to that modal.
301
+
302
+ - **Toasts top every overlay but Reconnect.** `overlayZ.toast` moves from 140 to 180, above the agent panel (150), a modal the panel opened (160) and one a card opened (170), so a toast reporting what that modal's controls did is no longer hidden behind it.
303
+ - **A question no longer pulls focus out of an overlay.** When `askUser` puts a question up while focus sits in a modal, sheet, menu or popconfirm, focus stays there, so typing meant for the modal no longer lands in the composer and Enter no longer sends it as the answer. Opening the panel still focuses the composer.
304
+ - **Escape closes one layer at a time.** With a modal, sheet or popconfirm open from the panel or from a card, Escape in the composer closes that overlay through its own close, `confirmClose` included, and only the next Escape closes the panel. It used to close the panel and the modal together, skipping `confirmClose`.
305
+
284
306
  - f5d1e63: A restored chat transcript that ends on an unanswered `askUser` call now opens on that question instead of closing it. This covers a server run that parked on a question while no chat was open, and a page reloaded mid-question.
285
307
 
286
308
  - The session's `pendingQuestion` holds the question, so `Agent.Chat` draws its card and the composer answers it as usual.
@@ -713,6 +735,7 @@
713
735
  **Upgrading.** The solid SQLite open used to reject with SQLite's error itself. Code that matched that error's `code` (`SQLITE_BUSY` or `SQLITE_LOCKED`) now finds it on `error.cause`. You can also branch on `AkanError.is(error, "databaseLocked")`.
714
736
 
715
737
  - 5757156: During a server render, a `fetch.*` query shares a request only with calls that end up with the same `timeout` and `retry`: the call's own, or else its endpoint's timeout and its client's (`clone({ retry })`, `setTimeout`). Before, the render shared one request between every call with the same endpoint, arguments and credential, from any client, so the first call's deadline and retry policy applied to all of them. A page's `fetch.isMemoOpen({ timeout: 3_000 })` after a layout's `fetch.isMemoOpen()` waited as long as the layout's call did, up to the client's 30 s default, and a page's `fetch.clone({ retry: { attempts: 4 } })` call ran without retries. Calls that pass no options still share one request per render, as before. The browser's in-flight sharing keys the same way, so a call naming `retry: false` (the default) now joins one that names none.
738
+ - fd125b0: A query that names the default 30 s timeout now shares its request with one that names none, and two queries whose `retry` policies hold the same fields in a different order share theirs, both in a server render and in the browser.
716
739
  - 9a2a8c9: The build refuses a `LevelBoundary` or `McpAppRoot` export on an app's root layout: `page/_layout.tsx`, or a grouped or base-path root layout. Akan.js defines both on the root layout it generates and reads neither from an app's layout, so such an export was silently ignored. The error names the export and the file and says why. Remove the export; it never took effect.
717
740
 
718
741
  `akanjs/common` exports `GENERATED_ROOT_LAYOUT_EXPORTS`, the set of those names.
@@ -1025,6 +1048,7 @@
1025
1048
  - **`ssr: "block"` writes every boundary in place,** so a blocking page never shows its `.loading()` fallback.
1026
1049
  - **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.
1027
1050
 
1051
+ - fd125b0: `akanjs/server` exports `StageFailedError`, the error a failed DI startup stage throws, so `StageFailedError.is(error)` narrows to a type whose `errors` holds each failed task's error without a cast.
1028
1052
  - 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.
1029
1053
  - 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.
1030
1054
  - 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.
@@ -16,6 +16,7 @@ export class RouteHead {
16
16
  ]);
17
17
 
18
18
  static readonly #pageIdentityKeys = new Set(["link:canonical", "meta:property:og:url"]);
19
+ static readonly #imageKeys = ["meta:property:og:image", "meta:name:twitter:image", "meta:property:twitter:image"];
19
20
 
20
21
  static merge(levels: ResolveHeadResult[]): ResolveHeadResult {
21
22
  const present = levels.filter((level) => RouteHead.#nodeOf(level) != null || RouteHead.#snapshotOf(level));
@@ -179,7 +180,9 @@ export class RouteHead {
179
180
  .map((item, idx) => ({ item, level, idx }))
180
181
  .filter(({ item }) => {
181
182
  const key = keyOf(item);
182
- return !key || owner.get(key) === level;
183
+ if (!key) return true;
184
+ const imageOwner = RouteHead.#imageKeys.find((imageKey) => key.startsWith(`${imageKey}:`));
185
+ return owner.get(key) === level && (!imageOwner || (owner.get(imageOwner) ?? level) <= level);
183
186
  }),
184
187
  );
185
188
  }
@@ -1,4 +1,4 @@
1
- import type { RouteViewport } from "./csrTypes";
1
+ import type { AkanHeadSnapshotNode, RouteViewport } from "./csrTypes";
2
2
 
3
3
  export interface ThemeColorTag {
4
4
  content: string;
@@ -9,6 +9,8 @@ export interface ThemeColorTag {
9
9
  export class ViewportMeta {
10
10
  static readonly #offMedia = "not all";
11
11
  static readonly #ownAttr = "data-akan-theme-color";
12
+ static readonly #mutedAttr = "data-akan-media";
13
+ static readonly #viewportAttr = "data-akan-viewport";
12
14
  static readonly #themeColorVar = "--akan-theme-color";
13
15
 
14
16
  static content(viewport: RouteViewport | undefined, { native = false }: { native?: boolean } = {}): string {
@@ -33,6 +35,13 @@ export class ViewportMeta {
33
35
  return first ? [{ content: first }] : [];
34
36
  }
35
37
 
38
+ static themeColorNodes(viewport: RouteViewport | undefined, theme?: string): AkanHeadSnapshotNode[] {
39
+ return ViewportMeta.themeColors(viewport, theme).map(({ content, media }) => ({
40
+ tag: "meta",
41
+ attrs: { name: "theme-color", content, ...(media ? { media } : {}), [ViewportMeta.#viewportAttr]: "" },
42
+ }));
43
+ }
44
+
36
45
  static applyContent(viewport: RouteViewport | undefined, { native = false }: { native?: boolean } = {}) {
37
46
  const meta = ViewportMeta.#ensureMeta("viewport");
38
47
  const content = ViewportMeta.content(viewport, { native });
@@ -45,13 +54,26 @@ export class ViewportMeta {
45
54
 
46
55
  static applyThemeColor(viewport: RouteViewport | undefined, theme?: string): string | null {
47
56
  const runtime = ViewportMeta.runtimeThemeColor();
48
- const tags = runtime ? [{ content: runtime }] : ViewportMeta.themeColors(viewport, theme);
49
57
  const existing = [...document.head.querySelectorAll<HTMLMetaElement>('meta[name="theme-color"]')];
58
+ const authored = existing.filter(
59
+ (meta) => !meta.hasAttribute(ViewportMeta.#ownAttr) && !meta.hasAttribute(ViewportMeta.#viewportAttr),
60
+ );
61
+ if (!runtime && authored.length) {
62
+ for (const meta of existing) {
63
+ if (meta.hasAttribute(ViewportMeta.#ownAttr)) meta.remove();
64
+ else if (meta.hasAttribute(ViewportMeta.#viewportAttr)) ViewportMeta.#mute(meta);
65
+ else ViewportMeta.#unmute(meta);
66
+ }
67
+ return ViewportMeta.#inEffect(
68
+ authored.map((meta) => ({ content: meta.content, media: meta.getAttribute("media") })),
69
+ );
70
+ }
71
+ const tags = runtime ? [{ content: runtime }] : ViewportMeta.themeColors(viewport, theme);
50
72
  if (!tags.length) {
51
73
  for (const meta of existing) if (meta.hasAttribute(ViewportMeta.#ownAttr)) meta.remove();
52
74
  return null;
53
75
  }
54
- const inEffect = tags.find((tag) => !tag.media || window.matchMedia(tag.media).matches)?.content ?? null;
76
+ const inEffect = ViewportMeta.#inEffect(tags);
55
77
  const live = existing.filter((meta) => meta.getAttribute("media") !== ViewportMeta.#offMedia);
56
78
  const isCurrent =
57
79
  live.length === tags.length &&
@@ -62,7 +84,7 @@ export class ViewportMeta {
62
84
 
63
85
  for (const meta of existing) {
64
86
  if (meta.hasAttribute(ViewportMeta.#ownAttr)) meta.remove();
65
- else meta.setAttribute("media", ViewportMeta.#offMedia);
87
+ else ViewportMeta.#mute(meta);
66
88
  }
67
89
  for (const tag of tags) {
68
90
  const meta = document.createElement("meta");
@@ -75,6 +97,26 @@ export class ViewportMeta {
75
97
  return inEffect;
76
98
  }
77
99
 
100
+ static #inEffect(tags: { content: string; media?: string | null }[]): string | null {
101
+ return tags.find((tag) => !tag.media || window.matchMedia(tag.media).matches)?.content ?? null;
102
+ }
103
+
104
+ static #mute(meta: HTMLMetaElement) {
105
+
106
+ if (meta.getAttribute("media") === ViewportMeta.#offMedia) return;
107
+ if (!meta.hasAttribute(ViewportMeta.#mutedAttr))
108
+ meta.setAttribute(ViewportMeta.#mutedAttr, meta.getAttribute("media") ?? "");
109
+ meta.setAttribute("media", ViewportMeta.#offMedia);
110
+ }
111
+
112
+ static #unmute(meta: HTMLMetaElement) {
113
+ const media = meta.getAttribute(ViewportMeta.#mutedAttr);
114
+ if (media === null) return;
115
+ if (media) meta.setAttribute("media", media);
116
+ else meta.removeAttribute("media");
117
+ meta.removeAttribute(ViewportMeta.#mutedAttr);
118
+ }
119
+
78
120
  static watchThemeColor(apply: () => void): () => void {
79
121
  let frame = 0;
80
122
  const schedule = () => {
@@ -85,10 +127,18 @@ export class ViewportMeta {
85
127
  };
86
128
  const observer = new MutationObserver(schedule);
87
129
  observer.observe(document.documentElement, { attributes: true, attributeFilter: ["style", "class", "data-theme"] });
130
+ const headObserver = new MutationObserver(schedule);
131
+ headObserver.observe(document.head, {
132
+ childList: true,
133
+ subtree: true,
134
+ attributes: true,
135
+ attributeFilter: ["content", "media", "name"],
136
+ });
88
137
  const scheme = window.matchMedia("(prefers-color-scheme: dark)");
89
138
  scheme.addEventListener("change", schedule);
90
139
  return () => {
91
140
  observer.disconnect();
141
+ headObserver.disconnect();
92
142
  scheme.removeEventListener("change", schedule);
93
143
  if (frame) cancelAnimationFrame(frame);
94
144
  };
@@ -397,13 +397,10 @@ export class FetchClient {
397
397
  const requestQuery = (requestSignal?: AbortSignal) =>
398
398
  this.http.get(url, { headers, baseUrl, timeout, retry: option?.retry, signal: requestSignal });
399
399
 
400
+ const budget = { timeout: timeout ?? this.http.timeout, retry: option?.retry ?? this.http.retry };
400
401
  const claim = baseUrl
401
402
  ? { value: requestQuery(signal), owned: true }
402
- : this.#claimQuery(makeRequestQueryCacheKey(this.origin, url, headers), requestQuery, {
403
- signal,
404
- timeout,
405
- retry: option?.retry,
406
- });
403
+ : this.#claimQuery(makeRequestQueryCacheKey(this.origin, url, headers, budget), requestQuery, signal);
407
404
  recordRequestQuery({ key, args: Object.fromEntries(argMap), returns: endpoint.returns, value: claim.value });
408
405
  const response = await this.#untilAborted(claim.value, signal);
409
406
  const payload = claim.owned ? response : deepCopy(response);
@@ -440,12 +437,7 @@ export class FetchClient {
440
437
  }
441
438
  }
442
439
 
443
- #claimQuery(
444
- cacheKey: string,
445
- requestQuery: (signal?: AbortSignal) => Promise<unknown>,
446
- { signal, timeout, retry }: { signal?: AbortSignal; timeout?: number | false; retry?: RetryPolicy | false },
447
- ) {
448
- const claimKey = `${cacheKey}\n${timeout ?? this.http.timeout}\n${JSON.stringify(retry ?? this.http.retry)}`;
440
+ #claimQuery(claimKey: string, requestQuery: (signal?: AbortSignal) => Promise<unknown>, signal?: AbortSignal) {
449
441
  if (getRequestStore()) return claimRequestQuery(claimKey, () => requestQuery());
450
442
  if (typeof window === "undefined") return { value: requestQuery(signal), owned: true };
451
443
  return { value: this.#inflight.claim(claimKey, requestQuery, signal), owned: true };
@@ -6,6 +6,7 @@ import {
6
6
  type RestoredError,
7
7
  restoreRemoteError,
8
8
  } from "./remoteError";
9
+ import { DEFAULT_TIMEOUT_MS } from "./requestScope";
9
10
 
10
11
  export interface HttpClientOptions {
11
12
  headers?: Record<string, string>;
@@ -47,8 +48,6 @@ const unexpectedResponseKey = "base.error.unexpectedResponse";
47
48
  const dictionaryErrorKey = /^\w+\.error\./;
48
49
  const transportDetailLimit = 200;
49
50
 
50
- const DEFAULT_TIMEOUT_MS = 30_000;
51
-
52
51
  export class HttpClient {
53
52
  static readonly #logger = new Logger("HttpClient");
54
53
  readonly baseUrl: string;
@@ -1,12 +1,21 @@
1
1
  import { getEnv, getWsPrefix } from "akanjs/base";
2
- import { trimTrailingSlashes } from "akanjs/common";
2
+ import { type RetryPolicy, trimTrailingSlashes } from "akanjs/common";
3
3
 
4
- export const makeRequestQueryCacheKey = (origin: string, url: string, headers: Record<string, string>): string => {
4
+ export const DEFAULT_TIMEOUT_MS = 30_000;
5
+
6
+ export const makeRequestQueryCacheKey = (
7
+ origin: string,
8
+ url: string,
9
+ headers: Record<string, string>,
10
+ budget: { timeout?: number | false; retry: RetryPolicy | false },
11
+ ): string => {
5
12
  return JSON.stringify({
6
13
  method: "GET",
7
14
  origin,
8
15
  url,
9
16
  headers: Object.entries(headers).sort(([a], [b]) => a.localeCompare(b)),
17
+ timeout: budget.timeout ?? DEFAULT_TIMEOUT_MS,
18
+ retry: JSON.stringify(budget.retry, Object.keys(budget.retry).sort()),
10
19
  });
11
20
  };
12
21
  export const deepCopy = <T>(value: T): T => {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "akanjs",
3
- "version": "3.2.0-rc.24",
3
+ "version": "3.2.0-rc.26",
4
4
  "sourceType": "module",
5
5
  "type": "module",
6
6
  "publishConfig": {
@@ -0,0 +1,10 @@
1
+ import { AkanError } from "akanjs/base";
2
+
3
+ export class StageFailedError extends AkanError<"stageFailed"> {
4
+ readonly errors: Error[];
5
+
6
+ constructor(message: string, errors: Error[]) {
7
+ super("stageFailed", message);
8
+ this.errors = errors;
9
+ }
10
+ }
@@ -3,6 +3,7 @@ import { lowerlize, toError } from "akanjs/common";
3
3
  import { ConstantRegistry, type FieldObject } from "akanjs/constant";
4
4
  import type { InjectInfo } from "akanjs/service";
5
5
  import type { DatabaseModule, ServiceModule } from "../akanLib";
6
+ import { StageFailedError } from "./stageFailedError";
6
7
 
7
8
  interface StageTask {
8
9
  label: string;
@@ -142,7 +143,7 @@ export const throwStageFailures = (
142
143
  const summary = failures.map((f) => ` • ${f.label}: ${reasonMessage(f.reason)}`).join("\n");
143
144
  const errors = failures.map((f) => toError(f.reason));
144
145
  const message = `[DI:${stageLabel}] ${failures.length}/${total} task(s) failed:\n${summary}`;
145
- throw Object.assign(new AkanError("stageFailed", message), { errors });
146
+ throw new StageFailedError(message, errors);
146
147
  };
147
148
 
148
149
  export const reasonMessage = (reason: unknown): string => {
package/server/index.ts CHANGED
@@ -112,6 +112,7 @@ export {
112
112
  type SliceNode,
113
113
  type Unserializable,
114
114
  } from "./devtools";
115
+ export { StageFailedError } from "./di/stageFailedError";
115
116
  export type { ChangeBatch, ChangeKind } from "./hmr/wsHub";
116
117
  export {
117
118
  MachineAccount,
@@ -150,6 +151,7 @@ export {
150
151
  type MigrationPatch,
151
152
  type MigrationPlan,
152
153
  type MigrationPlanResult,
154
+ type MigrationPruneResult,
153
155
  MigrationPulse,
154
156
  type MigrationRevertOutcome,
155
157
  type MigrationRewriteOption,
@@ -1,8 +1,9 @@
1
1
  import { parseArgs } from "node:util";
2
+ import type { UndeclaredIndex } from "akanjs/service";
2
3
  import { MigrationError, type MigrationErrorCode } from "./migrationError";
3
4
  import type { MigrationListItem, MigrationRunner } from "./migrationRunner";
4
5
 
5
- export const migrationActions = ["list", "plan", "apply", "verify", "rollback"] as const;
6
+ export const migrationActions = ["list", "plan", "apply", "verify", "rollback", "indexes", "prune-indexes"] as const;
6
7
  export type MigrationAction = (typeof migrationActions)[number];
7
8
  const migrationOptions = ["param", "expect", "actor", "items"] as const;
8
9
  type MigrationOption = (typeof migrationOptions)[number];
@@ -35,7 +36,10 @@ export class MigrationCommand {
35
36
  apply: ["param", "expect", "actor"],
36
37
  verify: ["param", "actor"],
37
38
  rollback: ["actor"],
39
+ indexes: [],
40
+ "prune-indexes": ["actor"],
38
41
  };
42
+ static readonly #untargeted = new Set<MigrationAction>(["list", "indexes", "prune-indexes"]);
39
43
 
40
44
  static usageOf(invokedAs = "ops migrate") {
41
45
  return [
@@ -45,6 +49,8 @@ export class MigrationCommand {
45
49
  ` ${invokedAs} apply <id> [--param <name>=<value>]... [--expect <planHash>] [--actor <id>] [--json]`,
46
50
  ` ${invokedAs} verify <id> [--param <name>=<value>]... [--actor <id>] [--json]`,
47
51
  ` ${invokedAs} rollback <applyRunId|id> [--actor <id>] [--json]`,
52
+ ` ${invokedAs} indexes [--json]`,
53
+ ` ${invokedAs} prune-indexes [--actor <id>] [--json]`,
48
54
  ].join("\n");
49
55
  }
50
56
 
@@ -59,7 +65,7 @@ export class MigrationCommand {
59
65
  if (!migrationActions.includes(name as MigrationAction))
60
66
  throw new MigrationError("usage", `Unknown action "${name}"\n${usage}`);
61
67
  const action = name as MigrationAction;
62
- if (action === "list" ? target : !target)
68
+ if (MigrationCommand.#untargeted.has(action) ? target : !target)
63
69
  throw new MigrationError("usage", `${action} ${target ? "takes no id" : "needs an id"}\n${usage}`);
64
70
  if (extra.length) throw new MigrationError("usage", `Unexpected arguments: ${extra.join(" ")}`);
65
71
  const refused = migrationOptions.find(
@@ -85,6 +91,19 @@ export class MigrationCommand {
85
91
  if (action === "list") return { ok: true, action, migrations: await runner.list() };
86
92
  if (action === "plan") return { ok: true, action, ...(await runner.plan(target, params, { actor, items })) };
87
93
  if (action === "rollback") return { ok: true, action, ...(await runner.rollback(target, { actor })) };
94
+ if (action === "indexes") return { ok: true, action, indexes: await runner.undeclaredIndexes() };
95
+ if (action === "prune-indexes") {
96
+ const { dropped, failed } = await runner.pruneIndexes({ actor });
97
+ if (!failed.length) return { ok: true, action, dropped, failed };
98
+ return {
99
+ ok: false,
100
+ action,
101
+ code: "failed",
102
+ error: `${failed.length} of the indexes could not be dropped`,
103
+ dropped,
104
+ failed,
105
+ };
106
+ }
88
107
  const result =
89
108
  action === "apply"
90
109
  ? await runner.apply(target, params, { expect, actor })
@@ -128,6 +147,8 @@ export class MigrationCommand {
128
147
  if (json) return JSON.stringify(result);
129
148
  if (result.ok && result.action === "list")
130
149
  return MigrationCommand.#renderList(result.migrations as MigrationListItem[]);
150
+ if (result.ok && result.action === "indexes")
151
+ return MigrationCommand.#renderIndexes(result.indexes as UndeclaredIndex[]);
131
152
  return JSON.stringify(result, null, 2);
132
153
  }
133
154
 
@@ -146,6 +167,14 @@ export class MigrationCommand {
146
167
  .join("\n");
147
168
  }
148
169
 
170
+ static #renderIndexes(indexes: UndeclaredIndex[]) {
171
+ if (!indexes.length) return "This release declares every index an earlier one built";
172
+ return [
173
+ "Kept for an earlier release; drop them with prune-indexes once no instance runs one:",
174
+ ...indexes.map(({ table, name, unique }) => `${unique ? "unique" : " "} ${table} ${name}`),
175
+ ].join("\n");
176
+ }
177
+
149
178
  static #parseArgs(argv: string[], usage: string) {
150
179
  try {
151
180
  return parseArgs({
@@ -1,6 +1,13 @@
1
1
  import { Logger } from "akanjs/common";
2
2
  import { createDocumentId, sanitizeJson } from "akanjs/document";
3
- import { type DatabaseAdaptor, descriptorHash, stableJson } from "akanjs/service";
3
+ import {
4
+ type DatabaseAdaptor,
5
+ descriptorHash,
6
+ type PrunedIndex,
7
+ type SqlDocumentStore,
8
+ stableJson,
9
+ type UndeclaredIndex,
10
+ } from "akanjs/service";
4
11
  import { MigrationChangeLog } from "./migrationChangeLog";
5
12
  import { MigrationChanges, type MigrationSkip } from "./migrationChanges";
6
13
  import { MigrationContext, type MigrationGet } from "./migrationContext";
@@ -79,6 +86,11 @@ export interface MigrationRollbackResult {
79
86
  runs: MigrationRollbackRun[];
80
87
  }
81
88
 
89
+ export interface MigrationPruneResult {
90
+ dropped: UndeclaredIndex[];
91
+ failed: PrunedIndex[];
92
+ }
93
+
82
94
  export class MigrationRunner {
83
95
  static readonly defaultItemNum = 100;
84
96
  readonly #entries: MigrationEntry[];
@@ -129,6 +141,29 @@ export class MigrationRunner {
129
141
  );
130
142
  }
131
143
 
144
+ async undeclaredIndexes(): Promise<UndeclaredIndex[]> {
145
+ const indexes: UndeclaredIndex[] = [];
146
+ for (const store of this.#stores()) indexes.push(...(await store.undeclaredIndexes()));
147
+ return indexes;
148
+ }
149
+
150
+ async pruneIndexes({ actor = null }: { actor?: string | null } = {}): Promise<MigrationPruneResult> {
151
+ const pruned: PrunedIndex[] = [];
152
+ for (const store of this.#stores()) pruned.push(...(await store.pruneUndeclaredIndexes()));
153
+ const failed = pruned.filter(({ error }) => error !== undefined);
154
+ const dropped = pruned.filter(({ error }) => error === undefined);
155
+ this.#logger.info(
156
+ `prune-indexes${actor ? ` for ${actor}` : ""}: ${dropped.length} dropped, ${failed.length} failed to drop`,
157
+ );
158
+ return { dropped, failed };
159
+ }
160
+
161
+ #stores(): SqlDocumentStore[] {
162
+ const stores = this.#database.stores?.();
163
+ if (!stores) throw new MigrationError("failed", "This database adaptor keeps no model stores to read indexes from");
164
+ return stores;
165
+ }
166
+
132
167
  async plan(
133
168
  id: string,
134
169
  raw: Record<string, string> = {},
@@ -54,7 +54,7 @@ export class MigrateJobs {
54
54
  return `id must match ${MigrateJobs.idPattern.source}`;
55
55
  if (typeof action !== "string" || !migrationActions.includes(action as MigrationAction))
56
56
  return `action must be one of ${migrationActions.join(", ")}`;
57
- if ((action === "apply" || action === "rollback") && !actor)
57
+ if ((action === "apply" || action === "rollback" || action === "prune-indexes") && !actor)
58
58
  return `${action} needs the token's sub, the person it runs for`;
59
59
  if (target !== undefined && (typeof target !== "string" || !MigrateJobs.targetPattern.test(target)))
60
60
  return `target must match ${MigrateJobs.targetPattern.source}`;
@@ -72,7 +72,7 @@ export class MigrateJobs {
72
72
  ...entries.map(([name, value]) => `--param=${name}=${value as string}`),
73
73
  ...(expect ? [`--expect=${expect}`] : []),
74
74
  ...(items === undefined ? [] : [`--items=${items}`]),
75
- ...(actor && action !== "list" ? [`--actor=${actor}`] : []),
75
+ ...(actor && action !== "list" && action !== "indexes" ? [`--actor=${actor}`] : []),
76
76
  "--json",
77
77
  ];
78
78
  return { id, action: action as MigrationAction, argv };
@@ -20,7 +20,7 @@ export class OpsCommand {
20
20
  "Usage:",
21
21
  " bun main.js ops snapshot [--id <id>] [--out <dir>] [--include-solid] [--db <file>] [--solid-db <file>] [--allow-plaintext] [--json]",
22
22
  " bun main.js ops restore <manifest.json> [--identity <file>] [--db <file>] [--solid-db <file>] [--allow-plaintext] [--force]",
23
- " bun main.js ops migrate [list|plan|apply|verify|rollback] [<id>] [--param <name>=<value>]... [--expect <planHash>] [--items <n>] [--actor <id>] [--json]",
23
+ " bun main.js ops migrate [list|plan|apply|verify|rollback|indexes|prune-indexes] [<id>] [--param <name>=<value>]... [--expect <planHash>] [--items <n>] [--actor <id>] [--json]",
24
24
  ].join("\n");
25
25
 
26
26
  static async run(argv: string[], host?: OpsHost): Promise<number> {
@@ -1,4 +1,4 @@
1
- import type { ResolvedHead, RouteRender, RouteViewport } from "akanjs/client";
1
+ import type { AkanHeadSnapshotNode, ResolvedHead, RouteRender, RouteViewport } from "akanjs/client";
2
2
  import { type AkanI18nConfig, getBasePathFromPathname, LocalePath } from "akanjs/common";
3
3
  import { untrackedRequest } from "akanjs/fetch";
4
4
  import type { ReactNode } from "react";
@@ -41,15 +41,8 @@ export class RscDocumentHead {
41
41
  return values.find((value) => value !== undefined);
42
42
  }
43
43
 
44
- renderViewport(viewport: RouteViewport | undefined, theme?: string): ReactNode {
45
- return (
46
- <>
47
- <meta key="viewport" name="viewport" content={ViewportMeta.content(viewport)} />
48
- {ViewportMeta.themeColors(viewport, theme).map(({ content, media }) => (
49
- <meta key={`theme-color:${media ?? ""}`} name="theme-color" content={content} media={media} />
50
- ))}
51
- </>
52
- );
44
+ renderViewport(viewport: RouteViewport | undefined): ReactNode {
45
+ return <meta key="viewport" name="viewport" content={ViewportMeta.content(viewport)} />;
53
46
  }
54
47
 
55
48
  async renderManifestLink(url: URL, renderRootLayouts: RouteRender[]): Promise<ReactNode> {
@@ -68,9 +61,11 @@ export class RscDocumentHead {
68
61
  snapshots,
69
62
  noindex = false,
70
63
  tags = null,
64
+ themeColors = [],
71
65
  }: {
72
66
  manifestLink: ReactNode;
73
67
  routeHead: ResolvedHead;
68
+ themeColors?: AkanHeadSnapshotNode[];
74
69
  snapshots?: RouteHeadSnapshots;
75
70
  noindex?: boolean;
76
71
  tags?: ReactNode[] | null;
@@ -83,14 +78,26 @@ export class RscDocumentHead {
83
78
  return (
84
79
  <>
85
80
  {ownsManifest ? null : manifestLink}
86
- <AkanRouteHeadReference layouts={snapshots.layouts} page={snapshots.page} />
81
+ <AkanRouteHeadReference
82
+ layouts={{
83
+ ...snapshots.layouts,
84
+ nodes: RouteHead.mergeSnapshots([themeColors, snapshots.layouts.nodes]).nodes,
85
+ }}
86
+ page={snapshots.page}
87
+ />
87
88
  </>
88
89
  );
89
90
  }
90
91
  const head = routeHead.node ?? this.renderDefaultHead();
91
92
  return (
92
93
  <>
93
- {RouteHead.mergeNodes([manifestLink, head, noindex ? RouteHead.noindexOver(head) : null, tags])}
94
+ {RouteHead.mergeNodes([
95
+ themeColors.map((node, idx) => <meta key={`theme-color:${idx}`} {...node.attrs} />),
96
+ manifestLink,
97
+ head,
98
+ noindex ? RouteHead.noindexOver(head) : null,
99
+ tags,
100
+ ])}
94
101
  {this.#renderLocaleAlternates(url)}
95
102
  </>
96
103
  );
@@ -3,6 +3,7 @@ import type { AkanI18nConfig, Logger } from "akanjs/common";
3
3
  import { setRequestFrameState, setRequestTheme, untrackedCookies, untrackedRequest } from "akanjs/fetch";
4
4
  import type { ReactNode } from "react";
5
5
  import { RouteHead } from "../client/route/RouteHead";
6
+ import { ViewportMeta } from "../client/viewportMeta";
6
7
  import { FallbackHead } from "./fallbackHead";
7
8
  import { resolveHeadResult } from "./head";
8
9
  import { type AdmittedNotFoundFallback, RouteElementComposer, type RouteNotFoundInPlace } from "./routeElementComposer";
@@ -100,7 +101,15 @@ export class RscRouteDocument {
100
101
  key="route-head"
101
102
  head={fallbackHead}
102
103
  until={gate?.opened ?? Promise.resolve()}
103
- render={(tags) => this.#head.renderHeadTags(url, { manifestLink, routeHead, noindex: true, tags })}
104
+ render={(tags) =>
105
+ this.#head.renderHeadTags(url, {
106
+ manifestLink,
107
+ routeHead,
108
+ noindex: true,
109
+ tags,
110
+ themeColors: ViewportMeta.themeColorNodes(viewport),
111
+ })
112
+ }
104
113
  />
105
114
  {this.#head.renderStylesheet(pathname)}
106
115
  </head>
@@ -173,12 +182,14 @@ export class RscRouteDocument {
173
182
  notFound: { ...notFound, head: fallbackHead },
174
183
  gate,
175
184
  });
185
+ const themeColors = ViewportMeta.themeColorNodes(viewport, themeColorTheme);
176
186
  const renderHead = async (tags: ReactNode[] | null) => {
177
187
  if (!tags)
178
188
  return this.#head.renderHeadTags(url, {
179
189
  manifestLink,
180
190
  routeHead: routeHead.layers.head,
181
191
  snapshots: routeHead.snapshots,
192
+ themeColors,
182
193
  });
183
194
  const layoutsHead = await RscRouteDocument.#resolveFallbackHead({
184
195
  kind: "not-found",
@@ -186,14 +197,20 @@ export class RscRouteDocument {
186
197
  params: match.params,
187
198
  searchParams,
188
199
  });
189
- return this.#head.renderHeadTags(url, { manifestLink, routeHead: layoutsHead, noindex: true, tags });
200
+ return this.#head.renderHeadTags(url, {
201
+ manifestLink,
202
+ routeHead: layoutsHead,
203
+ noindex: true,
204
+ tags,
205
+ themeColors,
206
+ });
190
207
  };
191
208
 
192
209
  const element = (
193
210
  <html lang={match.params.lang ?? this.#i18n.defaultLocale} suppressHydrationWarning>
194
211
  <head key="head">
195
212
  <meta key="charset" charSet="utf-8" />
196
- {this.#head.renderViewport(viewport, themeColorTheme)}
213
+ {this.#head.renderViewport(viewport)}
197
214
  <FallbackHead.Settled
198
215
  key="route-head"
199
216
  head={fallbackHead}
@@ -65,11 +65,13 @@ export type {
65
65
  DocumentStore,
66
66
  InsightSession,
67
67
  PostgresDatabaseConfig,
68
+ PrunedIndex,
68
69
  SearchConfig,
69
70
  SqlDialect,
70
71
  SqliteDatabaseConfig,
71
72
  SqlResultRows,
72
73
  TransferRow,
74
+ UndeclaredIndex,
73
75
  UpsertByIdOptions,
74
76
  } from "./sql/types";
75
77
  export { descriptorHash, stableJson } from "./sql/values";