@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
@@ -3,7 +3,7 @@ import {
3
3
  Workspace,
4
4
  script,
5
5
  command
6
- } from "./index-qmeh0s05.js";
6
+ } from "./index-00ke4phc.js";
7
7
  import"./index-52w0fvh8.js";
8
8
  import {
9
9
  rootAllowedFiles,
@@ -11,83 +11,190 @@ import {
11
11
  isAllowedLibFacetRootFile,
12
12
  libFacetRootHintOf,
13
13
  facetIndexShadowOf,
14
- rootEntryHintOf
15
- } from "./index-1e2955yd.js";
14
+ rootEntryHintOf,
15
+ AppExecutor,
16
+ LibExecutor
17
+ } from "./index-921cxqrd.js";
18
+ import {
19
+ MaintainabilityBaseline,
20
+ AbstractDoc,
21
+ SignalMutationIndex,
22
+ WorkspaceRunner
23
+ } from "./index-hvg3esm0.js";
24
+ import"./index-62md4dwy.js";
25
+ import"./index-hj6w4ka1.js";
26
+ import"./index-vgt25eh1.js";
16
27
 
17
28
  // pkgs/@akanjs/devkit/qualityScanner.ts
18
29
  import { createHash } from "crypto";
19
- import { readdir, readFile, stat } from "fs/promises";
20
- import path2 from "path";
30
+ import { readdir as readdir2, readFile as readFile2, stat } from "fs/promises";
31
+ import path4 from "path";
21
32
  import { RESERVED_ROUTE_CONFIG_EXPORTS } from "akanjs/common";
22
33
  import ignore from "ignore";
23
- import ts5 from "typescript";
34
+ import ts8 from "typescript";
24
35
 
25
- // pkgs/@akanjs/devkit/abstractDoc.ts
36
+ // pkgs/@akanjs/devkit/commentDensityScanner.ts
26
37
  import path from "path";
38
+ import ts2 from "typescript";
39
+
40
+ // pkgs/@akanjs/devkit/sourceComments.ts
41
+ import ts from "typescript";
42
+
43
+ class SourceComments {
44
+ static #scanner = ts.createScanner(ts.ScriptTarget.Latest, false);
45
+ static of(sourceFile) {
46
+ const comments = [];
47
+ const scanGap = (start, end) => {
48
+ if (end <= start)
49
+ return;
50
+ const scanner = SourceComments.#scanner;
51
+ scanner.setText(sourceFile.text, start, end - start);
52
+ for (let kind = scanner.scan();kind !== ts.SyntaxKind.EndOfFileToken; kind = scanner.scan()) {
53
+ if (kind !== ts.SyntaxKind.SingleLineCommentTrivia && kind !== ts.SyntaxKind.MultiLineCommentTrivia)
54
+ continue;
55
+ comments.push(SourceComments.#commentOf(sourceFile, scanner.getTokenStart(), scanner.getTokenText()));
56
+ }
57
+ scanner.setText(undefined);
58
+ };
59
+ const visit = (node) => {
60
+ if (node.kind === ts.SyntaxKind.JsxText)
61
+ return;
62
+ if (ts.isToken(node)) {
63
+ scanGap(node.pos, node.getStart(sourceFile));
64
+ return;
65
+ }
66
+ const children = [];
67
+ ts.forEachChild(node, (child) => {
68
+ children.push(child);
69
+ }, (nodes) => {
70
+ children.push(...nodes);
71
+ });
72
+ let cursor = node.pos;
73
+ for (const child of children) {
74
+ scanGap(cursor, child.pos);
75
+ visit(child);
76
+ cursor = Math.max(cursor, child.end);
77
+ }
78
+ scanGap(cursor, node.end);
79
+ };
80
+ visit(sourceFile);
81
+ return comments;
82
+ }
83
+ static #commentOf(sourceFile, pos, raw) {
84
+ return {
85
+ raw,
86
+ line: sourceFile.getLineAndCharacterOfPosition(pos).line + 1,
87
+ isJsDoc: raw.startsWith("/**") && !raw.startsWith("/**/"),
88
+ body: SourceComments.#bodyOf(raw)
89
+ };
90
+ }
91
+ static #bodyOf(raw) {
92
+ if (raw.startsWith("//"))
93
+ return [raw.replace(/^\/\/+/, "").trim()];
94
+ return raw.slice(2, raw.endsWith("*/") ? -2 : undefined).split(/\r?\n/).map((line) => line.replace(/^\s*\*+/, "").trim());
95
+ }
96
+ }
97
+
98
+ // pkgs/@akanjs/devkit/commentDensityScanner.ts
99
+ class CommentDensityScanner {
100
+ static rule = "akan.comment.density";
101
+ static maxShare = 0.01;
102
+ static minCommentLineNum = 5;
103
+ static #directive = /^(?:biome-ignore|@ts-(?:expect-error|ignore|nocheck|check)\b|eslint-(?:disable|enable)|<reference\b)/;
104
+ static #scaffoldMarkers = new Set(["state", "action"]);
105
+ scan(sourceFiles) {
106
+ const tallies = new Map;
107
+ for (const sourceFile of sourceFiles) {
108
+ const unit = CommentDensityScanner.#unitOf(sourceFile.file);
109
+ if (!unit || !CommentDensityScanner.#isMeasured(sourceFile))
110
+ continue;
111
+ const tally = tallies.get(unit) ?? { lineNum: 0, commentLineNum: 0, files: [] };
112
+ const commentLines = CommentDensityScanner.#commentLinesOf(sourceFile);
113
+ tally.lineNum += sourceFile.content.split(/\r?\n/).filter((line) => line.trim() !== "").length;
114
+ tally.commentLineNum += commentLines.length;
115
+ if (commentLines[0] !== undefined)
116
+ tally.files.push({ file: sourceFile.file, line: commentLines[0], commentLineNum: commentLines.length });
117
+ tallies.set(unit, tally);
118
+ }
119
+ return [...tallies].filter(([, tally]) => CommentDensityScanner.#isDense(tally)).map(([unit, tally]) => CommentDensityScanner.#warningOf(unit, tally));
120
+ }
121
+ static #commentLinesOf({ file, sourceFile }) {
122
+ const isRecipe = file.includes("/ui/Recipe/");
123
+ const lines = new Set;
124
+ for (const comment of SourceComments.of(sourceFile)) {
125
+ if (CommentDensityScanner.#isExempt(comment))
126
+ continue;
127
+ const contentIdxs = comment.body.flatMap((text, idx) => text ? [idx] : []);
128
+ const countedIdxs = isRecipe && comment.isJsDoc ? contentIdxs.slice(1) : contentIdxs;
129
+ for (const idx of countedIdxs)
130
+ lines.add(comment.line + idx);
131
+ }
132
+ return [...lines].sort((a, b) => a - b);
133
+ }
134
+ static #isExempt({ raw, body }) {
135
+ const head = body.find((text) => text !== "") ?? "";
136
+ if (CommentDensityScanner.#directive.test(head))
137
+ return true;
138
+ return raw.startsWith("//") && CommentDensityScanner.#scaffoldMarkers.has(head.toLowerCase());
139
+ }
140
+ static #isDense({ lineNum, commentLineNum }) {
141
+ return commentLineNum >= CommentDensityScanner.minCommentLineNum && commentLineNum > lineNum * CommentDensityScanner.maxShare;
142
+ }
143
+ static #warningOf(unit, { lineNum, commentLineNum, files }) {
144
+ const [primary] = [...files].sort((a, b) => b.commentLineNum - a.commentLineNum);
145
+ const share = (commentLineNum / lineNum * 100).toFixed(2);
146
+ return {
147
+ rule: CommentDensityScanner.rule,
148
+ scope: "comment",
149
+ severity: "warning",
150
+ file: primary?.file ?? unit,
151
+ line: primary?.line,
152
+ message: `${unit} is ${share}% comments (${commentLineNum} of ${lineNum} non-blank lines); product lib/ and ui/ code stays under ${CommentDensityScanner.maxShare * 100}%.`,
153
+ ...files.length > 1 ? { locations: files.map(({ file, line }) => ({ file, line })) } : {}
154
+ };
155
+ }
156
+ static #unitOf(file) {
157
+ const segments = file.split("/");
158
+ if (segments[0] !== "apps" && segments[0] !== "libs" || segments.length < 4)
159
+ return null;
160
+ if (segments[2] === "ui")
161
+ return segments.slice(0, 4).join("/");
162
+ if (segments[2] !== "lib")
163
+ return null;
164
+ const depth = segments[3] === "__scalar" ? 5 : 4;
165
+ return segments.length > depth ? segments.slice(0, depth).join("/") : null;
166
+ }
167
+ static #isMeasured({ file, sourceFile }) {
168
+ if (/\.(test|spec)\.tsx?$/.test(file) || path.basename(file) === "guards.ts")
169
+ return false;
170
+ return !sourceFile.statements.every((statement) => ts2.isExportDeclaration(statement) || ts2.isExpressionStatement(statement) && ts2.isStringLiteral(statement.expression));
171
+ }
172
+ }
27
173
 
28
- class AbstractDoc {
29
- path;
30
- content;
31
- siblingFiles;
32
- static suffix = ".abstract.md";
33
- static maxLines = 300;
34
- static #facetRoots = "{lib,ui,webkit,srvkit,common,plugin}";
35
- static isAbstractPath(filePath) {
36
- return filePath.endsWith(AbstractDoc.suffix);
37
- }
38
- static lineCountOf(content) {
39
- return content.split(/\r?\n/).length;
40
- }
41
- static kindOf(filePath) {
42
- const [root, folder, ...rest] = filePath.split("/");
43
- if (root !== "lib" || !folder)
44
- return "other";
45
- if (folder === "__scalar")
46
- return rest.length === 2 ? "scalar" : "other";
47
- if (rest.length !== 1)
48
- return "other";
49
- return folder.startsWith("_") ? "service" : "domain";
50
- }
51
- static async findAll(sys, { module } = {}) {
52
- const filePaths = (await sys.getAllFiles(`${AbstractDoc.#facetRoots}/**/*${AbstractDoc.suffix}`)).map((filePath) => filePath.split(path.sep).join("/")).sort((a, b) => a < b ? -1 : a > b ? 1 : 0);
53
- const docs = await Promise.all(filePaths.map((filePath) => AbstractDoc.read(sys, filePath)));
54
- if (!module)
55
- return docs;
56
- return docs.filter((doc) => doc.moduleName === module || doc.folderName === module);
57
- }
58
- static async read(sys, filePath) {
59
- const dirPath = filePath.split("/").slice(0, -1).join("/");
60
- const [content, folderFiles] = await Promise.all([sys.readFile(filePath), sys.readdir(dirPath)]);
61
- return new AbstractDoc(filePath, content, folderFiles.filter((fileName) => !AbstractDoc.isAbstractPath(fileName)));
62
- }
63
- constructor(path2, content, siblingFiles) {
64
- this.path = path2;
65
- this.content = content;
66
- this.siblingFiles = siblingFiles;
67
- }
68
- get kind() {
69
- return AbstractDoc.kindOf(this.path);
70
- }
71
- get folderName() {
72
- return this.path.split("/").at(-2) ?? "";
73
- }
74
- get moduleName() {
75
- return (this.path.split("/").at(-1) ?? "").slice(0, -AbstractDoc.suffix.length);
76
- }
77
- get lineCount() {
78
- return AbstractDoc.lineCountOf(this.content);
79
- }
80
- canReplaceWith(candidate) {
81
- const next = candidate.trim();
82
- if (!next.startsWith("#"))
174
+ // pkgs/@akanjs/devkit/deprecatedCommentScanner.ts
175
+ class DeprecatedCommentScanner {
176
+ static rule = "akan.comment.deprecated-marker";
177
+ static #marker = /^[!?*\s]*(?:(?:TODO|FIXME|XXX|NOTE)\b\s*:?\s*)?@?deprecated\b/i;
178
+ scan(sourceFiles) {
179
+ return sourceFiles.filter(({ file }) => /^(apps|libs)\//.test(file) && !/\.(test|spec)\.tsx?$/.test(file)).flatMap(({ file, sourceFile }) => SourceComments.of(sourceFile).filter((comment) => DeprecatedCommentScanner.#isLooseMarker(comment)).map((comment) => ({
180
+ rule: DeprecatedCommentScanner.rule,
181
+ scope: "comment",
182
+ severity: "warning",
183
+ file,
184
+ line: comment.line,
185
+ message: `"${comment.raw.split(/\r?\n/)[0]?.trim().slice(0, 80)}" marks nothing at the use sites; editors strike through only a JSDoc @deprecated tag.`
186
+ })));
187
+ }
188
+ static #isLooseMarker({ isJsDoc, body }) {
189
+ const text = body.filter((line) => line !== "").join(" ");
190
+ if (isJsDoc && /(^|\s)@deprecated\b/.test(text))
83
191
  return false;
