@akanjs/cli 3.1.1-rc.9 → 3.1.2-rc.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 (207) hide show
  1. package/.build-stamp +1 -1
  2. package/CodeAgent-dyc45f5w.js +11 -0
  3. package/{CodeAgentRpcHost-9g27hmer.js → CodeAgentRpcHost-6dzfkvsc.js} +1 -1
  4. package/CodeAgentRpcListener-tcwrdvst.js +182 -0
  5. package/{CodeTui-z5vkm9ea.js → CodeTui-q55b2zrn.js} +25 -8
  6. package/TunnelShare-hdq9h1hr.js +14 -0
  7. package/agent.command-20zaqe60.js +49 -0
  8. package/akanCode.js +13 -8
  9. package/{application.command-wthg8nn9.js → application.command-nd0fshsk.js} +45 -12
  10. package/{applicationBuildRunner-t2r84sz6.js → applicationBuildRunner-s13x3zqb.js} +14 -10
  11. package/buildBatch.proc.js +7 -7
  12. package/{cloud.command-sz11hpre.js → cloud.command-8kbddsz9.js} +28 -19
  13. package/cloud.script-hgvvajm3.js +27 -0
  14. package/code.command-625bg8s8.js +345 -0
  15. package/commandManifest.json +1 -1
  16. package/{context.command-15j9b7c0.js → context.command-p6haqjay.js} +20 -18
  17. package/context.runner-rsnqnk9j.js +27 -0
  18. package/{dependencyScanner-3afj2vt1.js → dependencyScanner-78sq8m4q.js} +2 -2
  19. package/{devTui-q7k7bakd.js → devTui-evr3b35y.js} +1 -1
  20. package/{fileSys-wzzrntkw.js → fileSys-zpvt5gtf.js} +1 -1
  21. package/{guideline.command-snh85ctf.js → guideline.command-195g0h9a.js} +4 -4
  22. package/guidelines/agentRule/agentRule.instruction.md +22 -8
  23. package/guidelines/conventions/core.md +106 -0
  24. package/guidelines/conventions/rules/app.md +83 -0
  25. package/guidelines/conventions/rules/auth.md +46 -0
  26. package/guidelines/conventions/rules/config.md +60 -0
  27. package/guidelines/conventions/rules/constant.md +24 -0
  28. package/guidelines/conventions/rules/gates.md +32 -0
  29. package/guidelines/conventions/rules/layer.md +25 -0
  30. package/guidelines/conventions/rules/migration.md +27 -0
  31. package/guidelines/conventions/rules/module.md +90 -0
  32. package/guidelines/conventions/rules/page.md +56 -0
  33. package/guidelines/conventions/rules/sensitive.md +16 -0
  34. package/guidelines/conventions/rules/server.md +91 -0
  35. package/guidelines/conventions/rules/ssr.md +47 -0
  36. package/guidelines/conventions/rules/style.md +43 -0
  37. package/guidelines/conventions/rules/test.md +34 -0
  38. package/guidelines/conventions/rules/ts.md +95 -0
  39. package/guidelines/conventions/rules/tsx.md +76 -0
  40. package/guidelines/mcpRule/mcpRule.instruction.md +1 -1
  41. package/guidelines/pageRule/pageRule.instruction.md +8 -7
  42. package/guidelines/queryRule/queryRule.instruction.md +4 -0
  43. package/guidelines/runtimeRule/runtimeRule.instruction.md +35 -25
  44. package/guidelines/ssrRule/ssrRule.instruction.md +11 -10
  45. package/guidelines/transportRule/transportRule.instruction.md +5 -4
  46. package/guidelines/workspaceRecipes/workspaceRecipes.instruction.md +4 -4
  47. package/incrementalBuilder.proc.js +7 -7
  48. package/{index-301pdbzz.js → index-00a7j05x.js} +7 -7
  49. package/{index-js6geqjn.js → index-0j1t1h2b.js} +3 -1
  50. package/{index-6txx6a9p.js → index-1h2jc0x3.js} +154 -88
  51. package/{index-55j120r8.js → index-1qsd8ft1.js} +65 -145
  52. package/{index-9th4gszy.js → index-2mwjshz5.js} +233 -1271
  53. package/index-2nxk8wgs.js +266 -0
  54. package/{index-j9vyj3dj.js → index-2phm56a1.js} +49 -8
  55. package/index-35j83zkd.js +61 -0
  56. package/index-4am4dvmf.js +29 -0
  57. package/index-75y7bcz4.js +28 -0
  58. package/index-7apsdr5g.js +487 -0
  59. package/{index-42j4a8zq.js → index-84h43kg6.js} +8 -6
  60. package/index-9bv479q5.js +1 -0
  61. package/{index-3wypz6xj.js → index-9zy8479y.js} +11 -5
  62. package/{index-a5dhqkdr.js → index-a1vb3x7t.js} +273 -259
  63. package/{index-52w0fvh8.js → index-bns3wcpc.js} +15 -0
  64. package/index-cjmjvg4r.js +3622 -0
  65. package/{index-pcwzkdqb.js → index-defp4gmb.js} +1 -1
  66. package/index-ewbmfarf.js +1606 -0
  67. package/index-fbewhg4g.js +590 -0
  68. package/index-fhw7yq2d.js +653 -0
  69. package/{index-wcej7g4z.js → index-g500c5j9.js} +271 -105
  70. package/{index-74tjjsnc.js → index-g841cap9.js} +33 -37
  71. package/{index-2azahjaw.js → index-gr9thy79.js} +5 -5
  72. package/{index-4pf8g7ff.js → index-h7hehkw6.js} +3 -0
  73. package/{index-xjf5j657.js → index-hm0tn7qv.js} +1001 -91
  74. package/index-j6eeh5d7.js +138 -0
  75. package/{index-31es1yev.js → index-j7hwy56s.js} +108 -7
  76. package/{index-skk9zc1x.js → index-jc2zbwra.js} +2 -2
  77. package/{index-905qdgqp.js → index-khk05tsf.js} +1 -1
  78. package/{index-5nd1wtkv.js → index-p6x5b7hr.js} +1 -1
  79. package/{index-tvehn2sp.js → index-qd7xn2bk.js} +1 -1
  80. package/{index-a58emady.js → index-qw6814m4.js} +55 -17
  81. package/index-raz588b3.js +445 -0
  82. package/{index-at7bz0xq.js → index-s4nvxpzm.js} +2 -0
  83. package/{index-bt438yxm.js → index-sp0qsr7a.js} +116 -13
  84. package/{index-xb8809yb.js → index-sveq36gh.js} +40 -43
  85. package/{index-hmt54t45.js → index-t1t9wq9a.js} +4 -4
  86. package/index-t78230d7.js +191 -0
  87. package/index-tenw3mah.js +225 -0
  88. package/{index-qfp55x1y.js → index-tgqameyb.js} +4 -4
  89. package/{index-espk51ah.js → index-tp56652m.js} +6 -6
  90. package/index-w15mg3km.js +389 -0
  91. package/{index-dy0jx9ay.js → index-wwe9rsrx.js} +14 -0
  92. package/{index-2xcc2ax5.js → index-y4kcmbt2.js} +2 -2
  93. package/index-yf9wc28h.js +52 -0
  94. package/{index-0fz95kxe.js → index-zbrwnmf1.js} +9 -7
  95. package/{index-40brg4px.js → index-zttm13c3.js} +5 -5
  96. package/index.js +24 -23
  97. package/{library.command-gycrwhf1.js → library.command-63hgt9te.js} +4 -4
  98. package/{localRegistry.command-jtd8gaes.js → localRegistry.command-g3f8k25t.js} +46 -22
  99. package/{module.command-v6hgs1bc.js → module.command-r4sa2khp.js} +7 -6
  100. package/{package.command-shzpcfph.js → package.command-96eheyvd.js} +5 -5
  101. package/package.json +2 -2
  102. package/{page.command-ptxn5kqk.js → page.command-gs6d841d.js} +4 -4
  103. package/{pipeline.command-zz31pgax.js → pipeline.command-wdfvdbfj.js} +3 -3
  104. package/{primitive.command-a1vse91z.js → primitive.command-dfsv4mpe.js} +8 -7
  105. package/{projectTypecheck-2ztky9cf.js → projectTypecheck-kqj1t6hb.js} +1 -1
  106. package/{prompter-76k56b37.js → prompter-qrwx1p17.js} +2 -2
  107. package/quality.command-webzxee2.js +78 -0
  108. package/{repair.command-cvazbz99.js → repair.command-3r3j1xre.js} +7 -6
  109. package/{routeSourceValidator-6jd0q6r6.js → routeSourceValidator-4h947v7c.js} +13 -3
  110. package/{scalar.command-0acvyp26.js → scalar.command-e8y47j6d.js} +6 -5
  111. package/skills/akan-agent/SKILL.md +43 -0
  112. package/skills/akan-code/SKILL.md +38 -11
  113. package/skills/akan-debug/SKILL.md +41 -6
  114. package/skills/akan-deps/SKILL.md +1 -2
  115. package/skills/akan-err/SKILL.md +2 -1
  116. package/skills/akan-mcp/SKILL.md +40 -0
  117. package/skills/akan-page/SKILL.md +44 -0
  118. package/skills/akan-query/SKILL.md +39 -0
  119. package/skills/akan-runtime/SKILL.md +43 -0
  120. package/skills/akan-scaffold/SKILL.md +16 -6
  121. package/skills/akan-transport/SKILL.md +40 -0
  122. package/skills/akan-validate/SKILL.md +13 -11
  123. package/{subspace.command-822qx2bx.js → subspace.command-a1sf9n5a.js} +12 -10
  124. package/templates/__scalar/__model__/__model__.constant.ts +3 -5
  125. package/templates/__scalar/__model__/__model__.dictionary.ts +6 -5
  126. package/templates/__scalar/__model__/__model__.document.ts +3 -3
  127. package/templates/app/akan.config.ts +2 -3
  128. package/templates/app/env/env.client.ts +2 -4
  129. package/templates/app/env/env.client.type.ts +2 -3
  130. package/templates/app/env/env.server.ts +2 -3
  131. package/templates/app/lib/___appName__/__appName__.dictionary.ts +1 -2
  132. package/templates/app/lib/___appName__/__appName__.service.ts +3 -3
  133. package/templates/app/lib/___appName__/__appName__.signal.ts +5 -5
  134. package/templates/app/lib/___appName__/__appName__.store.ts +4 -6
  135. package/templates/app/lib/option.ts +2 -3
  136. package/templates/app/main.ts +2 -4
  137. package/templates/app/page/_index.tsx +3 -3
  138. package/templates/app/page/_layout.tsx +13 -10
  139. package/templates/appSample/lib/__scalar/workHistory/workHistory.constant.ts +1 -5
  140. package/templates/appSample/lib/__scalar/workHistory/workHistory.dictionary.ts +1 -1
  141. package/templates/appSample/lib/_noti/noti.signal.ts +1 -1
  142. package/templates/appSample/lib/task/Task.Template.tsx +2 -1
  143. package/templates/appSample/lib/task/Task.Unit.tsx +3 -2
  144. package/templates/appSample/lib/task/Task.Util.tsx +16 -4
  145. package/templates/appSample/lib/task/task.constant.ts +1 -5
  146. package/templates/appSample/lib/task/task.dictionary.ts +2 -8
  147. package/templates/appSample/lib/task/task.document.ts +1 -1
  148. package/templates/appSample/lib/task/task.signal.ts +14 -9
  149. package/templates/appSample/page/task/_index.tsx +2 -1
  150. package/templates/appSample/page/task/new.tsx +2 -1
  151. package/templates/appSample/srvkit/guards.ts +11 -0
  152. package/templates/appSample/ui/QuantityControl.tsx +5 -9
  153. package/templates/biomeForm.ts +144 -0
  154. package/templates/crudPages/[__model__Id]/edit/page.tsx +3 -3
  155. package/templates/crudPages/[__model__Id]/page.tsx +5 -5
  156. package/templates/crudPages/new/page.tsx +4 -3
  157. package/templates/crudPages/page.tsx +3 -3
  158. package/templates/crudSinglePage/page.tsx +9 -5
  159. package/templates/libRoot/akan.config.ts +2 -3
  160. package/templates/libRoot/lib/___libName__/__libName__.dictionary.ts +1 -2
  161. package/templates/libRoot/lib/___libName__/__libName__.service.ts +5 -4
  162. package/templates/libRoot/lib/___libName__/__libName__.signal.ts +6 -5
  163. package/templates/libRoot/lib/___libName__/__libName__.store.ts +5 -6
  164. package/templates/libRoot/lib/option.ts +1 -2
  165. package/templates/module/__Model__.Template.tsx +11 -10
  166. package/templates/module/__Model__.Unit.tsx +18 -5
  167. package/templates/module/__Model__.Util.tsx +9 -7
  168. package/templates/module/__Model__.View.tsx +9 -6
  169. package/templates/module/__Model__.Zone.tsx +25 -17
  170. package/templates/module/__model__.constant.ts +8 -9
  171. package/templates/module/__model__.dictionary.ts +16 -17
  172. package/templates/module/__model__.document.ts +6 -8
  173. package/templates/module/__model__.service.ts +3 -3
  174. package/templates/module/__model__.signal.ts +11 -10
  175. package/templates/module/__model__.store.ts +3 -5
  176. package/templates/service/__model__.dictionary.ts +5 -6
  177. package/templates/service/__model__.service.ts +3 -3
  178. package/templates/service/__model__.signal.ts +5 -4
  179. package/templates/service/__model__.store.ts +3 -5
  180. package/templates/workspaceRoot/.gitignore.template +4 -0
  181. package/templates/workspaceRoot/.vscode/settings.json.template +21 -21
  182. package/templates/workspaceRoot/AGENTS.md.template +4 -10
  183. package/{tunnel.command-ycmja19q.js → tunnel.command-dcb0wg93.js} +25 -13
  184. package/{typeChecker-px49mezc.js → typeChecker-j2jdnqsr.js} +1 -1
  185. package/typecheck.proc.js +6 -1
  186. package/verify.command-yyepccbh.js +93 -0
  187. package/{workflow.command-abb1d5xy.js → workflow.command-z5pg9ay0.js} +49 -14
  188. package/workspace.command-d7x5jttw.js +290 -0
  189. package/CodeAgent-8d5qs787.js +0 -9
  190. package/CodeAgentRpcListener-7p7z5dd7.js +0 -97
  191. package/TunnelShare-qkm8zp03.js +0 -14
  192. package/agent.command-ydftceda.js +0 -25
  193. package/cloud.script-nqevg5qw.js +0 -24
  194. package/code.command-9h3yrzhe.js +0 -167
  195. package/context.runner-8gg030b0.js +0 -25
  196. package/guidelines/conventions/conventions.instruction.md +0 -617
  197. package/guidelines/workspaceOnboarding/workspaceOnboarding.instruction.md +0 -291
  198. package/index-2mwc0g0d.js +0 -49
  199. package/index-4vgbysa0.js +0 -279
  200. package/index-7md2g9vw.js +0 -6
  201. package/index-b70zct19.js +0 -856
  202. package/index-c6eggbee.js +0 -123
  203. package/index-zzvvc845.js +0 -74
  204. package/quality.command-ah8qcakd.js +0 -1478
  205. package/templates/workspaceRoot/docs/AI-DEVELOPMENT.md.template +0 -69
  206. package/templates/workspaceRoot/docs/GENERATED.md.template +0 -55
  207. package/workspace.command-qm7cw29v.js +0 -521
