akanjs 3.2.0-rc.8 → 3.2.0

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 (643) hide show
  1. package/ARCHITECTURE.md +41 -38
  2. package/CHANGELOG.md +0 -679
  3. package/CONTRIBUTING.md +3 -0
  4. package/base/base.ts +2 -1
  5. package/client/clientRuntime.ts +1 -0
  6. package/client/cn.ts +2 -2
  7. package/client/csrTypes.ts +2 -0
  8. package/client/frameConfig.ts +1 -0
  9. package/client/index.ts +249 -26
  10. package/client/locale.ts +1 -0
  11. package/client/makePageProto.tsx +12 -85
  12. package/client/nativeThemeColor.ts +51 -0
  13. package/client/route/PageDefinition.ts +11 -3
  14. package/client/route/RouteDefinition.ts +24 -7
  15. package/client/route/RouteGuards.ts +2 -1
  16. package/client/route/RouteHead.ts +4 -1
  17. package/client/route/routeArgs.ts +8 -0
  18. package/client/router.ts +17 -2
  19. package/client/rscNavigation.ts +1 -0
  20. package/client/viewportMeta.ts +86 -6
  21. package/common/CodeTranscript.ts +1 -1
  22. package/common/Logger.ts +4 -2
  23. package/common/PipelinePlanSchema.ts +2 -2
  24. package/common/clientAddress.ts +14 -0
  25. package/common/err.ts +122 -0
  26. package/common/eventStream.ts +71 -19
  27. package/common/facetBarrel.ts +38 -0
  28. package/common/index.ts +7 -0
  29. package/common/isGuardRefusal.ts +14 -0
  30. package/common/loggedFailure.ts +11 -0
  31. package/common/mcpExposure.ts +17 -4
  32. package/common/pipelinePlan.ts +1 -1
  33. package/common/routeConvention.ts +3 -1
  34. package/common/types.ts +18 -1
  35. package/constant/constantRegistry.ts +4 -8
  36. package/constant/crystalize.ts +1 -2
  37. package/constant/getDefault.ts +1 -1
  38. package/constant/immerify.ts +1 -1
  39. package/constant/index.ts +78 -21
  40. package/constant/purify.ts +4 -9
  41. package/constant/serialize.ts +4 -2
  42. package/constant/types.ts +1 -0
  43. package/constant/via.ts +1 -2
  44. package/dictionary/agent.dictionary.ts +12 -0
  45. package/dictionary/base.dictionary.ts +11 -0
  46. package/dictionary/locale.ts +1 -1
  47. package/dictionary/trans.ts +14 -97
  48. package/document/dataLoader.ts +39 -19
  49. package/document/databaseRegistry.ts +2 -1
  50. package/document/documentSchema.ts +1 -0
  51. package/document/filterMeta.ts +4 -1
  52. package/document/into.ts +2 -1
  53. package/document/loaderInfo.ts +2 -1
  54. package/document/noDocumentError.ts +4 -1
  55. package/document/queryEvaluator.ts +1 -1
  56. package/document/types.ts +1 -1
  57. package/fetch/client/fetchClient.ts +83 -269
  58. package/fetch/client/fetchClientTypes.ts +49 -0
  59. package/fetch/client/httpClient.ts +3 -2
  60. package/fetch/client/remoteError.ts +4 -20
  61. package/fetch/client/requestScope.ts +41 -0
  62. package/fetch/client/signalCatalog.ts +131 -0
  63. package/fetch/client/wsClient.ts +82 -6
  64. package/fetch/requestStorage.ts +1 -0
  65. package/package.json +1 -1
  66. package/server/agentHooks.ts +16 -0
  67. package/server/akanApp.ts +110 -1272
  68. package/server/akanOption.ts +30 -3
  69. package/server/akanServer.ts +179 -674
  70. package/server/artifact/builderRpc.ts +14 -6
  71. package/server/artifact/routeSeedIndexStore.ts +4 -2
  72. package/server/assetHeaders.ts +6 -0
  73. package/server/console.ts +6 -4
  74. package/server/decorators.ts +2 -2
  75. package/server/di/diLifecycle.ts +24 -35
  76. package/server/di/predefinedAdaptor.ts +24 -1
  77. package/server/di/resolveHierarchy.ts +19 -6
  78. package/server/di/stageFailedError.ts +10 -0
  79. package/server/di/utils.ts +8 -3
  80. package/server/ed25519Key.ts +31 -15
  81. package/server/flightRowReader.ts +106 -20
  82. package/server/gateway/childSupervisor.ts +328 -0
  83. package/server/gateway/devHostChannel.ts +47 -0
  84. package/server/gateway/gatewayChildren.ts +161 -0
  85. package/server/gateway/gatewayConfig.ts +182 -0
  86. package/server/gateway/gatewayHttpProxy.ts +231 -0
  87. package/server/gateway/gatewayLogging.ts +111 -0
  88. package/server/gateway/gatewayRooms.ts +141 -0
  89. package/server/gateway/gatewayStatus.ts +122 -0
  90. package/server/gateway/gatewayStatusPage.ts +54 -0
  91. package/server/gateway/gatewayWebSocketRelay.ts +149 -0
  92. package/server/gateway/listeningPort.ts +13 -0
  93. package/server/hmr/devHmrController.ts +10 -1
  94. package/server/htmlResultCache.ts +234 -0
  95. package/server/imageOptimizer.ts +4 -1
  96. package/server/index.ts +281 -17
  97. package/server/lifecycle/parentChannel.ts +79 -0
  98. package/server/lifecycle/shutdownManager.ts +6 -3
  99. package/server/lifecycle/startGuard.ts +90 -0
  100. package/server/logging/hubFileSink.ts +1 -0
  101. package/server/logging/logControlSocket.ts +42 -3
  102. package/server/logging/logHub.ts +0 -0
  103. package/server/logging/logStdoutWriter.ts +3 -1
  104. package/server/logging/logStreamRoute.ts +28 -11
  105. package/server/logging/serverLogging.ts +74 -0
  106. package/server/machine/machineToken.ts +10 -3
  107. package/server/mcp/AgentTools.ts +149 -0
  108. package/server/mcp/AgentToolsAccount.ts +26 -0
  109. package/server/mcp/McpApps.ts +32 -2
  110. package/server/mcp/McpDispatcher.ts +44 -30
  111. package/server/mcp/McpPages.ts +34 -12
  112. package/server/mcp/McpRateLimiter.ts +14 -0
  113. package/server/mcp/McpRouter.ts +4 -2
  114. package/server/mcp/McpUiSession.ts +2 -1
  115. package/server/mcp/index.ts +1 -0
  116. package/server/migration/migrationCommand.ts +31 -2
  117. package/server/migration/migrationRunner.ts +36 -1
  118. package/server/nativeFile.ts +39 -12
  119. package/server/nativeSecret.ts +12 -3
  120. package/server/oauth/OAuthClientIdMetadata.ts +2 -2
  121. package/server/ops/migrateJobs.ts +2 -2
  122. package/server/ops/opsCommand.ts +1 -1
  123. package/server/ops/opsRoute.ts +5 -1
  124. package/server/ops/opsToken.ts +3 -1
  125. package/server/remote/RemoteFetch.ts +161 -0
  126. package/server/remote/RemoteMcp.ts +242 -0
  127. package/server/remote/RemoteOAuth.ts +270 -0
  128. package/server/remote/RemoteSource.ts +214 -0
  129. package/server/remote/index.ts +17 -0
  130. package/server/remote/remoteError.ts +19 -0
  131. package/server/resolver/CascadeRunner.ts +20 -8
  132. package/server/resolver/database.resolver.ts +10 -417
  133. package/server/resolver/databaseModelInstance.ts +209 -0
  134. package/server/resolver/invalidSignal.ts +7 -0
  135. package/server/resolver/livePause.ts +34 -0
  136. package/server/resolver/modelFacade.ts +136 -0
  137. package/server/resolver/modelLoaders.ts +84 -0
  138. package/server/resolver/modelSchema.ts +52 -0
  139. package/server/resolver/roomAdmission.ts +68 -0
  140. package/server/resolver/signal.resolver.ts +45 -111
  141. package/server/resolver/sliceCrud.ts +63 -0
  142. package/server/resolver/timedQuery.ts +16 -0
  143. package/server/resolver/websocketOf.ts +2 -1
  144. package/server/routeElementComposer.tsx +45 -6
  145. package/server/routeTreeBuilder.ts +23 -9
  146. package/server/routing/apiRouter.ts +53 -28
  147. package/server/routing/builtinRoutes.ts +194 -0
  148. package/server/routing/localRooms.ts +34 -0
  149. package/server/routing/roomReplay.ts +2 -2
  150. package/server/routing/serverLimits.ts +4 -1
  151. package/server/routing/serverListener.ts +194 -0
  152. package/server/rscClient.tsx +122 -195
  153. package/server/rscClientCache.ts +165 -0
  154. package/server/rscClientChunks.ts +126 -8
  155. package/server/rscClientFetch.ts +9 -2
  156. package/server/rscClientPatch.ts +78 -15
  157. package/server/rscDocumentHead.tsx +177 -0
  158. package/server/rscFlightRenderer.ts +83 -0
  159. package/server/rscFlightStream.ts +259 -0
  160. package/server/rscHostReloads.ts +238 -0
  161. package/server/rscHostRenderStream.ts +297 -0
  162. package/server/rscHostRequests.ts +158 -0
  163. package/server/rscHttp.ts +18 -6
  164. package/server/rscNavigationState.ts +24 -1
  165. package/server/rscPagePrompts.ts +65 -14
  166. package/server/rscPrefetchCache.ts +31 -17
  167. package/server/rscRenderControl.ts +33 -0
  168. package/server/rscRenderFallbacks.ts +299 -0
  169. package/server/rscRenderHandler.ts +439 -0
  170. package/server/rscRenderStats.ts +49 -0
  171. package/server/rscResultCaches.ts +74 -0
  172. package/server/rscRouteDocument.tsx +316 -0
  173. package/server/rscSegmentOutletReference.ts +5 -1
  174. package/server/rscStaticApp.tsx +73 -0
  175. package/server/rscWorker.tsx +112 -1341
  176. package/server/rscWorkerHost.ts +175 -803
  177. package/server/rscWorkerProcess.ts +155 -0
  178. package/server/rscWorkerRecycler.ts +128 -0
  179. package/server/serverConfig.ts +128 -0
  180. package/server/serverMetrics.ts +52 -0
  181. package/server/sitemap.ts +1 -0
  182. package/server/ssrFromRscRenderer.tsx +20 -20
  183. package/server/ssrStaticApp.tsx +243 -0
  184. package/server/webArtifact.ts +86 -0
  185. package/server/webAssetRoutes.ts +84 -0
  186. package/server/webCsrSurface.ts +172 -0
  187. package/server/webDocumentRoute.ts +180 -0
  188. package/server/webRouteContext.ts +232 -0
  189. package/server/webRouter.ts +129 -1165
  190. package/server/webRscRoute.ts +155 -0
  191. package/server/webSiteFiles.ts +139 -0
  192. package/server/webStaticApp.ts +62 -0
  193. package/server/wellKnownRoutes.ts +73 -0
  194. package/service/agent.service.ts +14 -2
  195. package/service/agentAccounts.ts +19 -0
  196. package/service/agentLoop/agentLoop.ts +550 -0
  197. package/service/agentLoop/agentLoopTypes.ts +220 -0
  198. package/service/agentLoop/deltaStream.ts +40 -0
  199. package/service/agentLoop/loopAnswer.ts +67 -0
  200. package/service/agentLoop/loopAsk.ts +44 -0
  201. package/service/agentLoop/loopCompaction.ts +146 -0
  202. package/service/agentLoop/loopRemotes.ts +181 -0
  203. package/service/agentLoop/loopRequest.ts +120 -0
  204. package/service/agentLoop/loopStored.ts +24 -0
  205. package/service/agentLoop/loopToolOutput.ts +54 -0
  206. package/service/agentLoop/loopToolkits.ts +155 -0
  207. package/service/agentLoop/loopTranscript.ts +138 -0
  208. package/{signal → service}/agentMeter.ts +2 -1
  209. package/{signal → service}/agentRelayPolicy.ts +43 -8
  210. package/service/endpointCacheKeys.ts +14 -2
  211. package/service/index.ts +6 -0
  212. package/service/injectInfo.ts +2 -1
  213. package/service/ipcTypes.ts +8 -2
  214. package/service/liveRoomLimit.ts +68 -0
  215. package/service/liveRoomLimitError.ts +16 -0
  216. package/service/liveSyncHub.ts +24 -2
  217. package/service/predefinedAdaptor/agentTools.adaptor.ts +34 -0
  218. package/service/predefinedAdaptor/anthropicLlm.ts +33 -14
  219. package/service/predefinedAdaptor/compress.adaptor.ts +2 -2
  220. package/service/predefinedAdaptor/database.adaptor.ts +62 -19
  221. package/service/predefinedAdaptor/index.ts +1 -0
  222. package/service/predefinedAdaptor/llm.adaptor.ts +24 -1
  223. package/service/predefinedAdaptor/openaiDialect.ts +72 -23
  224. package/service/predefinedAdaptor/openaiLlm.ts +1 -1
  225. package/service/predefinedAdaptor/role.adaptor.ts +2 -0
  226. package/service/predefinedAdaptor/solidPubsub.adaptor.ts +35 -2
  227. package/service/predefinedAdaptor/solidQueue.adaptor.ts +2 -2
  228. package/service/predefinedAdaptor/solidSqlite.ts +6 -3
  229. package/service/predefinedAdaptor/sql/DocumentHydrator.ts +95 -0
  230. package/service/predefinedAdaptor/sql/DocumentRowCodec.ts +192 -0
  231. package/service/predefinedAdaptor/sql/DocumentWriter.ts +298 -0
  232. package/service/predefinedAdaptor/sql/QueryScope.ts +70 -0
  233. package/service/predefinedAdaptor/sql/QueryWriter.ts +200 -0
  234. package/service/predefinedAdaptor/sql/SqlDocumentStore.ts +127 -1069
  235. package/service/predefinedAdaptor/sql/SqlTableSchema.ts +357 -0
  236. package/service/predefinedAdaptor/sql/StoredRows.ts +95 -0
  237. package/service/predefinedAdaptor/sql/TransactionScope.ts +14 -7
  238. package/service/predefinedAdaptor/sql/dialect/postgres.ts +1 -1
  239. package/service/predefinedAdaptor/sql/dialect/sqlite.ts +1 -1
  240. package/service/predefinedAdaptor/sql/driver/bunSqlite.ts +20 -9
  241. package/service/predefinedAdaptor/sql/driver/postgres.ts +1 -1
  242. package/service/predefinedAdaptor/sql/types.ts +28 -4
  243. package/service/predefinedAdaptor/sseData.ts +88 -0
  244. package/service/predefinedAdaptor/storage.adaptor.ts +2 -1
  245. package/service/predefinedAdaptor/websocket.adaptor.ts +74 -44
  246. package/service/serviceRegistry.ts +1 -0
  247. package/signal/SignalFailure.ts +35 -0
  248. package/signal/agent.signal.ts +15 -9
  249. package/signal/agentTurnStream.ts +23 -9
  250. package/signal/byIdRead.ts +18 -0
  251. package/signal/carriedClientIps.ts +1 -0
  252. package/signal/endpointCache.ts +61 -6
  253. package/signal/endpointErrorContract.ts +1 -1
  254. package/signal/endpointRateLimit.ts +84 -3
  255. package/signal/index.ts +322 -32
  256. package/signal/mcp/McpDocument.ts +8 -1
  257. package/signal/mcp/mcpProtocol.ts +6 -1
  258. package/signal/mcp/pagePrompt.ts +15 -0
  259. package/signal/middleware.ts +10 -3
  260. package/signal/openapi/openapi.ts +10 -1
  261. package/signal/resolveFieldContext.ts +34 -0
  262. package/signal/serializer/fetch.serializer.ts +22 -15
  263. package/signal/signalContext.ts +15 -42
  264. package/signal/slice.ts +22 -19
  265. package/signal/trace.ts +44 -5
  266. package/signal/types.ts +46 -8
  267. package/store/action.ts +32 -1057
  268. package/store/actionErrorMessage.ts +20 -0
  269. package/store/actionOption.ts +22 -0
  270. package/store/baseSt.ts +1 -0
  271. package/store/formFieldSetters.ts +229 -0
  272. package/store/index.ts +125 -17
  273. package/store/modelActionContext.ts +65 -0
  274. package/store/modelOpenActions.ts +158 -0
  275. package/store/modelWriteActions.ts +240 -0
  276. package/store/modelWriteGuard.ts +3 -12
  277. package/store/openSeq.ts +34 -0
  278. package/store/sliceListActions.ts +370 -0
  279. package/store/sliceLiveActions.ts +140 -0
  280. package/store/stateBuilder.ts +2 -0
  281. package/store/storeInstance.ts +4 -18
  282. package/store/storeRegistry.ts +1 -1
  283. package/test/conformance.ts +25 -5
  284. package/types/base/base.d.ts +2 -1
  285. package/types/client/clientRuntime.d.ts +1 -0
  286. package/types/client/cn.d.ts +2 -2
  287. package/types/client/csrTypes.d.ts +2 -0
  288. package/types/client/frameConfig.d.ts +1 -0
  289. package/types/client/index.d.ts +25 -26
  290. package/types/client/locale.d.ts +1 -0
  291. package/types/client/makePageProto.d.ts +5 -13
  292. package/types/client/nativeThemeColor.d.ts +6 -0
  293. package/types/client/route/PageDefinition.d.ts +5 -2
  294. package/types/client/route/RouteDefinition.d.ts +2 -2
  295. package/types/client/route/routeArgs.d.ts +7 -0
  296. package/types/client/router.d.ts +3 -1
  297. package/types/client/rscNavigation.d.ts +1 -0
  298. package/types/client/viewportMeta.d.ts +5 -2
  299. package/types/common/CodeTranscript.d.ts +1 -1
  300. package/types/common/clientAddress.d.ts +5 -0
  301. package/types/common/err.d.ts +48 -0
  302. package/types/common/eventStream.d.ts +5 -1
  303. package/types/common/facetBarrel.d.ts +4 -0
  304. package/types/common/index.d.ts +6 -3
  305. package/types/common/isGuardRefusal.d.ts +3 -0
  306. package/types/common/loggedFailure.d.ts +2 -0
  307. package/types/common/mcpExposure.d.ts +9 -2
  308. package/types/common/routeConvention.d.ts +2 -0
  309. package/types/common/types.d.ts +18 -1
  310. package/types/constant/constantRegistry.d.ts +3 -1
  311. package/types/constant/crystalize.d.ts +1 -1
  312. package/types/constant/getDefault.d.ts +1 -1
  313. package/types/constant/immerify.d.ts +1 -1
  314. package/types/constant/index.d.ts +21 -21
  315. package/types/constant/purify.d.ts +2 -1
  316. package/types/constant/serialize.d.ts +1 -1
  317. package/types/constant/types.d.ts +1 -0
  318. package/types/dictionary/agent.dictionary.d.ts +1 -1
  319. package/types/dictionary/base.dictionary.d.ts +1 -1
  320. package/types/dictionary/dictionary.d.ts +9 -9
  321. package/types/dictionary/locale.d.ts +1 -1
  322. package/types/dictionary/trans.d.ts +3 -26
  323. package/types/document/dataLoader.d.ts +5 -0
  324. package/types/document/databaseRegistry.d.ts +2 -1
  325. package/types/document/documentSchema.d.ts +1 -0
  326. package/types/document/filterMeta.d.ts +4 -1
  327. package/types/document/into.d.ts +1 -1
  328. package/types/document/loaderInfo.d.ts +2 -1
  329. package/types/document/noDocumentError.d.ts +8 -1
  330. package/types/document/queryEvaluator.d.ts +1 -1
  331. package/types/document/types.d.ts +1 -1
  332. package/types/fetch/client/fetchClient.d.ts +6 -36
  333. package/types/fetch/client/fetchClientTypes.d.ts +40 -0
  334. package/types/fetch/client/httpClient.d.ts +2 -0
  335. package/types/fetch/client/remoteError.d.ts +0 -4
  336. package/types/fetch/client/requestScope.d.ts +11 -0
  337. package/types/fetch/client/signalCatalog.d.ts +25 -0
  338. package/types/fetch/client/wsClient.d.ts +2 -0
  339. package/types/fetch/requestStorage.d.ts +1 -0
  340. package/types/server/agentHooks.d.ts +4 -0
  341. package/types/server/akanApp.d.ts +2 -20
  342. package/types/server/akanOption.d.ts +16 -2
  343. package/types/server/akanServer.d.ts +2 -2
  344. package/types/server/assetHeaders.d.ts +1 -0
  345. package/types/server/console.d.ts +4 -3
  346. package/types/server/di/predefinedAdaptor.d.ts +1 -0
  347. package/types/server/di/stageFailedError.d.ts +5 -0
  348. package/types/server/ed25519Key.d.ts +1 -0
  349. package/types/server/flightRowReader.d.ts +8 -2
  350. package/types/server/gateway/childSupervisor.d.ts +35 -0
  351. package/types/server/gateway/devHostChannel.d.ts +14 -0
  352. package/types/server/gateway/gatewayChildren.d.ts +50 -0
  353. package/types/server/gateway/gatewayConfig.d.ts +82 -0
  354. package/types/server/gateway/gatewayHttpProxy.d.ts +22 -0
  355. package/types/server/gateway/gatewayLogging.d.ts +16 -0
  356. package/types/server/gateway/gatewayRooms.d.ts +25 -0
  357. package/types/server/gateway/gatewayStatus.d.ts +63 -0
  358. package/types/server/gateway/gatewayStatusPage.d.ts +9 -0
  359. package/types/server/gateway/gatewayWebSocketRelay.d.ts +17 -0
  360. package/types/server/gateway/listeningPort.d.ts +5 -0
  361. package/types/server/htmlResultCache.d.ts +51 -0
  362. package/types/server/index.d.ts +19 -17
  363. package/types/server/lifecycle/parentChannel.d.ts +13 -0
  364. package/types/server/lifecycle/startGuard.d.ts +10 -0
  365. package/types/server/logging/logHub.d.ts +5 -1
  366. package/types/server/logging/logStreamRoute.d.ts +2 -0
  367. package/types/server/logging/rotatingLogWriter.d.ts +1 -1
  368. package/types/server/logging/serverLogging.d.ts +12 -0
  369. package/types/server/mcp/AgentTools.d.ts +31 -0
  370. package/types/server/mcp/AgentToolsAccount.d.ts +7 -0
  371. package/types/server/mcp/McpApps.d.ts +6 -2
  372. package/types/server/mcp/McpDispatcher.d.ts +10 -1
  373. package/types/server/mcp/McpPages.d.ts +2 -1
  374. package/types/server/mcp/McpRateLimiter.d.ts +3 -0
  375. package/types/server/mcp/index.d.ts +1 -0
  376. package/types/server/migration/migrationCommand.d.ts +1 -1
  377. package/types/server/migration/migrationRunner.d.ts +9 -1
  378. package/types/server/remote/RemoteFetch.d.ts +42 -0
  379. package/types/server/remote/RemoteMcp.d.ts +52 -0
  380. package/types/server/remote/RemoteOAuth.d.ts +58 -0
  381. package/types/server/remote/RemoteSource.d.ts +51 -0
  382. package/types/server/remote/index.d.ts +5 -0
  383. package/types/server/remote/remoteError.d.ts +12 -0
  384. package/types/server/remote.d.ts +1 -0
  385. package/types/server/resolver/CascadeRunner.d.ts +2 -2
  386. package/types/server/resolver/database.resolver.d.ts +2 -2
  387. package/types/server/resolver/databaseModelInstance.d.ts +4 -0
  388. package/types/server/resolver/invalidSignal.d.ts +2 -0
  389. package/types/server/resolver/livePause.d.ts +5 -0
  390. package/types/server/resolver/modelFacade.d.ts +5 -0
  391. package/types/server/resolver/modelLoaders.d.ts +15 -0
  392. package/types/server/resolver/modelSchema.d.ts +6 -0
  393. package/types/server/resolver/roomAdmission.d.ts +7 -0
  394. package/types/server/resolver/signal.resolver.d.ts +1 -1
  395. package/types/server/resolver/sliceCrud.d.ts +8 -0
  396. package/types/server/resolver/timedQuery.d.ts +8 -0
  397. package/types/server/routeElementComposer.d.ts +21 -5
  398. package/types/server/routing/builtinRoutes.d.ts +24 -0
  399. package/types/server/routing/localRooms.d.ts +14 -0
  400. package/types/server/routing/roomReplay.d.ts +2 -2
  401. package/types/server/routing/serverListener.d.ts +31 -0
  402. package/types/server/rscClientCache.d.ts +34 -0
  403. package/types/server/rscClientChunks.d.ts +3 -1
  404. package/types/server/rscClientFetch.d.ts +1 -1
  405. package/types/server/rscClientPatch.d.ts +12 -1
  406. package/types/server/rscDocumentHead.d.ts +33 -0
  407. package/types/server/rscFlightRenderer.d.ts +14 -0
  408. package/types/server/rscFlightStream.d.ts +53 -0
  409. package/types/server/rscHostReloads.d.ts +54 -0
  410. package/types/server/rscHostRenderStream.d.ts +53 -0
  411. package/types/server/rscHostRequests.d.ts +29 -0
  412. package/types/server/rscHttp.d.ts +4 -2
  413. package/types/server/rscNavigationState.d.ts +5 -1
  414. package/types/server/rscPagePrompts.d.ts +13 -0
  415. package/types/server/rscPrefetchCache.d.ts +7 -6
  416. package/types/server/rscRenderControl.d.ts +12 -0
  417. package/types/server/rscRenderFallbacks.d.ts +41 -0
  418. package/types/server/rscRenderHandler.d.ts +29 -0
  419. package/types/server/rscRenderStats.d.ts +32 -0
  420. package/types/server/rscResultCaches.d.ts +18 -0
  421. package/types/server/rscRouteDocument.d.ts +52 -0
  422. package/types/server/rscStaticApp.d.ts +28 -0
  423. package/types/server/rscWorker.d.ts +1 -3
  424. package/types/server/rscWorkerHost.d.ts +10 -70
  425. package/types/server/rscWorkerProcess.d.ts +31 -0
  426. package/types/server/rscWorkerRecycler.d.ts +22 -0
  427. package/types/server/serverConfig.d.ts +30 -0
  428. package/types/server/serverMetrics.d.ts +11 -0
  429. package/types/server/sitemap.d.ts +1 -0
  430. package/types/server/ssrFromRscRenderer.d.ts +2 -2
  431. package/types/server/ssrStaticApp.d.ts +20 -0
  432. package/types/server/webArtifact.d.ts +7 -0
  433. package/types/server/webAssetRoutes.d.ts +11 -0
  434. package/types/server/webCsrSurface.d.ts +18 -0
  435. package/types/server/webDocumentRoute.d.ts +19 -0
  436. package/types/server/webRouteContext.d.ts +45 -0
  437. package/types/server/webRouter.d.ts +3 -28
  438. package/types/server/webRscRoute.d.ts +24 -0
  439. package/types/server/webSiteFiles.d.ts +12 -0
  440. package/types/server/webStaticApp.d.ts +8 -0
  441. package/types/server/wellKnownRoutes.d.ts +5 -0
  442. package/types/service/agent.service.d.ts +3 -0
  443. package/types/service/agentAccounts.d.ts +8 -0
  444. package/types/service/agentLoop/agentLoop.d.ts +33 -0
  445. package/types/service/agentLoop/agentLoopTypes.d.ts +235 -0
  446. package/types/service/agentLoop/deltaStream.d.ts +3 -0
  447. package/types/service/agentLoop/loopAnswer.d.ts +13 -0
  448. package/types/service/agentLoop/loopAsk.d.ts +12 -0
  449. package/types/service/agentLoop/loopCompaction.d.ts +12 -0
  450. package/types/service/agentLoop/loopRemotes.d.ts +40 -0
  451. package/types/service/agentLoop/loopRequest.d.ts +9 -0
  452. package/types/service/agentLoop/loopStored.d.ts +6 -0
  453. package/types/service/agentLoop/loopToolOutput.d.ts +8 -0
  454. package/types/service/agentLoop/loopToolkits.d.ts +17 -0
  455. package/types/service/agentLoop/loopTranscript.d.ts +13 -0
  456. package/types/{signal → service}/agentMeter.d.ts +1 -1
  457. package/types/{signal → service}/agentRelayPolicy.d.ts +18 -3
  458. package/types/service/index.d.ts +6 -0
  459. package/types/service/injectInfo.d.ts +2 -1
  460. package/types/service/ipcTypes.d.ts +10 -0
  461. package/types/service/liveRoomLimit.d.ts +26 -0
  462. package/types/service/liveRoomLimitError.d.ts +9 -0
  463. package/types/service/predefinedAdaptor/agentTools.adaptor.d.ts +31 -0
  464. package/types/service/predefinedAdaptor/anthropicLlm.d.ts +2 -2
  465. package/types/service/predefinedAdaptor/database.adaptor.d.ts +9 -7
  466. package/types/service/predefinedAdaptor/index.d.ts +1 -0
  467. package/types/service/predefinedAdaptor/llm.adaptor.d.ts +12 -0
  468. package/types/service/predefinedAdaptor/openaiDialect.d.ts +3 -2
  469. package/types/service/predefinedAdaptor/role.adaptor.d.ts +2 -0
  470. package/types/service/predefinedAdaptor/solidPubsub.adaptor.d.ts +3 -0
  471. package/types/service/predefinedAdaptor/solidSqlite.d.ts +1 -1
  472. package/types/service/predefinedAdaptor/sql/DocumentHydrator.d.ts +11 -0
  473. package/types/service/predefinedAdaptor/sql/DocumentRowCodec.d.ts +26 -0
  474. package/types/service/predefinedAdaptor/sql/DocumentWriter.d.ts +25 -0
  475. package/types/service/predefinedAdaptor/sql/QueryScope.d.ts +16 -0
  476. package/types/service/predefinedAdaptor/sql/QueryWriter.d.ts +20 -0
  477. package/types/service/predefinedAdaptor/sql/SqlDocumentStore.d.ts +5 -28
  478. package/types/service/predefinedAdaptor/sql/SqlTableSchema.d.ts +22 -0
  479. package/types/service/predefinedAdaptor/sql/StoredRows.d.ts +27 -0
  480. package/types/service/predefinedAdaptor/sql/TransactionScope.d.ts +3 -1
  481. package/types/service/predefinedAdaptor/sql/driver/bunSqlite.d.ts +3 -15
  482. package/types/service/predefinedAdaptor/sql/driver/postgres.d.ts +0 -8
  483. package/types/service/predefinedAdaptor/sql/types.d.ts +27 -4
  484. package/types/service/predefinedAdaptor/sseData.d.ts +13 -0
  485. package/types/service/predefinedAdaptor/websocket.adaptor.d.ts +7 -3
  486. package/types/service/serviceRegistry.d.ts +1 -0
  487. package/types/signal/SignalFailure.d.ts +4 -0
  488. package/types/signal/agentTurnStream.d.ts +3 -0
  489. package/types/signal/byIdRead.d.ts +7 -0
  490. package/types/signal/carriedClientIps.d.ts +4 -0
  491. package/types/signal/endpointRateLimit.d.ts +12 -0
  492. package/types/signal/index.d.ts +32 -32
  493. package/types/signal/mcp/McpDocument.d.ts +2 -0
  494. package/types/signal/mcp/mcpProtocol.d.ts +5 -0
  495. package/types/signal/mcp/pagePrompt.d.ts +13 -0
  496. package/types/signal/resolveFieldContext.d.ts +15 -0
  497. package/types/signal/serializer/fetch.serializer.d.ts +3 -1
  498. package/types/signal/signalContext.d.ts +2 -14
  499. package/types/signal/slice.d.ts +15 -13
  500. package/types/signal/trace.d.ts +12 -1
  501. package/types/signal/types.d.ts +38 -7
  502. package/types/store/action.d.ts +4 -27
  503. package/types/store/actionErrorMessage.d.ts +1 -0
  504. package/types/store/actionOption.d.ts +24 -0
  505. package/types/store/baseSt.d.ts +1 -0
  506. package/types/store/formFieldSetters.d.ts +80 -0
  507. package/types/store/index.d.ts +17 -16
  508. package/types/store/modelActionContext.d.ts +189 -0
  509. package/types/store/modelOpenActions.d.ts +12 -0
  510. package/types/store/modelWriteActions.d.ts +16 -0
  511. package/types/store/modelWriteGuard.d.ts +2 -5
  512. package/types/store/openSeq.d.ts +17 -0
  513. package/types/store/sliceListActions.d.ts +295 -0
  514. package/types/store/sliceLiveActions.d.ts +6 -0
  515. package/types/store/stateBuilder.d.ts +2 -0
  516. package/types/test/conformance.d.ts +3 -1
  517. package/types/ui/Agent/Chat.d.ts +5 -2
  518. package/types/ui/Agent/ChatHeader.d.ts +13 -0
  519. package/types/ui/Agent/ChatPendingCards.d.ts +23 -0
  520. package/types/ui/Agent/ToolRow.d.ts +13 -0
  521. package/types/ui/Field/Choice.d.ts +2 -1
  522. package/types/ui/Field/index.d.ts +1 -1
  523. package/types/ui/Reference/origin.d.ts +1 -0
  524. package/types/ui/UiOverride/UiOverride.d.ts +2 -0
  525. package/types/ui/index.d.ts +2 -1
  526. package/types/ui/overlayLayer.d.ts +8 -2
  527. package/types/ui/recipe/badgeRecipe.d.ts +3 -3
  528. package/types/ui/recipe/buttonRecipe.d.ts +3 -3
  529. package/types/ui/recipe/inputRecipe.d.ts +1 -1
  530. package/types/vendor/@akanjs/native/packages/cli/src/lib/project.d.ts +4 -0
  531. package/types/vendor/@akanjs/native/packages/desktop/src/relaunch.d.ts +1 -0
  532. package/types/vendor/@akanjs/native/plugins/appearance/src/index.d.ts +9 -0
  533. package/types/vendor/@akanjs/native/plugins/external-view/src/index.d.ts +22 -13
  534. package/types/vendor/@akanjs/native/plugins/single-instance/src/socket.d.ts +15 -2
  535. package/types/vendor/use-agentic/AgentClientTools.d.ts +19 -0
  536. package/types/vendor/use-agentic/Compaction.d.ts +3 -1
  537. package/types/vendor/use-agentic/SessionQuestion.d.ts +26 -0
  538. package/types/vendor/use-agentic/Transcript.d.ts +1 -1
  539. package/types/vendor/use-agentic/failureCode.d.ts +4 -0
  540. package/types/vendor/use-agentic/index.d.ts +1 -0
  541. package/types/vendor/use-agentic/types.d.ts +12 -3
  542. package/types/webkit/CsrGuards.d.ts +3 -0
  543. package/types/webkit/McpAppHost.d.ts +24 -0
  544. package/types/webkit/RouteLevelBoundary.d.ts +17 -0
  545. package/types/webkit/csrRefresh.d.ts +13 -0
  546. package/types/webkit/index.d.ts +3 -0
  547. package/types/webkit/needsBrowser.d.ts +5 -0
  548. package/types/webkit/useCamera.d.ts +1 -1
  549. package/types/webkit/useCsrKeyboard.d.ts +19 -0
  550. package/types/webkit/useCsrLocationState.d.ts +21 -0
  551. package/types/webkit/useCsrNavigation.d.ts +25 -0
  552. package/types/webkit/useCsrRefs.d.ts +33 -0
  553. package/types/webkit/useCsrRenderTrace.d.ts +13 -0
  554. package/types/webkit/useCsrStackLifecycle.d.ts +12 -0
  555. package/types/webkit/useCsrTransitions.d.ts +2 -0
  556. package/types/webkit/useGeoLocation.d.ts +1 -1
  557. package/types/webkit/useHistory.d.ts +2 -3
  558. package/types/webkit/useResolvedFrame.d.ts +38 -0
  559. package/types/webkit/useSyncNavigation.d.ts +22 -0
  560. package/ui/Agent/Bubble.tsx +4 -118
  561. package/ui/Agent/Chat.tsx +402 -235
  562. package/ui/Agent/ChatHeader.tsx +59 -0
  563. package/ui/Agent/ChatPendingCards.tsx +49 -0
  564. package/ui/Agent/ToolRow.tsx +117 -0
  565. package/ui/Agent/fetchRunner.ts +8 -1
  566. package/ui/BottomSheet.tsx +1 -1
  567. package/ui/Data/Item.tsx +2 -2
  568. package/ui/Data/ListContainer.tsx +348 -181
  569. package/ui/Data/useViewModal.ts +10 -4
  570. package/ui/Dialog/LegacyModal.tsx +1 -1
  571. package/ui/Dialog/Modal.tsx +1 -1
  572. package/ui/Field/Choice.tsx +3 -1
  573. package/ui/Load/StreamBoundary.tsx +1 -6
  574. package/ui/Load/View.tsx +2 -1
  575. package/ui/Model/EditModal.tsx +2 -1
  576. package/ui/Popconfirm.tsx +1 -1
  577. package/ui/Reference/origin.ts +1 -0
  578. package/ui/Select.tsx +43 -51
  579. package/ui/Signal/RestApi.tsx +3 -2
  580. package/ui/System/Client.tsx +4 -1
  581. package/ui/UiOverride/UiOverride.tsx +2 -0
  582. package/ui/index.ts +5 -0
  583. package/ui/overlayLayer.ts +25 -2
  584. package/vendor/@akanjs/native/native/android/src/com/akanjs/runtime/AkanNativeActivity.kt +31 -13
  585. package/vendor/@akanjs/native/native/android/src/com/akanjs/runtime/AkanNativePlugin.kt +4 -0
  586. package/vendor/@akanjs/native/native/desktop/Cargo.lock +1 -0
  587. package/vendor/@akanjs/native/native/desktop/Cargo.toml +2 -0
  588. package/vendor/@akanjs/native/native/desktop/src/external.rs +240 -114
  589. package/vendor/@akanjs/native/native/desktop/src/json.rs +14 -1
  590. package/vendor/@akanjs/native/native/desktop/src/lib.rs +12 -4
  591. package/vendor/@akanjs/native/native/desktop/src/linux/external.rs +696 -0
  592. package/vendor/@akanjs/native/native/desktop/src/linux/mod.rs +1 -0
  593. package/vendor/@akanjs/native/native/ios/Sources/AkanNativeViewController.swift +6 -1
  594. package/vendor/@akanjs/native/packages/cli/src/lib/native-plugins.ts +5 -3
  595. package/vendor/@akanjs/native/packages/cli/src/lib/project.ts +25 -1
  596. package/vendor/@akanjs/native/packages/desktop/src/deeplinks.ts +2 -2
  597. package/vendor/@akanjs/native/packages/desktop/src/host.ts +2 -2
  598. package/vendor/@akanjs/native/packages/desktop/src/relaunch.ts +8 -3
  599. package/vendor/@akanjs/native/plugins/app/src/desktop.ts +2 -2
  600. package/vendor/@akanjs/native/plugins/appearance/android/AppearancePlugin.kt +13 -0
  601. package/vendor/@akanjs/native/plugins/appearance/ios/AppearancePlugin.swift +27 -0
  602. package/vendor/@akanjs/native/plugins/appearance/native-plugin.json +2 -2
  603. package/vendor/@akanjs/native/plugins/appearance/src/index.ts +8 -1
  604. package/vendor/@akanjs/native/plugins/autostart/src/desktop.ts +2 -1
  605. package/vendor/@akanjs/native/plugins/external-view/native-plugin.json +4 -1
  606. package/vendor/@akanjs/native/plugins/external-view/src/index.ts +22 -13
  607. package/vendor/@akanjs/native/plugins/single-instance/src/socket.ts +113 -24
  608. package/vendor/use-agentic/AgentClientTools.ts +33 -0
  609. package/vendor/use-agentic/AgentSession.ts +35 -73
  610. package/vendor/use-agentic/CHANGELOG.md +0 -43
  611. package/vendor/use-agentic/Compaction.ts +12 -2
  612. package/vendor/use-agentic/SessionQuestion.ts +99 -0
  613. package/vendor/use-agentic/ToolRunner.ts +3 -15
  614. package/vendor/use-agentic/Transcript.ts +8 -5
  615. package/vendor/use-agentic/WIRE.md +28 -9
  616. package/vendor/use-agentic/failureCode.ts +44 -0
  617. package/vendor/use-agentic/httpRunner.ts +22 -8
  618. package/vendor/use-agentic/index.ts +1 -0
  619. package/vendor/use-agentic/types.ts +13 -1
  620. package/webkit/CsrGuards.ts +11 -2
  621. package/webkit/McpAppFetchBridge.ts +3 -1
  622. package/webkit/McpAppHost.ts +122 -0
  623. package/webkit/RenderLayer.tsx +48 -14
  624. package/webkit/RouteLevelBoundary.tsx +37 -0
  625. package/webkit/csrRefresh.ts +33 -0
  626. package/webkit/index.ts +3 -0
  627. package/webkit/lazy.tsx +5 -1
  628. package/webkit/needsBrowser.ts +10 -0
  629. package/webkit/useCamera.tsx +18 -7
  630. package/webkit/useCsrKeyboard.ts +155 -0
  631. package/webkit/useCsrLocationState.ts +58 -0
  632. package/webkit/useCsrNavigation.ts +302 -0
  633. package/webkit/useCsrRefs.ts +52 -0
  634. package/webkit/useCsrRenderTrace.ts +68 -0
  635. package/webkit/useCsrStackLifecycle.ts +120 -0
  636. package/webkit/useCsrTransitions.ts +552 -0
  637. package/webkit/useCsrValues.ts +73 -1235
  638. package/webkit/useGeoLocation.tsx +1 -3
  639. package/webkit/useHistory.ts +2 -2
  640. package/webkit/useLocation.ts +3 -2
  641. package/webkit/useResolvedFrame.ts +116 -0
  642. package/webkit/useSyncNavigation.ts +109 -0
  643. package/vendor/@akanjs/native/CHANGELOG.md +0 -21