84
- const lineCount = AbstractDoc.lineCountOf(next);
85
- return lineCount >= 3 && lineCount < this.lineCount;
192
+ return DeprecatedCommentScanner.#marker.test(text);
86
193
  }
87
194
  }
88
195
 
89
196
  // pkgs/@akanjs/devkit/formSetterScanner.ts
90
- import ts from "typescript";
197
+ import ts3 from "typescript";
91
198
 
92
199
  class FormSetterScanner {
93
200
  static #fieldSetter = /^set[A-Za-z0-9_$]*On[A-Za-z0-9_$]*$/;
@@ -97,12 +204,12 @@ class FormSetterScanner {
97
204
  #scanFile({ file, sourceFile }) {
98
205
  const wrapped = [];
99
206
  const visit = (node) => {
100
- if (ts.isJsxAttribute(node)) {
207
+ if (ts3.isJsxAttribute(node)) {
101
208
  const setter = FormSetterScanner.#wrappedSetterOf(node);
102
209
  if (setter)
103
210
  wrapped.push({ setter, line: FormSetterScanner.#lineOf(sourceFile, node) });
104
211
  }
105
- ts.forEachChild(node, visit);
212
+ ts3.forEachChild(node, visit);
106
213
  };
107
214
  visit(sourceFile);
108
215
  if (!wrapped.length)
@@ -121,13 +228,13 @@ class FormSetterScanner {
121
228
  ];
122
229
  }
123
230
  static #wrappedSetterOf(attribute) {
124
- if (!ts.isIdentifier(attribute.name) || !/^on[A-Z]/.test(attribute.name.text))
231
+ if (!ts3.isIdentifier(attribute.name) || !/^on[A-Z]/.test(attribute.name.text))
125
232
  return null;
126
233
  const initializer = attribute.initializer;
127
- if (!initializer || !ts.isJsxExpression(initializer) || !initializer.expression)
234
+ if (!initializer || !ts3.isJsxExpression(initializer) || !initializer.expression)
128
235
  return null;
129
236
  const handler = initializer.expression;
130
- if (!ts.isArrowFunction(handler) && !ts.isFunctionExpression(handler))
237
+ if (!ts3.isArrowFunction(handler) && !ts3.isFunctionExpression(handler))
131
238
  return null;
132
239
  if (!handler.parameters.length)
133
240
  return null;
@@ -138,14 +245,14 @@ class FormSetterScanner {
138
245
  const visit = (current) => {
139
246
  if (found)
140
247
  return;
141
- if (ts.isCallExpression(current) && ts.isPropertyAccessExpression(current.expression)) {
248
+ if (ts3.isCallExpression(current) && ts3.isPropertyAccessExpression(current.expression)) {
142
249
  const { expression, name } = current.expression;
143
- if (ts.isPropertyAccessExpression(expression) && ts.isIdentifier(expression.expression) && expression.expression.text === "st" && expression.name.text === "do" && FormSetterScanner.#fieldSetter.test(name.text)) {
250
+ if (ts3.isPropertyAccessExpression(expression) && ts3.isIdentifier(expression.expression) && expression.expression.text === "st" && expression.name.text === "do" && FormSetterScanner.#fieldSetter.test(name.text)) {
144
251
  found = name.text;
145
252
  return;
146
253
  }
147
254
  }
148
- ts.forEachChild(current, visit);
255
+ ts3.forEachChild(current, visit);
149
256
  };
150
257
  visit(node);
151
258
  return found;
@@ -155,11 +262,207 @@ class FormSetterScanner {
155
262
  }
156
263
  }
157
264
 
158
- // pkgs/@akanjs/devkit/ssrScanner.ts
265
+ // pkgs/@akanjs/devkit/kindBranchScanner.ts
266
+ import path2 from "path";
159
267
  import ts4 from "typescript";
160
268
 
269
+ class KindBranchScanner {
270
+ static rule = "akan.global.kind-branch";
271
+ static minFileNum = 3;
272
+ static #kindName = /(Kind|Type|Mode)$/;
273
+ static #kindSubject = /^(kind|type|mode)$|[a-z](Kind|Type|Mode)$/;
274
+ static #equalities = new Set([
275
+ ts4.SyntaxKind.EqualsEqualsEqualsToken,
276
+ ts4.SyntaxKind.ExclamationEqualsEqualsToken,
277
+ ts4.SyntaxKind.EqualsEqualsToken,
278
+ ts4.SyntaxKind.ExclamationEqualsToken
279
+ ]);
280
+ scan(sourceFiles) {
281
+ const enums = sourceFiles.flatMap((sourceFile) => KindBranchScanner.#enumsOf(sourceFile));
282
+ const ownersByValue = new Map;
283
+ for (const declaration of enums)
284
+ for (const value of declaration.values)
285
+ ownersByValue.set(value, [...ownersByValue.get(value) ?? [], declaration]);
286
+ const sitesByGroup = new Map;
287
+ for (const sourceFile of sourceFiles) {
288
+ if (!/^(apps|libs)\//.test(sourceFile.file) || /\.(test|spec)\.tsx?$/.test(sourceFile.file))
289
+ continue;
290
+ const sys = KindBranchScanner.#sysOf(sourceFile.file);
291
+ for (const site of KindBranchScanner.#sitesIn(sourceFile, ownersByValue)) {
292
+ const owners = (ownersByValue.get(site.value) ?? []).filter((owner) => owner.sys === sys || owner.sys.startsWith("libs/") && sys.startsWith("apps/"));
293
+ if (!owners.length || owners.some(({ module }) => site.file.startsWith(module)))
294
+ continue;
295
+ const group = owners.map(({ name, file }) => `${file}#${name}`).join(",");
296
+ const entry = sitesByGroup.get(group) ?? { owners, sites: [] };
297
+ entry.sites.push(site);
298
+ sitesByGroup.set(group, entry);
299
+ }
300
+ }
301
+ return [...sitesByGroup.values()].flatMap(({ owners, sites }) => KindBranchScanner.#warningOf(owners, sites));
302
+ }
303
+ static #warningOf(owners, sites) {
304
+ const filesByValue = new Map;
305
+ for (const { value, file } of sites)
306
+ filesByValue.set(value, (filesByValue.get(value) ?? new Set).add(file));
307
+ const values = [...filesByValue].filter(([, files]) => files.size >= KindBranchScanner.minFileNum).map(([value]) => value).sort((a, b) => a < b ? -1 : a > b ? 1 : 0);
308
+ const [owner] = owners;
309
+ if (!owner || !values.length)
310
+ return [];
311
+ const branched = sites.filter(({ value }) => values.includes(value));
312
+ const fileNum = new Set(branched.map(({ file }) => file)).size;
313
+ const enumNames = owners.map(({ name }) => `cnst.${name}`).join(" / ");
314
+ return [
315
+ {
316
+ rule: KindBranchScanner.rule,
317
+ scope: "global",
318
+ severity: "warning",
319
+ file: owner.file,
320
+ line: owner.line,
321
+ message: `${values.map((value) => `"${value}"`).join(", ")} of ${enumNames} ${values.length > 1 ? "are" : "is"} branched on in ${fileNum} files outside the enum's module.`,
322
+ locations: branched.map(({ file, line }) => ({ file, line })),
323
+ fix: `Declare one table keyed by the kind, \`{ [kind in cnst.${owner.name}["value"]]: \u2026 }\` (a component, label or handler per kind), and look the kind up in it instead of comparing it in each file.`
324
+ }
325
+ ];
326
+ }
327
+ static #sitesIn({ file, sourceFile }, ownersByValue) {
328
+ const sites = [];
329
+ const record = (literal, subject) => {
330
+ if (!ts4.isStringLiteralLike(literal) || !ownersByValue.has(literal.text))
331
+ return;
332
+ if (!KindBranchScanner.#isKindSubject(subject))
333
+ return;
334
+ sites.push({
335
+ value: literal.text,
336
+ file,
337
+ line: sourceFile.getLineAndCharacterOfPosition(literal.getStart(sourceFile)).line + 1
338
+ });
339
+ };
340
+ const visit = (node) => {
341
+ if (ts4.isBinaryExpression(node) && KindBranchScanner.#equalities.has(node.operatorToken.kind)) {
342
+ record(node.left, node.right);
343
+ record(node.right, node.left);
344
+ } else if (ts4.isCaseClause(node) && ts4.isSwitchStatement(node.parent.parent))
345
+ record(node.expression, node.parent.parent.expression);
346
+ ts4.forEachChild(node, visit);
347
+ };
348
+ visit(sourceFile);
349
+ return sites;
350
+ }
351
+ static #isKindSubject(subject) {
352
+ let current = subject;
353
+ while (ts4.isParenthesizedExpression(current) || ts4.isAsExpression(current) || ts4.isNonNullExpression(current))
354
+ current = current.expression;
355
+ const name = ts4.isIdentifier(current) ? current.text : ts4.isPropertyAccessExpression(current) ? current.name.text : ts4.isElementAccessExpression(current) && ts4.isStringLiteralLike(current.argumentExpression) ? current.argumentExpression.text : "";
356
+ return KindBranchScanner.#kindSubject.test(name);
357
+ }
358
+ static #enumsOf({ file, sourceFile }) {
359
+ if (!/^(apps|libs)\/[^/]+\/lib\/.+\.constant\.ts$/.test(file))
360
+ return [];
361
+ return sourceFile.statements.flatMap((statement) => {
362
+ if (!ts4.isClassDeclaration(statement) || !statement.name)
363
+ return [];
364
+ if (!KindBranchScanner.#kindName.test(statement.name.text))
365
+ return [];
366
+ const values = KindBranchScanner.#enumValuesOf(statement);
367
+ if (!values)
368
+ return [];
369
+ return [
370
+ {
371
+ name: statement.name.text,
372
+ sys: KindBranchScanner.#sysOf(file),
373
+ file,
374
+ line: sourceFile.getLineAndCharacterOfPosition(statement.getStart(sourceFile)).line + 1,
375
+ module: `${path2.posix.dirname(file)}/`,
376
+ values
377
+ }
378
+ ];
379
+ });
380
+ }
381
+ static #sysOf(file) {
382
+ return file.split("/").slice(0, 2).join("/");
383
+ }
384
+ static #enumValuesOf(statement) {
385
+ for (const clause of statement.heritageClauses ?? [])
386
+ for (const { expression } of clause.types) {
387
+ if (!ts4.isCallExpression(expression) || !ts4.isIdentifier(expression.expression))
388
+ continue;
389
+ if (expression.expression.text !== "enumOf")
390
+ continue;
391
+ let list = expression.arguments[1];
392
+ while (list && (ts4.isAsExpression(list) || ts4.isParenthesizedExpression(list)))
393
+ list = list.expression;
394
+ if (!list || !ts4.isArrayLiteralExpression(list))
395
+ return null;
396
+ return list.elements.filter(ts4.isStringLiteralLike).map(({ text }) => text);
397
+ }
398
+ return null;
399
+ }
400
+ }
401
+
402
+ // pkgs/@akanjs/devkit/maintainabilityExceptionScanner.ts
403
+ import { existsSync } from "fs";
404
+ import { readdir, readFile } from "fs/promises";
405
+ import path3 from "path";
406
+ class MaintainabilityExceptionScanner {
407
+ static rule = "akan.baseline.exceptions";
408
+ static #shapeFix = "Many reasoned exceptions under one rule mean its threshold is wrong: fix the limit in MaintainabilityLimits rather than record another. Otherwise shrink the code, and `akan lint` lowers each entry and drops it once it passes.";
409
+ static #correctnessFix = "A write rule takes no exception: send the writes through one store action and one endpoint (`akan workflow plan add-mutation`), and `akan lint` drops the entry.";
410
+ async scan(workspaceRoot) {
411
+ const sysPaths = await Promise.all(["apps", "libs"].map(async (sysRoot) => {
412
+ const absoluteRoot = path3.join(workspaceRoot, sysRoot);
413
+ if (!existsSync(absoluteRoot))
414
+ return [];
415
+ const entries = await readdir(absoluteRoot, { withFileTypes: true });
416
+ return entries.filter((entry) => entry.isDirectory()).map((entry) => `${sysRoot}/${entry.name}`);
417
+ }));
418
+ const warnings = await Promise.all(sysPaths.flat().map((sysPath) => MaintainabilityExceptionScanner.#scanSys(workspaceRoot, sysPath)));
419
+ return warnings.flat();
420
+ }
421
+ static async#scanSys(workspaceRoot, sysPath) {
422
+ const file = `${sysPath}/${MaintainabilityBaseline.fileName}`;
423
+ const absolutePath = path3.join(workspaceRoot, file);
424
+ if (!existsSync(absolutePath))
425
+ return [];
426
+ const text = await readFile(absolutePath, "utf8");
427
+ let baseline;
428
+ try {
429
+ baseline = MaintainabilityBaseline.parse(text, file);
430
+ } catch {
431
+ return [];
432
+ }
433
+ const lines = text.split(/\r?\n/);
434
+ return [...baseline.entriesByRule()].map(([rule, entries]) => MaintainabilityExceptionScanner.#warningOf(sysPath, file, lines, rule, entries));
435
+ }
436
+ static #warningOf(sysPath, file, lines, rule, entries) {
437
+ const reasonedNum = entries.filter(({ reason }) => reason !== undefined).length;
438
+ const adoptedNum = entries.length - reasonedNum;
439
+ const listed = entries.map(({ key, reason }) => reason === undefined ? key : `${key} (${JSON.stringify(reason)})`);
440
+ const locations = entries.map(({ key }) => ({
441
+ file,
442
+ line: MaintainabilityExceptionScanner.#lineOf(lines, rule, key)
443
+ }));
444
+ return {
445
+ rule: MaintainabilityExceptionScanner.rule,
446
+ scope: "file",
447
+ severity: "warning",
448
+ file,
449
+ line: locations[0]?.line ?? 1,
450
+ message: `${sysPath} carries ${reasonedNum} reasoned exception${reasonedNum === 1 ? "" : "s"} and ${adoptedNum} adopted-debt entr${adoptedNum === 1 ? "y" : "ies"} for ${rule}: ${listed.join(", ")}.`,
451
+ locations,
452
+ fix: MaintainabilityBaseline.reasonedRules.has(rule) ? MaintainabilityExceptionScanner.#shapeFix : MaintainabilityExceptionScanner.#correctnessFix
453
+ };
454
+ }
455
+ static #lineOf(lines, rule, key) {
456
+ const from = Math.max(lines.findIndex((line) => line.includes(`${JSON.stringify(rule)}:`)), 0);
457
+ return Math.max(lines.findIndex((line, idx) => idx >= from && line.includes(`${JSON.stringify(key)}:`)) + 1, 1);
458
+ }
459
+ }
460
+
461
+ // pkgs/@akanjs/devkit/ssrScanner.ts
462
+ import ts6 from "typescript";
463
+
161
464
  // pkgs/@akanjs/devkit/renderMutationScanner.ts
162
- import ts2 from "typescript";
465
+ import ts5 from "typescript";
163
466
 
164
467
  class RenderMutationScanner {
165
468
  static rule = "akan.ssr.render-mutation";
@@ -188,7 +491,7 @@ class RenderMutationScanner {
188
491
  const helper = follow ? RenderMutationScanner.#helperOf(node, functions) : undefined;
189
492
  if (helper)
190
493
  helpers.add(helper);
191
- ts2.forEachChild(node, (child) => visit(child, follow));
494
+ ts5.forEachChild(node, (child) => visit(child, follow));
192
495
  };
193
496
  for (const body of RenderMutationScanner.#renderBodiesOf(sourceFile, functions))
194
497
  visit(body, true);
@@ -205,7 +508,7 @@ class RenderMutationScanner {
205
508
  }));
206
509
  }
207
510
  #isRenderMutation(file, node, fetchNames) {
208
- if (!ts2.isCallExpression(node))
511
+ if (!ts5.isCallExpression(node))
209
512
  return false;
210
513
  const name = RenderMutationScanner.#endpointOf(node.expression, fetchNames);
211
514
  if (!name || !this.#mutations.isMutation(file, name))
@@ -213,64 +516,64 @@ class RenderMutationScanner {
213
516
  return !RenderMutationScanner.#optsIn(node, this.#mutations.policyIndexOf(file, name));
214
517
  }
215
518
  static #isEventHandler(node) {
216
- return ts2.isJsxAttribute(node) && ts2.isIdentifier(node.name) && /^on[A-Z]/.test(node.name.text);
519
+ return ts5.isJsxAttribute(node) && ts5.isIdentifier(node.name) && /^on[A-Z]/.test(node.name.text);
217
520
  }
218
521
  static #endpointOf(callee, fetchNames) {
219
- if (ts2.isPropertyAccessExpression(callee))
522
+ if (ts5.isPropertyAccessExpression(callee))
220
523
  return RenderMutationScanner.#isFetch(callee.expression, fetchNames) ? callee.name.text : null;
221
- if (ts2.isElementAccessExpression(callee) && ts2.isStringLiteralLike(callee.argumentExpression))
524
+ if (ts5.isElementAccessExpression(callee) && ts5.isStringLiteralLike(callee.argumentExpression))
222
525
  return RenderMutationScanner.#isFetch(callee.expression, fetchNames) ? callee.argumentExpression.text : null;
223
526
  return null;
224
527
  }
225
528
  static #isFetch(expression, fetchNames) {
226
- return ts2.isIdentifier(expression) && fetchNames.has(expression.text);
529
+ return ts5.isIdentifier(expression) && fetchNames.has(expression.text);
227
530
  }
