@akanjs/cli 3.1.1-rc.9 → 3.1.1

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 (184) hide show
  1. package/.build-stamp +1 -1
  2. package/CodeAgent-35wnb7w5.js +9 -0
  3. package/{CodeTui-z5vkm9ea.js → CodeTui-h6yz2kvq.js} +1 -1
  4. package/TunnelShare-xyjpa7gx.js +14 -0
  5. package/agent.command-3r4jsck8.js +46 -0
  6. package/akanCode.js +10 -6
  7. package/{application.command-wthg8nn9.js → application.command-g7xv6ad0.js} +44 -11
  8. package/{applicationBuildRunner-t2r84sz6.js → applicationBuildRunner-qvjnhr9j.js} +9 -6
  9. package/buildBatch.proc.js +6 -6
  10. package/{cloud.command-sz11hpre.js → cloud.command-6ebygmhw.js} +17 -15
  11. package/cloud.script-0s1jybd5.js +26 -0
  12. package/{code.command-9h3yrzhe.js → code.command-mpkm2emr.js} +6 -6
  13. package/commandManifest.json +1 -1
  14. package/{context.command-15j9b7c0.js → context.command-svdh6b2w.js} +18 -17
  15. package/context.runner-ch0z3a8g.js +26 -0
  16. package/{devTui-q7k7bakd.js → devTui-evr3b35y.js} +1 -1
  17. package/{guideline.command-snh85ctf.js → guideline.command-qwp3tnjx.js} +3 -3
  18. package/guidelines/conventions/core.md +106 -0
  19. package/guidelines/conventions/rules/app.md +83 -0
  20. package/guidelines/conventions/rules/auth.md +45 -0
  21. package/guidelines/conventions/rules/config.md +56 -0
  22. package/guidelines/conventions/rules/constant.md +24 -0
  23. package/guidelines/conventions/rules/gates.md +31 -0
  24. package/guidelines/conventions/rules/layer.md +25 -0
  25. package/guidelines/conventions/rules/migration.md +27 -0
  26. package/guidelines/conventions/rules/module.md +90 -0
  27. package/guidelines/conventions/rules/page.md +56 -0
  28. package/guidelines/conventions/rules/sensitive.md +16 -0
  29. package/guidelines/conventions/rules/server.md +86 -0
  30. package/guidelines/conventions/rules/ssr.md +47 -0
  31. package/guidelines/conventions/rules/style.md +43 -0
  32. package/guidelines/conventions/rules/test.md +34 -0
  33. package/guidelines/conventions/rules/ts.md +95 -0
  34. package/guidelines/conventions/rules/tsx.md +75 -0
  35. package/guidelines/mcpRule/mcpRule.instruction.md +1 -1
  36. package/guidelines/pageRule/pageRule.instruction.md +4 -3
  37. package/guidelines/queryRule/queryRule.instruction.md +4 -0
  38. package/guidelines/workspaceRecipes/workspaceRecipes.instruction.md +3 -3
  39. package/incrementalBuilder.proc.js +6 -6
  40. package/{index-pcwzkdqb.js → index-1p0qbq3m.js} +1 -1
  41. package/{index-xb8809yb.js → index-1shvxzt0.js} +3 -3
  42. package/{index-a58emady.js → index-266dewjs.js} +11 -11
  43. package/{index-bt438yxm.js → index-3yz30c07.js} +5 -4
  44. package/{index-xjf5j657.js → index-4mj92tsh.js} +952 -47
  45. package/index-4pdts00b.js +1604 -0
  46. package/{index-42j4a8zq.js → index-8559hsz4.js} +4 -3
  47. package/{index-wcej7g4z.js → index-8scw1pjk.js} +93 -23
  48. package/{index-a5dhqkdr.js → index-96wzdhfh.js} +74 -233
  49. package/index-9bv479q5.js +1 -0
  50. package/index-9rvcs76p.js +653 -0
  51. package/index-am36s3jh.js +3582 -0
  52. package/index-b8c289dx.js +444 -0
  53. package/{index-espk51ah.js → index-dd44g6vz.js} +3 -3
  54. package/{index-3wypz6xj.js → index-eja64h28.js} +7 -3
  55. package/index-fbewhg4g.js +590 -0
  56. package/index-jje9qzyq.js +27 -0
  57. package/{index-j9vyj3dj.js → index-k5jbcxyh.js} +3 -3
  58. package/{index-2mwc0g0d.js → index-ksfgqq1x.js} +1 -1
  59. package/index-m5n3ka0p.js +18 -0
  60. package/{index-5nd1wtkv.js → index-p6x5b7hr.js} +1 -1
  61. package/{index-6txx6a9p.js → index-payhwt51.js} +21 -29
  62. package/{index-2azahjaw.js → index-qkkdhjm6.js} +2 -2
  63. package/{index-74tjjsnc.js → index-qxzrp5xt.js} +33 -37
  64. package/{index-qfp55x1y.js → index-r0k3ham2.js} +4 -4
  65. package/{index-hmt54t45.js → index-r2w2eh93.js} +4 -4
  66. package/index-r2wedvqn.js +138 -0
  67. package/{index-skk9zc1x.js → index-rnphv731.js} +2 -2
  68. package/{index-9th4gszy.js → index-s6da8ta9.js} +82 -1227
  69. package/index-tenw3mah.js +225 -0
  70. package/{index-31es1yev.js → index-tgt2fnd6.js} +107 -6
  71. package/{index-55j120r8.js → index-vxmy1p4f.js} +16 -36
  72. package/{index-301pdbzz.js → index-w4k2ragk.js} +7 -7
  73. package/{index-js6geqjn.js → index-w7q6h97v.js} +1 -1
  74. package/{index-dy0jx9ay.js → index-wwe9rsrx.js} +14 -0
  75. package/{index-2xcc2ax5.js → index-xq543a5y.js} +2 -2
  76. package/{index-0fz95kxe.js → index-xqgwjz7a.js} +1 -1
  77. package/{index-40brg4px.js → index-xxfy1jp2.js} +4 -4
  78. package/{index-905qdgqp.js → index-z4b84y6k.js} +1 -1
  79. package/index-zcf6k8a5.js +410 -0
  80. package/index.js +23 -22
  81. package/{library.command-gycrwhf1.js → library.command-2853y6mk.js} +3 -3
  82. package/{localRegistry.command-jtd8gaes.js → localRegistry.command-76ds31p4.js} +19 -15
  83. package/{module.command-v6hgs1bc.js → module.command-yfnb0abs.js} +5 -5
  84. package/{package.command-shzpcfph.js → package.command-d9s86hp9.js} +3 -3
  85. package/package.json +2 -2
  86. package/{page.command-ptxn5kqk.js → page.command-6a8a8rd1.js} +3 -3
  87. package/{pipeline.command-zz31pgax.js → pipeline.command-rt3rwd2z.js} +2 -2
  88. package/{primitive.command-a1vse91z.js → primitive.command-emcebgrq.js} +6 -6
  89. package/{projectTypecheck-2ztky9cf.js → projectTypecheck-51m7eh1f.js} +1 -1
  90. package/{prompter-76k56b37.js → prompter-hgcta8pb.js} +1 -1
  91. package/quality.command-xtrk0n3x.js +76 -0
  92. package/{repair.command-cvazbz99.js → repair.command-51szxnxx.js} +5 -5
  93. package/{routeSourceValidator-6jd0q6r6.js → routeSourceValidator-4h947v7c.js} +13 -3
  94. package/{scalar.command-0acvyp26.js → scalar.command-8qv27t82.js} +4 -4
  95. package/skills/akan-agent/SKILL.md +36 -0
  96. package/skills/akan-code/SKILL.md +1 -0
  97. package/skills/akan-debug/SKILL.md +40 -6
  98. package/skills/akan-deps/SKILL.md +1 -2
  99. package/skills/akan-mcp/SKILL.md +40 -0
  100. package/skills/akan-page/SKILL.md +44 -0
  101. package/skills/akan-query/SKILL.md +38 -0
  102. package/skills/akan-runtime/SKILL.md +40 -0
  103. package/skills/akan-scaffold/SKILL.md +16 -6
  104. package/skills/akan-transport/SKILL.md +40 -0
  105. package/skills/akan-validate/SKILL.md +13 -11
  106. package/{subspace.command-822qx2bx.js → subspace.command-pn56pnh8.js} +8 -8
  107. package/templates/__scalar/__model__/__model__.constant.ts +3 -5
  108. package/templates/__scalar/__model__/__model__.dictionary.ts +6 -5
  109. package/templates/__scalar/__model__/__model__.document.ts +3 -3
  110. package/templates/app/akan.config.ts +2 -3
  111. package/templates/app/env/env.client.ts +2 -4
  112. package/templates/app/env/env.client.type.ts +2 -3
  113. package/templates/app/env/env.server.ts +2 -3
  114. package/templates/app/lib/___appName__/__appName__.dictionary.ts +1 -2
  115. package/templates/app/lib/___appName__/__appName__.service.ts +3 -3
  116. package/templates/app/lib/___appName__/__appName__.signal.ts +5 -5
  117. package/templates/app/lib/___appName__/__appName__.store.ts +4 -6
  118. package/templates/app/lib/option.ts +2 -3
  119. package/templates/app/main.ts +2 -4
  120. package/templates/app/page/_index.tsx +3 -3
  121. package/templates/app/page/_layout.tsx +13 -10
  122. package/templates/appSample/lib/__scalar/workHistory/workHistory.constant.ts +1 -5
  123. package/templates/appSample/lib/__scalar/workHistory/workHistory.dictionary.ts +1 -1
  124. package/templates/appSample/lib/_noti/noti.signal.ts +1 -1
  125. package/templates/appSample/lib/task/Task.Template.tsx +2 -1
  126. package/templates/appSample/lib/task/Task.Unit.tsx +3 -2
  127. package/templates/appSample/lib/task/Task.Util.tsx +16 -4
  128. package/templates/appSample/lib/task/task.constant.ts +1 -5
  129. package/templates/appSample/lib/task/task.dictionary.ts +2 -8
  130. package/templates/appSample/lib/task/task.document.ts +1 -1
  131. package/templates/appSample/page/task/_index.tsx +2 -1
  132. package/templates/appSample/page/task/new.tsx +2 -1
  133. package/templates/appSample/ui/QuantityControl.tsx +5 -9
  134. package/templates/biomeForm.ts +144 -0
  135. package/templates/crudPages/[__model__Id]/edit/page.tsx +3 -3
  136. package/templates/crudPages/[__model__Id]/page.tsx +5 -5
  137. package/templates/crudPages/new/page.tsx +4 -3
  138. package/templates/crudPages/page.tsx +3 -3
  139. package/templates/crudSinglePage/page.tsx +9 -5
  140. package/templates/libRoot/akan.config.ts +2 -3
  141. package/templates/libRoot/lib/___libName__/__libName__.dictionary.ts +1 -2
  142. package/templates/libRoot/lib/___libName__/__libName__.service.ts +5 -4
  143. package/templates/libRoot/lib/___libName__/__libName__.signal.ts +6 -5
  144. package/templates/libRoot/lib/___libName__/__libName__.store.ts +5 -6
  145. package/templates/libRoot/lib/option.ts +1 -2
  146. package/templates/module/__Model__.Template.tsx +11 -10
  147. package/templates/module/__Model__.Unit.tsx +18 -5
  148. package/templates/module/__Model__.Util.tsx +9 -7
  149. package/templates/module/__Model__.View.tsx +9 -6
  150. package/templates/module/__Model__.Zone.tsx +25 -17
  151. package/templates/module/__model__.constant.ts +8 -9
  152. package/templates/module/__model__.dictionary.ts +16 -17
  153. package/templates/module/__model__.document.ts +6 -8
  154. package/templates/module/__model__.service.ts +3 -3
  155. package/templates/module/__model__.signal.ts +11 -10
  156. package/templates/module/__model__.store.ts +3 -5
  157. package/templates/service/__model__.dictionary.ts +6 -5
  158. package/templates/service/__model__.service.ts +3 -3
  159. package/templates/service/__model__.signal.ts +5 -4
  160. package/templates/service/__model__.store.ts +3 -5
  161. package/templates/workspaceRoot/.gitignore.template +3 -0
  162. package/templates/workspaceRoot/.vscode/settings.json.template +21 -21
  163. package/templates/workspaceRoot/AGENTS.md.template +4 -10
  164. package/{tunnel.command-ycmja19q.js → tunnel.command-q2h0j2en.js} +7 -7
  165. package/{typeChecker-px49mezc.js → typeChecker-j2jdnqsr.js} +1 -1
  166. package/typecheck.proc.js +6 -1
  167. package/verify.command-z1dsbmrt.js +91 -0
  168. package/{workflow.command-abb1d5xy.js → workflow.command-r3y67jeq.js} +47 -13
  169. package/workspace.command-t2f0xsrw.js +263 -0
  170. package/CodeAgent-8d5qs787.js +0 -9
  171. package/TunnelShare-qkm8zp03.js +0 -14
  172. package/agent.command-ydftceda.js +0 -25
  173. package/cloud.script-nqevg5qw.js +0 -24
  174. package/context.runner-8gg030b0.js +0 -25
  175. package/guidelines/conventions/conventions.instruction.md +0 -617
  176. package/guidelines/workspaceOnboarding/workspaceOnboarding.instruction.md +0 -291
  177. package/index-4vgbysa0.js +0 -279
  178. package/index-7md2g9vw.js +0 -6
  179. package/index-b70zct19.js +0 -856
  180. package/index-zzvvc845.js +0 -74
  181. package/quality.command-ah8qcakd.js +0 -1478
  182. package/templates/workspaceRoot/docs/AI-DEVELOPMENT.md.template +0 -69
  183. package/templates/workspaceRoot/docs/GENERATED.md.template +0 -55
  184. package/workspace.command-qm7cw29v.js +0 -521
