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

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (130) hide show
  1. package/ARCHITECTURE.md +3 -3
  2. package/CHANGELOG.md +105 -1
  3. package/client/csrTypes.ts +13 -1
  4. package/client/frameConfig.ts +4 -2
  5. package/client/route/RouteHead.ts +11 -2
  6. package/client/router.ts +8 -4
  7. package/client/rscNavigation.ts +2 -3
  8. package/client/rscRoutePatch.ts +42 -0
  9. package/common/akanGraph.ts +1 -1
  10. package/common/types.ts +5 -0
  11. package/dictionary/base.dictionary.ts +1 -0
  12. package/fetch/client/fetchClient.ts +11 -16
  13. package/fetch/client/fetchHandle.ts +11 -1
  14. package/fetch/client/inflightQueries.ts +17 -0
  15. package/fetch/index.ts +1 -0
  16. package/fetch/staleReads.ts +27 -0
  17. package/fetch/streamedRead.ts +23 -0
  18. package/package.json +1 -1
  19. package/server/akanServer.ts +1 -1
  20. package/server/artifact/builderRpc.ts +22 -7
  21. package/server/artifact/ipcTypes.ts +9 -3
  22. package/server/devtools/README.md +4 -3
  23. package/server/devtools/devtoolsRouter.ts +9 -5
  24. package/server/devtools/studio/studioRoute.ts +18 -11
  25. package/server/head.tsx +4 -19
  26. package/server/routeElementComposer.tsx +86 -3
  27. package/server/routeState.ts +5 -1
  28. package/server/routeTreeBuilder.ts +1 -0
  29. package/server/rscClient.tsx +118 -21
  30. package/server/rscClientChunks.ts +62 -0
  31. package/server/rscClientFetch.ts +6 -1
  32. package/server/rscHeadPatch.ts +17 -56
  33. package/server/rscParkedRedirect.ts +23 -0
  34. package/server/rscPatchPlanner.ts +220 -0
  35. package/server/rscPrefetchCache.ts +39 -17
  36. package/server/rscResponse.ts +78 -0
  37. package/server/rscSegmentOutlet.tsx +24 -5
  38. package/server/rscSegmentOutletReference.ts +10 -12
  39. package/server/rscWorker.tsx +109 -154
  40. package/server/rscWorkerCache.ts +56 -0
  41. package/server/rscWorkerHost.ts +6 -8
  42. package/server/ssrTypes.ts +9 -0
  43. package/server/webRouter.ts +12 -89
  44. package/store/action.ts +282 -299
  45. package/store/actionErrorKey.ts +9 -0
  46. package/store/draftFlush.ts +5 -0
  47. package/store/draftStore.ts +2 -0
  48. package/store/formDrafts.ts +115 -0
  49. package/store/modelListPatch.ts +53 -0
  50. package/store/modelWriteGuard.ts +91 -0
  51. package/store/rootStore.ts +2 -0
  52. package/store/storeInstance.ts +9 -10
  53. package/store/uploadPoll.ts +52 -0
  54. package/store/withSelector.ts +6 -4
  55. package/types/client/csrTypes.d.ts +13 -1
  56. package/types/client/route/RouteHead.d.ts +5 -1
  57. package/types/client/router.d.ts +3 -2
  58. package/types/client/rscNavigation.d.ts +2 -2
  59. package/types/client/rscRoutePatch.d.ts +22 -0
  60. package/types/common/akanGraph.d.ts +1 -1
  61. package/types/common/types.d.ts +5 -0
  62. package/types/dictionary/base.dictionary.d.ts +1 -1
  63. package/types/dictionary/dictionary.d.ts +8 -8
  64. package/types/fetch/client/fetchHandle.d.ts +1 -0
  65. package/types/fetch/client/inflightQueries.d.ts +2 -0
  66. package/types/fetch/index.d.ts +1 -0
  67. package/types/fetch/staleReads.d.ts +8 -0
  68. package/types/fetch/streamedRead.d.ts +8 -0
  69. package/types/server/artifact/builderRpc.d.ts +8 -0
  70. package/types/server/artifact/ipcTypes.d.ts +8 -0
  71. package/types/server/devtools/devtoolsRouter.d.ts +4 -1
  72. package/types/server/devtools/studio/studioRoute.d.ts +2 -1
  73. package/types/server/head.d.ts +2 -2
  74. package/types/server/logging/rotatingLogWriter.d.ts +1 -1
  75. package/types/server/routeElementComposer.d.ts +24 -1
  76. package/types/server/routeState.d.ts +2 -0
  77. package/types/server/rscClient.d.ts +1 -0
  78. package/types/server/rscClientChunks.d.ts +10 -0
  79. package/types/server/rscHeadPatch.d.ts +5 -4
  80. package/types/server/rscParkedRedirect.d.ts +12 -0
  81. package/types/server/rscPatchPlanner.d.ts +49 -0
  82. package/types/server/rscPrefetchCache.d.ts +2 -2
  83. package/types/server/rscResponse.d.ts +9 -0
  84. package/types/server/rscSegmentOutlet.d.ts +5 -0
  85. package/types/server/rscSegmentOutletReference.d.ts +2 -1
  86. package/types/server/rscWorkerCache.d.ts +33 -1
  87. package/types/server/rscWorkerHost.d.ts +2 -6
  88. package/types/server/ssrTypes.d.ts +8 -0
  89. package/types/server/webRouter.d.ts +1 -7
  90. package/types/store/action.d.ts +10 -6
  91. package/types/store/actionErrorKey.d.ts +1 -0
  92. package/types/store/baseSt.d.ts +1 -295
  93. package/types/store/draftFlush.d.ts +4 -0
  94. package/types/store/formDrafts.d.ts +21 -0
  95. package/types/store/modelListPatch.d.ts +34 -0
  96. package/types/store/modelWriteGuard.d.ts +45 -0
  97. package/types/store/rootStore.d.ts +6 -0
  98. package/types/store/uploadPoll.d.ts +16 -0
  99. package/types/store/withSelector.d.ts +1 -1
  100. package/types/ui/Link/inputModality.d.ts +5 -0
  101. package/types/ui/Link/viewportPrefetch.d.ts +4 -0
  102. package/types/ui/Load/Edit_Client.d.ts +2 -0
  103. package/types/ui/Load/Pagination.d.ts +4 -1
  104. package/types/ui/Load/Stream.d.ts +7 -1
  105. package/types/ui/Load/StreamBoundary.d.ts +20 -0
  106. package/types/ui/Load/Units.d.ts +2 -0
  107. package/types/ui/Load/View.d.ts +2 -0
  108. package/types/webkit/nativeCore.d.ts +1 -0
  109. package/types/webkit/nativePurchase.d.ts +2 -1
  110. package/types/webkit/useFrameRuntime.d.ts +1 -0
  111. package/types/webkit/useGeoLocation.d.ts +1 -1
  112. package/types/webkit/usePurchase.d.ts +1 -1
  113. package/types/webkit/useTransitionStore.d.ts +1 -0
  114. package/ui/Button.tsx +1 -0
  115. package/ui/Link/inputModality.ts +21 -0
  116. package/ui/Link/prefetchIntent.ts +7 -25
  117. package/ui/Link/viewportPrefetch.ts +30 -0
  118. package/ui/Load/Edit_Client.tsx +7 -1
  119. package/ui/Load/Pagination.tsx +10 -2
  120. package/ui/Load/Stream.tsx +24 -4
  121. package/ui/Load/StreamBoundary.tsx +70 -0
  122. package/ui/Load/Units.tsx +3 -0
  123. package/ui/Load/View.tsx +3 -0
  124. package/ui/System/Client.tsx +28 -7
  125. package/webkit/nativeCore.ts +1 -0
  126. package/webkit/nativePurchase.ts +6 -3
  127. package/webkit/useCamera.tsx +22 -21
  128. package/webkit/useGeoLocation.tsx +4 -1
  129. package/webkit/usePurchase.tsx +4 -2
  130. package/webkit/useTransitionStore.ts +13 -0