228
531
  static #optsIn(call, policyIndex) {
229
532
  if (policyIndex === null)
230
533
  return false;
231
534
  const leading = call.arguments.slice(0, policyIndex + 1);
232
- if (leading.some((argument) => ts2.isSpreadElement(argument)))
535
+ if (leading.some((argument) => ts5.isSpreadElement(argument)))
233
536
  return true;
234
537
  const policy = leading[policyIndex];
235
538
  return policy ? RenderMutationScanner.#policyOptsIn(policy) : false;
236
539
  }
237
540
  static #policyOptsIn(argument) {
238
541
  const policy = RenderMutationScanner.#unwrap(argument);
239
- if (!ts2.isObjectLiteralExpression(policy))
542
+ if (!ts5.isObjectLiteralExpression(policy))
240
543
  return !RenderMutationScanner.#cannotBePolicy(policy);
241
544
  return policy.properties.some((property) => {
242
- if (ts2.isSpreadAssignment(property))
545
+ if (ts5.isSpreadAssignment(property))
243
546
  return true;
244
- if (!ts2.isPropertyAssignment(property) && !ts2.isShorthandPropertyAssignment(property))
547
+ if (!ts5.isPropertyAssignment(property) && !ts5.isShorthandPropertyAssignment(property))
245
548
  return false;
246
- if (!(ts2.isIdentifier(property.name) || ts2.isStringLiteral(property.name)))
549
+ if (!(ts5.isIdentifier(property.name) || ts5.isStringLiteral(property.name)))
247
550
  return false;
248
551
  if (property.name.text !== "duringRender")
249
552
  return false;
250
- if (ts2.isShorthandPropertyAssignment(property))
553
+ if (ts5.isShorthandPropertyAssignment(property))
251
554
  return true;
252
555
  const value = RenderMutationScanner.#unwrap(property.initializer);
253
- return value.kind !== ts2.SyntaxKind.FalseKeyword && !(ts2.isIdentifier(value) && value.text === "undefined");
556
+ return value.kind !== ts5.SyntaxKind.FalseKeyword && !(ts5.isIdentifier(value) && value.text === "undefined");
254
557
  });
255
558
  }
256
559
  static #unwrap(expression) {
257
560
  let current = expression;