@@ -1,29 +1,13 @@
1
1
  import fs from "node:fs";
2
2
  import path from "node:path";
3
3
  import type { AkanWebConfig } from "akanjs";
4
- import {
5
- type AkanI18nConfig,
6
- AppHosts,
7
- CookieJar,
8
- DEFAULT_AKAN_I18N,
9
- getBasePathFromPathname,
10
- LocalePath,
11
- Logger,
12
- type LogRecord,
13
- parseAkanI18nEnv,
14
- RequestLocale,
15
- resolveSubRouteHosts,
16
- } from "akanjs/common";
17
- import { type AkanRequestStore, createRequestStore } from "akanjs/fetch";
4
+ import { AkanError } from "akanjs/base";
5
+ import { AppHosts, Logger, type LogRecord, resolveSubRouteHosts } from "akanjs/common";
18
6
  import type { AkanMetricsReport } from "akanjs/service";
19
7
  import { PageDefinition } from "../client/route/PageDefinition";
20
- import { type Dictionary, TranslatorState } from "../client/translatorState";
21
- import { getWebManifestBasePath } from "../client/webManifest";
22
8
  import type { PagePromptSource } from "../signal/mcp/pagePrompt";
23
- import { SignalContext } from "../signal/signalContext";
24
9
  import {
25
10
  type BuilderRpc,
26
- type MergedManifest,
27
11
  ModulePreloadPlan,
28
12
  RouteClientCache,
29
13
  type RouteSeedIndex,
@@ -31,179 +15,28 @@ import {
31
15
  type RoutesManifest,
32
16
  RoutesManifestStore,
33
17
  } from "./artifact";
34
- import { type AssetHeaderOptions, applySecurityHeaders, assetHeaders, strictTransportSecurity } from "./assetHeaders";
35
- import {
36
- getClientFacingOrigin,
37
- hasRouteCacheInvalidationScope,
38
- LruTtlCache,
39
- parsePositiveInt,
40
- type RouteCacheEntry,
41
- type RouteCacheInvalidation,
42
- type RouteCacheRenderState,
43
- resolveHtmlCacheControl,
44
- resolvePublicRouteCacheEntryDecision,
45
- resolveRouteCacheStoreTtl,
46
- shouldInvalidateRouteCacheEntry,
47
- shouldStoreRouteCache,
48
- } from "./cachePolicy";
49
- import {
50
- type EncodedBody,
51
- encodeBody,
52
- encodedBodyResponse,
53
- encodedFileResponse,
54
- isCompressibleContentType,
55
- matchesIfNoneMatch,
56
- varyOnEncoding,
57
- } from "./contentEncoding";
58
- import { isCrawlerUserAgent } from "./crawler";
59
- import { HMR_CLIENT_SCRIPT } from "./hmr/clientScript";
60
- import { CSR_DEV_ROUTE_PREFIX, resolveDevCsrMode, SSR_DEV_DIRNAME, SSR_DEV_ROUTE_PREFIX } from "./hmr/csrDevManifest";
18
+ import type { RouteCacheInvalidation } from "./cachePolicy";
19
+ import { resolveDevCsrMode, SSR_DEV_DIRNAME, SSR_DEV_ROUTE_PREFIX } from "./hmr/csrDevManifest";
61
20
  import { CsrDevShell } from "./hmr/csrDevShell";
62
21
  import { DevHmrController } from "./hmr/devHmrController";
63
- import { SsrDevShim } from "./hmr/ssrDevShim";
64
22
  import type { HmrWsData, HmrWsHub } from "./hmr/wsHub";
23
+ import { HtmlResultCache } from "./htmlResultCache";
65
24
  import { ImageOptimizer } from "./imageOptimizer";
66
25
  import type { McpAppShellSource } from "./mcp/McpApps";
67
- import { normalizeHost, resolveArtifactDir, warnIgnoredSubRouteBasePaths } from "./proxy/hostBasePathWebProxy";
68
- import { createDefaultRobotsTxt } from "./robots";
69
- import { AKAN_RSC_DICTIONARY_HEADER, AKAN_RSC_IMPORT_MAP_HEADER, AKAN_RSC_PREFETCH_HEADER } from "./routeState";
70
- import {
71
- createRscNavigationStreamResponse,
72
- createRscNotFoundFallbackResponse,
73
- createRscRedirectResponse,
74
- } from "./rscResponse";
75
- import { type RscRedirectStatus, RscWorker, type RscWorkerStatus } from "./rscWorkerHost";
26
+ import { resolveArtifactDir, warnIgnoredSubRouteBasePaths } from "./proxy/hostBasePathWebProxy";
27
+ import { RscWorker, type RscWorkerStatus } from "./rscWorkerHost";
76
28
  import { SessionRefresh } from "./sessionRefresh";
77
- import { createDefaultSitemapXml, getSitemapBasePath } from "./sitemap";
78
29
  import { SsrFromRscRenderer } from "./ssrFromRscRenderer";
79
- import type { SsrManifest } from "./ssrTypes";
80
- import { resolveStaticPath, staysInTree } from "./staticPath";
81
- import { getPathnameLocale } from "./systemPageDocument";
82
- import { createSubRouteIndexResponse, createSystemPageResponse, getSystemPageHomeHref } from "./systemPages";
83
30
  import { type BaseBuildArtifact, type HttpRoutes, type RenderState, resolveWebConfig } from "./types";
84
-
85
- const CLIENT_CLOSED_REQUEST_STATUS = 499;
86
- export const DEFAULT_HTML_RESULT_CACHE_MAX_BODY_BYTES = 2 * 1024 * 1024;
87
- /** Well above any sensible TTL: this only has to reclaim a cache nobody is reading, not track expiry closely. */
88
- const ROUTE_CACHE_SWEEP_INTERVAL_MS = 60_000;
89
- const APPLE_APP_SITE_ASSOCIATION_PATH = "/.well-known/apple-app-site-association";
90
- const ANDROID_ASSET_LINKS_PATH = "/.well-known/assetlinks.json";
91
-
92
- function createDocumentRedirectResponse(location: string, requestUrl: URL, status: RscRedirectStatus): Response {
93
- const target = new URL(location, requestUrl.origin);
94
- const sameOrigin = target.origin === requestUrl.origin && !target.pathname.startsWith("//");
95
- const href = sameOrigin ? `${target.pathname}${target.search}${target.hash}` : target.href;
96
- return new Response(null, { status, headers: { Location: href, "Cache-Control": "no-store" } });
97
- }
98
-
99
- export function cacheHtmlWhileStreaming(
100
- stream: ReadableStream<Uint8Array>,
101
- onComplete: (html: string) => void,
102
- options: {
103
- shouldCache?: () => boolean | Promise<boolean>;
104
- maxBodyBytes?: number | null;
105
- onSkip?: (reason: "body-too-large" | "store-skip") => void;
106
- } = {},
107
- ): ReadableStream<Uint8Array> {
108
- const chunks: Uint8Array[] = [];
109
- let byteLength = 0;
110
- let exceededMaxBodyBytes = false;
111
- const decoder = new TextDecoder();
112
-
113
- return stream.pipeThrough(
114
- new TransformStream<Uint8Array, Uint8Array>({
115
- transform(chunk, controller) {
116
- if (!exceededMaxBodyBytes) {
117
- byteLength += chunk.byteLength;
118
- if (options.maxBodyBytes && byteLength > options.maxBodyBytes) {
119
- exceededMaxBodyBytes = true;
120
- chunks.length = 0;
121
- } else {
122
- chunks.push(chunk.slice());
123
- }
124
- }
125
- controller.enqueue(chunk);
126
- },
127
- async flush() {
128
- if (exceededMaxBodyBytes) {
129
- options.onSkip?.("body-too-large");
130
- return;
131
- }
132
- const body = new Uint8Array(byteLength);
133
- let offset = 0;
134
- for (const chunk of chunks) {
135
- body.set(chunk, offset);
136
- offset += chunk.byteLength;
137
- }
138
- try {
139
- if (options.shouldCache && !(await options.shouldCache())) {
140
- options.onSkip?.("store-skip");
141
- return;
142
- }
143
- onComplete(decoder.decode(body));
144
- } catch {
145
- }
146
- },
147
- }),
148
- );
149
- }
150
-
151
- export function cancelStreamForHeadResponse(stream: ReadableStream<Uint8Array>, message: string): void {
152
- void stream.cancel(new DOMException(message, "AbortError")).catch(() => {
153
- });
154
- }
155
-
156
- export function resolveHtmlRouteCacheStoreTtl(input: {
157
- baseTtl: number;
158
- workerCacheState: RouteCacheRenderState;
159
- hostRequestStore: AkanRequestStore;
160
- lateControl?: { type: "redirect" | "not-found" } | null;
161
- }): number | null {
162
- if (input.lateControl) return null;
163
- const workerTtl = resolveRouteCacheStoreTtl(input.baseTtl, input.workerCacheState);
164
- if (workerTtl === null) return null;
165
- const hostCacheState = shouldStoreRouteCache({
166
- policy: input.hostRequestStore.policy,
167
- dynamicUsage: input.hostRequestStore.dynamicUsage,
168
- });
169
- return resolveRouteCacheStoreTtl(workerTtl, hostCacheState);
170
- }
171
-
172
- export function normalizeRscTargetUrlForHostBasePath(
173
- targetUrl: URL,
174
- options: {
175
- basePath: string | null;
176
- basePaths?: readonly string[];
177
- i18n: AkanI18nConfig;
178
- seedEntries?: RouteSeedIndex["entries"];
179
- },
180
- ): { url: URL; basePath: string | null } {
181
- const { basePath, basePaths = [], i18n, seedEntries } = options;
182
- const routeMatches = (url: URL) => !seedEntries || Boolean(RouteSeedIndexStore.match(url.pathname, seedEntries));
183
-
184
- const segments = targetUrl.pathname.split("/").filter(Boolean);
185
- const [locale, firstPath] = segments;
186
- if (!locale || !i18n.locales.includes(locale)) return { url: targetUrl, basePath: null };
187
-
188
- if (basePath) {
189
- if (firstPath === basePath) return { url: targetUrl, basePath };
190
- const normalized = new URL(targetUrl);
191
- normalized.pathname = `/${[locale, basePath, ...segments.slice(1)].join("/")}`;
192
- return { url: normalized, basePath };
193
- }
194
-
195
- const targetBasePath = firstPath && basePaths.includes(firstPath) ? firstPath : null;
196
- if (seedEntries && routeMatches(targetUrl)) return { url: targetUrl, basePath: targetBasePath ?? basePath };
197
- const candidates = [...new Set([basePath, ...basePaths].filter((bp): bp is string => Boolean(bp)))];
198
- for (const candidate of candidates) {
199
- if (firstPath === candidate) continue;
200
- const normalized = new URL(targetUrl);
201
- normalized.pathname = `/${[locale, candidate, ...segments.slice(1)].join("/")}`;
202
- if (routeMatches(normalized)) return { url: normalized, basePath: candidate };
203
- }
204
-
205
- return { url: targetUrl, basePath: targetBasePath };
206
- }
31
+ import { WebArtifact } from "./webArtifact";
32
+ import { WebAssetRoutes } from "./webAssetRoutes";
33
+ import { WebCsrSurface } from "./webCsrSurface";
34
+ import { WebDocumentRoute } from "./webDocumentRoute";
35
+ import { WebRouteContext } from "./webRouteContext";
36
+ import { WebRscRoute } from "./webRscRoute";
37
+ import { WebSiteFiles } from "./webSiteFiles";
38
+ import { WebStaticApp } from "./webStaticApp";
39
+ import { WellKnownRoutes } from "./wellKnownRoutes";
207
40
 
208
41
  export interface SsrRoutesInputs {
209
42
  web: AkanWebConfig;
@@ -221,544 +54,158 @@ interface WebRouterOptions {
221
54
  prebuilt?: RoutesManifest | null;
222
55
  }
223
56
 
224
- interface CachedHtmlResult {
225
- body: EncodedBody;
226
- pathname: string;
227
- routeId?: string;
228
- tags?: string[];
229
- }
230
-
231
57
  export class WebRouter {
232
58
  /** Where the build writes each `.app()`'s view, beside `csr/`: a native app packs `csr/`, which needs none of them. */
233
59
  static readonly mcpAppViewDir = "mcp-apps";
234
60
  #logger = new Logger("WebRouter");
235
61
  #artifactDir = resolveArtifactDir();
236
- #artifact: BaseBuildArtifact;
237
- #importMapKey: string;
238
- #subRoutes: Record<string, string[]>;
239
62
  #rsc: RscWorker;
240
63
  #hub: HmrWsHub | null = null;
241
64
 
242
- #prodMode = process.env.NODE_ENV === "production" && process.env.AKAN_COMMAND_TYPE !== "start";
65
+ readonly #prodMode = process.env.NODE_ENV === "production" && process.env.AKAN_COMMAND_TYPE !== "start";
243
66
  #builderRpc: BuilderRpc | null;
244
- #routeCache: RouteClientCache;
245
67
  #devHmr: DevHmrController | null = null;
246
- #csrDevShell: CsrDevShell | null = null;
247
68
  /** Dev only: SSR pages load their client code from the dev module registry it serves. */
248
69
  #ssrDevShell: CsrDevShell | null = null;
249
- #csrArmed = false;
250
- readonly #builds = new Map<string, Promise<unknown>>();
251
- readonly #requestStats = {
252
- fullSsr: 0,
253
- rscNavigation: 0,
254
- rscPrefetch: 0,
255
- staticAsset: 0,
256
- csr: 0,
257
- image: 0,
258
- };
259
- readonly #htmlCache = new LruTtlCache<CachedHtmlResult>(
260
- parsePositiveInt(process.env.AKAN_HTML_RESULT_CACHE_MAX_ENTRIES) ?? 100,
261
- {
262
- sizeOf: (result) => result.body.byteLength,
263
- maxBytes: LruTtlCache.parseByteCeiling(process.env.AKAN_HTML_RESULT_CACHE_MAX_BYTES),
264
- sweepIntervalMs: ROUTE_CACHE_SWEEP_INTERVAL_MS,
265
- },
266
- );
267
- #htmlCacheHits = 0;
268
- #htmlCacheMisses = 0;
269
- #htmlCacheBypass = 0;
270
- #runtimeManifest: { revision: number; manifest: MergedManifest } | null = null;
271
- renderState: RenderState;
70
+ readonly #context: WebRouteContext;
71
+ readonly #csr: WebCsrSurface;
72
+ readonly #htmlCache: HtmlResultCache;
73
+ readonly #rscRoute: WebRscRoute;
74
+ readonly #document: WebDocumentRoute;
75
+ readonly renderState: RenderState;
272
76
  /** What this router actually mounts, already intersected with what the artifact carries. */
273
77
  readonly web: AkanWebConfig;
274
- #seedIndex: RouteSeedIndex;
275
78
  readonly #prebuilt: RoutesManifest | null;
276
-
277
- readonly #modulePreloadPlan?: ModulePreloadPlan;
278
79
  constructor({ artifact, web, cssBytesByUrl, rsc, seedIndex, upgradeHmrWs, prebuilt = null }: WebRouterOptions) {
279
80
  this.#logger.verbose(`[SSR] loaded ${Object.keys(cssBytesByUrl).length} CSS assets`);
280
81
  this.web = web;
281
82
  if (process.env.NODE_ENV === "production" && !this.#prodMode)
282
83
  this.#logger.warn("[SSR] NODE_ENV=production ignored under `akan start`; serving in dev mode");
283
- this.#artifact = artifact;
284
- this.#importMapKey = Bun.hash(JSON.stringify(artifact.vendorMap)).toString(36);
84
+ const importMapKey = Bun.hash(JSON.stringify(artifact.vendorMap)).toString(36);
285
85
  const { subRoutes, ignoredBasePaths } = resolveSubRouteHosts({
286
86
  subRoutes: artifact.subRoutes,
287
87
  basePaths: artifact.basePaths,
288
88
  env: process.env.AKAN_SUB_ROUTE_HOSTS,
289
89
  });
290
- this.#subRoutes = subRoutes;
291
90
  AppHosts.declare([...artifact.domains, ...Object.values(subRoutes).flat()]);
292
91
  warnIgnoredSubRouteBasePaths(this.#logger, ignoredBasePaths);
293
92
  this.#rsc = rsc;
294
93
  this.renderState = {
295
94
  buildId: 0,
296
- cssAssets: this.#artifact.cssAssets ?? {},
95
+ cssAssets: artifact.cssAssets ?? {},
297
96
  cssBytesByUrl,
298
97
  };
299
- this.#seedIndex = seedIndex;
300
98
  this.#prebuilt = prebuilt;
301
- if (prebuilt?.modulePreloads)
302
- this.#modulePreloadPlan = new ModulePreloadPlan(prebuilt.modulePreloads, prebuilt.clientManifest);
303
- if (this.#prodMode) {
304
- this.#builderRpc = null;
305
- this.#routeCache = new RouteClientCache({
306
- buildRoute: async (routeId) => {
307
- throw new Error(
308
- `[SSR] route ${routeId} missing from production artifact — rebuild with \`akan build\` to include it`,
309
- );
310
- },
311
- });
312
- } else {
313
- this.#devHmr = new DevHmrController({
314
- artifactDir: this.#artifactDir,
99
+ let htmlCache: HtmlResultCache | null = null;
100
+ try {
101
+ let routeCache: RouteClientCache;
102
+ let csrDevShell: CsrDevShell | null = null;
103
+ if (this.#prodMode) {
104
+ this.#builderRpc = null;
105
+ routeCache = new RouteClientCache({
106
+ buildRoute: async (routeId) => {
107
+ throw new AkanError(
108
+ "artifactMissing",
109
+ `[SSR] route ${routeId} missing from production artifact — rebuild with \`akan build\` to include it`,
110
+ );
111
+ },
112
+ });
113
+ } else {
114
+ this.#devHmr = new DevHmrController({
115
+ artifactDir: this.#artifactDir,
116
+ renderState: this.renderState,
117
+ rsc: this.#rsc,
118
+ seedIndex,
119
+ upgradeHmrWs,
120
+ pagesBundlePath: artifact.pagesBundlePath,
121
+ });
122
+ this.#builderRpc = this.#devHmr.builderRpc;
123
+ routeCache = this.#devHmr.routeCache;
124
+ this.#hub = this.#devHmr.hub;
125
+ if (resolveDevCsrMode() === "registry") csrDevShell = new CsrDevShell(this.#artifactDir);
126
+ this.#ssrDevShell = new CsrDevShell(this.#artifactDir, {
127
+ dirName: SSR_DEV_DIRNAME,
128
+ routePrefix: SSR_DEV_ROUTE_PREFIX,
129
+ });
130
+ }
131
+ this.#context = new WebRouteContext({
132
+ artifact,
133
+ prodMode: this.#prodMode,
315
134
  renderState: this.renderState,
316
- rsc: this.#rsc,
317
- seedIndex: this.#seedIndex,
318
- upgradeHmrWs,
319
- pagesBundlePath: this.#artifact.pagesBundlePath,
135
+ subRoutes,
136
+ seedIndex,
137
+ routeCache,
138
+ hub: () => this.#hub,
320
139
  });