@@ -1,6 +1,14 @@
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-8scw1pjk.js";
11
+ import {
4
12
  UNAVAILABLE_REDIS_HOST,
5
13
  redisTunnelPolicy,
6
14
  BUILDER_MIN_RSS_RECYCLE_INTERVAL_MS,
@@ -35,53 +43,32 @@ import {
35
43
  filesChangedSince,
36
44
  HmrWatcher,
37
45
  WatchRootResolver
38
- } from "./index-5nd1wtkv.js";
46
+ } from "./index-p6x5b7hr.js";
39
47
  import {
40
48
  runner,
41
- script,
42
- markCliErrorPrinted,
49
+ ExitCodeError,
43
50
  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";
51
+ } from "./index-eja64h28.js";
54
52
  import {
55
53
  UpdatePackFolder,
56
54
  UpdateUploader,
57
55
  NativePublicEnv,
58
56
  NativeApp
59
- } from "./index-bt438yxm.js";
57
+ } from "./index-3yz30c07.js";
60
58
  import {
61
59
  DesktopServerStage
62
- } from "./index-js6geqjn.js";
60
+ } from "./index-w7q6h97v.js";
63
61
  import {
64
62
  resolveMobileTargets,
65
63
  resolveAppId
66
64
  } from "./index-m9jj544v.js";