258
- while (ts2.isParenthesizedExpression(current) || ts2.isAsExpression(current) || ts2.isSatisfiesExpression(current) || ts2.isNonNullExpression(current) || ts2.isTypeAssertionExpression(current))
561
+ while (ts5.isParenthesizedExpression(current) || ts5.isAsExpression(current) || ts5.isSatisfiesExpression(current) || ts5.isNonNullExpression(current) || ts5.isTypeAssertionExpression(current))
259
562
  current = current.expression;
260
563
  return current;
261
564
  }
262
565
  static #cannotBePolicy(expression) {
263
- if (ts2.isIdentifier(expression))
566
+ if (ts5.isIdentifier(expression))
264
567
  return expression.text === "undefined";
265
- return ts2.isLiteralExpression(expression) || ts2.isNoSubstitutionTemplateLiteral(expression) || ts2.isTemplateExpression(expression) || ts2.isArrayLiteralExpression(expression) || ts2.isArrowFunction(expression) || ts2.isFunctionExpression(expression) || ts2.isVoidExpression(expression) || ts2.isPrefixUnaryExpression(expression) || [ts2.SyntaxKind.NullKeyword, ts2.SyntaxKind.TrueKeyword, ts2.SyntaxKind.FalseKeyword].includes(expression.kind);
568
+ return ts5.isLiteralExpression(expression) || ts5.isNoSubstitutionTemplateLiteral(expression) || ts5.isTemplateExpression(expression) || ts5.isArrayLiteralExpression(expression) || ts5.isArrowFunction(expression) || ts5.isFunctionExpression(expression) || ts5.isVoidExpression(expression) || ts5.isPrefixUnaryExpression(expression) || [ts5.SyntaxKind.NullKeyword, ts5.SyntaxKind.TrueKeyword, ts5.SyntaxKind.FalseKeyword].includes(expression.kind);
266
569
  }
267
570
  static #fetchBindingsOf(sourceFile) {
268
571
  const names = new Set;
269
572
  for (const statement of sourceFile.statements) {
270
- if (!ts2.isImportDeclaration(statement) || statement.importClause?.isTypeOnly)
573
+ if (!ts5.isImportDeclaration(statement) || statement.importClause?.isTypeOnly)
271
574
  continue;
272
575
  const bindings = statement.importClause?.namedBindings;
273
- if (!bindings || !ts2.isNamedImports(bindings))
576
+ if (!bindings || !ts5.isNamedImports(bindings))
274
577
  continue;
275
578
  for (const element of bindings.elements)
276
579
  if (!element.isTypeOnly && (element.propertyName ?? element.name).text === "fetch")
@@ -281,35 +584,35 @@ class RenderMutationScanner {
281
584
  static #functionsOf(sourceFile) {
282
585
  const functions = new Map;
283
586
  for (const statement of sourceFile.statements) {
284
- if (ts2.isFunctionDeclaration(statement) && statement.name && statement.body)
587
+ if (ts5.isFunctionDeclaration(statement) && statement.name && statement.body)
285
588
  functions.set(statement.name.text, statement.body);
286
- if (!ts2.isVariableStatement(statement))
589
+ if (!ts5.isVariableStatement(statement))
287
590
  continue;
288
591
  for (const declaration of statement.declarationList.declarations) {
289
592
  const initializer = declaration.initializer && RenderMutationScanner.#unwrap(declaration.initializer);
290
- if (!ts2.isIdentifier(declaration.name) || !initializer)
593
+ if (!ts5.isIdentifier(declaration.name) || !initializer)
291
594
  continue;
292
- if (ts2.isArrowFunction(initializer) || ts2.isFunctionExpression(initializer))
595
+ if (ts5.isArrowFunction(initializer) || ts5.isFunctionExpression(initializer))
293
596
  functions.set(declaration.name.text, initializer.body);
294
597
  }
295
598
  }
296
599
  return functions;
297
600
  }
298
601
  static #helperOf(node, functions) {
299
- const callee = ts2.isCallExpression(node) ? node.expression : ts2.isJsxSelfClosingElement(node) || ts2.isJsxOpeningElement(node) ? node.tagName : undefined;
300
- return callee && ts2.isIdentifier(callee) ? functions.get(callee.text) : undefined;
602
+ const callee = ts5.isCallExpression(node) ? node.expression : ts5.isJsxSelfClosingElement(node) || ts5.isJsxOpeningElement(node) ? node.tagName : undefined;
603
+ return callee && ts5.isIdentifier(callee) ? functions.get(callee.text) : undefined;
301
604
  }
302
605
  static #renderBodiesOf(sourceFile, functions) {
303
606
  const bodies = [];
304
- const bodyOf = (node) => ts2.isIdentifier(node) ? functions.get(node.text) : node;
607
+ const bodyOf = (node) => ts5.isIdentifier(node) ? functions.get(node.text) : node;
305
608
  const visit = (node) => {
306
- if (ts2.isCallExpression(node) && ts2.isPropertyAccessExpression(node.expression) && RenderMutationScanner.#stages.has(node.expression.name.text) && RenderMutationScanner.#isRouteChain(node.expression.expression))
609
+ if (ts5.isCallExpression(node) && ts5.isPropertyAccessExpression(node.expression) && RenderMutationScanner.#stages.has(node.expression.name.text) && RenderMutationScanner.#isRouteChain(node.expression.expression))
307
610
  for (const argument of node.arguments) {
308
611
  const body = bodyOf(argument);
309
612
  if (body)
310
613
  bodies.push(body);
311
614
  }
312
- ts2.forEachChild(node, visit);
615
+ ts5.forEachChild(node, visit);
313
616
  };
314
617
  visit(sourceFile);
315
618
  for (const statement of sourceFile.statements) {
@@ -321,144 +624,24 @@ class RenderMutationScanner {
321
624
  }
322
625
  static #isRouteChain(expression) {
323
626
  let current = expression;
324
- while (ts2.isCallExpression(current)) {
325
- if (ts2.isIdentifier(current.expression))
627
+ while (ts5.isCallExpression(current)) {
628
+ if (ts5.isIdentifier(current.expression))
326
629
  return RenderMutationScanner.#builders.has(current.expression.text);
327
- if (!ts2.isPropertyAccessExpression(current.expression))
630
+ if (!ts5.isPropertyAccessExpression(current.expression))
328
631
  return false;
329
632
  current = current.expression.expression;
330
633
  }
331
634
  return false;
332
635
  }
333
636
  static #legacyPageOf(statement, functions) {
334
- if (ts2.isFunctionDeclaration(statement))
335
- return statement.modifiers?.some((modifier) => modifier.kind === ts2.SyntaxKind.DefaultKeyword) ? statement.body : undefined;
336
- if (!ts2.isExportAssignment(statement))
637
+ if (ts5.isFunctionDeclaration(statement))
638
+ return statement.modifiers?.some((modifier) => modifier.kind === ts5.SyntaxKind.DefaultKeyword) ? statement.body : undefined;
639
+ if (!ts5.isExportAssignment(statement))
337
640
  return;
338
641
  const expression = RenderMutationScanner.#unwrap(statement.expression);
339
- if (ts2.isIdentifier(expression))
642
+ if (ts5.isIdentifier(expression))
340
643
  return functions.get(expression.text);
341
- return ts2.isArrowFunction(expression) || ts2.isFunctionExpression(expression) ? expression.body : undefined;
342
- }
343
- }
344
-
345
- // pkgs/@akanjs/devkit/signalMutationIndex.ts
346
- import ts3 from "typescript";
347
-
348
- class SignalMutationIndex {
349
- static #generatedArgCounts = { create: 1, update: 2, remove: 1, merge: 2 };
350
- static #argMethods = new Set(["param", "body", "search", "room", "msg"]);
351
- #shapesByOwner = new Map;
352
- constructor(sourceFiles) {
353
- for (const { file, sourceFile } of sourceFiles) {
354
- if (!/^(apps|libs)\/[^/]+\/lib\/.+\.signal\.ts$/.test(file))
355
- continue;
356
- const owner = file.split("/").slice(0, 2).join("/");
357
- const shapes = this.#shapesByOwner.get(owner) ?? new Map;
358
- SignalMutationIndex.#collect(sourceFile, shapes);
359
- this.#shapesByOwner.set(owner, shapes);
360
- }
361
- }
362
- isMutation(consumerFile, name) {
363
- return this.#shapeOf(consumerFile, name)?.kind === "mutation";
364
- }
365
- policyIndexOf(consumerFile, name) {
366
- const shape = this.#shapeOf(consumerFile, name);
367
- return shape?.kind === "mutation" ? shape.argCount : null;
368
- }
369
- #shapeOf(consumerFile, name) {
370
- const [root, owner] = consumerFile.split("/");
371
- const own = this.#shapesByOwner.get(`${root}/${owner}`)?.get(name);
372
- if (own)
373
- return own;
374
- for (const [key, shapes] of this.#shapesByOwner) {
375
- const shape = shapes.get(name);
376
- if (key.startsWith("libs/") && shape?.kind === "mutation")
377
- return shape;
378
- }
379
- return;
380
- }
381
- static #collect(sourceFile, kinds) {
382
- const visit = (node) => {
383
- if (ts3.isCallExpression(node) && ts3.isIdentifier(node.expression)) {
384
- if (node.expression.text === "slice")
385
- SignalMutationIndex.#collectGenerated(node, kinds);
386
- else if (node.expression.text === "endpoint")
387
- SignalMutationIndex.#collectEndpoints(node, kinds);
388
- }
389
- ts3.forEachChild(node, visit);
390
- };
391
- visit(sourceFile);
392
- }
393
- static #collectGenerated(slice, kinds) {
394
- let service = slice.arguments[0];
395
- while (service && ts3.isCallExpression(service) && ts3.isPropertyAccessExpression(service.expression))
396
- service = service.expression.expression;
397
- if (!service || !ts3.isPropertyAccessExpression(service) || !SignalMutationIndex.#isNamed(service.expression, "srv"))
398
- return;
399
- const model = service.name.text;
400
- const capModel = `${model.charAt(0).toUpperCase()}${model.slice(1)}`;
401
- for (const [verb, argCount] of Object.entries(SignalMutationIndex.#generatedArgCounts))
402
- kinds.set(`${verb}${capModel}`, { kind: "mutation", argCount });
403
- kinds.set(`add${capModel}Files`, { kind: "mutation", argCount: 2 });
404
- }
405
- static #collectEndpoints(endpoint, kinds) {
406
- const builder = endpoint.arguments[1];
407
- if (!builder || !ts3.isArrowFunction(builder) && !ts3.isFunctionExpression(builder))
408
- return;
409
- const map = SignalMutationIndex.#returnedObjectOf(builder);
410
- if (!map)
411
- return;
412
- const verbOf = SignalMutationIndex.#verbReaderOf(builder.parameters[0]);
413
- for (const property of map.properties) {
414
- if (!ts3.isPropertyAssignment(property))
415
- continue;
416
- if (!ts3.isIdentifier(property.name) && !ts3.isStringLiteral(property.name))
417
- continue;
418
- const { root, argCount } = SignalMutationIndex.#chainOf(property.initializer);
419
- const verb = verbOf(root);
420
- const kind = verb === "message" ? "mutation" : verb;
421
- if (kind === "query" || kind === "mutation")
422
- kinds.set(property.name.text, { kind, argCount });
423
- }
424
- }
425
- static #returnedObjectOf(builder) {
426
- let body = builder.body;
427
- if (ts3.isBlock(body))
428
- body = body.statements.find(ts3.isReturnStatement)?.expression;
429
- while (body && ts3.isParenthesizedExpression(body))
430
- body = body.expression;
431
- return body && ts3.isObjectLiteralExpression(body) ? body : null;
432
- }
433
- static #verbReaderOf(parameter) {
434
- const verbs = new Map;
435
- if (parameter && ts3.isObjectBindingPattern(parameter.name))
436
- for (const element of parameter.name.elements) {
437
- const verb = element.propertyName ?? element.name;
438
- if (ts3.isIdentifier(verb) && ts3.isIdentifier(element.name))
439
- verbs.set(element.name.text, verb.text);
440
- }
441
- const holder = parameter && ts3.isIdentifier(parameter.name) ? parameter.name.text : null;
442
- return (callee) => {
443
- if (callee && ts3.isIdentifier(callee))
444
- return verbs.get(callee.text);
445
- if (callee && ts3.isPropertyAccessExpression(callee) && SignalMutationIndex.#isNamed(callee.expression, holder))
446
- return callee.name.text;
447
- return;
448
- };
449
- }
450
- static #isNamed(expression, name) {
451
- return ts3.isIdentifier(expression) && expression.text === name;
452
- }
453
- static #chainOf(initializer) {
454
- let root = initializer;
455
- let argCount = 0;
456
- while (ts3.isCallExpression(root) && ts3.isPropertyAccessExpression(root.expression) && ts3.isCallExpression(root.expression.expression)) {
457
- if (SignalMutationIndex.#argMethods.has(root.expression.name.text))
458
- argCount += 1;
459
- root = root.expression.expression;
460
- }
461
- return { root: ts3.isCallExpression(root) ? root.expression : undefined, argCount };
644
+ return ts5.isArrowFunction(expression) || ts5.isFunctionExpression(expression) ? expression.body : undefined;
462
645
  }