321
- this.#builderRpc = this.#devHmr.builderRpc;
322
- this.#routeCache = this.#devHmr.routeCache;
323
- this.#hub = this.#devHmr.hub;
324
- if (resolveDevCsrMode() === "registry") this.#csrDevShell = new CsrDevShell(this.#artifactDir);
325
- this.#ssrDevShell = new CsrDevShell(this.#artifactDir, {
326
- dirName: SSR_DEV_DIRNAME,
327
- routePrefix: SSR_DEV_ROUTE_PREFIX,
140
+ this.#csr = new WebCsrSurface(this.#context, { devShell: csrDevShell, builderRpc: () => this.#builderRpc });
141
+ htmlCache = new HtmlResultCache({ prodMode: this.#prodMode, devRegistry: this.#ssrDevShell !== null });
142
+ this.#htmlCache = htmlCache;
143
+ this.#rscRoute = new WebRscRoute(this.#context, { rsc, importMapKey });
144
+ this.#document = new WebDocumentRoute(this.#context, {
145
+ rsc,
146
+ importMapKey,
147
+ ssrDevShell: this.#ssrDevShell,
148
+ htmlCache: this.#htmlCache,
149
+
150
+ modulePreloadPlan: prebuilt?.modulePreloads
151
+ ? new ModulePreloadPlan(prebuilt.modulePreloads, prebuilt.clientManifest)
152
+ : undefined,
328
153
  });
