akanjs 3.0.0-beta.22 → 3.0.0-beta.24

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 (101) hide show
  1. package/client/csrTypes.ts +27 -1
  2. package/client/native.ts +3 -0
  3. package/client/route/RouteDefinition.ts +41 -1
  4. package/fetch/client/wsClient.ts +6 -1
  5. package/package.json +16 -6
  6. package/server/akanApp.ts +2 -3
  7. package/server/artifact/builderRpc.ts +5 -0
  8. package/server/artifact/ipcTypes.ts +10 -0
  9. package/server/hmr/clientScript.ts +31 -2
  10. package/server/hmr/csrDevManifest.ts +25 -0
  11. package/server/hmr/csrDevRuntime.ts +474 -0
  12. package/server/hmr/csrDevShell.ts +111 -0
  13. package/server/hmr/csrDevSourceMap.ts +142 -0
  14. package/server/hmr/devHmrController.ts +33 -16
  15. package/server/hmr/runtimeMetadataFile.ts +17 -0
  16. package/server/hmr/wsHub.ts +30 -4
  17. package/server/resolver/signal.resolver.ts +11 -5
  18. package/server/routing/apiRouter.ts +2 -0
  19. package/server/types.tsx +2 -0
  20. package/server/vendor/react-dom.ts +1 -0
  21. package/server/vendor/react-refresh-runtime.ts +13 -1
  22. package/server/vendor/react.ts +2 -0
  23. package/server/webRouter.ts +32 -2
  24. package/service/predefinedAdaptor/sql/QueryCompiler.ts +3 -3
  25. package/store/agent/ScreenTarget.ts +1 -2
  26. package/store/agent/StoreSurfaceSource.ts +3 -1
  27. package/store/liveInsert.ts +35 -13
  28. package/store/storeInstance.ts +28 -21
  29. package/types/client/csrTypes.d.ts +22 -1
  30. package/types/client/native.d.ts +1 -0
  31. package/types/client/route/RouteDefinition.d.ts +14 -0
  32. package/types/server/artifact/builderRpc.d.ts +2 -1
  33. package/types/server/artifact/ipcTypes.d.ts +11 -0
  34. package/types/server/hmr/csrDevManifest.d.ts +18 -0
  35. package/types/server/hmr/csrDevRuntime.d.ts +71 -0
  36. package/types/server/hmr/csrDevShell.d.ts +14 -0
  37. package/types/server/hmr/csrDevSourceMap.d.ts +17 -0
  38. package/types/server/hmr/devHmrController.d.ts +2 -1
  39. package/types/server/hmr/runtimeMetadataFile.d.ts +1 -0
  40. package/types/server/hmr/wsHub.d.ts +11 -0
  41. package/types/server/routing/apiRouter.d.ts +1 -0
  42. package/types/server/types.d.ts +2 -0
  43. package/types/server/vendor/react-dom.d.ts +1 -1
  44. package/types/server/vendor/react-refresh-runtime.d.ts +1 -1
  45. package/types/server/vendor/react.d.ts +1 -1
  46. package/types/store/storeInstance.d.ts +4 -3
  47. package/types/ui/System/Client.d.ts +5 -3
  48. package/types/vendor/@akanjs/native/plugins/app/src/index.d.ts +17 -0
  49. package/types/vendor/@akanjs/native/plugins/app-state/src/index.d.ts +6 -0
  50. package/types/vendor/use-agentic/AgentActivity.d.ts +11 -0
  51. package/types/vendor/use-agentic/AgentGate.d.ts +10 -0
  52. package/types/vendor/use-agentic/AgenticSurface.d.ts +15 -5
  53. package/types/vendor/use-agentic/index.d.ts +2 -0
  54. package/types/vendor/use-agentic/surfaceContext.d.ts +3 -0
  55. package/types/webkit/CsrRouteTable.d.ts +32 -0
  56. package/types/webkit/CsrStack.d.ts +45 -0
  57. package/types/webkit/RenderLayer.d.ts +2 -2
  58. package/types/webkit/bootCsr.d.ts +7 -8
  59. package/types/webkit/index.d.ts +4 -1
  60. package/types/webkit/nativeNavigation.d.ts +13 -0
  61. package/types/webkit/useCsrValues.d.ts +6 -4
  62. package/types/webkit/useFetch.d.ts +3 -1
  63. package/types/webkit/useHistory.d.ts +5 -1
  64. package/types/webkit/usePageActivity.d.ts +2 -0
  65. package/types/webkit/usePageFocusEffect.d.ts +7 -0
  66. package/types/webkit/usePageLocation.d.ts +13 -0
  67. package/ui/Data/Dashboard.tsx +2 -2
  68. package/ui/Data/ListContainer.tsx +2 -2
  69. package/ui/Layout/BottomInset.tsx +1 -1
  70. package/ui/Layout/Navbar.tsx +1 -1
  71. package/ui/Layout/TopInset.tsx +4 -3
  72. package/ui/System/CSR.tsx +40 -79
  73. package/ui/System/Client.tsx +28 -13
  74. package/vendor/@akanjs/native/native/android/src/com/akanjs/runtime/AkanNativeActivity.kt +53 -9
  75. package/vendor/@akanjs/native/native/android/src/com/akanjs/runtime/AkanNativePlugin.kt +16 -0
  76. package/vendor/@akanjs/native/plugins/app/android/AppPlugin.kt +20 -0
  77. package/vendor/@akanjs/native/plugins/app/native-plugin.json +4 -4
  78. package/vendor/@akanjs/native/plugins/app/src/desktop.ts +3 -0
  79. package/vendor/@akanjs/native/plugins/app/src/index.ts +14 -2
  80. package/vendor/@akanjs/native/plugins/app-state/android/AppStatePlugin.kt +38 -2
  81. package/vendor/@akanjs/native/plugins/app-state/ios/AppStatePlugin.swift +19 -0
  82. package/vendor/@akanjs/native/plugins/app-state/native-plugin.json +1 -1
  83. package/vendor/@akanjs/native/plugins/app-state/src/index.ts +6 -1
  84. package/vendor/use-agentic/AgentActivity.tsx +26 -0
  85. package/vendor/use-agentic/AgentGate.ts +25 -0
  86. package/vendor/use-agentic/AgenticSurface.ts +92 -34
  87. package/vendor/use-agentic/index.ts +2 -0
  88. package/vendor/use-agentic/surfaceContext.ts +3 -0
  89. package/webkit/CsrRouteTable.ts +298 -0
  90. package/webkit/CsrStack.ts +98 -0
  91. package/webkit/RenderLayer.tsx +30 -8
  92. package/webkit/bootCsr.tsx +13 -217
  93. package/webkit/index.ts +4 -1
  94. package/webkit/nativeNavigation.ts +78 -5
  95. package/webkit/useCsrValues.ts +118 -22
  96. package/webkit/useFetch.ts +9 -2
  97. package/webkit/useHistory.ts +23 -6
  98. package/webkit/useLocation.ts +6 -3
  99. package/webkit/usePageActivity.ts +6 -0
  100. package/webkit/usePageFocusEffect.ts +13 -0
  101. package/webkit/usePageLocation.ts +17 -0