463
646
  }
464
647
 
@@ -543,18 +726,18 @@ class SsrScanner {
543
726
  return warnings;
544
727
  }
545
728
  #isMountEffect(sourceFile, node) {
546
- if (!ts4.isCallExpression(node))
729
+ if (!ts6.isCallExpression(node))
547
730
  return false;
548
731
  const callee = node.expression.getText(sourceFile);
549
732
  if (callee !== "useEffect" && callee !== "useLayoutEffect")
550
733
  return false;
551
734
  const deps = node.arguments[1];
552
- return !!deps && ts4.isArrayLiteralExpression(deps) && deps.elements.length === 0;
735
+ return !!deps && ts6.isArrayLiteralExpression(deps) && deps.elements.length === 0;
553
736
  }
554
737
  #getLoadCalls(sourceFile, node) {
555
738
  const calls = [];
556
739
  SsrScanner.#walk(node, (child) => {
557
- if (!ts4.isCallExpression(child))
740
+ if (!ts6.isCallExpression(child))
558
741
  return;
559
742
  const callee = child.expression.getText(sourceFile);
560
743
  if (/^fetch\.[a-z]/.test(callee) || /^st\.do\.(init|get|view|load|list|count|insight)[A-Z]/.test(callee))
@@ -567,7 +750,7 @@ class SsrScanner {
567
750
  return [];
568
751
  const warnings = [];
569
752
  SsrScanner.#walk(sourceFile.sourceFile, (node) => {
570
- if (ts4.isCallExpression(node) && node.expression.getText(sourceFile.sourceFile) === "useState")
753
+ if (ts6.isCallExpression(node) && node.expression.getText(sourceFile.sourceFile) === "useState")
571
754
  warnings.push(fileWarning("akan.ssr.template-client-state", "ssr", sourceFile.file, "Template holds form state in useState. Templates are store-driven and carry no local state.", this.#getLine(sourceFile.sourceFile, node)));
572
755
  });
573
756
  return warnings;
@@ -610,14 +793,14 @@ class SsrScanner {
610
793
  return components;
611
794
  }
612
795
  #getComponentNodes(statement) {
613
- if (ts4.isFunctionDeclaration(statement) && statement.body)
796
+ if (ts6.isFunctionDeclaration(statement) && statement.body)
614
797
  return [{ name: statement.name?.text ?? "default", node: statement.body }];
615
- if (!ts4.isVariableStatement(statement))
798
+ if (!ts6.isVariableStatement(statement))
616
799
  return [];
617
800
  return statement.declarationList.declarations.flatMap((declaration) => {
618
- if (!ts4.isIdentifier(declaration.name) || !declaration.initializer)
801
+ if (!ts6.isIdentifier(declaration.name) || !declaration.initializer)
619
802
  return [];
620
- if (!ts4.isArrowFunction(declaration.initializer) && !ts4.isFunctionExpression(declaration.initializer))
803
+ if (!ts6.isArrowFunction(declaration.initializer) && !ts6.isFunctionExpression(declaration.initializer))
621
804
  return [];
622
805
  return [{ name: declaration.name.text, node: declaration.initializer }];
623
806
  });
@@ -625,7 +808,7 @@ class SsrScanner {
625
808
  #getTouches(sourceFile, node) {
626
809
  const touches = [];
627
810
  SsrScanner.#walk(node, (child) => {
628
- if (ts4.isCallExpression(child)) {
811
+ if (ts6.isCallExpression(child)) {
629
812
  const callee = child.expression.getText(sourceFile);
630
813
  const bareName = callee.split(".").pop() ?? callee;
631
814
  if (callee === "createContext" || callee === "lazy")
@@ -633,9 +816,9 @@ class SsrScanner {
633
816
  else if (/^use[A-Z]/.test(bareName) && !SsrScanner.#serverSafeCalls.has(bareName))
634
817
  touches.push(bareName);
635
818
  }
636
- if (ts4.isJsxAttribute(child) && /^on[A-Z]/.test(child.name.getText(sourceFile)))
819
+ if (ts6.isJsxAttribute(child) && /^on[A-Z]/.test(child.name.getText(sourceFile)))
637
820
  touches.push(child.name.getText(sourceFile));
638
- if (ts4.isPropertyAccessExpression(child)) {
821
+ if (ts6.isPropertyAccessExpression(child)) {
639
822
  const root = getAccessRoot(child);
640
823
  if (root === "st")
641
824
  touches.push("st");
@@ -648,7 +831,7 @@ class SsrScanner {
648
831
  #getTagNames(sourceFile, node) {
649
832
  const tags = new Set;
650
833
  SsrScanner.#walk(node, (child) => {
651
- if (ts4.isJsxOpeningElement(child) || ts4.isJsxSelfClosingElement(child))
834
+ if (ts6.isJsxOpeningElement(child) || ts6.isJsxSelfClosingElement(child))
652
835
  tags.add(child.tagName.getText(sourceFile).split(".")[0]);
653
836
  });
654
837
  return tags;
@@ -656,7 +839,7 @@ class SsrScanner {
656
839
  #getMass(node) {
657
840
  let mass = 0;
658
841
  SsrScanner.#walk(node, (child) => {
659
- if (ts4.isJsxOpeningElement(child) || ts4.isJsxSelfClosingElement(child))
842
+ if (ts6.isJsxOpeningElement(child) || ts6.isJsxSelfClosingElement(child))
660
843
  mass += 1;
661
844
  });
662
845
  return mass;
@@ -664,30 +847,30 @@ class SsrScanner {
664
847
  static #walk(node, visit) {
665
848
  const walk = (child) => {
666
849
  visit(child);
667
- ts4.forEachChild(child, walk);
850
+ ts6.forEachChild(child, walk);
668
851
  };
669
- ts4.forEachChild(node, walk);
852
+ ts6.forEachChild(node, walk);
670
853
  }
671
854
  #hasUseClient(sourceFile) {
672
855
  const first = sourceFile.statements[0];
673
- if (!first || !ts4.isExpressionStatement(first) || !ts4.isStringLiteral(first.expression))
856
+ if (!first || !ts6.isExpressionStatement(first) || !ts6.isStringLiteral(first.expression))
674
857
  return false;
675
858
  return first.expression.text === "use client";
676
859
  }
677
860
  #hasVendorImport(sourceFile) {
678
- return sourceFile.statements.some((statement) => ts4.isImportDeclaration(statement) && isVendorSpecifier(getSpecifier(statement)));
861
+ return sourceFile.statements.some((statement) => ts6.isImportDeclaration(statement) && isVendorSpecifier(getSpecifier(statement)));
679
862
  }
680
863
  #getVendorNames(sourceFile) {
681
864
  const names = new Set;
682
865
  for (const statement of sourceFile.statements) {
683
- if (!ts4.isImportDeclaration(statement) || !isVendorSpecifier(getSpecifier(statement)))
866
+ if (!ts6.isImportDeclaration(statement) || !isVendorSpecifier(getSpecifier(statement)))
684
867
  continue;
685
868
  const clause = statement.importClause;
686
869
  if (clause?.name)
687
870
  names.add(clause.name.text);
688
- if (clause?.namedBindings && ts4.isNamespaceImport(clause.namedBindings))
871
+ if (clause?.namedBindings && ts6.isNamespaceImport(clause.namedBindings))
689
872
  names.add(clause.namedBindings.name.text);
690
- if (clause?.namedBindings && ts4.isNamedImports(clause.namedBindings))
873
+ if (clause?.namedBindings && ts6.isNamedImports(clause.namedBindings))
691
874
  for (const element of clause.namedBindings.elements)
692
875
  names.add(element.name.text);
693
876
  }
@@ -695,10 +878,10 @@ class SsrScanner {
695
878
  }
696
879
  #importsClientRuntime(sourceFile) {
697
880
  for (const statement of sourceFile.statements) {
698
- if (!ts4.isImportDeclaration(statement))
881
+ if (!ts6.isImportDeclaration(statement))
699
882
  continue;
700
883
  const bindings = statement.importClause?.namedBindings;
701
- if (!bindings || !ts4.isNamedImports(bindings))
884
+ if (!bindings || !ts6.isNamedImports(bindings))
702
885
  continue;
703
886
  if (bindings.elements.some((element) => SsrScanner.#clientRuntimeImports.has(element.name.text)))
704
887
  return true;
@@ -749,7 +932,7 @@ function getShare(serverMass, clientMass) {
749
932
  return total === 0 ? 1 : serverMass / total;
750
933
  }
751
934
  function getSpecifier(statement) {
752
- return ts4.isStringLiteral(statement.moduleSpecifier) ? statement.moduleSpecifier.text : "";
935
+ return ts6.isStringLiteral(statement.moduleSpecifier) ? statement.moduleSpecifier.text : "";
753
936
  }
754
937
  function isVendorSpecifier(specifier) {
755
938
  if (specifier === "" || specifier.startsWith(".") || specifier.startsWith("/"))
@@ -762,9 +945,108 @@ function isVendorSpecifier(specifier) {
762
945
  }
763
946
  function getAccessRoot(node) {
764
947
  let current = node;
765
- while (ts4.isPropertyAccessExpression(current))
948
+ while (ts6.isPropertyAccessExpression(current))
766
949
  current = current.expression;
767
- return ts4.isIdentifier(current) ? current.text : "";
950
+ return ts6.isIdentifier(current) ? current.text : "";
951
+ }
952
+
953
+ // pkgs/@akanjs/devkit/testOnlyExportScanner.ts
954
+ import ts7 from "typescript";
955
+
956
+ class TestOnlyExportScanner {
957
+ static rule = "akan.global.test-only-export";
958
+ static #facets = new Set(["common", "webkit", "srvkit", "ui"]);
959
+ scan(sourceFiles) {
960
+ const liveFileNumByName = new Map;
961
+ const testRefsByName = new Map;
962
+ for (const { file, sourceFile } of sourceFiles) {
963
+ const isTest = TestOnlyExportScanner.#isTest(file);
964
+ for (const [name, line] of TestOnlyExportScanner.#identifierLinesOf(sourceFile)) {
965
+ if (!isTest)
966
+ liveFileNumByName.set(name, (liveFileNumByName.get(name) ?? 0) + 1);
967
+ else if (testRefsByName.has(name))
968
+ testRefsByName.get(name)?.push({ file, line });
969
+ else
970
+ testRefsByName.set(name, [{ file, line }]);
971
+ }
972
+ }
973
+ return sourceFiles.filter(({ file }) => TestOnlyExportScanner.#isFacetSource(file)).flatMap(({ file, sourceFile }) => {
974
+ const declarations = TestOnlyExportScanner.#exportedDeclarationsOf(sourceFile);
975
+ return declarations.filter(({ name }) => (liveFileNumByName.get(name) ?? 0) <= 1).filter(({ name }) => !TestOnlyExportScanner.#isUsedInFile(sourceFile, name, declarations)).flatMap(({ name, line }) => {
976
+ const testRefs = testRefsByName.get(name);
977
+ if (!testRefs?.length)
978
+ return [];
979
+ return [
980
+ {
981
+ rule: TestOnlyExportScanner.rule,
982
+ scope: "global",
983
+ severity: "warning",
984
+ file,
985
+ line,
986
+ message: `Exported "${name}" is referenced only by tests: ${testRefs.map((ref) => ref.file).join(", ")}.`,
987
+ locations: testRefs
988
+ }
989
+ ];
990
+ });
991
+ });
992
+ }
993
+ static #isTest(file) {
994
+ return /\.(test|spec)\.tsx?$/.test(file);
995
+ }
996
+ static #isFacetSource(file) {
997
+ const segments = file.split("/");
998
+ if (segments[0] !== "apps")
999
+ return false;
1000
+ return TestOnlyExportScanner.#facets.has(segments[2] ?? "") && !TestOnlyExportScanner.#isTest(file);
1001
+ }
1002
+ static #identifierLinesOf(sourceFile) {
1003
+ const lines = new Map;
1004
+ const visit = (node) => {
1005
+ if (ts7.isIdentifier(node) && !lines.has(node.text))
1006
+ lines.set(node.text, sourceFile.getLineAndCharacterOfPosition(node.getStart(sourceFile)).line + 1);
1007
+ ts7.forEachChild(node, visit);
1008
+ };
1009
+ visit(sourceFile);
1010
+ return lines;
1011
+ }
1012
+ static #exportedDeclarationsOf(sourceFile) {
1013
+ return sourceFile.statements.flatMap((statement) => {
1014
+ if (!TestOnlyExportScanner.#isNamedExport(statement))
1015
+ return [];
1016
+ return TestOnlyExportScanner.#declaredNamesOf(statement).map((identifier) => ({
1017
+ name: identifier.text,
1018
+ line: sourceFile.getLineAndCharacterOfPosition(identifier.getStart(sourceFile)).line + 1,
1019
+ statement
1020
+ }));
1021
+ });
1022
+ }
1023
+ static #isNamedExport(statement) {
1024
+ if (!ts7.canHaveModifiers(statement))
1025
+ return false;
1026
+ const modifiers = ts7.getModifiers(statement) ?? [];
1027
+ return modifiers.some((modifier) => modifier.kind === ts7.SyntaxKind.ExportKeyword) && !modifiers.some((modifier) => modifier.kind === ts7.SyntaxKind.DefaultKeyword);
1028
+ }
1029
+ static #declaredNamesOf(statement) {
1030
+ if (ts7.isVariableStatement(statement))
1031
+ return statement.declarationList.declarations.map((declaration) => declaration.name).filter((name) => ts7.isIdentifier(name));
1032
+ if (ts7.isFunctionDeclaration(statement) || ts7.isClassDeclaration(statement) || ts7.isInterfaceDeclaration(statement) || ts7.isTypeAliasDeclaration(statement) || ts7.isEnumDeclaration(statement))
1033
+ return statement.name ? [statement.name] : [];
1034
+ return [];
1035
+ }
1036
+ static #isUsedInFile(sourceFile, name, declarations) {
1037
+ const ownStatements = new Set(declarations.filter((entry) => entry.name === name).map((entry) => entry.statement));
1038
+ let used = false;
1039
+ const visit = (node) => {
1040
+ if (used || ownStatements.has(node))
1041
+ return;
1042
+ if (ts7.isIdentifier(node) && node.text === name)
1043
+ used = true;
1044
+ else
1045
+ ts7.forEachChild(node, visit);
1046
+ };
1047
+ visit(sourceFile);
1048
+ return used;
1049
+ }
768
1050
  }
