@akanjs/cli 3.1.2-rc.4 → 3.2.0-rc.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 (120) hide show
  1. package/.build-stamp +1 -1
  2. package/{CodeAgent-z34p8m91.js → CodeAgent-vmd9k4ak.js} +3 -3
  3. package/{CodeTui-nvd9fk3g.js → CodeTui-zka44v52.js} +1 -1
  4. package/README.ko.md +9 -0
  5. package/README.md +9 -0
  6. package/TunnelShare-k3ja4w9x.js +14 -0
  7. package/{agent.command-962mp3kg.js → agent.command-2f657613.js} +19 -17
  8. package/akanCode.js +6 -6
  9. package/{application.command-1nr0bqq1.js → application.command-q6skd3am.js} +36 -22
  10. package/{applicationBuildRunner-xy7hnfzq.js → applicationBuildRunner-sctcmkyx.js} +55 -16
  11. package/buildBatch.proc.js +7 -7
  12. package/{cloud.command-cj7b3m6y.js → cloud.command-7642pks6.js} +36 -19
  13. package/cloud.script-1sfseznn.js +30 -0
  14. package/{code.command-asq7xrr6.js → code.command-7s4ndq2k.js} +6 -6
  15. package/commandManifest.json +1 -1
  16. package/{context.command-fw4g2pw1.js → context.command-569z0rqf.js} +20 -19
  17. package/context.runner-ms8v1rxy.js +29 -0
  18. package/{devTui-evr3b35y.js → devTui-w38ch13a.js} +1 -1
  19. package/{guideline.command-43gfjsjv.js → guideline.command-gnv3e8p8.js} +2 -2
  20. package/guidelines/akanApi/akanApi.instruction.md +317 -0
  21. package/guidelines/conventions/rules/app.md +5 -5
  22. package/guidelines/conventions/rules/config.md +1 -1
  23. package/guidelines/conventions/rules/gates.md +10 -5
  24. package/incrementalBuilder.proc.js +69 -39
  25. package/{index-0tkj05cz.js → index-0fb3cpbt.js} +3 -3
  26. package/{index-6t7fkx73.js → index-1q1cjn8s.js} +21 -11
  27. package/{index-tenw3mah.js → index-23860fej.js} +16 -6
  28. package/{index-6zgt7zmx.js → index-48d5qsj3.js} +4 -4
  29. package/{index-z47rw9ez.js → index-5w9my9qe.js} +8 -8
  30. package/{index-qwe079ww.js → index-6wpaq392.js} +61 -15
  31. package/{index-kc871vpc.js → index-7xdpww43.js} +69 -12
  32. package/index-7y5yghjg.js +2969 -0
  33. package/{index-38patcx6.js → index-8g7tdsk4.js} +249 -696
  34. package/{index-90q0w90q.js → index-8kczhnmv.js} +1 -1
  35. package/{index-kdswbvys.js → index-8pb9yvp8.js} +63 -21
  36. package/{index-hmj94es2.js → index-8ts9774g.js} +4 -4
  37. package/{index-r0q2ka2b.js → index-93ewzmp6.js} +43 -14
  38. package/{index-y0y0pnx8.js → index-9tbgb4d8.js} +1 -1
  39. package/{index-jzpeny42.js → index-a8a9ede9.js} +7 -7
  40. package/index-abgh0jve.js +126 -0
  41. package/{index-t0hk1kxq.js → index-aj3ehkcx.js} +1 -1
  42. package/{index-demt944k.js → index-d4n1wmrz.js} +37 -4
  43. package/{index-sra1a5f8.js → index-drz9e84d.js} +22 -8
  44. package/{index-gfh90r3t.js → index-e3vmjtph.js} +2 -2
  45. package/{index-k64mhwbw.js → index-eajbmk10.js} +2 -1
  46. package/{index-g0yds382.js → index-ed6ea0qp.js} +1 -1
  47. package/{index-ap6ac70m.js → index-fjr4d6yd.js} +444 -368
  48. package/index-hqrkqxx2.js +176 -0
  49. package/{index-ampz4vgv.js → index-kpdv34rq.js} +4 -4
  50. package/{index-kc6ffq0s.js → index-ktb3wcqz.js} +73 -34
  51. package/{index-dcm66hss.js → index-mmym5xmb.js} +4 -2
  52. package/{index-8d9r465x.js → index-mqntfzv5.js} +2 -2
  53. package/{index-4am4dvmf.js → index-ny2k80mv.js} +15 -3
  54. package/index-p6hjwt2d.js +1668 -0
  55. package/{index-53h0053j.js → index-rc5fvqj2.js} +12 -14
  56. package/{index-jzz6ye8x.js → index-s2grpzef.js} +40 -8
  57. package/{index-38by07nw.js → index-sr5da35e.js} +32 -9
  58. package/{index-qev8p5wp.js → index-sy481q2x.js} +1 -1
  59. package/{index-ck64kxrn.js → index-thckcabc.js} +2 -2
  60. package/{index-2yan1ajk.js → index-v4p1zye8.js} +18 -9
  61. package/{index-wymcdsas.js → index-vkzfk7qt.js} +25 -23
  62. package/{index-r8t5sq7z.js → index-vr68mxj5.js} +68 -21
  63. package/{index-vkpqe29t.js → index-w639tvkd.js} +24 -125
  64. package/index-ygdbn9jn.js +122 -0
  65. package/{index-w60zxxye.js → index-zpv14wpy.js} +3 -3
  66. package/index.js +24 -23
  67. package/{library.command-zh29tjdd.js → library.command-1gp5qe3r.js} +3 -3
  68. package/{localRegistry.command-k9pn9ahj.js → localRegistry.command-x7jptkd3.js} +26 -17
  69. package/{module.command-dgpqs9fz.js → module.command-4xz9he6h.js} +6 -6
  70. package/{package.command-1je4hsca.js → package.command-s7qpnn1g.js} +12 -3
  71. package/package.json +2 -2
  72. package/{page.command-cgsasanh.js → page.command-fan34c49.js} +3 -3
  73. package/{pipeline.command-tb46sa8v.js → pipeline.command-ph4fnn9w.js} +2 -2
  74. package/{primitive.command-bzsy23x5.js → primitive.command-3fqh8emf.js} +7 -7
  75. package/{projectTypecheck-h8rgaczy.js → projectTypecheck-vkb40hjc.js} +1 -1
  76. package/{quality.command-120m9h6v.js → quality.command-ecj6exsh.js} +15 -10
  77. package/{repair.command-6m4wd0qv.js → repair.command-fe9jw719.js} +6 -6
  78. package/{scalar.command-3dn5hsc6.js → scalar.command-cnvfhk0n.js} +5 -5
  79. package/skills/akan-debug/SKILL.md +2 -1
  80. package/skills/akan-page/SKILL.md +16 -7
  81. package/skills/akan-service/SKILL.md +48 -19
  82. package/{subspace.command-s8nyfqbn.js → subspace.command-qw5ddd6y.js} +8 -8
  83. package/templates/app/lib/___appName__/__appName__.abstract.md.template +6 -0
  84. package/templates/app/page/_index.tsx +4 -284
  85. package/templates/app/page/_layout.tsx +1 -26
  86. package/templates/app/page/styles.css.template +58 -318
  87. package/templates/appSample/page/_index.tsx +281 -0
  88. package/templates/appSample/page/_layout.tsx +55 -0
  89. package/templates/appSample/page/styles.css.template +327 -0
  90. package/templates/libRoot/lib/___libName__/__libName__.abstract.md.template +6 -0
  91. package/templates/workspaceRoot/package.json.template +1 -12
  92. package/{tunnel.command-8mwrqkr3.js → tunnel.command-ggj38mqf.js} +7 -7
  93. package/{verify.command-2pspfy7k.js → verify.command-w9ttxkdz.js} +16 -14
  94. package/{workflow.command-7sy5vnsj.js → workflow.command-ss8devj0.js} +12 -12
  95. package/{workspace.command-x518tdv4.js → workspace.command-6z2rh8ze.js} +51 -39
  96. package/TunnelShare-jwbb50kz.js +0 -14
  97. package/cloud.script-8kr7qgfa.js +0 -27
  98. package/context.runner-p6m5cxk3.js +0 -28
  99. package/index-d894868w.js +0 -842
  100. package/index-re2kfscb.js +0 -1363
  101. /package/templates/{app → appSample}/page/_overrides.tsx +0 -0
  102. /package/templates/{app → appSample}/public/fonts/Pretendard-Black.woff2 +0 -0
  103. /package/templates/{app → appSample}/public/fonts/Pretendard-Bold.woff2 +0 -0
  104. /package/templates/{app → appSample}/public/fonts/Pretendard-ExtraBold.woff2 +0 -0
  105. /package/templates/{app → appSample}/public/fonts/Pretendard-ExtraLight.woff2 +0 -0
  106. /package/templates/{app → appSample}/public/fonts/Pretendard-Light.woff2 +0 -0
  107. /package/templates/{app → appSample}/public/fonts/Pretendard-Medium.woff2 +0 -0
  108. /package/templates/{app → appSample}/public/fonts/Pretendard-Regular.woff2 +0 -0
  109. /package/templates/{app → appSample}/public/fonts/Pretendard-SemiBold.woff2 +0 -0
  110. /package/templates/{app → appSample}/public/fonts/Pretendard-Thin.woff2 +0 -0
  111. /package/templates/{app → appSample}/public/jelly/cloud.webp +0 -0
  112. /package/templates/{app → appSample}/public/jelly/comet.webp +0 -0
  113. /package/templates/{app → appSample}/public/jelly/moon.webp +0 -0
  114. /package/templates/{app → appSample}/public/jelly/planet.webp +0 -0
  115. /package/templates/{app → appSample}/public/jelly/rocket.webp +0 -0
  116. /package/templates/{app → appSample}/public/jelly/star.webp +0 -0
  117. /package/templates/{app → appSample}/public/jelly/sugar.webp +0 -0
  118. /package/templates/{app → appSample}/public/logo.png +0 -0
  119. /package/templates/{app → appSample}/ui/Recipe/index.ts +0 -0
  120. /package/templates/{app → appSample}/ui/Recipe/jellyButton.ts +0 -0