154
+ } catch (error) {
155
+
156
+ this.#devHmr?.dispose();
157
+ htmlCache?.dispose();
158
+ throw error;
329
159
  }
330
160
  }
331
161
 
332
162
  async initializeRoute() {
333
- if (this.#prebuilt) this.#routeCache.seed(this.#prebuilt);
163
+ const context = this.#context;
164
+ if (this.#prebuilt) context.routeCache.seed(this.#prebuilt);
334
165
 
335
- const clientServePrefix = `/_akan/client`;
336
- const clientOutputDir = `${this.#artifactDir}/client`;
337
- const dictServePrefix = "/_akan/dict";
338
- const dictOutputDir = `${this.#artifactDir}/dict`;
339
- const stylesServePrefix = "/_akan/styles";
340
- const stylesOutputDir = `${this.#artifactDir}/styles`;
341
- const fontsServePrefix = "/_akan/fonts";
342
- const fontsOutputDir = `${this.#artifactDir}/fonts`;
343
166
  const localCsrDir = path.join(process.cwd(), "csr");
344
167
  const csrOutputDir = fs.existsSync(localCsrDir) ? localCsrDir : path.join(this.#artifactDir, "csr");
345
168
  const publicDir = path.join(process.env.AKAN_APP_DIR ?? path.dirname(Bun.main), "public");
346
- const shippedPublicFiles = this.#prodMode ? WebRouter.#shippedFiles(publicDir) : null;
347
- const imageCacheDir = path.join(this.#artifactDir, "image-cache");
169
+ const siteFiles = new WebSiteFiles(context, { rsc: this.#rsc, publicDir });
348
170
  const imageOptimizer = new ImageOptimizer({
349
171
  publicDir,
350
- cacheDir: imageCacheDir,
172
+ cacheDir: path.join(this.#artifactDir, "image-cache"),
351
173
  prodMode: this.#prodMode,
352
- config: this.#artifact.imageConfig,
174
+ config: context.artifact.imageConfig,
353
175
  });
354
176
 
355
177
  const renderEnvRoutes: HttpRoutes = {
356
- ...(this.web.csr
357
- ? {
358
- "/__csr": async (req) => {
359
- this.#requestStats.csr += 1;
360
- if (this.#csrDevShell) return await this.#serveCsrDevShell(req, "/", this.#csrDevShell);
361
- const csrHtml = await this.#resolveCsrHtml(csrOutputDir, "/");
362
- const csrFile = csrHtml ? Bun.file(csrHtml) : null;
363
- const htmlText =
364
- csrFile && (await csrFile.exists())
365
- ? await csrFile.text()
366
- : `<!doctype html>
367
- <html lang="en">
368
- <head>
369
- <meta charset="utf-8" />
370
- <title>Minimal</title>
371
- <base href="/" />
372
- <meta name="viewport" content="width=device-width, initial-scale=1" />
373
- </head>
374
- <body>
375
- <div id="root"></div>
376
- <script type="module" src="/csr.js"></script>
377
- </body>
378
- </html>`;
379
- return new Response(this.#withCsrHmr(htmlText), { headers: this.#htmlResponseHeaders(200, req) });
380
- },
381
- ...(this.#csrDevShell
382
- ? {
383
- [`${CSR_DEV_ROUTE_PREFIX}*`]: async (req: Request) => {
384
- this.#requestStats.staticAsset += 1;
385
- return (await this.#csrDevShell?.serve(req)) ?? new Response("Not Found", { status: 404 });
386
- },
387
- }
388
- : {}),
389
- }
390
- : {}),
178
+ ...(this.web.csr ? this.#csr.routes(csrOutputDir) : {}),
391
179
  ...(this.#ssrDevShell
392
180
  ? {
393
181
  [`${SSR_DEV_ROUTE_PREFIX}*`]: async (req: Request) => {
394
- this.#requestStats.staticAsset += 1;
182
+ context.stats.staticAsset += 1;
395
183
  return (await this.#ssrDevShell?.serve(req)) ?? new Response("Not Found", { status: 404 });
396
184
  },
397
185
  }
398
186
  : {}),
399
- [`${clientServePrefix}/*`]: async (req) => {
400
- this.#requestStats.staticAsset += 1;
401
- const url = new URL(req.url);
402
- const filePath = resolveStaticPath(clientOutputDir, url.pathname.slice(clientServePrefix.length + 1));
403
- if (!filePath) return new Response("Not Found", { status: 404 });
404
- return WebRouter.#fileResponse(req, filePath, {
405
- contentType: Bun.file(filePath).type || "application/javascript",
406
- cacheControl: this.#prodMode ? "public, max-age=31536000, immutable" : "no-store",
407
- });
408
- },
409
- [`${stylesServePrefix}/*`]: (req) => {
410
- this.#requestStats.staticAsset += 1;
411
- const url = new URL(req.url);
412
- if (this.#prodMode) {
413
- const filePath = resolveStaticPath(stylesOutputDir, url.pathname.slice(`${stylesServePrefix}/`.length));
414
- if (filePath) {
415
- return WebRouter.#fileResponse(req, filePath, {
416
- contentType: "text/css; charset=utf-8",
417
- cacheControl: "public, max-age=31536000, immutable",
418
- });
419
- }
420
- }
421
- const cssBytes = this.renderState.cssBytesByUrl[url.pathname];
422
- if (!cssBytes) return new Response("Not Found", { status: 404 });
423
- const headers = assetHeaders({
424
- contentType: "text/css; charset=utf-8",
425
- cacheControl: "no-store",
426
- });
427
- return new Response(
428
- cssBytes.buffer.slice(cssBytes.byteOffset, cssBytes.byteOffset + cssBytes.byteLength) as ArrayBuffer,
429
- { headers },
430
- );
431
- },
432
- [`${fontsServePrefix}/*`]: (req) => {
433
- this.#requestStats.staticAsset += 1;
434
- const url = new URL(req.url);
435
- const filePath = resolveStaticPath(fontsOutputDir, url.pathname.slice(`${fontsServePrefix}/`.length));
436
- if (!filePath) return new Response("Not Found", { status: 404 });
437
- return WebRouter.#fileResponse(req, filePath, {
438
- contentType: Bun.file(filePath).type || "font/woff2",
439
- cacheControl: this.#prodMode ? "public, max-age=31536000, immutable" : "no-store",
440
- anyOrigin: true,
441
- });
442
- },
443
- [`${dictServePrefix}/*`]: (req) => {
444
- this.#requestStats.staticAsset += 1;
445
- const url = new URL(req.url);
446
- const filePath = resolveStaticPath(dictOutputDir, url.pathname.slice(`${dictServePrefix}/`.length));
447
- if (!filePath) return new Response("Not Found", { status: 404 });
448
- return WebRouter.#fileResponse(req, filePath, {
449
- contentType: "text/javascript; charset=utf-8",
450
- cacheControl: this.#prodMode ? "public, max-age=31536000, immutable" : "no-store",
451
- });
452
- },
453
- "/_akan/image": (req) => {
454
- this.#requestStats.image += 1;
455
- return imageOptimizer.handle(req);
456
- },
187
+ ...WebAssetRoutes.build(context, { artifactDir: this.#artifactDir, imageOptimizer }),
457
188
  ...(!this.#prodMode
458
189
  ? {
459
190
  "/_akan/hmr": (req: Request) =>
460
191
  this.#devHmr?.handleWs(req) ?? new Response("HMR unavailable", { status: 404 }),
461
192
  }
462
193
  : {}),
463
- "/__rsc": SessionRefresh.answering(async (req) => {
464
- const prefetch = req.headers.get(AKAN_RSC_PREFETCH_HEADER) === "1";
465
- this.#requestStats[prefetch ? "rscPrefetch" : "rscNavigation"] += 1;
466
- try {
467
-
468
- const importMap = req.headers.get(AKAN_RSC_IMPORT_MAP_HEADER);
469
- if (importMap && importMap !== this.#importMapKey)
470
- return new Response("Conflict", {
471
- status: 409,
472
- headers: { "Content-Type": "text/plain; charset=utf-8", "Cache-Control": "no-store" },
473
- });
474
- const reqUrl = new URL(req.url);
475
-
476
- const clientOrigin = getClientFacingOrigin(req);
477
- const target = reqUrl.searchParams.get("url");
478
- const rawTargetUrl = target ? new URL(target, clientOrigin) : reqUrl;
479
- const i18n = this.#artifact.i18n;
480
- const { locale: targetLocale, path: targetPath, isPrefixed } = LocalePath.split(rawTargetUrl.pathname, i18n);
481
- const localizedTargetUrl = new URL(rawTargetUrl);
482
- if (targetLocale && !isPrefixed) localizedTargetUrl.pathname = `/${targetLocale}${rawTargetUrl.pathname}`;
483
- const requestBasePath = this.#requestBasePath(req);
484
- const normalizedTarget = normalizeRscTargetUrlForHostBasePath(localizedTargetUrl, {
485
- basePath: requestBasePath,
486
- basePaths: this.#artifact.basePaths,
487
- i18n,
488
- seedEntries: this.#seedIndex.entries,
489
- });
490
- const targetUrl = normalizedTarget.url;
491
- if (!WebRouter.#isTrustedRscTarget(clientOrigin, targetUrl))
492
- return new Response("Bad Request", { status: 400 });
493
- await SessionRefresh.apply(req);
494
- const manifest = await this.#ensureRoute(targetUrl);
495
- const rscHeaders = new Headers(req.headers);
496
- if (normalizedTarget.basePath) rscHeaders.set("x-base-path", normalizedTarget.basePath);
497
-
498
- if (targetLocale) {
499
- rscHeaders.set("x-locale", targetLocale);
500
- rscHeaders.set("x-path", targetPath);
501
- }
502
- const rscReq = new Request(targetUrl, { method: "GET", headers: rscHeaders });
503
- const result = await this.#rsc.renderWithMeta(rscReq, {
504
- clientManifest: manifest.clientManifest,
505
- signal: req.signal,
506
- clientIp: SignalContext.clientIpOf(req),
507
- prefetch,
508
- });
509
- if (result.type === "redirect")
510
- return createRscRedirectResponse(result.location, result.method, result.status);
511
- if (result.type === "not-found") return createRscNotFoundFallbackResponse();
512
- if (result.status && result.status >= 500)
513
- return this.#renderRscErrorResponse("__rsc", "Internal Server Error");
514
- const response = await createRscNavigationStreamResponse(result, { explain: !this.#prodMode });
515
- const dictionaryUrl = this.#dictionaryUrlOf(rscHeaders, targetUrl.pathname);
516
- if (dictionaryUrl) response.headers.set(AKAN_RSC_DICTIONARY_HEADER, dictionaryUrl);
517
- return response;
518
- } catch (err) {
519
- return this.#renderRscErrorResponse("__rsc", err);
520
- }
521
- }),
522
- ...(!this.#prodMode || process.env.AKAN_EXPOSE_RSC_MANIFEST === "1"
523
- ? {
524
- "/__rsc/manifest": () =>
525
- new Response(JSON.stringify(this.#routeCache.merged.clientManifest, null, 2), {
526
- headers: applySecurityHeaders(
527
- new Headers({ "Content-Type": "application/json; charset=utf-8", "Cache-Control": "no-store" }),
528
- ),
529
- }),
530
- }
531
- : {}),
532
- [APPLE_APP_SITE_ASSOCIATION_PATH]: () =>
533
- WebRouter.#deepLinkAssociationResponse(APPLE_APP_SITE_ASSOCIATION_PATH, this.#artifact, {
534
- cacheControl: this.#prodMode ? "public, max-age=3600" : "no-store",
535
- }) ?? new Response("Not Found", { status: 404 }),
536
- [ANDROID_ASSET_LINKS_PATH]: () =>
537
- WebRouter.#deepLinkAssociationResponse(ANDROID_ASSET_LINKS_PATH, this.#artifact, {
538
- cacheControl: this.#prodMode ? "public, max-age=3600" : "no-store",
539
- }) ?? new Response("Not Found", { status: 404 }),
540
-
541
- "/.well-known/*": () =>
542
- new Response("Not Found", {
543
- status: 404,
544
- headers: { "Content-Type": "text/plain; charset=utf-8", "Cache-Control": "no-store" },
545
- }),
194
+ ...this.#rscRoute.routes(),
195
+ ...WellKnownRoutes.build(context.artifact, this.#prodMode),
546
196
  "/*": SessionRefresh.answering(async (req) => {
547
197
  const url = new URL(req.url);
548
198
  if (url.pathname.endsWith("/_akan/image")) {
549
- this.#requestStats.image += 1;
199
+ context.stats.image += 1;
550
200
  return imageOptimizer.handle(req);
551
201
  }
552
-
553
202
  if (this.web.csr) {
554
- const isCsr = url.searchParams.get("csr") === "true";
555
- if (isCsr) {
556
- this.#requestStats.csr += 1;
557
- if (this.#csrDevShell) return await this.#serveCsrDevShell(req, url.pathname, this.#csrDevShell);
558
- const csrHtml = await this.#resolveCsrHtml(csrOutputDir, url.pathname);
559
- if (!csrHtml) return this.#csrUnavailableResponse(url.pathname);
560
- const html = await Bun.file(csrHtml).text();
561
- return new Response(this.#withCsrHmr(html), { headers: this.#htmlResponseHeaders(200, req) });
562
- }
563
-
564
- const csrAssetPath = path.extname(url.pathname) ? resolveStaticPath(csrOutputDir, url.pathname) : null;
565
- if (csrAssetPath && (await Bun.file(csrAssetPath).exists())) {
566
- this.#requestStats.staticAsset += 1;
567
- return WebRouter.#fileResponse(req, csrAssetPath, {
568
- contentType: Bun.file(csrAssetPath).type || "application/octet-stream",
569
- cacheControl: this.#prodMode ? "public, max-age=31536000, immutable" : undefined,
570
- });
571
- }
572
- }
573
-
574
- const filePath = resolveStaticPath(publicDir, url.pathname);
575
- if (filePath && (await WebRouter.#isPublicFile(filePath, url.pathname, shippedPublicFiles))) {
576
- this.#requestStats.staticAsset += 1;
577
- const contentType = Bun.file(filePath).type || "application/octet-stream";
578
- return WebRouter.#fileResponse(req, filePath, {
579
- contentType,
580
-
581
- cacheControl: this.#prodMode ? "public, max-age=300, stale-while-revalidate=86400" : "no-store",
582
- anyOrigin: contentType.startsWith("font/"),
583
- });
584
- }
585
-
586
- if (url.pathname === "/robots.txt") {
587
- return new Response(createDefaultRobotsTxt(), {
588
- headers: {
589
- "Content-Type": "text/plain; charset=utf-8",
590
- "Cache-Control": this.#prodMode ? "public, max-age=3600" : "no-store",
591
- },
592
- });
593
- }
594
-
595
- const manifestBasePath = getWebManifestBasePath(
596
- url.pathname,
597
- this.#artifact.basePaths,
598
- this.#requestBasePath(req),
599
- );
600
- if (manifestBasePath !== undefined) {
601
- const manifestResponse = await this.#webManifestResponse(manifestBasePath);
602
- if (manifestResponse) return manifestResponse;
603
- }
604
-
605
- const sitemapBasePath = getSitemapBasePath(url.pathname, this.#artifact.basePaths, this.#requestBasePath(req));
606
- if (sitemapBasePath !== undefined) {
607
- return new Response(
608
- createDefaultSitemapXml({
609
- origin: getClientFacingOrigin(req),
610
- basePath: sitemapBasePath,
611
- entries: this.#seedIndex.entries,
612
- i18n: parseAkanI18nEnv(),
613
- }),
614
- {
615
- headers: {
616
- "Content-Type": "application/xml; charset=utf-8",
617
- "Cache-Control": this.#prodMode ? "public, max-age=3600" : "no-store",
618
- },
619
- },
620
- );
621
- }
622
-
623
- const subRouteIndex = this.#localSubRouteIndexResponse(req, url);
624
- if (subRouteIndex) return await subRouteIndex;
625
-
626
- try {
627
- this.#requestStats.fullSsr += 1;
628
- await SessionRefresh.apply(req);
629
- const manifest = await this.#ensureRoute(url);
630
- const isCrawler = isCrawlerUserAgent(req.headers.get("user-agent"));
631
- const htmlCacheDecision = this.#getHtmlCacheEntry(req, url, isCrawler);
632
- const htmlCacheEntry = htmlCacheDecision.entry;
633
- const cachedHtml = htmlCacheEntry ? this.#getCachedHtml(htmlCacheEntry.key) : null;
634
- if (cachedHtml) {
635
- const cachedHeaders = this.#htmlResponseHeaders(200, req);
636
- cachedHeaders.set("X-Akan-Cache", "HIT");
637
- return encodedBodyResponse(req, cachedHtml, { headers: cachedHeaders });
638
- }
639
- const rscResult = await this.#rsc.renderWithMeta(req, {
640
- clientManifest: manifest.clientManifest,
641
- signal: req.signal,
642
- clientIp: SignalContext.clientIpOf(req),
643
- });
644
- if (rscResult.type === "redirect")
645
- return createDocumentRedirectResponse(rscResult.location, url, rscResult.status);
646
- if (rscResult.type === "not-found") return this.#renderSystemNotFoundFallbackResponse(req, url);
647
-
648
- const cookieTheme = WebRouter.#cookieValue(req, "theme");
649
- const hostRequestStore = createRequestStore(req);
650
- const dictionaryUrl = this.#dictionaryUrlOf(req.headers, url.pathname);
651
- const extraBootstrapInline = [
652
- rscResult.trace?.routeState
653
- ? `self.__AKAN_RSC_INITIAL_STATE__=${JSON.stringify(rscResult.trace.routeState)};`
654
- : "",
655
- dictionaryUrl ? `self.__AKAN_DICT_URL__=${JSON.stringify(dictionaryUrl)};` : "",
656
- `self.__AKAN_IMPORT_MAP_KEY__=${JSON.stringify(this.#importMapKey)};`,
657
- this.#ssrDevShell
658
- ? SsrDevShim.script(await this.#ssrDevShell.readManifest(), Object.keys(this.#artifact.vendorMap))
659
- : "",
660
- !this.#prodMode ? HMR_CLIENT_SCRIPT : "",
661
- ]
662
- .filter(Boolean)
663
- .join("\n");
664
- const htmlStream = await new SsrFromRscRenderer().render({
665
- request: req,
666
- requestStore: hostRequestStore,
667
- rscStream: rscResult.stream,
668
- ssrManifest: manifest.ssrManifest,
669
- bootstrapModules: [this.#artifact.rscClientUrl],
670
- modulePreloads: dictionaryUrl ? [dictionaryUrl] : undefined,
671
- modulePreloadPlan: this.#modulePreloadPlan,
672
- extraBootstrapInline: extraBootstrapInline || undefined,
673
- importmap: this.#artifact.vendorMap,
674
-
675
- get theme() {
676
- return cookieTheme ?? rscResult.theme ?? "system";
677
- },
678
- lateControl: rscResult.lateControl,
679
- waitForAllReady: rscResult.trace?.ssrBlocking ?? false,
680
- inlineBoundaries: isCrawler,
681
- onCancel: (reason: unknown) => {
682
- rscResult.cancel(reason);
683
- },
684
- });
685
-
686
- const lateControl = await Promise.race([rscResult.lateControl, Promise.resolve(null)]);
687
- if (lateControl?.type === "redirect") {
688
- cancelStreamForHeadResponse(htmlStream, "redirected before the response started");
689
- return createDocumentRedirectResponse(lateControl.location, url, lateControl.status);
690
- }
691
- const responseStatus = lateControl?.type === "not-found" ? 404 : (rscResult.status ?? 200);
692
- const responseHeaders = this.#htmlResponseHeaders(responseStatus, req);
693
- if (req.method === "HEAD") {
694
- const headers = new Headers(responseHeaders);
695
- if (htmlCacheEntry && responseStatus === 200) headers.set("X-Akan-Cache", "MISS");
696
- else if (htmlCacheDecision.reason) {
697
- headers.set("X-Akan-Cache", "BYPASS");
698
- headers.set("X-Akan-Cache-Reason", htmlCacheDecision.reason);
699
- }
700
- cancelStreamForHeadResponse(htmlStream, "HEAD response does not consume body");
701
- return new Response(null, { status: responseStatus, headers });
702
- }
703
- if (htmlCacheEntry && responseStatus === 200) {
704
- const headers = new Headers(responseHeaders);
705
- headers.set("X-Akan-Cache", "MISS");
706
- let htmlStoreTtl = htmlCacheEntry.ttl;
707
- let htmlCacheMetadata: Omit<CachedHtmlResult, "body"> = { pathname: url.pathname };
708
- const shouldCacheHtml = Promise.all([rscResult.lateControl, rscResult.cacheState]).then(
709
- ([control, cacheState]) => {
710
- const storeTtl = resolveHtmlRouteCacheStoreTtl({
711
- baseTtl: htmlCacheEntry.ttl,
712
- workerCacheState: cacheState,
713
- hostRequestStore,
714
- lateControl: control,
715
- });
716
- if (storeTtl === null) return false;
717
- htmlStoreTtl = storeTtl;
718
- htmlCacheMetadata = {
719
- pathname: url.pathname,
720
- routeId: cacheState.routeId,
721
- tags: cacheState.tags,
722
- };
723
- return true;
724
- },
725
- );
726
- return new Response(
727
- cacheHtmlWhileStreaming(
728
- htmlStream,
729
- (html) => {
730
- void encodeBody(html).then((body) =>
731
- this.#htmlCache.set(htmlCacheEntry.key, { body, ...htmlCacheMetadata }, htmlStoreTtl),
732
- );
733
- },
734
- {
735
- shouldCache: () => shouldCacheHtml,
736
- maxBodyBytes:
737
- parsePositiveInt(process.env.AKAN_HTML_RESULT_CACHE_MAX_BODY_BYTES) ??
738
- DEFAULT_HTML_RESULT_CACHE_MAX_BODY_BYTES,
739
- onSkip: (reason) => {
740
- this.#logger.verbose(`html cache store skipped pathname=${url.pathname} reason=${reason}`);
741
- },
742
- },
743
- ),
744
- {
745
- status: responseStatus,
746
- headers,
747
- },
748
- );
749
- }
750
- const headers = new Headers(responseHeaders);
751
- if (htmlCacheDecision.reason) {
752
- headers.set("X-Akan-Cache", "BYPASS");
753
- headers.set("X-Akan-Cache-Reason", htmlCacheDecision.reason);
754
- }
755
- return new Response(htmlStream, {
756
- status: responseStatus,
757
- headers,
758
- });
759
- } catch (err) {
760
- return this.#renderErrorResponse(req, url.pathname, err);
203
+ const csrResponse = await this.#csr.answer(req, url, csrOutputDir);
204
+ if (csrResponse) return csrResponse;
761
205
  }
206
+ const siteFile = await siteFiles.answer(req, url);
207
+ if (siteFile) return siteFile;
208
+ return await this.#document.render(req, url);
762
209
  }),
763
210
  };
764
211
  return { renderEnvRoutes, hmrHub: this.#hub, builderRpc: this.#builderRpc };
@@ -785,10 +232,12 @@ export class WebRouter {
785
232
  }
786
233
 
787
234
  pagePrompts(): PagePromptSource {
235
+ const staticApps = new WebStaticApp(this.#context, () => this.#rsc);
788
236
  return {
789
237
  list: () => this.#rsc.listPagePrompts(),
790
238
  visible: (input) => this.#rsc.visiblePagePrompts(input),
791
239
  run: (input) => this.#rsc.runPagePrompt(input),
240
+ render: (input) => staticApps.render(input),
792
241
  };
793
242
  }
794
243
 
@@ -803,8 +252,8 @@ export class WebRouter {
803
252
  read: async (app) => {
804
253
  if (!PageDefinition.promptName.test(app)) return null;
805
254
  const viewPath = path.join(viewDir, `${app}.html`);
806
- if (this.#csrDevShell) await this.#buildMcpAppViews();
807
- else if (!fs.existsSync(viewPath)) await this.#armCsrArtifact("mcp app view");
255
+ if (this.#csr.devShell) await this.#csr.buildMcpAppViews();
256
+ else if (!fs.existsSync(viewPath)) await this.#csr.armArtifact("mcp app view");
808
257
  const file = Bun.file(viewPath);
809
258
  if (!(await file.exists())) return null;
810
259
  const cached = views.get(app);
@@ -826,366 +275,38 @@ export class WebRouter {
826
275
 
827
276
  getMetrics(): AkanMetricsReport {
828
277
  const ssrStats = SsrFromRscRenderer.getChunkRegistryStats();
278
+ const stats = this.#context.stats;
829
279
  return {
830
280
  ...this.#rsc.getMetrics(),
831
281
  ssrChunkRegistrySize: ssrStats.ssrChunkRegistrySize,
832
282
  ssrChunkLoadCount: ssrStats.ssrChunkLoadCount,
833
283
  ssrChunkCacheHitCount: ssrStats.ssrChunkCacheHitCount,
834
284
  ssrChunkEvictionCount: ssrStats.ssrChunkEvictionCount,
835
- httpFullSsrCount: this.#requestStats.fullSsr,
836
- httpRscNavigationCount: this.#requestStats.rscNavigation,
837
- httpRscPrefetchCount: this.#requestStats.rscPrefetch,
838
- httpStaticAssetCount: this.#requestStats.staticAsset,
839
- httpCsrCount: this.#requestStats.csr,
840
- httpImageCount: this.#requestStats.image,
841
- httpHtmlCacheEntries: this.#htmlCache.size,
842
- httpHtmlCacheBytes: this.#htmlCache.byteSize,
843
- httpHtmlCacheHits: this.#htmlCacheHits,
844
- httpHtmlCacheMisses: this.#htmlCacheMisses,
845
- httpHtmlCacheBypass: this.#htmlCacheBypass,
285
+ httpFullSsrCount: stats.fullSsr,
286
+ httpRscNavigationCount: stats.rscNavigation,
287
+ httpRscPrefetchCount: stats.rscPrefetch,
288
+ httpStaticAssetCount: stats.staticAsset,
289
+ httpCsrCount: stats.csr,
290
+ httpImageCount: stats.image,
291
+ ...this.#htmlCache.metrics(),
846
292
  };
847
293
  }
848
294
 
849
295
  invalidateRouteCaches(invalidation?: string | RouteCacheInvalidation): void {
850
- const payload = typeof invalidation === "string" ? { reason: invalidation } : invalidation;
851
- if (!hasRouteCacheInvalidationScope(payload)) {
852
- this.#htmlCache.clear();
853
- } else if (payload) {
854
- this.#htmlCache.invalidate((_key, value) =>
855
- shouldInvalidateRouteCacheEntry(
856
- {
857
- pathname: value.pathname,
858
- routeId: value.routeId,
859
- tags: value.tags,
860
- },
861
- payload,
862
- ),
863
- );
864
- }
296
+ this.#htmlCache.invalidate(invalidation);
865
297
  this.#rsc.invalidateRouteResultCache(invalidation);
866
298
  }
867
299
 
868
- #requestBasePath(req: Request): string | null {
869
- const headerBasePath = req.headers.get("x-base-path");
870
- if (headerBasePath && this.#artifact.basePaths.includes(headerBasePath)) return headerBasePath;
871
- return WebRouter.#basePathForRequestHost(req, this.#subRoutes);
872
- }
873
-
874
- static #basePathForRequestHost(req: Request, subRoutes: Record<string, string[]>): string | null {
875
- const host = normalizeHost(req.headers.get("x-forwarded-host")?.split(",")[0]?.trim() ?? req.headers.get("host"));
876
- if (!host) return null;
877
- for (const [basePath, domains] of Object.entries(subRoutes)) {
878
- if (domains.some((domain) => normalizeHost(domain) === host)) return basePath;
879
- }
880
- return null;
881
- }
882
-
883
- static #isTrustedRscTarget(clientOrigin: string, targetUrl: URL): boolean {
884
- try {
885
- if (targetUrl.origin === clientOrigin) return true;
886
-
887
- return targetUrl.hostname === new URL(clientOrigin).hostname;
888
- } catch {
889
- return false;
890
- }
891
- }
892
-
893
- #getHtmlCacheEntry(req: Request, url: URL, isCrawler: boolean): { entry: RouteCacheEntry | null; reason?: string } {
894
-
895
- if (this.#ssrDevShell) {
896
- this.#htmlCacheBypass += 1;
897
- return { entry: null, reason: "dev-registry" };
898
- }
899
- const decision = resolvePublicRouteCacheEntryDecision({
900
- request: req,
901
- url,
902
- theme: WebRouter.#cookieValue(req, "theme"),
903
- variant: isCrawler ? "crawler" : undefined,
904
- defaultEnabled: this.#prodMode,
905
- defaultAllow: this.#prodMode,
906
- env: {
907
- enabled: process.env.AKAN_HTML_RESULT_CACHE,
908
- ttl: process.env.AKAN_HTML_RESULT_CACHE_TTL,
909
- allow: process.env.AKAN_HTML_RESULT_CACHE_PATHS,
910
- deny: process.env.AKAN_HTML_RESULT_CACHE_EXCLUDE_PATHS,
911
- },
912
- });
913
- if (!decision.entry) this.#htmlCacheBypass += 1;
914
- return decision;
915
- }
916
-
917
- #getCachedHtml(cacheKey: string): EncodedBody | null {
918
- const cached = this.#htmlCache.get(cacheKey);
919
- if (!cached) {
920
- this.#htmlCacheMisses += 1;
921
- return null;
922
- }
923
- this.#htmlCacheHits += 1;
924
- return cached.body;
925
- }
926
-
927
- static #cookieValue(req: Request, name: string): string | undefined {
928
- return CookieJar.parse(req.headers.get("cookie")).read(name).value;
929
- }
930
-
931
- async #ensureRoute(url: URL) {
932
- const started = Date.now();
933
- const matched =
934
- RouteSeedIndexStore.match(url.pathname, this.#seedIndex.entries) ??
935
- RouteSeedIndexStore.matchPrefix(url.pathname, this.#seedIndex.entries);
936
- if (matched) await this.#routeCache.ensure(matched.entry.routeId, matched.entry.seeds);
937
- this.#logger.verbose(
938
- `[route-cache] ensure pathname=${url.pathname} routeId=${matched?.entry.routeId ?? "(none)"} in ${Date.now() - started}ms`,
939
- );
940
- return this.#mergeRuntimeManifest();
941
- }
942
-
943
- #mergeRuntimeManifest(): MergedManifest {
944
- const revision = this.#routeCache.revision;
945
- if (this.#runtimeManifest?.revision === revision) return this.#runtimeManifest.manifest;
946
- const snapshot = this.#routeCache.snapshot();
947
- const manifest: MergedManifest = {
948
- ...snapshot,
949
- clientManifest: Object.assign({}, this.#artifact.rscRuntimeClientManifest, snapshot.clientManifest),
950
- ssrManifest: {
951
- moduleLoading: null,
952
- moduleMap: Object.assign({}, this.#artifact.rscRuntimeSsrManifest?.moduleMap, snapshot.ssrManifest.moduleMap),
953
- },
954
- };
955
- this.#runtimeManifest = { revision, manifest };
956
- return manifest;
957
- }
958
- #renderSystemNotFoundFallbackResponse(req: Request, url: URL): Promise<Response> {
959
- return createSystemPageResponse({
960
- kind: "not-found",
961
- method: req.method,
962
- pathname: url.pathname,
963
- lang: getPathnameLocale(url.pathname, this.#artifact.i18n),
964
- homeHref: this.#getSystemPageHomeHref(req, url.pathname),
965
- stylesheetHref: this.#getStylesheetHref(req, url.pathname),
966
- });
967
- }
968
-
969
- async #webManifestResponse(basePath: string | null): Promise<Response | null> {
970
- try {
971
- const manifest = await this.#rsc.webManifest(basePath);
972
- if (!manifest) return null;
973
- return new Response(JSON.stringify(manifest), {
974
- headers: {
975
- "Content-Type": "application/manifest+json; charset=utf-8",
976
- "Cache-Control": this.#prodMode ? "public, max-age=3600" : "no-store",
977
- },
978
- });
979
- } catch (err) {
980
- this.#logger.warn(
981
- `web manifest unavailable basePath=${basePath ?? "(root)"}: ${err instanceof Error ? err.message : String(err)}`,
982
- );
983
- return new Response("Service Unavailable", {
984
- status: 503,
985
- headers: { "Content-Type": "text/plain; charset=utf-8", "Cache-Control": "no-store" },
986
- });
987
- }
988
- }
989
-
990
- #localSubRouteIndexResponse(req: Request, url: URL): Promise<Response> | null {
991
- if (process.env.AKAN_PUBLIC_ENV !== "local" || !this.#artifact.basePaths.length) return null;
992
- if (!WebRouter.#isSiteRootPathname(url.pathname, this.#artifact.i18n)) return null;
993
- return createSubRouteIndexResponse({
994
- method: req.method,
995
- locale: getPathnameLocale(url.pathname, this.#artifact.i18n),
996
- basePaths: this.#artifact.basePaths,
997
- subRoutes: this.#subRoutes,
998
- });
999
- }
1000
-
1001
- static #isSiteRootPathname(pathname: string, i18n: AkanI18nConfig): boolean {
1002
- const segments = pathname.split("/").filter(Boolean);
1003
- if (!segments.length) return true;
1004
- return segments.length === 1 && i18n.locales.includes(segments[0] ?? "");
1005
- }
1006
-
1007
- #renderErrorResponse(req: Request, scope: string, err: unknown): Promise<Response> {
1008
- if (WebRouter.#isExpectedRequestAbort(err)) return Promise.resolve(WebRouter.#clientClosedResponse());
1009
- const message = err instanceof Error ? err.message : String(err);
1010
- this.#logger.error(`[SSR] render failed scope=${scope}: ${message}`);
1011
- this.#hub?.broadcast({ type: "error", message });
1012
- return createSystemPageResponse({
1013
- kind: "error",
1014
- method: req.method,
1015
- pathname: scope,
1016
- lang: getPathnameLocale(new URL(req.url).pathname, this.#artifact.i18n),
1017
- homeHref: this.#getSystemPageHomeHref(req, new URL(req.url).pathname),
1018
- stylesheetHref: this.#getStylesheetHref(req, new URL(req.url).pathname),
1019
- showDetails: !this.#prodMode,
1020
- error: err,
1021
- ...(this.#prodMode ? {} : { script: `self.__AKAN_HMR_SYSTEM_PAGE__=true;${HMR_CLIENT_SCRIPT}` }),
1022
- });
1023
- }
1024
-
1025
- #dictionaryUrlOf(headers: Headers, pathname: string): string | undefined {
1026
- const i18n = parseAkanI18nEnv();
1027
- const { locale } = RequestLocale.resolve(
1028
- { localeHeader: headers.get("x-locale"), pathHeader: headers.get("x-path"), pathname },
1029
- i18n,
1030
- );
1031
- const assets = this.#artifact.dictAssets ?? {};
1032
- return (assets[locale] ?? assets[i18n.defaultLocale])?.url;
1033
- }
1034
-
1035
- #renderRscErrorResponse(scope: string, err: unknown): Response {
1036
- if (WebRouter.#isExpectedRequestAbort(err)) return WebRouter.#clientClosedResponse();
1037
- const message = err instanceof Error ? err.message : String(err);
1038
- this.#logger.error(`[SSR] render failed scope=${scope}: ${message}`);
1039
- this.#hub?.broadcast({ type: "error", message });
1040
- return new Response("Internal Server Error", {
1041
- status: 500,
1042
- headers: { "Content-Type": "text/plain; charset=utf-8", "Cache-Control": "no-store" },
1043
- });
1044
- }
1045
-
1046
- static #clientClosedResponse(): Response {
1047
- return new Response(null, {
1048
- status: CLIENT_CLOSED_REQUEST_STATUS,
1049
- headers: { "Cache-Control": "no-store" },
1050
- });
1051
- }
1052
-
1053
- static #isExpectedRequestAbort(error: unknown): boolean {
1054
- if (!(error instanceof Error)) return false;
1055
- return (
1056
- error.name === "AbortError" ||
1057
- error.message === "The connection was closed." ||
1058
- error.message === "Connection closed." ||
1059
- error.message.includes("The connection was closed")
1060
- );
1061
- }
1062
-
1063
- #getSystemPageHomeHref(req: Request, pathname: string): string {
1064
- return getSystemPageHomeHref({
1065
- pathname,
1066
- i18n: this.#artifact.i18n,
1067
- basePaths: this.#artifact.basePaths,
1068
- headerBasePath: this.#requestBasePath(req),
1069
- });
1070
- }
1071
-
1072
- #getStylesheetHref(req: Request, pathname: string): string | null {
1073
- const basePath = getBasePathFromPathname(pathname, {
1074
- basePaths: Object.keys(this.renderState.cssAssets),
1075
- i18n: this.#artifact.i18n,
1076
- headerBasePath: this.#requestBasePath(req),
1077
- });
1078
- return this.renderState.cssAssets[basePath ?? ""]?.cssUrl ?? null;
1079
- }
1080
-
1081
- #htmlResponseHeaders(status: number, req: Request): Headers {
1082
- const headers = new Headers({ "Content-Type": "text/html; charset=utf-8" });
1083
- if (status >= 400 || !this.#prodMode) headers.set("Cache-Control", "no-store");
1084
- else {
1085
- const cacheControl = resolveHtmlCacheControl(req);
1086
- if (cacheControl) headers.set("Cache-Control", cacheControl);
1087
- }
1088
- const hsts = this.#prodMode ? strictTransportSecurity() : null;
1089
- if (hsts && getClientFacingOrigin(req).startsWith("https:")) headers.set("Strict-Transport-Security", hsts);
1090
- return applySecurityHeaders(headers, { html: true });
1091
- }
1092
- #withCsrHmr(html: string): string {
1093
- if (this.#prodMode) return html;
1094
- const csrGeneration = this.renderState.csrGeneration ?? null;
1095
- const flags = `self.__AKAN_HMR_CLIENT__="csr";self.__AKAN_CSR_GENERATION__=${csrGeneration};`;
1096
- return WebRouter.#injectBeforeBodyEnd(html, `<script>${flags}${HMR_CLIENT_SCRIPT}</script>`);
1097
- }
1098
-
1099
- async #serveCsrDevShell(req: Request, pathname: string, shell: CsrDevShell): Promise<Response> {
1100
- await this.#armCsrArtifact(pathname);
1101
- const basePath =
1102
- getBasePathFromPathname(pathname, { basePaths: this.#artifact.basePaths, i18n: this.#artifact.i18n }) ?? "";
1103
- const html = await shell.render({
1104
- basePath,
1105
- lang: "en",
1106
- title: process.env.AKAN_PUBLIC_APP_NAME ?? "akan",
1107
- cssHref: this.#getStylesheetHref(req, pathname),
1108
- });
1109
- if (!html) return this.#csrUnavailableResponse(pathname);
1110
- return new Response(this.#withCsrHmr(html), { headers: this.#htmlResponseHeaders(200, req) });
1111
- }
1112
- async #resolveCsrHtml(csrOutputDir: string, pathname: string): Promise<string | null> {
1113
- const resolved = WebRouter.#resolveCsrHtmlPath(csrOutputDir, pathname, this.#artifact);
1114
- if (resolved) return resolved;
1115
- await this.#armCsrArtifact(pathname);
1116
- return WebRouter.#resolveCsrHtmlPath(csrOutputDir, pathname, this.#artifact);
1117
- }
1118
- #armCsrArtifact(reason: string): Promise<unknown> {
1119
- const rpc = this.#builderRpc;
1120
-
1121
- if (this.#csrArmed || !rpc) return Promise.resolve();
1122
- return this.#singleFlight("csr", () =>
1123
- rpc
1124
- .buildCsr(reason)
1125
- .then(() => {
1126
- this.#csrArmed = true;
1127
- this.#logger.info(`[csr] dev CSR artifact built on demand (${reason})`);
1128
- })
1129
- .catch((err: unknown) => {
1130
- this.#logger.error(`[csr] on-demand build failed: ${err instanceof Error ? err.message : String(err)}`);
1131
- }),
1132
- );
1133
- }
1134
-
1135
- async #buildMcpAppViews(): Promise<void> {
1136
- const rpc = this.#builderRpc;
1137
- if (!rpc) return;
1138
- await this.#singleFlight("mcpShell", () =>
1139
- rpc.buildCsr("mcp app view", { shell: true }).catch((err: unknown) => {
1140
- this.#logger.error(`[mcp] view build failed: ${err instanceof Error ? err.message : String(err)}`);
1141
- }),
1142
- );
1143
- }
1144
- #singleFlight(kind: string, run: () => Promise<unknown>): Promise<unknown> {
1145
- const pending = this.#builds.get(kind) ?? run().finally(() => this.#builds.delete(kind));
1146
- this.#builds.set(kind, pending);
1147
- return pending;
1148
- }
1149
- #csrUnavailableResponse(pathname: string): Response {
1150
- if (this.#prodMode) return new Response("Not Found", { status: 404 });
1151
- const message = `No CSR artifact for ${pathname}. Dev CSR is built on demand; check the dev server log for a csr-build failure and verify the basePath in the URL.`;
1152
- this.#logger.warn(`[csr] ${message}`);
1153
- return new Response(message, { status: 404, headers: { "Content-Type": "text/plain; charset=utf-8" } });
1154
- }
1155
-
1156
- static async #isPublicFile(filePath: string, pathname: string, shipped: Set<string> | null) {
1157
- if (shipped && !path.extname(pathname)) return shipped.has(filePath);
1158
- return await Bun.file(filePath).exists();
1159
- }
1160
-
1161
- static #shippedFiles(dir: string): Set<string> {
1162
- const files = new Set<string>();
1163
- if (!fs.existsSync(dir)) return files;
1164
- const scan = new Bun.Glob("**/*").scanSync({ cwd: dir, onlyFiles: true, dot: true, followSymlinks: true });
1165
- for (const relative of scan) {
1166
- const filePath = path.resolve(dir, relative);
1167
- if (staysInTree(dir, filePath)) files.add(filePath);
1168
- }
1169
- return files;
1170
- }
1171
-
1172
- static #injectBeforeBodyEnd(html: string, snippet: string): string {
1173
- const matches = [...html.matchAll(/<\/body\s*>/gi)];
1174
- const last = matches.at(-1);
1175
- if (!last || last.index === undefined) return `${html}\n${snippet}`;
1176
- return `${html.slice(0, last.index)}${snippet}\n${html.slice(last.index)}`;
1177
- }
1178
-
1179
300
  /** `null` when the build has no web artifact (an api-only build, or no `page/`): boot without a web surface. */