@@ -1,6 +1,17 @@
1
1
  // @bun
2
2
  import {
3
- ApplicationBuildReporter,
3
+ AppInfo,
4
+ CommandExecutionError,
5
+ WorkspaceExecutor,
6
+ SysExecutor,
7
+ AppExecutor,
8
+ LibExecutor,
9
+ PkgExecutor
10
+ } from "./index-g500c5j9.js";
11
+ import {
12
+ FileSys2
13
+ } from "./index-bns3wcpc.js";
14
+ import {
4
15
  UNAVAILABLE_REDIS_HOST,
5
16
  redisTunnelPolicy,
6
17
  BUILDER_MIN_RSS_RECYCLE_INTERVAL_MS,
@@ -35,61 +46,96 @@ import {
35
46
  filesChangedSince,
36
47
  HmrWatcher,
37
48
  WatchRootResolver
38
- } from "./index-5nd1wtkv.js";
49
+ } from "./index-p6x5b7hr.js";
39
50
  import {
40
51
  runner,
41
- script,
42
- markCliErrorPrinted,
52
+ ExitCodeError,
43
53
  assertPromptable
44
- } from "./index-3wypz6xj.js";
45
- import {
46
- AppInfo,
47
- CommandExecutionError,
48
- WorkspaceExecutor,
49
- SysExecutor,
50
- AppExecutor,
51
- LibExecutor,
52
- PkgExecutor
53
- } from "./index-wcej7g4z.js";
54
+ } from "./index-9zy8479y.js";
54
55
  import {
55
56
  UpdatePackFolder,
56
57
  UpdateUploader,
57
58
  NativePublicEnv,
58
59
  NativeApp
59
- } from "./index-bt438yxm.js";
60
+ } from "./index-sp0qsr7a.js";
60
61
  import {
61
62
  DesktopServerStage
62
- } from "./index-js6geqjn.js";
63
+ } from "./index-0j1t1h2b.js";
63
64
  import {
64
65
  resolveMobileTargets,
65
66
  resolveAppId
66
67
  } from "./index-m9jj544v.js";
67
68
  import {
68
- LibraryScript
69
- } from "./index-2xcc2ax5.js";
70
- import {
71
- stripAnsi
72
- } from "./index-7md2g9vw.js";
73
- import {
74
- SlicePlanner,
75
- formatSlicePlan
76
- } from "./index-pcwzkdqb.js";
69
+ SlicePlanner
70
+ } from "./index-defp4gmb.js";
77
71
  import {
78
72
  openBrowser
79
73
  } from "./index-9dp031by.js";
80
-
81
- // pkgs/@akanjs/cli/application/application.script.ts
82
- import { confirm } from "@inquirer/prompts";
83
- import { Logger as Logger6, toError as toError2 } from "akanjs/common";
74
+ import {
75
+ ShellOnlyEnv
76
+ } from "./index-yf9wc28h.js";
77
+ import {
78
+ ConfigLock
79
+ } from "./index-bqbf654f.js";
84
80
 
85
81
  // pkgs/@akanjs/cli/application/application.runner.ts
86
82
  import { existsSync, realpathSync } from "fs";
87
- import path5 from "path";
83
+ import path6 from "path";
88
84
 
89
85
  // pkgs/@akanjs/devkit/akanApp/akanApp.host.ts
90
- import path3 from "path";
86
+ import path4 from "path";
91
87
  import { Logger as Logger2 } from "akanjs/common";
92
88
 
89
+ // pkgs/@akanjs/devkit/createTunnel.ts
90
+ import { readFileSync } from "fs";
91
+
92
+ // pkgs/@akanjs/devkit/sshHostKeys.ts
93
+ import { createHash } from "crypto";
94
+ import { mkdir, rm, writeFile } from "fs/promises";
95
+ import path from "path";
96
+ class SshHostKeys {
97
+ static defaultPath() {
98
+ return path.join(Bun.env.HOME ?? Bun.env.USERPROFILE ?? "", ".akan", "ssh_known_hosts.json");
99
+ }
100
+ static fingerprintOf(key) {
101
+ return `SHA256:${createHash("sha256").update(key).digest("base64").replace(/=+$/, "")}`;
102
+ }
103
+ static parsePinned(value) {
104
+ return (value ?? "").split(",").map((fingerprint) => fingerprint.trim()).filter(Boolean).map((fingerprint) => fingerprint.startsWith("SHA256:") ? fingerprint : `SHA256:${fingerprint}`);
105
+ }
106
+ filePath;
107
+ constructor(filePath = SshHostKeys.defaultPath()) {
108
+ this.filePath = filePath;
109
+ }
110
+ async verify(hostId, key, pinned = []) {
111
+ const fingerprint = SshHostKeys.fingerprintOf(key);
112
+ if (pinned.length)
113
+ return { trusted: pinned.includes(fingerprint), firstUse: false, fingerprint };
114
+ return await ConfigLock.run(`${this.filePath}.lock`, async () => {
115
+ const known = await this.#read();
116
+ const stored = known[hostId];
117
+ if (stored)
118
+ return { trusted: stored === fingerprint, firstUse: false, fingerprint };
119
+ await this.#write({ ...known, [hostId]: fingerprint });
120
+ return { trusted: true, firstUse: true, fingerprint };
121
+ });
122
+ }
123
+ async#read() {
124
+ return await FileSys2.fileExists(this.filePath) ? await FileSys2.readJson(this.filePath) : {};
125
+ }
126
+ async#write(known) {
127
+ await mkdir(path.dirname(this.filePath), { recursive: true, mode: 448 });
128
+ const temp = `${this.filePath}.${process.pid}.${crypto.randomUUID()}.tmp`;
129
+ try {
130
+ await writeFile(temp, JSON.stringify(known, null, 2), { mode: 384 });
131
+ await FileSys2.replace(temp, this.filePath);
132
+ } catch (error) {
133
+ await rm(temp, { force: true });
134
+ throw error;
135
+ }
136
+ }
137
+ }
138
+
93
139
  // pkgs/@akanjs/devkit/sshTunnel.ts
94
140
  import { Client } from "ssh2";
