@akanjs/cli 3.1.1-rc.15 → 3.1.1-rc.16

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 (71) hide show
  1. package/.build-stamp +1 -1
  2. package/{CodeAgent-gtwn7tmb.js → CodeAgent-23ewzxqa.js} +2 -2
  3. package/{CodeTui-v941fqdh.js → CodeTui-kc99fk78.js} +1 -1
  4. package/TunnelShare-dk2gw78d.js +14 -0
  5. package/{agent.command-h82gepwn.js → agent.command-knp5j7bq.js} +5 -5
  6. package/akanCode.js +2 -2
  7. package/{application.command-j1reb9p1.js → application.command-bvfd1680.js} +9 -9
  8. package/{applicationBuildRunner-w20x63mz.js → applicationBuildRunner-4ajaesk1.js} +6 -5
  9. package/buildBatch.proc.js +5 -5
  10. package/{cloud.command-zd2mfkm0.js → cloud.command-f2w40fyy.js} +13 -13
  11. package/cloud.script-2r82sv0f.js +24 -0
  12. package/{code.command-dyet4xn6.js → code.command-dbhhnahn.js} +6 -6
  13. package/{context.command-79gxczm4.js → context.command-yswjwv6y.js} +17 -16
  14. package/context.runner-c3wsh2jw.js +26 -0
  15. package/{guideline.command-xwkskvky.js → guideline.command-ztx6dkpk.js} +2 -2
  16. package/guidelines/conventions/conventions.instruction.md +56 -10
  17. package/incrementalBuilder.proc.js +3 -3
  18. package/{index-yknrmkmt.js → index-005dqc83.js} +2 -2
  19. package/{index-qmeh0s05.js → index-00ke4phc.js} +2 -2
  20. package/{index-hdzjaq7s.js → index-2epb3wgh.js} +2 -2
  21. package/{index-rshwdv9w.js → index-2p1brf5e.js} +2 -2
  22. package/{index-wvvwdzfw.js → index-4332q6yj.js} +3 -3
  23. package/{index-6pzt55w3.js → index-4t4qb8jg.js} +3 -3
  24. package/{index-7ktk2hnz.js → index-76jwsm3g.js} +2 -2
  25. package/{index-tzzs52h0.js → index-7ndgffg4.js} +9 -9
  26. package/{index-1e2955yd.js → index-921cxqrd.js} +3 -1
  27. package/{index-8jb5ep2e.js → index-97fsvy66.js} +2 -2
  28. package/{index-pc9ps0hx.js → index-9sa6abze.js} +8 -8
  29. package/{index-jjd97ya6.js → index-deeskxjh.js} +1 -1
  30. package/{index-cz9g85xh.js → index-er16p89s.js} +1 -1
  31. package/{index-ygy8c12j.js → index-gxj80jz7.js} +1 -1
  32. package/index-hvg3esm0.js +1844 -0
  33. package/{index-41d3zx66.js → index-k9k18vq9.js} +3 -3
  34. package/{index-nmy1rana.js → index-m54n0v29.js} +4 -4
  35. package/index-m5n3ka0p.js +18 -0
  36. package/{index-brpk7gd8.js → index-m6qgr1rx.js} +7 -7
  37. package/{index-553xyb55.js → index-m93qg20j.js} +1 -1
  38. package/{index-4rwfh2de.js → index-mk391h0z.js} +3 -3
  39. package/{index-ch1sv7ke.js → index-nzfgyw3b.js} +9 -21
  40. package/{index-2qzzp0c9.js → index-p2pahmsa.js} +3 -3
  41. package/{index-kbbyzs6j.js → index-qx4r4cj2.js} +2 -2
  42. package/index-rxse80x6.js +408 -0
  43. package/{index-kr62ph5a.js → index-s4c2y5gs.js} +2 -2
  44. package/{index-jtydvvq7.js → index-saj9cx3a.js} +4 -4
  45. package/index-vgt25eh1.js +615 -0
  46. package/{index-8rvwgd1r.js → index-vq77g679.js} +1 -1
  47. package/{index-xeh7m2j5.js → index-xfp4dcnx.js} +1 -1
  48. package/{index-pqdz7rat.js → index-xjwcp91m.js} +910 -36
  49. package/{index-7abjzny1.js → index-ysyt782g.js} +33 -37
  50. package/index.js +22 -22
  51. package/{library.command-td8t85kb.js → library.command-hmbkcwzw.js} +3 -3
  52. package/{localRegistry.command-jx9zkmxf.js → localRegistry.command-sq5p4c9x.js} +15 -13
  53. package/{module.command-j70mqgpp.js → module.command-n4z29zcv.js} +5 -5
  54. package/{package.command-1b1v6k5v.js → package.command-20025dy3.js} +3 -3
  55. package/package.json +2 -2
  56. package/{page.command-m31w2tsz.js → page.command-q8fvpjer.js} +3 -3
  57. package/{pipeline.command-q7b8wy55.js → pipeline.command-8j97fq88.js} +2 -2
  58. package/{primitive.command-4zrbhkb9.js → primitive.command-e5y6dqp1.js} +6 -6
  59. package/{projectTypecheck-synx6qff.js → projectTypecheck-tbdye9k3.js} +1 -1
  60. package/{quality.command-cy0pgqjz.js → quality.command-168pt5vm.js} +621 -311
  61. package/{repair.command-98n6zxg7.js → repair.command-dq1gckth.js} +5 -5
  62. package/{scalar.command-rak5pjk3.js → scalar.command-5vwf152w.js} +4 -4
  63. package/{subspace.command-ej0rk116.js → subspace.command-182be8vj.js} +8 -8
  64. package/{tunnel.command-kdx3amrc.js → tunnel.command-bfzj7xkb.js} +7 -7
  65. package/{workflow.command-gffk9nj9.js → workflow.command-3g53242s.js} +37 -13
  66. package/workspace.command-h7399jwv.js +260 -0
  67. package/TunnelShare-26ty9skr.js +0 -14
  68. package/cloud.script-vdj8ymch.js +0 -24
  69. package/context.runner-ejag7mhr.js +0 -25
  70. package/index-y5m4j2w6.js +0 -856
  71. package/workspace.command-097hv6n1.js +0 -521