@@ -1,3 +1,4 @@
1
+ import { AgentGate } from "./AgentGate";
1
2
  import type {
2
3
  AgentCall,
3
4
  PublishedResource,
@@ -13,6 +14,11 @@ import type {
13
14
 
14
15
  const SHARED_KEY = Symbol.for("useAgentic.sharedSurface");
15
16
 
17
+ interface Registration<E> {
18
+ entry: E;
19
+ gate: AgentGate | null;
20
+ }
21
+
16
22
  /**
17
23
  * The live registry of what the mounted screen offers an agent: tools, readable resources, and scopes.
18
24
  *
@@ -41,10 +47,10 @@ export class AgenticSurface {
41
47
  return [...scope.map((part) => AgenticSurface.sanitize(part)), AgenticSurface.sanitize(name)].join(".");
42
48
  }
43
49
 
44
- #tools = new Map<string, ToolEntry[]>();
45
- #resources = new Map<string, ResourceEntry[]>();
46
- #scopes = new Map<string, ScopeEntry[]>();
47
- #guides: { scope: string; text: string }[] = [];
50
+ #tools = new Map<string, Registration<ToolEntry>[]>();
51
+ #resources = new Map<string, Registration<ResourceEntry>[]>();
52
+ #scopes = new Map<string, Registration<ScopeEntry>[]>();
53
+ #guides: { scope: string; text: string; gate: AgentGate | null }[] = [];
48
54
  readonly #calls: AgentCall[] = [];
49
55
  #sources = new Set<SurfaceSource>();
50
56
  #listeners = new Set<() => void>();
@@ -62,34 +68,37 @@ export class AgenticSurface {
62
68
  * argument rather than closing over it: every registration is then interchangeable and last-wins picks an
63
69
  * equivalent one. The description is what says so — two registrations that describe the same action to a model
64
70
  * are the same declaration twice, and fifty rows are one entry rather than fifty collisions. Two that describe
65
- * different actions under one name are a real clash whichever of them mounted last, and warn.
71
+ * different actions under one name are a real clash whichever of them mounted last, and warn. A clash needs both
72
+ * published at once, so a registration behind a parked gate, or over only parked ones, never warns.
66
73
  */
67
- registerTool(scope: string[], entry: ToolEntry) {
74
+ registerTool(scope: string[], entry: ToolEntry, gate: AgentGate | null = null) {
68
75
  const key = AgenticSurface.fullName(scope, entry.name);
69
- const stack = this.#tools.get(key);
70
- const interchangeable = !stack?.length || stack[stack.length - 1].description === entry.description;
76
+ const shown = AgenticSurface.#shown(this.#tools.get(key));
77
+ const clashes = !!shown && AgenticSurface.#isActive(gate) && shown.description !== entry.description;
71
78
  return this.#stack(
72
79
  this.#tools,
73
80
  key,
74
- entry,
75
- interchangeable ? null : "is registered by two declarations that describe it differently",
81
+ { entry, gate },
82
+ clashes ? "is registered by two declarations that describe it differently" : null,
76
83
  );
77
84
  }
78
85
 
79
- registerResource(scope: string[], entry: ResourceEntry) {
80
- return this.#stack(this.#resources, AgenticSurface.fullName(scope, entry.name), entry);
86
+ registerResource(scope: string[], entry: ResourceEntry, gate: AgentGate | null = null) {
87
+ const key = AgenticSurface.fullName(scope, entry.name);
88
+ return this.#stack(this.#resources, key, { entry, gate }, this.#duplicate(this.#resources, key, gate));
81
89
  }
82
90
 
83
- openScope(parent: string[], scope: ScopeEntry) {
84
- return this.#stack(this.#scopes, AgenticSurface.childPath(parent, scope.id).join("."), scope);
91
+ openScope(parent: string[], scope: ScopeEntry, gate: AgentGate | null = null) {
92
+ const key = AgenticSurface.childPath(parent, scope.id).join(".");
93
+ return this.#stack(this.#scopes, key, { entry: scope, gate }, this.#duplicate(this.#scopes, key, gate));
85
94
  }
86
95
 
87
96
  /**
88
97
  * Standing guidance for the agent while the registrant is mounted — instructions, not context data. Kept in
89
98
  * registration order rather than sorted: guides are prose, and each one must stay a coherent block.
90
99
  */
91
- registerGuide(scope: string[], text: string) {
92
- const entry = { scope: scope.join("."), text };
100
+ registerGuide(scope: string[], text: string, gate: AgentGate | null = null) {
101
+ const entry = { scope: scope.join("."), text, gate };
93
102
  this.#guides.push(entry);
94
103
  this.#notify();
95
104
  return () => {
@@ -110,6 +119,36 @@ export class AgenticSurface {
110
119
  };
111
120
  }
112
121
 
122
+ /** A gate whose every flip re-publishes this surface. Under `parent`, it is active only while the parent is. */
123
+ gate(active: boolean, parent: AgentGate | null = null) {
124
+ return new AgentGate(active, () => this.#notify(), parent);
125
+ }
126
+
127
+ /**
128
+ * This surface for a subtree behind `gate`: what registers through it is published only while the gate is active,
129
+ * and every other call reaches this surface untouched. A proxy rather than a wrapper class, so a method added to the
130
+ * surface later is forwarded instead of missing.
131
+ */
132
+ gated(gate: AgentGate): AgenticSurface {
133
+ const registrations: Partial<Record<PropertyKey, unknown>> = {
134
+ registerTool: (scope: string[], entry: ToolEntry) => this.registerTool(scope, entry, gate),
135
+ registerResource: (scope: string[], entry: ResourceEntry) => this.registerResource(scope, entry, gate),
136
+ openScope: (parent: string[], scope: ScopeEntry) => this.openScope(parent, scope, gate),
137
+ registerGuide: (scope: string[], text: string) => this.registerGuide(scope, text, gate),
138
+ };
139
+
140
+ const bound = new Map<PropertyKey, unknown>();
141
+ return new Proxy(this, {
142
+ get: (target, key) => {
143
+ if (Object.hasOwn(registrations, key)) return registrations[key];
144
+ const value = Reflect.get(target, key, target);
145
+ if (typeof value !== "function") return value;
146
+ if (!bound.has(key)) bound.set(key, value.bind(target));
147
+ return bound.get(key);
148
+ },
149
+ });
150
+ }
151
+
113
152
  snapshot(view: string[] = []): SurfaceSnapshot {
114
153
  const viewKey = view.join(".");
115
154
  const tools = [...this.#activeTools(view)].map(([name, entry]) => AgenticSurface.#publishTool(name, entry));
@@ -118,16 +157,19 @@ export class AgenticSurface {
118
157
  );
119
158
  const scopes = [...this.#scopes.entries()]
120
159
  .filter(([path]) => AgenticSurface.#within(viewKey, path))
121
- .map(([path, stack]) => {
122
- const scope = stack[stack.length - 1];
123
- return { path, ...(scope.label ? { label: scope.label } : {}), ...(scope.kind ? { kind: scope.kind } : {}) };
160
+ .flatMap(([path, stack]) => {
161
+ const scope = AgenticSurface.#shown(stack);
162
+ if (!scope) return [];
163
+ return [{ path, ...(scope.label ? { label: scope.label } : {}), ...(scope.kind ? { kind: scope.kind } : {}) }];
124
164
  });
125
165
 
126
166
  return {
127
167
  tools: tools.sort((a, b) => (a.name < b.name ? -1 : 1)),
128
168
  resources: resources.sort((a, b) => (a.name < b.name ? -1 : 1)),
129
169
  scopes: scopes.sort((a, b) => (a.path < b.path ? -1 : 1)),
130
- guides: this.#guides.filter((guide) => AgenticSurface.#guideApplies(viewKey, guide.scope)).map((g) => g.text),
170
+ guides: this.#guides
171
+ .filter((guide) => AgenticSurface.#isActive(guide.gate) && AgenticSurface.#guideApplies(viewKey, guide.scope))
172
+ .map((g) => g.text),
131
173
  };
132
174
  }
133
175
 
@@ -150,8 +192,8 @@ export class AgenticSurface {
150
192
 
151
193
  tool(name: string, view: string[] = []): ToolEntry | null {
152
194
  const viewKey = view.join(".");
153
- const stack = this.#tools.get(name);
154
- if (stack?.length && AgenticSurface.#within(viewKey, name)) return stack[stack.length - 1];
195
+ const shown = AgenticSurface.#shown(this.#tools.get(name));
196
+ if (shown && AgenticSurface.#within(viewKey, name)) return shown;
155
197
  for (const source of this.#sources) {
156
198
  const found = source.tools?.(view).find((candidate) => candidate.name === name);
157
199
  if (found) return found;
@@ -164,8 +206,7 @@ export class AgenticSurface {
164
206
  * what lets a host drop the built-in tools without dropping a screen's own tool that deliberately shadows one.
165
207
  */
166
208
  declares(name: string, view: string[] = []): boolean {
167
- const stack = this.#tools.get(name);
168
- return !!stack?.length && AgenticSurface.#within(view.join("."), name);
209
+ return !!AgenticSurface.#shown(this.#tools.get(name)) && AgenticSurface.#within(view.join("."), name);
169
210
  }
170
211
 
171
212
  /** Every call made through this surface, oldest first. What the dock shows the user to check against the screen. */
@@ -233,9 +274,10 @@ export class AgenticSurface {
233
274
  const viewKey = view.join(".");
234
275
  const seen = new Set<string>();
235
276
  for (const [name, stack] of this.#tools) {
236
- if (!AgenticSurface.#within(viewKey, name)) continue;
277
+ const shown = AgenticSurface.#shown(stack);
278
+ if (!shown || !AgenticSurface.#within(viewKey, name)) continue;
237
279
  seen.add(name);
238
- yield [name, stack[stack.length - 1]];
280
+ yield [name, shown];
239
281
  }
240
282
  for (const source of this.#sources) {
241
283
  for (const entry of source.tools?.(view) ?? []) {
@@ -250,9 +292,10 @@ export class AgenticSurface {
250
292
  const viewKey = view.join(".");
251
293
  const seen = new Set<string>();
252
294
  for (const [name, stack] of this.#resources) {
253
- if (!AgenticSurface.#within(viewKey, name)) continue;
295
+ const shown = AgenticSurface.#shown(stack);
296
+ if (!shown || !AgenticSurface.#within(viewKey, name)) continue;
254
297
  seen.add(name);
255
- yield [name, stack[stack.length - 1]];
298
+ yield [name, shown];
256
299
  }
257
300
  for (const source of this.#sources) {
258
301
  for (const entry of source.resources?.(view) ?? []) {
@@ -265,8 +308,8 @@ export class AgenticSurface {
265
308
 
266
309
  #resource(name: string, view: string[] = []): ResourceEntry | null {
267
310
  const viewKey = view.join(".");
268
- const stack = this.#resources.get(name);
269
- if (stack?.length && AgenticSurface.#within(viewKey, name)) return stack[stack.length - 1];
311
+ const shown = AgenticSurface.#shown(this.#resources.get(name));
312
+ if (shown && AgenticSurface.#within(viewKey, name)) return shown;
270
313
  for (const source of this.#sources) {
271
314
  const found = source.resources?.(view).find((candidate) => candidate.name === name);
272
315
  if (found) return found;
@@ -285,23 +328,38 @@ export class AgenticSurface {
285
328
  return viewKey.startsWith(`${scopeKey}.`) || scopeKey.startsWith(`${viewKey}.`);
286
329
  }
287
330
 
288
- #stack<E>(map: Map<string, E[]>, key: string, entry: E, clash: string | null = "is registered more than once") {
331
+ #duplicate<E>(map: Map<string, Registration<E>[]>, key: string, gate: AgentGate | null) {
332
+ return AgenticSurface.#shown(map.get(key)) && AgenticSurface.#isActive(gate)
333
+ ? "is registered more than once"
334
+ : null;
335
+ }
336
+
337
+ #stack<E>(map: Map<string, Registration<E>[]>, key: string, registration: Registration<E>, clash: string | null) {
289
338
  const stack = map.get(key) ?? [];
290
- if (stack.length && clash && !this.#warned.has(key)) {
339
+ if (clash && !this.#warned.has(key)) {
291
340
  this.#warned.add(key);
292
341
  console.warn(`[use-agentic] "${key}" ${clash}; the newest registration wins.`);
293
342
  }
294
- stack.push(entry);
343
+ stack.push(registration);
295
344
  map.set(key, stack);
296
345
  this.#notify();
297
346
  return () => {
298
- const idx = stack.indexOf(entry);
347
+ const idx = stack.indexOf(registration);
299
348
  if (idx >= 0) stack.splice(idx, 1);
300
349
  if (!stack.length) map.delete(key);
301
350
  this.#notify();
302
351
  };
303
352
  }
304
353
 
354
+ /** The newest registration whose gate is active: a parked subtree keeps its place without shadowing anything. */
355
+ static #shown<E>(stack: Registration<E>[] | undefined): E | undefined {
356
+ return stack?.findLast((registration) => AgenticSurface.#isActive(registration.gate))?.entry;
357
+ }
358
+
359
+ static #isActive(gate: AgentGate | null) {
360
+ return gate?.active ?? true;
361
+ }
362
+
305
363
  #notify() {
306
364
  for (const listener of this.#listeners) listener();
307
365
  }
@@ -1,4 +1,6 @@
1
1
  export * from "./AgentAbort";
2
+ export * from "./AgentActivity";
3
+ export * from "./AgentGate";
2
4
  export * from "./Agentic";
3
5
  export * from "./AgenticSurface";
4
6
  export * from "./AgentProgress";
@@ -1,10 +1,13 @@
1
1
  "use client";
2
2
  import { useContext } from "react";
3
+ import type { AgentGate } from "./AgentGate";
3
4
  import { AgenticSurface } from "./AgenticSurface";
4
5
  import { sharedContext } from "./sharedContext";
5
6
 
6
7
  export const SurfaceContext = sharedContext<AgenticSurface | null>("surface", null);
7
8
  export const ScopeContext = sharedContext<string[]>("scope", []);
9
+ export const GateContext = sharedContext<AgentGate | null>("gate", null);
8
10
 
9
11
  export const useSurface = () => useContext(SurfaceContext) ?? AgenticSurface.shared;
10
12
  export const useScopePath = () => useContext(ScopeContext);
13
+ export const useAgentGate = () => useContext(GateContext);
@@ -0,0 +1,298 @@
1
+ import {
2
+ type Device,
3
+ getExplicitPageConfigKeys,
4
+ type LayoutModule,
5
+ type PageConfig,
6
+ type PathRoute,
7
+ type Route,
8
+ type RouteGuide,
9
+ type RouteModule,
10
+ type RouteModuleSource,
11
+ type RouteRender,
12
+ readCssSafeAreaInsets,
13
+ resolvePageState,
14
+ resolveRouteModule,
15
+ validatePageConfig,
16
+ } from "akanjs/client";
17
+ import {
18
+ assertUniqueRoutePatterns,
19
+ getRouteExports,
20
+ Logger,
21
+ parseRouteModuleKey,
22
+ routeSegmentToTreePath,
23
+ } from "akanjs/common";
24
+
25
+ type RouteModuleWithConfig = RouteModule & { pageConfig?: PageConfig };
26
+ type CsrRouteModuleLoader = () => Promise<RouteModuleSource>;
27
+ export type CsrRouteModuleEntry = CsrRouteModuleLoader | { loader: CsrRouteModuleLoader; isAsyncDefault?: boolean };
28
+ export type CsrRouteContext = Record<string, CsrRouteModuleEntry>;
29
+
30
+ export interface CsrRoutes {
31
+ pathRoutes: PathRoute[];
32
+ routeGuide: RouteGuide;
33
+ }
34
+
35
+ interface CsrRouteTableOptions {
36
+ device: Pick<Device, "info" | "topSafeArea" | "bottomSafeArea">;
37
+ basePaths: string[] | null;
38
+ currentBasePath?: string;
39
+ }
40
+
41
+ /**
42
+ * The CSR bundle's route table, built from the route modules the entry hands over. It is a store rather than a value
43
+ * so a dev server can swap the modules in place: `replace` rebuilds the table and the router renders the new one while
44
+ * the history, the mounted pages and every store keep going.
45
+ */
46
+ export class CsrRouteTable {
47
+ static #active: CsrRouteTable | null = null;
48
+
49
+ static get active() {
50
+ return CsrRouteTable.#active;
51
+ }
52
+
53
+ static async boot(context: CsrRouteContext, options: CsrRouteTableOptions) {
54
+ const table = new CsrRouteTable(options);
55
+ table.#keys = CsrRouteTable.#keysOf(context);
56
+ table.#routes = await table.#build(context);
57
+ CsrRouteTable.#active = table;
58
+ return table;
59
+ }
60
+
61
+ readonly #options: CsrRouteTableOptions;
62
+ readonly #listeners = new Set<() => void>();
63
+ #keys: string[] = [];
64
+ #routes: CsrRoutes = { pathRoutes: [], routeGuide: { pathSegment: "/", children: {} } };
65
+ #generation = 0;
66
+
67
+ private constructor(options: CsrRouteTableOptions) {
68
+ this.#options = options;
69
+ }
70
+
71
+ subscribe = (listener: () => void) => {
72
+ this.#listeners.add(listener);
73
+ return () => {
74
+ this.#listeners.delete(listener);
75
+ };
76
+ };
77
+
78
+ snapshot = () => this.#routes;
79
+
80
+ /** `false` when the context names another set of modules: a route added or removed needs a reload. */
81
+ async replace(context: CsrRouteContext) {
82
+ const keys = CsrRouteTable.#keysOf(context);
83
+ if (keys.length !== this.#keys.length || keys.some((key, idx) => key !== this.#keys[idx])) {
84
+ Logger.warn("[csr] replacePages got another set of route modules; reload to add or remove a route");
85
+ return false;
86
+ }
87
+ const generation = ++this.#generation;
88
+ const routes = await this.#build(context);
89
+ if (generation !== this.#generation) return true;
90
+ this.#routes = routes;
91
+ for (const listener of this.#listeners) listener();
92
+ return true;
93
+ }
94
+
95
+ async #build(context: CsrRouteContext): Promise<CsrRoutes> {
96
+ const { device, basePaths, currentBasePath } = this.#options;
97
+ const baseLayoutPaths = ["/", "/:lang", ...(currentBasePath ? [`/:lang/${currentBasePath}`] : [])];
98
+ const otherBasePaths = basePaths?.filter((path) => path !== currentBasePath) ?? [];
99
+ const pages: { [key: string]: RouteModule } = {};
100
+ const asyncDefaultMap: { [key: string]: boolean | undefined } = {};
101
+ await Promise.all(
102
+ Object.entries(context).map(async ([key, value]) => {
103
+ const parsed = parseRouteModuleKey(key);
104
+ if (basePaths) {
105
+ const pageBasePath = parsed.sourceRouteSegments.find((segment) => !/^\(.+\)$/.test(segment));
106
+ if (pageBasePath && otherBasePaths.includes(pageBasePath)) return;
107
+ }
108
+ const entry = typeof value === "function" ? { loader: value } : value;
109
+ const loaded = await entry.loader();
110
+ const pageContent =
111
+ parsed.kind === "overrides"
112
+ ? (loaded as RouteModule)
113
+ : resolveRouteModule(loaded, key, { kind: parsed.kind, pattern: parsed.pattern }).module;
114
+ CsrRouteTable.#validateRouteModuleExports(key, pageContent);
115
+ validatePageConfig(key, (pageContent as RouteModuleWithConfig).pageConfig);
116
+ asyncDefaultMap[key] = entry.isAsyncDefault;
117
+
118
+ if (pageContent.default || parsed.kind === "overrides") pages[key] = pageContent;
119
+ }),
120
+ );
121
+ const cssSafeArea = readCssSafeAreaInsets();
122
+
123
+ const routeMap = new Map<string, Route>();
124
+ routeMap.set("/", { path: "/", children: new Map() });
125
+ const pagePatterns: { key: string; pattern: string }[] = [];
126
+ for (const filePath of Object.keys(pages)) {
127
+ const parsed = parseRouteModuleKey(filePath);
128
+ if (parsed.kind === "page") pagePatterns.push({ key: filePath, pattern: parsed.pattern });
129
+ const pathSegments = ["/", ...parsed.routeSegments.map(routeSegmentToTreePath)];
130
+
131
+ const targetRouteMap = pathSegments.slice(0, -1).reduce((rMap: Map<string, Route>, path: string) => {
132
+ if (!rMap.has(path)) rMap.set(path, { path, children: new Map() });
133
+ const children = rMap.get(path)?.children;
134
+ if (!children) throw new Error("No children");
135
+ return children;
136
+ }, routeMap);
137
+
138
+ const targetPath = pathSegments[pathSegments.length - 1];
139
+ if (!targetPath) continue;
140
+ const page = pages[filePath];
141
+ if (!page) continue;
142
+ if (parsed.kind === "overrides") {
143
+
144
+ const overridesRender: RouteRender = {
145
+ render: page.default as never,
146
+ isAsync: asyncDefaultMap[filePath] || page.default?.constructor.name === "AsyncFunction",
147
+ kind: "layout",
148
+ paramNames: CsrRouteTable.#paramNamesOf(parsed.pattern),
149
+ };
150
+ targetRouteMap.set(targetPath, {
151
+ ...(targetRouteMap.get(targetPath) ?? { path: targetPath, children: new Map<string, Route>() }),
152
+ renderOverrides: overridesRender,
153
+ } as Route);
154
+ continue;
155
+ }
156
+ const layoutPage = parsed.kind === "layout" ? (page as LayoutModule) : null;
157
+ const routeRender: RouteRender = {
158
+ render: page.default as never,
159
+ isAsync: asyncDefaultMap[filePath] || page.default?.constructor.name === "AsyncFunction",
160
+ kind: parsed.kind === "layout" ? "layout" : "page",
161
+ paramNames: CsrRouteTable.#paramNamesOf(parsed.pattern),
162
+ Loading: page.Loading as never,
163
+ NotFound: layoutPage?.NotFound,
164
+ Error: layoutPage?.Error,
165
+ resolveNotFound: layoutPage ? () => layoutPage.NotFound : undefined,
166
+ resolveError: layoutPage ? () => layoutPage.Error : undefined,
167
+ };
168
+ targetRouteMap.set(targetPath, {
169
+ ...(targetRouteMap.get(targetPath) ?? { path: targetPath, children: new Map<string, Route>() }),
170
+ ...(parsed.kind === "layout"
171
+ ? { renderLayout: routeRender, layoutPageConfig: (page as RouteModuleWithConfig).pageConfig }
172
+ : {
173
+ renderPage: routeRender,
174
+ pageIncludesOwnLayout: parsed.leaf === "_index",
175
+ isSpecialRoute: parsed.isSpecialRoute,
176
+ pageConfig: (page as RouteModuleWithConfig).pageConfig,
177
+ PageConfig: (page as RouteModuleWithConfig).pageConfig,
178
+ }),
179
+ } as Route);
180
+ }
181
+ assertUniqueRoutePatterns(pagePatterns);
182
+ const getPathRoutes = (
183
+ route: Route,
184
+ parentRootLayouts: RouteRender[] = [],
185
+ parentLayouts: RouteRender[] = [],
186
+ parentPaths: string[] = [],
187
+ parentPageConfigChain: PageConfig[] = [],
188
+ parentRootRenders: RouteRender[] = [],
189
+ ): PathRoute[] => {
190
+ const parentPath = parentPaths.filter((path) => path !== "/").join("");
191
+ const isRouteGroup = /^\/\(.*\)$/.test(route.path);
192
+ const currentPathSegment = isRouteGroup ? "" : route.path;
193
+ const path = parentPath + currentPathSegment;
194
+ const isRoot = !isRouteGroup && baseLayoutPaths.includes(path);
195
+ const pathSegments = [...parentPaths, ...(currentPathSegment ? [currentPathSegment] : [])];
196
+ const currentRootLayout = isRoot && route.renderLayout ? route.renderLayout : null;
197
+ const currentLayout = !isRoot && route.renderLayout ? route.renderLayout : null;
198
+ const currentLayoutConfig = route.renderLayout && route.layoutPageConfig ? route.layoutPageConfig : null;
199
+
200
+ const currentOverrideRenders = route.renderOverrides ? [route.renderOverrides] : [];
201
+ const nodeRenders = [...currentOverrideRenders, ...(route.renderLayout ? [route.renderLayout] : [])];
202
+ const rootLayoutStack = [...parentRootLayouts, ...(currentRootLayout ? [currentRootLayout] : [])];
203
+ const renderRootLayouts = isRoot ? [...parentRootRenders, ...nodeRenders] : parentRootRenders;
204
+ const renderLayouts = isRoot ? parentLayouts : [...parentLayouts, ...nodeRenders];
205
+ const pageConfigChain = [
206
+ ...parentPageConfigChain,
207
+ ...(currentRootLayout || currentLayout ? (currentLayoutConfig ? [currentLayoutConfig] : []) : []),
208
+ ];
209
+ const pageNodeRenders = route.pageIncludesOwnLayout === false ? currentOverrideRenders : nodeRenders;
210
+ const pageRenderRootLayouts = isRoot ? [...parentRootRenders, ...pageNodeRenders] : parentRootRenders;
211
+ const pageRenderLayouts = isRoot ? parentLayouts : [...parentLayouts, ...pageNodeRenders];
212
+ const pageRenderConfigChain =
213
+ route.pageIncludesOwnLayout === false && (currentRootLayout || currentLayout)
214
+ ? parentPageConfigChain
215
+ : pageConfigChain;
216
+ const ownPageConfig = route.renderPage && route.pageConfig ? route.pageConfig : null;
217
+ const finalPageConfigChain = [...pageRenderConfigChain, ...(ownPageConfig ? [ownPageConfig] : [])];
218
+ const pageState = resolvePageState({
219
+ configChain: finalPageConfigChain,
220
+ path,
221
+ basePath: currentBasePath,
222
+ platform: device.info.platform,
223
+ deviceSafeArea: { top: device.topSafeArea, bottom: device.bottomSafeArea },
224
+ cssSafeArea,
225
+ });
226
+ return [
227
+ ...(route.renderPage
228
+ ? [
229
+ {
230
+ path,
231
+ pathSegments,
232
+ renderPage: route.renderPage,
233
+ renderRootLayouts: pageRenderRootLayouts,
234
+ renderLayouts: pageRenderLayouts,
235
+ isSpecialRoute: route.isSpecialRoute,
236
+ pageState: route.pageState ?? pageState,
237
+ pageConfigChain: finalPageConfigChain,
238
+ explicitPageConfigKeys: getExplicitPageConfigKeys(finalPageConfigChain),
239
+ },
240
+ ]
241
+ : []),
242
+ ...(route.children.size
243
+ ? [...route.children.values()].flatMap((child) =>
244
+ getPathRoutes(child, rootLayoutStack, renderLayouts, pathSegments, pageConfigChain, renderRootLayouts),
245
+ )
246
+ : []),
247
+ ];
248
+ };
249
+ const rootRoute = routeMap.get("/");
250
+ if (!rootRoute) throw new Error("No root route");
251
+ const pathRoutes = getPathRoutes(rootRoute);
252
+ const routeGuide: RouteGuide = { pathSegment: "/", children: {} };
253
+ pathRoutes.forEach((pathRoute) => {
254
+ const pathSegments = pathRoute.pathSegments.slice(1);
255
+ pathSegments.reduce((routeGuide: RouteGuide, pathSegment: string, index: number) => {
256
+ const child = routeGuide.children[pathSegment] as RouteGuide | undefined;
257
+ const next: RouteGuide = {
258
+ ...(child ?? {}),
259
+ pathSegment,
260
+ ...(index === pathSegments.length - 1 ? { pathRoute } : {}),
261
+ children: (child?.children as { [key: string]: RouteGuide } | undefined) ?? {},
262
+ } as RouteGuide;
263
+ routeGuide.children[pathSegment] = next;
264
+ return next;
265
+ }, routeGuide);
266
+ });
267
+ return { pathRoutes, routeGuide };
268
+ }
269
+
270
+ static #keysOf(context: CsrRouteContext) {
271
+ return Object.keys(context).sort();
272
+ }
273
+
274
+ static #paramNamesOf(pattern: string) {
275
+ return pattern
276
+ .split("/")
277
+ .filter((part) => part.startsWith(":"))
278
+ .map((part) => part.slice(1).replace(/[?*+]$/, ""));
279
+ }
280
+
281
+ static #validateRouteModuleExports(key: string, mod: RouteModule) {
282
+ const parsed = parseRouteModuleKey(key);
283
+ if (parsed.kind === "overrides") {
284
+
285
+ if (!mod.default) throw new Error(`[route-convention] ${key} generated override wrapper has no default export`);
286
+ return;
287
+ }
288
+ const allowed = getRouteExports(parsed.kind, { rootLayout: parsed.isInternalRootLayout });
289
+ for (const exportName of Object.keys(mod)) {
290
+ if (!allowed.has(exportName)) {
291
+ throw new Error(`[route-convention] unsupported export "${exportName}" in ${key}`);
292
+ }
293
+ }
294
+ if ("head" in mod && "generateHead" in mod) {
295
+ throw new Error(`[route-convention] head and generateHead cannot both be exported in ${key}`);
296
+ }
297
+ }
298
+ }
@@ -0,0 +1,98 @@
1
+ import type { CsrNavigationPhase, CsrPageType, CsrStackEntry, History, Location } from "akanjs/client";
2
+
3
+ interface CsrStackState {
4
+ history: History;
5
+ location: Location;
6
+ prevLocation: Location | null;
7
+ pendingLocation: Location | null;
8
+ phase: CsrNavigationPhase;
9
+ }
10
+
11
+ interface StoredStack {
12
+ idx: number;
13
+ entries: { href: string; entryId: string }[];
14
+ }
15
+
16
+ /**
17
+ * Which history entries keep a mounted page. The current, previous and pending entries are live. Below them the
18
+ * nearest `retainLimit` stack entries stay mounted but hidden, so going back reveals each with its state instead of
19
+ * mounting it again, and every `cache` route visited keeps one page for the whole session.
20
+ */
21
+ export class CsrStack {
22
+ static retainLimit = 3;
23
+ static #seq = 0;
24
+ static readonly #session = Math.random().toString(36).slice(2, 8);
25
+ static readonly #storageKey = "akan.csr.stack";
26
+
27
+ /** Kept per tab, so a reload — or a WebView whose content process died and reloaded — gets its stack back. */
28
+ static save(history: History) {
29
+ const entries = history.locations.flatMap(({ href, entryId }) => (entryId ? [{ href, entryId }] : []));
30
+ if (entries.length !== history.locations.length) return;
31
+ try {
32
+ sessionStorage.setItem(CsrStack.#storageKey, JSON.stringify({ idx: history.idx, entries } satisfies StoredStack));
33
+ } catch {
34
+ }
35
+ }
36
+
37
+ /**
38
+ * The stack this tab had, when the entry it reopened on is the one the stack was on. Only the current and previous
39
+ * entries are mounted at once; the rest come back dormant and mount when they are visited.
40
+ */
41
+ static restore(current: Location, locate: (href: string) => Location) {
42
+ const stored = CsrStack.#stored();
43
+ const entryId = (window.history.state as { akanEntryId?: string } | null)?.akanEntryId;
44
+ const at = stored?.entries[stored.idx];
45
+ if (!stored || !at || !entryId || at.entryId !== entryId || at.href !== current.href) return null;
46
+ try {
47
+ const locations = stored.entries.map((entry, idx) =>
48
+ idx === stored.idx ? { ...current, entryId } : { ...locate(entry.href), entryId: entry.entryId },
49
+ );
50
+ const dormant = new Set(
51
+ stored.entries.filter((_, idx) => idx < stored.idx - 1 || idx > stored.idx).map((entry) => entry.entryId),
52
+ );
53
+ return { locations, idx: stored.idx, dormant };
54
+ } catch {
55
+ return null;
56
+ }
57
+ }
58
+
59
+ static #stored(): StoredStack | null {
60
+ try {
61
+ const stored = JSON.parse(sessionStorage.getItem(CsrStack.#storageKey) ?? "null") as StoredStack | null;
62
+ return stored && Array.isArray(stored.entries) && Number.isInteger(stored.idx) ? stored : null;
63
+ } catch {
64
+ return null;
65
+ }
66
+ }
67
+
68
+ static nextEntryId() {
69
+ CsrStack.#seq += 1;
70
+ return `${CsrStack.#session}-${CsrStack.#seq}`;
71
+ }
72
+
73
+ static keyOf(location: Location) {
74
+ return location.pathRoute.pageState.cache ? location.pathRoute.path : (location.entryId ?? location.href);
75
+ }
76
+
77
+ static entriesOf({ history, location, prevLocation, pendingLocation, phase }: CsrStackState): CsrStackEntry[] {
78
+ const entries = new Map<string, CsrStackEntry>();
79
+ const claim = (entryLocation: Location, pageType: CsrPageType, zIndex: number) => {
80
+ const key = CsrStack.keyOf(entryLocation);
81
+ if (!entries.has(key)) entries.set(key, { key, location: entryLocation, pageType, zIndex });
82
+ };
83
+ claim(location, "current", history.idx);
84
+ if (prevLocation) claim(prevLocation, "prev", Math.max(history.idx - 1, 0));
85
+ if (pendingLocation && phase === "preparing") claim(pendingLocation, "pending", history.idx + 1);
86
+ const dormant = (kept: Location) => !!kept.entryId && !!history.dormant?.has(kept.entryId);
87
+ let retained = 0;
88
+ for (let idx = history.idx - 1; idx >= 0 && retained < CsrStack.retainLimit; idx -= 1) {
89
+ const kept = history.locations[idx];
90
+ if (kept.pathRoute.pageState.cache || dormant(kept) || entries.has(CsrStack.keyOf(kept))) continue;
91
+ claim(kept, "cached", 0);
92
+ retained += 1;
93
+ }
94
+ for (const cached of history.cachedLocationMap.values()) if (!dormant(cached)) claim(cached, "cached", 0);
95
+
96
+ return [...entries.values()].sort((a, b) => (a.key < b.key ? -1 : 1));
97
+ }
98
+ }