769
1051
 
770
1052
  // pkgs/@akanjs/devkit/qualityScanner.ts
@@ -803,6 +1085,7 @@ var CONVENTION_SUFFIXES = [
803
1085
  var RULE_FIXES = {
804
1086
  "akan.global.duplicate-exported-function-name": "Rename one of the exports, or if they are the same thing, extract it into one shared module and import it in both places.",
805
1087
  "akan.global.duplicate-exported-function-body": "Extract the shared implementation into a single exported helper and import it, instead of copying the body.",
1088
+ "akan.global.test-only-export": "Delete the export together with its test. If a live caller in the same file needs it, keep it unexported and test it through that caller.",
806
1089
  "akan.file.recommended-max-lines": "Split the file by responsibility \u2014 move Zones, Utils, or subcomponents into sibling files.",
807
1090
  "akan.file.max-lines": "Break the file into smaller focused modules; keep one primary responsibility per file.",
808
1091
  "akan.file.abstract-max-lines": "Trim the abstract by hand to a title, one sentence naming what the module owns, a `## Rules` list of the invariants the source cannot show, and an optional workflow chain.",
@@ -828,7 +1111,9 @@ var RULE_FIXES = {
828
1111
  "akan.ssr.client-static-markup": "Keep the interactive element in the client component and hoist the static subtree into a server component, then accept it as `children` or render it through a Unit/View reference.",
829
1112
  "akan.ssr.client-mount-load": "Load the data in the route with `fetch.initX(...)` / `fetch.viewX(...)` and pass the init/view object down as a prop; the client store hydrates from it and the effect goes away.",
830
1113
  "akan.ssr.module-missing-server-view": "Add a <Model>.Unit.tsx for list/card rendering and a <Model>.View.tsx for the detail surface, then have the Zone delegate to them.",
831
- "akan.ssr.template-client-state": "Bind the field to the store instead: `value={xForm.field}` with `onChange={st.do.setFieldOnX}`."
1114
+ "akan.ssr.template-client-state": "Bind the field to the store instead: `value={xForm.field}` with `onChange={st.do.setFieldOnX}`.",
1115
+ "akan.comment.density": 'Delete comments that restate the code, label a section, or narrate a step; keep only those carrying a fact the code cannot show, such as a vendor quirk or security reasoning (AGENTS.md "Comments").',
1116
+ "akan.comment.deprecated-marker": "Replace the comment with `/** @deprecated <what to use instead> */` on the declaration, so every use site shows it struck through."
832
1117
  };
833
1118
  function getRuleFix(rule) {
834
1119
  if (rule.startsWith("akan.convention"))
@@ -850,6 +1135,9 @@ class AkanQualityScanner {
850
1135
  ...sourceFiles.flatMap((sourceFile) => this.#scanLayoutQuality(sourceFile)),
851
1136
  ...abstractFiles.flatMap((abstractFile) => this.#scanAbstractQuality(abstractFile)),
852
1137
  ...new FormSetterScanner().scan(sourceFiles),
1138
+ ...new CommentDensityScanner().scan(sourceFiles),
1139
+ ...new DeprecatedCommentScanner().scan(sourceFiles),
1140
+ ...await new MaintainabilityExceptionScanner().scan(workspaceRoot),
853
1141
  ...ssr.warnings
854
1142
  ];
855
1143
  return {
@@ -864,7 +1152,7 @@ class AkanQualityScanner {
864
1152
  const ignoreFilter = ignore().add(await this.#readGitIgnore(workspaceRoot));
865
1153
  const files = [];
866
1154
  for (const targetRoot of ["apps", "libs"]) {
867
- const absoluteTargetRoot = path2.join(workspaceRoot, targetRoot);
1155
+ const absoluteTargetRoot = path4.join(workspaceRoot, targetRoot);
868
1156
  if (!await isDirectory(absoluteTargetRoot))
869
1157
  continue;
870
1158
  await this.#walkTargetFiles(workspaceRoot, absoluteTargetRoot, ignoreFilter, files);
@@ -872,16 +1160,16 @@ class AkanQualityScanner {
872
1160
  return files.sort((a, b) => a < b ? -1 : a > b ? 1 : 0);
873
1161
  }
874
1162
  async#readGitIgnore(workspaceRoot) {
875
- const gitIgnorePath = path2.join(workspaceRoot, ".gitignore");
1163
+ const gitIgnorePath = path4.join(workspaceRoot, ".gitignore");
876
1164
  if (!await Bun.file(gitIgnorePath).exists())
877
1165
  return [];
878
- return (await readFile(gitIgnorePath, "utf8")).split(/\r?\n/);
1166
+ return (await readFile2(gitIgnorePath, "utf8")).split(/\r?\n/);
879
1167
  }
880
1168
  async#walkTargetFiles(workspaceRoot, currentPath, ignoreFilter, files) {
881
- const entries = await readdir(currentPath, { withFileTypes: true });
1169
+ const entries = await readdir2(currentPath, { withFileTypes: true });
882
1170
  for (const entry of entries) {
883
- const absolutePath = path2.join(currentPath, entry.name);
884
- const relativePath = toPosix(path2.relative(workspaceRoot, absolutePath));
1171
+ const absolutePath = path4.join(currentPath, entry.name);
1172
+ const relativePath = toPosix(path4.relative(workspaceRoot, absolutePath));
885
1173
  if (shouldSkipPath(relativePath, entry.isDirectory(), ignoreFilter))
886
1174
  continue;
887
1175
  if (entry.isDirectory()) {
@@ -896,17 +1184,17 @@ class AkanQualityScanner {
896
1184
  }
897
1185
  }
898
1186
  async#readSourceFile(workspaceRoot, file) {
899
- const absolutePath = path2.join(workspaceRoot, file);
900
- const content = await readFile(absolutePath, "utf8");
1187
+ const absolutePath = path4.join(workspaceRoot, file);
1188
+ const content = await readFile2(absolutePath, "utf8");
901
1189
  return {
902
1190
  file,
903
1191
  absolutePath,
904
1192
  content,
905
- sourceFile: ts5.createSourceFile(file, content, ts5.ScriptTarget.Latest, true, getScriptKind(file))
1193
+ sourceFile: ts8.createSourceFile(file, content, ts8.ScriptTarget.Latest, true, getScriptKind(file))
906
1194
  };
907
1195
  }
908
1196
  async#readTextFile(workspaceRoot, file) {
909
- return { file, content: await readFile(path2.join(workspaceRoot, file), "utf8") };
1197
+ return { file, content: await readFile2(path4.join(workspaceRoot, file), "utf8") };
910
1198
  }
911
1199
  #scanGlobalQuality(sourceFiles) {
912
1200
  const exportedFunctionLikes = sourceFiles.flatMap((sourceFile) => getExportedFunctionLikes(sourceFile));
@@ -936,6 +1224,8 @@ class AkanQualityScanner {
936
1224
  locations: declarations.map(({ file, line }) => ({ file, line }))
937
1225
  });
938
1226
  }
1227
+ warnings.push(...new TestOnlyExportScanner().scan(sourceFiles));
1228
+ warnings.push(...new KindBranchScanner().scan(sourceFiles));
939
1229
  return warnings;
940
1230
  }
941
1231
  #scanSingleFileQuality(sourceFile) {
@@ -997,8 +1287,8 @@ class AkanQualityScanner {
997
1287
  const suffix = CONVENTION_SUFFIXES.find((candidate) => sourceFile.file.endsWith(candidate));
998
1288
  if (!suffix)
999
1289
  return [];
1000
- const modelName = toPascalCase(path2.basename(sourceFile.file, suffix));
1001
- return getTopLevelDeclarations(sourceFile).filter((declaration) => !isAllowedConventionDeclaration(suffix, modelName, declaration)).map((declaration) => fileWarning(`akan.convention${suffix.replace(".ts", "")}`, "convention", sourceFile.file, `${path2.basename(sourceFile.file)} should not declare top-level ${declaration.kind} "${declaration.name}". Allowed declarations: ${getConventionDescription(suffix, modelName)}.`, declaration.line));
1290
+ const modelName = toPascalCase(path4.basename(sourceFile.file, suffix));
1291
+ return getTopLevelDeclarations(sourceFile).filter((declaration) => !isAllowedConventionDeclaration(suffix, modelName, declaration)).map((declaration) => fileWarning(`akan.convention${suffix.replace(".ts", "")}`, "convention", sourceFile.file, `${path4.basename(sourceFile.file)} should not declare top-level ${declaration.kind} "${declaration.name}". Allowed declarations: ${getConventionDescription(suffix, modelName)}.`, declaration.line));
1002
1292
  }
1003
1293
  #scanAbstractQuality({ file, content }) {
1004
1294
  const lineCount = AbstractDoc.lineCountOf(content);
@@ -1020,7 +1310,7 @@ class AkanQualityScanner {
1020
1310
  }
1021
1311
  const facetShadow = rootEntry?.isDir ? facetIndexShadowOf(sourceFile.file.split("/").slice(2).join("/")) : null;
1022
1312
  if (facetShadow)
1023
- warnings.push(fileWarning("akan.layout.facet-index-shadow", "layout", sourceFile.file, `${path2.basename(sourceFile.file)} ${facetShadow}.`));
1313
+ warnings.push(fileWarning("akan.layout.facet-index-shadow", "layout", sourceFile.file, `${path4.basename(sourceFile.file)} ${facetShadow}.`));
1024
1314
  const libFacetFile = getLibFacetRootFile(sourceFile.file);
1025
1315
  if (libFacetFile && !isAllowedLibFacetRootFile(libFacetFile))
1026
1316
  warnings.push(fileWarning("akan.layout.lib-facet-file", "layout", sourceFile.file, `Unexpected lib facet root file "${libFacetFile}". ${libFacetRootHintOf(libFacetFile) ?? "Keep direct lib/ root files limited to generated support facets."}`));
@@ -1099,13 +1389,13 @@ function getExportedFunctionLikes(sourceFile) {
1099
1389
  duplicateNameExempt: nameExempt || isConventionDuplicateNameExempt(sourceFile.file, isEnumClass)
1100
1390
  });
1101
1391
  for (const statement of sourceFile.sourceFile.statements) {
1102
- if (ts5.isFunctionDeclaration(statement) && statement.name && isExported(statement))
1392
+ if (ts8.isFunctionDeclaration(statement) && statement.name && isExported(statement))
1103
1393
  add(statement.name.text, "function", statement, statement.body);
1104
- if (ts5.isClassDeclaration(statement) && statement.name && isExported(statement))
1394
+ if (ts8.isClassDeclaration(statement) && statement.name && isExported(statement))
1105
1395
  add(statement.name.text, "class", statement, statement, isEnumClassStatement(sourceFile.sourceFile, statement));
1106
- if (ts5.isVariableStatement(statement) && isExported(statement)) {
1396
+ if (ts8.isVariableStatement(statement) && isExported(statement)) {
1107
1397
  for (const declaration of statement.declarationList.declarations) {
1108
- if (!ts5.isIdentifier(declaration.name) || !isFunctionLikeInitializer(declaration.initializer))
1398
+ if (!ts8.isIdentifier(declaration.name) || !isFunctionLikeInitializer(declaration.initializer))
1109
1399
  continue;
1110
1400
  add(declaration.name.text, "function-variable", declaration, declaration.initializer);
1111
1401
  }
@@ -1133,14 +1423,14 @@ function isConventionDuplicateNameExempt(file, isEnumClass) {
1133
1423
  return false;
1134
1424
  }
1135
1425
  function isEnumClassStatement(sourceFile, statement) {
1136
- if (!ts5.isClassDeclaration(statement))
1426
+ if (!ts8.isClassDeclaration(statement))
1137
1427
  return false;
1138
- const heritageClause = statement.heritageClauses?.find((clause) => clause.token === ts5.SyntaxKind.ExtendsKeyword);
1428
+ const heritageClause = statement.heritageClauses?.find((clause) => clause.token === ts8.SyntaxKind.ExtendsKeyword);
1139
1429
  const expression = heritageClause?.types[0]?.expression;
1140
1430
  return !!expression && expression.getText(sourceFile).startsWith("enumOf(");
1141
1431
  }
1142
1432
  function getExportedClassNames(sourceFile) {
1143
- return sourceFile.statements.filter((statement) => ts5.isClassDeclaration(statement)).filter((statement) => isExported(statement)).map((statement) => statement.name?.text).filter((name) => !!name);
1433
+ return sourceFile.statements.filter((statement) => ts8.isClassDeclaration(statement)).filter((statement) => isExported(statement)).map((statement) => statement.name?.text).filter((name) => !!name);
1144
1434
  }
1145
1435
  function isComponentDeclarationFile(file) {
1146
1436
  if (!file.endsWith(".tsx"))
@@ -1156,7 +1446,7 @@ function isComponentDeclarationFile(file) {
1156
1446
  function getComponentFileDeclarations(sourceFile) {
1157
1447
  const reExportedNames = new Set;
1158
1448
  for (const statement of sourceFile.statements) {
1159
- if (ts5.isExportDeclaration(statement) && statement.exportClause && ts5.isNamedExports(statement.exportClause)) {
1449
+ if (ts8.isExportDeclaration(statement) && statement.exportClause && ts8.isNamedExports(statement.exportClause)) {
1160
1450
  for (const element of statement.exportClause.elements)
1161
1451
  reExportedNames.add((element.propertyName ?? element.name).text);
1162
1452
  }
@@ -1166,19 +1456,19 @@ function getComponentFileDeclarations(sourceFile) {
1166
1456
  const isDefaultExport = isDefaultExportStatement(statement);
1167
1457
  const inlineExported = isExported(statement);
1168
1458
  const add = (name, kind, line) => declarations.push({ name, kind, line, exported: inlineExported || reExportedNames.has(name), isDefaultExport });
1169
- if (ts5.isInterfaceDeclaration(statement))
1459
+ if (ts8.isInterfaceDeclaration(statement))
1170
1460
  add(statement.name.text, "interface", getLine(sourceFile, statement));
1171
- else if (ts5.isTypeAliasDeclaration(statement))
1461
+ else if (ts8.isTypeAliasDeclaration(statement))
1172
1462
  add(statement.name.text, "type", getLine(sourceFile, statement));
1173
- else if (ts5.isEnumDeclaration(statement))
1463
+ else if (ts8.isEnumDeclaration(statement))
1174
1464
  add(statement.name.text, "enum", getLine(sourceFile, statement));
1175
- else if (ts5.isFunctionDeclaration(statement) && statement.name)
1465
+ else if (ts8.isFunctionDeclaration(statement) && statement.name)
1176
1466
  add(statement.name.text, "function", getLine(sourceFile, statement));
1177
- else if (ts5.isClassDeclaration(statement) && statement.name)
1467
+ else if (ts8.isClassDeclaration(statement) && statement.name)
1178
1468
  add(statement.name.text, "class", getLine(sourceFile, statement));
1179
- else if (ts5.isVariableStatement(statement)) {
1469
+ else if (ts8.isVariableStatement(statement)) {
1180
1470
  for (const declaration of statement.declarationList.declarations) {
1181
- if (!ts5.isIdentifier(declaration.name))
1471
+ if (!ts8.isIdentifier(declaration.name))
1182
1472
  continue;
1183
1473
  const kind = isFunctionLikeInitializer(declaration.initializer) ? "function" : "variable";
1184
1474
  add(declaration.name.text, kind, getLine(sourceFile, declaration));
@@ -1190,15 +1480,15 @@ function getComponentFileDeclarations(sourceFile) {
1190
1480
  function getCompoundComponentNames(sourceFile) {
1191
1481
  const names = new Set;
1192
1482
  for (const statement of sourceFile.statements) {
1193
- if (!ts5.isExpressionStatement(statement))
1483
+ if (!ts8.isExpressionStatement(statement))
1194
1484
  continue;
1195
1485
  const { expression } = statement;
1196
- if (!ts5.isBinaryExpression(expression) || expression.operatorToken.kind !== ts5.SyntaxKind.EqualsToken)
1486
+ if (!ts8.isBinaryExpression(expression) || expression.operatorToken.kind !== ts8.SyntaxKind.EqualsToken)
1197
1487
  continue;
1198
- if (!ts5.isPropertyAccessExpression(expression.left) || !isPascalCaseName(expression.left.name.text))
1488
+ if (!ts8.isPropertyAccessExpression(expression.left) || !isPascalCaseName(expression.left.name.text))
1199
1489
  continue;
1200
1490
  names.add(expression.left.name.text);
1201
- if (ts5.isIdentifier(expression.right) && isPascalCaseName(expression.right.text))
1491
+ if (ts8.isIdentifier(expression.right) && isPascalCaseName(expression.right.text))
1202
1492
  names.add(expression.right.text);
1203
1493
  }
1204
1494
  return names;
@@ -1218,11 +1508,11 @@ function isPascalCaseName(name) {
1218
1508
  return /^[A-Z]/.test(name) && !/^[A-Z0-9_]+$/.test(name);
1219
1509
  }
1220
1510
  function isDefaultExportStatement(statement) {
1221
- if (ts5.isExportAssignment(statement))
1511
+ if (ts8.isExportAssignment(statement))
1222
1512
  return !statement.isExportEquals;
1223
- if (!ts5.canHaveModifiers(statement))
1513
+ if (!ts8.canHaveModifiers(statement))
1224
1514
  return false;
1225
- return !!ts5.getModifiers(statement)?.some((modifier) => modifier.kind === ts5.SyntaxKind.DefaultKeyword);
1515
+ return !!ts8.getModifiers(statement)?.some((modifier) => modifier.kind === ts8.SyntaxKind.DefaultKeyword);
1226
1516
  }
1227
1517
  function getBangCommentWarnings(sourceFile) {
1228
1518
  if (!isClientReachableFile(sourceFile.file))
@@ -1258,11 +1548,11 @@ function getGlobalMutationWarnings(sourceFile) {
1258
1548
  const warnings = [];
1259
1549
  for (const statement of sourceFile.sourceFile.statements) {
1260
1550
  const warn = (rule, message) => warnings.push(fileWarning(rule, "file", sourceFile.file, message, getLine(sourceFile.sourceFile, statement)));
1261
- if (ts5.isModuleDeclaration(statement) && statement.name.getText(sourceFile.sourceFile) === "global")
1551
+ if (ts8.isModuleDeclaration(statement) && statement.name.getText(sourceFile.sourceFile) === "global")
1262
1552
  warn("akan.file.global-declaration", "Global declarations require an explicit low-level integration allowlist.");
1263
- if (ts5.isInterfaceDeclaration(statement) && statement.name.text === "Window")
1553
+ if (ts8.isInterfaceDeclaration(statement) && statement.name.text === "Window")
1264
1554
  warn("akan.file.window-augmentation", "Window augmentation should be isolated to approved browser integration files.");
1265
- if (ts5.isExpressionStatement(statement) && statement.expression.getText(sourceFile.sourceFile).includes(".prototype."))
1555
+ if (ts8.isExpressionStatement(statement) && statement.expression.getText(sourceFile.sourceFile).includes(".prototype."))
1266
1556
  warn("akan.file.prototype-mutation", "Prototype mutation should be avoided or isolated to approved low-level integration files.");
1267
1557
  }
1268
1558
  return warnings;
@@ -1279,19 +1569,19 @@ function getTopLevelDeclaration(sourceFile, statement) {
1279
1569
  exported: isExported(statement),
1280
1570
  node: statement
1281
1571
  });
1282
- if (ts5.isClassDeclaration(statement) && statement.name)
1572
+ if (ts8.isClassDeclaration(statement) && statement.name)
1283
1573
  return [declared(statement.name.text, "class")];
1284
- if (ts5.isFunctionDeclaration(statement) && statement.name)
1574
+ if (ts8.isFunctionDeclaration(statement) && statement.name)
1285
1575
  return [declared(statement.name.text, "function")];
1286
- if (ts5.isInterfaceDeclaration(statement))
1576
+ if (ts8.isInterfaceDeclaration(statement))
1287
1577
  return [declared(statement.name.text, "interface")];
1288
- if (ts5.isTypeAliasDeclaration(statement))
1578
+ if (ts8.isTypeAliasDeclaration(statement))
1289
1579
  return [declared(statement.name.text, "type")];
1290
- if (ts5.isEnumDeclaration(statement))
1580
+ if (ts8.isEnumDeclaration(statement))
1291
1581
  return [declared(statement.name.text, "enum")];
1292
- if (ts5.isVariableStatement(statement))
1293
- return statement.declarationList.declarations.filter((declaration) => ts5.isIdentifier(declaration.name)).map((declaration) => declared(declaration.name.text, "variable", getLine(sourceFile, declaration)));
1294
- if (ts5.isExportDeclaration(statement))
1582
+ if (ts8.isVariableStatement(statement))
1583
+ return statement.declarationList.declarations.filter((declaration) => ts8.isIdentifier(declaration.name)).map((declaration) => declared(declaration.name.text, "variable", getLine(sourceFile, declaration)));
1584
+ if (ts8.isExportDeclaration(statement))
1295
1585
  return [{ name: "export declaration", kind: "export", line, exported: true, node: statement }];
1296
1586
  return [];
1297
1587
  }
@@ -1379,13 +1669,13 @@ function getModuleInfo(file) {
1379
1669
  return { moduleName, fileName, kind: "database" };
1380
1670
  }
1381
1671
  function isExportedConst(declaration) {
1382
- return declaration.exported && ts5.isVariableStatement(declaration.node) && (declaration.node.declarationList.flags & ts5.NodeFlags.Const) !== 0;
1672
+ return declaration.exported && ts8.isVariableStatement(declaration.node) && (declaration.node.declarationList.flags & ts8.NodeFlags.Const) !== 0;
1383
1673
  }
1384
1674
  function isExported(node) {
1385
- return !!(ts5.getCombinedModifierFlags(node) & ts5.ModifierFlags.Export);
1675
+ return !!(ts8.getCombinedModifierFlags(node) & ts8.ModifierFlags.Export);
1386
1676
  }
1387
1677
  function isFunctionLikeInitializer(node) {
1388
- return !!node && (ts5.isArrowFunction(node) || ts5.isFunctionExpression(node));
1678
+ return !!node && (ts8.isArrowFunction(node) || ts8.isFunctionExpression(node));
1389
1679
  }
1390
1680
  function getBodyFingerprint(sourceFile, node) {
1391
1681
  if (!node)
@@ -1407,7 +1697,7 @@ async function isDirectory(absolutePath) {
1407
1697
  }
1408
1698
  }
1409
1699
  function getScriptKind(file) {
1410
- return file.endsWith(".tsx") ? ts5.ScriptKind.TSX : ts5.ScriptKind.TS;
1700
+ return file.endsWith(".tsx") ? ts8.ScriptKind.TSX : ts8.ScriptKind.TS;
1411
1701
  }
1412
1702
  function getLine(sourceFile, node) {
1413
1703
  return sourceFile.getLineAndCharacterOfPosition(node.getStart(sourceFile)).line + 1;
@@ -1428,7 +1718,7 @@ function toPascalCase(value) {
1428
1718
  return value.replace(/(^|[-_./])([a-zA-Z0-9])/g, (_, __, char) => char.toUpperCase()).replace(/[-_./]/g, "");
1429
1719
  }
1430
1720
  function toPosix(value) {
1431
- return value.split(path2.sep).join("/");
1721
+ return value.split(path4.sep).join("/");
1432
1722
  }
1433
1723
  function groupBy(items, getKey) {
1434
1724
  const grouped = new Map;
@@ -1444,8 +1734,7 @@ function compareWarnings(a, b) {
1444
1734
 
1445
1735
  // pkgs/@akanjs/cli/quality/quality.script.ts
1446
1736
  import { Logger } from "akanjs/common";
1447
-
1448
- class QualityScript extends script("quality") {
1737
+ class QualityScript extends script("quality", [WorkspaceRunner]) {
1449
1738
  async scan(workspace, format = "text") {
1450
1739
  const spinner = workspace.spinning("Scanning Akan code quality...");
1451
1740
  const result = await new AkanQualityScanner().scan(workspace.workspaceRoot);
@@ -1459,17 +1748,38 @@ class QualityScript extends script("quality") {
1459
1748
  spinner.succeed(`SSR scan completed (${result.scannedFiles} files, ${result.warnings.length} warnings)`);
1460
1749
  Logger.rawLog(format === "json" ? JSON.stringify(result, null, 2) : formatSsrScanResult(result));
1461
1750
  }
1751
+ async baseline(workspace, { force = false } = {}) {
1752
+ const [appNames, libNames] = await workspace.getExecs();
1753
+ const execs = [
1754
+ ...appNames.map((appName) => AppExecutor.from(workspace, appName)),
1755
+ ...libNames.map((libName) => LibExecutor.from(workspace, libName))
1756
+ ];
1757
+ const { fileName } = MaintainabilityBaseline;
1758
+ for (const exec of execs) {
1759
+ const contract = await this.workspaceRunner.maintainabilityContractOf(exec);
1760
+ const { result, violations } = await contract.seed({ force });
1761
+ const outcome = {
1762
+ written: `wrote ${fileName} with ${violations.length} entries`,
1763
+ kept: `kept the existing ${fileName} (${violations.length} current violations); --force rewrites it`,
1764
+ removed: `no violations, removed ${fileName}`,
1765
+ clean: "no violations"
1766
+ }[result];
1767
+ Logger.rawLog(`${contract.sysPath}: ${outcome}`);
1768
+ }
1769
+ }
1462
1770
  }
1463
1771
 
1464
1772
  // pkgs/@akanjs/cli/quality/quality.command.ts
1465
1773
  class QualityCommand extends command("quality", [QualityScript], ({ public: target }) => ({
1466
- quality: target({ desc: "Scan apps and libs for Akan code quality warnings" }).arg("action", String, { desc: "quality action", default: "scan", enum: ["scan", "ssr"] }).option("format", String, { desc: "output format", default: "text", enum: ["text", "json"] }).with(Workspace).exec(async function(action, format, workspace) {
1774
+ quality: target({ desc: "Scan apps and libs for Akan code quality warnings" }).arg("action", String, { desc: "quality action", default: "scan", enum: ["scan", "ssr", "baseline"] }).option("format", String, { desc: "output format", default: "text", enum: ["text", "json"] }).option("force", Boolean, { flag: "F", desc: "baseline: rewrite an existing akan.baseline.json", default: false }).with(Workspace).exec(async function(action, format, force, workspace) {
1467
1775
  if (action === "scan")
1468
1776
  await this.qualityScript.scan(workspace, format);
1469
1777
  else if (action === "ssr")
1470
1778
  await this.qualityScript.ssr(workspace, format);
1779
+ else if (action === "baseline")
1780
+ await this.qualityScript.baseline(workspace, { force });
1471
1781
  else
1472
- throw new Error(`Unknown quality action: ${action}. Use "scan" or "ssr".`);
1782
+ throw new Error(`Unknown quality action: ${action}. Use "scan", "ssr" or "baseline".`);
1473
1783
  })
1474
1784
  })) {
1475
1785
  }