@@ -0,0 +1,9 @@
1
+ import { isRecord } from "akanjs/common";
2
+
3
+ export const actionErrorKey = (error: unknown) => {
4
+ if (typeof error === "string") return error;
5
+ if (!isRecord(error)) return String(error);
6
+ if (typeof error.error === "string") return error.error;
7
+ if (typeof error.message === "string") return error.message;
8
+ return String(error);
9
+ };
@@ -0,0 +1,5 @@
1
+ export const flushDraftsKey = Symbol("akan.store.flushDrafts");
2
+
3
+ export interface DraftFlushing {
4
+ [flushDraftsKey]: () => void;
5
+ }
@@ -57,7 +57,9 @@ export class DraftStore {
57
57
  if (value === null || typeof value !== "object") return JSON.stringify(value) ?? "null";
58
58
  if (Array.isArray(value)) return `[${value.map((item) => DraftStore.#stableStringify(item)).join(",")}]`;
59
59
  const source = value as Record<string, unknown>;
60
+
60
61
  const entries = Object.keys(source)
62
+ .filter((key) => !["undefined", "function", "symbol"].includes(typeof source[key]))
61
63
  .sort()
62
64
  .map((key) => `${JSON.stringify(key)}:${DraftStore.#stableStringify(source[key])}`);
63
65
  return `{${entries.join(",")}}`;
@@ -0,0 +1,115 @@
1
+ import { Logger } from "akanjs/common";
2
+ import { type DraftFlushing, flushDraftsKey } from "./draftFlush";
3
+ import { DraftStore } from "./draftStore";
4
+ import type { DraftState } from "./state";
5
+ import type { SetGet } from "./types";
6
+
7
+ interface DraftSave {
8
+ restore: boolean;
9
+ }
10
+
11
+ export const makeFormDrafts = (refName: string, names: { modelDraft: string; modelForm: string }) => {
12
+
13
+ let openFormBase: object | null = null;
14
+ const draftSaves = new WeakMap<SetGet, Map<string, Set<DraftSave>>>();
15
+ function armDraft(this: SetGet, draftScope: string | undefined, form: object, baseUpdatedAt: string | null) {
16
+ openFormBase = draftScope ? form : null;
17
+ if (!draftScope) return null;
18
+
19
+ void DraftStore.reconcileIdentity();
20
+ return {
21
+ key: DraftStore.keyOf(refName, draftScope),
22
+ baseHash: DraftStore.formHash(refName, form),
23
+ baseUpdatedAt,
24
+ pending: null,
25
+ appliedAt: null,
26
+ };
27
+ }
28
+ async function applyDraft(this: SetGet, { auto }: { auto: boolean }) {
29
+ const draft = (this.get() as { [key: string]: any })[names.modelDraft] as DraftState | null;
30
+
31
+ if (!draft || draftSaves.get(this)?.has(draft.key)) return;
32
+ const record = await DraftStore.read(draft.key);
33
+ if (!record) return;
34
+
35
+ const current = (this.get() as { [key: string]: any })[names.modelDraft] as DraftState | null;
36
+ if (current?.key !== draft.key) return;
37
+
38
+ const openedForm = (this.get() as { [key: string]: any })[names.modelForm] as object;
39
+ if (DraftStore.contentHash(record.form) === DraftStore.contentHash(DraftStore.encodeForm(refName, openedForm))) {
40
+ await DraftStore.remove(draft.key);
41
+ return;
42
+ }
43
+
44
+ const draftedId = record.form.id;
45
+ if (typeof draftedId === "string" && draftedId && draftedId !== (openedForm as { id?: unknown }).id) {
46
+ await DraftStore.remove(draft.key);
47
+ return;
48
+ }
49
+ let form: object;
50
+ try {
51
+ form = DraftStore.decodeForm(refName, record.form);
52
+ } catch {
53
+
54
+ await DraftStore.remove(draft.key);
55
+ return;
56
+ }
57
+ const savedAt = new Date(record.savedAt);
58
+ if (auto || record.baseUpdatedAt === draft.baseUpdatedAt) {
59
+ this.set({ [names.modelForm]: form, [names.modelDraft]: { ...draft, appliedAt: savedAt } });
60
+ return;
61
+ }
62
+ this.set({ [names.modelDraft]: { ...draft, pending: { savedAt, form } } });
63
+ }
64
+
65
+ const forgetDraft = (ctx: SetGet, key: string) => {
66
+ for (const save of draftSaves.get(ctx)?.get(key) ?? []) save.restore = false;
67
+ void DraftStore.remove(key);
68
+ };
69
+ const clearDraft = (ctx: SetGet, draft: DraftState | null) => {
70
+ openFormBase = null;
71
+ if (draft) forgetDraft(ctx, draft.key);
72
+ return null;
73
+ };
74
+ const holdsSavedForm = (record: { form: Record<string, unknown> }, form: object) =>
75
+ DraftStore.contentHash(record.form) === DraftStore.contentHash(DraftStore.encodeForm(refName, form));
76
+ const restoreSavedDraft = async (draft: DraftState, form: object) => {
77
+
78
+ if ((await DraftStore.read(draft.key)) || DraftStore.formHash(refName, form) === draft.baseHash) return;
79
+ await DraftStore.write(draft.key, {
80
+ v: 1,
81
+ savedAt: new Date().toISOString(),
82
+ baseUpdatedAt: draft.baseUpdatedAt,
83
+ form: DraftStore.encodeForm(refName, form),
84
+ });
85
+ };
86
+
87
+ const savingDraft = async <T>(ctx: SetGet, draft: DraftState | null, form: object, save: () => Promise<T>) => {
88
+ if (!draft) return await save();
89
+
90
+ (ctx as SetGet & Partial<DraftFlushing>)[flushDraftsKey]?.();
91
+ const saves = draftSaves.get(ctx) ?? new Map<string, Set<DraftSave>>();
92
+ draftSaves.set(ctx, saves);
93
+ const keySaves = saves.get(draft.key) ?? new Set<DraftSave>();
94
+ saves.set(draft.key, keySaves);
95
+ const thisSave: DraftSave = { restore: true };
96
+ keySaves.add(thisSave);
97
+ try {
98
+ const answer = await save();
99
+
100
+ const record = await DraftStore.read(draft.key);
101
+ if (record && holdsSavedForm(record, form)) await DraftStore.remove(draft.key);
102
+ return answer;
103
+ } catch (error) {
104
+ if (thisSave.restore)
105
+ await restoreSavedDraft(draft, form).catch((restoreError: unknown) => {
106
+ Logger.warn(`Failed to restore the ${refName} form draft: ${String(restoreError)}`);
107
+ });
108
+ throw error;
109
+ } finally {
110
+ keySaves.delete(thisSave);
111
+ if (!keySaves.size) saves.delete(draft.key);
112
+ }
113
+ };
114
+ return { formBase: () => openFormBase, armDraft, applyDraft, forgetDraft, clearDraft, savingDraft };
115
+ };
@@ -0,0 +1,53 @@
1
+ import { DataList } from "akanjs/base";
2
+ import type { DynamicRecord } from "akanjs/common";
3
+ import { type BaseInsight, type BaseObject, type ConstantModel, withSharedInstances } from "akanjs/constant";
4
+ import type { LiveEventPayload, SerializedSlice } from "akanjs/signal";
5
+ import type { sliceKeysOf } from "./sliceKeys";
6
+ import type { SetGet } from "./types";
7
+
8
+ type ModelRow = BaseObject;
9
+ interface ListPatchSource {
10
+ cnst: ConstantModel;
11
+ names: { model: string; modelList: string; modelListLoading: string; modelInsight: string };
12
+ slices: { sliceName: string; keys: ReturnType<typeof sliceKeysOf>; slice: SerializedSlice }[];
13
+ }
14
+
15
+ export const makeModelListPatches = ({ cnst, names, slices }: ListPatchSource) => {
16
+ const isLiveSlice = (sliceName: string) => !!slices.find((entry) => entry.sliceName === sliceName)?.slice.live;
17
+
18
+ const createdListPatchOf = (sliceName: string, model: ModelRow, seen: { [key: string]: unknown }) => {
19
+ const listKey = sliceName.replace(names.model, names.modelList);
20
+ if (isLiveSlice(sliceName) || seen[sliceName.replace(names.model, names.modelListLoading)] || !seen[listKey])
21
+ return {};
22
+ const insightKey = sliceName.replace(names.model, names.modelInsight);
23
+ const modelInsight = seen[insightKey] as BaseInsight & { count: number };
24
+ return {
25
+ [listKey]: new DataList([model, ...(seen[listKey] as DataList<ModelRow>)]),
26
+ [insightKey]: new cnst.insight().set({ ...modelInsight, count: modelInsight.count + 1 }),
27
+ };
28
+ };
29
+ function applyLiveCreate(this: SetGet, sliceName: string, model: ModelRow) {
30
+ const target = slices.find((entry) => entry.sliceName === sliceName);
31
+ if (!target?.slice.live) return;
32
+ const applyLive = (this as unknown as DynamicRecord)[target.keys.action.applyLiveModel] as
33
+ | ((event: LiveEventPayload) => void)
34
+ | undefined;
35
+ applyLive?.({ op: "enter", id: model.id, light: new cnst.light().set(model) as unknown as object });
36
+ }
37
+ const updatedListPatchOf = (state: { [key: string]: unknown }, ...updatedModels: ModelRow[]) => {
38
+ const lightModels = withSharedInstances(() =>
39
+ updatedModels.map((updatedModel) => new cnst.light().set(updatedModel) as unknown as ModelRow),
40
+ );
41
+ const patch: { [key: string]: DataList<ModelRow> } = {};
42
+ for (const { keys } of slices) {
43
+ const namesOfSlice = keys.state;
44
+ const modelList = state[namesOfSlice.modelList] as DataList<ModelRow>;
45
+ if (state[namesOfSlice.modelListLoading] || !lightModels.some(({ id }) => modelList.has(id))) continue;
46
+ const nextList = new DataList(modelList);
47
+ for (const lightModel of lightModels) if (nextList.has(lightModel.id)) nextList.set(lightModel);
48
+ patch[namesOfSlice.modelList] = nextList;
49
+ }
50
+ return patch;
51
+ };
52
+ return { createdListPatchOf, applyLiveCreate, updatedListPatchOf };
53
+ };
@@ -0,0 +1,91 @@
1
+ import { AbortSignals } from "akanjs/common";
2
+ import { actionErrorKey } from "./actionErrorKey";
3
+ import type { SetGet } from "./types";
4
+
5
+ type StateRecord = { [key: string]: unknown };
6
+ export interface OpenSeq {
7
+ open: number;
8
+ form: number;
9
+ }
10
+ interface WriteGuardNames {
11
+ model: string;
12
+ modelForm: string;
13
+ modelModal: string;
14
+ modelLoading: string;
15
+ }
16
+
17
+ export const makeModelWriteGuard = (names: WriteGuardNames) => {
18
+ const flagOwners = new WeakMap<SetGet, Map<string, object>>();
19
+ const openSeqs = new WeakMap<SetGet, OpenSeq>();
20
+ const openSeqOf = (ctx: SetGet): OpenSeq => openSeqs.get(ctx) ?? { open: 0, form: 0 };
21
+ const markOpened = (ctx: SetGet, { form }: { form: boolean }) => {
22
+ const seen = openSeqOf(ctx);
23
+ const opened = { open: seen.open + 1, form: form ? seen.form + 1 : seen.form };
24
+ openSeqs.set(ctx, opened);
25
+ return opened;
26
+ };
27
+
28
+ const isOvertaken = (ctx: SetGet, seen: OpenSeq) => openSeqOf(ctx).open !== seen.open;
29
+
30
+ const isSavedFormOpen = (ctx: SetGet, seen: OpenSeq, savedForm: { id?: string }) =>
31
+ openSeqOf(ctx).form === seen.form &&
32
+ ((ctx.get() as StateRecord)[names.modelForm] as { id?: string }).id === savedForm.id;
33
+
34
+ const withFlag = async <T>(
35
+ ctx: SetGet,
36
+ {
37
+ flag,
38
+ opening = {},
39
+ failed,
40
+ onError,
41
+ request,
42
+ land,
43
+ }: {
44
+ flag: { key: string; value: string | true } | null;
45
+ opening?: StateRecord;
46
+ failed?: () => StateRecord;
47
+ onError?: (key: string) => void;
48
+ request: () => Promise<T>;
49
+ land: (answer: T, ownsFlag: boolean) => void;
50
+ },
51
+ ) => {
52
+ const owner = {};
53
+ let answered = false;
54
+ const ownsFlag = () =>
55
+ !!flag && flagOwners.get(ctx)?.get(flag.key) === owner && (ctx.get() as StateRecord)[flag.key] === flag.value;
56
+ try {
57
+ if (flag) {
58
+ const owners = flagOwners.get(ctx) ?? new Map<string, object>();
59
+ flagOwners.set(ctx, owners.set(flag.key, owner));
60
+ }
61
+ if (flag || Object.keys(opening).length) ctx.set({ ...opening, ...(flag ? { [flag.key]: flag.value } : {}) });
62
+ const answer = await request();
63
+ answered = true;
64
+ land(answer, ownsFlag());
65
+ return answer;
66
+ } catch (error) {
67
+ const released = { ...(flag && ownsFlag() ? { [flag.key]: false } : {}), ...failed?.() };
68
+ if (Object.keys(released).length) ctx.set(released);
69
+
70
+ if (!answered && !AbortSignals.isAbort(error)) onError?.(actionErrorKey(error));
71
+ throw error;
72
+ }
73
+ };
74
+
75
+ const closedUnlessShown = (ctx: SetGet, seen: OpenSeq, shownKey: string, id: string): StateRecord =>
76
+ isOvertaken(ctx, seen) || ((ctx.get() as StateRecord)[shownKey] as { id?: string } | null)?.id === id
77
+ ? {}
78
+ : { [names.modelModal]: null };
79
+ const openModelPatchOf = (
80
+ latest: StateRecord,
81
+ updatedModel: { id: string },
82
+ ownsFlag: boolean,
83
+ opened: StateRecord = {},
84
+ ) => ({
85
+ ...((latest[names.model] as { id: string } | null)?.id === updatedModel.id
86
+ ? { [names.model]: updatedModel, ...opened }
87
+ : {}),
88
+ ...(ownsFlag ? { [names.modelLoading]: false } : {}),
89
+ });
90
+ return { openSeqOf, markOpened, isOvertaken, isSavedFormOpen, withFlag, closedUnlessShown, openModelPatchOf };
91
+ };
@@ -24,5 +24,7 @@ export type RootStoreCls<
24
24
  [ACTION_OWNER_META]: { [key: string]: ActionOwner };
25
25
  slice: { [key: string]: { [key: string]: SerializedSlice } };
26
26
  _slice: SliceInfoObj;
27
+
28
+ _root: { writable: WritableState; action: Action; slice: InternalSliceObj; state: State };
27
29
  }
