akanjs 3.1.0-rc.8 → 3.1.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 (323) hide show
  1. package/CHANGELOG.md +547 -0
  2. package/README.ko.md +2 -2
  3. package/README.md +2 -2
  4. package/client/cookie.ts +5 -0
  5. package/client/csrLocation.ts +17 -72
  6. package/client/csrTypes.ts +19 -4
  7. package/client/href.ts +8 -0
  8. package/client/makePageProto.tsx +3 -2
  9. package/client/route/PageDefinition.ts +103 -10
  10. package/client/route/RouteDefinition.ts +44 -3
  11. package/client/route/RouteGuards.ts +64 -0
  12. package/client/route/index.ts +1 -0
  13. package/client/route/resolveRouteModule.ts +8 -0
  14. package/client/route/routeArgs.ts +9 -0
  15. package/client/router.ts +51 -2
  16. package/client/translator.ts +16 -0
  17. package/client/viewportMeta.ts +23 -8
  18. package/common/Logger.ts +6 -4
  19. package/common/authCookie.ts +13 -0
  20. package/common/authToken.ts +1 -12
  21. package/common/codeAgentWire.ts +8 -1
  22. package/common/index.ts +2 -8
  23. package/common/routeConvention.ts +2 -0
  24. package/constant/inputParser.ts +1 -1
  25. package/dictionary/base.dictionary.ts +11 -0
  26. package/document/database.ts +3 -0
  27. package/document/documentQuery.ts +21 -0
  28. package/document/into.ts +2 -0
  29. package/document/liveRowScope.ts +4 -8
  30. package/document/noDocumentError.ts +6 -1
  31. package/document/queryEvaluator.ts +5 -8
  32. package/fetch/appScope.ts +54 -0
  33. package/fetch/client/fetchClient.ts +46 -29
  34. package/fetch/client/httpClient.ts +38 -10
  35. package/fetch/client/sliceInitHandle.ts +2 -3
  36. package/fetch/client/wsClient.ts +3 -1
  37. package/fetch/fetchType/endpointFetch.type.ts +11 -9
  38. package/fetch/index.ts +1 -0
  39. package/index.ts +2 -0
  40. package/package.json +32 -22
  41. package/server/akanApp.ts +12 -3
  42. package/server/akanServer.ts +10 -5
  43. package/server/index.ts +1 -0
  44. package/server/mcp/McpApps.ts +44 -50
  45. package/server/mcp/McpDispatcher.ts +3 -3
  46. package/server/mcp/McpPages.ts +93 -19
  47. package/server/mcp/McpRouter.ts +14 -11
  48. package/server/memoryLimit.ts +4 -0
  49. package/server/migration/docPath.ts +121 -0
  50. package/server/migration/index.ts +15 -0
  51. package/server/migration/migrationChangeLog.ts +86 -0
  52. package/server/migration/migrationChanges.ts +70 -0
  53. package/server/migration/migrationCommand.ts +179 -0
  54. package/server/migration/migrationContext.ts +53 -0
  55. package/server/migration/migrationDefinition.ts +87 -0
  56. package/server/migration/migrationError.ts +45 -0
  57. package/server/migration/migrationLedger.ts +172 -0
  58. package/server/migration/migrationLock.ts +103 -0
  59. package/server/migration/migrationParams.ts +122 -0
  60. package/server/migration/migrationPulse.ts +39 -0
  61. package/server/migration/migrationRunner.ts +525 -0
  62. package/server/migration/migrationScope.ts +93 -0
  63. package/server/migration/migrationTable.ts +258 -0
  64. package/server/migration/migrations.ts +57 -0
  65. package/server/ops/migrateJobs.ts +145 -0
  66. package/server/ops/opsCommand.ts +30 -1
  67. package/server/ops/opsRoute.ts +39 -7
  68. package/server/ops/opsToken.ts +7 -2
  69. package/server/resolver/CascadeRunner.ts +15 -2
  70. package/server/resolver/database.resolver.ts +4 -0
  71. package/server/resolver/service.resolver.ts +3 -0
  72. package/server/resolver/signal.resolver.ts +41 -31
  73. package/server/routeElementComposer.tsx +33 -6
  74. package/server/routeState.ts +1 -0
  75. package/server/routeTreeBuilder.ts +5 -0
  76. package/server/rscClient.tsx +67 -22
  77. package/server/rscClientFetch.ts +8 -3
  78. package/server/rscNavigationState.ts +2 -2
  79. package/server/rscPagePrompts.ts +66 -16
  80. package/server/rscScrollRestoration.ts +21 -8
  81. package/server/rscWorker.tsx +79 -32
  82. package/server/rscWorkerHost.ts +12 -1
  83. package/server/tunnel/TunnelAgent.ts +2 -1
  84. package/server/webRouter.ts +33 -27
  85. package/service/agent.service.ts +21 -1
  86. package/service/endpointCacheKeys.ts +35 -0
  87. package/service/index.ts +1 -0
  88. package/service/liveSyncHub.ts +2 -1
  89. package/service/predefinedAdaptor/anthropicLlm.ts +37 -17
  90. package/service/predefinedAdaptor/database.adaptor.ts +98 -25
  91. package/service/predefinedAdaptor/documentTransfer.ts +50 -0
  92. package/service/predefinedAdaptor/endpointCacheControl.adaptor.ts +19 -0
  93. package/service/predefinedAdaptor/index.ts +1 -0
  94. package/service/predefinedAdaptor/llm.adaptor.ts +7 -0
  95. package/service/predefinedAdaptor/openaiDialect.ts +53 -17
  96. package/service/predefinedAdaptor/openaiLlm.ts +1 -1
  97. package/service/predefinedAdaptor/solidQueue.adaptor.ts +30 -9
  98. package/service/predefinedAdaptor/sql/MigrationTables.ts +90 -0
  99. package/service/predefinedAdaptor/sql/QueryCompiler.ts +16 -14
  100. package/service/predefinedAdaptor/sql/RawDocumentTable.ts +200 -0
  101. package/service/predefinedAdaptor/sql/SqlDocumentStore.ts +218 -44
  102. package/service/predefinedAdaptor/sql/SqliteInsightSession.ts +4 -1
  103. package/service/predefinedAdaptor/sql/dialect/postgres.ts +13 -3
  104. package/service/predefinedAdaptor/sql/dialect/sqlite.ts +13 -2
  105. package/service/predefinedAdaptor/sql/driver/bunSqlite.ts +4 -5
  106. package/service/predefinedAdaptor/sql/types.ts +22 -1
  107. package/service/predefinedAdaptor/sql/values.ts +19 -0
  108. package/service/predefinedAdaptor/storage.adaptor.ts +19 -0
  109. package/service/serviceModule.ts +3 -0
  110. package/service/types.ts +1 -0
  111. package/signal/TaggedJson.ts +26 -4
  112. package/signal/endpointCache.ts +16 -6
  113. package/signal/exception.ts +4 -1
  114. package/signal/mcp/mcpProtocol.ts +7 -0
  115. package/signal/mcp/pagePrompt.ts +18 -1
  116. package/signal/signalContext.ts +7 -10
  117. package/store/action.ts +181 -73
  118. package/store/agent/ScreenImage.ts +166 -0
  119. package/store/agent/StoreSurfaceSource.ts +41 -2
  120. package/store/agent/index.ts +2 -1
  121. package/store/databaseStateNames.ts +1 -0
  122. package/store/formUploadOf.ts +41 -0
  123. package/store/index.ts +1 -0
  124. package/store/liveInsert.ts +5 -1
  125. package/store/sliceKeys.ts +1 -0
  126. package/store/state.ts +15 -3
  127. package/store/stateBuilder.ts +7 -1
  128. package/store/storeInstance.ts +22 -4
  129. package/types/client/csrLocation.d.ts +3 -7
  130. package/types/client/csrTypes.d.ts +22 -3
  131. package/types/client/href.d.ts +3 -0
  132. package/types/client/route/PageDefinition.d.ts +21 -4
  133. package/types/client/route/RouteDefinition.d.ts +4 -0
  134. package/types/client/route/RouteGuards.d.ts +15 -0
  135. package/types/client/route/index.d.ts +1 -0
  136. package/types/client/route/resolveRouteModule.d.ts +2 -0
  137. package/types/client/route/routeArgs.d.ts +5 -0
  138. package/types/client/route/routeBuilders.d.ts +1 -1
  139. package/types/client/router.d.ts +9 -1
  140. package/types/client/translator.d.ts +2 -0
  141. package/types/common/authCookie.d.ts +5 -0
  142. package/types/common/authToken.d.ts +0 -5
  143. package/types/common/codeAgentWire.d.ts +7 -0
  144. package/types/common/index.d.ts +2 -1
  145. package/types/dictionary/base.dictionary.d.ts +1 -1
  146. package/types/dictionary/dictionary.d.ts +8 -8
  147. package/types/document/database.d.ts +3 -0
  148. package/types/document/documentQuery.d.ts +1 -0
  149. package/types/document/into.d.ts +2 -0
  150. package/types/document/noDocumentError.d.ts +6 -1
  151. package/types/fetch/appScope.d.ts +18 -0
  152. package/types/fetch/client/fetchClient.d.ts +1 -1
  153. package/types/fetch/fetchType/endpointFetch.type.d.ts +1 -1
  154. package/types/fetch/index.d.ts +1 -0
  155. package/types/index.d.ts +5 -0
  156. package/types/server/akanServer.d.ts +10 -5
  157. package/types/server/index.d.ts +1 -0
  158. package/types/server/mcp/McpApps.d.ts +14 -8
  159. package/types/server/mcp/McpPages.d.ts +6 -3
  160. package/types/server/migration/docPath.d.ts +20 -0
  161. package/types/server/migration/index.d.ts +15 -0
  162. package/types/server/migration/migrationChangeLog.d.ts +27 -0
  163. package/types/server/migration/migrationChanges.d.ts +27 -0
  164. package/types/server/migration/migrationCommand.d.ts +33 -0
  165. package/types/server/migration/migrationContext.d.ts +28 -0
  166. package/types/server/migration/migrationDefinition.d.ts +42 -0
  167. package/types/server/migration/migrationError.d.ts +15 -0
  168. package/types/server/migration/migrationLedger.d.ts +51 -0
  169. package/types/server/migration/migrationLock.d.ts +34 -0
  170. package/types/server/migration/migrationParams.d.ts +41 -0
  171. package/types/server/migration/migrationPulse.d.ts +15 -0
  172. package/types/server/migration/migrationRunner.d.ts +93 -0
  173. package/types/server/migration/migrationScope.d.ts +42 -0
  174. package/types/server/migration/migrationTable.d.ts +52 -0
  175. package/types/server/migration/migrations.d.ts +12 -0
  176. package/types/server/migration.d.ts +1 -0
  177. package/types/server/ops/migrateJobs.d.ts +36 -0
  178. package/types/server/ops/opsCommand.d.ts +10 -1
  179. package/types/server/ops/opsRoute.d.ts +4 -1
  180. package/types/server/ops/opsToken.d.ts +3 -0
  181. package/types/server/routeElementComposer.d.ts +10 -1
  182. package/types/server/routeState.d.ts +1 -0
  183. package/types/server/rscClientFetch.d.ts +2 -0
  184. package/types/server/rscNavigationState.d.ts +1 -1
  185. package/types/server/rscPagePrompts.d.ts +3 -1
  186. package/types/server/rscScrollRestoration.d.ts +2 -0
  187. package/types/server/rscWorkerHost.d.ts +2 -1
  188. package/types/server/webRouter.d.ts +3 -0
  189. package/types/service/agent.service.d.ts +2 -0
  190. package/types/service/endpointCacheKeys.d.ts +8 -0
  191. package/types/service/index.d.ts +1 -0
  192. package/types/service/predefinedAdaptor/anthropicLlm.d.ts +9 -4
  193. package/types/service/predefinedAdaptor/database.adaptor.d.ts +21 -2
  194. package/types/service/predefinedAdaptor/documentTransfer.d.ts +1 -0
  195. package/types/service/predefinedAdaptor/endpointCacheControl.adaptor.d.ts +9 -0
  196. package/types/service/predefinedAdaptor/index.d.ts +1 -0
  197. package/types/service/predefinedAdaptor/llm.adaptor.d.ts +7 -0
  198. package/types/service/predefinedAdaptor/openaiDialect.d.ts +20 -5
  199. package/types/service/predefinedAdaptor/solidQueue.adaptor.d.ts +1 -0
  200. package/types/service/predefinedAdaptor/sql/MigrationTables.d.ts +17 -0
  201. package/types/service/predefinedAdaptor/sql/QueryCompiler.d.ts +0 -1
  202. package/types/service/predefinedAdaptor/sql/RawDocumentTable.d.ts +38 -0
  203. package/types/service/predefinedAdaptor/sql/SqlDocumentStore.d.ts +1 -0
  204. package/types/service/predefinedAdaptor/sql/dialect/postgres.d.ts +2 -1
  205. package/types/service/predefinedAdaptor/sql/dialect/sqlite.d.ts +3 -1
  206. package/types/service/predefinedAdaptor/sql/driver/bunSqlite.d.ts +2 -2
  207. package/types/service/predefinedAdaptor/sql/types.d.ts +26 -0
  208. package/types/service/predefinedAdaptor/sql/values.d.ts +1 -0
  209. package/types/service/predefinedAdaptor/storage.adaptor.d.ts +8 -0
  210. package/types/service/types.d.ts +1 -0
  211. package/types/signal/exception.d.ts +4 -1
  212. package/types/signal/mcp/mcpProtocol.d.ts +6 -0
  213. package/types/signal/mcp/pagePrompt.d.ts +16 -0
  214. package/types/signal/signalContext.d.ts +0 -2
  215. package/types/store/action.d.ts +2 -0
  216. package/types/store/agent/ScreenImage.d.ts +27 -0
  217. package/types/store/agent/StoreSurfaceSource.d.ts +1 -1
  218. package/types/store/agent/index.d.ts +2 -1
  219. package/types/store/databaseStateNames.d.ts +1 -0
  220. package/types/store/formUploadOf.d.ts +9 -0
  221. package/types/store/index.d.ts +1 -0
  222. package/types/store/liveInsert.d.ts +3 -1
  223. package/types/store/sliceKeys.d.ts +1 -0
  224. package/types/store/state.d.ts +10 -4
  225. package/types/store/stateBuilder.d.ts +1 -0
  226. package/types/ui/Agent/Composer.d.ts +2 -0
  227. package/types/ui/Agent/Menu.d.ts +2 -0
  228. package/types/ui/CsrImage.d.ts +2 -0
  229. package/types/ui/Image.d.ts +3 -1
  230. package/types/ui/Layout/FrameSlotPortal.d.ts +1 -1
  231. package/types/ui/Load/sliceClaim.d.ts +28 -0
  232. package/types/ui/Model/Edit.d.ts +3 -2
  233. package/types/ui/Model/editSeed.d.ts +4 -0
  234. package/types/ui/System/App.d.ts +17 -0
  235. package/types/ui/System/index.d.ts +2 -0
  236. package/types/ui/recipe/badgeRecipe.d.ts +2 -2
  237. package/types/ui/recipe/buttonRecipe.d.ts +2 -2
  238. package/types/ui/sliceNamesOf.d.ts +2 -0
  239. package/types/vendor/@akanjs/native/packages/cli/src/lib/compat.d.ts +6 -0
  240. package/types/vendor/@akanjs/native/packages/cli/src/lib/toolchains.d.ts +2 -2
  241. package/types/vendor/use-agentic/Compaction.d.ts +3 -1
  242. package/types/vendor/use-agentic/Reference.d.ts +7 -2
  243. package/types/vendor/use-agentic/ToolOutput.d.ts +6 -1
  244. package/types/vendor/use-agentic/ToolReturn.d.ts +18 -0
  245. package/types/vendor/use-agentic/Transcript.d.ts +7 -0
  246. package/types/vendor/use-agentic/index.d.ts +1 -0
  247. package/types/vendor/use-agentic/types.d.ts +6 -0
  248. package/types/webkit/CsrGuards.d.ts +25 -0
  249. package/types/webkit/CsrRouteTable.d.ts +6 -0
  250. package/types/webkit/CsrStack.d.ts +7 -0
  251. package/types/webkit/McpAppBoot.d.ts +32 -0
  252. package/types/webkit/McpAppBridge.d.ts +10 -1
  253. package/types/webkit/McpAppFetchBridge.d.ts +3 -1
  254. package/types/webkit/McpAppView.d.ts +4 -1
  255. package/types/webkit/PageNotFound.d.ts +5 -0
  256. package/types/webkit/RenderLayer.d.ts +1 -3
  257. package/types/webkit/index.d.ts +1 -0
  258. package/types/webkit/useDebounce.d.ts +1 -1
  259. package/ui/Agent/Chat.tsx +1 -0
  260. package/ui/Agent/Composer.tsx +2 -0
  261. package/ui/Agent/Menu.tsx +5 -1
  262. package/ui/Agent/agentSessionOf.ts +15 -8
  263. package/ui/Agent/mentionDraft.ts +2 -3
  264. package/ui/Agent/useReferenceMenu.ts +1 -0
  265. package/ui/Agent/useSlashMenu.ts +1 -0
  266. package/ui/CsrImage.tsx +3 -1
  267. package/ui/Dialog/LegacyModal.tsx +7 -5
  268. package/ui/Dialog/Modal.tsx +7 -4
  269. package/ui/Field/Collection.tsx +2 -1
  270. package/ui/Image.tsx +4 -4
  271. package/ui/Layout/BottomInset.tsx +2 -11
  272. package/ui/Layout/FrameSlotPortal.tsx +1 -3
  273. package/ui/Layout/Navbar.tsx +7 -22
  274. package/ui/Layout/TopInset.tsx +3 -4
  275. package/ui/Load/Units.tsx +34 -12
  276. package/ui/Load/sliceClaim.ts +164 -0
  277. package/ui/Model/Edit.tsx +22 -3
  278. package/ui/Model/EditModal.tsx +22 -6
  279. package/ui/Model/LoadStore.tsx +1 -1
  280. package/ui/Model/NewWrapper_Client.tsx +1 -1
  281. package/ui/Model/ViewEditModal.tsx +9 -3
  282. package/ui/Model/editSeed.ts +28 -0
  283. package/ui/System/App.tsx +43 -0
  284. package/ui/System/CSR.tsx +1 -10
  285. package/ui/System/Client.tsx +3 -0
  286. package/ui/System/index.tsx +3 -0
  287. package/ui/Tab/Provider.tsx +6 -8
  288. package/ui/styles.css +10 -0
  289. package/vendor/@akanjs/native/native/ios/Sources/AkanNativeBridge.swift +3 -2
  290. package/vendor/@akanjs/native/packages/cli/src/lib/compat.ts +6 -2
  291. package/vendor/@akanjs/native/packages/cli/src/lib/native-plugins.ts +1 -1
  292. package/vendor/@akanjs/native/packages/cli/src/lib/toolchains.ts +1 -1
  293. package/vendor/@akanjs/native/packages/cli/src/lib/updates.ts +3 -3
  294. package/vendor/@akanjs/native/plugins/sqlite/src/desktop.ts +10 -5
  295. package/vendor/@akanjs/native/plugins/updates/src/desktop.ts +45 -15
  296. package/vendor/use-agentic/CHANGELOG.md +31 -0
  297. package/vendor/use-agentic/Compaction.ts +38 -7
  298. package/vendor/use-agentic/Reference.ts +14 -10
  299. package/vendor/use-agentic/ToolOutput.ts +25 -3
  300. package/vendor/use-agentic/ToolReturn.ts +32 -0
  301. package/vendor/use-agentic/ToolRunner.ts +15 -13
  302. package/vendor/use-agentic/Transcript.ts +38 -2
  303. package/vendor/use-agentic/WIRE.md +20 -0
  304. package/vendor/use-agentic/index.ts +1 -0
  305. package/vendor/use-agentic/types.ts +6 -0
  306. package/webkit/CsrGuards.ts +112 -0
  307. package/webkit/CsrRouteTable.ts +71 -16
  308. package/webkit/CsrStack.ts +47 -1
  309. package/webkit/McpAppAgent.ts +14 -2
  310. package/webkit/McpAppBoot.tsx +129 -0
  311. package/webkit/McpAppBridge.ts +30 -6
  312. package/webkit/McpAppFetchBridge.ts +8 -2
  313. package/webkit/McpAppView.ts +39 -28
  314. package/webkit/PageNotFound.tsx +24 -0
  315. package/webkit/RenderLayer.tsx +106 -30
  316. package/webkit/bootCsr.tsx +4 -43
  317. package/webkit/index.ts +1 -0
  318. package/webkit/useCsrValues.ts +66 -6
  319. package/webkit/useDebounce.ts +23 -14
  320. package/webkit/useEscapeKey.tsx +1 -1
  321. package/webkit/useLocation.ts +21 -19
  322. package/types/webkit/EmbeddedLayout.d.ts +0 -10
  323. package/webkit/EmbeddedLayout.tsx +0 -82