95
141
  var closeQuietly = (close) => {
@@ -199,38 +245,86 @@ var closeBunSocket = (socket, error) => {
199
245
  };
200
246
 
201
247
  // pkgs/@akanjs/devkit/createTunnel.ts
248
+ var tunnelEnv = new ShellOnlyEnv([
249
+ "SSH_TUNNEL_PRIVATE_KEY_PATH",
250
+ "SSH_TUNNEL_PASSPHRASE",
251
+ "SSH_TUNNEL_HOST_FINGERPRINT",
252
+ "SSH_TUNNEL_KNOWN_HOSTS",
253
+ "SSH_TUNNEL_BIND_HOST"
254
+ ]);
255
+ var tunnelAuth = (app, repoName) => {
256
+ const keyPath = tunnelEnv.get("SSH_TUNNEL_PRIVATE_KEY_PATH");
257
+ const passphrase = tunnelEnv.get("SSH_TUNNEL_PASSPHRASE");
258
+ if (keyPath)
259
+ return { privateKey: readFileSync(keyPath), ...passphrase ? { passphrase } : {} };
260
+ if (process.env.SSH_TUNNEL_PASSWORD)
261
+ return { password: process.env.SSH_TUNNEL_PASSWORD };
262
+ app.logger.warn("The SSH tunnel uses the default shared credential. " + "Set SSH_TUNNEL_PRIVATE_KEY_PATH to a key (or SSH_TUNNEL_PASSWORD) once the cluster's tunnel endpoint accepts it.");
263
+ return { password: repoName };
264
+ };
265
+ var tunnelHostVerifier = (app, hostId, onRefusal) => {
266
+ const pinned = SshHostKeys.parsePinned(tunnelEnv.get("SSH_TUNNEL_HOST_FINGERPRINT"));
267
+ const hostKeys = new SshHostKeys(tunnelEnv.get("SSH_TUNNEL_KNOWN_HOSTS") || undefined);
268
+ return (key, verify) => {
269
+ if (pinned.includes("SHA256:*")) {
270
+ app.logger.warn(`SSH_TUNNEL_HOST_FINGERPRINT=* accepts any host key ${hostId} shows.`);
271
+ verify(true);
272
+ return;
273
+ }
274
+ hostKeys.verify(hostId, key, pinned).then(({ trusted, firstUse, fingerprint }) => {
275
+ if (firstUse)
276
+ app.logger.warn(`Trusting the SSH host key ${fingerprint} of ${hostId} on first use; kept in ${hostKeys.filePath}.`);
277
+ if (!trusted)
278
+ onRefusal(pinned.length ? `the host key ${fingerprint} of ${hostId} is not one SSH_TUNNEL_HOST_FINGERPRINT pins` : `the host key ${fingerprint} of ${hostId} differs from the one ${hostKeys.filePath} keeps; if the host was rebuilt, remove its entry or pin the new key with SSH_TUNNEL_HOST_FINGERPRINT`);
279
+ verify(trusted);
280
+ }, (error) => {
281
+ onRefusal(`the host key store ${hostKeys.filePath} could not be read (${error instanceof Error ? error.message : String(error)})`);
282
+ verify(false);
283
+ });
284
+ };
285
+ };
202
286
  var createTunnel = async (service, { app, environment, port = service === "postgres" ? 5432 : 6379 }) => {
203
287
  const baseDevEnv = WorkspaceExecutor.getBaseDevEnv();
204
288
  WorkspaceExecutor.assertDeployableEnv(baseDevEnv, environment, `The ${service} tunnel`);
289
+ for (const line of tunnelEnv.ignored())
290
+ app.logger.warn(line);
205
291
  const { serveDomain, repoName } = baseDevEnv;
206
292
  const host = `${app.name}-${environment}.${serveDomain}`;
293
+ const sshHost = host.endsWith(".localhost") ? "localhost" : host;
207
294
  const sshPort = process.env.SSH_TUNNEL_PORT ? parseInt(process.env.SSH_TUNNEL_PORT) : 32767;
208
295
  const dstHost = `${service}-0.${service}-svc.${app.name}-${environment}.svc.cluster.local`;
209
296
  const dstPort = service === "postgres" ? 5432 : 6379;
297
+ const bindHost = tunnelEnv.get("SSH_TUNNEL_BIND_HOST") || "127.0.0.1";
298
+ if (!["127.0.0.1", "localhost", "::1"].includes(bindHost))
299
+ app.logger.warn(`The ${service} tunnel listens on ${bindHost} (SSH_TUNNEL_BIND_HOST), so other machines that reach it reach ${dstHost}.`);
300
+ let refusal = null;
210
301
  try {
211
302
  await createSshTunnel({
212
- localHost: "0.0.0.0",
303
+ localHost: bindHost,
213
304
  localPort: port,
214
- srcHost: "0.0.0.0",
305
+ srcHost: "127.0.0.1",
215
306
  srcPort: port,
216
307
  dstHost,
217
308
  dstPort,
218
309
  sshOptions: {
219
- host: host.endsWith(".localhost") ? "localhost" : host,
310
+ host: sshHost,
220
311
  port: sshPort,
221
312
  username: process.env.SSH_TUNNEL_USERNAME ?? "root",
222
- password: process.env.SSH_TUNNEL_PASSWORD ?? repoName
313
+ ...tunnelAuth(app, repoName),
314
+ hostVerifier: tunnelHostVerifier(app, `${sshHost}:${sshPort}`, (reason) => {
315
+ refusal = reason;
316
+ })
223
317
  }
224
318
  });
225
319
  } catch (error) {
226
320
  const reasons = error instanceof AggregateError ? error.errors.map((reason) => reason instanceof Error ? reason.message : String(reason)).join("; ") : error instanceof Error ? error.message : String(error);
227
- throw new Error(`Could not open the ${service} tunnel for ${app.name}-${environment}: SSH ${host}:${sshPort} -> ${dstHost}:${dstPort} failed (${reasons})`, { cause: error });
321
+ throw new Error(`Could not open the ${service} tunnel for ${app.name}-${environment}: SSH ${host}:${sshPort} -> ${dstHost}:${dstPort} failed (${refusal ?? reasons})`, { cause: error });
228
322
  }
229
323
  return `localhost:${port}`;
230
324
  };
231
325
  // pkgs/@akanjs/devkit/incrementalBuilder/incrementalBuilder.host.ts
232
326
  import fs from "fs";
233
- import path from "path";
327
+ import path2 from "path";
234
328
  import { Logger } from "akanjs/common";
235
329
  import { CSR_DEV_DIRNAME, CSR_DEV_PATCHING_MARKER, SSR_DEV_DIRNAME } from "akanjs/server/hmr/csrDevManifest";
236
330
  import { MemoryLimit } from "akanjs/server/memoryLimit";
@@ -377,7 +471,7 @@ class IncrementalBuilderHost {
377
471
  this.logger.verbose(`builder spawned pid=${proc.pid} entry=${this.entry}${isRestart ? " restart=1" : ""}`);
378
472
  }
379
473
  #checkPatchingMarker(afterCrash) {
380
- const markers = [CSR_DEV_DIRNAME, SSR_DEV_DIRNAME].map((dirName) => path.join(this.app.cwdPath, ".akan/artifact", dirName, CSR_DEV_PATCHING_MARKER)).filter((marker) => fs.existsSync(marker));
474
+ const markers = [CSR_DEV_DIRNAME, SSR_DEV_DIRNAME].map((dirName) => path2.join(this.app.cwdPath, ".akan/artifact", dirName, CSR_DEV_PATCHING_MARKER)).filter((marker) => fs.existsSync(marker));
381
475
  if (markers.length === 0)
382
476
  return;
383
477
  if (afterCrash && !this.#patcherOff) {
@@ -496,10 +590,10 @@ class IncrementalBuilderHost {
496
590
  patcherOff = false
497
591
  } = {}) {
498
592
  const candidates = [
499
- path.join(app.workspace.workspaceRoot, "pkgs/@akanjs/devkit/incrementalBuilder/incrementalBuilder.proc.ts"),
500
- path.join(app.workspace.workspaceRoot, "node_modules/@akanjs/devkit/incrementalBuilder/incrementalBuilder.proc.ts"),
501
- path.join(import.meta.dir, "incrementalBuilder.proc.js"),
502
- path.join(import.meta.dir, "incrementalBuilder.proc.ts")
593
+ path2.join(app.workspace.workspaceRoot, "pkgs/@akanjs/devkit/incrementalBuilder/incrementalBuilder.proc.ts"),
594
+ path2.join(app.workspace.workspaceRoot, "node_modules/@akanjs/devkit/incrementalBuilder/incrementalBuilder.proc.ts"),
595
+ path2.join(import.meta.dir, "incrementalBuilder.proc.js"),
596
+ path2.join(import.meta.dir, "incrementalBuilder.proc.ts")
503
597
  ];
504
598
  for (const c of candidates)
505
599
  if (await Bun.file(c).exists())
@@ -544,7 +638,7 @@ class BuilderRequestRouter {
544
638
 
545
639
  // pkgs/@akanjs/devkit/akanApp/BackendImportGraph.ts
546
640
  import { stat } from "fs/promises";
547
- import path2 from "path";
641
+ import path3 from "path";
548
642
  var NON_SOURCE_EXT_RE = /\.(css|scss|sass|less|json|svg|png|jpe?g|webp|gif|avif|ico|woff2?|ttf|otf|mp3|mp4|wav|html)$/i;
549
643
  var GRAPH_IMPORT_KINDS = new Set([
550
644
  "import-statement",
@@ -575,7 +669,7 @@ class BackendImportGraph {
575
669
  return this.#lastRefreshSucceeded;
576
670
  }
577
671
  has(file) {
578
- return this.#files.has(path2.resolve(file));
672
+ return this.#files.has(path3.resolve(file));
579
673
  }
580
674
  async fingerprint() {
581
675
  const stamps = await Promise.all([...this.#files].map(async (file) => {
@@ -603,9 +697,9 @@ class BackendImportGraph {
603
697
  const roots = await this.#entrypoints();
604
698
  const files = new Set;
605
699
  const queue = [...roots];
606
- const workspaceRoot = path2.resolve(this.#app.workspace.workspaceRoot);
700
+ const workspaceRoot = path3.resolve(this.#app.workspace.workspaceRoot);
607
701
  while (queue.length > 0) {
608
- const current = path2.resolve(queue.pop());
702
+ const current = path3.resolve(queue.pop());
609
703
  if (files.has(current))
610
704
  continue;
611
705
  if (!this.#isWorkspaceSource(current, workspaceRoot))
@@ -614,7 +708,7 @@ class BackendImportGraph {
614
708
  if (!imports)
615
709
  continue;
616
710
  files.add(current);
617
- const importerDir = path2.dirname(current);
711
+ const importerDir = path3.dirname(current);
618
712
  for (const imp of imports) {
619
713
  if (!GRAPH_IMPORT_KINDS.has(imp.kind) || !imp.path || NON_SOURCE_EXT_RE.test(imp.path))
620
714
  continue;
@@ -645,7 +739,7 @@ class BackendImportGraph {
645
739
  const roots = [`${this.#app.cwdPath}/main.ts`, `${this.#app.cwdPath}/server.ts`];
646
740
  const existing = [];
647
741
  for (const root of roots) {
648
- const abs = path2.resolve(root);
742
+ const abs = path3.resolve(root);
649
743
  if (await Bun.file(abs).exists())
650
744
  existing.push(abs);
651
745
  }
@@ -654,25 +748,25 @@ class BackendImportGraph {
654
748
  #resolve(specifier, importerDir) {
655
749
  try {
656
750
  const resolved = Bun.resolveSync(specifier, importerDir);
657
- if (!path2.isAbsolute(resolved))
751
+ if (!path3.isAbsolute(resolved))
658
752
  return null;
659
- if (!SOURCE_EXTS.has(path2.extname(resolved).toLowerCase()))
753
+ if (!SOURCE_EXTS.has(path3.extname(resolved).toLowerCase()))
660
754
  return null;
661
- return path2.resolve(resolved);
755
+ return path3.resolve(resolved);
662
756
  } catch {
663
757
  return null;
664
758
  }
665
759
  }
666
760
  #isWorkspaceSource(file, workspaceRoot) {
667
- const rel = path2.relative(workspaceRoot, file);
668
- if (rel.startsWith("..") || path2.isAbsolute(rel))
761
+ const rel = path3.relative(workspaceRoot, file);
762
+ if (rel.startsWith("..") || path3.isAbsolute(rel))
669
763
  return false;
670
- if (rel.includes(`${path2.sep}node_modules${path2.sep}`) || rel.includes(`${path2.sep}.akan${path2.sep}`))
764
+ if (rel.includes(`${path3.sep}node_modules${path3.sep}`) || rel.includes(`${path3.sep}.akan${path3.sep}`))
671
765
  return false;
672
- return SOURCE_EXTS.has(path2.extname(file).toLowerCase());
766
+ return SOURCE_EXTS.has(path3.extname(file).toLowerCase());
673
767
  }
674
768
  #scanImports(file, source) {
675
- const ext = path2.extname(file).toLowerCase();
769
+ const ext = path3.extname(file).toLowerCase();
676
770
  if (ext === ".tsx")
677
771
  return this.#tsxTranspiler.scanImports(source);
678
772
  if (ext === ".jsx")
@@ -1271,6 +1365,11 @@ ${this.#backendStderrTail.join(`
1271
1365
  static async readProcessRssBytes(pid) {
1272
1366
  if (process.platform === "win32")
1273
1367
  return await AkanAppHost.#readRssKbVia(["tasklist", "/FI", `PID eq ${pid}`, "/FO", "CSV", "/NH"], AkanAppHost.#tasklistRssKb);
1368
+ if (process.platform === "darwin") {
1369
+ const footprintBytes = await AkanAppHost.#readRssKbVia(["footprint", "-p", String(pid), "-f", "bytes"], AkanAppHost.#footprintKb);
1370
+ if (footprintBytes !== null)
1371
+ return footprintBytes;
1372
+ }
1274
1373
  const status = await Bun.file(`/proc/${pid}/status`).text().catch(() => null);
1275
1374
  const vmRssKb = status === null ? null : /VmRSS:\s+(\d+) kB/.exec(status)?.[1];
1276
1375
  if (vmRssKb)
@@ -1300,6 +1399,10 @@ ${this.#backendStderrTail.join(`
1300
1399
  const memUsage = /"([^"]*)"\s*$/m.exec(output)?.[1];
1301
1400
  return memUsage ? Number(memUsage.replace(/\D/g, "")) : Number.NaN;
1302
1401
  }
1402
+ static #footprintKb(output) {
1403
+ const bytes = /Footprint: (\d+) B\b/.exec(output)?.[1];
1404
+ return bytes ? Number(bytes) / 1024 : Number.NaN;
1405
+ }
1303
1406
  #cancelRssRecycle() {
1304
1407
  this.#rssRecycleReason = null;
1305
1408
  this.#rssRecycleOver = null;
@@ -1697,7 +1800,7 @@ ${this.#backendStderrTail.join(`
1697
1800
  const generation = message.devPlan?.generation ?? message.generation ?? this.#nextBackendBuildStatusGeneration();
1698
1801
  const detail = err instanceof Error ? err.message : String(err);
1699
1802
  this.logger.warn(`[dev-host] ${kind.toLowerCase()} restart failed generation=${generation}: ${detail}`);
1700
- const names = message.files.slice(0, 3).map((file) => path3.basename(file));
1803
+ const names = message.files.slice(0, 3).map((file) => path4.basename(file));
1701
1804
  const saved = names.length > 0 ? names.join(", ") : "the changed file";
1702
1805
  const status = {
1703
1806
  generation,
@@ -1878,16 +1981,16 @@ ${this.#backendStderrTail.join(`
1878
1981
  }
1879
1982
  }
1880
1983
  // pkgs/@akanjs/devkit/applicationTestPreload.ts
1881
- import path4 from "path";
1984
+ import path5 from "path";
1882
1985
  var SIGNAL_TEST_PRELOAD_PATH = "test/signalTest.preload.ts";
1883
1986
  async function resolveSignalTestPreloadPath(target) {
1884
1987
  const candidates = [];
1885
- for (const basePath of [target.cwdPath, process.cwd(), path4.dirname(Bun.main), import.meta.dir]) {
1988
+ for (const basePath of [target.cwdPath, process.cwd(), path5.dirname(Bun.main), import.meta.dir]) {
1886
1989
  try {
1887
- candidates.push(path4.join(path4.dirname(Bun.resolveSync("akanjs/package.json", basePath)), SIGNAL_TEST_PRELOAD_PATH));
1990
+ candidates.push(path5.join(path5.dirname(Bun.resolveSync("akanjs/package.json", basePath)), SIGNAL_TEST_PRELOAD_PATH));
1888
1991
  } catch {}
1889
1992
  }
1890
- candidates.push(path4.join(target.cwdPath, "../../node_modules/akanjs", SIGNAL_TEST_PRELOAD_PATH), path4.join(target.cwdPath, "../../pkgs/akanjs", SIGNAL_TEST_PRELOAD_PATH), path4.join(process.cwd(), "node_modules/akanjs", SIGNAL_TEST_PRELOAD_PATH), path4.join(process.cwd(), "pkgs/akanjs", SIGNAL_TEST_PRELOAD_PATH), path4.join(path4.dirname(Bun.main), "../../akanjs", SIGNAL_TEST_PRELOAD_PATH), path4.resolve(import.meta.dir, "../../akanjs", SIGNAL_TEST_PRELOAD_PATH));
1993
+ candidates.push(path5.join(target.cwdPath, "../../node_modules/akanjs", SIGNAL_TEST_PRELOAD_PATH), path5.join(target.cwdPath, "../../pkgs/akanjs", SIGNAL_TEST_PRELOAD_PATH), path5.join(process.cwd(), "node_modules/akanjs", SIGNAL_TEST_PRELOAD_PATH), path5.join(process.cwd(), "pkgs/akanjs", SIGNAL_TEST_PRELOAD_PATH), path5.join(path5.dirname(Bun.main), "../../akanjs", SIGNAL_TEST_PRELOAD_PATH), path5.resolve(import.meta.dir, "../../akanjs", SIGNAL_TEST_PRELOAD_PATH));
1891
1994
  const uniqueCandidates = [...new Set(candidates)];
1892
1995
  for (const candidate of uniqueCandidates)
1893
1996
  if (await Bun.file(candidate).exists())
@@ -1900,7 +2003,7 @@ ${uniqueCandidates.map((candidate) => ` - ${candidate}`).join(`
1900
2003
 
1901
2004
  // pkgs/@akanjs/cli/application/application.runner.ts
1902
2005
  import { Logger as Logger3, toError } from "akanjs/common";
1903
- var loadBuildRunner = async () => (await import("./applicationBuildRunner-t2r84sz6.js")).ApplicationBuildRunner;
2006
+ var loadBuildRunner = async () => (await import("./applicationBuildRunner-s13x3zqb.js")).ApplicationBuildRunner;
1904
2007
  var loadPrompts = async () => await import("@inquirer/prompts");
1905
2008
 
1906
2009
  class ApplicationRunner extends runner("application") {
@@ -1951,13 +2054,13 @@ class ApplicationRunner extends runner("application") {
1951
2054
  stdio: "inherit"
1952
2055
  });
1953
2056
  }
1954
- #runtimeDirOf(app, override) {
1955
- return path5.resolve(override ?? process.env.AKAN_RUNTIME_DIR ?? path5.join(app.workspace.workspaceRoot, "local", "apps", app.name, "runtime"));
2057
+ static runtimeDirOf(app, override) {
2058
+ return path6.resolve(override ?? process.env.AKAN_RUNTIME_DIR ?? path6.join(app.workspace.workspaceRoot, "local", "apps", app.name, "runtime"));
1956
2059
  }
1957
2060
  async runLogs(app, options) {
1958
2061
  const { LogControlUnavailableError, LogTailClient } = await import("akanjs/server/logging/logTailClient");
1959
2062
  const { LogQueryMatcher } = await import("akanjs/server/logging/logQuery");
1960
- const runtimeDir = this.#runtimeDirOf(app, options.runtimeDir);
2063
+ const runtimeDir = ApplicationRunner.runtimeDirOf(app, options.runtimeDir);
1961
2064
  const socketPath = LogTailClient.socketPath(runtimeDir);
1962
2065
  const { level, grep, endpoint, trace, child, role, origin, since } = options;
1963
2066
  const query = Object.fromEntries(Object.entries({ level, grep, endpoint, trace, child, role, origin, since }).filter(([, value]) => value !== undefined && value !== null && value !== ""));
@@ -1978,7 +2081,7 @@ class ApplicationRunner extends runner("application") {
1978
2081
  });
1979
2082
  } catch (error) {
1980
2083
  if (error instanceof LogControlUnavailableError)
1981
- throw new Error(`${app.name} is not running (no ${path5.basename(socketPath)} in ${runtimeDir}). Start it with \`akan start ${app.name}\`, or pass --runtime-dir for a built app.`);
2084
+ throw new Error(`${app.name} is not running (no ${path6.basename(socketPath)} in ${runtimeDir}). Start it with \`akan start ${app.name}\`, or pass --runtime-dir for a built app.`);
1982
2085
  throw error;
1983
2086
  }
1984
2087
  const sinceMs = since ? LogQueryMatcher.parseSince(since) : undefined;
@@ -2010,7 +2113,7 @@ class ApplicationRunner extends runner("application") {
2010
2113
  const serverPath = `${app.cwdPath}/server.ts`;
2011
2114
  if (!await app.exists("server.ts"))
2012
2115
  throw new Error(`Server file not found: apps/${app.name}/server.ts`);
2013
- const runtimeDir = this.#runtimeDirOf(app);
2116
+ const runtimeDir = ApplicationRunner.runtimeDirOf(app);
2014
2117
  const code = `
2015
2118
  const serverModule = await import(${JSON.stringify(serverPath)});
2016
2119
  const { assertAkanConsoleAllowed, startAkanConsole } = await import("akanjs/server");
@@ -2040,7 +2143,7 @@ try {
2040
2143
  const serverPath = `${app.cwdPath}/server.ts`;
2041
2144
  if (!await app.exists("server.ts"))
2042
2145
  throw new Error(`Server file not found: apps/${app.name}/server.ts`);
2043
- const target = path5.resolve(app.workspace.workspaceRoot, dir);
2146
+ const target = path6.resolve(app.workspace.workspaceRoot, dir);
2044
2147
  const code = `
2045
2148
  const { server } = await import(${JSON.stringify(serverPath)});
2046
2149
  const { DatabaseAdaptorRole, DocumentTransfer } = await import("akanjs/service");
@@ -2101,7 +2204,7 @@ if (loaded) process.exitCode = await loaded.migrations.command(loaded.server, ar
2101
2204
  await new (await loadBuildRunner())(app).typecheck(options);
2102
2205
  }
2103
2206
  async typecheckLibrary(lib, options = {}) {
2104
- const { ProjectTypecheck } = await import("./projectTypecheck-2ztky9cf.js");
2207
+ const { ProjectTypecheck } = await import("./projectTypecheck-kqj1t6hb.js");
2105
2208
  const root = lib.workspace.workspaceRoot;
2106
2209
  await new ProjectTypecheck(lib.cwdPath, root, { ...process.env, AKAN_WORKSPACE_ROOT: root }).run([
2107
2210
  "../../server.ts",
@@ -2114,15 +2217,15 @@ if (loaded) process.exitCode = await loaded.migrations.command(loaded.server, ar
2114
2217
  }
2115
2218
  resolveTestPaths(exec, files) {
2116
2219
  const root = exec instanceof SysExecutor || exec instanceof PkgExecutor ? exec.workspace.workspaceRoot : process.cwd();
2117
- const target = path5.relative(root, exec.cwdPath).split(path5.sep).join("/");
2118
- const isInside = (relative) => relative !== ".." && !relative.startsWith(`..${path5.sep}`) && !path5.isAbsolute(relative);
2220
+ const target = path6.relative(root, exec.cwdPath).split(path6.sep).join("/");
2221
+ const isInside = (relative) => relative !== ".." && !relative.startsWith(`..${path6.sep}`) && !path6.isAbsolute(relative);
2119
2222
  return files.map((file) => {
2120
- const candidates = path5.isAbsolute(file) ? [file] : [path5.resolve(exec.cwdPath, file), path5.resolve(root, file)];
2121
- const existing = candidates.filter((candidate) => existsSync(candidate)).map((candidate) => path5.relative(exec.cwdPath, candidate));
2223
+ const candidates = path6.isAbsolute(file) ? [file] : [path6.resolve(exec.cwdPath, file), path6.resolve(root, file)];
2224
+ const existing = candidates.filter((candidate) => existsSync(candidate)).map((candidate) => path6.relative(exec.cwdPath, candidate));
2122
2225
  const found = existing.find(isInside);
2123
2226
  if (found === undefined)
2124
2227
  throw new Error(existing.length ? `${file} is outside ${target}: akan test ${exec.name} runs its own tests only` : `${file} names no file or folder in ${target}`);
2125
- return `./${found.split(path5.sep).join("/")}`;
2228
+ return `./${found.split(path6.sep).join("/")}`;
2126
2229
  });
2127
2230
  }
2128
2231
  async test(exec, testPaths = []) {
@@ -2133,7 +2236,7 @@ if (loaded) process.exitCode = await loaded.migrations.command(loaded.server, ar
2133
2236
  AKAN_TEST_TARGET_TYPE: exec.type,
2134
2237
  AKAN_TEST_TARGET_NAME: exec.name,
2135
2238
  AKAN_TEST_LIBS: exec.getScanInfo({ allowEmpty: true })?.getLibs().join(",") ?? "",
2136
- AKAN_RUNTIME_DIR: path5.join(exec.workspace.workspaceRoot, "local", `${exec.type}s`, exec.name, "runtime")
2239
+ AKAN_RUNTIME_DIR: path6.join(exec.workspace.workspaceRoot, "local", `${exec.type}s`, exec.name, "runtime")
2137
2240
  } : {};
2138
2241
  const args = ["test", "--isolate", ...preloadPath ? ["--preload", preloadPath] : [], ...testPaths];
2139
2242
  await exec.spawn("bun", args, {
@@ -2251,7 +2354,7 @@ if (loaded) process.exitCode = await loaded.migrations.command(loaded.server, ar
2251
2354
  try {
2252
2355
  return realpathSync.native(root);
2253
2356
  } catch {
2254
- return path5.resolve(root);
2357
+ return path6.resolve(root);
2255
2358
  }
2256
2359
  };
2257
2360
  return canonical(reported) === canonical(own);
@@ -2275,13 +2378,13 @@ if (loaded) process.exitCode = await loaded.migrations.command(loaded.server, ar
2275
2378
  if (!mobileTarget || targets.length > 1)
2276
2379
  throw new Error("pack-update packs one native target at a time; pass --target <name>.");
2277
2380
  const nativeApp = new NativeApp(app, mobileTarget, env);
2278
- await UpdatePackFolder.clear(path5.resolve(out ?? path5.join(nativeApp.updatesDir, platform)));
2381
+ await UpdatePackFolder.clear(path6.resolve(out ?? path6.join(nativeApp.updatesDir, platform)));
2279
2382
  const pinned = publicEnv ? await NativePublicEnv.load(publicEnv) : against ? await NativePublicEnv.recordedIn(against) : null;
2280
2383
  await this.#buildMobileCsr(app, env, undefined, pinned);
2281
2384
  const { pack } = await nativeApp.packUpdate(platform, { out });
2282
2385
  app.logger.info(`packed ${mobileTarget.name} ${platform} for channel '${pack.channel}' to ${pack.out}: ${pack.files} files, ${(pack.size / 1024).toFixed(0)} KiB, native API ${pack.nativeApi}`);
2283
2386
  if (against) {
2284
- const bundle = path5.join(pack.out, UpdatePackFolder.bundleFile);
2387
+ const bundle = path6.join(pack.out, UpdatePackFolder.bundleFile);
2285
2388
  const compat = await NativeApp.compareBundles(app.cwdPath, against, bundle);
2286
2389
  const envProblem = await NativePublicEnv.problemAgainst(against, bundle);
2287
2390
  await UpdatePackFolder.writeCompat(pack, {
@@ -2525,1212 +2628,71 @@ ${detail}`
2525
2628
  }
2526
2629
  }
2527
2630
 
2528
- // pkgs/@akanjs/cli/application/hostProcessProbe.ts
2529
- import { readdirSync, readFileSync, readlinkSync } from "fs";
2530
-
2531
- class HostProcessProbe {
2532
- static timeoutMs = 3000;
2533
- static win32TimeoutMs = 20000;
2534
- static #procTcpListen = "0A";
2535
- static #win32ProcessQuery = "[Console]::OutputEncoding=[Text.Encoding]::UTF8; Get-CimInstance Win32_Process | Select-Object ProcessId,ParentProcessId,CommandLine,CreationDate | ConvertTo-Json -Compress";
2536
- platform;
2537
- #win32Table = null;
2538
- constructor(platform = process.platform) {
2539
- this.platform = platform;
2540
- }
2541
- async listenersOn(port) {
2542
- if (this.platform === "win32")
2543
- return HostProcessProbe.parseNetstat(await HostProcessProbe.run(["netstat", "-ano"]), port);
2544
- if (this.platform === "linux")
2545
- return HostProcessProbe.#procListenersOn(port);
2546
- const output = await HostProcessProbe.run(["lsof", "-ti", `tcp:${port}`, "-sTCP:LISTEN"]);
2547
- return [
2548
- ...new Set(output.split(`
2549
- `).map((line) => Number(line.trim())).filter((pid) => Number.isInteger(pid) && pid > 0))
2550
- ];
2631
+ // pkgs/@akanjs/cli/verify/verifyScope.ts
2632
+ class VerifyScope {
2633
+ targets;
2634
+ constructor(targets) {
2635
+ this.targets = targets;
2551
2636
  }
2552
- async parentOf(pid) {
2553
- if (this.platform === "win32") {
2554
- const child = await this.#win32Process(pid);
2555
- const parent = child ? await this.#win32Process(child.ppid) : null;
2556
- return child && parent ? HostProcessProbe.parentPidOf(child, parent) : null;
2557
- }
2558
- if (this.platform === "linux") {
2559
- const stat = HostProcessProbe.#readProc(pid, "stat");
2560
- return stat === null ? null : HostProcessProbe.parseProcStatPpid(stat);
2561
- }
2562
- const parsed = Number((await HostProcessProbe.run(["ps", "-p", String(pid), "-o", "ppid="])).trim());
2563
- return Number.isInteger(parsed) && parsed > 0 ? parsed : null;
2637
+ get touchesTsx() {
2638
+ return this.targets.some((target) => target.files.some((file) => file.endsWith(".tsx")));
2564
2639
  }
2565
- async commandOf(pid) {
2566
- if (this.platform === "win32")
2567
- return (await this.#win32Process(pid))?.command ?? null;
2568
- if (this.platform === "linux") {
2569
- const cmdline = HostProcessProbe.#readProc(pid, "cmdline");
2570
- return cmdline?.split("\x00").filter(Boolean).join(" ") || null;
2571
- }
2572
- return (await HostProcessProbe.run(["ps", "-ww", "-p", String(pid), "-o", "command="])).trim() || null;
2640
+ get changedFiles() {
2641
+ return new Set(this.targets.flatMap((target) => target.files));
2573
2642
  }
2574
- static parentPidOf(child, parent) {
2575
- if (child.ppid !== parent.pid)
2643
+ static async changesIn(workspaceRoot) {
2644
+ const prefix = await VerifyScope.#git(workspaceRoot, ["rev-parse", "--show-prefix"]);
2645
+ if (prefix === null)
2576
2646
  return null;
2577
- if (parent.startedAt !== null && child.startedAt !== null && parent.startedAt > child.startedAt)
2647
+ const status = await VerifyScope.#git(workspaceRoot, ["status", "--porcelain=v1", "-z", "--untracked-files=all"]);
2648
+ if (status === null)
2578
2649
  return null;
2579
- return parent.pid;
2580
- }
2581
- static parseNetstat(output, port) {
2582
- const pids = new Set;
2583
- for (const line of output.split(/\r?\n/)) {
2584
- const fields = line.trim().split(/\s+/);
2585
- if (fields[0] !== "TCP" || fields.length < 5)
2586
- continue;
2587
- const [, local, remote] = fields;
2588
- if (!local?.endsWith(`:${port}`) || !remote?.endsWith(":0"))
2589
- continue;
2590
- const pid = Number(fields.at(-1));
2591
- if (Number.isInteger(pid) && pid > 0)
2592
- pids.add(pid);
2593
- }
2594
- return [...pids];
2595
- }
2596
- static parseProcNetTcp(text, port) {
2597
- const inodes = [];
2598
- for (const line of text.split(`
2599
- `).slice(1)) {
2600
- const fields = line.trim().split(/\s+/);
2601
- const [, local, , state, , , , , , inode] = fields;
2602
- if (!local || !inode || state !== HostProcessProbe.#procTcpListen || inode === "0")
2603
- continue;
2604
- if (Number.parseInt(local.slice(local.lastIndexOf(":") + 1), 16) === port)
2605
- inodes.push(inode);
2606
- }
2607
- return inodes;
2608
- }
2609
- static parseProcStatPpid(stat) {
2610
- const ppid = Number(stat.slice(stat.lastIndexOf(")") + 2).split(" ")[1]);
2611
- return Number.isInteger(ppid) && ppid > 0 ? ppid : null;
2612
- }
2613
- static parseWin32Processes(json) {
2614
- const table = new Map;
2615
- let parsed;
2616
- try {
2617
- parsed = JSON.parse(json.trim() || "[]");
2618
- } catch {
2619
- return table;
2620
- }
2621
- const rows = Array.isArray(parsed) ? parsed : [parsed];
2622
- for (const row of rows) {
2623
- if (typeof row?.ProcessId !== "number")
2650
+ return VerifyScope.parseStatus(status, prefix.trim());
2651
+ }
2652
+ static parseStatus(status, prefix = "") {
2653
+ const tokens = status.split("\x00");
2654
+ const changes = [];
2655
+ for (let idx = 0;idx < tokens.length; idx++) {
2656
+ const token = tokens[idx] ?? "";
2657
+ if (token.length < 4)
2624
2658
  continue;
2625
- table.set(row.ProcessId, {
2626
- pid: row.ProcessId,
2627
- ppid: row.ParentProcessId ?? 0,
2628
- command: row.CommandLine?.trim() || null,
2629
- startedAt: HostProcessProbe.#parseCimDate(row.CreationDate)
2630
- });
2631
- }
2632
- return table;
2633
- }
2634
- static async run(command, timeoutMs = HostProcessProbe.timeoutMs) {
2635
- let proc;
2636
- try {
2637
- proc = Bun.spawn(command, { stdio: ["ignore", "pipe", "ignore"], windowsHide: true });
2638
- } catch {
2639
- return "";
2640
- }
2641
- const timer = setTimeout(() => proc.kill("SIGKILL"), timeoutMs);
2642
- try {
2643
- return await new Response(proc.stdout).text();
2644
- } catch {
2645
- return "";
2646
- } finally {
2647
- clearTimeout(timer);
2648
- }
2649
- }
2650
- async#win32Process(pid) {
2651
- this.#win32Table ??= await HostProcessProbe.#queryWin32Processes();
2652
- if (!this.#win32Table.has(pid))
2653
- this.#win32Table = await HostProcessProbe.#queryWin32Processes();
2654
- return this.#win32Table.get(pid) ?? null;
2655
- }
2656
- static async#queryWin32Processes() {
2657
- const output = await HostProcessProbe.run(["powershell", "-NoProfile", "-NonInteractive", "-Command", HostProcessProbe.#win32ProcessQuery], HostProcessProbe.win32TimeoutMs);
2658
- return HostProcessProbe.parseWin32Processes(output);
2659
- }
2660
- static #parseCimDate(value) {
2661
- if (!value)
2662
- return null;
2663
- const legacy = /\/Date\((\d+)/.exec(value)?.[1];
2664
- const ms = legacy ? Number(legacy) : Date.parse(value);
2665
- return Number.isFinite(ms) ? ms : null;
2666
- }
2667
- static #procListenersOn(port) {
2668
- const inodes = new Set(["tcp", "tcp6"].flatMap((table) => HostProcessProbe.parseProcNetTcp(HostProcessProbe.#readProc("net", table) ?? "", port)));
2669
- if (!inodes.size)
2670
- return [];
2671
- const pids = [];
2672
- for (const entry of HostProcessProbe.#listDir("/proc")) {
2673
- if (!/^\d+$/.test(entry))
2659
+ const code = token.slice(0, 2);
2660
+ const file = token.slice(3);
2661
+ if (code.includes("R") || code.includes("C"))
2662
+ idx++;
2663
+ if (!file.startsWith(prefix))
2674
2664
  continue;
2675
- const holds = HostProcessProbe.#listDir(`/proc/${entry}/fd`).some((fd) => {
2676
- const link = HostProcessProbe.#orElse(() => readlinkSync(`/proc/${entry}/fd/${fd}`), "");
2677
- const inode = /^socket:\[(\d+)\]$/.exec(link)?.[1];
2678
- return !!inode && inodes.has(inode);
2665
+ changes.push({ code, file: file.slice(prefix.length) });
2666
+ }
2667
+ return changes;
2668
+ }
2669
+ static resolve(changes, names, requested = []) {
2670
+ const known = VerifyScope.#knownTargets(names);
2671
+ const changedFilesOf = (dir) => changes.filter((change) => change.file.startsWith(`${dir}/`)).map((change) => change.file);
2672
+ if (requested.length) {
2673
+ const targets = requested.map((name) => {
2674
+ const target = known.find((candidate) => candidate.name === name);
2675
+ if (!target)
2676
+ throw new ExitCodeError(`${name} is not an app, library or package of this workspace`, 2);
2677
+ return { ...target, files: changedFilesOf(target.dir) };
2679
2678
  });
2680
- if (holds)
2681
- pids.push(Number(entry));
2682
- }
2683
- return pids;
2684
- }
2685
- static #readProc(pid, file) {
2686
- return HostProcessProbe.#orElse(() => readFileSync(`/proc/${pid}/${file}`, "utf8"), null);
2687
- }
2688
- static #listDir(dir) {
2689
- return HostProcessProbe.#orElse(() => readdirSync(dir), []);
2690
- }
2691
- static #orElse(read, fallback) {
2692
- try {
2693
- return read();
2694
- } catch {
2695
- return fallback;
2696
- }
2697
- }
2698
- }
2699
-
2700
- // pkgs/@akanjs/cli/application/devPortReclaimer.ts
2701
- class DevPortReclaimer {
2702
- static releaseTimeoutMs = 8000;
2703
- static maxAncestorDepth = 8;
2704
- static #releasePollMs = 100;
2705
- static wsPortOffset = 1e4;
2706
- static portsFor(ports) {
2707
- return [...new Set(ports.flatMap((port) => [port, port + DevPortReclaimer.wsPortOffset]))].sort((left, right) => left - right);
2708
- }
2709
- static isAkanCommand(command) {
2710
- const normalized = command.replaceAll("\\", "/");
2711
- return /(^|\/)akan(\.exe)?"?(\s|$)/.test(normalized) || normalized.includes("@akanjs/cli") || normalized.includes("akanjs/server") || /\bapps\/[^/\s]+\/main\.ts\b/.test(normalized) || normalized.includes("incrementalBuilder.proc") || normalized.includes("rscWorker");
2712
- }
2713
- #probe;
2714
- constructor(probe = new HostProcessProbe) {
2715
- this.#probe = probe;
2716
- }
2717
- async reclaim(ports) {
2718
- const killed = [];
2719
- const foreign = [];
2720
- const seen = new Set;
2721
- for (const port of DevPortReclaimer.portsFor(ports)) {
2722
- for (const holder of await this.holdersOf(port)) {
2723
- if (seen.has(holder.pid))
2724
- continue;
2725
- seen.add(holder.pid);
2726
- if (!holder.akan) {
2727
- foreign.push(holder);
2728
- continue;
2729
- }
2730
- if (await this.#terminate(holder.pid))
2731
- killed.push(holder);
2732
- else
2733
- foreign.push(holder);
2734
- }
2735
- }
2736
- return { killed, foreign };
2737
- }
2738
- async holdersOf(port) {
2739
- const holders = [];
2740
- for (const listenerPid of await this.#probe.listenersOn(port)) {
2741
- if (listenerPid === process.pid || listenerPid === process.ppid)
2742
- continue;
2743
- const command = await this.#probe.commandOf(listenerPid);
2744
- if (!command)
2745
- continue;
2746
- if (!DevPortReclaimer.isAkanCommand(command)) {
2747
- holders.push({ pid: listenerPid, command, port, listenerPid, akan: false });
2748
- continue;
2749
- }
2750
- const root = await this.#akanRootOf(listenerPid, command);
2751
- holders.push({ pid: root.pid, command: root.command, port, listenerPid, akan: true });
2752
- }
2753
- return holders;
2754
- }
2755
- async#akanRootOf(pid, command) {
2756
- let root = { pid, command };
2757
- for (let depth = 0;depth < DevPortReclaimer.maxAncestorDepth; depth += 1) {
2758
- const parentPid = await this.#probe.parentOf(root.pid);
2759
- if (parentPid === null || parentPid <= 1 || parentPid === process.pid || parentPid === process.ppid)
2760
- break;
2761
- const parentCommand = await this.#probe.commandOf(parentPid);
2762
- if (!parentCommand || !DevPortReclaimer.isAkanCommand(parentCommand))
2763
- break;
2764
- root = { pid: parentPid, command: parentCommand };
2765
- }
2766
- return root;
2767
- }
2768
- async#terminate(pid) {
2769
- if (this.#probe.platform === "win32") {
2770
- await HostProcessProbe.run(["taskkill", "/PID", String(pid), "/T", "/F"]);
2771
- return await this.#released(pid);
2772
- }
2773
- if (!this.#signal(pid, "SIGTERM"))
2774
- return !this.#alive(pid);
2775
- if (await this.#released(pid))
2776
- return true;
2777
- this.#signal(pid, "SIGKILL");
2778
- await Bun.sleep(DevPortReclaimer.#releasePollMs);
2779
- return !this.#alive(pid);
2780
- }
2781
- async#released(pid) {
2782
- const deadline = Date.now() + DevPortReclaimer.releaseTimeoutMs;
2783
- while (Date.now() < deadline) {
2784
- if (!this.#alive(pid))
2785
- return true;
2786
- await Bun.sleep(DevPortReclaimer.#releasePollMs);
2787
- }
2788
- return false;
2789
- }
2790
- #signal(pid, signal) {
2791
- try {
2792
- process.kill(pid, signal);
2793
- return true;
2794
- } catch {
2795
- return false;
2796
- }
2797
- }
2798
- #alive(pid) {
2799
- try {
2800
- process.kill(pid, 0);
2801
- return true;
2802
- } catch (error) {
2803
- return error.code === "EPERM";
2804
- }
2805
- }
2806
- }
2807
-
2808
- // pkgs/@akanjs/cli/application/devStreamView.ts
2809
- import { Logger as Logger4 } from "akanjs/common";
2810
- import chalk from "chalk";
2811
- var appColors = ["cyan", "magenta", "yellow", "green", "blue", "red"];
2812
-
2813
- class DevStreamView {
2814
- #logger = new Logger4("akan start");
2815
- #partial = new Map;
2816
- #lastState = new Map;
2817
- #color = new Map;
2818
- #width = 0;
2819
- constructor(appNames) {
2820
- this.#width = appNames.reduce((max, name) => Math.max(max, name.length), 0);
2821
- appNames.forEach((name, idx) => {
2822
- this.#color.set(name, appColors[idx % appColors.length] ?? "cyan");
2823
- });
2824
- }
2825
- onOutput = (app, kind, text) => {
2826
- const key = `${app}:${kind}`;
2827
- const pending = `${this.#partial.get(key) ?? ""}${text}`;
2828
- const lines = pending.split(`
2829
- `);
2830
- this.#partial.set(key, lines.pop() ?? "");
2831
- if (lines.length === 0)
2832
- return;
2833
- const prefixed = lines.map((line) => `${this.#prefix(app)}${line}`).join(`
2834
- `);
2835
- (kind === "stderr" ? process.stderr : process.stdout).write(`${prefixed}
2836
- `);
2837
- };
2838
- onStatus = (statuses) => {
2839
- for (const status of statuses) {
2840
- if (this.#lastState.get(status.name) === status.state)
2841
- continue;
2842
- this.#lastState.set(status.name, status.state);
2843
- const detail = status.detail ? ` (${status.detail})` : "";
2844
- const where = status.state === "ready" ? ` \u2014 ${status.url}` : "";
2845
- const line = `${status.name} ${status.state}${detail}${where}`;
2846
- if (status.state === "failed")
2847
- this.#logger.error(line);
2848
- else if (status.state === "stopped")
2849
- this.#logger.warn(line);
2850
- else
2851
- this.#logger.info(line);
2852
- }
2853
- };
2854
- onNote = (text, level) => {
2855
- if (level === "warn")
2856
- this.#logger.warn(text);
2857
- else
2858
- this.#logger.info(text);
2859
- };
2860
- waitForExit = () => new Promise(() => {
2861
- return;
2862
- });
2863
- close = () => {
2864
- for (const [key, remainder] of this.#partial) {
2865
- if (!remainder)
2866
- continue;
2867
- const app = key.slice(0, key.lastIndexOf(":"));
2868
- process.stdout.write(`${this.#prefix(app)}${remainder}
2869
- `);
2870
- }
2871
- this.#partial.clear();
2872
- };
2873
- #prefix(app) {
2874
- const color = this.#color.get(app) ?? "cyan";
2875
- return `${chalk[color](app.padEnd(this.#width))} ${chalk.dim("\u2502")} `;
2876
- }
2877
- }
2878
-
2879
- // pkgs/@akanjs/cli/application/devBootConcurrency.ts
2880
- import os from "os";
2881
- import { MemoryLimit as MemoryLimit2 } from "akanjs/server/memoryLimit";
2882
-
2883
- class DevBootConcurrency {
2884
- static perAppBytes = 1800 * 1024 * 1024;
2885
- static memoryShare = 0.5;
2886
- static coresPerApp = 4;
2887
- static budget() {
2888
- const hostBytes = os.totalmem();
2889
- const declaredBytes = MemoryLimit2.parseBytesEnv("AKAN_MEMORY_LIMIT") ?? MemoryLimit2.readCgroupBytes();
2890
- return { memoryBytes: Math.min(hostBytes, declaredBytes ?? hostBytes), cores: os.availableParallelism() };
2891
- }
2892
- static resolve(appCount, requested, budget = DevBootConcurrency.budget()) {
2893
- const apps = Math.max(1, Math.trunc(appCount));
2894
- if (requested !== null && Number.isFinite(requested)) {
2895
- const asked = Math.max(1, Math.trunc(requested));
2896
- return { concurrency: Math.min(apps, asked), reason: `--concurrency ${asked}` };
2897
- }
2898
- const byMemory = Math.floor(budget.memoryBytes * DevBootConcurrency.memoryShare / DevBootConcurrency.perAppBytes);
2899
- const byCores = Math.floor(budget.cores / DevBootConcurrency.coresPerApp);
2900
- return {
2901
- concurrency: Math.max(1, Math.min(apps, byMemory, byCores)),
2902
- reason: `${budget.cores} cores, ${DevBootConcurrency.#formatBytes(budget.memoryBytes)} memory`
2903
- };
2904
- }
2905
- static describe(appCount, plan) {
2906
- if (plan.concurrency >= appCount)
2907
- return `booting all ${appCount} apps at once (${plan.reason})`;
2908
- return `booting ${plan.concurrency} of ${appCount} apps at a time (${plan.reason}) \u2014 --concurrency raises it`;
2909
- }
2910
- static #formatBytes(bytes) {
2911
- const gigabytes = bytes / 1024 ** 3;
2912
- return gigabytes >= 10 ? `${Math.round(gigabytes)}GB` : `${gigabytes.toFixed(1)}GB`;
2913
- }
2914
- }
2915
-
2916
- // pkgs/@akanjs/cli/application/devSessionLog.ts
2917
- import { mkdir, rename } from "fs/promises";
2918
- import path6 from "path";
2919
- import dayjs from "dayjs";
2920
-
2921
- class DevSessionLog {
2922
- static fileName = "dev.log";
2923
- static previousFileName = "dev.prev.log";
2924
- static flushMs = 200;
2925
- static bufferBytes = 64 * 1024;
2926
- #workspaceRoot;
2927
- #appNames;
2928
- #now;
2929
- #writers = new Map;
2930
- #partial = new Map;
2931
- #lastState = new Map;
2932
- #flushTimer = null;
2933
- constructor({ workspaceRoot, apps, now = () => new Date }) {
2934
- this.#workspaceRoot = workspaceRoot;
2935
- this.#appNames = [...apps];
2936
- this.#now = now;
2937
- }
2938
- get appNames() {
2939
- return [...this.#appNames];
2940
- }
2941
- pathOf(app) {
2942
- return path6.join(this.#runtimeDirOf(app), DevSessionLog.fileName);
2943
- }
2944
- previousPathOf(app) {
2945
- return path6.join(this.#runtimeDirOf(app), DevSessionLog.previousFileName);
2946
- }
2947
- relativePathOf(app) {
2948
- return path6.relative(this.#workspaceRoot, this.pathOf(app));
2949
- }
2950
- async open() {
2951
- const stamp = dayjs(this.#now()).format("YYYY-MM-DD HH:mm:ss");
2952
- for (const app of this.#appNames) {
2953
- const file = this.pathOf(app);
2954
- await mkdir(path6.dirname(file), { recursive: true });
2955
- await rename(file, this.previousPathOf(app)).catch(() => {
2956
- return;
2957
- });
2958
- this.#writers.set(app, Bun.file(file).writer({ highWaterMark: DevSessionLog.bufferBytes }));
2959
- this.#writeLine(app, `\u2500\u2500 akan start \xB7 ${app} \xB7 ${stamp} \u2500\u2500`);
2960
- }
2961
- }
2962
- write(app, kind, chunk) {
2963
- const key = `${app}:${kind}`;
2964
- const parts = `${this.#partial.get(key) ?? ""}${chunk}`.split(`
2965
- `);
2966
- this.#partial.set(key, parts.pop() ?? "");
2967
- for (const line of parts)
2968
- this.#writeLine(app, stripAnsi(line));
2969
- }
2970
- note(text) {
2971
- for (const app of this.#appNames)
2972
- this.#writeLine(app, `[akan] ${text}`);
2973
- }
2974
- status(statuses) {
2975
- for (const status of statuses) {
2976
- if (this.#lastState.get(status.name) === status.state)
2977
- continue;
2978
- this.#lastState.set(status.name, status.state);
2979
- const detail = status.detail ? ` (${status.detail})` : "";
2980
- const where = status.state === "ready" ? ` \u2014 ${status.url}` : "";
2981
- this.#writeLine(status.name, `[akan] ${status.name} ${status.state}${detail}${where}`);
2982
- }
2983
- }
2984
- async close() {
2985
- for (const [key, remainder] of this.#partial) {
2986
- if (!remainder)
2987
- continue;
2988
- this.#writeLine(key.slice(0, key.lastIndexOf(":")), stripAnsi(remainder));
2679
+ return new VerifyScope(targets);
2989
2680
  }
2990
- this.#partial.clear();
2991
- if (this.#flushTimer)
2992
- clearTimeout(this.#flushTimer);
2993
- this.#flushTimer = null;
2994
- await Promise.all([...this.#writers.values()].map(async (writer) => await writer.end()));
2995
- this.#writers.clear();
2681
+ const targets = known.map((target) => ({ ...target, files: changedFilesOf(target.dir) })).filter((target) => target.files.length > 0);
2682
+ return new VerifyScope(targets);
2996
2683
  }
2997
- #runtimeDirOf(app) {
2998
- return path6.join(this.#workspaceRoot, "local", "apps", app, "runtime");
2999
- }
3000
- #writeLine(app, text) {
3001
- const writer = this.#writers.get(app);
3002
- if (!writer)
3003
- return;
3004
- writer.write(`${text}
3005
- `);
3006
- this.#scheduleFlush();
3007
- }
3008
- #scheduleFlush() {
3009
- if (this.#flushTimer)
3010
- return;
3011
- this.#flushTimer = setTimeout(() => {
3012
- this.#flushTimer = null;
3013
- for (const writer of this.#writers.values())
3014
- writer.flush();
3015
- }, DevSessionLog.flushMs);
3016
- }
3017
- }
3018
-
3019
- // pkgs/@akanjs/cli/application/devSupervisor.ts
3020
- class DevSupervisor {
3021
- static resolveDevUi(plain, {
3022
- isTty = !!process.stdout.isTTY,
3023
- columns = process.stdout.columns ?? 0
3024
- } = {}) {
3025
- if (plain)
3026
- return { mode: "stream", downgraded: false };
3027
- if (!isTty || columns <= 0)
3028
- return { mode: "stream", downgraded: true };
3029
- return { mode: "tui", downgraded: false };
3030
- }
3031
- static supervisedEnvKey = "AKAN_DEV_SUPERVISED";
3032
- static childHooks() {
3033
- if (process.env[DevSupervisor.supervisedEnvKey] !== "1" || !process.send)
3034
- return {};
3035
- const send = process.send.bind(process);
3036
- return {
3037
- stdio: "pipe",
3038
- onDevEvent: (event) => {
3039
- try {
3040
- send(event);
3041
- } catch {}
3042
- }
3043
- };
3044
- }
3045
- static bootTimeoutMs = 180000;
3046
- static shutdownGraceMs = 12000;
3047
- #options;
3048
- #children = new Map;
3049
- #sessionLog;
3050
- #view = null;
3051
- #stopping = false;
3052
- constructor(options) {
3053
- this.#options = options;
3054
- this.#sessionLog = new DevSessionLog({
3055
- workspaceRoot: options.apps[0]?.workspace.workspaceRoot ?? process.cwd(),
3056
- apps: options.apps.map((app) => app.name)
3057
- });
3058
- }
3059
- get statuses() {
3060
- return [...this.#children.values()].map((child) => child.status);
3061
- }
3062
- get sessionLog() {
3063
- return this.#sessionLog;
3064
- }
3065
- async run(view) {
3066
- this.#view = view;
3067
- await this.#sessionLog.open();
3068
- const ports = await this.#assignPorts();
3069
- for (const app of this.#options.apps)
3070
- this.#children.set(app.name, this.#makeChild(app, ports.get(app.name) ?? 0));
3071
- this.#publishStatus();
3072
- const logPaths = this.#sessionLog.appNames.map((name) => this.#sessionLog.relativePathOf(name));
3073
- this.#note(`session log: ${logPaths.join(" \xB7 ")}`, "info");
3074
- const stopped = this.#installSignalHandlers();
3075
- this.#bootInOrder();
3076
- await Promise.race([view.waitForExit(), stopped]);
3077
- await this.stop();
3078
- view.close?.();
3079
- await this.#sessionLog.close();
3080
- }
3081
- async#assignPorts() {
3082
- const taken = new Set;
3083
- const ports = new Map;
3084
- for (const app of this.#options.apps) {
3085
- let port = await app.getDevPort();
3086
- while (taken.has(port))
3087
- port += 1;
3088
- taken.add(port);
3089
- ports.set(app.name, port);
3090
- }
3091
- return ports;
3092
- }
3093
- #makeChild(app, port) {
3094
- const { promise: booted, resolve: markBooted } = Promise.withResolvers();
3095
- return {
3096
- status: {
3097
- app,
3098
- name: app.name,
3099
- port,
3100
- url: `http://localhost:${port}`,
3101
- shareUrl: this.#options.shares?.get(app.name) ?? null,
3102
- state: "starting",
3103
- detail: "queued",
3104
- exitCode: null
3105
- },
3106
- proc: null,
3107
- booted,
3108
- markBooted,
3109
- opened: false
3110
- };
3111
- }
3112
- async#bootInOrder() {
3113
- const queue = [...this.#children.values()];
3114
- const plan = DevBootConcurrency.resolve(queue.length, this.#options.concurrency ?? null);
3115
- const concurrency = plan.concurrency;
3116
- if (queue.length > 1)
3117
- this.#note(DevBootConcurrency.describe(queue.length, plan), "info");
3118
- const waves = [];
3119
- for (let idx = 0;idx < queue.length; idx += concurrency)
3120
- waves.push(queue.slice(idx, idx + concurrency));
3121
- for (const wave of waves) {
3122
- if (this.#stopping)
3123
- return;
3124
- for (const child of wave)
3125
- this.#spawnChild(child);
3126
- this.#publishStatus();
3127
- await Promise.all(wave.map(async (child) => await this.#waitForBoot(child)));
3128
- }
3129
- }
3130
- async#waitForBoot(child) {
3131
- if (await DevSupervisor.timesOut(child.booted, DevSupervisor.bootTimeoutMs))
3132
- this.#note(`${child.status.name} has not finished booting after ${Math.round(DevSupervisor.bootTimeoutMs / 1000)}s; starting the next app anyway`, "warn");
3133
- }
3134
- static async timesOut(work, ms) {
3135
- let timer;
3136
- const expired = new Promise((resolve) => {
3137
- timer = setTimeout(() => resolve(true), ms);
3138
- });
3139
- try {
3140
- return await Promise.race([work.then(() => false), expired]);
3141
- } finally {
3142
- clearTimeout(timer);
3143
- }
3144
- }
3145
- static childArgs(name, { write = true } = {}) {
2684
+ static #knownTargets({ apps, libs, pkgs }) {
3146
2685
  return [
3147
- "start",
3148
- name,
3149
- "--plain",
3150
- "--dbup",
3151
- "false",
3152
- "--write",
3153
- String(write)
2686
+ ...apps.map((name) => ({ type: "app", name, dir: `apps/${name}`, files: [] })),
2687
+ ...libs.map((name) => ({ type: "lib", name, dir: `libs/${name}`, files: [] })),
2688
+ ...pkgs.map((name) => ({ type: "pkg", name, dir: `pkgs/${name}`, files: [] }))
3154
2689
  ];
3155
2690
  }
3156
- #spawnChild(child) {
3157
- const { app, name, port } = child.status;
3158
- const args = DevSupervisor.childArgs(name, { write: this.#options.write ?? true });
3159
- const proc = Bun.spawn([process.execPath, Bun.main, ...args], {
3160
- cwd: app.workspace.workspaceRoot,
3161
- env: {
3162
- ...process.env,
3163
- [DevSupervisor.supervisedEnvKey]: "1",
3164
- AKAN_PUBLIC_APP_NAME: name,
3165
- AKAN_DEV_PORT: String(port)
3166
- },
3167
- stdio: ["ignore", "pipe", "pipe"],
3168
- ipc: (message) => {
3169
- if (!message || typeof message !== "object")
3170
- return;
3171
- if ("booted" in message)
3172
- child.markBooted();
3173
- else if (typeof message.state === "string")
3174
- this.#applyChildEvent(child, message);
3175
- },
3176
- serialization: "advanced",
3177
- onExit: (_proc, exitCode, signalCode) => {
3178
- child.proc = null;
3179
- child.status.exitCode = exitCode;
3180
- if (this.#stopping)
3181
- return;
3182
- child.status.state = "stopped";
3183
- child.status.detail = signalCode ? `killed by ${signalCode}` : `exited with ${exitCode}`;
3184
- child.markBooted();
3185
- this.#publishStatus();
3186
- }
3187
- });
3188
- child.proc = proc;
3189
- child.status.state = "starting";
3190
- child.status.detail = `pid ${proc.pid}`;
3191
- this.#drain(proc.stdout, name, "stdout");
3192
- this.#drain(proc.stderr, name, "stderr");
3193
- }
3194
- #applyChildEvent(child, event) {
3195
- child.status.state = event.state;
3196
- child.status.detail = event.detail ?? "";
3197
- if (event.state === "ready") {
3198
- if (this.#options.open && !child.opened) {
3199
- child.opened = true;
3200
- openBrowser(child.status.url);
3201
- }
3202
- }
3203
- if (event.state === "failed")
3204
- child.markBooted();
3205
- this.#publishStatus();
3206
- }
3207
- async#drain(stream, name, kind) {
3208
- const decoder = new TextDecoder;
3209
- try {
3210
- for await (const chunk of stream) {
3211
- const text = decoder.decode(chunk, { stream: true });
3212
- if (!text)
3213
- continue;
3214
- this.#view?.onOutput(name, kind, text);
3215
- this.#sessionLog.write(name, kind, text);
3216
- }
3217
- } catch {}
3218
- }
3219
- #publishStatus() {
3220
- this.#view?.onStatus(this.statuses);
3221
- this.#sessionLog.status(this.statuses);
3222
- }
3223
- #note(text, level) {
3224
- this.#view?.onNote(text, level);
3225
- this.#sessionLog.note(text);
3226
- }
3227
- #installSignalHandlers() {
3228
- return new Promise((resolve) => {
3229
- let asked = false;
3230
- const onSignal = () => {
3231
- if (asked) {
3232
- this.#note("abandoning the wait; children may be left running", "warn");
3233
- process.exit(130);
3234
- }
3235
- asked = true;
3236
- resolve();
3237
- };
3238
- process.on("SIGINT", onSignal);
3239
- process.on("SIGTERM", onSignal);
3240
- });
3241
- }
3242
- async restart(name) {
3243
- const child = this.#children.get(name);
3244
- if (!child || this.#stopping)
3245
- return;
3246
- const running = child.proc;
3247
- if (running) {
3248
- running.kill("SIGTERM");
3249
- await running.exited;
3250
- }
3251
- child.status.state = "starting";
3252
- child.status.detail = "restarting";
3253
- child.status.exitCode = null;
3254
- this.#publishStatus();
3255
- this.#spawnChild(child);
3256
- this.#publishStatus();
3257
- }
3258
- async stop() {
3259
- if (this.#stopping)
3260
- return;
3261
- this.#stopping = true;
3262
- const running = [...this.#children.values()].filter((child) => Boolean(child.proc));
3263
- for (const child of running)
3264
- child.proc.kill("SIGTERM");
3265
- const exited = Promise.all(running.map(async (child) => await child.proc.exited));
3266
- if (!await DevSupervisor.timesOut(exited, DevSupervisor.shutdownGraceMs))
3267
- return;
3268
- for (const child of running) {
3269
- if (child.proc.killed)
3270
- continue;
3271
- this.#note(`${child.status.name} did not exit in time; killing it`, "warn");
3272
- child.proc.kill("SIGKILL");
3273
- }
3274
- }
3275
- }
3276
-
3277
- // pkgs/@akanjs/cli/application/interruptTeardown.ts
3278
- import { Logger as Logger5 } from "akanjs/common";
3279
-
3280
- class InterruptTeardown {
3281
- #teardowns = [];
3282
- #exit;
3283
- #listen;
3284
- #report;
3285
- #interrupted = false;
3286
- #chain = Promise.resolve();
3287
- ownsExit = true;
3288
- constructor({ exit, listen, report } = {}) {
3289
- this.#exit = exit ?? ((code) => process.exit(code));
3290
- this.#listen = listen ?? ((onSignal) => {
3291
- process.on("SIGINT", onSignal);
3292
- });
3293
- this.#report = report ?? ((message) => Logger5.rawLog(message, undefined, "error"));
3294
- }
3295
- add(run, abandoned, exitCode = 0) {
3296
- this.#teardowns.push({ run, abandoned, exitCode, state: "pending" });
3297
- if (this.#teardowns.length === 1)
3298
- this.#listen(() => this.#onSignal());
3299
- }
3300
- async runAll() {
3301
- await this.#runTeardowns();
3302
- }
3303
- #onSignal() {
3304
- if (this.#interrupted) {
3305
- for (const one of this.#teardowns)
3306
- if (one.state !== "done")
3307
- this.#report(one.abandoned);
3308
- this.#exit(130);
3309
- return;
3310
- }
3311
- this.#interrupted = true;
3312
- this.#runTeardowns().finally(() => {
3313
- if (this.ownsExit)
3314
- this.#exit(Math.max(0, ...this.#teardowns.map((one) => one.exitCode)));
3315
- });
3316
- }
3317
- async#runTeardowns() {
3318
- this.#chain = this.#chain.then(async () => {
3319
- for (const one of this.#teardowns.toReversed()) {
3320
- if (one.state !== "pending")
3321
- continue;
3322
- one.state = "running";
3323
- await one.run().catch(() => {
3324
- return;
3325
- });
3326
- one.state = "done";
3327
- }
3328
- });
3329
- await this.#chain;
3330
- }
3331
- }
3332
-
3333
- // pkgs/@akanjs/cli/application/application.script.ts
3334
- class ApplicationScript extends script("application", [ApplicationRunner, LibraryScript]) {
3335
- static dbShutdownTimeoutMs = 20000;
3336
- static devServerReadyTimeoutMs = DevSupervisor.bootTimeoutMs;
3337
- #interrupt = new InterruptTeardown;
3338
- async confirmDatabaseModeDependencyInstall(databaseMode, installSpecs) {
3339
- assertPromptable(`Database mode '${databaseMode}' requires missing dependencies: ${installSpecs.join(", ")}`, {
3340
- remedy: `install them first with \`bun add ${installSpecs.join(" ")}\``
3341
- });
3342
- return await confirm({
3343
- message: `Database mode '${databaseMode}' requires missing dependencies: ${installSpecs.join(", ")}. Install them now?`,
3344
- default: true
3345
- });
3346
- }
3347
- async syncDatabaseModeDependencies(app, akanConfig, databaseMode) {
3348
- const installSpecs = akanConfig.getMissingDatabaseModeDependencySpecs(databaseMode);
3349
- if (installSpecs.length === 0)
3350
- return;
3351
- const shouldInstall = await this.confirmDatabaseModeDependencyInstall(databaseMode, installSpecs);
3352
- if (!shouldInstall)
3353
- throw new Error(`Database mode '${databaseMode}' requires missing dependencies: ${installSpecs.join(", ")}.`);
3354
- await this.#addDependencies(app, installSpecs, `database dependencies for ${databaseMode} mode`);
3355
- }
3356
- async#addDependencies(app, installSpecs, what) {
3357
- const spinner = app.workspace.spinning(`Installing ${what}...`);
3358
- try {
3359
- await app.workspace.spawn("bun", ["add", ...installSpecs], { stdio: "inherit" });
3360
- await app.workspace.getPackageJson({ refresh: true });
3361
- spinner.succeed(`Installed ${what}`);
3362
- } catch (error) {
3363
- spinner.fail(`Failed to install ${what}`);
3364
- throw error;
3365
- }
3366
- }
3367
- async createApplication(appName, workspace, { start = false, libs = [], sample = false } = {}) {
3368
- const spinner = workspace.spinning("Creating application...");
3369
- const app = await this.applicationRunner.createApplication(appName, workspace, libs, { sample });
3370
- spinner.succeed(`Application created in apps/${app.name}`);
3371
- await app.scanSync();
3372
- if (start)
3373
- await this.startOne(app, { open: true });
3374
- }
3375
- async removeApplication(app) {
3376
- const spinner = app.spinning("Removing application...");
3377
- await this.applicationRunner.removeApplication(app);
3378
- spinner.succeed(`Application ${app.name} (apps/${app.name}) removed`);
3379
- }
3380
- async planSlice(app, format = "text") {
3381
- const spinner = app.spinning("Planning distributable slice...");
3382
- const plan = await this.applicationRunner.planSlice(app);
3383
- spinner.succeed(`Slice planned (${plan.libs.length} libs, ${plan.warnings.length} warnings)`);
3384
- Logger6.rawLog(format === "json" ? JSON.stringify(plan, null, 2) : formatSlicePlan(plan));
3385
- }
3386
- async sync(sys) {
3387
- if (sys.type === "app")
3388
- await sys.scanSync();
3389
- else
3390
- await this.libraryScript.syncLibrary(sys);
3391
- }
3392
- async script(app, filename) {
3393
- const scriptFilename = filename ?? await this.applicationRunner.getScriptFilename(app);
3394
- await app.scanSync();
3395
- await this.applicationRunner.runScript(app, scriptFilename);
3396
- }
3397
- async console(app) {
3398
- await app.scanSync();
3399
- await this.applicationRunner.runConsole(app);
3400
- }
3401
- async migrate(app, argv) {
3402
- await app.scanSync();
3403
- await this.applicationRunner.migrate(app, argv);
3404
- }
3405
- async createMigration(app, migrationName) {
3406
- const migrationId = await this.applicationRunner.createMigration(app, migrationName);
3407
- Logger6.rawLog(`Created apps/${app.name}/script/migration/${migrationId}.ts; plan it with \`akan migrate ${app.name} plan ${migrationId}\``);
3408
- }
3409
- async logs(app, options) {
3410
- await this.applicationRunner.runLogs(app, options);
3411
- }
3412
- async build(app, {
3413
- write = true,
3414
- fast = false,
3415
- quiet = false,
3416
- profile
3417
- } = {}) {
3418
- await app.scanSync({ write });
3419
- if (!quiet)
3420
- Logger6.rawLog(`Creating an optimized production build for ${app.name}...`);
3421
- try {
3422
- const result = await this.applicationRunner.build(app, { fast, spinner: !quiet, envProfile: profile });
3423
- Logger6.rawLog(`${app.name} built in dist/apps/${app.name}`);
3424
- if (!quiet)
3425
- ApplicationBuildReporter.printSummary(result);
3426
- } catch (error) {
3427
- Logger6.rawLog(`${app.name} build failed in dist/apps/${app.name}`, undefined, "error");
3428
- Logger6.rawLog(ApplicationBuildReporter.formatError(error), undefined, "error");
3429
- markCliErrorPrinted(error);
3430
- throw error;
3431
- }
3432
- }
3433
- async typecheck(exec, { write = true, clean = false, incremental = true, tests = false } = {}) {
3434
- if (!(exec instanceof AppExecutor) && !(exec instanceof LibExecutor))
3435
- throw new Error(`akan typecheck takes an app or a library; ${exec.name} is a package, checked by its own tsconfig.`);
3436
- if (exec instanceof AppExecutor)
3437
- await exec.scanSync({ write });
3438
- else if (write)
3439
- await this.libraryScript.syncLibrary(exec);
3440
- else
3441
- await exec.scan({ write: false });
3442
- const spinner = exec.spinning(`Typechecking ${exec.name}${tests ? " with its tests" : ""}...`);
3443
- try {
3444
- if (exec instanceof LibExecutor)
3445
- await this.applicationRunner.typecheckLibrary(exec, { clean, incremental, tests });
3446
- else
3447
- await this.applicationRunner.typecheck(exec, { clean, incremental, tests });
3448
- spinner.succeed(`${exec.name} typechecked`);
3449
- } catch (error) {
3450
- spinner.fail(`${exec.name} typecheck failed`);
3451
- Logger6.rawLog(ApplicationBuildReporter.formatError(error), undefined, "error");
3452
- markCliErrorPrinted(error);
3453
- throw error;
3454
- }
3455
- }
3456
- async test(exec, { write = true, files = [] } = {}) {
3457
- const testPaths = this.applicationRunner.resolveTestPaths(exec, files);
3458
- if (exec instanceof LibExecutor) {
3459
- if (write)
3460
- await this.libraryScript.syncLibrary(exec);
3461
- else
3462
- await exec.scan({ write: false });
3463
- exec.spinning(`Preparing ${exec.name}...`).succeed(`${exec.name} prepared`);
3464
- await this.applicationRunner.test(exec, testPaths);
3465
- return;
3466
- }
3467
- const spinner = exec.spinning(`Preparing ${exec.name}...`);
3468
- try {
3469
- if (exec instanceof PkgExecutor)
3470
- await exec.scan({ refresh: true });
3471
- else
3472
- await exec.scanSync({ write });
3473
- spinner.succeed(`${exec.name} prepared`);
3474
- } catch (error) {
3475
- spinner.fail(`${exec.name} prepare failed`);
3476
- throw error;
3477
- }
3478
- await this.applicationRunner.test(exec, testPaths);
3479
- }
3480
- async start(apps, {
3481
- open = false,
3482
- dbup = true,
3483
- write = true,
3484
- plain = false,
3485
- kill = false,
3486
- share = false,
3487
- concurrency = null
3488
- } = {}) {
3489
- const first = apps[0];
3490
- if (!first)
3491
- throw new Error("No app selected to start");
3492
- const { mode, downgraded } = DevSupervisor.resolveDevUi(plain);
3493
- if (downgraded)
3494
- first.workspace.log("no sized terminal to draw on; printing prefixed lines instead");
3495
- if (kill)
3496
- await this.reclaimDevPorts(apps);
3497
- const shares = share ? await this.#shareOnInterrupt(apps) : null;
3498
- if (mode === "stream" && apps.length === 1)
3499
- return await this.startOne(first, { open, dbup, write, ...DevSupervisor.childHooks() });
3500
- this.#interrupt.ownsExit = false;
3501
- await this.#startMany(apps, { open, dbup, write, mode, concurrency, shares });
3502
- }
3503
- async startOne(app, { open = false, dbup = true, stdio = "inherit", write = true, onDevEvent } = {}) {
3504
- await app.scanSync({ write });
3505
- const akanConfig = await app.getConfig();
3506
- const databaseMode = akanConfig.resolveDatabaseMode();
3507
- await this.syncDatabaseModeDependencies(app, akanConfig, databaseMode);
3508
- if (app.getEnv() === "local" && dbup && databaseMode !== "single") {
3509
- const wasDbAlreadyUp = await this.dbup(app.workspace, databaseMode);
3510
- if (!wasDbAlreadyUp)
3511
- this.#stopDatabaseOnInterrupt(app.workspace);
3512
- }
3513
- const spinner = app.spinning("Preparing backend...");
3514
- return await this.applicationRunner.start(app, {
3515
- open,
3516
- onStart: () => spinner.succeed(`${app.name} prepared, ready to start`),
3517
- onDevEvent,
3518
- stdio
3519
- });
3520
- }
3521
- async reclaimDevPorts(apps) {
3522
- const workspace = apps[0]?.workspace;
3523
- if (!workspace)
3524
- return;
3525
- const ports = await Promise.all(apps.map(async (app) => await app.getDevPort()));
3526
- const { killed, foreign } = await new DevPortReclaimer().reclaim(ports);
3527
- for (const holder of killed)
3528
- workspace.log(`freed port ${holder.port} \u2014 killed pid ${holder.pid} (${holder.command})`);
3529
- for (const holder of foreign)
3530
- Logger6.rawLog(`port ${holder.port} is held by pid ${holder.pid} and was left alone: ${holder.command}`, undefined, "error");
3531
- if (killed.length === 0 && foreign.length === 0)
3532
- workspace.log("dev ports are free; nothing to kill");
3533
- }
3534
- async#startMany(apps, {
3535
- open,
3536
- dbup,
3537
- write,
3538
- mode,
3539
- concurrency,
3540
- shares
3541
- }) {
3542
- const workspace = apps[0]?.workspace;
3543
- if (!workspace)
3544
- throw new Error("No app selected to start");
3545
- const startedDatabase = dbup ? await this.#prepareSharedDatabase(apps) : false;
3546
- const supervisor = new DevSupervisor({ apps, mode, concurrency, open, write, shares });
3547
- const view = mode === "tui" ? new (await import("./devTui-q7k7bakd.js")).DevTui(supervisor) : new DevStreamView(apps.map((app) => app.name));
3548
- await supervisor.run(view);
3549
- if (startedDatabase)
3550
- await this.#stopDatabase(workspace);
3551
- }
3552
- async#prepareSharedDatabase(apps) {
3553
- const workspace = apps[0]?.workspace;
3554
- if (!workspace)
3555
- return false;
3556
- const modes = new Set;
3557
- for (const app of apps) {
3558
- if (app.getEnv() !== "local")
3559
- continue;
3560
- const akanConfig = await app.getConfig();
3561
- const mode = akanConfig.resolveDatabaseMode();
3562
- await this.syncDatabaseModeDependencies(app, akanConfig, mode);
3563
- if (mode !== "single")
3564
- modes.add(mode);
3565
- }
3566
- let started = false;
3567
- for (const mode of modes)
3568
- if (!await this.dbup(workspace, mode))
3569
- started = true;
3570
- return started;
3571
- }
3572
- async buildIos(app, { write = true, ...options } = {}) {
3573
- await app.scanSync({ write });
3574
- await this.applicationRunner.buildMobile(app, "ios", options);
3575
- }
3576
- async buildAndroid(app, { write = true, ...options } = {}) {
3577
- await app.scanSync({ write });
3578
- await this.applicationRunner.buildMobile(app, "android", options);
3579
- }
3580
- async buildDesktop(app, { write = true, ...options } = {}) {
3581
- await app.scanSync({ write });
3582
- await this.applicationRunner.buildDesktop(app, options);
3583
- }
3584
- async startIos(app, { write = true, ...options } = {}) {
3585
- await app.scanSync({ write });
3586
- await this.applicationRunner.startMobile(app, "ios", options);
3587
- }
3588
- async startAndroid(app, { write = true, ...options } = {}) {
3589
- await app.scanSync({ write });
3590
- await this.applicationRunner.startMobile(app, "android", options);
3591
- }
3592
- async startDesktop(app, { write = true, ...options } = {}) {
3593
- await app.scanSync({ write });
3594
- if (options.operation === "release")
3595
- return await this.applicationRunner.startDesktop(app, options);
3596
- const mobileTarget = await ApplicationRunner.startTarget(app, undefined, options.target);
3597
- if (!ApplicationRunner.carriesServer(mobileTarget))
3598
- return await this.applicationRunner.startDesktop(app, options);
3599
- DesktopServerStage.assertCarriable(await app.getConfig());
3600
- const upstream = `http://localhost:${await app.getDevPort()}`;
3601
- try {
3602
- if (await ApplicationRunner.answers(upstream, app.name, app.workspace.workspaceRoot))
3603
- app.log(`The desktop app follows the dev server on ${upstream}.`);
3604
- else
3605
- await this.#startDevServerFor(app, upstream);
3606
- await this.applicationRunner.startDesktop(app, { ...options, interrupt: this.#interrupt });
3607
- } finally {
3608
- await this.#interrupt.runAll();
3609
- }
3610
- }
3611
- async#startDevServerFor(app, upstream) {
3612
- app.log(`No dev server answers on ${upstream}; starting \`akan start ${app.name}\` for the desktop app.`);
3613
- let settle = () => {};
3614
- const settled = new Promise((resolve) => settle = resolve);
3615
- const appHost = await this.startOne(app, {
3616
- write: false,
3617
- onDevEvent: (event) => {
3618
- if ("state" in event && (event.state === "ready" || event.state === "failed"))
3619
- settle(event.state);
3620
- }
3621
- });
3622
- this.#interrupt.add(async () => {
3623
- await appHost.stop();
3624
- }, "Abandoning the dev server shutdown; its processes may still be running.", 130);
3625
- let state;
3626
- const timedOut = await DevSupervisor.timesOut(settled.then((settledState) => state = settledState), ApplicationScript.devServerReadyTimeoutMs);
3627
- if (state === "ready")
3628
- return;
3629
- await this.#interrupt.runAll();
3630
- throw new Error(timedOut ? `akan start ${app.name} did not answer within ${ApplicationScript.devServerReadyTimeoutMs / 1000}s; see its log above.` : `akan start ${app.name} gave up restarting its server; see its log above.`);
3631
- }
3632
- async releaseIos(app, {
3633
- write = true,
3634
- allowLocalRelease = false,
3635
- ...options
3636
- } = {}) {
3637
- await app.scanSync({ write });
3638
- ApplicationScript.#assertReleaseEnv("releaseIos", options.env ?? "main", allowLocalRelease);
3639
- await this.applicationRunner.releaseIos(app, options);
3640
- }
3641
- async releaseAndroid(app, format, {
3642
- write = true,
3643
- allowLocalRelease = false,
3644
- ...options
3645
- } = {}) {
3646
- await app.scanSync({ write });
3647
- ApplicationScript.#assertReleaseEnv("releaseAndroid", options.env ?? "main", allowLocalRelease);
3648
- await this.applicationRunner.releaseAndroid(app, format, options);
3649
- }
3650
- async packUpdate(app, platform, {
3651
- write = true,
3652
- allowLocalRelease = false,
3653
- ...options
3654
- } = {}) {
3655
- await app.scanSync({ write });
3656
- ApplicationScript.#assertReleaseEnv("packUpdate", options.env ?? "main", allowLocalRelease);
3657
- return await this.applicationRunner.packUpdate(app, platform, options);
3658
- }
3659
- async updateKeygen(app, platform, { target } = {}) {
3660
- await this.applicationRunner.updateKeygen(app, platform, target);
3661
- }
3662
- async publishUpdate(app, platform, {
3663
- write = true,
3664
- allowLocalRelease = false,
3665
- ...options
3666
- } = {}) {
3667
- await app.scanSync({ write });
3668
- ApplicationScript.#assertReleaseEnv("publishUpdate", options.env ?? "main", allowLocalRelease);
3669
- await this.applicationRunner.publishUpdate(app, platform, options);
3670
- }
3671
- static #assertReleaseEnv(command, env, allowLocalRelease) {
3672
- if (env === "local" && !allowLocalRelease)
3673
- throw new Error(`${command} --env local is blocked. Pass allowLocalRelease only for explicit local release testing.`);
3674
- }
3675
- async transferDatabase(app, direction, dir) {
3676
- await this.applicationRunner.transferDatabase(app, direction, dir);
3677
- }
3678
- async dbupDeclared(workspace, mode) {
3679
- const declared = mode ? [mode] : await Promise.all((await workspace.getApps()).map(async (appName) => (await AppExecutor.from(workspace, appName).getConfig()).database.modes)).then((modes) => [...new Set(modes.flat())]);
3680
- const needing = declared.filter((each) => each !== "single");
3681
- if (!needing.length) {
3682
- workspace.log("No app here declares a database mode that runs on local services; single needs none.");
3683
- return;
3684
- }
3685
- for (const each of needing)
3686
- await this.dbup(workspace, each);
3687
- }
3688
- async dbup(workspace, mode = "multiple") {
3689
- const spinner = workspace.spinning(`Starting local database (${mode})...`);
3690
- const wasAlreadyUp = await this.applicationRunner.dbup(workspace, mode);
3691
- spinner.succeed(wasAlreadyUp ? `Local database (${mode}) was already up` : `Local database (${mode}) is up`);
3692
- return wasAlreadyUp;
3693
- }
3694
- async dbdown(workspace) {
3695
- const spinner = workspace.spinning("Stopping local database...");
3696
- try {
3697
- await this.applicationRunner.dbdown(workspace);
3698
- } catch (error) {
3699
- spinner.fail("Local database failed to stop");
3700
- throw error;
3701
- }
3702
- spinner.succeed("Local database (/local/docker-compose.yaml) is down");
3703
- }
3704
- async#shareOnInterrupt(apps) {
3705
- const shares = [];
3706
- const urls = new Map;
3707
- this.#interrupt.add(async () => {
3708
- await Promise.all(shares.map(async (share) => await share.close()));
3709
- }, "Abandoning the tunnel release; the shares expire on their own.");
3710
- await Promise.all(apps.map(async (app) => {
3711
- const { TunnelShare } = await import("./TunnelShare-qkm8zp03.js");
3712
- const share = await TunnelShare.open(app, { workspace: app.workspace });
3713
- shares.push(share);
3714
- urls.set(app.name, share.url);
3715
- Logger6.rawLog(`${app.name} is shared at ${share.url}`);
3716
- })).catch((error) => {
3717
- Logger6.rawLog(`Could not open the tunnel: ${toError2(error).message}`, undefined, "error");
3718
- });
3719
- return urls;
3720
- }
3721
- #stopDatabaseOnInterrupt(workspace) {
3722
- this.#interrupt.add(async () => {
3723
- await this.#stopDatabase(workspace);
3724
- }, "Abandoning the local database teardown; containers are left running.");
3725
- }
3726
- async#stopDatabase(workspace) {
3727
- const stopped = this.dbdown(workspace).catch(() => {
3728
- return;
3729
- });
3730
- if (!await DevSupervisor.timesOut(stopped, ApplicationScript.dbShutdownTimeoutMs))
3731
- return;
3732
- Logger6.rawLog(`Local database did not stop within ${ApplicationScript.dbShutdownTimeoutMs}ms; run \`akan dbdown\` once Docker responds.`, undefined, "error");
2691
+ static async#git(cwd, args) {
2692
+ const proc = Bun.spawn(["git", ...args], { cwd, stdout: "pipe", stderr: "ignore" });
2693
+ const [text, exitCode] = await Promise.all([new Response(proc.stdout).text(), proc.exited]);
2694
+ return exitCode === 0 ? text : null;
3733
2695
  }
3734
2696
  }
3735
2697
 
3736
- export { ApplicationScript };
2698
+ export { ApplicationRunner, VerifyScope };