28
30
  >;
@@ -6,8 +6,10 @@ import type { SerializedArg } from "akanjs/signal";
6
6
  import { enableMapSet, produce } from "immer";
7
7
  import type { EffectCallback, RefObject } from "react";
8
8
  import { type AgentGate, useAgentGate, useScopePath } from "../vendor/use-agentic";
9
+ import { actionErrorKey } from "./actionErrorKey";
9
10
  import { type ActionOwner, actionTagOf, tagAction } from "./actionTag";
10
11
  import { useFormTools } from "./agentic/useFormTools";
12
+ import { type DraftFlushing, flushDraftsKey } from "./draftFlush";
11
13
  import { DraftStore } from "./draftStore";
12
14
  import { useEffect, useRef, useSyncExternalStore } from "./hooks";
13
15
  import type { RootStoreCls } from "./rootStore";
@@ -25,14 +27,6 @@ const DRAFT_DEBOUNCE_MS = 400;
25
27
  type StoreAction = (...args: unknown[]) => unknown;
26
28
  type TranslationParam = Record<string, string | number>;
27
29
 
28
- const getActionErrorKey = (error: unknown) => {
29
- if (typeof error === "string") return error;
30
- if (!isRecord(error)) return String(error);
31
- if (typeof error.error === "string") return error.error;
32
- if (typeof error.message === "string") return error.message;
33
- return String(error);
34
- };
35
-
36
30
  const getActionErrorData = (error: unknown): TranslationParam | undefined => {
37
31
  if (!isRecord(error) || !isRecord(error.data)) return undefined;
38
32
  const data = Object.fromEntries(
@@ -114,7 +108,12 @@ export class StoreInstance {
114
108
  return ret;
115
109
  };
116
110
 
117
- #ctx: Record<string, unknown> = { set: this.set, get: this.get, pick: this.#pick };
111
+ #ctx: Record<string, unknown> & DraftFlushing = {
112
+ set: this.set,
113
+ get: this.get,
114
+ pick: this.#pick,
115
+ [flushDraftsKey]: () => this.flushDrafts(),
116
+ };
118
117
 
119
118
  subscribe = (listener: () => void) => {
120
119
  this.#listeners.add(listener);
@@ -423,7 +422,7 @@ export class StoreInstance {
423
422
  if (typeof showMessage !== "function") return;
424
423
  try {
425
424
  const lang = Translator.getActiveLocale() ?? parseAkanI18nEnv().defaultLocale;
426
- const errorKey = getActionErrorKey(error);
425
+ const errorKey = actionErrorKey(error);
427
426
  const content = Translator.translateByLocale(lang, errorKey, getActionErrorData(error));
428
427
  showMessage({ type: "error", key: actionKey, duration: 3, content });
429
428
  } catch (messageError) {
@@ -0,0 +1,52 @@
1
+ import { Logger } from "akanjs/common";
2
+ import type { ProtoLightFile } from "akanjs/constant";
3
+
4
+ const UPLOAD_POLL_INTERVAL_MS = 3000;
5
+ const UPLOAD_POLL_ATTEMPTS = 40;
6
+
7
+ export type Uploading = { [field: string]: string[] };
8
+
9
+ export const releasedUpload = (uploading: Uploading, field: string, ticket?: string): Uploading => {
10
+ const pending = uploading[field];
11
+ if (!pending || (ticket && !pending.includes(ticket))) return uploading;
12
+ const { [field]: tickets = [], ...rest } = uploading;
13
+ const left = ticket ? tickets.filter((pending) => pending !== ticket) : [];
14
+ return left.length ? { ...rest, [field]: left } : rest;
15
+ };
16
+
17
+ interface UploadPoll {
18
+ files: { id: string }[];
19
+ readName: string;
20
+ read: (id: string) => Promise<ProtoLightFile>;
21
+ holds: (id: string) => boolean;
22
+ land: (file: ProtoLightFile) => void;
23
+ }
24
+
25
+ export const pollUploadedFiles = ({ files, readName, read, holds, land }: UploadPoll) => {
26
+ for (const file of files) {
27
+ let attemptsLeft = UPLOAD_POLL_ATTEMPTS;
28
+ const intervalKey = setInterval(() => {
29
+ void (async () => {
30
+ if (!holds(file.id)) {
31
+ clearInterval(intervalKey);
32
+ return;
33
+ }
34
+ attemptsLeft -= 1;
35
+ try {
36
+ const currentFile = await read(file.id);
37
+ if (!holds(currentFile.id)) {
38
+ clearInterval(intervalKey);
39
+ return;
40
+ }
41
+ land(currentFile);
42
+ if (currentFile.status !== "uploading" || attemptsLeft <= 0) clearInterval(intervalKey);
43
+ } catch (error) {
44
+ clearInterval(intervalKey);
45
+ Logger.warn(
46
+ `Upload poll for ${readName} ${file.id} stopped: ${error instanceof Error ? error.message : String(error)}`,
47
+ );
48
+ }
49
+ })();
50
+ }, UPLOAD_POLL_INTERVAL_MS);
51
+ }
52
+ };
@@ -7,10 +7,12 @@ import type { SliceStateAction, StoreUseOptions, VoidActions } from "./types";
7
7
 
8
8
  type SetKey<Key extends string> = `set${Capitalize<Key>}`;
9
9
 
10
- export type WithSelectors<RtStoreCls extends RootStoreCls> =
11
- RtStoreCls extends RootStoreCls<any, infer WritableState, infer Action, infer InternalSliceObj, any, any, infer State>
12
- ? WithSelectorsOf<State, WritableState, Action, InternalSliceObj>
13
- : never;
10
+ export type WithSelectors<RtStoreCls extends RootStoreCls> = WithSelectorsOf<
11
+ RtStoreCls["_root"]["state"],
12
+ RtStoreCls["_root"]["writable"],
13
+ RtStoreCls["_root"]["action"],
14
+ RtStoreCls["_root"]["slice"]
15
+ >;
14
16
 
15
17
  type WithSelectorsOf<State, WritableState, Action, InternalSliceObj> = StAgentic & {
16
18
  sub: {
@@ -32,8 +32,15 @@ export interface PageConfig {
32
32
  cache?: boolean;
33
33
  /** Initial full-document SSR strategy. Defaults to `"stream"`. */
34
34
  ssr?: SsrRenderMode;
35
- /** Opt-in suffix-only RSC commits, for a page needing no head update under a layout head its siblings share. */
35
+ /**
36
+ * Opt-in suffix-only RSC commits under `AKAN_PUBLIC_RSC_PARTIAL_COMMIT=1`: the page's `.head()` is plain `title`,
37
+ * `meta` and `link` tags, and the layouts above it render the same for each sibling page, apart from what they
38
+ * read through `usePathCtx()`.
39
+ */
36
40
  rscPatchHeadSafe?: boolean;
41
+ /** `false` answers a `Link` prefetch of the page (on a layout, of every page under it) without rendering it, for a
42
+ * render with a side effect such as counting a view; the click renders it as usual. */
43
+ prefetch?: boolean;
37
44
  topSafeAreaColor?: string;
38
45
  bottomSafeAreaColor?: string;
39
46
  /** Keeps the route (on a `_layout`, its whole directory) out of `akan build` while `akan start` serves it. Write a
@@ -384,6 +391,11 @@ export interface PathRoute {
384
391
  renderRootLayouts: RouteRender[];
385
392
  renderLayouts: RouteRender[];
386
393
  resolveHead?: ResolveHead;
394
+ /**
395
+ * The layouts' part of `resolveHead`, which a partial commit keeps on screen while it swaps the page's part;
396
+ * `resolveHead` must equal this merged with the page's own head by `RouteHead.mergePage`.
397
+ */
398
+ resolveLayoutsHead?: ResolveHead;
387
399
  }
388
400
  export type FrameSlotScope = "page" | "layout";
389
401
  export type FrameSlotType = "topInset" | "bottomInset";
@@ -1,5 +1,5 @@
1
1
  import { type ReactElement, type ReactNode } from "react";
2
- import type { ResolveHeadResult } from "../csrTypes.d.ts";
2
+ import type { AkanHeadSnapshotNode, AkanHeadSnapshotV1, ResolveHeadResult } from "../csrTypes.d.ts";
3
3
  type TagProps = Record<string, unknown>;
4
4
  /** Merges the `.head()` of every route level, root first: a deeper level takes over each singleton tag it writes. */
5
5
  export declare class RouteHead {
@@ -7,6 +7,8 @@ export declare class RouteHead {
7
7
  static merge(levels: ResolveHeadResult[]): ResolveHeadResult;
8
8
  /** `merge` of a page's head over its layouts': a canonical or `og:url` comes from the page or not at all. */
9
9
  static mergePage(layouts: ResolveHeadResult, page: ResolveHeadResult): ResolveHeadResult;
10
+ /** `head` as the title, meta and link data a navigation swaps in, or `undefined` if any tag it holds has no such form. */
11
+ static snapshotOf(head: ResolveHeadResult): AkanHeadSnapshotV1 | undefined;
10
12
  /** The tags at the top of `node` that a head merges by identity, apart from the rest, which is `node` if none. */
11
13
  static split(node: ReactNode): {
12
14
  tags: ReactNode[];
@@ -18,5 +20,7 @@ export declare class RouteHead {
18
20
  static keyOf(tag: string, props: TagProps): string | null;
19
21
  /** `merge` for plain JSX heads, root first. */
20
22
  static mergeNodes(nodes: ReactNode[]): ReactNode;
23
+ /** `merge` for snapshot nodes, root first. */
24
+ static mergeSnapshots(levels: AkanHeadSnapshotNode[][]): AkanHeadSnapshotV1;
21
25
  }
22
26
  export {};
@@ -27,7 +27,7 @@ export interface RouterInstance {
27
27
  refresh: () => void;
28
28
  /** Whether `back` has a page to return to; left out, the router reads the index stamped on the history entry. */
29
29
  canGoBack?: () => boolean;
30
- prefetch?: (href: string, priority?: PrefetchPriority) => void;
30
+ prefetch?: (href: string, priority?: PrefetchPriority) => (() => void) | void;
31
31
  }
32
32
  interface RouterOptions {
33
33
  prefix?: string;
@@ -97,9 +97,10 @@ declare class Router {
97
97
  enterDeepLink(href: string, options?: DeepLinkOptions): boolean;
98
98
  push(href: string, routeOptions?: RouteOptions): never;
99
99
  replace(href: string, routeOptions?: RouteOptions): never;
100
+ /** Returns the call that withdraws the request while it still waits behind others. */
100
101
  prefetch(href: string, { priority }?: {
101
102
  priority?: PrefetchPriority;
102
- }): void;
103
+ }): () => void;
103
104
  /**
104
105
  * Asks `guard` before every in-app move — `push`, `replace`, `back`, a `Link`, the browser's back and forward, the
105
106
  * agent's navigate — and keeps the page when it answers `false`; returns the call that removes it. A redirect, a
@@ -6,7 +6,7 @@ declare global {
6
6
  var __AKAN_RSC_REFRESH__: ((options?: {
7
7
  buildId?: number;
8
8
  }) => Promise<void>) | undefined;
9
- var __AKAN_RSC_PREFETCH__: ((href: string, priority?: PrefetchPriority) => void) | undefined;
9
+ var __AKAN_RSC_PREFETCH__: ((href: string, priority?: PrefetchPriority) => () => void) | undefined;
10
10
  var __AKAN_RSC_NAVIGATE__: ((href: string, options?: {
11
11
  replace?: boolean;
12
12
  scrollToTop?: boolean;
@@ -25,7 +25,7 @@ export declare const navigateRsc: (href: string, options?: {
25
25
  scrollToTop?: boolean;
26
26
  shallow?: boolean;
27
27
  }) => Promise<void> | undefined;
28
- export declare const prefetchRsc: (href: string, priority?: PrefetchPriority) => void;
28
+ export declare const prefetchRsc: (href: string, priority?: PrefetchPriority) => (() => void) | undefined;
29
29
  export declare const refreshRsc: () => Promise<void> | undefined;
30
30
  export declare const useRscNavigation: () => {
31
31
  clearCache: () => void;
@@ -0,0 +1,22 @@
1
+ import type { AkanHeadSnapshotV1 } from "./csrTypes.d.ts";
2
+ /** What a partial commit put on screen under the layouts the last full commit rendered, until the next full one. */
3
+ export interface RscRoutePatch {
4
+ href: string;
5
+ /** The page's part of the head; the layouts' part is the one the last full commit rendered. */
6
+ head: AkanHeadSnapshotV1;
7
+ }
8
+ interface RscRoutePatchStore {
9
+ current: RscRoutePatch | null;
10
+ listeners: Set<() => void>;
11
+ heads: Set<() => void>;
12
+ }
13
+ declare global {
14
+ var __AKAN_RSC_ROUTE_PATCH__: RscRoutePatchStore | undefined;
15
+ }
16
+ export declare const readRscRoutePatch: () => RscRoutePatch | null;
17
+ export declare const writeRscRoutePatch: (patch: RscRoutePatch | null) => void;
18
+ export declare const subscribeRscRoutePatch: (listener: () => void, { head }?: {
19
+ head?: boolean;
20
+ }) => () => void;
21
+ export declare const hasRscRouteHead: () => boolean;
22
+ export {};
@@ -1,5 +1,5 @@
1
1
  export type AkanGraphNodeKind = "model" | "scalar" | "enum" | "query" | "slice" | "endpoint" | "guard" | "method" | "action" | "component" | "route" | "layout" | "internal" | "adaptor";
2
- export type AkanGraphEdgeKind = "field" | "guard" | "calls" | "fetches" | "uses" | "wraps" | "plugs";
2
+ export type AkanGraphEdgeKind = "field" | "guard" | "calls" | "fetches" | "uses" | "wraps" | "plugs" | "binds";
3
3
  export type AkanGraphChange = "added" | "removed" | "changed";
4
4
  export interface AkanGraphLocation {
5
5
  file: string;
@@ -36,6 +36,11 @@ export interface FetchPolicy<_Returns = unknown> {
36
36
  * it, so only a write that is harmless to repeat and safe for anyone to trigger may pass it.
37
37
  */
38
38
  duringRender?: boolean;
39
+ /**
40
+ * Marks a write that changes nothing a query reads back, such as a typing notice: queries already in flight and the
41
+ * pages a link prefetched survive it, where any other write sends them again.
42
+ */
43
+ keepsReads?: boolean;
39
44
  }
40
45
  export type SnakeCase<S extends string> = S extends `${infer T}_${infer U}` ? `${Lowercase<T>}_${SnakeCase<U>}` : S;
41
46
  export type SnakeCaseObj<T> = {
@@ -1 +1 @@
1
- export declare const baseDictionary: import("./dictInfo.d.ts").ServiceDictInfo<[string, string], "ping" | "pingBody" | "pingParam" | "pingQuery" | "wsPing" | "pubsubPing", "payloadTooLarge" | "tooManyRequests" | "gatewayTimeout" | "documentNotFound" | "serverUnreachable" | "serverUnavailable" | "unexpectedResponse" | "immutableField" | "invalidArgument" | "requiredArgument" | "invalidField" | "relationNotFound" | "idempotencyInFlight" | "endpointClosed" | "mutationInApp" | "mutationInRender" | "readOnlyDeployment", "error" | "unauthorized" | "edit" | "ok" | "retry" | "approve" | "view" | "remove" | "skip" | "success" | "password" | "save" | "refresh" | "agent" | "stop" | "connecting" | "send" | "cancel" | "copy" | "createModel" | "updateModel" | "removeModel" | "somethingWrong" | "connected" | "serverDisconnected" | "refreshing" | "tryReconnecting" | "serverHasProblem" | "checkServerStatus" | "cameraPromptHeader" | "cameraPromptPhoto" | "cameraPromptPicture" | "cameraPromptCancel" | "failed" | "processing" | "processed" | "noData" | "invalidValueError" | "emailInvalidError" | "phoneInvalidError" | "pageLoadFailed" | "pageNotFound" | "goBack" | "agentIntro" | "agentPlaceholder" | "agentClear" | "agentQuestion" | "agentToolCard" | "agentAnswer" | "agentListen" | "agentVoiceFailed" | "agentAttach" | "agentAttachRemove" | "agentAttachReading" | "agentReferenceRemove" | "agentReferenceFailed" | "agentAttachTooLarge" | "agentAttachUnsupported" | "agentAttachDuplicate" | "agentAttachTooMany" | "agentAttachTooMuch" | "agentAnswerNeeded" | "agentQueue" | "agentQueuePlaceholder" | "agentQueued" | "agentQueueEdit" | "agentQueueCancel" | "agentToolDone" | "agentToolFailed" | "agentToolRunning" | "agentToolResult" | "agentTokens" | "agentTokensOf" | "agentCompactsAt" | "agentSummarizing" | "agentContinue" | "agentKeepGoing" | "agentCmdNew" | "agentCmdRetry" | "agentCmdCompact" | "agentCmdCopy" | "agentCmdHelp" | "agentCmdTools" | "agentHelpIntro" | "agentHelpNote" | "agentNothingToRetry" | "agentNothingToCompact" | "agentCompacted" | "agentSummary" | "agentBusy" | "agentCopied" | "agentCopyFailed" | "agentToolsHead" | "agentToolsState" | "decline" | "confirmClose" | "textTooShortError" | "textTooLongError" | "selectTooShortError" | "selectTooLongError" | "numberTooSmallError" | "numberTooBigError" | "passwordNotMatchError" | "selectDateError" | "priceUnit" | "passwordConfirm" | "noOptions" | "noSelection" | "addModel" | "createSuccess" | "updateSuccess" | "removeSuccess" | "sureToRemove" | "irreversibleOps" | "typeNameToRemove" | "yesRemove" | "removeMsg" | "confirmMsg" | "perPage" | "cardView" | "tableView" | "exportCsv" | "exportJson" | "actions" | "draftConflict" | "draftApplied" | "draftRestore" | "draftDiscard" | "draftStartOver" | "new">;
1
+ export declare const baseDictionary: import("./dictInfo.d.ts").ServiceDictInfo<[string, string], "ping" | "pingBody" | "pingParam" | "pingQuery" | "wsPing" | "pubsubPing", "payloadTooLarge" | "tooManyRequests" | "gatewayTimeout" | "documentNotFound" | "serverUnreachable" | "serverUnavailable" | "unexpectedResponse" | "immutableField" | "invalidArgument" | "requiredArgument" | "invalidField" | "relationNotFound" | "idempotencyInFlight" | "endpointClosed" | "mutationInApp" | "mutationInRender" | "readOnlyDeployment", "error" | "unauthorized" | "edit" | "ok" | "retry" | "approve" | "view" | "remove" | "skip" | "success" | "password" | "save" | "refresh" | "agent" | "stop" | "connecting" | "send" | "cancel" | "copy" | "createModel" | "updateModel" | "removeModel" | "somethingWrong" | "connected" | "serverDisconnected" | "refreshing" | "tryReconnecting" | "serverHasProblem" | "checkServerStatus" | "cameraPromptHeader" | "cameraPromptPhoto" | "cameraPromptPicture" | "cameraPromptCancel" | "failed" | "processing" | "processed" | "noData" | "invalidValueError" | "emailInvalidError" | "phoneInvalidError" | "pageLoadFailed" | "loadFailed" | "pageNotFound" | "goBack" | "agentIntro" | "agentPlaceholder" | "agentClear" | "agentQuestion" | "agentToolCard" | "agentAnswer" | "agentListen" | "agentVoiceFailed" | "agentAttach" | "agentAttachRemove" | "agentAttachReading" | "agentReferenceRemove" | "agentReferenceFailed" | "agentAttachTooLarge" | "agentAttachUnsupported" | "agentAttachDuplicate" | "agentAttachTooMany" | "agentAttachTooMuch" | "agentAnswerNeeded" | "agentQueue" | "agentQueuePlaceholder" | "agentQueued" | "agentQueueEdit" | "agentQueueCancel" | "agentToolDone" | "agentToolFailed" | "agentToolRunning" | "agentToolResult" | "agentTokens" | "agentTokensOf" | "agentCompactsAt" | "agentSummarizing" | "agentContinue" | "agentKeepGoing" | "agentCmdNew" | "agentCmdRetry" | "agentCmdCompact" | "agentCmdCopy" | "agentCmdHelp" | "agentCmdTools" | "agentHelpIntro" | "agentHelpNote" | "agentNothingToRetry" | "agentNothingToCompact" | "agentCompacted" | "agentSummary" | "agentBusy" | "agentCopied" | "agentCopyFailed" | "agentToolsHead" | "agentToolsState" | "decline" | "confirmClose" | "textTooShortError" | "textTooLongError" | "selectTooShortError" | "selectTooLongError" | "numberTooSmallError" | "numberTooBigError" | "passwordNotMatchError" | "selectDateError" | "priceUnit" | "passwordConfirm" | "noOptions" | "noSelection" | "addModel" | "createSuccess" | "updateSuccess" | "removeSuccess" | "sureToRemove" | "irreversibleOps" | "typeNameToRemove" | "yesRemove" | "removeMsg" | "confirmMsg" | "perPage" | "cardView" | "tableView" | "exportCsv" | "exportJson" | "actions" | "draftConflict" | "draftApplied" | "draftRestore" | "draftDiscard" | "draftStartOver" | "new">;