package/index-d894868w.js DELETED
@@ -1,842 +0,0 @@
1
- // @bun
2
- // pkgs/@akanjs/devkit/applicationBuildReporter.ts
3
- import { realpathSync } from "fs";
4
- import path from "path";
5
- import { Logger } from "akanjs/common";
6
-
7
- class ApplicationBuildReporter {
8
- static create() {
9
- return {
10
- phaseDone: (phase) => Logger.rawLog(ApplicationBuildReporter.formatPhaseLine(phase))
11
- };
12
- }
13
- static printSummary(result) {
14
- Logger.rawLog("");
15
- Logger.rawLog(`Route artifacts: ${result.artifactDir}`);
16
- Logger.rawLog(`Server output: ${result.outputDir}`);
17
- Logger.rawLog(`Done in ${ApplicationBuildReporter.formatDuration(result.durationMs)}`);
18
- if (result.environment === "local")
19
- Logger.rawLog(ApplicationBuildReporter.localBuildNotice);
20
- }
21
- static localBuildNotice = "Built for local, which serves the dev routes to every caller. For a host others can reach, build with AKAN_PUBLIC_ENV=main, AKAN_PUBLIC_REPO_NAME and AKAN_PUBLIC_SERVE_DOMAIN set.";
22
- static formatError(error, workspaceRoot = process.cwd()) {
23
- if (error instanceof AggregateError) {
24
- const nestedMessages = error.errors.map((nestedError, index) => ApplicationBuildReporter.formatError(nestedError, workspaceRoot).trim() || `Unknown error ${index + 1}`).map((message) => message.replace(/^/gm, " ")).join(`
25
- `);
26
- return nestedMessages ? `${error.message}
27
- ${nestedMessages}` : error.message;
28
- }
29
- if (error instanceof Error) {
30
- const causeMessage = error.cause ? `
31
- Caused by: ${ApplicationBuildReporter.formatError(error.cause, workspaceRoot)}` : "";
32
- return `${ApplicationBuildReporter.#withLocation(error.message, error, workspaceRoot)}${causeMessage}`;
33
- }
34
- if (typeof error === "object" && error !== null && "message" in error)
35
- return ApplicationBuildReporter.#withLocation(String(error.message), error, workspaceRoot);
36
- return String(error);
37
- }
38
- static #withLocation(message, error, workspaceRoot) {
39
- const { position } = error;
40
- if (!position?.file)
41
- return message;
42
- const file = ApplicationBuildReporter.#relativeToWorkspace(position.file, workspaceRoot);
43
- const location = position.line > 0 ? `${file}:${position.line}:${position.column}` : file;
44
- return message.includes(location) ? message : message.replace(/^.*/, (headline) => `${headline} (${location})`);
45
- }
46
- static #relativeToWorkspace(file, workspaceRoot) {
47
- if (!path.isAbsolute(file))
48
- return file;
49
- for (const root of [workspaceRoot, ApplicationBuildReporter.#realpathOf(workspaceRoot)]) {
50
- const relative = path.relative(root, file);
51
- if (!relative.startsWith(`..${path.sep}`) && !path.isAbsolute(relative))
52
- return relative.replaceAll(path.sep, "/");
53
- }
54
- return file;
55
- }
56
- static #realpathOf(dir) {
57
- try {
58
- return realpathSync(dir);
59
- } catch {
60
- return dir;
61
- }
62
- }
63
- static formatDuration(ms) {
64
- if (ms < 1000)
65
- return `${ms}ms`;
66
- if (ms < 60000)
67
- return `${Math.round(ms / 100) / 10}s`;
68
- const seconds = Math.floor(ms / 1000);
69
- return `${Math.floor(seconds / 60)}m ${seconds % 60}s`;
70
- }
71
- static formatPhaseLine(phase) {
72
- const summary = phase.summary ? `: ${phase.summary}` : "";
73
- return `\u2713 ${phase.label}${summary} (${ApplicationBuildReporter.formatDuration(phase.durationMs)})`;
74
- }
75
- }
76
-
77
- // pkgs/@akanjs/devkit/akanApp/devHostPolicy.ts
78
- import path2 from "path";
79
- var UNAVAILABLE_REDIS_HOST = "redis-tunnel-unavailable.invalid";
80
- var redisTunnelPolicy = ({
81
- environment,
82
- databaseMode
83
- }) => environment === "local" ? "none" : databaseMode === "single" ? "optional" : "required";
84
- var BACKEND_RECOVERY_MAX_ATTEMPTS = 5;
85
- var HELD_BUILDER_REQUEST_LIMIT = 64;
86
- var BUILDER_MIN_RSS_RECYCLE_INTERVAL_MS = 30000;
87
- var BUILDER_TIGHT_RSS_REPORT_LIMIT = 2;
88
- var BUILDER_RSS_HARD_MULTIPLE = 1.5;
89
- var DEV_IDLE_SUSPEND_MS = 300000;
90
- var DEV_IDLE_MIN_UPTIME_MS = 30000;
91
- var SOURCE_EXTS = new Set([".ts", ".tsx", ".js", ".jsx", ".mjs", ".cjs"]);
92
- var SERVER_SUFFIXES = [".service.ts", ".document.ts"];
93
- var SHARED_SUFFIXES = [".constant.ts", ".dictionary.ts", ".signal.ts"];
94
- var RUNTIME_METADATA_BASENAMES = new Set(["dict.ts", "sig.ts", "useClient.ts", "useServer.ts"]);
95
- var shouldRestartBackendByDevPlan = (message) => {
96
- if (!message.devPlan)
97
- return null;
98
- if (message.devPlan.actions.includes("report-error"))
99
- return false;
100
- if (message.devPlan.actions.includes("restart-builder"))
101
- return false;
102
- return message.devPlan.actions.includes("restart-backend");
103
- };
104
- var shouldRestartBuilderByDevPlan = (message) => message.devPlan?.actions.includes("restart-builder") ?? false;
105
- var shouldAbandonBackendRecovery = (attempts, maxAttempts = BACKEND_RECOVERY_MAX_ATTEMPTS) => attempts >= maxAttempts;
106
- var normalizeBackendReportedGeneration = (generation) => generation >= 0 ? generation : undefined;
107
- var shouldRestartDevHostByDevPlan = (message) => message.devPlan?.actions.includes("restart-dev-host") ?? message.kinds.includes("config");
108
- var devHostStateByBackendState = {
109
- starting: "starting",
110
- ready: "ready",
111
- "restart-pending": "restarting",
112
- recovering: "recovering",
113
- stopping: "stopped",
114
- stopped: "stopped"
115
- };
116
- var devHostStateOf = (state, gaveUp) => state === "stopped" && gaveUp ? "failed" : devHostStateByBackendState[state];
117
- var RESTART_ROLE_ORDER = ["server", "shared", "barrel", "config"];
118
- var generationValue = (generation) => generation ?? -1;
119
- var isLegacyBackendFallbackFile = (file, workspaceRoot) => {
120
- const abs = path2.resolve(file);
121
- const ext = path2.extname(abs).toLowerCase();
122
- if (!SOURCE_EXTS.has(ext))
123
- return false;
124
- const rel = path2.relative(path2.resolve(workspaceRoot), abs);
125
- if (!rel || rel.startsWith("..") || path2.isAbsolute(rel))
126
- return false;
127
- const parts = rel.split(path2.sep).filter(Boolean);
128
- const [scope] = parts;
129
- if (scope !== "apps" && scope !== "libs" && scope !== "pkgs")
130
- return false;
131
- const base = path2.basename(abs);
132
- return parts.includes("srvkit") || parts.includes("common") || SERVER_SUFFIXES.some((suffix) => base.endsWith(suffix)) || SHARED_SUFFIXES.some((suffix) => base.endsWith(suffix)) || RUNTIME_METADATA_BASENAMES.has(base) || base === "main.ts" || base === "server.ts";
133
- };
134
- var shouldMarkBuildPhaseRecovered = (previousByPhase, status) => {
135
- const previous = previousByPhase.get(status.phase);
136
- if (!previous || previous.ok || !status.ok)
137
- return false;
138
- const generation = generationValue(status.generation);
139
- if (status.phase === "route" && status.scope !== undefined && previous.scope !== undefined)
140
- return status.scope === previous.scope && generation >= previous.generation;
141
- if (generation !== previous.generation)
142
- return generation > previous.generation;
143
- return status.phase === "backend";
144
- };
145
- var shouldKeepBuildFailure = (previousByPhase, status) => status.ok && previousByPhase.get(status.phase)?.ok === false && !shouldMarkBuildPhaseRecovered(previousByPhase, status);
146
- var createBackendBuildStatus = ({
147
- generation,
148
- ok,
149
- files = [],
150
- message
151
- }) => ({
152
- generation,
153
- phase: "backend",
154
- ok,
155
- files,
156
- message
157
- });
158
- var backendRestartReasonFromMessage = (message) => {
159
- const roleSet = new Set;
160
- for (const role of message.devPlan?.roles ?? []) {
161
- if (role === "server" || role === "shared" || role === "barrel" || role === "config")
162
- roleSet.add(role);
163
- }
164
- return {
165
- generation: message.devPlan?.generation ?? message.generation,
166
- files: [...new Set(message.files)].sort(),
167
- roles: RESTART_ROLE_ORDER.filter((role) => roleSet.has(role))
168
- };
169
- };
170
- var mergeBackendRestartReasons = (current, next) => ({
171
- generation: generationValue(next.generation) >= generationValue(current?.generation) ? next.generation : current?.generation,
172
- files: [...new Set([...current?.files ?? [], ...next.files])].sort(),
173
- roles: RESTART_ROLE_ORDER.filter((role) => current?.roles.includes(role) || next.roles.includes(role))
174
- });
175
- var shouldReplaceLastGoodMessage = (current, next) => !current || generationValue(next.data.generation) >= generationValue(current.data.generation);
176
- var shouldQueueBuildStatusReplay = (backendReady, pendingReplayCount) => !backendReady || pendingReplayCount > 0;
177
- var hasBuildFailureForGeneration = (statusByPhase, generation) => {
178
- if (typeof generation !== "number")
179
- return false;
180
- for (const status of statusByPhase.values()) {
181
- if (!status.ok && status.phase !== "route" && status.generation === generation)
182
- return true;
183
- }
184
- return false;
185
- };
186
- var decideBuilderRssRecycle = ({
187
- rssBytes,
188
- ceilingBytes,
189
- buildFailed,
190
- msSinceLastRecycle,
191
- minIntervalMs = BUILDER_MIN_RSS_RECYCLE_INTERVAL_MS
192
- }) => {
193
- if (!ceilingBytes)
194
- return "unbounded";
195
- if (rssBytes < ceilingBytes)
196
- return "below-ceiling";
197
- if (buildFailed)
198
- return "build-failed";
199
- if (msSinceLastRecycle !== null && msSinceLastRecycle < minIntervalMs)
200
- return "too-soon";
201
- return "recycle";
202
- };
203
- var decideBuilderRssSettle = ({
204
- rssBytes,
205
- ceilingBytes,
206
- hardMultiple = BUILDER_RSS_HARD_MULTIPLE
207
- }) => rssBytes >= ceilingBytes * hardMultiple ? "recycle-now" : "wait-and-recheck";
208
- var decideIdleSuspend = ({
209
- enabled,
210
- suspended,
211
- builderReady,
212
- backendReady,
213
- buildFailed,
214
- restartPending,
215
- msSinceWake,
216
- minUptimeMs = DEV_IDLE_MIN_UPTIME_MS
217
- }) => {
218
- if (!enabled)
219
- return "disabled";
220
- if (suspended)
221
- return "already-suspended";
222
- if (!builderReady)
223
- return "builder-not-ready";
224
- if (!backendReady)
225
- return "backend-not-ready";
226
- if (buildFailed)
227
- return "build-failed";
228
- if (restartPending)
229
- return "restart-pending";
230
- if (msSinceWake !== null && msSinceWake < minUptimeMs)
231
- return "too-soon";
232
- return "suspend";
233
- };
234
- var resolveIdleSuspendMs = (raw) => {
235
- if (raw === undefined || raw === "")
236
- return DEV_IDLE_SUSPEND_MS;
237
- const parsed = Number(raw);
238
- if (!Number.isFinite(parsed) || parsed <= 0)
239
- return null;
240
- return Math.round(parsed);
241
- };
242
- var hasAnyBuildFailure = (statusByPhase) => [...statusByPhase.values()].some((status) => !status.ok && status.phase !== "route");
243
- var shouldRefreshConfigOnIdleWake = (batch) => !!batch && batch.kinds.has("config");
244
- var RETURNING_BUILDER_STATUSES = new Set(["starting", "recycling", "restarting"]);
245
- var shouldHoldForReturningBuilder = ({
246
- status,
247
- heldCount,
248
- limit = HELD_BUILDER_REQUEST_LIMIT
249
- }) => RETURNING_BUILDER_STATUSES.has(status) && heldCount < limit;
250
- var shouldWarnBuilderRssCeilingTight = (reportsSinceRecycle, limit = BUILDER_TIGHT_RSS_REPORT_LIMIT) => reportsSinceRecycle >= limit;
251
- var isRssCeilingUnreachable = (freshRssBytes, ceilingBytes) => freshRssBytes !== null && ceilingBytes !== null && freshRssBytes >= ceilingBytes;
252
- var shouldRelayRecycledFrontendState = (current, next) => {
253
- if (!current || current.type !== next.type)
254
- return true;
255
- if (current.type === "pages-updated" && next.type === "pages-updated")
256
- return current.data.bundlePath !== next.data.bundlePath;
257
- if (current.type === "css-updated" && next.type === "css-updated")
258
- return JSON.stringify(current.data.cssAssets) !== JSON.stringify(next.data.cssAssets);
259
- return true;
260
- };
261
- var mergeDevPlans = (current, next) => {
262
- if (!current)
263
- return next;
264
- if (!next)
265
- return current;
266
- const reasonByFile = { ...current.reasonByFile };
267
- for (const [file, reasons] of Object.entries(next.reasonByFile)) {
268
- reasonByFile[file] = [...new Set([...reasonByFile[file] ?? [], ...reasons])].sort();
269
- }
270
- return {
271
- generation: Math.max(current.generation, next.generation),
272
- files: [...new Set([...current.files, ...next.files])].sort(),
273
- generatedFiles: [...new Set([...current.generatedFiles, ...next.generatedFiles])].sort(),
274
- roles: [...new Set([...current.roles, ...next.roles])].sort(),
275
- actions: [...new Set([...current.actions, ...next.actions])].sort(),
276
- reasonByFile
277
- };
278
- };
279
- var mergeInvalidateMessages = (current, next) => {
280
- const generation = Math.max(generationValue(current.generation), generationValue(next.generation));
281
- return {
282
- type: "invalidate",
283
- kinds: [...new Set([...current.kinds, ...next.kinds])].sort(),
284
- files: [...new Set([...current.files, ...next.files])].sort(),
285
- generation: generation >= 0 ? generation : undefined,
286
- devPlan: mergeDevPlans(current.devPlan, next.devPlan)
287
- };
288
- };
289
- var buildStatusReplaySequence = (pendingReplay, latestByPhase) => [...pendingReplay, ...latestByPhase.values()];
290
- var filesChangedSince = (before, after) => [...before].filter(([file, stamp]) => after.get(file) !== stamp).map(([file]) => file);
291
-
292
- // pkgs/@akanjs/devkit/frontendBuild/watchRootResolver.ts
293
- import fs from "fs";
294
- import { readFile } from "fs/promises";
295
- import path3 from "path";
296
-
297
- class WatchRootResolver {
298
- #app;
299
- constructor(app) {
300
- this.#app = app;
301
- }
302
- async resolve() {
303
- const tsconfig = await this.#app.getTsConfig();
304
- const appDir = path3.resolve(this.#app.cwdPath);
305
- const appsContainer = path3.dirname(appDir);
306
- const libsContainer = path3.resolve(this.#app.workspace.workspaceRoot, "libs");
307
- const libRoots = (await this.#resolveLibDeps(libsContainer))?.map((name) => path3.join(libsContainer, name)).filter((dir) => fs.existsSync(dir));
308
- const set = new Set;
309
- set.add(path3.resolve(`${this.#app.cwdPath}/page`));
310
- for (const targets of Object.values(tsconfig.compilerOptions.paths ?? {})) {
311
- for (const target of targets) {
312
- if (!target)
313
- continue;
314
- if (path3.isAbsolute(target))
315
- continue;
316
- const cleaned = target.replace(/\/?\*+.*$/, "").replace(/\/[^/]+\.[^/]+$/, "");
317
- const resolved = path3.resolve(this.#app.workspace.workspaceRoot, cleaned);
318
- if (resolved === libsContainer && libRoots) {
319
- for (const root of libRoots)
320
- set.add(root);
321
- continue;
322
- }
323
- const root = resolved === appsContainer ? appDir : resolved;
324
- if (fs.existsSync(root))
325
- set.add(root);
326
- }
327
- }
328
- return [...set];
329
- }
330
- async#resolveLibDeps(libsContainer) {
331
- const scanInfo = this.#app.getScanInfo({ allowEmpty: true });
332
- if (scanInfo?.type === "app")
333
- return scanInfo.libDeps;
334
- const direct = await WatchRootResolver.#readManifestLibDeps(path3.join(this.#app.cwdPath, "akan.app.json"));
335
- if (!direct)
336
- return null;
337
- const closure = new Set;
338
- const queue = [...direct];
339
- while (queue.length > 0) {
340
- const name = queue.shift();
341
- if (!name || closure.has(name))
342
- continue;
343
- closure.add(name);
344
- const nested = await WatchRootResolver.#readManifestLibDeps(path3.join(libsContainer, name, "akan.lib.json"));
345
- if (!nested)
346
- return null;
347
- queue.push(...nested);
348
- }
349
- return [...closure];
350
- }
351
- static async#readManifestLibDeps(manifestPath) {
352
- try {
353
- const parsed = JSON.parse(await readFile(manifestPath, "utf8"));
354
- if (!Array.isArray(parsed.libDeps))
355
- return null;
356
- return parsed.libDeps.filter((name) => typeof name === "string" && name.length > 0);
357
- } catch {
358
- return null;
359
- }
360
- }
361
- }
362
-
363
- // pkgs/@akanjs/devkit/frontendBuild/hmrWatcher.ts
364
- import fs2 from "fs";
365
- import path6 from "path";
366
-
367
- // pkgs/@akanjs/devkit/frontendBuild/hmrChangeClassifier.ts
368
- import path4 from "path";
369
- var CSS_EXTS = new Set([".css"]);
370
- var CONFIG_BASENAMES = new Set(["akan.config.ts", "bunfig.toml", "tsconfig.json", "package.json"]);
371
-
372
- class HmrChangeClassifier {
373
- classify(abs) {
374
- if (this.#isUninteresting(abs))
375
- return "ignore";
376
- const base = path4.basename(abs);
377
- if (CONFIG_BASENAMES.has(base))
378
- return "config";
379
- const ext = path4.extname(abs).toLowerCase();
380
- if (CSS_EXTS.has(ext))
381
- return "css";
382
- if (SOURCE_EXTS.has(ext))
383
- return "code";
384
- return "ignore";
385
- }
386
- #isUninteresting(abs) {
387
- const base = path4.basename(abs);
388
- if (!base)
389
- return true;
390
- if (base.startsWith("."))
391
- return true;
392
- if (base.endsWith("~") || base.endsWith(".swp") || base.endsWith(".swx") || base.endsWith(".tmp"))
393
- return true;
394
- if (abs.includes(`${path4.sep}node_modules${path4.sep}`))
395
- return true;
396
- if (abs.includes(`${path4.sep}.akan${path4.sep}`))
397
- return true;
398
- return false;
399
- }
400
- }
401
-
402
- // pkgs/@akanjs/devkit/frontendBuild/sourceMtimeIndex.ts
403
- import { readdir, stat } from "fs/promises";
404
- import path5 from "path";
405
- var UNREADABLE = Number.NaN;
406
-
407
- class SourceMtimeIndex {
408
- static #defaultDirSettleMs = 20;
409
- #dirSettleMs;
410
- #roots;
411
- #classifier;
412
- #files = new Map;
413
- #dirs = new Map;
414
- #unreadable = new Map;
415
- #unsettled = new Set;
416
- #primed = false;
417
- #queue = Promise.resolve();
418
- constructor({ roots, classifier, dirSettleMs }) {
419
- this.#roots = SourceMtimeIndex.#pruneNestedRoots(roots);
420
- this.#classifier = classifier ?? new HmrChangeClassifier;
421
- this.#dirSettleMs = dirSettleMs ?? SourceMtimeIndex.#defaultDirSettleMs;
422
- }
423
- get primed() {
424
- return this.#primed;
425
- }
426
- get trackedFileCount() {
427
- return this.#files.size;
428
- }
429
- get coverageGaps() {
430
- return [...this.#unreadable].map(([file, code]) => ({ path: file, code }));
431
- }
432
- get hasUnsettledDirs() {
433
- return this.#unsettled.size > 0;
434
- }
435
- async prime() {
436
- await this.#serialize(async () => {
437
- this.#files.clear();
438
- this.#dirs.clear();
439
- this.#unreadable.clear();
440
- this.#unsettled.clear();
441
- await Promise.all(this.#roots.map((root) => this.#walk(root, null)));
442
- this.#primed = true;
443
- });
444
- }
445
- async collectChanges() {
446
- return this.#serialize(async () => {
447
- if (!this.#primed)
448
- return [];
449
- const changed = new Set;
450
- await this.#collectFileChanges(changed);
451
- await this.#collectDirChanges(changed);
452
- return [...changed];
453
- });
454
- }
455
- async#serialize(work) {
456
- const run = this.#queue.then(work, work);
457
- this.#queue = run.catch(() => {
458
- return;
459
- });
460
- return run;
461
- }
462
- async absorb(paths) {
463
- await this.#serialize(async () => {
464
- if (!this.#primed)
465
- return;
466
- await Promise.all(paths.map(async (file) => {
467
- const abs = path5.resolve(file);
468
- const stats = await stat(abs).catch(() => null);
469
- if (!stats?.isFile()) {
470
- this.#files.delete(abs);
471
- return;
472
- }
473
- this.#files.set(abs, { mtimeMs: stats.mtimeMs, size: stats.size });
474
- }));
475
- });
476
- }
477
- async#collectFileChanges(changed) {
478
- await Promise.all([...this.#files.keys()].map(async (abs) => {
479
- const { stats, err } = await SourceMtimeIndex.#statPath(abs);
480
- if (!stats) {
481
- if (err && !SourceMtimeIndex.#isMissing(err)) {
482
- this.#unreadable.set(abs, err.code ?? "EUNKNOWN");
483
- return;
484
- }
485
- this.#files.delete(abs);
486
- this.#unreadable.delete(abs);
487
- changed.add(abs);
488
- return;
489
- }
490
- this.#unreadable.delete(abs);
491
- if (!stats.isFile()) {
492
- this.#files.delete(abs);
493
- changed.add(abs);
494
- return;
495
- }
496
- const known = this.#files.get(abs);
497
- if (known && known.mtimeMs === stats.mtimeMs && known.size === stats.size)
498
- return;
499
- this.#files.set(abs, { mtimeMs: stats.mtimeMs, size: stats.size });
500
- changed.add(abs);
501
- }));
502
- }
503
- async#collectDirChanges(changed) {
504
- const moved = new Set;
505
- const gone = [];
506
- await Promise.all([...this.#dirs.entries()].map(async ([dir, mtimeMs]) => {
507
- const { stats, err } = await SourceMtimeIndex.#statPath(dir);
508
- if (!stats?.isDirectory()) {
509
- if (err && !SourceMtimeIndex.#isMissing(err)) {
510
- this.#markUnreadable(dir, err);
511
- return;
512
- }
513
- gone.push(dir);
514
- return;
515
- }
516
- if (stats.mtimeMs !== mtimeMs)
517
- moved.add(dir);
518
- }));
519
- for (const dir of this.#unsettled)
520
- if (this.#dirs.has(dir))
521
- moved.add(dir);
522
- for (const dir of gone)
523
- this.#forget(dir);
524
- for (const dir of moved)
525
- await this.#walk(dir, changed);
526
- }
527
- async#walk(dir, changed) {
528
- const [listing, dirStat] = await Promise.all([SourceMtimeIndex.#readdirPath(dir), SourceMtimeIndex.#statPath(dir)]);
529
- const entries = listing.entries;
530
- const dirStats = dirStat.stats;
531
- if (!entries || !dirStats?.isDirectory()) {
532
- const err = listing.err ?? dirStat.err;
533
- if (err && !SourceMtimeIndex.#isMissing(err)) {
534
- this.#markUnreadable(dir, err);
535
- return;
536
- }
537
- this.#forget(dir);
538
- return;
539
- }
540
- const known = this.#dirs.has(dir);
541
- this.#dirs.set(dir, dirStats.mtimeMs);
542
- this.#unreadable.delete(dir);
543
- if (this.#isUnsettled(dirStats.mtimeMs))
544
- this.#unsettled.add(dir);
545
- else
546
- this.#unsettled.delete(dir);
547
- const descend = [];
548
- const present = new Set;
549
- let blind = false;
550
- for (const entry of entries) {
551
- if (SourceMtimeIndex.#skipDirent(entry.name))
552
- continue;
553
- const abs = path5.join(dir, entry.name);
554
- if (entry.isDirectory()) {
555
- descend.push(abs);
556
- continue;
557
- }
558
- if (!entry.isFile())
559
- continue;
560
- if (this.#classifier.classify(abs) === "ignore")
561
- continue;
562
- present.add(abs);
563
- const { stats, err } = await SourceMtimeIndex.#statPath(abs);
564
- if (!stats?.isFile()) {
565
- if (err && !SourceMtimeIndex.#isMissing(err)) {
566
- this.#unreadable.set(abs, err.code ?? "EUNKNOWN");
567
- blind = true;
568
- }
569
- continue;
570
- }
571
- this.#unreadable.delete(abs);
572
- const previous = this.#files.get(abs);
573
- if (previous && previous.mtimeMs === stats.mtimeMs && previous.size === stats.size)
574
- continue;
575
- this.#files.set(abs, { mtimeMs: stats.mtimeMs, size: stats.size });
576
- changed?.add(abs);
577
- }
578
- if (known) {
579
- for (const abs of [...this.#files.keys()]) {
580
- if (present.has(abs) || path5.dirname(abs) !== dir)
581
- continue;
582
- this.#files.delete(abs);
583
- changed?.add(abs);
584
- }
585
- }
586
- if (blind) {
587
- this.#dirs.set(dir, UNREADABLE);
588
- this.#unsettled.delete(dir);
589
- }
590
- await Promise.all(descend.filter((sub) => !this.#dirs.has(sub)).map((sub) => this.#walk(sub, changed)));
591
- }
592
- #markUnreadable(dir, err) {
593
- this.#dirs.set(dir, UNREADABLE);
594
- this.#unreadable.set(dir, err.code ?? "EUNKNOWN");
595
- this.#unsettled.delete(dir);
596
- }
597
- #forget(dir) {
598
- const prefix = `${dir}${path5.sep}`;
599
- this.#dirs.delete(dir);
600
- this.#unreadable.delete(dir);
601
- this.#unsettled.delete(dir);
602
- for (const known of [...this.#dirs.keys()])
603
- if (known.startsWith(prefix))
604
- this.#dirs.delete(known);
605
- for (const known of [...this.#unreadable.keys()])
606
- if (known.startsWith(prefix))
607
- this.#unreadable.delete(known);
608
- for (const known of [...this.#unsettled])
609
- if (known.startsWith(prefix))
610
- this.#unsettled.delete(known);
611
- }
612
- #isUnsettled(mtimeMs) {
613
- return Math.abs(Date.now() - mtimeMs) < this.#dirSettleMs;
614
- }
615
- static async#statPath(abs) {
616
- try {
617
- return { stats: await stat(abs), err: null };
618
- } catch (err) {
619
- return { stats: null, err };
620
- }
621
- }
622
- static async#readdirPath(dir) {
623
- try {
624
- return { entries: await readdir(dir, { withFileTypes: true }), err: null };
625
- } catch (err) {
626
- return { entries: null, err };
627
- }
628
- }
629
- static #isMissing(err) {
630
- return err.code === "ENOENT" || err.code === "ENOTDIR";
631
- }
632
- static #skipDirent(name) {
633
- return !name || name.startsWith(".") || name === "node_modules";
634
- }
635
- static #pruneNestedRoots(roots) {
636
- const resolved = [...new Set(roots.map((root) => path5.resolve(root)))].sort();
637
- return resolved.filter((root) => !resolved.some((other) => other !== root && root.startsWith(`${other}${path5.sep}`)));
638
- }
639
- }
640
-
641
- // pkgs/@akanjs/devkit/frontendBuild/hmrWatcher.ts
642
- class HmrWatcher {
643
- #roots;
644
- #debounceMs;
645
- #verifyDelayMs;
646
- #onBatch;
647
- #logger;
648
- #watchers = [];
649
- #pending = new Map;
650
- #hinted = new Set;
651
- #classifier = new HmrChangeClassifier;
652
- #index;
653
- #timer = null;
654
- #verifyTimer = null;
655
- #windowStartedAt = null;
656
- #stopped = false;
657
- #flushing = false;
658
- #unreportedChanges = 0;
659
- #reportedCompensating = false;
660
- #reportedGaps = "";
661
- constructor(opts) {
662
- this.#roots = [...new Set(opts.roots.map((r) => path6.resolve(r)))];
663
- this.#debounceMs = opts.debounceMs ?? HmrWatcher.#envDebounceMs() ?? 30;
664
- this.#verifyDelayMs = opts.verifyDelayMs ?? 250;
665
- this.#onBatch = opts.onBatch;
666
- this.#logger = opts.logger;
667
- this.#index = new SourceMtimeIndex({ roots: this.#roots, classifier: this.#classifier });
668
- }
669
- get unreportedChanges() {
670
- return this.#unreportedChanges;
671
- }
672
- async start() {
673
- for (const root of this.#roots) {
674
- try {
675
- const w = fs2.watch(root, { recursive: true, persistent: false }, (_event, filename) => {
676
- if (!filename)
677
- return;
678
- const abs = path6.resolve(root, filename.toString());
679
- this.#queue(abs);
680
- });
681
- w.on("error", (err) => {
682
- if (err.code === "EACCES" || err.code === "EPERM")
683
- this.#logger.verbose(`[hmr] ${err.message}`);
684
- else
685
- this.#logger.warn(`[hmr] watcher error under ${root}: ${err.message}`);
686
- });
687
- this.#watchers.push(w);
688
- this.#logger.verbose(`[hmr] watching ${root}`);
689
- } catch (err) {
690
- this.#logger.error(`[hmr] failed to watch ${root}: ${err.message}`);
691
- }
692
- }
693
- try {
694
- await this.#index.prime();
695
- this.#reportCoverageGaps();
696
- this.#logger.verbose(`[hmr] tracking ${this.#index.trackedFileCount} source files for change verification`);
697
- } catch (err) {
698
- this.#logger.error(`[hmr] mtime index unavailable; falling back to watcher events alone, which drop concurrent saves: ${err.message}`);
699
- }
700
- }
701
- stop() {
702
- this.#stopped = true;
703
- if (this.#timer)
704
- clearTimeout(this.#timer);
705
- if (this.#verifyTimer)
706
- clearTimeout(this.#verifyTimer);
707
- for (const w of this.#watchers) {
708
- try {
709
- w.close();
710
- } catch {}
711
- }
712
- }
713
- async absorb(paths) {
714
- if (paths.length === 0)
715
- return;
716
- await this.#index.absorb(paths);
717
- }
718
- #queue(abs) {
719
- const kind = this.#classifier.classify(abs);
720
- if (!this.#index.primed) {
721
- if (kind === "ignore")
722
- return;
723
- this.#pending.set(abs, kind);
724
- this.#scheduleFlush();
725
- return;
726
- }
727
- if (kind === "ignore") {
728
- this.#scheduleVerify();
729
- return;
730
- }
731
- this.#hinted.add(abs);
732
- this.#scheduleFlush();
733
- }
734
- #scheduleFlush() {
735
- this.#windowStartedAt ??= Date.now();
736
- if (this.#flushing)
737
- return;
738
- if (this.#timer)
739
- clearTimeout(this.#timer);
740
- this.#timer = setTimeout(() => this.#flush(), this.#debounceMs);
741
- }
742
- #flush() {
743
- this.#timer = null;
744
- if (this.#stopped || this.#flushing)
745
- return;
746
- this.#drain();
747
- }
748
- async#drain() {
749
- this.#flushing = true;
750
- try {
751
- while (!this.#stopped) {
752
- await this.#mergeDetectedChanges();
753
- if (this.#pending.size === 0) {
754
- this.#windowStartedAt = null;
755
- break;
756
- }
757
- const files = Array.from(this.#pending.keys());
758
- const kinds = new Set(this.#pending.values());
759
- const flushAt = Date.now();
760
- const trace = { eventAt: this.#windowStartedAt ?? flushAt, flushAt };
761
- this.#windowStartedAt = null;
762
- this.#pending.clear();
763
- this.#hinted.clear();
764
- try {
765
- await this.#onBatch({ files, kinds, trace });
766
- } catch (e) {
767
- this.#logger.error(`[hmr] onBatch error: ${e.message}`);
768
- }
769
- }
770
- } finally {
771
- this.#flushing = false;
772
- if (!this.#stopped && this.#pending.size > 0)
773
- this.#timer = setTimeout(() => this.#flush(), this.#debounceMs);
774
- else
775
- this.#scheduleVerify();
776
- }
777
- }
778
- async#mergeDetectedChanges() {
779
- const detected = await this.#index.collectChanges().catch((err) => {
780
- this.#logger.error(`[hmr] mtime scan failed: ${err.message}`);
781
- return [];
782
- });
783
- this.#reportCoverageGaps();
784
- let unreported = 0;
785
- for (const abs of detected) {
786
- const kind = this.#classifier.classify(abs);
787
- if (kind === "ignore")
788
- continue;
789
- if (!this.#hinted.has(abs))
790
- unreported += 1;
791
- this.#pending.set(abs, kind);
792
- }
793
- if (unreported === 0)
794
- return;
795
- this.#unreportedChanges += unreported;
796
- if (!this.#reportedCompensating) {
797
- this.#reportedCompensating = true;
798
- this.#logger.verbose(`[hmr] recovered ${unreported} change(s) that fs.watch did not report; Bun coalesces concurrent saves and drops all but one, so changes are resolved by mtime`);
799
- }
800
- this.#logger.verbose(`[hmr] mtime scan found ${unreported} change(s) fs.watch never reported (${this.#unreportedChanges} total)`);
801
- }
802
- #reportCoverageGaps() {
803
- const gaps = this.#index.coverageGaps;
804
- const key = gaps.map((gap) => `${gap.code}:${gap.path}`).sort((a, b) => a < b ? -1 : a > b ? 1 : 0).join("|");
805
- if (key === this.#reportedGaps)
806
- return;
807
- this.#reportedGaps = key;
808
- if (gaps.length === 0) {
809
- this.#logger.info("[hmr] all watch roots readable again; change detection is complete");
810
- return;
811
- }
812
- const shown = gaps.slice(0, 3).map((gap) => `${gap.path} (${gap.code})`).join(", ");
813
- const rest = gaps.length > 3 ? ` and ${gaps.length - 3} more` : "";
814
- this.#logger.warn(`[hmr] cannot read ${gaps.length} path(s), so edits underneath them will not rebuild: ${shown}${rest}`);
815
- }
816
- static #envDebounceMs() {
817
- const raw = process.env.AKAN_DEV_WATCH_DEBOUNCE_MS;
818
- const ms = raw ? Number(raw) : Number.NaN;
819
- return Number.isInteger(ms) && ms >= 0 ? ms : null;
820
- }
821
- #scheduleVerify() {
822
- if (this.#stopped || this.#verifyDelayMs <= 0)
823
- return;
824
- if (this.#verifyTimer)
825
- clearTimeout(this.#verifyTimer);
826
- this.#verifyTimer = setTimeout(() => {
827
- this.#verifyTimer = null;
828
- this.#verify();
829
- }, this.#verifyDelayMs);
830
- }
831
- async#verify() {
832
- if (this.#stopped || this.#flushing)
833
- return;
834
- await this.#mergeDetectedChanges();
835
- if (this.#pending.size > 0)
836
- await this.#drain();
837
- else if (this.#index.hasUnsettledDirs)
838
- this.#scheduleVerify();
839
- }
840
- }
841
-
842
- export { UNAVAILABLE_REDIS_HOST, redisTunnelPolicy, BUILDER_MIN_RSS_RECYCLE_INTERVAL_MS, SOURCE_EXTS, shouldRestartBackendByDevPlan, shouldRestartBuilderByDevPlan, shouldAbandonBackendRecovery, normalizeBackendReportedGeneration, shouldRestartDevHostByDevPlan, devHostStateOf, isLegacyBackendFallbackFile, shouldMarkBuildPhaseRecovered, shouldKeepBuildFailure, createBackendBuildStatus, backendRestartReasonFromMessage, mergeBackendRestartReasons, shouldReplaceLastGoodMessage, shouldQueueBuildStatusReplay, hasBuildFailureForGeneration, decideBuilderRssRecycle, decideBuilderRssSettle, decideIdleSuspend, resolveIdleSuspendMs, hasAnyBuildFailure, shouldRefreshConfigOnIdleWake, shouldHoldForReturningBuilder, shouldWarnBuilderRssCeilingTight, isRssCeilingUnreachable, shouldRelayRecycledFrontendState, mergeInvalidateMessages, buildStatusReplaySequence, filesChangedSince, HmrWatcher, WatchRootResolver, ApplicationBuildReporter };