67
65
  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";
66
+ SlicePlanner
67
+ } from "./index-1p0qbq3m.js";
77
68
  import {
78
69
  openBrowser
79
70
  } from "./index-9dp031by.js";
80
71
 
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";
84
-
85
72
  // pkgs/@akanjs/cli/application/application.runner.ts
86
73
  import { existsSync, realpathSync } from "fs";
87
74
  import path5 from "path";
@@ -1271,6 +1258,11 @@ ${this.#backendStderrTail.join(`
1271
1258
  static async readProcessRssBytes(pid) {
1272
1259
  if (process.platform === "win32")
1273
1260
  return await AkanAppHost.#readRssKbVia(["tasklist", "/FI", `PID eq ${pid}`, "/FO", "CSV", "/NH"], AkanAppHost.#tasklistRssKb);
1261
+ if (process.platform === "darwin") {
1262
+ const footprintBytes = await AkanAppHost.#readRssKbVia(["footprint", "-p", String(pid), "-f", "bytes"], AkanAppHost.#footprintKb);
1263
+ if (footprintBytes !== null)
1264
+ return footprintBytes;
1265
+ }
1274
1266
  const status = await Bun.file(`/proc/${pid}/status`).text().catch(() => null);
1275
1267
  const vmRssKb = status === null ? null : /VmRSS:\s+(\d+) kB/.exec(status)?.[1];
1276
1268
  if (vmRssKb)
@@ -1300,6 +1292,10 @@ ${this.#backendStderrTail.join(`
1300
1292
  const memUsage = /"([^"]*)"\s*$/m.exec(output)?.[1];
1301
1293
  return memUsage ? Number(memUsage.replace(/\D/g, "")) : Number.NaN;
1302
1294
  }