@@ -0,0 +1,122 @@
1
+ import { type Cls, type EnumInstance, isEnum, PrimitiveRegistry, type PrimitiveScalar } from "akanjs/base";
2
+ import { deserialize, type FieldToValue, type ParamFieldType } from "akanjs/constant";
3
+ import { MigrationError } from "./migrationError";
4
+
5
+ export interface MigrationParamOption<Value = unknown> {
6
+ /** What the value means, shown beside its input on the approval form — so English. */
7
+ desc?: string;
8
+ /** For a `String`, the values it may take. */
9
+ enum?: readonly string[];
10
+ default?: Value;
11
+ /** Left out, the value is `null` rather than a refusal. */
12
+ nullable?: boolean;
13
+ }
14
+
15
+ export type MigrationParamValue<Type, Option> = Option extends { default: unknown }
16
+ ? MigrationParamBase<Type, Option>
17
+ : Option extends { nullable: true }
18
+ ? MigrationParamBase<Type, Option> | null
19
+ : MigrationParamBase<Type, Option>;
20
+
21
+ type MigrationParamBase<Type, Option> = Option extends { enum: readonly (infer Value)[] } ? Value : FieldToValue<Type>;
22
+
23
+ export interface MigrationParamInfo extends MigrationParamOption {
24
+ name: string;
25
+ type: ParamFieldType;
26
+ }
27
+
28
+ /** One declared param as `list` reports it, enough to build its input. */
29
+ export interface MigrationParamSpec {
30
+ name: string;
31
+ type: string;
32
+ required: boolean;
33
+ enum?: readonly (string | number)[];
34
+ default?: unknown;
35
+ desc?: string;
36
+ }
37
+
38
+ export class MigrationParams {
39
+ readonly list: MigrationParamInfo[] = [];
40
+
41
+ declare(info: MigrationParamInfo) {
42
+ if (!/^[A-Za-z][A-Za-z0-9_]*$/.test(info.name))
43
+ throw new Error(`Migration param "${info.name}" must start with a letter and hold letters, digits and _`);
44
+ if (this.list.some((existing) => existing.name === info.name))
45
+ throw new Error(`Migration param "${info.name}" is declared twice`);
46
+ this.list.push(info);
47
+ }
48
+
49
+ parse(raw: Record<string, string>): Record<string, unknown> {
50
+ const unknown = Object.keys(raw).find((name) => !this.list.some((info) => info.name === name));
51
+ if (unknown)
52
+ throw new MigrationError(
53
+ "invalidParam",
54
+ `Unknown param "${unknown}"; this migration takes ${this.list.map(({ name }) => name).join(", ") || "none"}`,
55
+ );
56
+ return Object.fromEntries(this.list.map((info) => [info.name, MigrationParams.#value(info, raw[info.name])]));
57
+ }
58
+
59
+ /** Params a run recorded as JSON, as their declared types again: what a rollback hands the script. */
60
+ revive(stored: Record<string, unknown>): Record<string, unknown> {
61
+ return Object.fromEntries(
62
+ this.list.map((info) => {
63
+ const value = stored[info.name];
64
+ if (value === undefined || value === null) return [info.name, value ?? info.default ?? null];
65
+ try {
66
+ return [info.name, MigrationParams.#deserialize(info, value)];
67
+ } catch {
68
+ return [info.name, value];
69
+ }
70
+ }),
71
+ );
72
+ }
73
+
74
+ specs(): MigrationParamSpec[] {
75
+ return this.list.map((info) => ({
76
+ name: info.name,
77
+ type: MigrationParams.#typeName(info),
78
+ required: !("default" in info) && !info.nullable,
79
+ ...(MigrationParams.#choices(info) ? { enum: MigrationParams.#choices(info) } : {}),
80
+ ...("default" in info ? { default: info.default } : {}),
81
+ ...(info.desc ? { desc: info.desc } : {}),
82
+ }));
83
+ }
84
+
85
+ static #value(info: MigrationParamInfo, raw: string | undefined) {
86
+ if (raw === undefined || raw === "") {
87
+ if ("default" in info) return info.default;
88
+ if (info.nullable) return null;
89
+ throw new MigrationError("invalidParam", `Param "${info.name}" is required`);
90
+ }
91
+
92
+ const input = (info.type as unknown) === Date && /^\d{4}-\d{2}-\d{2}$/.test(raw) ? `${raw}T00:00:00.000Z` : raw;
93
+ let value: unknown;
94
+ try {
95
+ value = MigrationParams.#deserialize(info, input);
96
+ } catch {
97
+ throw new MigrationError("invalidParam", `Param "${info.name}" expects ${MigrationParams.#typeName(info)}`);
98
+ }
99
+ if (info.enum && !info.enum.includes(value as string))
100
+ throw new MigrationError("invalidParam", `Param "${info.name}" expects one of ${info.enum.join(", ")}`);
101
+ return value;
102
+ }
103
+
104
+ static #deserialize(info: MigrationParamInfo, value: unknown) {
105
+ const enumRef = isEnum(info.type as Cls) ? (info.type as EnumInstance) : undefined;
106
+ const scalar = (enumRef ? enumRef.type : info.type) as typeof PrimitiveScalar;
107
+ return deserialize(scalar as never, 0, value, { key: info.name, enum: enumRef });
108
+ }
109
+
110
+ static #choices(info: MigrationParamInfo): readonly (string | number)[] | undefined {
111
+ if (isEnum(info.type as Cls)) return (info.type as EnumInstance).values as readonly (string | number)[];
112
+ return info.enum;
113
+ }
114
+
115
+ static #typeName(info: MigrationParamInfo) {
116
+ const choices = MigrationParams.#choices(info);
117
+ if (choices) return `one of ${choices.join(", ")}`;
118
+ return PrimitiveRegistry.has(info.type as Cls)
119
+ ? PrimitiveRegistry.getName(info.type as typeof PrimitiveScalar)
120
+ : "a value";
121
+ }
122
+ }
@@ -0,0 +1,39 @@
1
+ import type { MigrationLock } from "./migrationLock";
2
+
3
+ /** What every table call of a run beats: its lease, and a warning once its own transaction has held SQLite long. */
4
+ export class MigrationPulse {
5
+
6
+ static readonly holdWarnMs = 5_000;
7
+ readonly lock: MigrationLock;
8
+ #onLongHold: ((heldMs: number) => void) | null;
9
+ #heldSince: number | null = null;
10
+
11
+ constructor(lock: MigrationLock, onLongHold: ((heldMs: number) => void) | null = null) {
12
+ this.lock = lock;
13
+ this.#onLongHold = onLongHold;
14
+ }
15
+
16
+ /** A writer stops once its lease is lost; a reader reads on, as nothing it does clashes with whoever took over. */
17
+ async beat({ strict, force = false }: { strict: boolean; force?: boolean }) {
18
+ try {
19
+ await this.lock.heartbeat({ force });
20
+ } catch (error) {
21
+ if (strict) throw error;
22
+ }
23
+ if (this.#heldSince === null || !this.#onLongHold) return;
24
+ const heldMs = Date.now() - this.#heldSince;
25
+ if (heldMs < MigrationPulse.holdWarnMs) return;
26
+ this.#onLongHold(heldMs);
27
+ this.#onLongHold = null;
28
+ }
29
+
30
+ /** Runs `fn` as the span the warning measures: the run's own transaction. */
31
+ async hold<T>(fn: () => Promise<T>) {
32
+ this.#heldSince = Date.now();
33
+ try {
34
+ return await fn();
35
+ } finally {
36
+ this.#heldSince = null;
37
+ }
38
+ }
39
+ }
@@ -0,0 +1,525 @@
1
+ import { Logger } from "akanjs/common";
2
+ import { createDocumentId, sanitizeJson } from "akanjs/document";
3
+ import { type DatabaseAdaptor, descriptorHash, stableJson } from "akanjs/service";
4
+ import { MigrationChangeLog } from "./migrationChangeLog";
5
+ import { MigrationChanges, type MigrationSkip } from "./migrationChanges";
6
+ import { MigrationContext, type MigrationGet } from "./migrationContext";
7
+ import { MigrationDefinition, type MigrationPlan, type MigrationSettings } from "./migrationDefinition";
8
+ import { MigrationError } from "./migrationError";
9
+ import { MigrationLedger, type MigrationRun, type MigrationRunKind } from "./migrationLedger";
10
+ import { MigrationLock } from "./migrationLock";
11
+ import type { MigrationParamSpec } from "./migrationParams";
12
+ import { MigrationPulse } from "./migrationPulse";
13
+ import { MigrationScope } from "./migrationScope";
14
+
15
+ export interface MigrationEntry {
16
+ id: string;
17
+ /** sha256 of the script's source: the ledger keeps which version of a script ran. */
18
+ checksum: string;
19
+ load: () => Promise<{ default?: unknown }>;
20
+ }
21
+
22
+ export interface MigrationRunnerOption {
23
+ database: DatabaseAdaptor;
24
+ get?: MigrationGet;
25
+ buildId?: string | null;
26
+ logger?: Logger;
27
+ }
28
+
29
+ export type MigrationStatus = "pending" | "applied" | "partial";
30
+
31
+ export interface MigrationListItem {
32
+ id: string;
33
+ title: string | null;
34
+ checksum: string;
35
+ /** `partial`: an apply outside one transaction failed after committing some of its batches. */
36
+ status: MigrationStatus;
37
+ appliedRunId: string | null;
38
+ appliedAt: number | null;
39
+ /** The applied run ran another version of the script than this build carries. */
40
+ checksumMismatch: boolean;
41
+ params: MigrationParamSpec[];
42
+ error?: string;
43
+ }
44
+
45
+ export interface MigrationPlanResult {
46
+ id: string;
47
+ runId: string;
48
+ planHash: string;
49
+ params: Record<string, unknown>;
50
+ summary: unknown;
51
+ items: unknown[];
52
+ itemCount: number;
53
+ }
54
+
55
+ export interface MigrationApplyResult {
56
+ id: string;
57
+ runId: string;
58
+ planHash: string;
59
+ summary: unknown;
60
+ changes: number;
61
+ problems: string[];
62
+ }
63
+
64
+ export interface MigrationVerifyResult {
65
+ id: string;
66
+ runId: string;
67
+ problems: string[];
68
+ }
69
+
70
+ export interface MigrationRollbackRun {
71
+ runId: string;
72
+ target: string;
73
+ reverted: number;
74
+ skipped: MigrationSkip[];
75
+ }
76
+
77
+ export interface MigrationRollbackResult {
78
+ id: string;
79
+ runs: MigrationRollbackRun[];
80
+ }
81
+
82
+ export class MigrationRunner {
83
+ static readonly defaultItemNum = 100;
84
+ readonly #entries: MigrationEntry[];
85
+ readonly #database: DatabaseAdaptor;
86
+ readonly #get: MigrationGet;
87
+ readonly #buildId: string | null;
88
+ readonly #logger: Logger;
89
+ readonly #ledger: MigrationLedger;
90
+
91
+ constructor(entries: MigrationEntry[], { database, get, buildId = null, logger }: MigrationRunnerOption) {
92
+ this.#entries = entries;
93
+ this.#database = database;
94
+ this.#get =
95
+ get ??
96
+ (() => {
97
+ throw new Error("ctx.get needs a booted server; run migrations through akan migrate or ops migrate");
98
+ });
99
+ this.#buildId = buildId;
100
+ this.#logger = logger ?? new Logger("Migration");
101
+ this.#ledger = new MigrationLedger(() => database.getConnection());
102
+ }
103
+
104
+ async list(): Promise<MigrationListItem[]> {
105
+ const runs = await this.#ledger.runsOf();
106
+ return await Promise.all(
107
+ this.#entries.map(async (entry) => {
108
+ const state = await this.#ledger.state(runs.filter((run) => run.migrationId === entry.id));
109
+ const status: MigrationStatus = state.applied ? "applied" : state.partial.length ? "partial" : "pending";
110
+ const item: MigrationListItem = {
111
+ id: entry.id,
112
+ title: null,
113
+ checksum: entry.checksum,
114
+ status,
115
+ appliedRunId: state.applied?.id ?? null,
116
+ appliedAt: state.applied?.finishedAt ?? null,
117
+ checksumMismatch: !!state.applied && state.applied.checksum !== entry.checksum,
118
+ params: [],
119
+ };
120
+ try {
121
+ const definition = await MigrationRunner.#definition(entry);
122
+ item.title = definition.title;
123
+ item.params = definition.params.specs();
124
+ } catch (error) {
125
+ item.error = MigrationError.messageOf(error);
126
+ }
127
+ return item;
128
+ }),
129
+ );
130
+ }
131
+
132
+ async plan(
133
+ id: string,
134
+ raw: Record<string, string> = {},
135
+ { actor = null, items = MigrationRunner.defaultItemNum }: { actor?: string | null; items?: number } = {},
136
+ ): Promise<MigrationPlanResult> {
137
+ const { entry, definition } = await this.#load(id);
138
+ const params = definition.params.parse(raw);
139
+ return await this.#locked(async (lock) => {
140
+ const run = await this.#begin("plan", entry, { params, actor });
141
+ try {
142
+ const plan = await this.#plan(definition, id, params, new MigrationPulse(lock));
143
+ const planHash = await MigrationRunner.#planHash(params, plan);
144
+ await this.#ledger.finish(run.id, { status: "done", planHash, summary: { plan: plan.summary } });
145
+ const report = (sanitizeJson(plan.items ?? []) ?? []) as unknown[];
146
+ return {
147
+ id,
148
+ runId: run.id,
149
+ planHash,
150
+ params: MigrationRunner.#json(params),
151
+ summary: sanitizeJson(plan.summary),
152
+ items: report.slice(0, Math.max(0, items)),
153
+ itemCount: report.length,
154
+ };
155
+ } catch (error) {
156
+ throw await this.#failed(run.id, error);
157
+ }
158
+ });
159
+ }
160
+
161
+ /**
162
+ * Recomputes the plan inside the run's own transaction and refuses when it no longer hashes to `expect`, the plan a
163
+ * person approved. Verify runs once the writes commit; its problems leave the run applied but the result not ok.
164
+ */
165
+ async apply(
166
+ id: string,
167
+ raw: Record<string, string> = {},
168
+ { expect = null, actor = null }: { expect?: string | null; actor?: string | null } = {},
169
+ ): Promise<MigrationApplyResult> {
170
+ const { entry, definition } = await this.#load(id);
171
+ const applyStage = definition.applyStage;
172
+ if (!applyStage) throw new MigrationError("usage", `${id} declares no .apply()`);
173
+ const params = definition.params.parse(raw);
174
+ const settings = definition.settings;
175
+ return await this.#locked(async (lock) => {
176
+ const runs = await this.#ledger.runsOf(id);
177
+ const state = await this.#ledger.state(runs);
178
+ if (state.applied)
179
+ throw new MigrationError("alreadyApplied", `${id} was applied by run ${state.applied.id}; roll it back first`);
180
+ const resumed = settings.transaction ? null : (state.partial[0] ?? null);
181
+ if (resumed && MigrationRunner.#hashable(resumed.params) !== MigrationRunner.#hashable(params))
182
+ throw new MigrationError(
183
+ "invalidParam",
184
+ `run ${resumed.id} stopped partway with other params; apply with the same params to resume it, or roll it back`,
185
+ );
186
+
187
+ const checkpoint =
188
+ resumed && !runs.some((run) => run.kind === "rollback" && run.target === resumed.id)
189
+ ? resumed.checkpoint
190
+ : null;
191
+
192
+ const run = await this.#begin("apply", entry, { params, actor, checkpoint, summary: { settings } });
193
+ const pulse = new MigrationPulse(lock, this.#holdWarning(id, settings.transaction));
194
+ const scope = new MigrationScope({
195
+ database: this.#database,
196
+ readOnly: false,
197
+ batchSize: settings.batchSize,
198
+ log: new MigrationChangeLog(run.id, () => this.#database.getConnection()),
199
+ checkpoints: settings.transaction ? null : { runId: run.id, ledger: this.#ledger, resumed: checkpoint ?? {} },
200
+ beat: async () => await pulse.beat({ strict: true }),
201
+ });
202
+ const planned: { hash: string; summary: unknown; changes: number } = { hash: "", summary: null, changes: 0 };
203
+ try {
204
+ await this.#run(pulse, settings.transaction, async () => {
205
+
206
+ if (settings.transaction && scope.dialect.name === "postgres")
207
+ await scope.connection().execute("SET TRANSACTION ISOLATION LEVEL REPEATABLE READ");
208
+ const plan = await this.#plan(definition, id, params, pulse);
209
+ planned.hash = await MigrationRunner.#planHash(params, plan);
210
+ planned.summary = sanitizeJson(plan.summary);
211
+ if (expect && expect !== planned.hash)
212
+ throw new MigrationError("planChanged", `${id}'s plan changed since it was approved; plan it again`);
213
+ await applyStage(this.#context(id, params, scope), plan);
214
+ planned.changes = await MigrationChangeLog.count(this.#database.getConnection(), run.id);
215
+ await pulse.beat({ strict: true, force: true });
216
+
217
+ await this.#ledger.complete(run.id, {
218
+ planHash: planned.hash,
219
+ summary: { plan: planned.summary, changes: planned.changes, settings },
220
+ });
221
+ });
222
+ } catch (error) {
223
+ if ((await this.#ledger.get(run.id))?.status !== "done") {
224
+ const changes = await MigrationChangeLog.count(this.#database.getConnection(), run.id);
225
+ throw await this.#failed(run.id, error, {
226
+ status: MigrationError.codeOf(error) === "planChanged" ? "aborted" : "failed",
227
+ planHash: planned.hash || null,
228
+ summary: { plan: planned.summary, changes, settings },
229
+ });
230
+ }
231
+ this.#committedThenFailed(id, error);
232
+ }
233
+ const problems = await this.#verify(definition, id, params, pulse);
234
+ await this.#ledger.finish(run.id, {
235
+ status: "done",
236
+ planHash: planned.hash,
237
+ summary: { plan: planned.summary, changes: planned.changes, settings, problems },
238
+ });
239
+ return {
240
+ id,
241
+ runId: run.id,
242
+ planHash: planned.hash,
243
+ summary: planned.summary,
244
+ changes: planned.changes,
245
+ problems,
246
+ };
247
+ });
248
+ }
249
+
250
+ async verify(id: string, raw: Record<string, string> = {}, { actor = null }: { actor?: string | null } = {}) {
251
+ const { entry, definition } = await this.#load(id);
252
+ if (!definition.verifyStage) throw new MigrationError("usage", `${id} declares no .verify()`);
253
+ const params = definition.params.parse(raw);
254
+ return await this.#locked(async (lock): Promise<MigrationVerifyResult> => {
255
+ const run = await this.#begin("verify", entry, { params, actor });
256
+ const problems = await this.#verify(definition, id, params, new MigrationPulse(lock));
257
+ await this.#ledger.finish(
258
+ run.id,
259
+ problems.length
260
+ ? { status: "failed", summary: { problems }, error: MigrationError.remaining(problems.length) }
261
+ : { status: "done", summary: { problems } },
262
+ );
263
+ return { id, runId: run.id, problems };
264
+ });
265
+ }
266
+
267
+ /**
268
+ * `target` is the newest apply run, or a migration id for every run of it not yet rolled back, newest first. Works
269
+ * for a script this build no longer carries: the change log and the settings the apply ran with are enough.
270
+ */
271
+ async rollback(target: string, { actor = null }: { actor?: string | null } = {}): Promise<MigrationRollbackResult> {
272
+ return await this.#locked(async (lock) => {
273
+ const applies = await this.#rollbackTargets(target);
274
+ const runs: MigrationRollbackRun[] = [];
275
+ for (const apply of applies) runs.push(await this.#rollbackRun(apply, actor, lock));
276
+ return { id: applies[0]?.migrationId ?? target, runs };
277
+ });
278
+ }
279
+
280
+ async #rollbackTargets(target: string) {
281
+ const run = await this.#ledger.get(target);
282
+ if (run) {
283
+ if (run.kind !== "apply") throw new MigrationError("usage", `run ${target} is a ${run.kind}, not an apply`);
284
+ const live = await this.#liveApplies(run.migrationId);
285
+ if (!live.some(({ id }) => id === run.id))
286
+ throw new MigrationError("notApplied", `run ${target} has nothing left to roll back`);
287
+ const newest = live[0];
288
+ if (newest && newest.id !== run.id)
289
+ throw new MigrationError(
290
+ "usage",
291
+ `run ${newest.id} applied ${run.migrationId} after run ${target} and may build on it; roll back ${run.migrationId} to undo both, newest first`,
292
+ );
293
+ return [run];
294
+ }
295
+ const applies = await this.#liveApplies(target);
296
+ if (!applies.length) {
297
+ if (!this.#entries.some(({ id }) => id === target))
298
+ throw new MigrationError("notFound", `${target} is neither a migration of this build nor a run in the ledger`);
299
+ throw new MigrationError("notApplied", `${target} has no applied run to roll back`);
300
+ }
301
+ return applies;
302
+ }
303
+
304
+ async #liveApplies(migrationId: string) {
305
+ const state = await this.#ledger.state(await this.#ledger.runsOf(migrationId));
306
+ return [state.applied, ...state.partial]
307
+ .filter((apply): apply is MigrationRun => !!apply)
308
+ .sort((a, b) => b.startedAt - a.startedAt);
309
+ }
310
+
311
+ async #rollbackRun(apply: MigrationRun, actor: string | null, lock: MigrationLock): Promise<MigrationRollbackRun> {
312
+ const entry = this.#entries.find(({ id }) => id === apply.migrationId) ?? null;
313
+ const definition = entry ? await MigrationRunner.#definition(entry) : null;
314
+ if (entry && entry.checksum !== apply.checksum)
315
+ this.#logger.warn(
316
+ `${apply.migrationId} changed since run ${apply.id} applied it; rolling back with this build's`,
317
+ );
318
+ const settings = definition?.settings ?? MigrationRunner.#settingsOf(apply);
319
+ const rollbackStage = definition?.rollbackStage ?? null;
320
+
321
+ const from = rollbackStage || settings.transaction ? null : await this.#reachedBefore(apply);
322
+ const run = await this.#begin("rollback", entry ?? { id: apply.migrationId, checksum: apply.checksum }, {
323
+ params: apply.params ?? {},
324
+ actor,
325
+ target: apply.id,
326
+ });
327
+ const pulse = new MigrationPulse(lock, this.#holdWarning(apply.migrationId, settings.transaction));
328
+ const scope = new MigrationScope({
329
+ database: this.#database,
330
+ readOnly: false,
331
+ batchSize: settings.batchSize,
332
+ log: new MigrationChangeLog(run.id, () => this.#database.getConnection()),
333
+ beat: async () => await pulse.beat({ strict: true }),
334
+ });
335
+ const params = definition ? definition.params.revive(apply.params ?? {}) : (apply.params ?? {});
336
+ const ctx = this.#context(apply.migrationId, params, scope);
337
+ const changes = new MigrationChanges(
338
+ async (below, limit) => await MigrationChangeLog.page(this.#database.getConnection(), apply.id, below, limit),
339
+ (name) => ctx.table(name),
340
+ from,
341
+ );
342
+ const summary = () => ({ reverted: changes.reverted, skipped: changes.skipped });
343
+ try {
344
+ await this.#run(pulse, settings.transaction, async () => {
345
+ if (rollbackStage) await rollbackStage(ctx, changes);
346
+ else await changes.revertAll();
347
+ await pulse.beat({ strict: true, force: true });
348
+ await this.#ledger.complete(run.id, { summary: summary() });
349
+ });
350
+ } catch (error) {
351
+ if ((await this.#ledger.get(run.id))?.status !== "done") {
352
+ if (!rollbackStage && !settings.transaction && changes.reached !== null)
353
+ await this.#ledger.saveCheckpoint(run.id, { seq: String(changes.reached) });
354
+ throw await this.#failed(run.id, error, { summary: summary() });
355
+ }
356
+ this.#committedThenFailed(apply.migrationId, error);
357
+ }
358
+ return { runId: run.id, target: apply.id, ...summary() };
359
+ }
360
+
361
+ /** Where the newest default rollback of `apply` that was cut short got down to: every newer change is handled. */
362
+ async #reachedBefore(apply: MigrationRun) {
363
+ const cut = (await this.#ledger.runsOf(apply.migrationId))
364
+ .filter((run) => run.kind === "rollback" && run.target === apply.id && run.status === "failed")
365
+ .map((run) => Number(run.checkpoint?.seq))
366
+ .filter((seq) => Number.isInteger(seq));
367
+ return cut.at(-1) ?? null;
368
+ }
369
+
370
+ async #plan(
371
+ definition: MigrationDefinition<Record<string, unknown>>,
372
+ id: string,
373
+ params: Record<string, unknown>,
374
+ pulse: MigrationPulse,
375
+ ) {
376
+ const scope = this.#readScope(definition.settings.batchSize, pulse);
377
+ const plan = definition.planStage ? await definition.planStage(this.#context(id, params, scope)) : { summary: {} };
378
+ return plan as MigrationPlan;
379
+ }
380
+
381
+ async #verify(
382
+ definition: MigrationDefinition<Record<string, unknown>>,
383
+ id: string,
384
+ params: Record<string, unknown>,
385
+ pulse: MigrationPulse,
386
+ ) {
387
+ if (!definition.verifyStage) return [];
388
+ const scope = this.#readScope(definition.settings.batchSize, pulse);
389
+ try {
390
+ return (await definition.verifyStage(this.#context(id, params, scope))).map(String);
391
+ } catch (error) {
392
+ this.#logger.error(
393
+ `${id} verify threw: ${error instanceof Error ? (error.stack ?? error.message) : String(error)}`,
394
+ );
395
+ return [`verify threw: ${MigrationError.messageOf(error)}`];
396
+ }
397
+ }
398
+
399
+ #context(id: string, params: Record<string, unknown>, scope: MigrationScope) {
400
+ return new MigrationContext({ id, params, logger: new Logger(`Migration:${id}`), get: this.#get, scope });
401
+ }
402
+
403
+ #readScope(batchSize: number, pulse: MigrationPulse) {
404
+ return new MigrationScope({
405
+ database: this.#database,
406
+ readOnly: true,
407
+ batchSize,
408
+ beat: async () => await pulse.beat({ strict: false }),
409
+ });
410
+ }
411
+
412
+ async #run(pulse: MigrationPulse, transaction: boolean, fn: () => Promise<void>) {
413
+ if (transaction) await this.#database.transaction(async () => await pulse.hold(fn));
414
+ else await fn();
415
+ }
416
+
417
+ #holdWarning(id: string, transaction: boolean) {
418
+ if (!transaction || this.#database.dialect?.name !== "sqlite") return null;
419
+ return (heldMs: number) =>
420
+ this.#logger.warn(
421
+ `${id} has held the SQLite write lock for ${Math.round(heldMs / 1000)}s; the live server's writes fail until it commits. A long run belongs in .config({ transaction: false })`,
422
+ );
423
+ }
424
+
425
+ #committedThenFailed(id: string, error: unknown) {
426
+ this.#logger.warn(`${id} committed, but what ran after the commit failed: ${MigrationError.messageOf(error)}`);
427
+ }
428
+
429
+ async #locked<T>(fn: (lock: MigrationLock) => Promise<T>) {
430
+ const lock = new MigrationLock(() => this.#database.getConnection(), {
431
+ inBand: this.#database.dialect?.name === "sqlite",
432
+ });
433
+ if (!(await lock.acquire()))
434
+ throw new MigrationError("locked", "Another migration run holds the lock; try again once it finishes");
435
+ try {
436
+ await this.#ledger.interruptRunning();
437
+ return await fn(lock);
438
+ } finally {
439
+ await lock.release();
440
+ }
441
+ }
442
+
443
+ async #begin(
444
+ kind: MigrationRunKind,
445
+ entry: Pick<MigrationEntry, "id" | "checksum">,
446
+ {
447
+ params,
448
+ actor,
449
+ target = null,
450
+ checkpoint = null,
451
+ summary = null,
452
+ }: {
453
+ params: Record<string, unknown>;
454
+ actor: string | null;
455
+ target?: string | null;
456
+ checkpoint?: Record<string, string> | null;
457
+ summary?: Record<string, unknown> | null;
458
+ },
459
+ ) {
460
+ return await this.#ledger.insert({
461
+ id: createDocumentId(),
462
+ migrationId: entry.id,
463
+ kind,
464
+ status: "running",
465
+ target,
466
+ checksum: entry.checksum,
467
+ buildId: this.#buildId,
468
+ params: MigrationRunner.#json(params),
469
+ planHash: null,
470
+ summary,
471
+ actor,
472
+ checkpoint,
473
+ startedAt: Date.now(),
474
+ finishedAt: null,
475
+ error: null,
476
+ });
477
+ }
478
+
479
+ async #failed(
480
+ runId: string,
481
+ error: unknown,
482
+ {
483
+ status = "failed",
484
+ planHash = null,
485
+ summary = null,
486
+ }: { status?: "failed" | "aborted"; planHash?: string | null; summary?: Record<string, unknown> | null } = {},
487
+ ) {
488
+ if (status === "failed")
489
+ this.#logger.error(
490
+ `run ${runId} failed: ${error instanceof Error ? (error.stack ?? error.message) : String(error)}`,
491
+ );
492
+ await this.#ledger.finish(runId, { status, planHash, summary, error: MigrationError.messageOf(error) });
493
+ return MigrationError.recorded(error, runId);
494
+ }
495
+
496
+ async #load(id: string) {
497
+ const entry = this.#entries.find((entry) => entry.id === id);
498
+ if (!entry) throw new MigrationError("notFound", `This build carries no migration "${id}"`);
499
+ return { entry, definition: await MigrationRunner.#definition(entry) };
500
+ }
501
+
502
+ static async #definition(entry: MigrationEntry) {
503
+ const definition = (await entry.load()).default;
504
+ if (!MigrationDefinition.is(definition))
505
+ throw new MigrationError("failed", `script/migration/${entry.id}.ts must export default migration(...)`);
506
+ return definition;
507
+ }
508
+
509
+ static #settingsOf(apply: MigrationRun): MigrationSettings {
510
+ const recorded = apply.summary?.settings as Partial<MigrationSettings> | undefined;
511
+ return { ...MigrationDefinition.defaultSettings, ...recorded };
512
+ }
513
+
514
+ static async #planHash(params: Record<string, unknown>, plan: MigrationPlan) {
515
+ return await descriptorHash({ params: sanitizeJson(params), plan: sanitizeJson(plan) });
516
+ }
517
+
518
+ static #hashable(params: Record<string, unknown> | null) {
519
+ return stableJson(sanitizeJson(params ?? {}));
520
+ }
521
+
522
+ static #json(params: Record<string, unknown>) {
523
+ return (sanitizeJson(params) ?? {}) as Record<string, unknown>;
524
+ }
525
+ }