@@ -0,0 +1,1844 @@
1
+ // @bun
2
+ import {
3
+ camelToKebabCase,
4
+ runner
5
+ } from "./index-00ke4phc.js";
6
+ import {
7
+ FileSys2
8
+ } from "./index-52w0fvh8.js";
9
+ import {
10
+ extractAgentBlock,
11
+ collectScopeRecipeSources,
12
+ renderScopeAgentBlock,
13
+ JsonFormatter,
14
+ Linter,
15
+ WorkspaceExecutor,
16
+ SysExecutor,
17
+ LibExecutor
18
+ } from "./index-921cxqrd.js";
19
+ import {
20
+ countBlocking,
21
+ formatStyleContract,
22
+ ThemeValidator
23
+ } from "./index-62md4dwy.js";
24
+ import {
25
+ collectRecipeSources2,
26
+ scanRecipes2
27
+ } from "./index-hj6w4ka1.js";
28
+ import {
29
+ sysInputs,
30
+ workflowSpecs
31
+ } from "./index-vgt25eh1.js";
32
+ import {
33
+ getNpmRegistryUrl,
34
+ getLatestPackageVersion
35
+ } from "./index-m5n3ka0p.js";
36
+
37
+ // pkgs/@akanjs/cli/workspace/workspace.runner.ts
38
+ import { mkdir, writeFile as writeFile2 } from "fs/promises";
39
+ import path5 from "path";
40
+
41
+ // pkgs/@akanjs/devkit/biomeBase.ts
42
+ var biomeVersion = "2.5.14";
43
+
44
+ // pkgs/@akanjs/devkit/maintainabilityContract.ts
45
+ import { existsSync } from "fs";
46
+ import { readFile, rm, writeFile } from "fs/promises";
47
+ import path4 from "path";
48
+ import ts11 from "typescript";
49
+
50
+ // pkgs/@akanjs/devkit/componentSizeScanner.ts
51
+ import ts from "typescript";
52
+
53
+ class ComponentSizeScanner {
54
+ static #componentName = /^(?:[A-Z]|use[A-Z])[A-Za-z0-9]*$/;
55
+ static componentsAndHooksOf(sourceFile) {
56
+ return sourceFile.statements.flatMap((statement) => {
57
+ if (ts.isFunctionDeclaration(statement))
58
+ return statement.name && statement.body && ComponentSizeScanner.#componentName.test(statement.name.text) ? [{ name: statement.name.text, node: statement }] : [];
59
+ if (!ts.isVariableStatement(statement))
60
+ return [];
61
+ return statement.declarationList.declarations.flatMap((declaration) => ts.isIdentifier(declaration.name) && ComponentSizeScanner.#componentName.test(declaration.name.text) && declaration.initializer && ComponentSizeScanner.#holdsFunction(declaration.initializer) ? [{ name: declaration.name.text, node: declaration }] : []);
62
+ });
63
+ }
64
+ measure(sourceFile) {
65
+ return ComponentSizeScanner.componentsAndHooksOf(sourceFile).map(({ name, node }) => {
66
+ const line = sourceFile.getLineAndCharacterOfPosition(node.getStart(sourceFile)).line + 1;
67
+ const endLine = sourceFile.getLineAndCharacterOfPosition(node.getEnd()).line + 1;
68
+ return { name, line, lineCount: endLine - line + 1 };
69
+ });
70
+ }
71
+ static #holdsFunction(expression) {
72
+ let current = expression;
73
+ while (ts.isParenthesizedExpression(current) || ts.isAsExpression(current) || ts.isSatisfiesExpression(current))
74
+ current = current.expression;
75
+ if (ts.isArrowFunction(current) || ts.isFunctionExpression(current))
76
+ return true;
77
+ return ts.isCallExpression(current) && current.arguments.some((arg) => ComponentSizeScanner.#holdsFunction(arg));
78
+ }
79
+ }
80
+
81
+ // pkgs/@akanjs/devkit/componentWriteChainScanner.ts
82
+ import ts4 from "typescript";
83
+
84
+ // pkgs/@akanjs/devkit/storeAccessScanner.ts
85
+ import ts2 from "typescript";
86
+ class StoreAccessScanner {
87
+ static #formSetter = /^(?:(?:set|add|sub|addOrSub|upload)[A-Z]\w*On|writeOn)[A-Z]\w*$/;
88
+ #index;
89
+ constructor(index) {
90
+ this.#index = index;
91
+ }
92
+ static stNamesOf(sourceFile) {
93
+ return StoreAccessScanner.localNamesOf(sourceFile, "st");
94
+ }
95
+ static localNamesOf(sourceFile, imported) {
96
+ const names = new Set;
97
+ for (const statement of sourceFile.statements) {
98
+ if (!ts2.isImportDeclaration(statement) || statement.importClause?.isTypeOnly)
99
+ continue;
100
+ const bindings = statement.importClause?.namedBindings;
101
+ if (!bindings || !ts2.isNamedImports(bindings))
102
+ continue;
103
+ for (const element of bindings.elements)
104
+ if (!element.isTypeOnly && (element.propertyName ?? element.name).text === imported)
105
+ names.add(element.name.text);
106
+ }
107
+ return names;
108
+ }
109
+ measure(sourceFile) {
110
+ const stNames = StoreAccessScanner.stNamesOf(sourceFile);
111
+ if (!stNames.size)
112
+ return [];
113
+ return ComponentSizeScanner.componentsAndHooksOf(sourceFile).map(({ name, node }) => {
114
+ let accessCount = 0;
115
+ const visit = (child) => {
116
+ if (ts2.isPropertyAccessExpression(child) && ts2.isIdentifier(child.expression) && stNames.has(child.expression.text) && !this.#isFormSetter(child))
117
+ accessCount += 1;
118
+ ts2.forEachChild(child, visit);
119
+ };
120
+ visit(node);
121
+ return {
122
+ component: name,
123
+ line: sourceFile.getLineAndCharacterOfPosition(node.getStart(sourceFile)).line + 1,
124
+ accessCount
125
+ };
126
+ });
127
+ }
128
+ #isFormSetter(access) {
129
+ const action = access.parent;
130
+ return access.name.text === "do" && ts2.isPropertyAccessExpression(action) && action.expression === access && StoreAccessScanner.#formSetter.test(action.name.text) && !this.#index.isWritingAction(action.name.text);
131
+ }
132
+ }
133
+
134
+ // pkgs/@akanjs/devkit/writePath.ts
135
+ import ts3 from "typescript";
136
+
137
+ class WritePath {
138
+ static #perElement = new Set([
139
+ "map",
140
+ "flatMap",
141
+ "forEach",
142
+ "filter",
143
+ "reduce",
144
+ "some",
145
+ "every",
146
+ "find",
147
+ "findIndex"
148
+ ]);
149
+ #matches;
150
+ #enters;
151
+ #repeated = new WeakSet;
152
+ constructor(matches, { enters = () => true } = {}) {
153
+ this.#matches = matches;
154
+ this.#enters = enters;
155
+ }
156
+ along(node) {
157
+ if (ts3.isFunctionLike(node) && !this.#enters(node))
158
+ return [];
159
+ if (WritePath.isPerElementCallback(node))
160
+ return this.#repeat(this.#children(node));
161
+ if (WritePath.#isFlowStatement(node))
162
+ return this.#busiestOf(this.#flowOf(node));
163
+ if (ts3.isConditionalExpression(node))
164
+ return [...this.along(node.condition), ...this.#busier(this.along(node.whenTrue), this.along(node.whenFalse))];
165
+ const own = ts3.isCallExpression(node) && this.#matches(node) ? [node] : [];
166
+ return [...own, ...this.#children(node)];
167
+ }
168
+ isRepeated(call) {
169
+ return this.#repeated.has(call);
170
+ }
171
+ countOf(calls) {
172
+ return calls.reduce((count, call) => count + (this.isRepeated(call) ? 2 : 1), 0);
173
+ }
174
+ labelOf(call, sourceFile) {
175
+ const callee = call.expression.getText(sourceFile);
176
+ return this.isRepeated(call) ? `${callee} (per item)` : callee;
177
+ }
178
+ static isPerElementCallback(node) {
179
+ const call = node.parent;
180
+ return (ts3.isArrowFunction(node) || ts3.isFunctionExpression(node)) && !!call && ts3.isCallExpression(call) && call.arguments.some((arg) => arg === node) && ts3.isPropertyAccessExpression(call.expression) && WritePath.#perElement.has(call.expression.name.text);
181
+ }
182
+ #children(node) {
183
+ const children = [];
184
+ ts3.forEachChild(node, (child) => {
185
+ children.push(child);
186
+ });
187
+ return children.flatMap((child) => this.along(child));
188
+ }
189
+ #repeat(calls) {
190
+ for (const call of calls)
191
+ this.#repeated.add(call);
192
+ return calls;
193
+ }
194
+ #flowOf(node) {
195
+ if (ts3.isBlock(node))
196
+ return this.#sequenceOf(node.statements);
197
+ if (ts3.isReturnStatement(node) || ts3.isThrowStatement(node))
198
+ return { through: null, exit: node.expression ? this.along(node.expression) : [], jump: null };
199
+ if (ts3.isBreakStatement(node) || ts3.isContinueStatement(node))
200
+ return { through: null, exit: null, jump: [] };
201
+ if (ts3.isLabeledStatement(node))
202
+ return this.#flowOf(node.statement);
203
+ if (ts3.isIfStatement(node))
204
+ return WritePath.#prefixed(this.along(node.expression), this.#merged(this.#flowOf(node.thenStatement), node.elseStatement ? this.#flowOf(node.elseStatement) : WritePath.#onward([])));
205
+ if (ts3.isSwitchStatement(node))
206
+ return WritePath.#prefixed(this.along(node.expression), this.#switchOf(node));
207
+ if (ts3.isTryStatement(node))
208
+ return this.#tryOf(node);
209
+ if (ts3.isForOfStatement(node) || ts3.isForInStatement(node))
210
+ return this.#loopOf(this.along(node.expression), [], node.statement, true);
211
+ if (ts3.isForStatement(node))
212
+ return this.#loopOf(node.initializer ? this.along(node.initializer) : [], [node.condition, node.incrementor].flatMap((part) => part ? this.along(part) : []), node.statement, WritePath.#walksItems(node.condition));
213
+ if (ts3.isWhileStatement(node) || ts3.isDoStatement(node))
214
+ return this.#loopOf([], this.along(node.expression), node.statement, WritePath.#walksItems(node.expression));
215
+ return WritePath.#onward(this.along(node));
216
+ }
217
+ #sequenceOf(statements) {
218
+ let through = [];
219
+ let exit = null;
220
+ let jump = null;
221
+ for (const statement of statements) {
222
+ if (through === null)
223
+ break;
224
+ const flow = this.#flowOf(statement);
225
+ if (flow.exit)
226
+ exit = this.#busierOf(exit, [...through, ...flow.exit]);
227
+ if (flow.jump)
228
+ jump = this.#busierOf(jump, [...through, ...flow.jump]);
229
+ through = flow.through && [...through, ...flow.through];
230
+ }
231
+ return { through, exit, jump };
232
+ }
233
+ #switchOf(node) {
234
+ const hasDefault = node.caseBlock.clauses.some(ts3.isDefaultClause);
235
+ let flow = { through: hasDefault ? null : [], exit: null, jump: null };
236
+ let fallen = null;
237
+ for (const clause of node.caseBlock.clauses) {
238
+ const entry = fallen && this.countOf(fallen) > 0 ? fallen : [];
239
+ const own = WritePath.#prefixed(entry, this.#sequenceOf(clause.statements));
240
+ flow = this.#merged(flow, { through: own.jump, exit: own.exit, jump: null });
241
+ fallen = own.through;
242
+ }
243
+ return this.#merged(flow, { through: fallen, exit: null, jump: null });
244
+ }
245
+ #tryOf(node) {
246
+ const tried = this.#flowOf(node.tryBlock);
247
+ const sent = this.#busiestOf(tried);
248
+ const caught = node.catchClause ? WritePath.#prefixed(sent, this.#flowOf(node.catchClause.block)) : { through: null, exit: sent, jump: null };
249
+ const flow = this.#merged(tried, caught);
250
+ if (!node.finallyBlock)
251
+ return flow;
252
+ const after = this.#busiestOf(this.#flowOf(node.finallyBlock));
253
+ return {
254
+ through: flow.through && [...flow.through, ...after],
255
+ exit: flow.exit && [...flow.exit, ...after],
256
+ jump: flow.jump && [...flow.jump, ...after]
257
+ };
258
+ }
259
+ #loopOf(once, everyTurn, body, isPerItem) {
260
+ const flow = this.#flowOf(body);
261
+ const turn = [...everyTurn, ...this.#busierOf(flow.through, flow.jump) ?? []];
262
+ const repeated = isPerItem ? this.#repeat(turn) : turn;
263
+ return { through: [...once, ...repeated], exit: flow.exit && [...once, ...flow.exit], jump: null };
264
+ }
265
+ #merged(a, b) {
266
+ return {
267
+ through: this.#busierOf(a.through, b.through),
268
+ exit: this.#busierOf(a.exit, b.exit),
269
+ jump: this.#busierOf(a.jump, b.jump)
270
+ };
271
+ }
272
+ #busiestOf({ through, exit, jump }) {
273
+ return this.#busierOf(this.#busierOf(through, exit), jump) ?? [];
274
+ }
275
+ #busierOf(a, b) {
276
+ return a && b ? this.#busier(a, b) : a ?? b;
277
+ }
278
+ static #onward(calls) {
279
+ return { through: calls, exit: null, jump: null };
280
+ }
281
+ static #prefixed(calls, { through, exit, jump }) {
282
+ return {
283
+ through: through && [...calls, ...through],
284
+ exit: exit && [...calls, ...exit],
285
+ jump: jump && [...calls, ...jump]
286
+ };
287
+ }
288
+ static #isFlowStatement(node) {
289
+ return ts3.isBlock(node) || ts3.isIfStatement(node) || ts3.isSwitchStatement(node) || ts3.isTryStatement(node) || ts3.isLabeledStatement(node) || ts3.isReturnStatement(node) || ts3.isThrowStatement(node) || ts3.isBreakStatement(node) || ts3.isContinueStatement(node) || ts3.isIterationStatement(node, false);
290
+ }
291
+ static #walksItems(node) {
292
+ if (!node)
293
+ return false;
294
+ if (ts3.isCallExpression(node))
295
+ return true;
296
+ if (ts3.isPropertyAccessExpression(node) && ["length", "size"].includes(node.name.text))
297
+ return true;
298
+ return !!ts3.forEachChild(node, (child) => WritePath.#walksItems(child) || undefined);
299
+ }
300
+ #busier = (a, b) => this.countOf(b) > this.countOf(a) ? b : a;
301
+ }
302
+
303
+ // pkgs/@akanjs/devkit/componentWriteChainScanner.ts
304
+ class ComponentWriteChainScanner {
305
+ static #inlineCallers = new Set([
306
+ "map",
307
+ "flatMap",
308
+ "forEach",
309
+ "filter",
310
+ "reduce",
311
+ "some",
312
+ "every",
313
+ "find",
314
+ "findIndex",
315
+ "then",
316
+ "catch",
317
+ "finally"
318
+ ]);
319
+ #index;
320
+ constructor(index) {
321
+ this.#index = index;
322
+ }
323
+ scan(sourceFile) {
324
+ const stNames = StoreAccessScanner.stNamesOf(sourceFile);
325
+ if (!stNames.size)
326
+ return [];
327
+ const path = new WritePath((call) => {
328
+ const action = ComponentWriteChainScanner.#actionOf(call.expression, stNames);
329
+ return !!action && this.#index.isWritingAction(action);
330
+ }, { enters: ComponentWriteChainScanner.#isInlineCallback });
331
+ return ComponentSizeScanner.componentsAndHooksOf(sourceFile).flatMap(({ name, node }) => ComponentWriteChainScanner.#handlersIn(node).flatMap((handler) => {
332
+ const writes = path.along(handler);
333
+ const writeCount = path.countOf(writes);
334
+ const second = writes[1] ?? writes[0];
335
+ if (writeCount < 2 || !second)
336
+ return [];
337
+ return [
338
+ {
339
+ component: name,
340
+ line: sourceFile.getLineAndCharacterOfPosition(second.getStart(sourceFile)).line + 1,
341
+ writes: writes.map((call) => path.labelOf(call, sourceFile)),
342
+ writeCount
343
+ }
344
+ ];
345
+ }));
346
+ }
347
+ static #handlersIn(component) {
348
+ const bodies = [];
349
+ const visit = (node) => {
350
+ if (ComponentWriteChainScanner.#isFunction(node) && node.body && !ComponentWriteChainScanner.#isInlineCallback(node))
351
+ bodies.push(node.body);
352
+ ts4.forEachChild(node, visit);
353
+ };
354
+ visit(component);
355
+ return bodies;
356
+ }
357
+ static #isFunction(node) {
358
+ return ts4.isArrowFunction(node) || ts4.isFunctionExpression(node) || ts4.isFunctionDeclaration(node) || ts4.isMethodDeclaration(node);
359
+ }
360
+ static #isInlineCallback(fn) {
361
+ const call = fn.parent;
362
+ return !!call && ts4.isCallExpression(call) && call.arguments.some((arg) => arg === fn) && ts4.isPropertyAccessExpression(call.expression) && ComponentWriteChainScanner.#inlineCallers.has(call.expression.name.text);
363
+ }
364
+ static #actionOf(callee, stNames) {
365
+ if (!ts4.isPropertyAccessExpression(callee) || !ts4.isPropertyAccessExpression(callee.expression))
366
+ return null;
367
+ const { expression: st, name } = callee.expression;
368
+ return ts4.isIdentifier(st) && stNames.has(st.text) && name.text === "do" ? callee.name.text : null;
369
+ }
370
+ }
371
+
372
+ // pkgs/@akanjs/devkit/endpointReach.ts
373
+ import path from "path";
374
+ import ts5 from "typescript";
375
+
376
+ class EndpointReach {
377
+ static #requestBuilders = new Set(["endpoint", "slice"]);
378
+ #reached = new Set;
379
+ constructor(signalFiles, serviceFiles) {
380
+ const methodsByService = new Map;
381
+ for (const { file, sourceFile } of serviceFiles) {
382
+ const methods = methodsByService.get(EndpointReach.serviceOf(file)) ?? new Map;
383
+ for (const cls of sourceFile.statements.filter(ts5.isClassDeclaration))
384
+ for (const member of cls.members)
385
+ if (ts5.isMethodDeclaration(member) && member.body && (ts5.isIdentifier(member.name) || ts5.isPrivateIdentifier(member.name)))
386
+ methods.set(member.name.text, member);
387
+ methodsByService.set(EndpointReach.serviceOf(file), methods);
388
+ }
389
+ const pending = [];
390
+ const reach = ([service, method]) => {
391
+ const key = `${service}.${method}`;
392
+ if (this.#reached.has(key) || !methodsByService.get(service)?.has(method))
393
+ return;
394
+ this.#reached.add(key);
395
+ pending.push([service, method]);
396
+ };
397
+ for (const { sourceFile } of signalFiles)
398
+ for (const cls of sourceFile.statements.filter(ts5.isClassDeclaration)) {
399
+ const base = cls.heritageClauses?.[0]?.types[0]?.expression;
400
+ if (base && ts5.isCallExpression(base) && ts5.isIdentifier(base.expression) && EndpointReach.#requestBuilders.has(base.expression.text))
401
+ EndpointReach.#serviceCallsIn(base, null).forEach(reach);
402
+ }
403
+ for (let next = pending.pop();next; next = pending.pop()) {
404
+ const [service, method] = next;
405
+ const declaration = methodsByService.get(service)?.get(method);
406
+ if (declaration)
407
+ EndpointReach.#serviceCallsIn(declaration, service).forEach(reach);
408
+ }
409
+ }
410
+ static serviceOf(file) {
411
+ return path.posix.basename(file).replace(/\.service\.ts$/, "");
412
+ }
413
+ reaches(service, method) {
414
+ return this.#reached.has(`${service}.${method}`);
415
+ }
416
+ static #serviceCallsIn(node, ownService) {
417
+ const calls = [];
418
+ const visit = (child) => {
419
+ if (ts5.isCallExpression(child) && ts5.isPropertyAccessExpression(child.expression)) {
420
+ const { expression: owner, name } = child.expression;
421
+ if (owner.kind === ts5.SyntaxKind.ThisKeyword && ownService)
422
+ calls.push([ownService, name.text]);
423
+ else if (ts5.isPropertyAccessExpression(owner) && owner.expression.kind === ts5.SyntaxKind.ThisKeyword) {
424
+ const field = owner.name.text;
425
+ if (field.length > "Service".length && field.endsWith("Service"))
426
+ calls.push([field.slice(0, -"Service".length), name.text]);
427
+ }
428
+ }
429
+ ts5.forEachChild(child, visit);
430
+ };
431
+ visit(node);
432
+ return calls;
433
+ }
434
+ }
435
+
436
+ // pkgs/@akanjs/devkit/maintainabilityBaseline.ts
437
+ class MaintainabilityBaseline {
438
+ sections;
439
+ reasons;
440
+ static fileName = "akan.baseline.json";
441
+ static reasonMinChars = 10;
442
+ static debtRules = [
443
+ "akan.size.file",
444
+ "akan.size.component",
445
+ "akan.component.store-access",
446
+ "akan.store.multi-write",
447
+ "akan.store.root-write-chain",
448
+ "akan.component.write-chain",
449
+ "akan.write.placement",
450
+ "akan.service.call-in-loop"
451
+ ];
452
+ static reasonedRules = new Set([
453
+ "akan.size.file",
454
+ "akan.size.component",
455
+ "akan.component.store-access",
456
+ "akan.service.call-in-loop"
457
+ ]);
458
+ static countOf(violation) {
459
+ if (violation.kind === "size")
460
+ return violation.lineCount;
461
+ if (violation.kind === "storeAccess")
462
+ return violation.accessCount;
463
+ if (violation.kind === "multiWrite")
464
+ return violation.writeCount;
465
+ if (violation.kind === "writePlacement")
466
+ return violation.writes.length;
467
+ return violation.calls.length;
468
+ }
469
+ static isDebtRule(name) {
470
+ return MaintainabilityBaseline.debtRules.includes(name);
471
+ }
472
+ static parse(text, source = MaintainabilityBaseline.fileName, { lenient = false } = {}) {
473
+ let json;
474
+ try {
475
+ json = JSON.parse(text);
476
+ } catch {
477
+ throw new Error(`${source} is not valid JSON.`);
478
+ }
479
+ if (typeof json !== "object" || json === null || Array.isArray(json))
480
+ throw new Error(`${source} holds an object keyed by rule id.`);
481
+ const sections = new Map;
482
+ let reasons = new Map;
483
+ for (const [name, value] of Object.entries(json)) {
484
+ if (name === "reasons") {
485
+ const entries = MaintainabilityBaseline.#reasonsOf(value);
486
+ if (!entries)
487
+ throw new Error(`${source}: "reasons" maps an entry's key to a sentence.`);
488
+ reasons = new Map(entries);
489
+ continue;
490
+ }
491
+ if (!MaintainabilityBaseline.isDebtRule(name)) {
492
+ if (lenient)
493
+ continue;
494
+ throw new Error(`${source}: "${name}" is not a rule id. Its sections are ${MaintainabilityBaseline.debtRules.join(", ")} and "reasons"; rewrite it with \`akan quality baseline --force\`.`);
495
+ }
496
+ const counts = MaintainabilityBaseline.#countsOf(value);
497
+ if (!counts)
498
+ throw new Error(`${source}: "${name}" maps each key to a whole-number count.`);
499
+ sections.set(name, new Map(counts));
500
+ }
501
+ return new MaintainabilityBaseline(sections, reasons);
502
+ }
503
+ static of(violations, reasons = new Map) {
504
+ const sections = new Map;
505
+ for (const violation of violations) {
506
+ const counts = sections.get(violation.rule) ?? new Map;
507
+ const count = MaintainabilityBaseline.countOf(violation);
508
+ counts.set(violation.key, Math.max(counts.get(violation.key) ?? 0, count));
509
+ sections.set(violation.rule, counts);
510
+ }
511
+ return new MaintainabilityBaseline(sections).#withReasonsOf(reasons);
512
+ }
513
+ constructor(sections = new Map, reasons = new Map) {
514
+ this.sections = sections;
515
+ this.reasons = reasons;
516
+ }
517
+ get isEmpty() {
518
+ return [...this.sections.values()].every((counts) => !counts.size);
519
+ }
520
+ allows(violation) {
521
+ const recorded = this.recordedOf(violation);
522
+ return recorded !== undefined && MaintainabilityBaseline.countOf(violation) <= recorded;
523
+ }
524
+ recordedOf(violation) {
525
+ return this.sections.get(violation.rule)?.get(violation.key);
526
+ }
527
+ reasonOf(key) {
528
+ const reason = this.#holdsReasoned(key) ? this.reasons.get(key) : undefined;
529
+ return reason && reason.replace(/\s/g, "").length >= MaintainabilityBaseline.reasonMinChars ? reason : undefined;
530
+ }
531
+ entriesByRule() {
532
+ return new Map([...this.sections].filter(([, counts]) => counts.size).map(([rule, counts]) => [
533
+ rule,
534
+ [...counts].map(([key, count]) => ({
535
+ key,
536
+ count,
537
+ reason: MaintainabilityBaseline.reasonedRules.has(rule) ? this.reasonOf(key) : undefined
538
+ }))
539
+ ]));
540
+ }
541
+ tightenedBy(violations) {
542
+ const current = MaintainabilityBaseline.of(violations);
543
+ const sections = new Map([...this.sections].map(([rule, counts]) => [
544
+ rule,
545
+ MaintainabilityBaseline.#lowered(counts, current.sections.get(rule) ?? new Map)
546
+ ]));
547
+ return new MaintainabilityBaseline(sections).#withReasonsOf(this.reasons);
548
+ }
549
+ #withReasonsOf(reasons) {
550
+ return new MaintainabilityBaseline(this.sections, new Map([...reasons].filter(([key]) => this.#holdsReasoned(key))));
551
+ }
552
+ grownFrom(committed) {
553
+ return [...this.sections].flatMap(([rule, counts]) => MaintainabilityBaseline.#raised(counts, committed.sections.get(rule) ?? new Map).filter(([key]) => !(MaintainabilityBaseline.reasonedRules.has(rule) && this.reasonOf(key))).map(([key, count, recorded]) => ({ rule, key, count, committed: recorded })));
554
+ }
555
+ stringify() {
556
+ const sections = MaintainabilityBaseline.debtRules.flatMap((rule) => {
557
+ const counts = this.sections.get(rule);
558
+ return counts?.size ? [[rule, MaintainabilityBaseline.#sortedObjectOf(counts)]] : [];
559
+ });
560
+ return JsonFormatter.stringify({
561
+ ...Object.fromEntries(sections),
562
+ ...this.reasons.size ? { reasons: MaintainabilityBaseline.#sortedObjectOf(this.reasons) } : {}
563
+ }, MaintainabilityBaseline.fileName);
564
+ }
565
+ #holdsReasoned(key) {
566
+ return [...this.sections].some(([rule, counts]) => MaintainabilityBaseline.reasonedRules.has(rule) && counts.has(key));
567
+ }
568
+ static #countsOf(value) {
569
+ if (typeof value !== "object" || value === null || Array.isArray(value))
570
+ return null;
571
+ const entries = Object.entries(value);
572
+ return entries.every(([, count]) => Number.isInteger(count)) ? entries : null;
573
+ }
574
+ static #reasonsOf(value) {
575
+ if (typeof value !== "object" || value === null || Array.isArray(value))
576
+ return null;
577
+ const entries = Object.entries(value);
578
+ return entries.every(([, reason]) => typeof reason === "string") ? entries : null;
579
+ }
580
+ static #lowered(recorded, current) {
581
+ return new Map([...recorded].flatMap(([key, count]) => {
582
+ const measured = current.get(key);
583
+ return measured === undefined ? [] : [[key, Math.min(count, measured)]];
584
+ }));
585
+ }
586
+ static #raised(working, committed) {
587
+ return [...working].flatMap(([key, count]) => {
588
+ const recorded = committed.get(key);
589
+ return recorded !== undefined && count <= recorded ? [] : [[key, count, recorded]];
590
+ });
591
+ }
592
+ static #sortedObjectOf(values) {
593
+ return Object.fromEntries([...values].sort(([a], [b]) => MaintainabilityBaseline.#byKey(a, b)));
594
+ }
595
+ static #byKey(a, b) {
596
+ return a < b ? -1 : a > b ? 1 : 0;
597
+ }
598
+ }
599
+
600
+ // pkgs/@akanjs/devkit/maintainabilityLimits.ts
601
+ import path3 from "path";
602
+ import ts6 from "typescript";
603
+
604
+ // pkgs/@akanjs/devkit/abstractDoc.ts
605
+ import path2 from "path";
606
+
607
+ class AbstractDoc {
608
+ path;
609
+ content;
610
+ siblingFiles;
611
+ static suffix = ".abstract.md";
612
+ static maxLines = 300;
613
+ static #facetRoots = "{lib,ui,webkit,srvkit,common,plugin}";
614
+ static isAbstractPath(filePath) {
615
+ return filePath.endsWith(AbstractDoc.suffix);
616
+ }
617
+ static lineCountOf(content) {
618
+ return content.split(/\r?\n/).length;
619
+ }
620
+ static kindOf(filePath) {
621
+ const [root, folder, ...rest] = filePath.split("/");
622
+ if (root !== "lib" || !folder)
623
+ return "other";
624
+ if (folder === "__scalar")
625
+ return rest.length === 2 ? "scalar" : "other";
626
+ if (rest.length !== 1)
627
+ return "other";
628
+ return folder.startsWith("_") ? "service" : "domain";
629
+ }
630
+ static async findAll(sys, { module } = {}) {
631
+ const filePaths = (await sys.getAllFiles(`${AbstractDoc.#facetRoots}/**/*${AbstractDoc.suffix}`)).map((filePath) => filePath.split(path2.sep).join("/")).sort((a, b) => a < b ? -1 : a > b ? 1 : 0);
632
+ const docs = await Promise.all(filePaths.map((filePath) => AbstractDoc.read(sys, filePath)));
633
+ if (!module)
634
+ return docs;
635
+ return docs.filter((doc) => doc.moduleName === module || doc.folderName === module);
636
+ }
637
+ static async read(sys, filePath) {
638
+ const dirPath = filePath.split("/").slice(0, -1).join("/");
639
+ const [content, folderFiles] = await Promise.all([sys.readFile(filePath), sys.readdir(dirPath)]);
640
+ return new AbstractDoc(filePath, content, folderFiles.filter((fileName) => !AbstractDoc.isAbstractPath(fileName)));
641
+ }
642
+ constructor(path, content, siblingFiles) {
643
+ this.path = path;
644
+ this.content = content;
645
+ this.siblingFiles = siblingFiles;
646
+ }
647
+ get kind() {
648
+ return AbstractDoc.kindOf(this.path);
649
+ }
650
+ get folderName() {
651
+ return this.path.split("/").at(-2) ?? "";
652
+ }
653
+ get moduleName() {
654
+ return (this.path.split("/").at(-1) ?? "").slice(0, -AbstractDoc.suffix.length);
655
+ }
656
+ get lineCount() {
657
+ return AbstractDoc.lineCountOf(this.content);
658
+ }
659
+ canReplaceWith(candidate) {
660
+ const next = candidate.trim();
661
+ if (!next.startsWith("#"))
662
+ return false;
663
+ const lineCount = AbstractDoc.lineCountOf(next);
664
+ return lineCount >= 3 && lineCount < this.lineCount;
665
+ }
666
+ }
667
+
668
+ // pkgs/@akanjs/devkit/maintainabilityLimits.ts
669
+ class MaintainabilityLimits {
670
+ static fileMaxLines = {
671
+ ".Template.tsx": 400,
672
+ ".Unit.tsx": 400,
673
+ ".Util.tsx": 400,
674
+ ".View.tsx": 400,
675
+ ".Zone.tsx": 400,
676
+ ".store.ts": 400,
677
+ ".document.ts": 500,
678
+ ".service.ts": 500,
679
+ [AbstractDoc.suffix]: AbstractDoc.maxLines
680
+ };
681
+ static folderMaxLines = { "ui/": 400, "webkit/": 400 };
682
+ static #maxLinesByKind = { ...MaintainabilityLimits.fileMaxLines, ...MaintainabilityLimits.folderMaxLines };
683
+ static componentMaxLines = 250;
684
+ static componentMaxStoreAccesses = 16;
685
+ static fileKindOf(sysRelativePath) {
686
+ const kinds = Object.keys(MaintainabilityLimits.#maxLinesByKind);
687
+ const suffix = kinds.find((kind) => sysRelativePath.endsWith(kind));
688
+ if (suffix)
689
+ return suffix;
690
+ if (!/\.tsx?$/.test(sysRelativePath) || MaintainabilityLimits.#isTest(sysRelativePath))
691
+ return null;
692
+ return kinds.find((kind) => sysRelativePath.startsWith(kind)) ?? null;
693
+ }
694
+ static fileMaxLinesOf(sysRelativePath) {
695
+ const kind = MaintainabilityLimits.fileKindOf(sysRelativePath);
696
+ return kind ? MaintainabilityLimits.#maxLinesByKind[kind] : null;
697
+ }
698
+ static isReexportBarrel(file, content) {
699
+ if (path3.posix.basename(file) !== "index.ts")
700
+ return false;
701
+ return ts6.createSourceFile(file, content, ts6.ScriptTarget.Latest, false, ts6.ScriptKind.TS).statements.every((statement) => ts6.isExportDeclaration(statement));
702
+ }
703
+ static lineCountOf(content) {
704
+ return AbstractDoc.lineCountOf(content);
705
+ }
706
+ static isClientCode(sysRelativePath) {
707
+ if (MaintainabilityLimits.#isTest(sysRelativePath))
708
+ return false;
709
+ if (sysRelativePath.startsWith("lib/"))
710
+ return sysRelativePath.endsWith(".tsx");
711
+ return /^(ui|webkit)\/.+\.tsx?$/.test(sysRelativePath) && !sysRelativePath.endsWith(".d.ts");
712
+ }
713
+ static #isTest(sysRelativePath) {
714
+ return /\.(test|spec)\.tsx?$/.test(sysRelativePath);
715
+ }
716
+ }
717
+
718
+ // pkgs/@akanjs/devkit/maintainabilityReport.ts
719
+ class MaintainabilityReport {
720
+ static #clientSplitFix = 'Split it, in this order: a mode/kind table `{ [kind in cnst.X["value"]]: \u2026 }` in place of mode flags, each entry a component of the module owning the data of that kind; an interaction hook in `webkit/use<X>.tsx` with its pure logic in `common/` (`akan workflow plan create-interaction`); the writes behind one endpoint (`akan workflow plan add-mutation`); last, a sub-concept in its own module (`lib/<sub>` or `lib/_<feature>`), never model-bound code moved into `ui/`.';
721
+ static #serverMarkupFix = "Move model-independent pieces into ui/ components and display logic onto Light<Model>.";
722
+ static #oneEndpointFix = "Make it one service method that runs the writes inside `this.transaction(fn)`, with a side effect such as a push command in `this.afterCommit(fn)`, behind one endpoint the action calls once; a write per item becomes one endpoint taking the list. An MCP agent or another screen calling one endpoint alone skips the rest.";
723
+ static #fixes = {
724
+ ".Template.tsx": MaintainabilityReport.#clientSplitFix,
725
+ ".Unit.tsx": MaintainabilityReport.#serverMarkupFix,
726
+ ".Util.tsx": MaintainabilityReport.#clientSplitFix,
727
+ ".View.tsx": MaintainabilityReport.#serverMarkupFix,
728
+ ".Zone.tsx": MaintainabilityReport.#clientSplitFix,
729
+ "ui/": MaintainabilityReport.#clientSplitFix,
730
+ "webkit/": MaintainabilityReport.#clientSplitFix,
731
+ ".store.ts": "Move business logic into the service behind an endpoint and derived values onto Light<Model>; an action is fetch, set, toast.",
732
+ ".document.ts": "Move display and predicate logic onto Light<Model>, and split an unrelated concept into its own module.",
733
+ ".service.ts": "Move state transitions into document chain methods, and split an unrelated responsibility into its own module.",
734
+ [AbstractDoc.suffix]: "Trim the abstract to a title, one sentence naming what the module owns, and a `## Rules` list of the invariants the code cannot show.",
735
+ "akan.size.component": MaintainabilityReport.#clientSplitFix,
736
+ "akan.store.multi-write": MaintainabilityReport.#oneEndpointFix,
737
+ "akan.store.root-write-chain": `A store may call another through \`RootStore\`, but that does not make the writes one. ${MaintainabilityReport.#oneEndpointFix}`,
738
+ "akan.component.write-chain": "Move the writes into one service method behind one endpoint, called by one store action the handler calls once; a component chaining `st.do` writes, or writing once per item, leaves an agent or another screen half-done.",
739
+ "akan.component.store-access": MaintainabilityReport.#clientSplitFix,
740
+ "akan.write.placement": "A server write leaves the browser through one store action, started by one module component. Move a `fetch.<mutation>` into a store action, and hand `ui/` and `webkit/` code the write as an `onX` prop or hook argument from the module's `Zone` or `Util`: they stay free of any one model, and an agent or another screen reaches the write through the store.",
741
+ "akan.service.call-in-loop": "Load the set once (`load<Model>Many(ids)`, one filter query) or write it once (one batch method), then loop in memory: a call per item is a round trip per item, so the endpoint slows as its input grows.",
742
+ "akan.baseline.growth": "Restore the entry from the default branch, then split the file or move the writes instead: `akan lint` lowers an entry as the code shrinks and never raises one."
743
+ };
744
+ static #labels = {
745
+ "ui/": "ui/**",
746
+ "webkit/": "webkit/**",
747
+ "akan.size.component": "component or hook",
748
+ "akan.store.multi-write": "store action with several writes",
749
+ "akan.store.root-write-chain": "store method chaining other stores' writes",
750
+ "akan.component.write-chain": "handler with several writes",
751
+ "akan.component.store-access": "component or hook reaching the store often",
752
+ "akan.write.placement": "write sent outside a store action or module component",
753
+ "akan.service.call-in-loop": "service call per item",
754
+ "akan.baseline.growth": "baseline entry"
755
+ };
756
+ static #units = {
757
+ "akan.size.file": "lines",
758
+ "akan.size.component": "lines",
759
+ "akan.component.store-access": "store accesses",
760
+ "akan.store.multi-write": "writes",
761
+ "akan.store.root-write-chain": "writes",
762
+ "akan.component.write-chain": "writes",
763
+ "akan.write.placement": "writes",
764
+ "akan.service.call-in-loop": "calls per item"
765
+ };
766
+ static describe(sysPath, failures, commands = {}) {
767
+ const groups = new Map;
768
+ for (const failure of failures) {
769
+ const fixKey = MaintainabilityReport.#fixKeyOf(failure);
770
+ const fix = MaintainabilityReport.#fixes[fixKey];
771
+ const group = groups.get(fix) ?? { labels: [], rules: new Set };
772
+ const label = MaintainabilityReport.#labelOf(fixKey);
773
+ if (!group.labels.includes(label))
774
+ group.labels.push(label);
775
+ group.rules.add(failure.rule);
776
+ groups.set(fix, group);
777
+ }
778
+ return [
779
+ `[maintainability] ${failures.length} violation(s) in ${sysPath}:`,
780
+ ...failures.map((failure) => ` ${sysPath}/${failure.file}:${failure.line} ${failure.rule} ${MaintainabilityReport.#problemOf(failure)}`),
781
+ "How to fix:",
782
+ ...[...groups].flatMap(([fix, { labels, rules }]) => [
783
+ ` ${labels.join(", ")}: ${fix}`,
784
+ ...[...new Set([...rules].flatMap((rule) => commands[rule] ?? []))].map((command) => ` Path: ${command}`)
785
+ ])
786
+ ].join(`
787
+ `);
788
+ }
789
+ static #problemOf(failure) {
790
+ if (failure.kind === "baselineGrowth") {
791
+ const entry = `entry "${failure.key}" under ${failure.debtRule}`;
792
+ return failure.committed === undefined ? `${entry} is not in the baseline at ${failure.reference}, which may only shrink` : `${entry} allows ${failure.count} ${MaintainabilityReport.#units[failure.debtRule]}, above the ${failure.committed} at ${failure.reference}; the baseline may only shrink`;
793
+ }
794
+ const grown = failure.recorded === undefined ? "" : `, more than the ${failure.recorded} recorded`;
795
+ if (failure.kind === "multiWrite") {
796
+ const writes = failure.writes.some((write) => write.endsWith("(per item)")) ? "a write per item" : `${failure.writes.length} writes`;
797
+ const listed = `${failure.writes.join(", ")}${grown}`;
798
+ if (failure.rule === "akan.component.write-chain")
799
+ return `${MaintainabilityReport.#unitOf(failure.owner)} ${failure.owner} sends ${writes} from one handler: ${listed}`;
800
+ if (failure.rule === "akan.store.root-write-chain")
801
+ return `store method ${failure.owner} chains ${writes} through other stores from the browser: ${listed}`;
802
+ return `store action ${failure.owner} sends ${writes} from the browser: ${listed}`;
803
+ }
804
+ if (failure.kind === "writePlacement")
805
+ return `sends ${failure.writes.length} server write(s) from outside a store action or a module component: ${failure.writes.join(", ")}${grown}`;
806
+ if (failure.kind === "loopCall")
807
+ return `service method ${failure.owner} calls once per item: ${failure.calls.join(", ")}${grown}`;
808
+ if (failure.kind === "storeAccess")
809
+ return `${MaintainabilityReport.#unitOf(failure.component)} ${failure.component} reaches the store ${failure.accessCount} times, over the ${failure.maxAccesses}-access limit${failure.recorded === undefined ? "" : `, up from ${failure.recorded}`}`;
810
+ const subject = failure.component ? `${MaintainabilityReport.#unitOf(failure.component)} ${failure.component} has` : "file has";
811
+ const up = failure.recorded === undefined ? "" : `, up from ${failure.recorded}`;
812
+ return `${subject} ${failure.lineCount} lines, over the ${failure.maxLines}-line limit${up}`;
813
+ }
814
+ static #unitOf(name) {
815
+ return /^use[A-Z]/.test(name) ? "hook" : "component";
816
+ }
817
+ static #fixKeyOf(failure) {
818
+ if (failure.rule !== "akan.size.file")
819
+ return failure.rule;
820
+ return MaintainabilityLimits.fileKindOf(failure.file) ?? "akan.size.component";
821
+ }
822
+ static #labelOf(fixKey) {
823
+ return MaintainabilityReport.#labels[fixKey] ?? `*${fixKey}`;
824
+ }
825
+ }
826
+
827
+ // pkgs/@akanjs/devkit/serviceLoopCallScanner.ts
828
+ import ts7 from "typescript";
829
+ class ServiceLoopCallScanner {
830
+ static #reachingField = /(?:Service|Model)$/;
831
+ static #generatedQuery = /^_*(?:get|load|list|find|pick|exists|count|insight|create|update|remove|search)[A-Z]/;
832
+ scan(sourceFile, answersCaller) {
833
+ return sourceFile.statements.filter(ts7.isClassDeclaration).flatMap((cls) => {
834
+ const methods = cls.members.filter((member) => ts7.isMethodDeclaration(member) && !!member.body && (ts7.isIdentifier(member.name) || ts7.isPrivateIdentifier(member.name)));
835
+ const declared = new Set(methods.map((method) => method.name.text));
836
+ const reaching = ServiceLoopCallScanner.#reachingMethodsOf(methods, declared);
837
+ const reaches = (call) => ServiceLoopCallScanner.#reaches(call, declared, reaching);
838
+ const ownModel = cls.name?.text.replace(/Service$/, "") ?? "";
839
+ return methods.flatMap((method) => {
840
+ if (!answersCaller(method.name.text))
841
+ return [];
842
+ const calls = [];
843
+ const visit = (node, perItem) => {
844
+ if (perItem && ts7.isCallExpression(node) && reaches(node) && !(perItem === "callback" && ServiceLoopCallScanner.#isBatchedLoad(node, declared, ownModel)))
845
+ calls.push(node);
846
+ if (ts7.isForOfStatement(node) || ts7.isForInStatement(node)) {
847
+ visit(node.expression, perItem);
848
+ visit(node.statement, "loop");
849
+ return;
850
+ }
851
+ ts7.forEachChild(node, (child) => visit(child, perItem === "loop" || !WritePath.isPerElementCallback(child) ? perItem : "callback"));
852
+ };
853
+ visit(method, false);
854
+ const first = calls[0];
855
+ if (!first)
856
+ return [];
857
+ return [
858
+ {
859
+ method: method.name.text,
860
+ line: sourceFile.getLineAndCharacterOfPosition(first.getStart(sourceFile)).line + 1,
861
+ calls: calls.map((call) => call.expression.getText(sourceFile))
862
+ }
863
+ ];
864
+ });
865
+ });
866
+ }
867
+ static #reachingMethodsOf(methods, declared) {
868
+ const reaching = new Set;
869
+ let grew = true;
870
+ while (grew) {
871
+ grew = false;
872
+ for (const method of methods) {
873
+ const name = method.name.text;
874
+ if (reaching.has(name))
875
+ continue;
876
+ let found = false;
877
+ const visit = (node) => {
878
+ if (found)
879
+ return;
880
+ if (ts7.isCallExpression(node) && ServiceLoopCallScanner.#reaches(node, declared, reaching))
881
+ found = true;
882
+ else
883
+ ts7.forEachChild(node, visit);
884
+ };
885
+ visit(method);
886
+ if (found) {
887
+ reaching.add(name);
888
+ grew = true;
889
+ }
890
+ }
891
+ }
892
+ return reaching;
893
+ }
894
+ static #isBatchedLoad(call, declared, ownModel) {
895
+ const callee = call.expression;
896
+ if (!ts7.isPropertyAccessExpression(callee))
897
+ return false;
898
+ const model = ServiceLoopCallScanner.#loadedModelOf(callee, declared, ownModel);
899
+ if (!model)
900
+ return false;
901
+ const className = `${model.charAt(0).toUpperCase()}${model.slice(1)}`;
902
+ return [`get${className}`, `load${className}`, `load${className}Many`].includes(callee.name.text);
903
+ }
904
+ static #loadedModelOf(callee, declared, ownModel) {
905
+ const owner = callee.expression;
906
+ if (owner.kind === ts7.SyntaxKind.ThisKeyword)
907
+ return declared.has(callee.name.text) ? null : ownModel;
908
+ if (!ts7.isPropertyAccessExpression(owner) || owner.expression.kind !== ts7.SyntaxKind.ThisKeyword)
909
+ return null;
910
+ return owner.name.text.match(/^(\w+)Model$/)?.[1] ?? null;
911
+ }
912
+ static #reaches(call, declared, reaching) {
913
+ const callee = call.expression;
914
+ if (!ts7.isPropertyAccessExpression(callee))
915
+ return false;
916
+ const owner = callee.expression;
917
+ if (owner.kind === ts7.SyntaxKind.ThisKeyword) {
918
+ const name = callee.name.text;
919
+ return declared.has(name) ? reaching.has(name) : ServiceLoopCallScanner.#generatedQuery.test(name);
920
+ }
921
+ return ts7.isPropertyAccessExpression(owner) && owner.expression.kind === ts7.SyntaxKind.ThisKeyword && ServiceLoopCallScanner.#reachingField.test(owner.name.text);
922
+ }
923
+ }
924
+
925
+ // pkgs/@akanjs/devkit/signalMutationIndex.ts
926
+ import ts8 from "typescript";
927
+
928
+ class SignalMutationIndex {
929
+ static #generatedArgCounts = { create: 1, update: 2, remove: 1, merge: 2 };
930
+ static #argMethods = new Set(["param", "body", "search", "room", "msg"]);
931
+ #shapesByOwner = new Map;
932
+ constructor(sourceFiles) {
933
+ for (const { file, sourceFile } of sourceFiles) {
934
+ if (!/^(apps|libs)\/[^/]+\/lib\/.+\.signal\.ts$/.test(file))
935
+ continue;
936
+ const owner = file.split("/").slice(0, 2).join("/");
937
+ const shapes = this.#shapesByOwner.get(owner) ?? new Map;
938
+ SignalMutationIndex.#collect(sourceFile, shapes);
939
+ this.#shapesByOwner.set(owner, shapes);
940
+ }
941
+ }
942
+ isMutation(consumerFile, name) {
943
+ return this.#shapeOf(consumerFile, name)?.kind === "mutation";
944
+ }
945
+ policyIndexOf(consumerFile, name) {
946
+ const shape = this.#shapeOf(consumerFile, name);
947
+ return shape?.kind === "mutation" ? shape.argCount : null;
948
+ }
949
+ #shapeOf(consumerFile, name) {
950
+ const [root, owner] = consumerFile.split("/");
951
+ const own = this.#shapesByOwner.get(`${root}/${owner}`)?.get(name);
952
+ if (own)
953
+ return own;
954
+ for (const [key, shapes] of this.#shapesByOwner) {
955
+ const shape = shapes.get(name);
956
+ if (key.startsWith("libs/") && shape?.kind === "mutation")
957
+ return shape;
958
+ }
959
+ return;
960
+ }
961
+ static #collect(sourceFile, kinds) {
962
+ const visit = (node) => {
963
+ if (ts8.isCallExpression(node) && ts8.isIdentifier(node.expression)) {
964
+ if (node.expression.text === "slice")
965
+ SignalMutationIndex.#collectGenerated(node, kinds);
966
+ else if (node.expression.text === "endpoint")
967
+ SignalMutationIndex.#collectEndpoints(node, kinds);
968
+ }
969
+ ts8.forEachChild(node, visit);
970
+ };
971
+ visit(sourceFile);
972
+ }
973
+ static #collectGenerated(slice, kinds) {
974
+ let service = slice.arguments[0];
975
+ while (service && ts8.isCallExpression(service) && ts8.isPropertyAccessExpression(service.expression))
976
+ service = service.expression.expression;
977
+ if (!service || !ts8.isPropertyAccessExpression(service) || !SignalMutationIndex.#isNamed(service.expression, "srv"))
978
+ return;
979
+ const model = service.name.text;
980
+ const capModel = `${model.charAt(0).toUpperCase()}${model.slice(1)}`;
981
+ for (const [verb, argCount] of Object.entries(SignalMutationIndex.#generatedArgCounts))
982
+ kinds.set(`${verb}${capModel}`, { kind: "mutation", argCount });
983
+ kinds.set(`add${capModel}Files`, { kind: "mutation", argCount: 2 });
984
+ }
985
+ static #collectEndpoints(endpoint, kinds) {
986
+ const builder = endpoint.arguments[1];
987
+ if (!builder || !ts8.isArrowFunction(builder) && !ts8.isFunctionExpression(builder))
988
+ return;
989
+ const map = SignalMutationIndex.#returnedObjectOf(builder);
990
+ if (!map)
991
+ return;
992
+ const verbOf = SignalMutationIndex.#verbReaderOf(builder.parameters[0]);
993
+ for (const property of map.properties) {
994
+ if (!ts8.isPropertyAssignment(property))
995
+ continue;
996
+ if (!ts8.isIdentifier(property.name) && !ts8.isStringLiteral(property.name))
997
+ continue;
998
+ const { root, argCount } = SignalMutationIndex.#chainOf(property.initializer);
999
+ const verb = verbOf(root);
1000
+ const kind = verb === "message" ? "mutation" : verb;
1001
+ if (kind === "query" || kind === "mutation")
1002
+ kinds.set(property.name.text, { kind, argCount });
1003
+ }
1004
+ }
1005
+ static #returnedObjectOf(builder) {
1006
+ let body = builder.body;
1007
+ if (ts8.isBlock(body))
1008
+ body = body.statements.find(ts8.isReturnStatement)?.expression;
1009
+ while (body && ts8.isParenthesizedExpression(body))
1010
+ body = body.expression;
1011
+ return body && ts8.isObjectLiteralExpression(body) ? body : null;
1012
+ }
1013
+ static #verbReaderOf(parameter) {
1014
+ const verbs = new Map;
1015
+ if (parameter && ts8.isObjectBindingPattern(parameter.name))
1016
+ for (const element of parameter.name.elements) {
1017
+ const verb = element.propertyName ?? element.name;
1018
+ if (ts8.isIdentifier(verb) && ts8.isIdentifier(element.name))
1019
+ verbs.set(element.name.text, verb.text);
1020
+ }
1021
+ const holder = parameter && ts8.isIdentifier(parameter.name) ? parameter.name.text : null;
1022
+ return (callee) => {
1023
+ if (callee && ts8.isIdentifier(callee))
1024
+ return verbs.get(callee.text);
1025
+ if (callee && ts8.isPropertyAccessExpression(callee) && SignalMutationIndex.#isNamed(callee.expression, holder))
1026
+ return callee.name.text;
1027
+ return;
1028
+ };
1029
+ }
1030
+ static #isNamed(expression, name) {
1031
+ return ts8.isIdentifier(expression) && expression.text === name;
1032
+ }
1033
+ static #chainOf(initializer) {
1034
+ let root = initializer;
1035
+ let argCount = 0;
1036
+ while (ts8.isCallExpression(root) && ts8.isPropertyAccessExpression(root.expression) && ts8.isCallExpression(root.expression.expression)) {
1037
+ if (SignalMutationIndex.#argMethods.has(root.expression.name.text))
1038
+ argCount += 1;
1039
+ root = root.expression.expression;
1040
+ }
1041
+ return { root: ts8.isCallExpression(root) ? root.expression : undefined, argCount };
1042
+ }
1043
+ }
1044
+
1045
+ // pkgs/@akanjs/devkit/storeSource.ts
1046
+ import ts9 from "typescript";
1047
+
1048
+ class StoreSource {
1049
+ file;
1050
+ stores = [];
1051
+ methods = [];
1052
+ #fetchNames;
1053
+ #ownActionsByStore = new Map;
1054
+ #rootAliasesByMethod = new Map;
1055
+ static generatedWritesOf(refName) {
1056
+ const model = `${refName.charAt(0).toUpperCase()}${refName.slice(1)}`;
1057
+ return [
1058
+ `create${model}`,
1059
+ `update${model}`,
1060
+ `remove${model}`,
1061
+ `merge${model}`,
1062
+ `create${model}InForm`,
1063
+ `update${model}InForm`,
1064
+ `submit${model}`
1065
+ ];
1066
+ }
1067
+ constructor({ file, sourceFile }) {
1068
+ this.file = file;
1069
+ this.#fetchNames = StoreSource.#fetchBindingsOf(sourceFile);
1070
+ for (const statement of sourceFile.statements) {
1071
+ if (!ts9.isClassDeclaration(statement) || !statement.name)
1072
+ continue;
1073
+ const refName = StoreSource.#refNameOf(statement);
1074
+ if (refName === undefined)
1075
+ continue;
1076
+ const store = statement.name.text;
1077
+ this.stores.push({ name: store, refName });
1078
+ const ownActions = new Set(refName ? StoreSource.generatedWritesOf(refName) : []);
1079
+ for (const member of statement.members) {
1080
+ if (!ts9.isMethodDeclaration(member) || !member.body)
1081
+ continue;
1082
+ const isStatic = !!ts9.getModifiers(member)?.some(({ kind }) => kind === ts9.SyntaxKind.StaticKeyword);
1083
+ const name = member.name.getText(sourceFile);
1084
+ if (!isStatic)
1085
+ ownActions.add(name);
1086
+ const method = { store, name, isStatic, body: member.body };
1087
+ this.methods.push(method);
1088
+ this.#rootAliasesByMethod.set(method, StoreSource.#rootAliasesIn(member));
1089
+ }
1090
+ this.#ownActionsByStore.set(store, ownActions);
1091
+ }
1092
+ }
1093
+ targetsIn(method) {
1094
+ const targets = [];
1095
+ const visit = (node) => {
1096
+ const target = ts9.isCallExpression(node) ? this.targetOf(method, node) : null;
1097
+ if (target)
1098
+ targets.push(target);
1099
+ ts9.forEachChild(node, visit);
1100
+ };
1101
+ visit(method.body);
1102
+ return targets;
1103
+ }
1104
+ targetOf(method, call) {
1105
+ const callee = call.expression;
1106
+ if (!ts9.isPropertyAccessExpression(callee) && !ts9.isElementAccessExpression(callee))
1107
+ return null;
1108
+ const name = ts9.isPropertyAccessExpression(callee) ? callee.name.text : ts9.isStringLiteralLike(callee.argumentExpression) ? callee.argumentExpression.text : null;
1109
+ if (name === null)
1110
+ return null;
1111
+ const receiver = StoreSource.#unwrap(callee.expression);
1112
+ const isThis = receiver.kind === ts9.SyntaxKind.ThisKeyword;
1113
+ if (isThis && method.isStatic)
1114
+ return { kind: "static", store: method.store, name };
1115
+ if (!isThis && !ts9.isIdentifier(receiver))
1116
+ return null;
1117
+ if (ts9.isIdentifier(receiver) && this.#fetchNames.has(receiver.text))
1118
+ return { kind: "fetch", name };
1119
+ if (isThis || ts9.isIdentifier(receiver) && this.#rootAliasesByMethod.get(method)?.has(receiver.text))
1120
+ return { kind: "action", name, isOwn: !!this.#ownActionsByStore.get(method.store)?.has(name) };
1121
+ return ts9.isIdentifier(receiver) ? { kind: "static", store: receiver.text, name } : null;
1122
+ }
1123
+ static #rootAliasesIn(method) {
1124
+ const aliases = new Set;
1125
+ const visit = (node) => {
1126
+ if (ts9.isParameter(node) && ts9.isIdentifier(node.name) && StoreSource.#isRootStoreType(node.type))
1127
+ aliases.add(node.name.text);
1128
+ if (ts9.isVariableDeclaration(node) && ts9.isIdentifier(node.name) && node.initializer && StoreSource.#unwrap(node.initializer).kind === ts9.SyntaxKind.ThisKeyword)
1129
+ aliases.add(node.name.text);
1130
+ ts9.forEachChild(node, visit);
1131
+ };
1132
+ visit(method);
1133
+ return aliases;
1134
+ }
1135
+ static #isRootStoreType(type) {
1136
+ return !!type && ts9.isTypeReferenceNode(type) && ts9.isIdentifier(type.typeName) && type.typeName.text === "RootStore";
1137
+ }
1138
+ static #unwrap(expression) {
1139
+ let current = expression;
1140
+ while (ts9.isParenthesizedExpression(current) || ts9.isAsExpression(current) || ts9.isTypeAssertionExpression(current) || ts9.isSatisfiesExpression(current) || ts9.isNonNullExpression(current))
1141
+ current = current.expression;
1142
+ return current;
1143
+ }
1144
+ static #refNameOf(statement) {
1145
+ for (const clause of statement.heritageClauses ?? []) {
1146
+ if (clause.token !== ts9.SyntaxKind.ExtendsKeyword)
1147
+ continue;
1148
+ for (const { expression } of clause.types) {
1149
+ if (!ts9.isCallExpression(expression) || !ts9.isIdentifier(expression.expression))
1150
+ continue;
1151
+ if (expression.expression.text !== "store")
1152
+ continue;
1153
+ const sig = expression.arguments[0];
1154
+ return sig && ts9.isPropertyAccessExpression(sig) ? sig.name.text : null;
1155
+ }
1156
+ }
1157
+ return;
1158
+ }
1159
+ static #fetchBindingsOf(sourceFile) {
1160
+ const names = new Set;
1161
+ for (const statement of sourceFile.statements) {
1162
+ if (!ts9.isImportDeclaration(statement) || statement.importClause?.isTypeOnly)
1163
+ continue;
1164
+ const bindings = statement.importClause?.namedBindings;
1165
+ if (!bindings || !ts9.isNamedImports(bindings))
1166
+ continue;
1167
+ for (const element of bindings.elements)
1168
+ if (!element.isTypeOnly && (element.propertyName ?? element.name).text === "fetch")
1169
+ names.add(element.name.text);
1170
+ }
1171
+ return names;
1172
+ }
1173
+ }
1174
+
1175
+ // pkgs/@akanjs/devkit/storeWriteScanner.ts
1176
+ class StoreWriteScanner {
1177
+ #index;
1178
+ constructor(index) {
1179
+ this.#index = index;
1180
+ }
1181
+ scan({ file, sourceFile }) {
1182
+ const source = new StoreSource({ file, sourceFile });
1183
+ return source.methods.flatMap((method) => {
1184
+ const targets = new Map;
1185
+ const path = new WritePath((call) => {
1186
+ const target = this.#index.writeOf(source, method, call);
1187
+ if (target)
1188
+ targets.set(call, target);
1189
+ return !!target;
1190
+ });
1191
+ const writes = path.along(method.body);
1192
+ const writeCount = path.countOf(writes);
1193
+ const second = writes[1] ?? writes[0];
1194
+ if (writeCount < 2 || !second)
1195
+ return [];
1196
+ return [
1197
+ {
1198
+ action: method.name,
1199
+ line: sourceFile.getLineAndCharacterOfPosition(second.getStart(sourceFile)).line + 1,
1200
+ writes: writes.map((call) => path.labelOf(call, sourceFile)),
1201
+ writeCount,
1202
+ isRootChain: writes.some((call) => StoreWriteScanner.#crossesStores(targets.get(call), method.store))
1203
+ }
1204
+ ];
1205
+ });
1206
+ }
1207
+ static #crossesStores(target, ownStore) {
1208
+ return target?.kind === "static" && target.store !== ownStore || target?.kind === "action" && !target.isOwn;
1209
+ }
1210
+ }
1211
+
1212
+ // pkgs/@akanjs/devkit/writePlacementScanner.ts
1213
+ import ts10 from "typescript";
1214
+ class WritePlacementScanner {
1215
+ #index;
1216
+ constructor(index) {
1217
+ this.#index = index;
1218
+ }
1219
+ scan(file, workspaceFile, sourceFile) {
1220
+ const fetchNames = StoreAccessScanner.localNamesOf(sourceFile, "fetch");
1221
+ const stNames = file.startsWith("lib/") ? new Set : StoreAccessScanner.stNamesOf(sourceFile);
1222
+ if (!fetchNames.size && !stNames.size)
1223
+ return null;
1224
+ const sites = [];
1225
+ const visit = (node) => {
1226
+ if (ts10.isPropertyAccessExpression(node) && this.#isWrite(node, workspaceFile, fetchNames, stNames))
1227
+ sites.push(node);
1228
+ ts10.forEachChild(node, visit);
1229
+ };
1230
+ visit(sourceFile);
1231
+ const first = sites[0];
1232
+ if (!first)
1233
+ return null;
1234
+ return {
1235
+ line: sourceFile.getLineAndCharacterOfPosition(first.getStart(sourceFile)).line + 1,
1236
+ writes: sites.map((site) => site.getText(sourceFile))
1237
+ };
1238
+ }
1239
+ #isWrite(access, workspaceFile, fetchNames, stNames) {
1240
+ const owner = access.expression;
1241
+ if (ts10.isIdentifier(owner) && fetchNames.has(owner.text))
1242
+ return this.#index.isMutation(workspaceFile, access.name.text);
1243
+ return ts10.isPropertyAccessExpression(owner) && owner.name.text === "do" && ts10.isIdentifier(owner.expression) && stNames.has(owner.expression.text) && this.#index.isWritingAction(access.name.text);
1244
+ }
1245
+ }
1246
+
1247
+ // pkgs/@akanjs/devkit/writingActionIndex.ts
1248
+ class WritingActionIndex {
1249
+ #mutations;
1250
+ #actions = new Set;
1251
+ #statics = new Set;
1252
+ constructor(mutations, storeFiles) {
1253
+ this.#mutations = mutations;
1254
+ const sources = storeFiles.map((storeFile) => new StoreSource(storeFile));
1255
+ for (const source of sources)
1256
+ for (const { refName } of source.stores) {
1257
+ const generated = refName ? StoreSource.generatedWritesOf(refName) : [];
1258
+ if (generated[0] && mutations.isMutation(source.file, generated[0]))
1259
+ for (const name of generated)
1260
+ this.#actions.add(name);
1261
+ }
1262
+ const methods = sources.flatMap((source) => source.methods.map((method) => ({ file: source.file, method, targets: source.targetsIn(method) })));
1263
+ let grew = true;
1264
+ while (grew) {
1265
+ grew = false;
1266
+ for (const { file, method, targets } of methods) {
1267
+ if (this.#holds(method) || !targets.some((target) => this.#writes(file, target)))
1268
+ continue;
1269
+ if (method.isStatic)
1270
+ this.#statics.add(`${method.store}.${method.name}`);
1271
+ else
1272
+ this.#actions.add(method.name);
1273
+ grew = true;
1274
+ }
1275
+ }
1276
+ }
1277
+ isWritingAction(name) {
1278
+ return this.#actions.has(name);
1279
+ }
1280
+ isMutation(consumerFile, name) {
1281
+ return this.#mutations.isMutation(consumerFile, name);
1282
+ }
1283
+ writeOf(source, method, call) {
1284
+ const target = source.targetOf(method, call);
1285
+ if (!target || !this.#writes(source.file, target))
1286
+ return null;
1287
+ const isSelf = target.kind !== "fetch" && target.name === method.name && (target.kind === "static" ? method.isStatic && target.store === method.store : !method.isStatic);
1288
+ return isSelf ? null : target;
1289
+ }
1290
+ #holds(method) {
1291
+ return method.isStatic ? this.#statics.has(`${method.store}.${method.name}`) : this.#actions.has(method.name);
1292
+ }
1293
+ #writes(file, target) {
1294
+ if (target.kind === "fetch")
1295
+ return this.#mutations.isMutation(file, target.name);
1296
+ if (target.kind === "action")
1297
+ return this.#actions.has(target.name);
1298
+ return this.#statics.has(`${target.store}.${target.name}`);
1299
+ }
1300
+ }
1301
+
1302
+ // pkgs/@akanjs/devkit/maintainabilityContract.ts
1303
+ class MaintainabilityContract {
1304
+ static ruleIds = [
1305
+ "akan.size.file",
1306
+ "akan.size.component",
1307
+ "akan.store.multi-write",
1308
+ "akan.store.root-write-chain",
1309
+ "akan.component.write-chain",
1310
+ "akan.component.store-access",
1311
+ "akan.write.placement",
1312
+ "akan.service.call-in-loop",
1313
+ "akan.baseline.growth"
1314
+ ];
1315
+ static #measuredFiles = "{lib,ui,webkit,srvkit,common,plugin}/**/*.{ts,tsx,md}";
1316
+ static #defaultBranches = ["upstream/HEAD", "upstream/main", "origin/HEAD", "origin/main", "main", "master"];
1317
+ #workspaceRoot;
1318
+ #scope;
1319
+ #libNames;
1320
+ constructor(workspaceRoot, scope, libNames = []) {
1321
+ this.#workspaceRoot = workspaceRoot;
1322
+ this.#scope = scope;
1323
+ this.#libNames = libNames.filter((libName) => scope.type === "app" || libName !== scope.name);
1324
+ }
1325
+ get sysPath() {
1326
+ return `${this.#scope.type}s/${this.#scope.name}`;
1327
+ }
1328
+ get baselinePath() {
1329
+ return path4.join(this.#workspaceRoot, this.sysPath, MaintainabilityBaseline.fileName);
1330
+ }
1331
+ async measure() {
1332
+ const [signalFiles, storeFiles, serviceFiles] = await Promise.all([
1333
+ this.#reachedSources("lib/**/*.signal.ts"),
1334
+ this.#reachedSources("lib/**/*.store.ts"),
1335
+ this.#reachedSources("lib/**/*.service.ts")
1336
+ ]);
1337
+ const index = new WritingActionIndex(new SignalMutationIndex(signalFiles), storeFiles);
1338
+ const reach = new EndpointReach(signalFiles, serviceFiles);
1339
+ const files = await MaintainabilityContract.#filesUnder(path4.join(this.#workspaceRoot, this.sysPath), MaintainabilityContract.#measuredFiles);
1340
+ const violations = await Promise.all(files.map((file) => this.#measureFile(file, index, reach)));
1341
+ return violations.flat().sort((a, b) => a.file < b.file ? -1 : a.file > b.file ? 1 : a.line - b.line);
1342
+ }
1343
+ async enforce({ fix }) {
1344
+ const [violations, existing, reference] = await Promise.all([
1345
+ this.measure(),
1346
+ this.#readBaseline(),
1347
+ this.#readReferenceBaseline()
1348
+ ]);
1349
+ const baseline = existing === null ? new MaintainabilityBaseline : MaintainabilityBaseline.parse(existing, this.baselinePath);
1350
+ const tightened = baseline.tightenedBy(violations);
1351
+ if (fix && existing !== null)
1352
+ await this.#tighten(baseline, tightened);
1353
+ const failures = violations.filter((violation) => !baseline.allows(violation)).map((violation) => {
1354
+ const recorded = baseline.recordedOf(violation);
1355
+ return recorded === undefined ? violation : { ...violation, recorded };
1356
+ });
1357
+ if (reference === null)
1358
+ return failures;
1359
+ const lines = (await this.#readBaseline() ?? "").split(/\r?\n/);
1360
+ const label = `${reference.ref}:${this.sysPath}/${MaintainabilityBaseline.fileName}`;
1361
+ const growths = (fix ? tightened : baseline).grownFrom(MaintainabilityBaseline.parse(reference.text, label, { lenient: true })).map(({ rule, ...growth }) => ({
1362
+ kind: "baselineGrowth",
1363
+ rule: "akan.baseline.growth",
1364
+ file: MaintainabilityBaseline.fileName,
1365
+ line: MaintainabilityContract.#lineOf(lines, rule, growth.key),
1366
+ debtRule: rule,
1367
+ reference: reference.ref,
1368
+ ...growth
1369
+ })).sort((a, b) => a.line - b.line);
1370
+ return [...growths, ...failures];
1371
+ }
1372
+ async seed({ force = false } = {}) {
1373
+ const violations = await this.measure();
1374
+ const exists = existsSync(this.baselinePath);
1375
+ if (exists && !force)
1376
+ return { result: "kept", violations };
1377
+ const next = MaintainabilityBaseline.of(violations, MaintainabilityContract.#reasonsIn(await this.#readBaseline()));
1378
+ if (!next.isEmpty)
1379
+ await writeFile(this.baselinePath, next.stringify());
1380
+ else if (exists)
1381
+ await rm(this.baselinePath, { force: true });
1382
+ return { result: next.isEmpty ? exists ? "removed" : "clean" : "written", violations };
1383
+ }
1384
+ describe(failures, commands) {
1385
+ return MaintainabilityReport.describe(this.sysPath, failures, commands);
1386
+ }
1387
+ async#measureFile(file, index, reach) {
1388
+ const maxLines = MaintainabilityLimits.fileMaxLinesOf(file);
1389
+ const isStore = file.endsWith(".store.ts");
1390
+ const isService = file.endsWith(".service.ts");
1391
+ const isClientCode = MaintainabilityLimits.isClientCode(file);
1392
+ if (!maxLines && !isStore && !isClientCode)
1393
+ return [];
1394
+ const workspaceFile = `${this.sysPath}/${file}`;
1395
+ const content = await readFile(path4.join(this.#workspaceRoot, workspaceFile), "utf8");
1396
+ const violations = [];
1397
+ const lineCount = MaintainabilityLimits.lineCountOf(content);
1398
+ if (maxLines && lineCount > maxLines && !MaintainabilityLimits.isReexportBarrel(file, content))
1399
+ violations.push({ kind: "size", rule: "akan.size.file", key: file, file, line: 1, lineCount, maxLines });
1400
+ if (!isStore && !isService && !isClientCode)
1401
+ return violations;
1402
+ const source = this.#sourceOf(workspaceFile, content);
1403
+ if (isClientCode)
1404
+ violations.push(...MaintainabilityContract.#measureClientCode(file, source, index));
1405
+ if (isStore)
1406
+ for (const { action, line, writes, writeCount, isRootChain } of new StoreWriteScanner(index).scan(source))
1407
+ violations.push({
1408
+ kind: "multiWrite",
1409
+ rule: isRootChain ? "akan.store.root-write-chain" : "akan.store.multi-write",
1410
+ key: `${file}#${action}`,
1411
+ file,
1412
+ line,
1413
+ owner: action,
1414
+ writes,
1415
+ writeCount
1416
+ });
1417
+ if (isService)
1418
+ for (const { method, line, calls } of new ServiceLoopCallScanner().scan(source.sourceFile, (method) => reach.reaches(EndpointReach.serviceOf(file), method)))
1419
+ violations.push({
1420
+ kind: "loopCall",
1421
+ rule: "akan.service.call-in-loop",
1422
+ key: `${file}#${method}`,
1423
+ file,
1424
+ line,
1425
+ owner: method,
1426
+ calls
1427
+ });
1428
+ return violations;
1429
+ }
1430
+ static #measureClientCode(file, { file: workspaceFile, sourceFile }, index) {
1431
+ const violations = [];
1432
+ const placement = new WritePlacementScanner(index).scan(file, workspaceFile, sourceFile);
1433
+ if (placement)
1434
+ violations.push({ kind: "writePlacement", rule: "akan.write.placement", key: file, file, ...placement });
1435
+ for (const component of new ComponentSizeScanner().measure(sourceFile))
1436
+ if (component.lineCount > MaintainabilityLimits.componentMaxLines)
1437
+ violations.push({
1438
+ kind: "size",
1439
+ rule: "akan.size.component",
1440
+ key: `${file}#${component.name}`,
1441
+ file,
1442
+ line: component.line,
1443
+ lineCount: component.lineCount,
1444
+ maxLines: MaintainabilityLimits.componentMaxLines,
1445
+ component: component.name
1446
+ });
1447
+ for (const { component, line, writes, writeCount } of new ComponentWriteChainScanner(index).scan(sourceFile))
1448
+ violations.push({
1449
+ kind: "multiWrite",
1450
+ rule: "akan.component.write-chain",
1451
+ key: `${file}#${component}`,
1452
+ file,
1453
+ line,
1454
+ owner: component,
1455
+ writes,
1456
+ writeCount
1457
+ });
1458
+ for (const { component, line, accessCount } of new StoreAccessScanner(index).measure(sourceFile))
1459
+ if (accessCount > MaintainabilityLimits.componentMaxStoreAccesses)
1460
+ violations.push({
1461
+ kind: "storeAccess",
1462
+ rule: "akan.component.store-access",
1463
+ key: `${file}#${component}`,
1464
+ file,
1465
+ line,
1466
+ component,
1467
+ accessCount,
1468
+ maxAccesses: MaintainabilityLimits.componentMaxStoreAccesses
1469
+ });
1470
+ return violations;
1471
+ }
1472
+ async#reachedSources(pattern) {
1473
+ const roots = [this.sysPath, ...this.#libNames.map((libName) => `libs/${libName}`)];
1474
+ const files = await Promise.all(roots.map(async (root) => (await MaintainabilityContract.#filesUnder(path4.join(this.#workspaceRoot, root), pattern)).map((file) => `${root}/${file}`)));
1475
+ return await Promise.all(files.flat().map(async (file) => this.#sourceOf(file, await readFile(path4.join(this.#workspaceRoot, file), "utf8"))));
1476
+ }
1477
+ #sourceOf(file, content) {
1478
+ const scriptKind = file.endsWith(".tsx") ? ts11.ScriptKind.TSX : ts11.ScriptKind.TS;
1479
+ return {
1480
+ file,
1481
+ absolutePath: path4.join(this.#workspaceRoot, file),
1482
+ content,
1483
+ sourceFile: ts11.createSourceFile(file, content, ts11.ScriptTarget.Latest, true, scriptKind)
1484
+ };
1485
+ }
1486
+ async#readBaseline() {
1487
+ return existsSync(this.baselinePath) ? await readFile(this.baselinePath, "utf8") : null;
1488
+ }
1489
+ async#readReferenceBaseline() {
1490
+ const ref = await this.#referenceRef();
1491
+ const text = await this.#git(["show", `${ref}:./${this.sysPath}/${MaintainabilityBaseline.fileName}`]);
1492
+ return text === null ? null : { ref: ref === "HEAD" ? ref : ref.slice(0, 12), text };
1493
+ }
1494
+ async#referenceRef() {
1495
+ for (const branch of MaintainabilityContract.#defaultBranches) {
1496
+ if (await this.#git(["rev-parse", "--verify", "--quiet", `${branch}^{commit}`]) === null)
1497
+ continue;
1498
+ const forkPoint = (await this.#git(["merge-base", "HEAD", branch]))?.trim();
1499
+ if (forkPoint)
1500
+ return forkPoint;
1501
+ throw new Error(MaintainabilityContract.#missingHistory(this.sysPath, `HEAD shares no commit with ${branch}`));
1502
+ }
1503
+ if ((await this.#git(["rev-parse", "--is-shallow-repository"]))?.trim() === "true")
1504
+ throw new Error(MaintainabilityContract.#missingHistory(this.sysPath, "this is a shallow clone"));
1505
+ return "HEAD";
1506
+ }
1507
+ static #missingHistory(sysPath, cause) {
1508
+ return `${sysPath}/${MaintainabilityBaseline.fileName} is compared with its copy where this branch forked from the default branch, ` + `but ${cause}. Fetch the default branch with its history (in GitHub Actions, actions/checkout with fetch-depth: 0).`;
1509
+ }
1510
+ async#git(args) {
1511
+ try {
1512
+ const proc = Bun.spawn(["git", ...args], { cwd: this.#workspaceRoot, stdout: "pipe", stderr: "ignore" });
1513
+ const [text, exitCode] = await Promise.all([new Response(proc.stdout).text(), proc.exited]);
1514
+ return exitCode === 0 ? text : null;
1515
+ } catch {
1516
+ return null;
1517
+ }
1518
+ }
1519
+ static #reasonsIn(text) {
1520
+ if (text === null)
1521
+ return new Map;
1522
+ try {
1523
+ return MaintainabilityBaseline.parse(text, MaintainabilityBaseline.fileName, { lenient: true }).reasons;
1524
+ } catch {
1525
+ return new Map;
1526
+ }
1527
+ }
1528
+ async#tighten(current, next) {
1529
+ if (next.isEmpty)
1530
+ await rm(this.baselinePath, { force: true });
1531
+ else if (next.stringify() !== current.stringify())
1532
+ await writeFile(this.baselinePath, next.stringify());
1533
+ }
1534
+ static #lineOf(lines, rule, key) {
1535
+ const from = Math.max(lines.findIndex((line) => line.includes(`${JSON.stringify(rule)}:`)), 0);
1536
+ const idx = lines.findIndex((line, lineIdx) => lineIdx >= from && line.includes(`${JSON.stringify(key)}:`));
1537
+ return Math.max(idx + 1, 1);
1538
+ }
1539
+ static async#filesUnder(root, pattern) {
1540
+ if (!existsSync(root))
1541
+ return [];
1542
+ const files = await Array.fromAsync(new Bun.Glob(pattern).scan({ cwd: root, onlyFiles: true }));
1543
+ return files.map((file) => file.split(path4.sep).join("/")).filter((file) => !file.includes("node_modules/")).sort((a, b) => a < b ? -1 : a > b ? 1 : 0);
1544
+ }
1545
+ }
1546
+
1547
+ // pkgs/@akanjs/cli/workspace/workspace.runner.ts
1548
+ import { Ed25519Key } from "akanjs/server/ed25519Key";
1549
+
1550
+ // pkgs/@akanjs/cli/workflows/maintainabilityPaths.ts
1551
+ class MaintainabilityPaths {
1552
+ static pathless = new Set([
1553
+ "akan.size.file",
1554
+ "akan.size.component",
1555
+ "akan.service.call-in-loop",
1556
+ "akan.baseline.growth"
1557
+ ]);
1558
+ #specs;
1559
+ constructor(specs = workflowSpecs) {
1560
+ this.#specs = specs;
1561
+ }
1562
+ static isRule(rule) {
1563
+ return MaintainabilityContract.ruleIds.includes(rule);
1564
+ }
1565
+ commandsOf(target) {
1566
+ const commands = {};
1567
+ for (const spec of this.#specs)
1568
+ for (const rule of (spec.replacesRules ?? []).filter(MaintainabilityPaths.isRule))
1569
+ commands[rule] = [...commands[rule] ?? [], MaintainabilityPaths.#planOf(spec, target)];
1570
+ return commands;
1571
+ }
1572
+ static #planOf(spec, target) {
1573
+ const flags = Object.entries(spec.inputs).filter(([, input]) => input.required).map(([name]) => {
1574
+ const flag = camelToKebabCase(name);
1575
+ return `--${flag} ${name in sysInputs ? target : `<${flag}>`}`;
1576
+ });
1577
+ return ["akan workflow plan", spec.name, ...flags].join(" ");
1578
+ }
1579
+ }
1580
+
1581
+ // pkgs/@akanjs/cli/workspace/workspace.runner.ts
1582
+ var defaultWorkspacePeerDependencies = new Set([
1583
+ "@react-spring/web",
1584
+ "@use-gesture/react",
1585
+ "chance",
1586
+ "react",
1587
+ "react-dom",
1588
+ "react-icons",
1589
+ "react-refresh",
1590
+ "react-server-dom-webpack",
1591
+ "react-spring",
1592
+ "scheduler",
1593
+ "tailwind-scrollbar",
1594
+ "tailwindcss",
1595
+ "typescript"
1596
+ ]);
1597
+ var defaultWorkspaceTypeDependencies = { "@types/react": "^19.3.0", "@types/react-dom": "^19.3.0" };
1598
+ var defaultMaxDiagnostics = 200;
1599
+
1600
+ class WorkspaceRunner extends runner("workspace") {
1601
+ async machineKeygen(workspace, out) {
1602
+ const file = path5.resolve(workspace.workspaceRoot, out);
1603
+ const { privatePem, publicKey } = Ed25519Key.generate();
1604
+ await mkdir(path5.dirname(file), { recursive: true });
1605
+ try {
1606
+ await writeFile2(file, privatePem, { mode: 384, flag: "wx" });
1607
+ } catch (error) {
1608
+ if (error.code === "EEXIST")
1609
+ throw new Error(`${file} exists; machine-keygen never overwrites a key. Name another file.`);
1610
+ throw error;
1611
+ }
1612
+ return { file, publicKey };
1613
+ }
1614
+ async generateAgentRules(workspace, { overwrite = false, cursorRules = true } = {}) {
1615
+ const [appNames] = await workspace.getExecs();
1616
+ const dict = { repoName: workspace.repoName, appName: appNames[0] ?? "app" };
1617
+ const templates = [
1618
+ [".", "workspaceRoot/AGENTS.md.template"],
1619
+ [".", "workspaceRoot/CLAUDE.md.template"],
1620
+ ...cursorRules ? [[".cursor/rules", "workspaceRoot/.cursor/rules/akan.mdc.template"]] : []
1621
+ ];
1622
+ const created = [];
1623
+ for (const [basePath, template] of templates)
1624
+ created.push(...await workspace.applyTemplate({ basePath, template, dict, overwrite }));
1625
+ return created;
1626
+ }
1627
+ async createWorkspace(repoName, appName, {
1628
+ dirname = ".",
1629
+ init = true,
1630
+ akanVersion,
1631
+ registryUrl,
1632
+ owner = ""
1633
+ }) {
1634
+ const cwdPath = process.cwd();
1635
+ const workspaceRoot = path5.resolve(cwdPath, dirname, repoName);
1636
+ const normalizedRegistryUrl = registryUrl ? getNpmRegistryUrl(registryUrl) : undefined;
1637
+ const workspace = WorkspaceExecutor.fromRoot({ workspaceRoot, repoName });
1638
+ const templateSpinner = workspace.spinning(`Creating workspace template files in ${workspaceRoot}...`);
1639
+ const latestTypesBunVersion = await getLatestPackageVersion("@types/bun", "latest", normalizedRegistryUrl);
1640
+ await workspace.applyTemplate({
1641
+ basePath: ".",
1642
+ template: "workspaceRoot",
1643
+ dict: { repoName, appName, serveDomain: "localhost", owner }
1644
+ });
1645
+ if (normalizedRegistryUrl)
1646
+ await workspace.writeFile(".npmrc", `registry=${normalizedRegistryUrl}/
1647
+ `);
1648
+ templateSpinner.succeed(`Workspace files created in ${workspaceRoot}`);
1649
+ const [rootPackageJson, peerDependencies] = await Promise.all([
1650
+ workspace.getPackageJson(),
1651
+ this.#getAkanPeerDependencies()
1652
+ ]);
1653
+ const { typescript, ...dependencies } = peerDependencies;
1654
+ const packageJson = {
1655
+ ...rootPackageJson,
1656
+ dependencies: {
1657
+ ...rootPackageJson.dependencies,
1658
+ ...dependencies,
1659
+ akanjs: akanVersion
1660
+ },
1661
+ devDependencies: {
1662
+ ...rootPackageJson.devDependencies,
1663
+ "@biomejs/biome": biomeVersion,
1664
+ "@types/bun": latestTypesBunVersion,
1665
+ ...defaultWorkspaceTypeDependencies,
1666
+ "@akanjs/devkit": akanVersion,
1667
+ "@akanjs/cli": akanVersion,
1668
+ ...typescript ? { typescript } : {}
1669
+ }
1670
+ };
1671
+ await workspace.setPackageJson(packageJson);
1672
+ if (init) {
1673
+ const installSpinner = workspace.spinning("Installing dependencies with bun...");
1674
+ await workspace.spawn("bun", ["install"]);
1675
+ installSpinner.succeed("Dependencies installed with bun");
1676
+ }
1677
+ return workspace;
1678
+ }
1679
+ async#getAkanPeerDependencies() {
1680
+ const [packageJson, cliPackageJson] = await Promise.all([this.#getAkanPackageJson(), this.#getCliPackageJson()]);
1681
+ const dependencyVersions = {
1682
+ ...packageJson.dependencies,
1683
+ ...packageJson.peerDependencies,
1684
+ ...cliPackageJson.dependencies
1685
+ };
1686
+ return Object.fromEntries(Object.entries(dependencyVersions).filter(([dependency]) => defaultWorkspacePeerDependencies.has(dependency)));
1687
+ }
1688
+ async#getCliPackageJson() {
1689
+ const found = await this.#findPackageJson("@akanjs/cli", [
1690
+ path5.join(import.meta.dir, "../package.json"),
1691
+ path5.join(import.meta.dir, "package.json"),
1692
+ path5.join(path5.dirname(Bun.main), "package.json")
1693
+ ]);
1694
+ return found ?? { name: "@akanjs/cli", version: "0.0.0", description: "@akanjs/cli" };
1695
+ }
1696
+ async#getAkanPackageJson() {
1697
+ const ancestors = [];
1698
+ for (let current = import.meta.dir, depth = 0;depth < 6; depth++) {
1699
+ ancestors.push(path5.join(current, "package.json"));
1700
+ if (path5.dirname(current) === current)
1701
+ break;
1702
+ current = path5.dirname(current);
1703
+ }
1704
+ const found = await this.#findPackageJson("akanjs", [
1705
+ path5.join(import.meta.dir, "../../../akanjs/package.json"),
1706
+ path5.join(process.cwd(), "pkgs/akanjs/package.json"),
1707
+ path5.join(path5.dirname(Bun.main), "node_modules/akanjs/package.json"),
1708
+ ...ancestors
1709
+ ]);
1710
+ if (!found)
1711
+ throw new Error(`[workspace] failed to locate akanjs package.json from ${import.meta.dir}`);
1712
+ return found;
1713
+ }
1714
+ async#findPackageJson(name, candidates) {
1715
+ try {
1716
+ candidates.unshift(Bun.resolveSync(`${name}/package.json`, import.meta.dir));
1717
+ } catch {}
1718
+ for (const packageJsonPath of candidates) {
1719
+ if (!await Bun.file(packageJsonPath).exists())
1720
+ continue;
1721
+ const packageJson = await FileSys2.readJson(packageJsonPath);
1722
+ if (packageJson.name === name)
1723
+ return packageJson;
1724
+ }
1725
+ return null;
1726
+ }
1727
+ async lint(exec, workspace, { fix = true, maxDiagnostics = defaultMaxDiagnostics } = {}) {
1728
+ const configPath = await WorkspaceRunner.resolveBiomeConfigPath(workspace);
1729
+ const [biome, ...biomeArgs] = Linter.biomeCommand(workspace.workspaceRoot);
1730
+ await workspace.spawn(biome, [
1731
+ ...biomeArgs,
1732
+ "check",
1733
+ ...fix ? ["--write"] : [],
1734
+ "--no-errors-on-unmatched",
1735
+ `--max-diagnostics=${maxDiagnostics > 0 ? maxDiagnostics : "none"}`,
1736
+ ...configPath ? ["--config-path", configPath] : [],
1737
+ exec.cwdPath
1738
+ ]);
1739
+ await this.#enforceStyleContract(exec);
1740
+ await this.#enforceRecipeGate(exec);
1741
+ await this.#enforceAgentsIndex(exec);
1742
+ await this.#enforceMaintainability(exec, fix);
1743
+ }
1744
+ async maintainabilityContractOf(exec) {
1745
+ const libNames = new Set;
1746
+ const visit = async (sys) => {
1747
+ for (const libName of (await sys.scan({ write: false })).getScanResult().libDeps) {
1748
+ if (libNames.has(libName))
1749
+ continue;
1750
+ libNames.add(libName);
1751
+ await visit(LibExecutor.from(exec, libName));
1752
+ }
1753
+ };
1754
+ await visit(exec);
1755
+ return new MaintainabilityContract(exec.workspace.workspaceRoot, { type: exec.type, name: exec.name }, [
1756
+ ...libNames
1757
+ ]);
1758
+ }
1759
+ static async resolveBiomeConfigPath(workspace) {
1760
+ for (const fileName of ["biome.json", "biome.jsonc"]) {
1761
+ const configPath = path5.join(workspace.workspaceRoot, fileName);
1762
+ if (await Bun.file(configPath).exists())
1763
+ return configPath;
1764
+ }
1765
+ return null;
1766
+ }
1767
+ async#enforceAgentsIndex(exec) {
1768
+ if (!(exec instanceof SysExecutor))
1769
+ return;
1770
+ const scope = { type: exec.type, name: exec.name };
1771
+ const scanInfo = await exec.scan({ write: false });
1772
+ const sources = await collectScopeRecipeSources(exec.workspace.workspaceRoot, scope, scanInfo.getScanResult().libDeps);
1773
+ const expected = renderScopeAgentBlock(scope, scanRecipes2(sources));
1774
+ const existing = await exec.exists("AGENTS.md") ? await exec.readFile("AGENTS.md") : null;
1775
+ const actual = existing ? extractAgentBlock(existing) : null;
1776
+ if (actual === expected.trim())
1777
+ return;
1778
+ throw new Error(`[agentsIndex] The recipe index in ${scope.type}s/${scope.name}/AGENTS.md is stale: it differs from the recipe ` + `sources. Run \`akan sync ${scope.name}\` to regenerate it.`);
1779
+ }
1780
+ async#enforceMaintainability(exec, fix) {
1781
+ if (!(exec instanceof SysExecutor))
1782
+ return;
1783
+ const contract = await this.maintainabilityContractOf(exec);
1784
+ const failures = await contract.enforce({ fix });
1785
+ if (failures.length)
1786
+ throw new Error(contract.describe(failures, new MaintainabilityPaths().commandsOf(exec.name)));
1787
+ }
1788
+ async#enforceRecipeGate(exec) {
1789
+ const cwdPath = exec.cwdPath;
1790
+ if (!cwdPath)
1791
+ return;
1792
+ const uiDir = path5.join(cwdPath, "ui");
1793
+ const sources = [
1794
+ ...await collectRecipeSources2(uiDir, "ui/Recipe"),
1795
+ ...await collectRecipeSources2(uiDir, "ui/recipe", "recipe")
1796
+ ];
1797
+ if (sources.length === 0)
1798
+ return;
1799
+ const offenders = scanRecipes2(sources).filter((recipe) => !Object.values(recipe.variants).some((values) => values.length >= 2 || values.length === 1 && values[0] === "true"));
1800
+ if (offenders.length === 0)
1801
+ return;
1802
+ throw new Error(`[recipeGate] variant-less recipe(s): ${[...new Set(offenders.map((recipe) => recipe.name))].join(", ")}
1803
+ ` + "A look with nothing to pick is not a recipe: promote one that has its own markup to a component, and keep " + "a skin passed into another component's className as a shared class constant.");
1804
+ }
1805
+ async#enforceStyleContract(exec) {
1806
+ const cwdPath = exec.cwdPath;
1807
+ if (!cwdPath)
1808
+ return;
1809
+ const stylesCssPath = path5.join(cwdPath, "page", "styles.css");
1810
+ if (!await Bun.file(stylesCssPath).exists())
1811
+ return;
1812
+ const violations = {
1813
+ theme: new ThemeValidator().validate(await Bun.file(stylesCssPath).text())
1814
+ };
1815
+ const blocking = countBlocking(violations);
1816
+ if (blocking === 0)
1817
+ return;
1818
+ throw new Error(`[themeValidator] ${blocking} blocking contrast violation(s):
1819
+ ${formatStyleContract(violations)}
1820
+
1821
+ ` + "Raise the foreground/background contrast of these theme token values to the WCAG threshold.");
1822
+ }
1823
+ async writeTopLevelEnv(workspace, devProjectId) {
1824
+ await workspace.writeFile(".env", `AKAN_WORKSPACE_ID=${devProjectId}
1825
+
1826
+ # organization configuration, no need to change
1827
+ AKAN_PUBLIC_REPO_NAME=${workspace.repoName}
1828
+
1829
+ # serve domain, it changes the domain of the server.
1830
+ AKAN_PUBLIC_SERVE_DOMAIN=try.akanjs.com
1831
+
1832
+ # development branch, debug, develop, main, etc. mainly it changes databases.
1833
+ AKAN_PUBLIC_ENV=local
1834
+
1835
+ # local, cloud, edge it changes the connection point of the clients.
1836
+ AKAN_PUBLIC_OPERATION_MODE=local
1837
+
1838
+ # log level, debug, info, warn, error
1839
+ AKAN_PUBLIC_LOG_LEVEL=debug
1840
+ `);
1841
+ }
1842
+ }
1843
+
1844
+ export { MaintainabilityBaseline, AbstractDoc, SignalMutationIndex, defaultMaxDiagnostics, WorkspaceRunner };