1180
301
  static async create({ web, upgradeHmrWs }: SsrRoutesInputs): Promise<WebRouter | null> {
1181
302
  const artifactDir = resolveArtifactDir();
1182
303
  const artifactFile = Bun.file(path.join(artifactDir, "base-artifact.json"));
1183
304
  if (!(await artifactFile.exists())) return null;
1184
- const artifact = WebRouter.#normalizeArtifact((await artifactFile.json()) as BaseBuildArtifact, artifactDir);
305
+ const artifact = WebArtifact.normalize((await artifactFile.json()) as BaseBuildArtifact, artifactDir);
1185
306
  const builtWeb = resolveWebConfig(artifact.web);
1186
307
  if (!builtWeb.ssr) return null;
1187
- const cssBytesByUrl = await WebRouter.#loadCssBytesByUrl(artifact, artifactDir);
1188
- await WebRouter.#seedDictionaries(artifact, artifactDir);
308
+ const cssBytesByUrl = await WebArtifact.loadCssBytesByUrl(artifact, artifactDir);
309
+ await WebArtifact.seedDictionaries(artifact, artifactDir);
1189
310
  const prodMode = process.env.NODE_ENV === "production" && process.env.AKAN_COMMAND_TYPE !== "start";
1190
311
 
1191
312
  const prebuilt = prodMode ? await RoutesManifestStore.read(artifactDir) : null;
@@ -1203,178 +324,21 @@ export class WebRouter {
1203
324
  new Logger("WebRouter").error(`RSC worker failed to load the pages bundle: ${String(error)}`);
1204
325
  process.exit(1);
1205
326
  });