1295
+ static #footprintKb(output) {
1296
+ const bytes = /Footprint: (\d+) B\b/.exec(output)?.[1];
1297
+ return bytes ? Number(bytes) / 1024 : Number.NaN;
1298
+ }
1303
1299
  #cancelRssRecycle() {
1304
1300
  this.#rssRecycleReason = null;
1305
1301
  this.#rssRecycleOver = null;
@@ -1900,7 +1896,7 @@ ${uniqueCandidates.map((candidate) => ` - ${candidate}`).join(`
1900
1896
 
1901
1897
  // pkgs/@akanjs/cli/application/application.runner.ts
1902
1898
  import { Logger as Logger3, toError } from "akanjs/common";
1903
- var loadBuildRunner = async () => (await import("./applicationBuildRunner-t2r84sz6.js")).ApplicationBuildRunner;
1899
+ var loadBuildRunner = async () => (await import("./applicationBuildRunner-qvjnhr9j.js")).ApplicationBuildRunner;
1904
1900
  var loadPrompts = async () => await import("@inquirer/prompts");
1905
1901
 
1906
1902
  class ApplicationRunner extends runner("application") {
@@ -1951,13 +1947,13 @@ class ApplicationRunner extends runner("application") {
1951
1947
  stdio: "inherit"
1952
1948
  });
1953
1949
  }
1954
- #runtimeDirOf(app, override) {
1950
+ static runtimeDirOf(app, override) {
1955
1951
  return path5.resolve(override ?? process.env.AKAN_RUNTIME_DIR ?? path5.join(app.workspace.workspaceRoot, "local", "apps", app.name, "runtime"));
1956
1952
  }
1957
1953
  async runLogs(app, options) {
1958
1954
  const { LogControlUnavailableError, LogTailClient } = await import("akanjs/server/logging/logTailClient");
1959
1955
  const { LogQueryMatcher } = await import("akanjs/server/logging/logQuery");
1960
- const runtimeDir = this.#runtimeDirOf(app, options.runtimeDir);
1956
+ const runtimeDir = ApplicationRunner.runtimeDirOf(app, options.runtimeDir);
1961
1957
  const socketPath = LogTailClient.socketPath(runtimeDir);
1962
1958
  const { level, grep, endpoint, trace, child, role, origin, since } = options;
1963
1959
  const query = Object.fromEntries(Object.entries({ level, grep, endpoint, trace, child, role, origin, since }).filter(([, value]) => value !== undefined && value !== null && value !== ""));
@@ -2010,7 +2006,7 @@ class ApplicationRunner extends runner("application") {
2010
2006
  const serverPath = `${app.cwdPath}/server.ts`;
2011
2007
  if (!await app.exists("server.ts"))
2012
2008
  throw new Error(`Server file not found: apps/${app.name}/server.ts`);
2013
- const runtimeDir = this.#runtimeDirOf(app);
2009
+ const runtimeDir = ApplicationRunner.runtimeDirOf(app);
2014
2010
  const code = `
2015
2011
  const serverModule = await import(${JSON.stringify(serverPath)});
2016
2012
  const { assertAkanConsoleAllowed, startAkanConsole } = await import("akanjs/server");
@@ -2101,7 +2097,7 @@ if (loaded) process.exitCode = await loaded.migrations.command(loaded.server, ar
2101
2097
  await new (await loadBuildRunner())(app).typecheck(options);
2102
2098
  }
2103
2099
  async typecheckLibrary(lib, options = {}) {
2104
- const { ProjectTypecheck } = await import("./projectTypecheck-2ztky9cf.js");
2100
+ const { ProjectTypecheck } = await import("./projectTypecheck-51m7eh1f.js");
2105
2101
  const root = lib.workspace.workspaceRoot;
2106
2102
  await new ProjectTypecheck(lib.cwdPath, root, { ...process.env, AKAN_WORKSPACE_ROOT: root }).run([
2107
2103
  "../../server.ts",
@@ -2525,1212 +2521,71 @@ ${detail}`
2525
2521
  }
2526
2522
  }
2527
2523
 
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
- ];
2524
+ // pkgs/@akanjs/cli/verify/verifyScope.ts
2525
+ class VerifyScope {
2526
+ targets;
2527
+ constructor(targets) {
2528
+ this.targets = targets;
2551
2529
  }
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;
2530
+ get touchesTsx() {
2531
+ return this.targets.some((target) => target.files.some((file) => file.endsWith(".tsx")));
2564
2532
  }
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;
2533
+ get changedFiles() {
2534
+ return new Set(this.targets.flatMap((target) => target.files));
2573
2535
  }
2574
- static parentPidOf(child, parent) {
2575
- if (child.ppid !== parent.pid)
2536
+ static async changesIn(workspaceRoot) {
2537
+ const prefix = await VerifyScope.#git(workspaceRoot, ["rev-parse", "--show-prefix"]);
2538
+ if (prefix === null)
2576
2539
  return null;
2577
- if (parent.startedAt !== null && child.startedAt !== null && parent.startedAt > child.startedAt)
2540
+ const status = await VerifyScope.#git(workspaceRoot, ["status", "--porcelain=v1", "-z", "--untracked-files=all"]);
2541
+ if (status === null)
2578
2542
  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)
2543
+ return VerifyScope.parseStatus(status, prefix.trim());
2544
+ }
2545
+ static parseStatus(status, prefix = "") {
2546
+ const tokens = status.split("\x00");
2547
+ const changes = [];
2548
+ for (let idx = 0;idx < tokens.length; idx++) {
2549
+ const token = tokens[idx] ?? "";
2550
+ if (token.length < 4)
2586
2551
  continue;
2587
- const [, local, remote] = fields;
2588
- if (!local?.endsWith(`:${port}`) || !remote?.endsWith(":0"))
2552
+ const code = token.slice(0, 2);
2553
+ const file = token.slice(3);
2554
+ if (code.includes("R") || code.includes("C"))
2555
+ idx++;
2556
+ if (!file.startsWith(prefix))
2589
2557
  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")
2624
- 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)
2558
+ changes.push({ code, file: file.slice(prefix.length) });
2559
+ }
2560
+ return changes;
2561
+ }
2562
+ static resolve(changes, names, requested = []) {
2563
+ const known = VerifyScope.#knownTargets(names);
2564
+ const changedFilesOf = (dir) => changes.filter((change) => change.file.startsWith(`${dir}/`)).map((change) => change.file);
2565
+ if (requested.length) {
2566
+ const targets = requested.map((name) => {
2567
+ const target = known.find((candidate) => candidate.name === name);
2568
+ if (!target)
2569
+ throw new ExitCodeError(`${name} is not an app, library or package of this workspace`, 2);
2570
+ return { ...target, files: changedFilesOf(target.dir) };
2630
2571
  });
2572
+ return new VerifyScope(targets);
2631
2573
  }
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))
2674
- 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);
2679
- });
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));
2989
- }
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();
2996
- }
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
- }
2574
+ const targets = known.map((target) => ({ ...target, files: changedFilesOf(target.dir) })).filter((target) => target.files.length > 0);
2575
+ return new VerifyScope(targets);
3144
2576
  }
3145
- static childArgs(name, { write = true } = {}) {
2577
+ static #knownTargets({ apps, libs, pkgs }) {
3146
2578
  return [
3147
- "start",
3148
- name,
3149
- "--plain",
3150
- "--dbup",
3151
- "false",
3152
- "--write",
3153
- String(write)
2579
+ ...apps.map((name) => ({ type: "app", name, dir: `apps/${name}`, files: [] })),
2580
+ ...libs.map((name) => ({ type: "lib", name, dir: `libs/${name}`, files: [] })),
2581
+ ...pkgs.map((name) => ({ type: "pkg", name, dir: `pkgs/${name}`, files: [] }))
3154
2582
  ];
3155
2583
  }
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");
2584
+ static async#git(cwd, args) {
2585
+ const proc = Bun.spawn(["git", ...args], { cwd, stdout: "pipe", stderr: "ignore" });
2586
+ const [text, exitCode] = await Promise.all([new Response(proc.stdout).text(), proc.exited]);
2587
+ return exitCode === 0 ? text : null;
3733
2588
  }
3734
2589
  }
3735
2590
 
3736
- export { ApplicationScript };
2591
+ export { ApplicationRunner, VerifyScope };