1206
- else await rsc.ready;
1207
- const seedIndex = await RouteSeedIndexStore.load(artifactDir);
1208
- return new WebRouter({
1209
- artifact,
1210
- web: { ssr: true, csr: web.csr && builtWeb.csr },
1211
- cssBytesByUrl,
1212
- rsc,
1213
- seedIndex,
1214
- upgradeHmrWs,
1215
- prebuilt,
1216
- });
1217
- }
1218
-
1219
- static #normalizeArtifact(artifact: BaseBuildArtifact, artifactDir: string): BaseBuildArtifact {
1220
- const normalizedArtifactDir = path.resolve(artifactDir);
1221
- const pagesBundlePath = WebRouter.#resolveArtifactPath(artifact.pagesBundlePath, normalizedArtifactDir);
1222
- return {
1223
- ...artifact,
1224
- cssAssets: artifact.cssAssets ?? {},
1225
- dictAssets: artifact.dictAssets ?? {},
1226
- pagesBundlePath,
1227
- rscRuntimeSsrManifest: artifact.rscRuntimeSsrManifest
1228
- ? WebRouter.#normalizeSsrManifest(artifact.rscRuntimeSsrManifest, normalizedArtifactDir)
1229
- : undefined,
1230
- i18n: artifact.i18n ?? DEFAULT_AKAN_I18N,
1231
- };
1232
- }
1233
-
1234
- static #normalizeSsrManifest(ssrManifest: SsrManifest, artifactDir: string): SsrManifest {
1235
- return {
1236
- ...ssrManifest,
1237
- moduleMap: Object.fromEntries(
1238
- Object.entries(ssrManifest.moduleMap).map(([entryUrl, byName]) => [
1239
- entryUrl,
1240
- Object.fromEntries(
1241
- Object.entries(byName).map(([name, entry]) => [
1242
- name,
1243
- {
1244
- ...entry,
1245
- id: WebRouter.#resolveArtifactPath(entry.id, artifactDir),
1246
- chunks: entry.chunks.map((chunk) => WebRouter.#resolveArtifactPath(chunk, artifactDir)),
1247
- },
1248
- ]),
1249
- ),
1250
- ]),
1251
- ),
1252
- };
1253
- }
1254
-
1255
- static async #loadCssBytesByUrl(
1256
- artifact: BaseBuildArtifact,
1257
- artifactDir: string,
1258
- ): Promise<Record<string, Uint8Array>> {
1259
- const normalizedArtifactDir = path.resolve(artifactDir);
1260
- return Object.fromEntries(
1261
- await Promise.all(
1262
- Object.values(artifact.cssAssets ?? {}).map(async (asset) => [
1263
- asset.cssUrl,
1264
- await Bun.file(path.join(normalizedArtifactDir, asset.cssRelPath)).bytes(),
1265
- ]),
1266
- ),
1267
- );
1268
- }
1269
-
1270
- static async #seedDictionaries(artifact: BaseBuildArtifact, artifactDir: string): Promise<void> {
1271
- const normalizedArtifactDir = path.resolve(artifactDir);
1272
- await Promise.all(
1273
- Object.values(artifact.dictAssets ?? {}).map(async (asset) => {
1274
- const { lang, default: dictionary } = (await import(path.join(normalizedArtifactDir, asset.relPath))) as {
1275
- lang: string;
1276
- default: Dictionary;
1277
- };
1278
- TranslatorState.replace(lang, dictionary);
1279
- }),
1280
- );
1281
- }
1282
-
1283
- static #resolveArtifactPath(artifactPath: string, artifactDir: string): string {
1284
- if (!path.isAbsolute(artifactPath)) return path.resolve(artifactDir, artifactPath);
1285
- if (fs.existsSync(artifactPath)) return artifactPath;
1286
-
1287
- const marker = `${path.sep}.akan${path.sep}artifact${path.sep}`;
1288
- const markerIndex = artifactPath.lastIndexOf(marker);
1289
- if (markerIndex >= 0) {
1290
- const rel = artifactPath.slice(markerIndex + marker.length);
1291
- return path.resolve(artifactDir, rel);
1292
- }
1293
-
1294
- return path.resolve(artifactDir, "server", path.basename(artifactPath));
1295
- }
1296
-
1297
- static #resolveCsrHtmlPath(csrOutputDir: string, pathname: string, artifact: BaseBuildArtifact): string | null {
1298
- const basePath = getBasePathFromPathname(pathname, {
1299
- basePaths: artifact.basePaths,
1300
- i18n: artifact.i18n,
1301
- });
1302
- const filename = basePath ? `${basePath}.html` : "index.html";
1303
- const filePath = resolveStaticPath(csrOutputDir, filename);
1304
- return filePath && fs.existsSync(filePath) ? filePath : null;
1305
- }
1306
-
1307
- static async #fileResponse(req: Request, filePath: string, options: AssetHeaderOptions): Promise<Response> {
1308
- const headers = assetHeaders(options);
1309
- const file = Bun.file(filePath);
1310
- if (!(await file.exists())) return new Response("Not Found", { status: 404 });
1311
- const stat = fs.statSync(filePath);
1312
- const lastModifiedMs = Math.floor(stat.mtimeMs / 1000) * 1000;
1313
- const etag = `W/"${stat.size.toString(16)}-${lastModifiedMs.toString(16)}"`;
1314
- headers.set("ETag", etag);
1315
- headers.set("Last-Modified", new Date(lastModifiedMs).toUTCString());
1316
- if (isCompressibleContentType(options.contentType)) varyOnEncoding(headers);
1317
- if (WebRouter.#isNotModified(req, etag, lastModifiedMs)) return new Response(null, { status: 304, headers });
1318
-
1319
- return await encodedFileResponse(req, filePath, options.contentType, headers);
1320
- }
1321
-
1322
- static #deepLinkAssociationResponse(
1323
- pathname: string,
1324
- artifact: BaseBuildArtifact,
1325
- { cacheControl }: { cacheControl: string },
1326
- ) {
1327
- const associations = artifact.deepLinkAssociations ?? [];
1328
- if (pathname === APPLE_APP_SITE_ASSOCIATION_PATH) {
1329
- const details = associations
1330
- .filter((association) => association.domains.length > 0 && association.iosTeamId && association.iosAppId)
1331
- .map((association) => ({
1332
- appIDs: [`${association.iosTeamId}.${association.iosAppId}`],
1333
- components: [{ "/": "/*" }],
1334
- }));
1335
- if (details.length === 0) return null;
1336
- return WebRouter.#jsonResponse({ applinks: { apps: [], details } }, cacheControl);
327
+ try {
328
+ if (!prodMode) await rsc.ready;
329
+ const seedIndex = await RouteSeedIndexStore.load(artifactDir);
330
+ return new WebRouter({
331
+ artifact,
332
+ web: { ssr: true, csr: web.csr && builtWeb.csr },
333
+ cssBytesByUrl,
334
+ rsc,
335
+ seedIndex,
336
+ upgradeHmrWs,
337
+ prebuilt,
338
+ });
339
+ } catch (error) {
340
+ rsc.kill();
341
+ throw error;
1337
342
  }
1338
-
1339
- const packageSuffixes = process.env.AKAN_PUBLIC_ENV === "main" ? [""] : ["", ".debug"];
1340
- const assetLinks = associations
1341
- .filter(
1342
- (association) =>
1343
- association.domains.length > 0 &&
1344
- !!association.androidAppId &&
1345
- (association.androidSha256CertFingerprints?.length ?? 0) > 0,
1346
- )
1347
- .flatMap((association) =>
1348
- packageSuffixes.map((suffix) => ({
1349
- relation: ["delegate_permission/common.handle_all_urls"],
1350
- target: {
1351
- namespace: "android_app",
1352
- package_name: `${association.androidAppId}${suffix}`,
1353
- sha256_cert_fingerprints: association.androidSha256CertFingerprints,
1354
- },
1355
- })),
1356
- );
1357
- if (assetLinks.length === 0) return null;
1358
- return WebRouter.#jsonResponse(assetLinks, cacheControl);
1359
- }
1360
-
1361
- static #jsonResponse(body: unknown, cacheControl: string) {
1362
- return new Response(JSON.stringify(body, null, 2), {
1363
- headers: {
1364
- "Content-Type": "application/json; charset=utf-8",
1365
- "Cache-Control": cacheControl,
1366
- },
1367
- });
1368
- }
1369
-
1370
- static #isNotModified(req: Request, etag: string, lastModifiedMs: number): boolean {
1371
- if (req.method !== "GET" && req.method !== "HEAD") return false;
1372
- const ifNoneMatch = req.headers.get("if-none-match");
1373
- if (ifNoneMatch) return matchesIfNoneMatch(ifNoneMatch, etag);
1374
-
1375
- const ifModifiedSince = req.headers.get("if-modified-since");
1376
- if (!ifModifiedSince) return false;
1377
- const sinceMs = Date.parse(ifModifiedSince);
1378
- return Number.isFinite(sinceMs) && sinceMs >= lastModifiedMs;
1379
343
  }
1380
344
  }