@akanjs/cli 3.1.1-rc.16 → 3.1.1-rc.17
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.
- package/.build-stamp +1 -1
- package/{CodeAgent-23ewzxqa.js → CodeAgent-fbcq8vks.js} +2 -2
- package/{CodeTui-kc99fk78.js → CodeTui-0626gxqd.js} +1 -1
- package/TunnelShare-2p24xxza.js +14 -0
- package/agent.command-hpza0pg9.js +46 -0
- package/akanCode.js +5 -3
- package/{application.command-bvfd1680.js → application.command-3a7q1hs2.js} +11 -10
- package/{applicationBuildRunner-4ajaesk1.js → applicationBuildRunner-s7yt71j4.js} +5 -5
- package/buildBatch.proc.js +6 -6
- package/{cloud.command-f2w40fyy.js → cloud.command-4vg0pcea.js} +15 -14
- package/cloud.script-nkmeyhet.js +25 -0
- package/{code.command-dbhhnahn.js → code.command-fbntb67p.js} +6 -6
- package/commandManifest.json +1 -1
- package/{context.command-yswjwv6y.js → context.command-31rm54v0.js} +18 -18
- package/context.runner-w01a32ph.js +26 -0
- package/{guideline.command-ztx6dkpk.js → guideline.command-cv3by2ng.js} +3 -3
- package/guidelines/conventions/core.md +104 -0
- package/guidelines/conventions/rules/app.md +83 -0
- package/guidelines/conventions/rules/auth.md +45 -0
- package/guidelines/conventions/rules/config.md +56 -0
- package/guidelines/conventions/rules/constant.md +24 -0
- package/guidelines/conventions/rules/gates.md +31 -0
- package/guidelines/conventions/rules/layer.md +25 -0
- package/guidelines/conventions/rules/migration.md +27 -0
- package/guidelines/conventions/rules/module.md +90 -0
- package/guidelines/conventions/rules/page.md +56 -0
- package/guidelines/conventions/rules/sensitive.md +16 -0
- package/guidelines/conventions/rules/server.md +86 -0
- package/guidelines/conventions/rules/ssr.md +47 -0
- package/guidelines/conventions/rules/style.md +43 -0
- package/guidelines/conventions/rules/test.md +34 -0
- package/guidelines/conventions/rules/ts.md +95 -0
- package/guidelines/conventions/rules/tsx.md +75 -0
- package/guidelines/mcpRule/mcpRule.instruction.md +1 -1
- package/guidelines/workspaceRecipes/workspaceRecipes.instruction.md +3 -3
- package/incrementalBuilder.proc.js +6 -6
- package/{index-xjwcp91m.js → index-05nxx4m5.js} +43 -12
- package/{index-k9k18vq9.js → index-0ht91675.js} +37 -59
- package/{index-er16p89s.js → index-0zwznvv1.js} +1 -1
- package/{index-76jwsm3g.js → index-0zyatd10.js} +2 -2
- package/{index-97fsvy66.js → index-12kzwak1.js} +3 -3
- package/{index-005dqc83.js → index-1dhf8ymv.js} +2 -2
- package/{index-00ke4phc.js → index-3gccwenr.js} +1 -1
- package/{index-2epb3wgh.js → index-3txrjt6n.js} +2 -2
- package/{index-7ndgffg4.js → index-57q1ayd2.js} +18 -1240
- package/index-5kh9scvs.js +514 -0
- package/index-5n5hds19.js +1246 -0
- package/{index-9sa6abze.js → index-6269mf2s.js} +10 -9
- package/{index-921cxqrd.js → index-64g9fsjy.js} +41 -12
- package/index-7zeb5r1p.js +653 -0
- package/{index-s4c2y5gs.js → index-8s8b4eba.js} +45 -4
- package/{index-4332q6yj.js → index-922k2zwq.js} +3 -3
- package/{index-m6qgr1rx.js → index-9ndw5d8j.js} +7 -7
- package/{index-xfp4dcnx.js → index-et6ce601.js} +1 -1
- package/{index-saj9cx3a.js → index-f5adsa58.js} +4 -4
- package/{index-vgt25eh1.js → index-fbewhg4g.js} +7 -32
- package/{index-ysyt782g.js → index-hm7x0c11.js} +4 -4
- package/{index-2p1brf5e.js → index-hvv5rnaq.js} +2 -2
- package/index-jje9qzyq.js +27 -0
- package/{index-rxse80x6.js → index-js1gj6f6.js} +12 -10
- package/{index-p2pahmsa.js → index-kjrvwzav.js} +3 -3
- package/index-m6r88hhr.js +3582 -0
- package/{index-mk391h0z.js → index-mt0wa941.js} +4 -4
- package/{index-m93qg20j.js → index-mwj9q2ya.js} +1 -1
- package/{index-5nd1wtkv.js → index-p6x5b7hr.js} +1 -1
- package/index-r2wedvqn.js +138 -0
- package/{index-gxj80jz7.js → index-rvynj5gz.js} +1 -1
- package/{index-m54n0v29.js → index-tdv66eah.js} +4 -4
- package/{index-vq77g679.js → index-w134p86k.js} +1 -1
- package/{index-deeskxjh.js → index-wfczhj1z.js} +14 -36
- package/{index-dy0jx9ay.js → index-wwe9rsrx.js} +14 -0
- package/{index-qx4r4cj2.js → index-x5ecanqh.js} +2 -2
- package/{index-nzfgyw3b.js → index-zre4m2ce.js} +4 -4
- package/index.js +23 -22
- package/{library.command-hmbkcwzw.js → library.command-sh70fyvy.js} +3 -3
- package/{localRegistry.command-sq5p4c9x.js → localRegistry.command-2nbyy84d.js} +14 -13
- package/{module.command-n4z29zcv.js → module.command-n0bmtzwy.js} +5 -5
- package/{package.command-20025dy3.js → package.command-7h9r51bz.js} +3 -3
- package/package.json +2 -2
- package/{page.command-q8fvpjer.js → page.command-vjtpfbb1.js} +3 -3
- package/{pipeline.command-8j97fq88.js → pipeline.command-c93se3ar.js} +2 -2
- package/{primitive.command-e5y6dqp1.js → primitive.command-a3075qp2.js} +6 -6
- package/{projectTypecheck-tbdye9k3.js → projectTypecheck-sf9xwaga.js} +1 -1
- package/{prompter-76k56b37.js → prompter-hgcta8pb.js} +1 -1
- package/quality.command-dw1y9hmy.js +76 -0
- package/{repair.command-dq1gckth.js → repair.command-tg57d8yt.js} +5 -5
- package/{scalar.command-5vwf152w.js → scalar.command-cwzge353.js} +4 -4
- package/skills/akan-agent/SKILL.md +36 -0
- package/skills/akan-debug/SKILL.md +3 -3
- package/skills/akan-deps/SKILL.md +1 -2
- package/skills/akan-mcp/SKILL.md +40 -0
- package/skills/akan-page/SKILL.md +44 -0
- package/skills/akan-query/SKILL.md +38 -0
- package/skills/akan-runtime/SKILL.md +40 -0
- package/skills/akan-scaffold/SKILL.md +16 -6
- package/skills/akan-transport/SKILL.md +40 -0
- package/skills/akan-validate/SKILL.md +13 -11
- package/{subspace.command-182be8vj.js → subspace.command-3h03c7kc.js} +8 -8
- package/templates/workspaceRoot/.gitignore.template +3 -0
- package/templates/workspaceRoot/AGENTS.md.template +4 -10
- package/{tunnel.command-bfzj7xkb.js → tunnel.command-czaz6ys4.js} +7 -7
- package/{typeChecker-px49mezc.js → typeChecker-j2jdnqsr.js} +1 -1
- package/typecheck.proc.js +6 -1
- package/verify.command-nzwhtz71.js +91 -0
- package/{workflow.command-3g53242s.js → workflow.command-srhky88x.js} +23 -13
- package/{workspace.command-h7399jwv.js → workspace.command-9stchcd2.js} +31 -29
- package/TunnelShare-dk2gw78d.js +0 -14
- package/agent.command-knp5j7bq.js +0 -25
- package/cloud.script-2r82sv0f.js +0 -24
- package/context.runner-c3wsh2jw.js +0 -26
- package/guidelines/conventions/conventions.instruction.md +0 -663
- package/guidelines/workspaceOnboarding/workspaceOnboarding.instruction.md +0 -291
- package/index-4t4qb8jg.js +0 -279
- package/index-hvg3esm0.js +0 -1844
- package/index-zzvvc845.js +0 -74
- package/quality.command-168pt5vm.js +0 -1788
- package/templates/workspaceRoot/docs/AI-DEVELOPMENT.md.template +0 -69
- package/templates/workspaceRoot/docs/GENERATED.md.template +0 -55
|
@@ -0,0 +1,3582 @@
|
|
|
1
|
+
// @bun
|
|
2
|
+
import {
|
|
3
|
+
camelToKebabCase,
|
|
4
|
+
runner
|
|
5
|
+
} from "./index-3gccwenr.js";
|
|
6
|
+
import {
|
|
7
|
+
FileSys2
|
|
8
|
+
} from "./index-52w0fvh8.js";
|
|
9
|
+
import {
|
|
10
|
+
extractAgentBlock,
|
|
11
|
+
collectScopeRecipeSources,
|
|
12
|
+
renderScopeAgentBlock,
|
|
13
|
+
JsonFormatter,
|
|
14
|
+
Linter,
|
|
15
|
+
rootAllowedFiles,
|
|
16
|
+
rootAllowedDirs,
|
|
17
|
+
isAllowedLibFacetRootFile,
|
|
18
|
+
libFacetRootHintOf,
|
|
19
|
+
facetIndexShadowOf,
|
|
20
|
+
rootEntryHintOf,
|
|
21
|
+
WorkspaceExecutor,
|
|
22
|
+
SysExecutor,
|
|
23
|
+
LibExecutor
|
|
24
|
+
} from "./index-64g9fsjy.js";
|
|
25
|
+
import {
|
|
26
|
+
countBlocking,
|
|
27
|
+
formatStyleContract,
|
|
28
|
+
ThemeValidator
|
|
29
|
+
} from "./index-62md4dwy.js";
|
|
30
|
+
import {
|
|
31
|
+
collectRecipeSources2,
|
|
32
|
+
scanRecipes2
|
|
33
|
+
} from "./index-hj6w4ka1.js";
|
|
34
|
+
import {
|
|
35
|
+
sysInputs,
|
|
36
|
+
workflowSpecs
|
|
37
|
+
} from "./index-fbewhg4g.js";
|
|
38
|
+
import {
|
|
39
|
+
getNpmRegistryUrl,
|
|
40
|
+
getLatestPackageVersion
|
|
41
|
+
} from "./index-m5n3ka0p.js";
|
|
42
|
+
|
|
43
|
+
// pkgs/@akanjs/cli/workspace/workspace.runner.ts
|
|
44
|
+
import { mkdir, writeFile as writeFile2 } from "fs/promises";
|
|
45
|
+
import path5 from "path";
|
|
46
|
+
|
|
47
|
+
// pkgs/@akanjs/devkit/biomeBase.ts
|
|
48
|
+
var biomeVersion = "2.5.14";
|
|
49
|
+
|
|
50
|
+
// pkgs/@akanjs/devkit/maintainabilityContract.ts
|
|
51
|
+
import { existsSync } from "fs";
|
|
52
|
+
import { readFile, rm, writeFile } from "fs/promises";
|
|
53
|
+
import path4 from "path";
|
|
54
|
+
import ts11 from "typescript";
|
|
55
|
+
|
|
56
|
+
// pkgs/@akanjs/devkit/componentSizeScanner.ts
|
|
57
|
+
import ts from "typescript";
|
|
58
|
+
|
|
59
|
+
class ComponentSizeScanner {
|
|
60
|
+
static #componentName = /^(?:[A-Z]|use[A-Z])[A-Za-z0-9]*$/;
|
|
61
|
+
static componentsAndHooksOf(sourceFile) {
|
|
62
|
+
return sourceFile.statements.flatMap((statement) => {
|
|
63
|
+
if (ts.isFunctionDeclaration(statement))
|
|
64
|
+
return statement.name && statement.body && ComponentSizeScanner.#componentName.test(statement.name.text) ? [{ name: statement.name.text, node: statement }] : [];
|
|
65
|
+
if (!ts.isVariableStatement(statement))
|
|
66
|
+
return [];
|
|
67
|
+
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 }] : []);
|
|
68
|
+
});
|
|
69
|
+
}
|
|
70
|
+
measure(sourceFile) {
|
|
71
|
+
return ComponentSizeScanner.componentsAndHooksOf(sourceFile).map(({ name, node }) => {
|
|
72
|
+
const line = sourceFile.getLineAndCharacterOfPosition(node.getStart(sourceFile)).line + 1;
|
|
73
|
+
const endLine = sourceFile.getLineAndCharacterOfPosition(node.getEnd()).line + 1;
|
|
74
|
+
return { name, line, lineCount: endLine - line + 1 };
|
|
75
|
+
});
|
|
76
|
+
}
|
|
77
|
+
static #holdsFunction(expression) {
|
|
78
|
+
let current = expression;
|
|
79
|
+
while (ts.isParenthesizedExpression(current) || ts.isAsExpression(current) || ts.isSatisfiesExpression(current))
|
|
80
|
+
current = current.expression;
|
|
81
|
+
if (ts.isArrowFunction(current) || ts.isFunctionExpression(current))
|
|
82
|
+
return true;
|
|
83
|
+
return ts.isCallExpression(current) && current.arguments.some((arg) => ComponentSizeScanner.#holdsFunction(arg));
|
|
84
|
+
}
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
// pkgs/@akanjs/devkit/componentWriteChainScanner.ts
|
|
88
|
+
import ts4 from "typescript";
|
|
89
|
+
|
|
90
|
+
// pkgs/@akanjs/devkit/storeAccessScanner.ts
|
|
91
|
+
import ts2 from "typescript";
|
|
92
|
+
class StoreAccessScanner {
|
|
93
|
+
static #formSetter = /^(?:(?:set|add|sub|addOrSub|upload)[A-Z]\w*On|writeOn)[A-Z]\w*$/;
|
|
94
|
+
#index;
|
|
95
|
+
constructor(index) {
|
|
96
|
+
this.#index = index;
|
|
97
|
+
}
|
|
98
|
+
static stNamesOf(sourceFile) {
|
|
99
|
+
return StoreAccessScanner.localNamesOf(sourceFile, "st");
|
|
100
|
+
}
|
|
101
|
+
static localNamesOf(sourceFile, imported) {
|
|
102
|
+
const names = new Set;
|
|
103
|
+
for (const statement of sourceFile.statements) {
|
|
104
|
+
if (!ts2.isImportDeclaration(statement) || statement.importClause?.isTypeOnly)
|
|
105
|
+
continue;
|
|
106
|
+
const bindings = statement.importClause?.namedBindings;
|
|
107
|
+
if (!bindings || !ts2.isNamedImports(bindings))
|
|
108
|
+
continue;
|
|
109
|
+
for (const element of bindings.elements)
|
|
110
|
+
if (!element.isTypeOnly && (element.propertyName ?? element.name).text === imported)
|
|
111
|
+
names.add(element.name.text);
|
|
112
|
+
}
|
|
113
|
+
return names;
|
|
114
|
+
}
|
|
115
|
+
measure(sourceFile) {
|
|
116
|
+
const stNames = StoreAccessScanner.stNamesOf(sourceFile);
|
|
117
|
+
if (!stNames.size)
|
|
118
|
+
return [];
|
|
119
|
+
return ComponentSizeScanner.componentsAndHooksOf(sourceFile).map(({ name, node }) => {
|
|
120
|
+
let accessCount = 0;
|
|
121
|
+
const visit = (child) => {
|
|
122
|
+
if (ts2.isPropertyAccessExpression(child) && ts2.isIdentifier(child.expression) && stNames.has(child.expression.text) && !this.#isFormSetter(child))
|
|
123
|
+
accessCount += 1;
|
|
124
|
+
ts2.forEachChild(child, visit);
|
|
125
|
+
};
|
|
126
|
+
visit(node);
|
|
127
|
+
return {
|
|
128
|
+
component: name,
|
|
129
|
+
line: sourceFile.getLineAndCharacterOfPosition(node.getStart(sourceFile)).line + 1,
|
|
130
|
+
accessCount
|
|
131
|
+
};
|
|
132
|
+
});
|
|
133
|
+
}
|
|
134
|
+
#isFormSetter(access) {
|
|
135
|
+
const action = access.parent;
|
|
136
|
+
return access.name.text === "do" && ts2.isPropertyAccessExpression(action) && action.expression === access && StoreAccessScanner.#formSetter.test(action.name.text) && !this.#index.isWritingAction(action.name.text);
|
|
137
|
+
}
|
|
138
|
+
}
|
|
139
|
+
|
|
140
|
+
// pkgs/@akanjs/devkit/writePath.ts
|
|
141
|
+
import ts3 from "typescript";
|
|
142
|
+
|
|
143
|
+
class WritePath {
|
|
144
|
+
static #perElement = new Set([
|
|
145
|
+
"map",
|
|
146
|
+
"flatMap",
|
|
147
|
+
"forEach",
|
|
148
|
+
"filter",
|
|
149
|
+
"reduce",
|
|
150
|
+
"some",
|
|
151
|
+
"every",
|
|
152
|
+
"find",
|
|
153
|
+
"findIndex"
|
|
154
|
+
]);
|
|
155
|
+
#matches;
|
|
156
|
+
#enters;
|
|
157
|
+
#repeated = new WeakSet;
|
|
158
|
+
constructor(matches, { enters = () => true } = {}) {
|
|
159
|
+
this.#matches = matches;
|
|
160
|
+
this.#enters = enters;
|
|
161
|
+
}
|
|
162
|
+
along(node) {
|
|
163
|
+
if (ts3.isFunctionLike(node) && !this.#enters(node))
|
|
164
|
+
return [];
|
|
165
|
+
if (WritePath.isPerElementCallback(node))
|
|
166
|
+
return this.#repeat(this.#children(node));
|
|
167
|
+
if (WritePath.#isFlowStatement(node))
|
|
168
|
+
return this.#busiestOf(this.#flowOf(node));
|
|
169
|
+
if (ts3.isConditionalExpression(node))
|
|
170
|
+
return [...this.along(node.condition), ...this.#busier(this.along(node.whenTrue), this.along(node.whenFalse))];
|
|
171
|
+
const own = ts3.isCallExpression(node) && this.#matches(node) ? [node] : [];
|
|
172
|
+
return [...own, ...this.#children(node)];
|
|
173
|
+
}
|
|
174
|
+
isRepeated(call) {
|
|
175
|
+
return this.#repeated.has(call);
|
|
176
|
+
}
|
|
177
|
+
countOf(calls) {
|
|
178
|
+
return calls.reduce((count, call) => count + (this.isRepeated(call) ? 2 : 1), 0);
|
|
179
|
+
}
|
|
180
|
+
labelOf(call, sourceFile) {
|
|
181
|
+
const callee = call.expression.getText(sourceFile);
|
|
182
|
+
return this.isRepeated(call) ? `${callee} (per item)` : callee;
|
|
183
|
+
}
|
|
184
|
+
static isPerElementCallback(node) {
|
|
185
|
+
const call = node.parent;
|
|
186
|
+
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);
|
|
187
|
+
}
|
|
188
|
+
#children(node) {
|
|
189
|
+
const children = [];
|
|
190
|
+
ts3.forEachChild(node, (child) => {
|
|
191
|
+
children.push(child);
|
|
192
|
+
});
|
|
193
|
+
return children.flatMap((child) => this.along(child));
|
|
194
|
+
}
|
|
195
|
+
#repeat(calls) {
|
|
196
|
+
for (const call of calls)
|
|
197
|
+
this.#repeated.add(call);
|
|
198
|
+
return calls;
|
|
199
|
+
}
|
|
200
|
+
#flowOf(node) {
|
|
201
|
+
if (ts3.isBlock(node))
|
|
202
|
+
return this.#sequenceOf(node.statements);
|
|
203
|
+
if (ts3.isReturnStatement(node) || ts3.isThrowStatement(node))
|
|
204
|
+
return { through: null, exit: node.expression ? this.along(node.expression) : [], jump: null };
|
|
205
|
+
if (ts3.isBreakStatement(node) || ts3.isContinueStatement(node))
|
|
206
|
+
return { through: null, exit: null, jump: [] };
|
|
207
|
+
if (ts3.isLabeledStatement(node))
|
|
208
|
+
return this.#flowOf(node.statement);
|
|
209
|
+
if (ts3.isIfStatement(node))
|
|
210
|
+
return WritePath.#prefixed(this.along(node.expression), this.#merged(this.#flowOf(node.thenStatement), node.elseStatement ? this.#flowOf(node.elseStatement) : WritePath.#onward([])));
|
|
211
|
+
if (ts3.isSwitchStatement(node))
|
|
212
|
+
return WritePath.#prefixed(this.along(node.expression), this.#switchOf(node));
|
|
213
|
+
if (ts3.isTryStatement(node))
|
|
214
|
+
return this.#tryOf(node);
|
|
215
|
+
if (ts3.isForOfStatement(node) || ts3.isForInStatement(node))
|
|
216
|
+
return this.#loopOf(this.along(node.expression), [], node.statement, true);
|
|
217
|
+
if (ts3.isForStatement(node))
|
|
218
|
+
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));
|
|
219
|
+
if (ts3.isWhileStatement(node) || ts3.isDoStatement(node))
|
|
220
|
+
return this.#loopOf([], this.along(node.expression), node.statement, WritePath.#walksItems(node.expression));
|
|
221
|
+
return WritePath.#onward(this.along(node));
|
|
222
|
+
}
|
|
223
|
+
#sequenceOf(statements) {
|
|
224
|
+
let through = [];
|
|
225
|
+
let exit = null;
|
|
226
|
+
let jump = null;
|
|
227
|
+
for (const statement of statements) {
|
|
228
|
+
if (through === null)
|
|
229
|
+
break;
|
|
230
|
+
const flow = this.#flowOf(statement);
|
|
231
|
+
if (flow.exit)
|
|
232
|
+
exit = this.#busierOf(exit, [...through, ...flow.exit]);
|
|
233
|
+
if (flow.jump)
|
|
234
|
+
jump = this.#busierOf(jump, [...through, ...flow.jump]);
|
|
235
|
+
through = flow.through && [...through, ...flow.through];
|
|
236
|
+
}
|
|
237
|
+
return { through, exit, jump };
|
|
238
|
+
}
|
|
239
|
+
#switchOf(node) {
|
|
240
|
+
const hasDefault = node.caseBlock.clauses.some(ts3.isDefaultClause);
|
|
241
|
+
let flow = { through: hasDefault ? null : [], exit: null, jump: null };
|
|
242
|
+
let fallen = null;
|
|
243
|
+
for (const clause of node.caseBlock.clauses) {
|
|
244
|
+
const entry = fallen && this.countOf(fallen) > 0 ? fallen : [];
|
|
245
|
+
const own = WritePath.#prefixed(entry, this.#sequenceOf(clause.statements));
|
|
246
|
+
flow = this.#merged(flow, { through: own.jump, exit: own.exit, jump: null });
|
|
247
|
+
fallen = own.through;
|
|
248
|
+
}
|
|
249
|
+
return this.#merged(flow, { through: fallen, exit: null, jump: null });
|
|
250
|
+
}
|
|
251
|
+
#tryOf(node) {
|
|
252
|
+
const tried = this.#flowOf(node.tryBlock);
|
|
253
|
+
const sent = this.#busiestOf(tried);
|
|
254
|
+
const caught = node.catchClause ? WritePath.#prefixed(sent, this.#flowOf(node.catchClause.block)) : { through: null, exit: sent, jump: null };
|
|
255
|
+
const flow = this.#merged(tried, caught);
|
|
256
|
+
if (!node.finallyBlock)
|
|
257
|
+
return flow;
|
|
258
|
+
const after = this.#busiestOf(this.#flowOf(node.finallyBlock));
|
|
259
|
+
return {
|
|
260
|
+
through: flow.through && [...flow.through, ...after],
|
|
261
|
+
exit: flow.exit && [...flow.exit, ...after],
|
|
262
|
+
jump: flow.jump && [...flow.jump, ...after]
|
|
263
|
+
};
|
|
264
|
+
}
|
|
265
|
+
#loopOf(once, everyTurn, body, isPerItem) {
|
|
266
|
+
const flow = this.#flowOf(body);
|
|
267
|
+
const turn = [...everyTurn, ...this.#busierOf(flow.through, flow.jump) ?? []];
|
|
268
|
+
const repeated = isPerItem ? this.#repeat(turn) : turn;
|
|
269
|
+
return { through: [...once, ...repeated], exit: flow.exit && [...once, ...flow.exit], jump: null };
|
|
270
|
+
}
|
|
271
|
+
#merged(a, b) {
|
|
272
|
+
return {
|
|
273
|
+
through: this.#busierOf(a.through, b.through),
|
|
274
|
+
exit: this.#busierOf(a.exit, b.exit),
|
|
275
|
+
jump: this.#busierOf(a.jump, b.jump)
|
|
276
|
+
};
|
|
277
|
+
}
|
|
278
|
+
#busiestOf({ through, exit, jump }) {
|
|
279
|
+
return this.#busierOf(this.#busierOf(through, exit), jump) ?? [];
|
|
280
|
+
}
|
|
281
|
+
#busierOf(a, b) {
|
|
282
|
+
return a && b ? this.#busier(a, b) : a ?? b;
|
|
283
|
+
}
|
|
284
|
+
static #onward(calls) {
|
|
285
|
+
return { through: calls, exit: null, jump: null };
|
|
286
|
+
}
|
|
287
|
+
static #prefixed(calls, { through, exit, jump }) {
|
|
288
|
+
return {
|
|
289
|
+
through: through && [...calls, ...through],
|
|
290
|
+
exit: exit && [...calls, ...exit],
|
|
291
|
+
jump: jump && [...calls, ...jump]
|
|
292
|
+
};
|
|
293
|
+
}
|
|
294
|
+
static #isFlowStatement(node) {
|
|
295
|
+
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);
|
|
296
|
+
}
|
|
297
|
+
static #walksItems(node) {
|
|
298
|
+
if (!node)
|
|
299
|
+
return false;
|
|
300
|
+
if (ts3.isCallExpression(node))
|
|
301
|
+
return true;
|
|
302
|
+
if (ts3.isPropertyAccessExpression(node) && ["length", "size"].includes(node.name.text))
|
|
303
|
+
return true;
|
|
304
|
+
return !!ts3.forEachChild(node, (child) => WritePath.#walksItems(child) || undefined);
|
|
305
|
+
}
|
|
306
|
+
#busier = (a, b) => this.countOf(b) > this.countOf(a) ? b : a;
|
|
307
|
+
}
|
|
308
|
+
|
|
309
|
+
// pkgs/@akanjs/devkit/componentWriteChainScanner.ts
|
|
310
|
+
class ComponentWriteChainScanner {
|
|
311
|
+
static #inlineCallers = new Set([
|
|
312
|
+
"map",
|
|
313
|
+
"flatMap",
|
|
314
|
+
"forEach",
|
|
315
|
+
"filter",
|
|
316
|
+
"reduce",
|
|
317
|
+
"some",
|
|
318
|
+
"every",
|
|
319
|
+
"find",
|
|
320
|
+
"findIndex",
|
|
321
|
+
"then",
|
|
322
|
+
"catch",
|
|
323
|
+
"finally"
|
|
324
|
+
]);
|
|
325
|
+
#index;
|
|
326
|
+
constructor(index) {
|
|
327
|
+
this.#index = index;
|
|
328
|
+
}
|
|
329
|
+
scan(sourceFile) {
|
|
330
|
+
const stNames = StoreAccessScanner.stNamesOf(sourceFile);
|
|
331
|
+
if (!stNames.size)
|
|
332
|
+
return [];
|
|
333
|
+
const path = new WritePath((call) => {
|
|
334
|
+
const action = ComponentWriteChainScanner.#actionOf(call.expression, stNames);
|
|
335
|
+
return !!action && this.#index.isWritingAction(action);
|
|
336
|
+
}, { enters: ComponentWriteChainScanner.#isInlineCallback });
|
|
337
|
+
return ComponentSizeScanner.componentsAndHooksOf(sourceFile).flatMap(({ name, node }) => ComponentWriteChainScanner.#handlersIn(node).flatMap((handler) => {
|
|
338
|
+
const writes = path.along(handler);
|
|
339
|
+
const writeCount = path.countOf(writes);
|
|
340
|
+
const second = writes[1] ?? writes[0];
|
|
341
|
+
if (writeCount < 2 || !second)
|
|
342
|
+
return [];
|
|
343
|
+
return [
|
|
344
|
+
{
|
|
345
|
+
component: name,
|
|
346
|
+
line: sourceFile.getLineAndCharacterOfPosition(second.getStart(sourceFile)).line + 1,
|
|
347
|
+
writes: writes.map((call) => path.labelOf(call, sourceFile)),
|
|
348
|
+
writeCount
|
|
349
|
+
}
|
|
350
|
+
];
|
|
351
|
+
}));
|
|
352
|
+
}
|
|
353
|
+
static #handlersIn(component) {
|
|
354
|
+
const bodies = [];
|
|
355
|
+
const visit = (node) => {
|
|
356
|
+
if (ComponentWriteChainScanner.#isFunction(node) && node.body && !ComponentWriteChainScanner.#isInlineCallback(node))
|
|
357
|
+
bodies.push(node.body);
|
|
358
|
+
ts4.forEachChild(node, visit);
|
|
359
|
+
};
|
|
360
|
+
visit(component);
|
|
361
|
+
return bodies;
|
|
362
|
+
}
|
|
363
|
+
static #isFunction(node) {
|
|
364
|
+
return ts4.isArrowFunction(node) || ts4.isFunctionExpression(node) || ts4.isFunctionDeclaration(node) || ts4.isMethodDeclaration(node);
|
|
365
|
+
}
|
|
366
|
+
static #isInlineCallback(fn) {
|
|
367
|
+
const call = fn.parent;
|
|
368
|
+
return !!call && ts4.isCallExpression(call) && call.arguments.some((arg) => arg === fn) && ts4.isPropertyAccessExpression(call.expression) && ComponentWriteChainScanner.#inlineCallers.has(call.expression.name.text);
|
|
369
|
+
}
|
|
370
|
+
static #actionOf(callee, stNames) {
|
|
371
|
+
if (!ts4.isPropertyAccessExpression(callee) || !ts4.isPropertyAccessExpression(callee.expression))
|
|
372
|
+
return null;
|
|
373
|
+
const { expression: st, name } = callee.expression;
|
|
374
|
+
return ts4.isIdentifier(st) && stNames.has(st.text) && name.text === "do" ? callee.name.text : null;
|
|
375
|
+
}
|
|
376
|
+
}
|
|
377
|
+
|
|
378
|
+
// pkgs/@akanjs/devkit/endpointReach.ts
|
|
379
|
+
import path from "path";
|
|
380
|
+
import ts5 from "typescript";
|
|
381
|
+
|
|
382
|
+
class EndpointReach {
|
|
383
|
+
static #requestBuilders = new Set(["endpoint", "slice"]);
|
|
384
|
+
#reached = new Set;
|
|
385
|
+
constructor(signalFiles, serviceFiles) {
|
|
386
|
+
const methodsByService = new Map;
|
|
387
|
+
for (const { file, sourceFile } of serviceFiles) {
|
|
388
|
+
const methods = methodsByService.get(EndpointReach.serviceOf(file)) ?? new Map;
|
|
389
|
+
for (const cls of sourceFile.statements.filter(ts5.isClassDeclaration))
|
|
390
|
+
for (const member of cls.members)
|
|
391
|
+
if (ts5.isMethodDeclaration(member) && member.body && (ts5.isIdentifier(member.name) || ts5.isPrivateIdentifier(member.name)))
|
|
392
|
+
methods.set(member.name.text, member);
|
|
393
|
+
methodsByService.set(EndpointReach.serviceOf(file), methods);
|
|
394
|
+
}
|
|
395
|
+
const pending = [];
|
|
396
|
+
const reach = ([service, method]) => {
|
|
397
|
+
const key = `${service}.${method}`;
|
|
398
|
+
if (this.#reached.has(key) || !methodsByService.get(service)?.has(method))
|
|
399
|
+
return;
|
|
400
|
+
this.#reached.add(key);
|
|
401
|
+
pending.push([service, method]);
|
|
402
|
+
};
|
|
403
|
+
for (const { sourceFile } of signalFiles)
|
|
404
|
+
for (const cls of sourceFile.statements.filter(ts5.isClassDeclaration)) {
|
|
405
|
+
const base = cls.heritageClauses?.[0]?.types[0]?.expression;
|
|
406
|
+
if (base && ts5.isCallExpression(base) && ts5.isIdentifier(base.expression) && EndpointReach.#requestBuilders.has(base.expression.text))
|
|
407
|
+
EndpointReach.#serviceCallsIn(base, null).forEach(reach);
|
|
408
|
+
}
|
|
409
|
+
for (let next = pending.pop();next; next = pending.pop()) {
|
|
410
|
+
const [service, method] = next;
|
|
411
|
+
const declaration = methodsByService.get(service)?.get(method);
|
|
412
|
+
if (declaration)
|
|
413
|
+
EndpointReach.#serviceCallsIn(declaration, service).forEach(reach);
|
|
414
|
+
}
|
|
415
|
+
}
|
|
416
|
+
static serviceOf(file) {
|
|
417
|
+
return path.posix.basename(file).replace(/\.service\.ts$/, "");
|
|
418
|
+
}
|
|
419
|
+
reaches(service, method) {
|
|
420
|
+
return this.#reached.has(`${service}.${method}`);
|
|
421
|
+
}
|
|
422
|
+
static #serviceCallsIn(node, ownService) {
|
|
423
|
+
const calls = [];
|
|
424
|
+
const visit = (child) => {
|
|
425
|
+
if (ts5.isCallExpression(child) && ts5.isPropertyAccessExpression(child.expression)) {
|
|
426
|
+
const { expression: owner, name } = child.expression;
|
|
427
|
+
if (owner.kind === ts5.SyntaxKind.ThisKeyword && ownService)
|
|
428
|
+
calls.push([ownService, name.text]);
|
|
429
|
+
else if (ts5.isPropertyAccessExpression(owner) && owner.expression.kind === ts5.SyntaxKind.ThisKeyword) {
|
|
430
|
+
const field = owner.name.text;
|
|
431
|
+
if (field.length > "Service".length && field.endsWith("Service"))
|
|
432
|
+
calls.push([field.slice(0, -"Service".length), name.text]);
|
|
433
|
+
}
|
|
434
|
+
}
|
|
435
|
+
ts5.forEachChild(child, visit);
|
|
436
|
+
};
|
|
437
|
+
visit(node);
|
|
438
|
+
return calls;
|
|
439
|
+
}
|
|
440
|
+
}
|
|
441
|
+
|
|
442
|
+
// pkgs/@akanjs/devkit/maintainabilityBaseline.ts
|
|
443
|
+
class MaintainabilityBaseline {
|
|
444
|
+
sections;
|
|
445
|
+
reasons;
|
|
446
|
+
static fileName = "akan.baseline.json";
|
|
447
|
+
static reasonMinChars = 10;
|
|
448
|
+
static debtRules = [
|
|
449
|
+
"akan.size.file",
|
|
450
|
+
"akan.size.component",
|
|
451
|
+
"akan.component.store-access",
|
|
452
|
+
"akan.store.multi-write",
|
|
453
|
+
"akan.store.root-write-chain",
|
|
454
|
+
"akan.component.write-chain",
|
|
455
|
+
"akan.write.placement",
|
|
456
|
+
"akan.service.call-in-loop"
|
|
457
|
+
];
|
|
458
|
+
static reasonedRules = new Set([
|
|
459
|
+
"akan.size.file",
|
|
460
|
+
"akan.size.component",
|
|
461
|
+
"akan.component.store-access",
|
|
462
|
+
"akan.service.call-in-loop"
|
|
463
|
+
]);
|
|
464
|
+
static countOf(violation) {
|
|
465
|
+
if (violation.kind === "size")
|
|
466
|
+
return violation.lineCount;
|
|
467
|
+
if (violation.kind === "storeAccess")
|
|
468
|
+
return violation.accessCount;
|
|
469
|
+
if (violation.kind === "multiWrite")
|
|
470
|
+
return violation.writeCount;
|
|
471
|
+
if (violation.kind === "writePlacement")
|
|
472
|
+
return violation.writes.length;
|
|
473
|
+
return violation.calls.length;
|
|
474
|
+
}
|
|
475
|
+
static isDebtRule(name) {
|
|
476
|
+
return MaintainabilityBaseline.debtRules.includes(name);
|
|
477
|
+
}
|
|
478
|
+
static parse(text, source = MaintainabilityBaseline.fileName, { lenient = false } = {}) {
|
|
479
|
+
let json;
|
|
480
|
+
try {
|
|
481
|
+
json = JSON.parse(text);
|
|
482
|
+
} catch {
|
|
483
|
+
throw new Error(`${source} is not valid JSON.`);
|
|
484
|
+
}
|
|
485
|
+
if (typeof json !== "object" || json === null || Array.isArray(json))
|
|
486
|
+
throw new Error(`${source} holds an object keyed by rule id.`);
|
|
487
|
+
const sections = new Map;
|
|
488
|
+
let reasons = new Map;
|
|
489
|
+
for (const [name, value] of Object.entries(json)) {
|
|
490
|
+
if (name === "reasons") {
|
|
491
|
+
const entries = MaintainabilityBaseline.#reasonsOf(value);
|
|
492
|
+
if (!entries)
|
|
493
|
+
throw new Error(`${source}: "reasons" maps an entry's key to a sentence.`);
|
|
494
|
+
reasons = new Map(entries);
|
|
495
|
+
continue;
|
|
496
|
+
}
|
|
497
|
+
if (!MaintainabilityBaseline.isDebtRule(name)) {
|
|
498
|
+
if (lenient)
|
|
499
|
+
continue;
|
|
500
|
+
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\`.`);
|
|
501
|
+
}
|
|
502
|
+
const counts = MaintainabilityBaseline.#countsOf(value);
|
|
503
|
+
if (!counts)
|
|
504
|
+
throw new Error(`${source}: "${name}" maps each key to a whole-number count.`);
|
|
505
|
+
sections.set(name, new Map(counts));
|
|
506
|
+
}
|
|
507
|
+
return new MaintainabilityBaseline(sections, reasons);
|
|
508
|
+
}
|
|
509
|
+
static of(violations, reasons = new Map) {
|
|
510
|
+
const sections = new Map;
|
|
511
|
+
for (const violation of violations) {
|
|
512
|
+
const counts = sections.get(violation.rule) ?? new Map;
|
|
513
|
+
const count = MaintainabilityBaseline.countOf(violation);
|
|
514
|
+
counts.set(violation.key, Math.max(counts.get(violation.key) ?? 0, count));
|
|
515
|
+
sections.set(violation.rule, counts);
|
|
516
|
+
}
|
|
517
|
+
return new MaintainabilityBaseline(sections).#withReasonsOf(reasons);
|
|
518
|
+
}
|
|
519
|
+
constructor(sections = new Map, reasons = new Map) {
|
|
520
|
+
this.sections = sections;
|
|
521
|
+
this.reasons = reasons;
|
|
522
|
+
}
|
|
523
|
+
get isEmpty() {
|
|
524
|
+
return [...this.sections.values()].every((counts) => !counts.size);
|
|
525
|
+
}
|
|
526
|
+
allows(violation) {
|
|
527
|
+
const recorded = this.recordedOf(violation);
|
|
528
|
+
return recorded !== undefined && MaintainabilityBaseline.countOf(violation) <= recorded;
|
|
529
|
+
}
|
|
530
|
+
recordedOf(violation) {
|
|
531
|
+
return this.sections.get(violation.rule)?.get(violation.key);
|
|
532
|
+
}
|
|
533
|
+
reasonOf(key) {
|
|
534
|
+
const reason = this.#holdsReasoned(key) ? this.reasons.get(key) : undefined;
|
|
535
|
+
return reason && reason.replace(/\s/g, "").length >= MaintainabilityBaseline.reasonMinChars ? reason : undefined;
|
|
536
|
+
}
|
|
537
|
+
entriesByRule() {
|
|
538
|
+
return new Map([...this.sections].filter(([, counts]) => counts.size).map(([rule, counts]) => [
|
|
539
|
+
rule,
|
|
540
|
+
[...counts].map(([key, count]) => ({
|
|
541
|
+
key,
|
|
542
|
+
count,
|
|
543
|
+
reason: MaintainabilityBaseline.reasonedRules.has(rule) ? this.reasonOf(key) : undefined
|
|
544
|
+
}))
|
|
545
|
+
]));
|
|
546
|
+
}
|
|
547
|
+
tightenedBy(violations) {
|
|
548
|
+
const current = MaintainabilityBaseline.of(violations);
|
|
549
|
+
const sections = new Map([...this.sections].map(([rule, counts]) => [
|
|
550
|
+
rule,
|
|
551
|
+
MaintainabilityBaseline.#lowered(counts, current.sections.get(rule) ?? new Map)
|
|
552
|
+
]));
|
|
553
|
+
return new MaintainabilityBaseline(sections).#withReasonsOf(this.reasons);
|
|
554
|
+
}
|
|
555
|
+
#withReasonsOf(reasons) {
|
|
556
|
+
return new MaintainabilityBaseline(this.sections, new Map([...reasons].filter(([key]) => this.#holdsReasoned(key))));
|
|
557
|
+
}
|
|
558
|
+
grownFrom(committed) {
|
|
559
|
+
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 })));
|
|
560
|
+
}
|
|
561
|
+
stringify() {
|
|
562
|
+
const sections = MaintainabilityBaseline.debtRules.flatMap((rule) => {
|
|
563
|
+
const counts = this.sections.get(rule);
|
|
564
|
+
return counts?.size ? [[rule, MaintainabilityBaseline.#sortedObjectOf(counts)]] : [];
|
|
565
|
+
});
|
|
566
|
+
return JsonFormatter.stringify({
|
|
567
|
+
...Object.fromEntries(sections),
|
|
568
|
+
...this.reasons.size ? { reasons: MaintainabilityBaseline.#sortedObjectOf(this.reasons) } : {}
|
|
569
|
+
}, MaintainabilityBaseline.fileName);
|
|
570
|
+
}
|
|
571
|
+
#holdsReasoned(key) {
|
|
572
|
+
return [...this.sections].some(([rule, counts]) => MaintainabilityBaseline.reasonedRules.has(rule) && counts.has(key));
|
|
573
|
+
}
|
|
574
|
+
static #countsOf(value) {
|
|
575
|
+
if (typeof value !== "object" || value === null || Array.isArray(value))
|
|
576
|
+
return null;
|
|
577
|
+
const entries = Object.entries(value);
|
|
578
|
+
return entries.every(([, count]) => Number.isInteger(count)) ? entries : null;
|
|
579
|
+
}
|
|
580
|
+
static #reasonsOf(value) {
|
|
581
|
+
if (typeof value !== "object" || value === null || Array.isArray(value))
|
|
582
|
+
return null;
|
|
583
|
+
const entries = Object.entries(value);
|
|
584
|
+
return entries.every(([, reason]) => typeof reason === "string") ? entries : null;
|
|
585
|
+
}
|
|
586
|
+
static #lowered(recorded, current) {
|
|
587
|
+
return new Map([...recorded].flatMap(([key, count]) => {
|
|
588
|
+
const measured = current.get(key);
|
|
589
|
+
return measured === undefined ? [] : [[key, Math.min(count, measured)]];
|
|
590
|
+
}));
|
|
591
|
+
}
|
|
592
|
+
static #raised(working, committed) {
|
|
593
|
+
return [...working].flatMap(([key, count]) => {
|
|
594
|
+
const recorded = committed.get(key);
|
|
595
|
+
return recorded !== undefined && count <= recorded ? [] : [[key, count, recorded]];
|
|
596
|
+
});
|
|
597
|
+
}
|
|
598
|
+
static #sortedObjectOf(values) {
|
|
599
|
+
return Object.fromEntries([...values].sort(([a], [b]) => MaintainabilityBaseline.#byKey(a, b)));
|
|
600
|
+
}
|
|
601
|
+
static #byKey(a, b) {
|
|
602
|
+
return a < b ? -1 : a > b ? 1 : 0;
|
|
603
|
+
}
|
|
604
|
+
}
|
|
605
|
+
|
|
606
|
+
// pkgs/@akanjs/devkit/maintainabilityLimits.ts
|
|
607
|
+
import path3 from "path";
|
|
608
|
+
import ts6 from "typescript";
|
|
609
|
+
|
|
610
|
+
// pkgs/@akanjs/devkit/abstractDoc.ts
|
|
611
|
+
import path2 from "path";
|
|
612
|
+
|
|
613
|
+
class AbstractDoc {
|
|
614
|
+
path;
|
|
615
|
+
content;
|
|
616
|
+
siblingFiles;
|
|
617
|
+
static suffix = ".abstract.md";
|
|
618
|
+
static maxLines = 300;
|
|
619
|
+
static #facetRoots = "{lib,ui,webkit,srvkit,common,plugin}";
|
|
620
|
+
static isAbstractPath(filePath) {
|
|
621
|
+
return filePath.endsWith(AbstractDoc.suffix);
|
|
622
|
+
}
|
|
623
|
+
static lineCountOf(content) {
|
|
624
|
+
return content.split(/\r?\n/).length;
|
|
625
|
+
}
|
|
626
|
+
static kindOf(filePath) {
|
|
627
|
+
const [root, folder, ...rest] = filePath.split("/");
|
|
628
|
+
if (root !== "lib" || !folder)
|
|
629
|
+
return "other";
|
|
630
|
+
if (folder === "__scalar")
|
|
631
|
+
return rest.length === 2 ? "scalar" : "other";
|
|
632
|
+
if (rest.length !== 1)
|
|
633
|
+
return "other";
|
|
634
|
+
return folder.startsWith("_") ? "service" : "domain";
|
|
635
|
+
}
|
|
636
|
+
static async findAll(sys, { module } = {}) {
|
|
637
|
+
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);
|
|
638
|
+
const docs = await Promise.all(filePaths.map((filePath) => AbstractDoc.read(sys, filePath)));
|
|
639
|
+
if (!module)
|
|
640
|
+
return docs;
|
|
641
|
+
return docs.filter((doc) => doc.moduleName === module || doc.folderName === module);
|
|
642
|
+
}
|
|
643
|
+
static async read(sys, filePath) {
|
|
644
|
+
const dirPath = filePath.split("/").slice(0, -1).join("/");
|
|
645
|
+
const [content, folderFiles] = await Promise.all([sys.readFile(filePath), sys.readdir(dirPath)]);
|
|
646
|
+
return new AbstractDoc(filePath, content, folderFiles.filter((fileName) => !AbstractDoc.isAbstractPath(fileName)));
|
|
647
|
+
}
|
|
648
|
+
constructor(path, content, siblingFiles) {
|
|
649
|
+
this.path = path;
|
|
650
|
+
this.content = content;
|
|
651
|
+
this.siblingFiles = siblingFiles;
|
|
652
|
+
}
|
|
653
|
+
get kind() {
|
|
654
|
+
return AbstractDoc.kindOf(this.path);
|
|
655
|
+
}
|
|
656
|
+
get folderName() {
|
|
657
|
+
return this.path.split("/").at(-2) ?? "";
|
|
658
|
+
}
|
|
659
|
+
get moduleName() {
|
|
660
|
+
return (this.path.split("/").at(-1) ?? "").slice(0, -AbstractDoc.suffix.length);
|
|
661
|
+
}
|
|
662
|
+
get lineCount() {
|
|
663
|
+
return AbstractDoc.lineCountOf(this.content);
|
|
664
|
+
}
|
|
665
|
+
canReplaceWith(candidate) {
|
|
666
|
+
const next = candidate.trim();
|
|
667
|
+
if (!next.startsWith("#"))
|
|
668
|
+
return false;
|
|
669
|
+
const lineCount = AbstractDoc.lineCountOf(next);
|
|
670
|
+
return lineCount >= 3 && lineCount < this.lineCount;
|
|
671
|
+
}
|
|
672
|
+
}
|
|
673
|
+
|
|
674
|
+
// pkgs/@akanjs/devkit/maintainabilityLimits.ts
|
|
675
|
+
class MaintainabilityLimits {
|
|
676
|
+
static fileMaxLines = {
|
|
677
|
+
".Template.tsx": 400,
|
|
678
|
+
".Unit.tsx": 400,
|
|
679
|
+
".Util.tsx": 400,
|
|
680
|
+
".View.tsx": 400,
|
|
681
|
+
".Zone.tsx": 400,
|
|
682
|
+
".store.ts": 400,
|
|
683
|
+
".document.ts": 500,
|
|
684
|
+
".service.ts": 500,
|
|
685
|
+
[AbstractDoc.suffix]: AbstractDoc.maxLines
|
|
686
|
+
};
|
|
687
|
+
static folderMaxLines = { "ui/": 400, "webkit/": 400 };
|
|
688
|
+
static #maxLinesByKind = { ...MaintainabilityLimits.fileMaxLines, ...MaintainabilityLimits.folderMaxLines };
|
|
689
|
+
static componentMaxLines = 250;
|
|
690
|
+
static componentMaxStoreAccesses = 16;
|
|
691
|
+
static fileKindOf(sysRelativePath) {
|
|
692
|
+
const kinds = Object.keys(MaintainabilityLimits.#maxLinesByKind);
|
|
693
|
+
const suffix = kinds.find((kind) => sysRelativePath.endsWith(kind));
|
|
694
|
+
if (suffix)
|
|
695
|
+
return suffix;
|
|
696
|
+
if (!/\.tsx?$/.test(sysRelativePath) || MaintainabilityLimits.#isTest(sysRelativePath))
|
|
697
|
+
return null;
|
|
698
|
+
return kinds.find((kind) => sysRelativePath.startsWith(kind)) ?? null;
|
|
699
|
+
}
|
|
700
|
+
static fileMaxLinesOf(sysRelativePath) {
|
|
701
|
+
const kind = MaintainabilityLimits.fileKindOf(sysRelativePath);
|
|
702
|
+
return kind ? MaintainabilityLimits.#maxLinesByKind[kind] : null;
|
|
703
|
+
}
|
|
704
|
+
static isReexportBarrel(file, content) {
|
|
705
|
+
if (path3.posix.basename(file) !== "index.ts")
|
|
706
|
+
return false;
|
|
707
|
+
return ts6.createSourceFile(file, content, ts6.ScriptTarget.Latest, false, ts6.ScriptKind.TS).statements.every((statement) => ts6.isExportDeclaration(statement));
|
|
708
|
+
}
|
|
709
|
+
static lineCountOf(content) {
|
|
710
|
+
return AbstractDoc.lineCountOf(content);
|
|
711
|
+
}
|
|
712
|
+
static isClientCode(sysRelativePath) {
|
|
713
|
+
if (MaintainabilityLimits.#isTest(sysRelativePath))
|
|
714
|
+
return false;
|
|
715
|
+
if (sysRelativePath.startsWith("lib/"))
|
|
716
|
+
return sysRelativePath.endsWith(".tsx");
|
|
717
|
+
return /^(ui|webkit)\/.+\.tsx?$/.test(sysRelativePath) && !sysRelativePath.endsWith(".d.ts");
|
|
718
|
+
}
|
|
719
|
+
static #isTest(sysRelativePath) {
|
|
720
|
+
return /\.(test|spec)\.tsx?$/.test(sysRelativePath);
|
|
721
|
+
}
|
|
722
|
+
}
|
|
723
|
+
|
|
724
|
+
// pkgs/@akanjs/devkit/maintainabilityReport.ts
|
|
725
|
+
class MaintainabilityReport {
|
|
726
|
+
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/`.';
|
|
727
|
+
static #serverMarkupFix = "Move model-independent pieces into ui/ components and display logic onto Light<Model>.";
|
|
728
|
+
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.";
|
|
729
|
+
static #fixes = {
|
|
730
|
+
".Template.tsx": MaintainabilityReport.#clientSplitFix,
|
|
731
|
+
".Unit.tsx": MaintainabilityReport.#serverMarkupFix,
|
|
732
|
+
".Util.tsx": MaintainabilityReport.#clientSplitFix,
|
|
733
|
+
".View.tsx": MaintainabilityReport.#serverMarkupFix,
|
|
734
|
+
".Zone.tsx": MaintainabilityReport.#clientSplitFix,
|
|
735
|
+
"ui/": MaintainabilityReport.#clientSplitFix,
|
|
736
|
+
"webkit/": MaintainabilityReport.#clientSplitFix,
|
|
737
|
+
".store.ts": "Move business logic into the service behind an endpoint and derived values onto Light<Model>; an action is fetch, set, toast.",
|
|
738
|
+
".document.ts": "Move display and predicate logic onto Light<Model>, and split an unrelated concept into its own module.",
|
|
739
|
+
".service.ts": "Move state transitions into document chain methods, and split an unrelated responsibility into its own module.",
|
|
740
|
+
[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.",
|
|
741
|
+
"akan.size.component": MaintainabilityReport.#clientSplitFix,
|
|
742
|
+
"akan.store.multi-write": MaintainabilityReport.#oneEndpointFix,
|
|
743
|
+
"akan.store.root-write-chain": `A store may call another through \`RootStore\`, but that does not make the writes one. ${MaintainabilityReport.#oneEndpointFix}`,
|
|
744
|
+
"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.",
|
|
745
|
+
"akan.component.store-access": MaintainabilityReport.#clientSplitFix,
|
|
746
|
+
"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.",
|
|
747
|
+
"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.",
|
|
748
|
+
"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."
|
|
749
|
+
};
|
|
750
|
+
static #labels = {
|
|
751
|
+
"ui/": "ui/**",
|
|
752
|
+
"webkit/": "webkit/**",
|
|
753
|
+
"akan.size.component": "component or hook",
|
|
754
|
+
"akan.store.multi-write": "store action with several writes",
|
|
755
|
+
"akan.store.root-write-chain": "store method chaining other stores' writes",
|
|
756
|
+
"akan.component.write-chain": "handler with several writes",
|
|
757
|
+
"akan.component.store-access": "component or hook reaching the store often",
|
|
758
|
+
"akan.write.placement": "write sent outside a store action or module component",
|
|
759
|
+
"akan.service.call-in-loop": "service call per item",
|
|
760
|
+
"akan.baseline.growth": "baseline entry"
|
|
761
|
+
};
|
|
762
|
+
static #units = {
|
|
763
|
+
"akan.size.file": "lines",
|
|
764
|
+
"akan.size.component": "lines",
|
|
765
|
+
"akan.component.store-access": "store accesses",
|
|
766
|
+
"akan.store.multi-write": "writes",
|
|
767
|
+
"akan.store.root-write-chain": "writes",
|
|
768
|
+
"akan.component.write-chain": "writes",
|
|
769
|
+
"akan.write.placement": "writes",
|
|
770
|
+
"akan.service.call-in-loop": "calls per item"
|
|
771
|
+
};
|
|
772
|
+
static describe(sysPath, failures, commands = {}) {
|
|
773
|
+
const groups = new Map;
|
|
774
|
+
for (const failure of failures) {
|
|
775
|
+
const fixKey = MaintainabilityReport.#fixKeyOf(failure);
|
|
776
|
+
const fix = MaintainabilityReport.#fixes[fixKey];
|
|
777
|
+
const group = groups.get(fix) ?? { labels: [], rules: new Set };
|
|
778
|
+
const label = MaintainabilityReport.#labelOf(fixKey);
|
|
779
|
+
if (!group.labels.includes(label))
|
|
780
|
+
group.labels.push(label);
|
|
781
|
+
group.rules.add(failure.rule);
|
|
782
|
+
groups.set(fix, group);
|
|
783
|
+
}
|
|
784
|
+
return [
|
|
785
|
+
`[maintainability] ${failures.length} violation(s) in ${sysPath}:`,
|
|
786
|
+
...failures.map((failure) => ` ${sysPath}/${failure.file}:${failure.line} ${failure.rule} ${MaintainabilityReport.#problemOf(failure)}`),
|
|
787
|
+
"How to fix:",
|
|
788
|
+
...[...groups].flatMap(([fix, { labels, rules }]) => [
|
|
789
|
+
` ${labels.join(", ")}: ${fix}`,
|
|
790
|
+
...[...new Set([...rules].flatMap((rule) => commands[rule] ?? []))].map((command) => ` Path: ${command}`)
|
|
791
|
+
])
|
|
792
|
+
].join(`
|
|
793
|
+
`);
|
|
794
|
+
}
|
|
795
|
+
static entriesOf(sysPath, failures, commands = {}) {
|
|
796
|
+
return failures.map((failure) => ({
|
|
797
|
+
file: `${sysPath}/${failure.file}`,
|
|
798
|
+
line: failure.line,
|
|
799
|
+
rule: failure.rule,
|
|
800
|
+
problem: MaintainabilityReport.#problemOf(failure),
|
|
801
|
+
fix: MaintainabilityReport.#fixes[MaintainabilityReport.#fixKeyOf(failure)],
|
|
802
|
+
path: commands[failure.rule]?.[0] ?? null
|
|
803
|
+
}));
|
|
804
|
+
}
|
|
805
|
+
static #problemOf(failure) {
|
|
806
|
+
if (failure.kind === "baselineGrowth") {
|
|
807
|
+
const entry = `entry "${failure.key}" under ${failure.debtRule}`;
|
|
808
|
+
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`;
|
|
809
|
+
}
|
|
810
|
+
const grown = failure.recorded === undefined ? "" : `, more than the ${failure.recorded} recorded`;
|
|
811
|
+
if (failure.kind === "multiWrite") {
|
|
812
|
+
const writes = failure.writes.some((write) => write.endsWith("(per item)")) ? "a write per item" : `${failure.writes.length} writes`;
|
|
813
|
+
const listed = `${failure.writes.join(", ")}${grown}`;
|
|
814
|
+
if (failure.rule === "akan.component.write-chain")
|
|
815
|
+
return `${MaintainabilityReport.#unitOf(failure.owner)} ${failure.owner} sends ${writes} from one handler: ${listed}`;
|
|
816
|
+
if (failure.rule === "akan.store.root-write-chain")
|
|
817
|
+
return `store method ${failure.owner} chains ${writes} through other stores from the browser: ${listed}`;
|
|
818
|
+
return `store action ${failure.owner} sends ${writes} from the browser: ${listed}`;
|
|
819
|
+
}
|
|
820
|
+
if (failure.kind === "writePlacement")
|
|
821
|
+
return `sends ${failure.writes.length} server write(s) from outside a store action or a module component: ${failure.writes.join(", ")}${grown}`;
|
|
822
|
+
if (failure.kind === "loopCall")
|
|
823
|
+
return `service method ${failure.owner} calls once per item: ${failure.calls.join(", ")}${grown}`;
|
|
824
|
+
if (failure.kind === "storeAccess")
|
|
825
|
+
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}`}`;
|
|
826
|
+
const subject = failure.component ? `${MaintainabilityReport.#unitOf(failure.component)} ${failure.component} has` : "file has";
|
|
827
|
+
const up = failure.recorded === undefined ? "" : `, up from ${failure.recorded}`;
|
|
828
|
+
return `${subject} ${failure.lineCount} lines, over the ${failure.maxLines}-line limit${up}`;
|
|
829
|
+
}
|
|
830
|
+
static #unitOf(name) {
|
|
831
|
+
return /^use[A-Z]/.test(name) ? "hook" : "component";
|
|
832
|
+
}
|
|
833
|
+
static #fixKeyOf(failure) {
|
|
834
|
+
if (failure.rule !== "akan.size.file")
|
|
835
|
+
return failure.rule;
|
|
836
|
+
return MaintainabilityLimits.fileKindOf(failure.file) ?? "akan.size.component";
|
|
837
|
+
}
|
|
838
|
+
static #labelOf(fixKey) {
|
|
839
|
+
return MaintainabilityReport.#labels[fixKey] ?? `*${fixKey}`;
|
|
840
|
+
}
|
|
841
|
+
}
|
|
842
|
+
|
|
843
|
+
// pkgs/@akanjs/devkit/serviceLoopCallScanner.ts
|
|
844
|
+
import ts7 from "typescript";
|
|
845
|
+
class ServiceLoopCallScanner {
|
|
846
|
+
static #reachingField = /(?:Service|Model)$/;
|
|
847
|
+
static #generatedQuery = /^_*(?:get|load|list|find|pick|exists|count|insight|create|update|remove|search)[A-Z]/;
|
|
848
|
+
scan(sourceFile, answersCaller) {
|
|
849
|
+
return sourceFile.statements.filter(ts7.isClassDeclaration).flatMap((cls) => {
|
|
850
|
+
const methods = cls.members.filter((member) => ts7.isMethodDeclaration(member) && !!member.body && (ts7.isIdentifier(member.name) || ts7.isPrivateIdentifier(member.name)));
|
|
851
|
+
const declared = new Set(methods.map((method) => method.name.text));
|
|
852
|
+
const reaching = ServiceLoopCallScanner.#reachingMethodsOf(methods, declared);
|
|
853
|
+
const reaches = (call) => ServiceLoopCallScanner.#reaches(call, declared, reaching);
|
|
854
|
+
const ownModel = cls.name?.text.replace(/Service$/, "") ?? "";
|
|
855
|
+
return methods.flatMap((method) => {
|
|
856
|
+
if (!answersCaller(method.name.text))
|
|
857
|
+
return [];
|
|
858
|
+
const calls = [];
|
|
859
|
+
const visit = (node, perItem) => {
|
|
860
|
+
if (perItem && ts7.isCallExpression(node) && reaches(node) && !(perItem === "callback" && ServiceLoopCallScanner.#isBatchedLoad(node, declared, ownModel)))
|
|
861
|
+
calls.push(node);
|
|
862
|
+
if (ts7.isForOfStatement(node) || ts7.isForInStatement(node)) {
|
|
863
|
+
visit(node.expression, perItem);
|
|
864
|
+
visit(node.statement, "loop");
|
|
865
|
+
return;
|
|
866
|
+
}
|
|
867
|
+
ts7.forEachChild(node, (child) => visit(child, perItem === "loop" || !WritePath.isPerElementCallback(child) ? perItem : "callback"));
|
|
868
|
+
};
|
|
869
|
+
visit(method, false);
|
|
870
|
+
const first = calls[0];
|
|
871
|
+
if (!first)
|
|
872
|
+
return [];
|
|
873
|
+
return [
|
|
874
|
+
{
|
|
875
|
+
method: method.name.text,
|
|
876
|
+
line: sourceFile.getLineAndCharacterOfPosition(first.getStart(sourceFile)).line + 1,
|
|
877
|
+
calls: calls.map((call) => call.expression.getText(sourceFile))
|
|
878
|
+
}
|
|
879
|
+
];
|
|
880
|
+
});
|
|
881
|
+
});
|
|
882
|
+
}
|
|
883
|
+
static #reachingMethodsOf(methods, declared) {
|
|
884
|
+
const reaching = new Set;
|
|
885
|
+
let grew = true;
|
|
886
|
+
while (grew) {
|
|
887
|
+
grew = false;
|
|
888
|
+
for (const method of methods) {
|
|
889
|
+
const name = method.name.text;
|
|
890
|
+
if (reaching.has(name))
|
|
891
|
+
continue;
|
|
892
|
+
let found = false;
|
|
893
|
+
const visit = (node) => {
|
|
894
|
+
if (found)
|
|
895
|
+
return;
|
|
896
|
+
if (ts7.isCallExpression(node) && ServiceLoopCallScanner.#reaches(node, declared, reaching))
|
|
897
|
+
found = true;
|
|
898
|
+
else
|
|
899
|
+
ts7.forEachChild(node, visit);
|
|
900
|
+
};
|
|
901
|
+
visit(method);
|
|
902
|
+
if (found) {
|
|
903
|
+
reaching.add(name);
|
|
904
|
+
grew = true;
|
|
905
|
+
}
|
|
906
|
+
}
|
|
907
|
+
}
|
|
908
|
+
return reaching;
|
|
909
|
+
}
|
|
910
|
+
static #isBatchedLoad(call, declared, ownModel) {
|
|
911
|
+
const callee = call.expression;
|
|
912
|
+
if (!ts7.isPropertyAccessExpression(callee))
|
|
913
|
+
return false;
|
|
914
|
+
const model = ServiceLoopCallScanner.#loadedModelOf(callee, declared, ownModel);
|
|
915
|
+
if (!model)
|
|
916
|
+
return false;
|
|
917
|
+
const className = `${model.charAt(0).toUpperCase()}${model.slice(1)}`;
|
|
918
|
+
return [`get${className}`, `load${className}`, `load${className}Many`].includes(callee.name.text);
|
|
919
|
+
}
|
|
920
|
+
static #loadedModelOf(callee, declared, ownModel) {
|
|
921
|
+
const owner = callee.expression;
|
|
922
|
+
if (owner.kind === ts7.SyntaxKind.ThisKeyword)
|
|
923
|
+
return declared.has(callee.name.text) ? null : ownModel;
|
|
924
|
+
if (!ts7.isPropertyAccessExpression(owner) || owner.expression.kind !== ts7.SyntaxKind.ThisKeyword)
|
|
925
|
+
return null;
|
|
926
|
+
return owner.name.text.match(/^(\w+)Model$/)?.[1] ?? null;
|
|
927
|
+
}
|
|
928
|
+
static #reaches(call, declared, reaching) {
|
|
929
|
+
const callee = call.expression;
|
|
930
|
+
if (!ts7.isPropertyAccessExpression(callee))
|
|
931
|
+
return false;
|
|
932
|
+
const owner = callee.expression;
|
|
933
|
+
if (owner.kind === ts7.SyntaxKind.ThisKeyword) {
|
|
934
|
+
const name = callee.name.text;
|
|
935
|
+
return declared.has(name) ? reaching.has(name) : ServiceLoopCallScanner.#generatedQuery.test(name);
|
|
936
|
+
}
|
|
937
|
+
return ts7.isPropertyAccessExpression(owner) && owner.expression.kind === ts7.SyntaxKind.ThisKeyword && ServiceLoopCallScanner.#reachingField.test(owner.name.text);
|
|
938
|
+
}
|
|
939
|
+
}
|
|
940
|
+
|
|
941
|
+
// pkgs/@akanjs/devkit/signalMutationIndex.ts
|
|
942
|
+
import ts8 from "typescript";
|
|
943
|
+
|
|
944
|
+
class SignalMutationIndex {
|
|
945
|
+
static #generatedArgCounts = { create: 1, update: 2, remove: 1, merge: 2 };
|
|
946
|
+
static #argMethods = new Set(["param", "body", "search", "room", "msg"]);
|
|
947
|
+
#shapesByOwner = new Map;
|
|
948
|
+
constructor(sourceFiles) {
|
|
949
|
+
for (const { file, sourceFile } of sourceFiles) {
|
|
950
|
+
if (!/^(apps|libs)\/[^/]+\/lib\/.+\.signal\.ts$/.test(file))
|
|
951
|
+
continue;
|
|
952
|
+
const owner = file.split("/").slice(0, 2).join("/");
|
|
953
|
+
const shapes = this.#shapesByOwner.get(owner) ?? new Map;
|
|
954
|
+
SignalMutationIndex.#collect(sourceFile, shapes);
|
|
955
|
+
this.#shapesByOwner.set(owner, shapes);
|
|
956
|
+
}
|
|
957
|
+
}
|
|
958
|
+
isMutation(consumerFile, name) {
|
|
959
|
+
return this.#shapeOf(consumerFile, name)?.kind === "mutation";
|
|
960
|
+
}
|
|
961
|
+
policyIndexOf(consumerFile, name) {
|
|
962
|
+
const shape = this.#shapeOf(consumerFile, name);
|
|
963
|
+
return shape?.kind === "mutation" ? shape.argCount : null;
|
|
964
|
+
}
|
|
965
|
+
#shapeOf(consumerFile, name) {
|
|
966
|
+
const [root, owner] = consumerFile.split("/");
|
|
967
|
+
const own = this.#shapesByOwner.get(`${root}/${owner}`)?.get(name);
|
|
968
|
+
if (own)
|
|
969
|
+
return own;
|
|
970
|
+
for (const [key, shapes] of this.#shapesByOwner) {
|
|
971
|
+
const shape = shapes.get(name);
|
|
972
|
+
if (key.startsWith("libs/") && shape?.kind === "mutation")
|
|
973
|
+
return shape;
|
|
974
|
+
}
|
|
975
|
+
return;
|
|
976
|
+
}
|
|
977
|
+
static #collect(sourceFile, kinds) {
|
|
978
|
+
const visit = (node) => {
|
|
979
|
+
if (ts8.isCallExpression(node) && ts8.isIdentifier(node.expression)) {
|
|
980
|
+
if (node.expression.text === "slice")
|
|
981
|
+
SignalMutationIndex.#collectGenerated(node, kinds);
|
|
982
|
+
else if (node.expression.text === "endpoint")
|
|
983
|
+
SignalMutationIndex.#collectEndpoints(node, kinds);
|
|
984
|
+
}
|
|
985
|
+
ts8.forEachChild(node, visit);
|
|
986
|
+
};
|
|
987
|
+
visit(sourceFile);
|
|
988
|
+
}
|
|
989
|
+
static #collectGenerated(slice, kinds) {
|
|
990
|
+
let service = slice.arguments[0];
|
|
991
|
+
while (service && ts8.isCallExpression(service) && ts8.isPropertyAccessExpression(service.expression))
|
|
992
|
+
service = service.expression.expression;
|
|
993
|
+
if (!service || !ts8.isPropertyAccessExpression(service) || !SignalMutationIndex.#isNamed(service.expression, "srv"))
|
|
994
|
+
return;
|
|
995
|
+
const model = service.name.text;
|
|
996
|
+
const capModel = `${model.charAt(0).toUpperCase()}${model.slice(1)}`;
|
|
997
|
+
for (const [verb, argCount] of Object.entries(SignalMutationIndex.#generatedArgCounts))
|
|
998
|
+
kinds.set(`${verb}${capModel}`, { kind: "mutation", argCount });
|
|
999
|
+
kinds.set(`add${capModel}Files`, { kind: "mutation", argCount: 2 });
|
|
1000
|
+
}
|
|
1001
|
+
static #collectEndpoints(endpoint, kinds) {
|
|
1002
|
+
const builder = endpoint.arguments[1];
|
|
1003
|
+
if (!builder || !ts8.isArrowFunction(builder) && !ts8.isFunctionExpression(builder))
|
|
1004
|
+
return;
|
|
1005
|
+
const map = SignalMutationIndex.#returnedObjectOf(builder);
|
|
1006
|
+
if (!map)
|
|
1007
|
+
return;
|
|
1008
|
+
const verbOf = SignalMutationIndex.#verbReaderOf(builder.parameters[0]);
|
|
1009
|
+
for (const property of map.properties) {
|
|
1010
|
+
if (!ts8.isPropertyAssignment(property))
|
|
1011
|
+
continue;
|
|
1012
|
+
if (!ts8.isIdentifier(property.name) && !ts8.isStringLiteral(property.name))
|
|
1013
|
+
continue;
|
|
1014
|
+
const { root, argCount } = SignalMutationIndex.#chainOf(property.initializer);
|
|
1015
|
+
const verb = verbOf(root);
|
|
1016
|
+
const kind = verb === "message" ? "mutation" : verb;
|
|
1017
|
+
if (kind === "query" || kind === "mutation")
|
|
1018
|
+
kinds.set(property.name.text, { kind, argCount });
|
|
1019
|
+
}
|
|
1020
|
+
}
|
|
1021
|
+
static #returnedObjectOf(builder) {
|
|
1022
|
+
let body = builder.body;
|
|
1023
|
+
if (ts8.isBlock(body))
|
|
1024
|
+
body = body.statements.find(ts8.isReturnStatement)?.expression;
|
|
1025
|
+
while (body && ts8.isParenthesizedExpression(body))
|
|
1026
|
+
body = body.expression;
|
|
1027
|
+
return body && ts8.isObjectLiteralExpression(body) ? body : null;
|
|
1028
|
+
}
|
|
1029
|
+
static #verbReaderOf(parameter) {
|
|
1030
|
+
const verbs = new Map;
|
|
1031
|
+
if (parameter && ts8.isObjectBindingPattern(parameter.name))
|
|
1032
|
+
for (const element of parameter.name.elements) {
|
|
1033
|
+
const verb = element.propertyName ?? element.name;
|
|
1034
|
+
if (ts8.isIdentifier(verb) && ts8.isIdentifier(element.name))
|
|
1035
|
+
verbs.set(element.name.text, verb.text);
|
|
1036
|
+
}
|
|
1037
|
+
const holder = parameter && ts8.isIdentifier(parameter.name) ? parameter.name.text : null;
|
|
1038
|
+
return (callee) => {
|
|
1039
|
+
if (callee && ts8.isIdentifier(callee))
|
|
1040
|
+
return verbs.get(callee.text);
|
|
1041
|
+
if (callee && ts8.isPropertyAccessExpression(callee) && SignalMutationIndex.#isNamed(callee.expression, holder))
|
|
1042
|
+
return callee.name.text;
|
|
1043
|
+
return;
|
|
1044
|
+
};
|
|
1045
|
+
}
|
|
1046
|
+
static #isNamed(expression, name) {
|
|
1047
|
+
return ts8.isIdentifier(expression) && expression.text === name;
|
|
1048
|
+
}
|
|
1049
|
+
static #chainOf(initializer) {
|
|
1050
|
+
let root = initializer;
|
|
1051
|
+
let argCount = 0;
|
|
1052
|
+
while (ts8.isCallExpression(root) && ts8.isPropertyAccessExpression(root.expression) && ts8.isCallExpression(root.expression.expression)) {
|
|
1053
|
+
if (SignalMutationIndex.#argMethods.has(root.expression.name.text))
|
|
1054
|
+
argCount += 1;
|
|
1055
|
+
root = root.expression.expression;
|
|
1056
|
+
}
|
|
1057
|
+
return { root: ts8.isCallExpression(root) ? root.expression : undefined, argCount };
|
|
1058
|
+
}
|
|
1059
|
+
}
|
|
1060
|
+
|
|
1061
|
+
// pkgs/@akanjs/devkit/storeSource.ts
|
|
1062
|
+
import ts9 from "typescript";
|
|
1063
|
+
|
|
1064
|
+
class StoreSource {
|
|
1065
|
+
file;
|
|
1066
|
+
stores = [];
|
|
1067
|
+
methods = [];
|
|
1068
|
+
#fetchNames;
|
|
1069
|
+
#ownActionsByStore = new Map;
|
|
1070
|
+
#rootAliasesByMethod = new Map;
|
|
1071
|
+
static generatedWritesOf(refName) {
|
|
1072
|
+
const model = `${refName.charAt(0).toUpperCase()}${refName.slice(1)}`;
|
|
1073
|
+
return [
|
|
1074
|
+
`create${model}`,
|
|
1075
|
+
`update${model}`,
|
|
1076
|
+
`remove${model}`,
|
|
1077
|
+
`merge${model}`,
|
|
1078
|
+
`create${model}InForm`,
|
|
1079
|
+
`update${model}InForm`,
|
|
1080
|
+
`submit${model}`
|
|
1081
|
+
];
|
|
1082
|
+
}
|
|
1083
|
+
constructor({ file, sourceFile }) {
|
|
1084
|
+
this.file = file;
|
|
1085
|
+
this.#fetchNames = StoreSource.#fetchBindingsOf(sourceFile);
|
|
1086
|
+
for (const statement of sourceFile.statements) {
|
|
1087
|
+
if (!ts9.isClassDeclaration(statement) || !statement.name)
|
|
1088
|
+
continue;
|
|
1089
|
+
const refName = StoreSource.#refNameOf(statement);
|
|
1090
|
+
if (refName === undefined)
|
|
1091
|
+
continue;
|
|
1092
|
+
const store = statement.name.text;
|
|
1093
|
+
this.stores.push({ name: store, refName });
|
|
1094
|
+
const ownActions = new Set(refName ? StoreSource.generatedWritesOf(refName) : []);
|
|
1095
|
+
for (const member of statement.members) {
|
|
1096
|
+
if (!ts9.isMethodDeclaration(member) || !member.body)
|
|
1097
|
+
continue;
|
|
1098
|
+
const isStatic = !!ts9.getModifiers(member)?.some(({ kind }) => kind === ts9.SyntaxKind.StaticKeyword);
|
|
1099
|
+
const name = member.name.getText(sourceFile);
|
|
1100
|
+
if (!isStatic)
|
|
1101
|
+
ownActions.add(name);
|
|
1102
|
+
const method = { store, name, isStatic, body: member.body };
|
|
1103
|
+
this.methods.push(method);
|
|
1104
|
+
this.#rootAliasesByMethod.set(method, StoreSource.#rootAliasesIn(member));
|
|
1105
|
+
}
|
|
1106
|
+
this.#ownActionsByStore.set(store, ownActions);
|
|
1107
|
+
}
|
|
1108
|
+
}
|
|
1109
|
+
targetsIn(method) {
|
|
1110
|
+
const targets = [];
|
|
1111
|
+
const visit = (node) => {
|
|
1112
|
+
const target = ts9.isCallExpression(node) ? this.targetOf(method, node) : null;
|
|
1113
|
+
if (target)
|
|
1114
|
+
targets.push(target);
|
|
1115
|
+
ts9.forEachChild(node, visit);
|
|
1116
|
+
};
|
|
1117
|
+
visit(method.body);
|
|
1118
|
+
return targets;
|
|
1119
|
+
}
|
|
1120
|
+
targetOf(method, call) {
|
|
1121
|
+
const callee = call.expression;
|
|
1122
|
+
if (!ts9.isPropertyAccessExpression(callee) && !ts9.isElementAccessExpression(callee))
|
|
1123
|
+
return null;
|
|
1124
|
+
const name = ts9.isPropertyAccessExpression(callee) ? callee.name.text : ts9.isStringLiteralLike(callee.argumentExpression) ? callee.argumentExpression.text : null;
|
|
1125
|
+
if (name === null)
|
|
1126
|
+
return null;
|
|
1127
|
+
const receiver = StoreSource.#unwrap(callee.expression);
|
|
1128
|
+
const isThis = receiver.kind === ts9.SyntaxKind.ThisKeyword;
|
|
1129
|
+
if (isThis && method.isStatic)
|
|
1130
|
+
return { kind: "static", store: method.store, name };
|
|
1131
|
+
if (!isThis && !ts9.isIdentifier(receiver))
|
|
1132
|
+
return null;
|
|
1133
|
+
if (ts9.isIdentifier(receiver) && this.#fetchNames.has(receiver.text))
|
|
1134
|
+
return { kind: "fetch", name };
|
|
1135
|
+
if (isThis || ts9.isIdentifier(receiver) && this.#rootAliasesByMethod.get(method)?.has(receiver.text))
|
|
1136
|
+
return { kind: "action", name, isOwn: !!this.#ownActionsByStore.get(method.store)?.has(name) };
|
|
1137
|
+
return ts9.isIdentifier(receiver) ? { kind: "static", store: receiver.text, name } : null;
|
|
1138
|
+
}
|
|
1139
|
+
static #rootAliasesIn(method) {
|
|
1140
|
+
const aliases = new Set;
|
|
1141
|
+
const visit = (node) => {
|
|
1142
|
+
if (ts9.isParameter(node) && ts9.isIdentifier(node.name) && StoreSource.#isRootStoreType(node.type))
|
|
1143
|
+
aliases.add(node.name.text);
|
|
1144
|
+
if (ts9.isVariableDeclaration(node) && ts9.isIdentifier(node.name) && node.initializer && StoreSource.#unwrap(node.initializer).kind === ts9.SyntaxKind.ThisKeyword)
|
|
1145
|
+
aliases.add(node.name.text);
|
|
1146
|
+
ts9.forEachChild(node, visit);
|
|
1147
|
+
};
|
|
1148
|
+
visit(method);
|
|
1149
|
+
return aliases;
|
|
1150
|
+
}
|
|
1151
|
+
static #isRootStoreType(type) {
|
|
1152
|
+
return !!type && ts9.isTypeReferenceNode(type) && ts9.isIdentifier(type.typeName) && type.typeName.text === "RootStore";
|
|
1153
|
+
}
|
|
1154
|
+
static #unwrap(expression) {
|
|
1155
|
+
let current = expression;
|
|
1156
|
+
while (ts9.isParenthesizedExpression(current) || ts9.isAsExpression(current) || ts9.isTypeAssertionExpression(current) || ts9.isSatisfiesExpression(current) || ts9.isNonNullExpression(current))
|
|
1157
|
+
current = current.expression;
|
|
1158
|
+
return current;
|
|
1159
|
+
}
|
|
1160
|
+
static #refNameOf(statement) {
|
|
1161
|
+
for (const clause of statement.heritageClauses ?? []) {
|
|
1162
|
+
if (clause.token !== ts9.SyntaxKind.ExtendsKeyword)
|
|
1163
|
+
continue;
|
|
1164
|
+
for (const { expression } of clause.types) {
|
|
1165
|
+
if (!ts9.isCallExpression(expression) || !ts9.isIdentifier(expression.expression))
|
|
1166
|
+
continue;
|
|
1167
|
+
if (expression.expression.text !== "store")
|
|
1168
|
+
continue;
|
|
1169
|
+
const sig = expression.arguments[0];
|
|
1170
|
+
return sig && ts9.isPropertyAccessExpression(sig) ? sig.name.text : null;
|
|
1171
|
+
}
|
|
1172
|
+
}
|
|
1173
|
+
return;
|
|
1174
|
+
}
|
|
1175
|
+
static #fetchBindingsOf(sourceFile) {
|
|
1176
|
+
const names = new Set;
|
|
1177
|
+
for (const statement of sourceFile.statements) {
|
|
1178
|
+
if (!ts9.isImportDeclaration(statement) || statement.importClause?.isTypeOnly)
|
|
1179
|
+
continue;
|
|
1180
|
+
const bindings = statement.importClause?.namedBindings;
|
|
1181
|
+
if (!bindings || !ts9.isNamedImports(bindings))
|
|
1182
|
+
continue;
|
|
1183
|
+
for (const element of bindings.elements)
|
|
1184
|
+
if (!element.isTypeOnly && (element.propertyName ?? element.name).text === "fetch")
|
|
1185
|
+
names.add(element.name.text);
|
|
1186
|
+
}
|
|
1187
|
+
return names;
|
|
1188
|
+
}
|
|
1189
|
+
}
|
|
1190
|
+
|
|
1191
|
+
// pkgs/@akanjs/devkit/storeWriteScanner.ts
|
|
1192
|
+
class StoreWriteScanner {
|
|
1193
|
+
#index;
|
|
1194
|
+
constructor(index) {
|
|
1195
|
+
this.#index = index;
|
|
1196
|
+
}
|
|
1197
|
+
scan({ file, sourceFile }) {
|
|
1198
|
+
const source = new StoreSource({ file, sourceFile });
|
|
1199
|
+
return source.methods.flatMap((method) => {
|
|
1200
|
+
const targets = new Map;
|
|
1201
|
+
const path = new WritePath((call) => {
|
|
1202
|
+
const target = this.#index.writeOf(source, method, call);
|
|
1203
|
+
if (target)
|
|
1204
|
+
targets.set(call, target);
|
|
1205
|
+
return !!target;
|
|
1206
|
+
});
|
|
1207
|
+
const writes = path.along(method.body);
|
|
1208
|
+
const writeCount = path.countOf(writes);
|
|
1209
|
+
const second = writes[1] ?? writes[0];
|
|
1210
|
+
if (writeCount < 2 || !second)
|
|
1211
|
+
return [];
|
|
1212
|
+
return [
|
|
1213
|
+
{
|
|
1214
|
+
action: method.name,
|
|
1215
|
+
line: sourceFile.getLineAndCharacterOfPosition(second.getStart(sourceFile)).line + 1,
|
|
1216
|
+
writes: writes.map((call) => path.labelOf(call, sourceFile)),
|
|
1217
|
+
writeCount,
|
|
1218
|
+
isRootChain: writes.some((call) => StoreWriteScanner.#crossesStores(targets.get(call), method.store))
|
|
1219
|
+
}
|
|
1220
|
+
];
|
|
1221
|
+
});
|
|
1222
|
+
}
|
|
1223
|
+
static #crossesStores(target, ownStore) {
|
|
1224
|
+
return target?.kind === "static" && target.store !== ownStore || target?.kind === "action" && !target.isOwn;
|
|
1225
|
+
}
|
|
1226
|
+
}
|
|
1227
|
+
|
|
1228
|
+
// pkgs/@akanjs/devkit/writePlacementScanner.ts
|
|
1229
|
+
import ts10 from "typescript";
|
|
1230
|
+
class WritePlacementScanner {
|
|
1231
|
+
#index;
|
|
1232
|
+
constructor(index) {
|
|
1233
|
+
this.#index = index;
|
|
1234
|
+
}
|
|
1235
|
+
scan(file, workspaceFile, sourceFile) {
|
|
1236
|
+
const fetchNames = StoreAccessScanner.localNamesOf(sourceFile, "fetch");
|
|
1237
|
+
const stNames = file.startsWith("lib/") ? new Set : StoreAccessScanner.stNamesOf(sourceFile);
|
|
1238
|
+
if (!fetchNames.size && !stNames.size)
|
|
1239
|
+
return null;
|
|
1240
|
+
const sites = [];
|
|
1241
|
+
const visit = (node) => {
|
|
1242
|
+
if (ts10.isPropertyAccessExpression(node) && this.#isWrite(node, workspaceFile, fetchNames, stNames))
|
|
1243
|
+
sites.push(node);
|
|
1244
|
+
ts10.forEachChild(node, visit);
|
|
1245
|
+
};
|
|
1246
|
+
visit(sourceFile);
|
|
1247
|
+
const first = sites[0];
|
|
1248
|
+
if (!first)
|
|
1249
|
+
return null;
|
|
1250
|
+
return {
|
|
1251
|
+
line: sourceFile.getLineAndCharacterOfPosition(first.getStart(sourceFile)).line + 1,
|
|
1252
|
+
writes: sites.map((site) => site.getText(sourceFile))
|
|
1253
|
+
};
|
|
1254
|
+
}
|
|
1255
|
+
#isWrite(access, workspaceFile, fetchNames, stNames) {
|
|
1256
|
+
const owner = access.expression;
|
|
1257
|
+
if (ts10.isIdentifier(owner) && fetchNames.has(owner.text))
|
|
1258
|
+
return this.#index.isMutation(workspaceFile, access.name.text);
|
|
1259
|
+
return ts10.isPropertyAccessExpression(owner) && owner.name.text === "do" && ts10.isIdentifier(owner.expression) && stNames.has(owner.expression.text) && this.#index.isWritingAction(access.name.text);
|
|
1260
|
+
}
|
|
1261
|
+
}
|
|
1262
|
+
|
|
1263
|
+
// pkgs/@akanjs/devkit/writingActionIndex.ts
|
|
1264
|
+
class WritingActionIndex {
|
|
1265
|
+
#mutations;
|
|
1266
|
+
#actions = new Set;
|
|
1267
|
+
#statics = new Set;
|
|
1268
|
+
constructor(mutations, storeFiles) {
|
|
1269
|
+
this.#mutations = mutations;
|
|
1270
|
+
const sources = storeFiles.map((storeFile) => new StoreSource(storeFile));
|
|
1271
|
+
for (const source of sources)
|
|
1272
|
+
for (const { refName } of source.stores) {
|
|
1273
|
+
const generated = refName ? StoreSource.generatedWritesOf(refName) : [];
|
|
1274
|
+
if (generated[0] && mutations.isMutation(source.file, generated[0]))
|
|
1275
|
+
for (const name of generated)
|
|
1276
|
+
this.#actions.add(name);
|
|
1277
|
+
}
|
|
1278
|
+
const methods = sources.flatMap((source) => source.methods.map((method) => ({ file: source.file, method, targets: source.targetsIn(method) })));
|
|
1279
|
+
let grew = true;
|
|
1280
|
+
while (grew) {
|
|
1281
|
+
grew = false;
|
|
1282
|
+
for (const { file, method, targets } of methods) {
|
|
1283
|
+
if (this.#holds(method) || !targets.some((target) => this.#writes(file, target)))
|
|
1284
|
+
continue;
|
|
1285
|
+
if (method.isStatic)
|
|
1286
|
+
this.#statics.add(`${method.store}.${method.name}`);
|
|
1287
|
+
else
|
|
1288
|
+
this.#actions.add(method.name);
|
|
1289
|
+
grew = true;
|
|
1290
|
+
}
|
|
1291
|
+
}
|
|
1292
|
+
}
|
|
1293
|
+
isWritingAction(name) {
|
|
1294
|
+
return this.#actions.has(name);
|
|
1295
|
+
}
|
|
1296
|
+
isMutation(consumerFile, name) {
|
|
1297
|
+
return this.#mutations.isMutation(consumerFile, name);
|
|
1298
|
+
}
|
|
1299
|
+
writeOf(source, method, call) {
|
|
1300
|
+
const target = source.targetOf(method, call);
|
|
1301
|
+
if (!target || !this.#writes(source.file, target))
|
|
1302
|
+
return null;
|
|
1303
|
+
const isSelf = target.kind !== "fetch" && target.name === method.name && (target.kind === "static" ? method.isStatic && target.store === method.store : !method.isStatic);
|
|
1304
|
+
return isSelf ? null : target;
|
|
1305
|
+
}
|
|
1306
|
+
#holds(method) {
|
|
1307
|
+
return method.isStatic ? this.#statics.has(`${method.store}.${method.name}`) : this.#actions.has(method.name);
|
|
1308
|
+
}
|
|
1309
|
+
#writes(file, target) {
|
|
1310
|
+
if (target.kind === "fetch")
|
|
1311
|
+
return this.#mutations.isMutation(file, target.name);
|
|
1312
|
+
if (target.kind === "action")
|
|
1313
|
+
return this.#actions.has(target.name);
|
|
1314
|
+
return this.#statics.has(`${target.store}.${target.name}`);
|
|
1315
|
+
}
|
|
1316
|
+
}
|
|
1317
|
+
|
|
1318
|
+
// pkgs/@akanjs/devkit/maintainabilityContract.ts
|
|
1319
|
+
class MaintainabilityContract {
|
|
1320
|
+
static ruleIds = [
|
|
1321
|
+
"akan.size.file",
|
|
1322
|
+
"akan.size.component",
|
|
1323
|
+
"akan.store.multi-write",
|
|
1324
|
+
"akan.store.root-write-chain",
|
|
1325
|
+
"akan.component.write-chain",
|
|
1326
|
+
"akan.component.store-access",
|
|
1327
|
+
"akan.write.placement",
|
|
1328
|
+
"akan.service.call-in-loop",
|
|
1329
|
+
"akan.baseline.growth"
|
|
1330
|
+
];
|
|
1331
|
+
static #measuredFiles = "{lib,ui,webkit,srvkit,common,plugin}/**/*.{ts,tsx,md}";
|
|
1332
|
+
static #defaultBranches = ["upstream/HEAD", "upstream/main", "origin/HEAD", "origin/main", "main", "master"];
|
|
1333
|
+
#workspaceRoot;
|
|
1334
|
+
#scope;
|
|
1335
|
+
#libNames;
|
|
1336
|
+
constructor(workspaceRoot, scope, libNames = []) {
|
|
1337
|
+
this.#workspaceRoot = workspaceRoot;
|
|
1338
|
+
this.#scope = scope;
|
|
1339
|
+
this.#libNames = libNames.filter((libName) => scope.type === "app" || libName !== scope.name);
|
|
1340
|
+
}
|
|
1341
|
+
get sysPath() {
|
|
1342
|
+
return `${this.#scope.type}s/${this.#scope.name}`;
|
|
1343
|
+
}
|
|
1344
|
+
get baselinePath() {
|
|
1345
|
+
return path4.join(this.#workspaceRoot, this.sysPath, MaintainabilityBaseline.fileName);
|
|
1346
|
+
}
|
|
1347
|
+
async measure() {
|
|
1348
|
+
const [signalFiles, storeFiles, serviceFiles] = await Promise.all([
|
|
1349
|
+
this.#reachedSources("lib/**/*.signal.ts"),
|
|
1350
|
+
this.#reachedSources("lib/**/*.store.ts"),
|
|
1351
|
+
this.#reachedSources("lib/**/*.service.ts")
|
|
1352
|
+
]);
|
|
1353
|
+
const index = new WritingActionIndex(new SignalMutationIndex(signalFiles), storeFiles);
|
|
1354
|
+
const reach = new EndpointReach(signalFiles, serviceFiles);
|
|
1355
|
+
const files = await MaintainabilityContract.#filesUnder(path4.join(this.#workspaceRoot, this.sysPath), MaintainabilityContract.#measuredFiles);
|
|
1356
|
+
const violations = await Promise.all(files.map((file) => this.#measureFile(file, index, reach)));
|
|
1357
|
+
return violations.flat().sort((a, b) => a.file < b.file ? -1 : a.file > b.file ? 1 : a.line - b.line);
|
|
1358
|
+
}
|
|
1359
|
+
async enforce({ fix }) {
|
|
1360
|
+
const [violations, existing, reference] = await Promise.all([
|
|
1361
|
+
this.measure(),
|
|
1362
|
+
this.#readBaseline(),
|
|
1363
|
+
this.#readReferenceBaseline()
|
|
1364
|
+
]);
|
|
1365
|
+
const baseline = existing === null ? new MaintainabilityBaseline : MaintainabilityBaseline.parse(existing, this.baselinePath);
|
|
1366
|
+
const tightened = baseline.tightenedBy(violations);
|
|
1367
|
+
if (fix && existing !== null)
|
|
1368
|
+
await this.#tighten(baseline, tightened);
|
|
1369
|
+
const failures = violations.filter((violation) => !baseline.allows(violation)).map((violation) => {
|
|
1370
|
+
const recorded = baseline.recordedOf(violation);
|
|
1371
|
+
return recorded === undefined ? violation : { ...violation, recorded };
|
|
1372
|
+
});
|
|
1373
|
+
if (reference === null)
|
|
1374
|
+
return failures;
|
|
1375
|
+
const lines = (await this.#readBaseline() ?? "").split(/\r?\n/);
|
|
1376
|
+
const label = `${reference.ref}:${this.sysPath}/${MaintainabilityBaseline.fileName}`;
|
|
1377
|
+
const growths = (fix ? tightened : baseline).grownFrom(MaintainabilityBaseline.parse(reference.text, label, { lenient: true })).map(({ rule, ...growth }) => ({
|
|
1378
|
+
kind: "baselineGrowth",
|
|
1379
|
+
rule: "akan.baseline.growth",
|
|
1380
|
+
file: MaintainabilityBaseline.fileName,
|
|
1381
|
+
line: MaintainabilityContract.#lineOf(lines, rule, growth.key),
|
|
1382
|
+
debtRule: rule,
|
|
1383
|
+
reference: reference.ref,
|
|
1384
|
+
...growth
|
|
1385
|
+
})).sort((a, b) => a.line - b.line);
|
|
1386
|
+
return [...growths, ...failures];
|
|
1387
|
+
}
|
|
1388
|
+
async seed({ force = false } = {}) {
|
|
1389
|
+
const violations = await this.measure();
|
|
1390
|
+
const exists = existsSync(this.baselinePath);
|
|
1391
|
+
if (exists && !force)
|
|
1392
|
+
return { result: "kept", violations };
|
|
1393
|
+
const next = MaintainabilityBaseline.of(violations, MaintainabilityContract.#reasonsIn(await this.#readBaseline()));
|
|
1394
|
+
if (!next.isEmpty)
|
|
1395
|
+
await writeFile(this.baselinePath, next.stringify());
|
|
1396
|
+
else if (exists)
|
|
1397
|
+
await rm(this.baselinePath, { force: true });
|
|
1398
|
+
return { result: next.isEmpty ? exists ? "removed" : "clean" : "written", violations };
|
|
1399
|
+
}
|
|
1400
|
+
describe(failures, commands) {
|
|
1401
|
+
return MaintainabilityReport.describe(this.sysPath, failures, commands);
|
|
1402
|
+
}
|
|
1403
|
+
async#measureFile(file, index, reach) {
|
|
1404
|
+
const maxLines = MaintainabilityLimits.fileMaxLinesOf(file);
|
|
1405
|
+
const isStore = file.endsWith(".store.ts");
|
|
1406
|
+
const isService = file.endsWith(".service.ts");
|
|
1407
|
+
const isClientCode = MaintainabilityLimits.isClientCode(file);
|
|
1408
|
+
if (!maxLines && !isStore && !isClientCode)
|
|
1409
|
+
return [];
|
|
1410
|
+
const workspaceFile = `${this.sysPath}/${file}`;
|
|
1411
|
+
const content = await readFile(path4.join(this.#workspaceRoot, workspaceFile), "utf8");
|
|
1412
|
+
const violations = [];
|
|
1413
|
+
const lineCount = MaintainabilityLimits.lineCountOf(content);
|
|
1414
|
+
if (maxLines && lineCount > maxLines && !MaintainabilityLimits.isReexportBarrel(file, content))
|
|
1415
|
+
violations.push({ kind: "size", rule: "akan.size.file", key: file, file, line: 1, lineCount, maxLines });
|
|
1416
|
+
if (!isStore && !isService && !isClientCode)
|
|
1417
|
+
return violations;
|
|
1418
|
+
const source = this.#sourceOf(workspaceFile, content);
|
|
1419
|
+
if (isClientCode)
|
|
1420
|
+
violations.push(...MaintainabilityContract.#measureClientCode(file, source, index));
|
|
1421
|
+
if (isStore)
|
|
1422
|
+
for (const { action, line, writes, writeCount, isRootChain } of new StoreWriteScanner(index).scan(source))
|
|
1423
|
+
violations.push({
|
|
1424
|
+
kind: "multiWrite",
|
|
1425
|
+
rule: isRootChain ? "akan.store.root-write-chain" : "akan.store.multi-write",
|
|
1426
|
+
key: `${file}#${action}`,
|
|
1427
|
+
file,
|
|
1428
|
+
line,
|
|
1429
|
+
owner: action,
|
|
1430
|
+
writes,
|
|
1431
|
+
writeCount
|
|
1432
|
+
});
|
|
1433
|
+
if (isService)
|
|
1434
|
+
for (const { method, line, calls } of new ServiceLoopCallScanner().scan(source.sourceFile, (method) => reach.reaches(EndpointReach.serviceOf(file), method)))
|
|
1435
|
+
violations.push({
|
|
1436
|
+
kind: "loopCall",
|
|
1437
|
+
rule: "akan.service.call-in-loop",
|
|
1438
|
+
key: `${file}#${method}`,
|
|
1439
|
+
file,
|
|
1440
|
+
line,
|
|
1441
|
+
owner: method,
|
|
1442
|
+
calls
|
|
1443
|
+
});
|
|
1444
|
+
return violations;
|
|
1445
|
+
}
|
|
1446
|
+
static #measureClientCode(file, { file: workspaceFile, sourceFile }, index) {
|
|
1447
|
+
const violations = [];
|
|
1448
|
+
const placement = new WritePlacementScanner(index).scan(file, workspaceFile, sourceFile);
|
|
1449
|
+
if (placement)
|
|
1450
|
+
violations.push({ kind: "writePlacement", rule: "akan.write.placement", key: file, file, ...placement });
|
|
1451
|
+
for (const component of new ComponentSizeScanner().measure(sourceFile))
|
|
1452
|
+
if (component.lineCount > MaintainabilityLimits.componentMaxLines)
|
|
1453
|
+
violations.push({
|
|
1454
|
+
kind: "size",
|
|
1455
|
+
rule: "akan.size.component",
|
|
1456
|
+
key: `${file}#${component.name}`,
|
|
1457
|
+
file,
|
|
1458
|
+
line: component.line,
|
|
1459
|
+
lineCount: component.lineCount,
|
|
1460
|
+
maxLines: MaintainabilityLimits.componentMaxLines,
|
|
1461
|
+
component: component.name
|
|
1462
|
+
});
|
|
1463
|
+
for (const { component, line, writes, writeCount } of new ComponentWriteChainScanner(index).scan(sourceFile))
|
|
1464
|
+
violations.push({
|
|
1465
|
+
kind: "multiWrite",
|
|
1466
|
+
rule: "akan.component.write-chain",
|
|
1467
|
+
key: `${file}#${component}`,
|
|
1468
|
+
file,
|
|
1469
|
+
line,
|
|
1470
|
+
owner: component,
|
|
1471
|
+
writes,
|
|
1472
|
+
writeCount
|
|
1473
|
+
});
|
|
1474
|
+
for (const { component, line, accessCount } of new StoreAccessScanner(index).measure(sourceFile))
|
|
1475
|
+
if (accessCount > MaintainabilityLimits.componentMaxStoreAccesses)
|
|
1476
|
+
violations.push({
|
|
1477
|
+
kind: "storeAccess",
|
|
1478
|
+
rule: "akan.component.store-access",
|
|
1479
|
+
key: `${file}#${component}`,
|
|
1480
|
+
file,
|
|
1481
|
+
line,
|
|
1482
|
+
component,
|
|
1483
|
+
accessCount,
|
|
1484
|
+
maxAccesses: MaintainabilityLimits.componentMaxStoreAccesses
|
|
1485
|
+
});
|
|
1486
|
+
return violations;
|
|
1487
|
+
}
|
|
1488
|
+
async#reachedSources(pattern) {
|
|
1489
|
+
const roots = [this.sysPath, ...this.#libNames.map((libName) => `libs/${libName}`)];
|
|
1490
|
+
const files = await Promise.all(roots.map(async (root) => (await MaintainabilityContract.#filesUnder(path4.join(this.#workspaceRoot, root), pattern)).map((file) => `${root}/${file}`)));
|
|
1491
|
+
return await Promise.all(files.flat().map(async (file) => this.#sourceOf(file, await readFile(path4.join(this.#workspaceRoot, file), "utf8"))));
|
|
1492
|
+
}
|
|
1493
|
+
#sourceOf(file, content) {
|
|
1494
|
+
const scriptKind = file.endsWith(".tsx") ? ts11.ScriptKind.TSX : ts11.ScriptKind.TS;
|
|
1495
|
+
return {
|
|
1496
|
+
file,
|
|
1497
|
+
absolutePath: path4.join(this.#workspaceRoot, file),
|
|
1498
|
+
content,
|
|
1499
|
+
sourceFile: ts11.createSourceFile(file, content, ts11.ScriptTarget.Latest, true, scriptKind)
|
|
1500
|
+
};
|
|
1501
|
+
}
|
|
1502
|
+
async#readBaseline() {
|
|
1503
|
+
return existsSync(this.baselinePath) ? await readFile(this.baselinePath, "utf8") : null;
|
|
1504
|
+
}
|
|
1505
|
+
async#readReferenceBaseline() {
|
|
1506
|
+
const ref = await this.#referenceRef();
|
|
1507
|
+
const text = await this.#git(["show", `${ref}:./${this.sysPath}/${MaintainabilityBaseline.fileName}`]);
|
|
1508
|
+
return text === null ? null : { ref: ref === "HEAD" ? ref : ref.slice(0, 12), text };
|
|
1509
|
+
}
|
|
1510
|
+
async#referenceRef() {
|
|
1511
|
+
for (const branch of MaintainabilityContract.#defaultBranches) {
|
|
1512
|
+
if (await this.#git(["rev-parse", "--verify", "--quiet", `${branch}^{commit}`]) === null)
|
|
1513
|
+
continue;
|
|
1514
|
+
const forkPoint = (await this.#git(["merge-base", "HEAD", branch]))?.trim();
|
|
1515
|
+
if (forkPoint)
|
|
1516
|
+
return forkPoint;
|
|
1517
|
+
throw new Error(MaintainabilityContract.#missingHistory(this.sysPath, `HEAD shares no commit with ${branch}`));
|
|
1518
|
+
}
|
|
1519
|
+
if ((await this.#git(["rev-parse", "--is-shallow-repository"]))?.trim() === "true")
|
|
1520
|
+
throw new Error(MaintainabilityContract.#missingHistory(this.sysPath, "this is a shallow clone"));
|
|
1521
|
+
return "HEAD";
|
|
1522
|
+
}
|
|
1523
|
+
static #missingHistory(sysPath, cause) {
|
|
1524
|
+
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).`;
|
|
1525
|
+
}
|
|
1526
|
+
async#git(args) {
|
|
1527
|
+
try {
|
|
1528
|
+
const proc = Bun.spawn(["git", ...args], { cwd: this.#workspaceRoot, stdout: "pipe", stderr: "ignore" });
|
|
1529
|
+
const [text, exitCode] = await Promise.all([new Response(proc.stdout).text(), proc.exited]);
|
|
1530
|
+
return exitCode === 0 ? text : null;
|
|
1531
|
+
} catch {
|
|
1532
|
+
return null;
|
|
1533
|
+
}
|
|
1534
|
+
}
|
|
1535
|
+
static #reasonsIn(text) {
|
|
1536
|
+
if (text === null)
|
|
1537
|
+
return new Map;
|
|
1538
|
+
try {
|
|
1539
|
+
return MaintainabilityBaseline.parse(text, MaintainabilityBaseline.fileName, { lenient: true }).reasons;
|
|
1540
|
+
} catch {
|
|
1541
|
+
return new Map;
|
|
1542
|
+
}
|
|
1543
|
+
}
|
|
1544
|
+
async#tighten(current, next) {
|
|
1545
|
+
if (next.isEmpty)
|
|
1546
|
+
await rm(this.baselinePath, { force: true });
|
|
1547
|
+
else if (next.stringify() !== current.stringify())
|
|
1548
|
+
await writeFile(this.baselinePath, next.stringify());
|
|
1549
|
+
}
|
|
1550
|
+
static #lineOf(lines, rule, key) {
|
|
1551
|
+
const from = Math.max(lines.findIndex((line) => line.includes(`${JSON.stringify(rule)}:`)), 0);
|
|
1552
|
+
const idx = lines.findIndex((line, lineIdx) => lineIdx >= from && line.includes(`${JSON.stringify(key)}:`));
|
|
1553
|
+
return Math.max(idx + 1, 1);
|
|
1554
|
+
}
|
|
1555
|
+
static async#filesUnder(root, pattern) {
|
|
1556
|
+
if (!existsSync(root))
|
|
1557
|
+
return [];
|
|
1558
|
+
const files = await Array.fromAsync(new Bun.Glob(pattern).scan({ cwd: root, onlyFiles: true }));
|
|
1559
|
+
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);
|
|
1560
|
+
}
|
|
1561
|
+
}
|
|
1562
|
+
|
|
1563
|
+
// pkgs/@akanjs/cli/workspace/workspace.runner.ts
|
|
1564
|
+
import { Ed25519Key } from "akanjs/server/ed25519Key";
|
|
1565
|
+
|
|
1566
|
+
// pkgs/@akanjs/cli/workflows/maintainabilityPaths.ts
|
|
1567
|
+
class MaintainabilityPaths {
|
|
1568
|
+
static pathless = new Set([
|
|
1569
|
+
"akan.size.file",
|
|
1570
|
+
"akan.size.component",
|
|
1571
|
+
"akan.service.call-in-loop",
|
|
1572
|
+
"akan.baseline.growth"
|
|
1573
|
+
]);
|
|
1574
|
+
#specs;
|
|
1575
|
+
constructor(specs = workflowSpecs) {
|
|
1576
|
+
this.#specs = specs;
|
|
1577
|
+
}
|
|
1578
|
+
static isRule(rule) {
|
|
1579
|
+
return MaintainabilityContract.ruleIds.includes(rule);
|
|
1580
|
+
}
|
|
1581
|
+
commandsOf(target) {
|
|
1582
|
+
const commands = {};
|
|
1583
|
+
for (const spec of this.#specs)
|
|
1584
|
+
for (const rule of (spec.replacesRules ?? []).filter(MaintainabilityPaths.isRule))
|
|
1585
|
+
commands[rule] = [...commands[rule] ?? [], MaintainabilityPaths.#planOf(spec, target)];
|
|
1586
|
+
return commands;
|
|
1587
|
+
}
|
|
1588
|
+
static #planOf(spec, target) {
|
|
1589
|
+
const flags = Object.entries(spec.inputs).filter(([, input]) => input.required).map(([name]) => {
|
|
1590
|
+
const flag = camelToKebabCase(name);
|
|
1591
|
+
return `--${flag} ${name in sysInputs ? target : `<${flag}>`}`;
|
|
1592
|
+
});
|
|
1593
|
+
return ["akan workflow plan", spec.name, ...flags].join(" ");
|
|
1594
|
+
}
|
|
1595
|
+
}
|
|
1596
|
+
|
|
1597
|
+
// pkgs/@akanjs/cli/workspace/workspace.runner.ts
|
|
1598
|
+
var defaultWorkspacePeerDependencies = new Set([
|
|
1599
|
+
"@react-spring/web",
|
|
1600
|
+
"@use-gesture/react",
|
|
1601
|
+
"chance",
|
|
1602
|
+
"react",
|
|
1603
|
+
"react-dom",
|
|
1604
|
+
"react-icons",
|
|
1605
|
+
"react-refresh",
|
|
1606
|
+
"react-server-dom-webpack",
|
|
1607
|
+
"react-spring",
|
|
1608
|
+
"scheduler",
|
|
1609
|
+
"tailwind-scrollbar",
|
|
1610
|
+
"tailwindcss",
|
|
1611
|
+
"typescript"
|
|
1612
|
+
]);
|
|
1613
|
+
var defaultWorkspaceTypeDependencies = { "@types/react": "^19.3.0", "@types/react-dom": "^19.3.0" };
|
|
1614
|
+
var defaultMaxDiagnostics = 200;
|
|
1615
|
+
|
|
1616
|
+
class WorkspaceRunner extends runner("workspace") {
|
|
1617
|
+
async machineKeygen(workspace, out) {
|
|
1618
|
+
const file = path5.resolve(workspace.workspaceRoot, out);
|
|
1619
|
+
const { privatePem, publicKey } = Ed25519Key.generate();
|
|
1620
|
+
await mkdir(path5.dirname(file), { recursive: true });
|
|
1621
|
+
try {
|
|
1622
|
+
await writeFile2(file, privatePem, { mode: 384, flag: "wx" });
|
|
1623
|
+
} catch (error) {
|
|
1624
|
+
if (error.code === "EEXIST")
|
|
1625
|
+
throw new Error(`${file} exists; machine-keygen never overwrites a key. Name another file.`);
|
|
1626
|
+
throw error;
|
|
1627
|
+
}
|
|
1628
|
+
return { file, publicKey };
|
|
1629
|
+
}
|
|
1630
|
+
async generateAgentRules(workspace, { overwrite = false, cursorRules = true } = {}) {
|
|
1631
|
+
const [appNames] = await workspace.getExecs();
|
|
1632
|
+
const dict = { repoName: workspace.repoName, appName: appNames[0] ?? "app" };
|
|
1633
|
+
const templates = [
|
|
1634
|
+
[".", "workspaceRoot/AGENTS.md.template"],
|
|
1635
|
+
[".", "workspaceRoot/CLAUDE.md.template"],
|
|
1636
|
+
...cursorRules ? [[".cursor/rules", "workspaceRoot/.cursor/rules/akan.mdc.template"]] : []
|
|
1637
|
+
];
|
|
1638
|
+
const created = [];
|
|
1639
|
+
for (const [basePath, template] of templates)
|
|
1640
|
+
created.push(...await workspace.applyTemplate({ basePath, template, dict, overwrite }));
|
|
1641
|
+
return created;
|
|
1642
|
+
}
|
|
1643
|
+
async createWorkspace(repoName, appName, {
|
|
1644
|
+
dirname = ".",
|
|
1645
|
+
init = true,
|
|
1646
|
+
akanVersion,
|
|
1647
|
+
registryUrl,
|
|
1648
|
+
owner = ""
|
|
1649
|
+
}) {
|
|
1650
|
+
const cwdPath = process.cwd();
|
|
1651
|
+
const workspaceRoot = path5.resolve(cwdPath, dirname, repoName);
|
|
1652
|
+
const normalizedRegistryUrl = registryUrl ? getNpmRegistryUrl(registryUrl) : undefined;
|
|
1653
|
+
const workspace = WorkspaceExecutor.fromRoot({ workspaceRoot, repoName });
|
|
1654
|
+
const templateSpinner = workspace.spinning(`Creating workspace template files in ${workspaceRoot}...`);
|
|
1655
|
+
const latestTypesBunVersion = await getLatestPackageVersion("@types/bun", "latest", normalizedRegistryUrl);
|
|
1656
|
+
await workspace.applyTemplate({
|
|
1657
|
+
basePath: ".",
|
|
1658
|
+
template: "workspaceRoot",
|
|
1659
|
+
dict: { repoName, appName, serveDomain: "localhost", owner }
|
|
1660
|
+
});
|
|
1661
|
+
if (normalizedRegistryUrl)
|
|
1662
|
+
await workspace.writeFile(".npmrc", `registry=${normalizedRegistryUrl}/
|
|
1663
|
+
`);
|
|
1664
|
+
templateSpinner.succeed(`Workspace files created in ${workspaceRoot}`);
|
|
1665
|
+
const [rootPackageJson, peerDependencies] = await Promise.all([
|
|
1666
|
+
workspace.getPackageJson(),
|
|
1667
|
+
this.#getAkanPeerDependencies()
|
|
1668
|
+
]);
|
|
1669
|
+
const { typescript, ...dependencies } = peerDependencies;
|
|
1670
|
+
const packageJson = {
|
|
1671
|
+
...rootPackageJson,
|
|
1672
|
+
dependencies: {
|
|
1673
|
+
...rootPackageJson.dependencies,
|
|
1674
|
+
...dependencies,
|
|
1675
|
+
akanjs: akanVersion
|
|
1676
|
+
},
|
|
1677
|
+
devDependencies: {
|
|
1678
|
+
...rootPackageJson.devDependencies,
|
|
1679
|
+
"@biomejs/biome": biomeVersion,
|
|
1680
|
+
"@types/bun": latestTypesBunVersion,
|
|
1681
|
+
...defaultWorkspaceTypeDependencies,
|
|
1682
|
+
"@akanjs/devkit": akanVersion,
|
|
1683
|
+
"@akanjs/cli": akanVersion,
|
|
1684
|
+
...typescript ? { typescript } : {}
|
|
1685
|
+
}
|
|
1686
|
+
};
|
|
1687
|
+
await workspace.setPackageJson(packageJson);
|
|
1688
|
+
if (init) {
|
|
1689
|
+
const installSpinner = workspace.spinning("Installing dependencies with bun...");
|
|
1690
|
+
await workspace.spawn("bun", ["install"]);
|
|
1691
|
+
installSpinner.succeed("Dependencies installed with bun");
|
|
1692
|
+
}
|
|
1693
|
+
return workspace;
|
|
1694
|
+
}
|
|
1695
|
+
async#getAkanPeerDependencies() {
|
|
1696
|
+
const [packageJson, cliPackageJson] = await Promise.all([this.#getAkanPackageJson(), this.#getCliPackageJson()]);
|
|
1697
|
+
const dependencyVersions = {
|
|
1698
|
+
...packageJson.dependencies,
|
|
1699
|
+
...packageJson.peerDependencies,
|
|
1700
|
+
...cliPackageJson.dependencies
|
|
1701
|
+
};
|
|
1702
|
+
return Object.fromEntries(Object.entries(dependencyVersions).filter(([dependency]) => defaultWorkspacePeerDependencies.has(dependency)));
|
|
1703
|
+
}
|
|
1704
|
+
async#getCliPackageJson() {
|
|
1705
|
+
const found = await this.#findPackageJson("@akanjs/cli", [
|
|
1706
|
+
path5.join(import.meta.dir, "../package.json"),
|
|
1707
|
+
path5.join(import.meta.dir, "package.json"),
|
|
1708
|
+
path5.join(path5.dirname(Bun.main), "package.json")
|
|
1709
|
+
]);
|
|
1710
|
+
return found ?? { name: "@akanjs/cli", version: "0.0.0", description: "@akanjs/cli" };
|
|
1711
|
+
}
|
|
1712
|
+
async#getAkanPackageJson() {
|
|
1713
|
+
const ancestors = [];
|
|
1714
|
+
for (let current = import.meta.dir, depth = 0;depth < 6; depth++) {
|
|
1715
|
+
ancestors.push(path5.join(current, "package.json"));
|
|
1716
|
+
if (path5.dirname(current) === current)
|
|
1717
|
+
break;
|
|
1718
|
+
current = path5.dirname(current);
|
|
1719
|
+
}
|
|
1720
|
+
const found = await this.#findPackageJson("akanjs", [
|
|
1721
|
+
path5.join(import.meta.dir, "../../../akanjs/package.json"),
|
|
1722
|
+
path5.join(process.cwd(), "pkgs/akanjs/package.json"),
|
|
1723
|
+
path5.join(path5.dirname(Bun.main), "node_modules/akanjs/package.json"),
|
|
1724
|
+
...ancestors
|
|
1725
|
+
]);
|
|
1726
|
+
if (!found)
|
|
1727
|
+
throw new Error(`[workspace] failed to locate akanjs package.json from ${import.meta.dir}`);
|
|
1728
|
+
return found;
|
|
1729
|
+
}
|
|
1730
|
+
async#findPackageJson(name, candidates) {
|
|
1731
|
+
try {
|
|
1732
|
+
candidates.unshift(Bun.resolveSync(`${name}/package.json`, import.meta.dir));
|
|
1733
|
+
} catch {}
|
|
1734
|
+
for (const packageJsonPath of candidates) {
|
|
1735
|
+
if (!await Bun.file(packageJsonPath).exists())
|
|
1736
|
+
continue;
|
|
1737
|
+
const packageJson = await FileSys2.readJson(packageJsonPath);
|
|
1738
|
+
if (packageJson.name === name)
|
|
1739
|
+
return packageJson;
|
|
1740
|
+
}
|
|
1741
|
+
return null;
|
|
1742
|
+
}
|
|
1743
|
+
async lint(exec, workspace, { fix = true, maxDiagnostics = defaultMaxDiagnostics } = {}) {
|
|
1744
|
+
const configPath = await WorkspaceRunner.resolveBiomeConfigPath(workspace);
|
|
1745
|
+
const [biome, ...biomeArgs] = Linter.biomeCommand(workspace.workspaceRoot);
|
|
1746
|
+
await workspace.spawn(biome, [
|
|
1747
|
+
...biomeArgs,
|
|
1748
|
+
"check",
|
|
1749
|
+
...fix ? ["--write"] : [],
|
|
1750
|
+
"--no-errors-on-unmatched",
|
|
1751
|
+
`--max-diagnostics=${maxDiagnostics > 0 ? maxDiagnostics : "none"}`,
|
|
1752
|
+
...configPath ? ["--config-path", configPath] : [],
|
|
1753
|
+
exec.cwdPath
|
|
1754
|
+
]);
|
|
1755
|
+
await this.#enforceStyleContract(exec);
|
|
1756
|
+
await this.#enforceRecipeGate(exec);
|
|
1757
|
+
await this.#enforceAgentsIndex(exec);
|
|
1758
|
+
await this.#enforceMaintainability(exec, fix);
|
|
1759
|
+
}
|
|
1760
|
+
async lintGateFailures(exec, fix) {
|
|
1761
|
+
const messages = [];
|
|
1762
|
+
for (const gate of [
|
|
1763
|
+
() => this.#enforceStyleContract(exec),
|
|
1764
|
+
() => this.#enforceRecipeGate(exec),
|
|
1765
|
+
() => this.#enforceAgentsIndex(exec)
|
|
1766
|
+
])
|
|
1767
|
+
await gate().catch((error) => messages.push(error instanceof Error ? error.message : String(error)));
|
|
1768
|
+
if (!(exec instanceof SysExecutor))
|
|
1769
|
+
return { messages, maintainability: [] };
|
|
1770
|
+
const contract = await this.maintainabilityContractOf(exec);
|
|
1771
|
+
const failures = await contract.enforce({ fix });
|
|
1772
|
+
const maintainability = MaintainabilityReport.entriesOf(contract.sysPath, failures, new MaintainabilityPaths().commandsOf(exec.name));
|
|
1773
|
+
return { messages, maintainability };
|
|
1774
|
+
}
|
|
1775
|
+
async maintainabilityContractOf(exec) {
|
|
1776
|
+
const libNames = new Set;
|
|
1777
|
+
const visit = async (sys) => {
|
|
1778
|
+
for (const libName of (await sys.scan({ write: false })).getScanResult().libDeps) {
|
|
1779
|
+
if (libNames.has(libName))
|
|
1780
|
+
continue;
|
|
1781
|
+
libNames.add(libName);
|
|
1782
|
+
await visit(LibExecutor.from(exec, libName));
|
|
1783
|
+
}
|
|
1784
|
+
};
|
|
1785
|
+
await visit(exec);
|
|
1786
|
+
return new MaintainabilityContract(exec.workspace.workspaceRoot, { type: exec.type, name: exec.name }, [
|
|
1787
|
+
...libNames
|
|
1788
|
+
]);
|
|
1789
|
+
}
|
|
1790
|
+
static async resolveBiomeConfigPath(workspace) {
|
|
1791
|
+
for (const fileName of ["biome.json", "biome.jsonc"]) {
|
|
1792
|
+
const configPath = path5.join(workspace.workspaceRoot, fileName);
|
|
1793
|
+
if (await Bun.file(configPath).exists())
|
|
1794
|
+
return configPath;
|
|
1795
|
+
}
|
|
1796
|
+
return null;
|
|
1797
|
+
}
|
|
1798
|
+
async#enforceAgentsIndex(exec) {
|
|
1799
|
+
if (!(exec instanceof SysExecutor))
|
|
1800
|
+
return;
|
|
1801
|
+
const scope = { type: exec.type, name: exec.name };
|
|
1802
|
+
const scanInfo = await exec.scan({ write: false });
|
|
1803
|
+
const sources = await collectScopeRecipeSources(exec.workspace.workspaceRoot, scope, scanInfo.getScanResult().libDeps);
|
|
1804
|
+
const expected = renderScopeAgentBlock(scope, scanRecipes2(sources));
|
|
1805
|
+
const existing = await exec.exists("AGENTS.md") ? await exec.readFile("AGENTS.md") : null;
|
|
1806
|
+
const actual = existing ? extractAgentBlock(existing) : null;
|
|
1807
|
+
if (actual === expected.trim())
|
|
1808
|
+
return;
|
|
1809
|
+
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.`);
|
|
1810
|
+
}
|
|
1811
|
+
async#enforceMaintainability(exec, fix) {
|
|
1812
|
+
if (!(exec instanceof SysExecutor))
|
|
1813
|
+
return;
|
|
1814
|
+
const contract = await this.maintainabilityContractOf(exec);
|
|
1815
|
+
const failures = await contract.enforce({ fix });
|
|
1816
|
+
if (failures.length)
|
|
1817
|
+
throw new Error(contract.describe(failures, new MaintainabilityPaths().commandsOf(exec.name)));
|
|
1818
|
+
}
|
|
1819
|
+
async#enforceRecipeGate(exec) {
|
|
1820
|
+
const cwdPath = exec.cwdPath;
|
|
1821
|
+
if (!cwdPath)
|
|
1822
|
+
return;
|
|
1823
|
+
const uiDir = path5.join(cwdPath, "ui");
|
|
1824
|
+
const sources = [
|
|
1825
|
+
...await collectRecipeSources2(uiDir, "ui/Recipe"),
|
|
1826
|
+
...await collectRecipeSources2(uiDir, "ui/recipe", "recipe")
|
|
1827
|
+
];
|
|
1828
|
+
if (sources.length === 0)
|
|
1829
|
+
return;
|
|
1830
|
+
const offenders = scanRecipes2(sources).filter((recipe) => !Object.values(recipe.variants).some((values) => values.length >= 2 || values.length === 1 && values[0] === "true"));
|
|
1831
|
+
if (offenders.length === 0)
|
|
1832
|
+
return;
|
|
1833
|
+
throw new Error(`[recipeGate] variant-less recipe(s): ${[...new Set(offenders.map((recipe) => recipe.name))].join(", ")}
|
|
1834
|
+
` + "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.");
|
|
1835
|
+
}
|
|
1836
|
+
async#enforceStyleContract(exec) {
|
|
1837
|
+
const cwdPath = exec.cwdPath;
|
|
1838
|
+
if (!cwdPath)
|
|
1839
|
+
return;
|
|
1840
|
+
const stylesCssPath = path5.join(cwdPath, "page", "styles.css");
|
|
1841
|
+
if (!await Bun.file(stylesCssPath).exists())
|
|
1842
|
+
return;
|
|
1843
|
+
const violations = {
|
|
1844
|
+
theme: new ThemeValidator().validate(await Bun.file(stylesCssPath).text())
|
|
1845
|
+
};
|
|
1846
|
+
const blocking = countBlocking(violations);
|
|
1847
|
+
if (blocking === 0)
|
|
1848
|
+
return;
|
|
1849
|
+
throw new Error(`[themeValidator] ${blocking} blocking contrast violation(s):
|
|
1850
|
+
${formatStyleContract(violations)}
|
|
1851
|
+
|
|
1852
|
+
` + "Raise the foreground/background contrast of these theme token values to the WCAG threshold.");
|
|
1853
|
+
}
|
|
1854
|
+
async writeTopLevelEnv(workspace, devProjectId) {
|
|
1855
|
+
await workspace.writeFile(".env", `AKAN_WORKSPACE_ID=${devProjectId}
|
|
1856
|
+
|
|
1857
|
+
# organization configuration, no need to change
|
|
1858
|
+
AKAN_PUBLIC_REPO_NAME=${workspace.repoName}
|
|
1859
|
+
|
|
1860
|
+
# serve domain, it changes the domain of the server.
|
|
1861
|
+
AKAN_PUBLIC_SERVE_DOMAIN=try.akanjs.com
|
|
1862
|
+
|
|
1863
|
+
# development branch, debug, develop, main, etc. mainly it changes databases.
|
|
1864
|
+
AKAN_PUBLIC_ENV=local
|
|
1865
|
+
|
|
1866
|
+
# local, cloud, edge it changes the connection point of the clients.
|
|
1867
|
+
AKAN_PUBLIC_OPERATION_MODE=local
|
|
1868
|
+
|
|
1869
|
+
# log level, debug, info, warn, error
|
|
1870
|
+
AKAN_PUBLIC_LOG_LEVEL=debug
|
|
1871
|
+
`);
|
|
1872
|
+
}
|
|
1873
|
+
}
|
|
1874
|
+
|
|
1875
|
+
// pkgs/@akanjs/devkit/qualityScanner.ts
|
|
1876
|
+
import { createHash } from "crypto";
|
|
1877
|
+
import { readdir as readdir2, readFile as readFile3, stat } from "fs/promises";
|
|
1878
|
+
import path9 from "path";
|
|
1879
|
+
import { RESERVED_ROUTE_CONFIG_EXPORTS } from "akanjs/common";
|
|
1880
|
+
import ignore from "ignore";
|
|
1881
|
+
import ts19 from "typescript";
|
|
1882
|
+
|
|
1883
|
+
// pkgs/@akanjs/devkit/commentDensityScanner.ts
|
|
1884
|
+
import path6 from "path";
|
|
1885
|
+
import ts13 from "typescript";
|
|
1886
|
+
|
|
1887
|
+
// pkgs/@akanjs/devkit/sourceComments.ts
|
|
1888
|
+
import ts12 from "typescript";
|
|
1889
|
+
|
|
1890
|
+
class SourceComments {
|
|
1891
|
+
static #scanner = ts12.createScanner(ts12.ScriptTarget.Latest, false);
|
|
1892
|
+
static of(sourceFile) {
|
|
1893
|
+
const comments = [];
|
|
1894
|
+
const scanGap = (start, end) => {
|
|
1895
|
+
if (end <= start)
|
|
1896
|
+
return;
|
|
1897
|
+
const scanner = SourceComments.#scanner;
|
|
1898
|
+
scanner.setText(sourceFile.text, start, end - start);
|
|
1899
|
+
for (let kind = scanner.scan();kind !== ts12.SyntaxKind.EndOfFileToken; kind = scanner.scan()) {
|
|
1900
|
+
if (kind !== ts12.SyntaxKind.SingleLineCommentTrivia && kind !== ts12.SyntaxKind.MultiLineCommentTrivia)
|
|
1901
|
+
continue;
|
|
1902
|
+
comments.push(SourceComments.#commentOf(sourceFile, scanner.getTokenStart(), scanner.getTokenText()));
|
|
1903
|
+
}
|
|
1904
|
+
scanner.setText(undefined);
|
|
1905
|
+
};
|
|
1906
|
+
const visit = (node) => {
|
|
1907
|
+
if (node.kind === ts12.SyntaxKind.JsxText)
|
|
1908
|
+
return;
|
|
1909
|
+
if (ts12.isToken(node)) {
|
|
1910
|
+
scanGap(node.pos, node.getStart(sourceFile));
|
|
1911
|
+
return;
|
|
1912
|
+
}
|
|
1913
|
+
const children = [];
|
|
1914
|
+
ts12.forEachChild(node, (child) => {
|
|
1915
|
+
children.push(child);
|
|
1916
|
+
}, (nodes) => {
|
|
1917
|
+
children.push(...nodes);
|
|
1918
|
+
});
|
|
1919
|
+
let cursor = node.pos;
|
|
1920
|
+
for (const child of children) {
|
|
1921
|
+
scanGap(cursor, child.pos);
|
|
1922
|
+
visit(child);
|
|
1923
|
+
cursor = Math.max(cursor, child.end);
|
|
1924
|
+
}
|
|
1925
|
+
scanGap(cursor, node.end);
|
|
1926
|
+
};
|
|
1927
|
+
visit(sourceFile);
|
|
1928
|
+
return comments;
|
|
1929
|
+
}
|
|
1930
|
+
static #commentOf(sourceFile, pos, raw) {
|
|
1931
|
+
return {
|
|
1932
|
+
raw,
|
|
1933
|
+
line: sourceFile.getLineAndCharacterOfPosition(pos).line + 1,
|
|
1934
|
+
isJsDoc: raw.startsWith("/**") && !raw.startsWith("/**/"),
|
|
1935
|
+
body: SourceComments.#bodyOf(raw)
|
|
1936
|
+
};
|
|
1937
|
+
}
|
|
1938
|
+
static #bodyOf(raw) {
|
|
1939
|
+
if (raw.startsWith("//"))
|
|
1940
|
+
return [raw.replace(/^\/\/+/, "").trim()];
|
|
1941
|
+
return raw.slice(2, raw.endsWith("*/") ? -2 : undefined).split(/\r?\n/).map((line) => line.replace(/^\s*\*+/, "").trim());
|
|
1942
|
+
}
|
|
1943
|
+
}
|
|
1944
|
+
|
|
1945
|
+
// pkgs/@akanjs/devkit/commentDensityScanner.ts
|
|
1946
|
+
class CommentDensityScanner {
|
|
1947
|
+
static rule = "akan.comment.density";
|
|
1948
|
+
static maxShare = 0.01;
|
|
1949
|
+
static minCommentLineNum = 5;
|
|
1950
|
+
static #directive = /^(?:biome-ignore|@ts-(?:expect-error|ignore|nocheck|check)\b|eslint-(?:disable|enable)|<reference\b)/;
|
|
1951
|
+
static #scaffoldMarkers = new Set(["state", "action"]);
|
|
1952
|
+
scan(sourceFiles) {
|
|
1953
|
+
const tallies = new Map;
|
|
1954
|
+
for (const sourceFile of sourceFiles) {
|
|
1955
|
+
const unit = CommentDensityScanner.#unitOf(sourceFile.file);
|
|
1956
|
+
if (!unit || !CommentDensityScanner.#isMeasured(sourceFile))
|
|
1957
|
+
continue;
|
|
1958
|
+
const tally = tallies.get(unit) ?? { lineNum: 0, commentLineNum: 0, files: [] };
|
|
1959
|
+
const commentLines = CommentDensityScanner.#commentLinesOf(sourceFile);
|
|
1960
|
+
tally.lineNum += sourceFile.content.split(/\r?\n/).filter((line) => line.trim() !== "").length;
|
|
1961
|
+
tally.commentLineNum += commentLines.length;
|
|
1962
|
+
if (commentLines[0] !== undefined)
|
|
1963
|
+
tally.files.push({ file: sourceFile.file, line: commentLines[0], commentLineNum: commentLines.length });
|
|
1964
|
+
tallies.set(unit, tally);
|
|
1965
|
+
}
|
|
1966
|
+
return [...tallies].filter(([, tally]) => CommentDensityScanner.#isDense(tally)).map(([unit, tally]) => CommentDensityScanner.#warningOf(unit, tally));
|
|
1967
|
+
}
|
|
1968
|
+
static #commentLinesOf({ file, sourceFile }) {
|
|
1969
|
+
const isRecipe = file.includes("/ui/Recipe/");
|
|
1970
|
+
const lines = new Set;
|
|
1971
|
+
for (const comment of SourceComments.of(sourceFile)) {
|
|
1972
|
+
if (CommentDensityScanner.#isExempt(comment))
|
|
1973
|
+
continue;
|
|
1974
|
+
const contentIdxs = comment.body.flatMap((text, idx) => text ? [idx] : []);
|
|
1975
|
+
const countedIdxs = isRecipe && comment.isJsDoc ? contentIdxs.slice(1) : contentIdxs;
|
|
1976
|
+
for (const idx of countedIdxs)
|
|
1977
|
+
lines.add(comment.line + idx);
|
|
1978
|
+
}
|
|
1979
|
+
return [...lines].sort((a, b) => a - b);
|
|
1980
|
+
}
|
|
1981
|
+
static #isExempt({ raw, body }) {
|
|
1982
|
+
const head = body.find((text) => text !== "") ?? "";
|
|
1983
|
+
if (CommentDensityScanner.#directive.test(head))
|
|
1984
|
+
return true;
|
|
1985
|
+
return raw.startsWith("//") && CommentDensityScanner.#scaffoldMarkers.has(head.toLowerCase());
|
|
1986
|
+
}
|
|
1987
|
+
static #isDense({ lineNum, commentLineNum }) {
|
|
1988
|
+
return commentLineNum >= CommentDensityScanner.minCommentLineNum && commentLineNum > lineNum * CommentDensityScanner.maxShare;
|
|
1989
|
+
}
|
|
1990
|
+
static #warningOf(unit, { lineNum, commentLineNum, files }) {
|
|
1991
|
+
const [primary] = [...files].sort((a, b) => b.commentLineNum - a.commentLineNum);
|
|
1992
|
+
const share = (commentLineNum / lineNum * 100).toFixed(2);
|
|
1993
|
+
return {
|
|
1994
|
+
rule: CommentDensityScanner.rule,
|
|
1995
|
+
scope: "comment",
|
|
1996
|
+
severity: "warning",
|
|
1997
|
+
file: primary?.file ?? unit,
|
|
1998
|
+
line: primary?.line,
|
|
1999
|
+
message: `${unit} is ${share}% comments (${commentLineNum} of ${lineNum} non-blank lines); product lib/ and ui/ code stays under ${CommentDensityScanner.maxShare * 100}%.`,
|
|
2000
|
+
...files.length > 1 ? { locations: files.map(({ file, line }) => ({ file, line })) } : {}
|
|
2001
|
+
};
|
|
2002
|
+
}
|
|
2003
|
+
static #unitOf(file) {
|
|
2004
|
+
const segments = file.split("/");
|
|
2005
|
+
if (segments[0] !== "apps" && segments[0] !== "libs" || segments.length < 4)
|
|
2006
|
+
return null;
|
|
2007
|
+
if (segments[2] === "ui")
|
|
2008
|
+
return segments.slice(0, 4).join("/");
|
|
2009
|
+
if (segments[2] !== "lib")
|
|
2010
|
+
return null;
|
|
2011
|
+
const depth = segments[3] === "__scalar" ? 5 : 4;
|
|
2012
|
+
return segments.length > depth ? segments.slice(0, depth).join("/") : null;
|
|
2013
|
+
}
|
|
2014
|
+
static #isMeasured({ file, sourceFile }) {
|
|
2015
|
+
if (/\.(test|spec)\.tsx?$/.test(file) || path6.basename(file) === "guards.ts")
|
|
2016
|
+
return false;
|
|
2017
|
+
return !sourceFile.statements.every((statement) => ts13.isExportDeclaration(statement) || ts13.isExpressionStatement(statement) && ts13.isStringLiteral(statement.expression));
|
|
2018
|
+
}
|
|
2019
|
+
}
|
|
2020
|
+
|
|
2021
|
+
// pkgs/@akanjs/devkit/deprecatedCommentScanner.ts
|
|
2022
|
+
class DeprecatedCommentScanner {
|
|
2023
|
+
static rule = "akan.comment.deprecated-marker";
|
|
2024
|
+
static #marker = /^[!?*\s]*(?:(?:TODO|FIXME|XXX|NOTE)\b\s*:?\s*)?@?deprecated\b/i;
|
|
2025
|
+
scan(sourceFiles) {
|
|
2026
|
+
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) => ({
|
|
2027
|
+
rule: DeprecatedCommentScanner.rule,
|
|
2028
|
+
scope: "comment",
|
|
2029
|
+
severity: "warning",
|
|
2030
|
+
file,
|
|
2031
|
+
line: comment.line,
|
|
2032
|
+
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.`
|
|
2033
|
+
})));
|
|
2034
|
+
}
|
|
2035
|
+
static #isLooseMarker({ isJsDoc, body }) {
|
|
2036
|
+
const text = body.filter((line) => line !== "").join(" ");
|
|
2037
|
+
if (isJsDoc && /(^|\s)@deprecated\b/.test(text))
|
|
2038
|
+
return false;
|
|
2039
|
+
return DeprecatedCommentScanner.#marker.test(text);
|
|
2040
|
+
}
|
|
2041
|
+
}
|
|
2042
|
+
|
|
2043
|
+
// pkgs/@akanjs/devkit/formSetterScanner.ts
|
|
2044
|
+
import ts14 from "typescript";
|
|
2045
|
+
|
|
2046
|
+
class FormSetterScanner {
|
|
2047
|
+
static #fieldSetter = /^set[A-Za-z0-9_$]*On[A-Za-z0-9_$]*$/;
|
|
2048
|
+
scan(sourceFiles) {
|
|
2049
|
+
return sourceFiles.filter((sourceFile) => sourceFile.file.endsWith(".tsx")).flatMap((f) => this.#scanFile(f));
|
|
2050
|
+
}
|
|
2051
|
+
#scanFile({ file, sourceFile }) {
|
|
2052
|
+
const wrapped = [];
|
|
2053
|
+
const visit = (node) => {
|
|
2054
|
+
if (ts14.isJsxAttribute(node)) {
|
|
2055
|
+
const setter = FormSetterScanner.#wrappedSetterOf(node);
|
|
2056
|
+
if (setter)
|
|
2057
|
+
wrapped.push({ setter, line: FormSetterScanner.#lineOf(sourceFile, node) });
|
|
2058
|
+
}
|
|
2059
|
+
ts14.forEachChild(node, visit);
|
|
2060
|
+
};
|
|
2061
|
+
visit(sourceFile);
|
|
2062
|
+
if (!wrapped.length)
|
|
2063
|
+
return [];
|
|
2064
|
+
const setters = [...new Set(wrapped.map((entry) => entry.setter))].sort();
|
|
2065
|
+
return [
|
|
2066
|
+
{
|
|
2067
|
+
rule: "akan.agent.unpublished-form-setter",
|
|
2068
|
+
scope: "agent",
|
|
2069
|
+
severity: "warning",
|
|
2070
|
+
message: setters.length === 1 ? `${setters[0]} is reached through a wrapper, so that field publishes no agent tool and carries no data-akan-action.` : `${setters.length} field setters are reached through a wrapper, so those fields publish no agent tool and carry no data-akan-action: ${setters.join(", ")}.`,
|
|
2071
|
+
file,
|
|
2072
|
+
line: wrapped[0]?.line,
|
|
2073
|
+
locations: wrapped.map(({ line }) => ({ file, line }))
|
|
2074
|
+
}
|
|
2075
|
+
];
|
|
2076
|
+
}
|
|
2077
|
+
static #wrappedSetterOf(attribute) {
|
|
2078
|
+
if (!ts14.isIdentifier(attribute.name) || !/^on[A-Z]/.test(attribute.name.text))
|
|
2079
|
+
return null;
|
|
2080
|
+
const initializer = attribute.initializer;
|
|
2081
|
+
if (!initializer || !ts14.isJsxExpression(initializer) || !initializer.expression)
|
|
2082
|
+
return null;
|
|
2083
|
+
const handler = initializer.expression;
|
|
2084
|
+
if (!ts14.isArrowFunction(handler) && !ts14.isFunctionExpression(handler))
|
|
2085
|
+
return null;
|
|
2086
|
+
if (!handler.parameters.length)
|
|
2087
|
+
return null;
|
|
2088
|
+
return FormSetterScanner.#setterCallIn(handler.body);
|
|
2089
|
+
}
|
|
2090
|
+
static #setterCallIn(node) {
|
|
2091
|
+
let found = null;
|
|
2092
|
+
const visit = (current) => {
|
|
2093
|
+
if (found)
|
|
2094
|
+
return;
|
|
2095
|
+
if (ts14.isCallExpression(current) && ts14.isPropertyAccessExpression(current.expression)) {
|
|
2096
|
+
const { expression, name } = current.expression;
|
|
2097
|
+
if (ts14.isPropertyAccessExpression(expression) && ts14.isIdentifier(expression.expression) && expression.expression.text === "st" && expression.name.text === "do" && FormSetterScanner.#fieldSetter.test(name.text)) {
|
|
2098
|
+
found = name.text;
|
|
2099
|
+
return;
|
|
2100
|
+
}
|
|
2101
|
+
}
|
|
2102
|
+
ts14.forEachChild(current, visit);
|
|
2103
|
+
};
|
|
2104
|
+
visit(node);
|
|
2105
|
+
return found;
|
|
2106
|
+
}
|
|
2107
|
+
static #lineOf(sourceFile, node) {
|
|
2108
|
+
return sourceFile.getLineAndCharacterOfPosition(node.getStart(sourceFile)).line + 1;
|
|
2109
|
+
}
|
|
2110
|
+
}
|
|
2111
|
+
|
|
2112
|
+
// pkgs/@akanjs/devkit/kindBranchScanner.ts
|
|
2113
|
+
import path7 from "path";
|
|
2114
|
+
import ts15 from "typescript";
|
|
2115
|
+
|
|
2116
|
+
class KindBranchScanner {
|
|
2117
|
+
static rule = "akan.global.kind-branch";
|
|
2118
|
+
static minFileNum = 3;
|
|
2119
|
+
static #kindName = /(Kind|Type|Mode)$/;
|
|
2120
|
+
static #kindSubject = /^(kind|type|mode)$|[a-z](Kind|Type|Mode)$/;
|
|
2121
|
+
static #equalities = new Set([
|
|
2122
|
+
ts15.SyntaxKind.EqualsEqualsEqualsToken,
|
|
2123
|
+
ts15.SyntaxKind.ExclamationEqualsEqualsToken,
|
|
2124
|
+
ts15.SyntaxKind.EqualsEqualsToken,
|
|
2125
|
+
ts15.SyntaxKind.ExclamationEqualsToken
|
|
2126
|
+
]);
|
|
2127
|
+
scan(sourceFiles) {
|
|
2128
|
+
const enums = sourceFiles.flatMap((sourceFile) => KindBranchScanner.#enumsOf(sourceFile));
|
|
2129
|
+
const ownersByValue = new Map;
|
|
2130
|
+
for (const declaration of enums)
|
|
2131
|
+
for (const value of declaration.values)
|
|
2132
|
+
ownersByValue.set(value, [...ownersByValue.get(value) ?? [], declaration]);
|
|
2133
|
+
const sitesByGroup = new Map;
|
|
2134
|
+
for (const sourceFile of sourceFiles) {
|
|
2135
|
+
if (!/^(apps|libs)\//.test(sourceFile.file) || /\.(test|spec)\.tsx?$/.test(sourceFile.file))
|
|
2136
|
+
continue;
|
|
2137
|
+
const sys = KindBranchScanner.#sysOf(sourceFile.file);
|
|
2138
|
+
for (const site of KindBranchScanner.#sitesIn(sourceFile, ownersByValue)) {
|
|
2139
|
+
const owners = (ownersByValue.get(site.value) ?? []).filter((owner) => owner.sys === sys || owner.sys.startsWith("libs/") && sys.startsWith("apps/"));
|
|
2140
|
+
if (!owners.length || owners.some(({ module }) => site.file.startsWith(module)))
|
|
2141
|
+
continue;
|
|
2142
|
+
const group = owners.map(({ name, file }) => `${file}#${name}`).join(",");
|
|
2143
|
+
const entry = sitesByGroup.get(group) ?? { owners, sites: [] };
|
|
2144
|
+
entry.sites.push(site);
|
|
2145
|
+
sitesByGroup.set(group, entry);
|
|
2146
|
+
}
|
|
2147
|
+
}
|
|
2148
|
+
return [...sitesByGroup.values()].flatMap(({ owners, sites }) => KindBranchScanner.#warningOf(owners, sites));
|
|
2149
|
+
}
|
|
2150
|
+
static #warningOf(owners, sites) {
|
|
2151
|
+
const filesByValue = new Map;
|
|
2152
|
+
for (const { value, file } of sites)
|
|
2153
|
+
filesByValue.set(value, (filesByValue.get(value) ?? new Set).add(file));
|
|
2154
|
+
const values = [...filesByValue].filter(([, files]) => files.size >= KindBranchScanner.minFileNum).map(([value]) => value).sort((a, b) => a < b ? -1 : a > b ? 1 : 0);
|
|
2155
|
+
const [owner] = owners;
|
|
2156
|
+
if (!owner || !values.length)
|
|
2157
|
+
return [];
|
|
2158
|
+
const branched = sites.filter(({ value }) => values.includes(value));
|
|
2159
|
+
const fileNum = new Set(branched.map(({ file }) => file)).size;
|
|
2160
|
+
const enumNames = owners.map(({ name }) => `cnst.${name}`).join(" / ");
|
|
2161
|
+
return [
|
|
2162
|
+
{
|
|
2163
|
+
rule: KindBranchScanner.rule,
|
|
2164
|
+
scope: "global",
|
|
2165
|
+
severity: "warning",
|
|
2166
|
+
file: owner.file,
|
|
2167
|
+
line: owner.line,
|
|
2168
|
+
message: `${values.map((value) => `"${value}"`).join(", ")} of ${enumNames} ${values.length > 1 ? "are" : "is"} branched on in ${fileNum} files outside the enum's module.`,
|
|
2169
|
+
locations: branched.map(({ file, line }) => ({ file, line })),
|
|
2170
|
+
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.`
|
|
2171
|
+
}
|
|
2172
|
+
];
|
|
2173
|
+
}
|
|
2174
|
+
static #sitesIn({ file, sourceFile }, ownersByValue) {
|
|
2175
|
+
const sites = [];
|
|
2176
|
+
const record = (literal, subject) => {
|
|
2177
|
+
if (!ts15.isStringLiteralLike(literal) || !ownersByValue.has(literal.text))
|
|
2178
|
+
return;
|
|
2179
|
+
if (!KindBranchScanner.#isKindSubject(subject))
|
|
2180
|
+
return;
|
|
2181
|
+
sites.push({
|
|
2182
|
+
value: literal.text,
|
|
2183
|
+
file,
|
|
2184
|
+
line: sourceFile.getLineAndCharacterOfPosition(literal.getStart(sourceFile)).line + 1
|
|
2185
|
+
});
|
|
2186
|
+
};
|
|
2187
|
+
const visit = (node) => {
|
|
2188
|
+
if (ts15.isBinaryExpression(node) && KindBranchScanner.#equalities.has(node.operatorToken.kind)) {
|
|
2189
|
+
record(node.left, node.right);
|
|
2190
|
+
record(node.right, node.left);
|
|
2191
|
+
} else if (ts15.isCaseClause(node) && ts15.isSwitchStatement(node.parent.parent))
|
|
2192
|
+
record(node.expression, node.parent.parent.expression);
|
|
2193
|
+
ts15.forEachChild(node, visit);
|
|
2194
|
+
};
|
|
2195
|
+
visit(sourceFile);
|
|
2196
|
+
return sites;
|
|
2197
|
+
}
|
|
2198
|
+
static #isKindSubject(subject) {
|
|
2199
|
+
let current = subject;
|
|
2200
|
+
while (ts15.isParenthesizedExpression(current) || ts15.isAsExpression(current) || ts15.isNonNullExpression(current))
|
|
2201
|
+
current = current.expression;
|
|
2202
|
+
const name = ts15.isIdentifier(current) ? current.text : ts15.isPropertyAccessExpression(current) ? current.name.text : ts15.isElementAccessExpression(current) && ts15.isStringLiteralLike(current.argumentExpression) ? current.argumentExpression.text : "";
|
|
2203
|
+
return KindBranchScanner.#kindSubject.test(name);
|
|
2204
|
+
}
|
|
2205
|
+
static #enumsOf({ file, sourceFile }) {
|
|
2206
|
+
if (!/^(apps|libs)\/[^/]+\/lib\/.+\.constant\.ts$/.test(file))
|
|
2207
|
+
return [];
|
|
2208
|
+
return sourceFile.statements.flatMap((statement) => {
|
|
2209
|
+
if (!ts15.isClassDeclaration(statement) || !statement.name)
|
|
2210
|
+
return [];
|
|
2211
|
+
if (!KindBranchScanner.#kindName.test(statement.name.text))
|
|
2212
|
+
return [];
|
|
2213
|
+
const values = KindBranchScanner.#enumValuesOf(statement);
|
|
2214
|
+
if (!values)
|
|
2215
|
+
return [];
|
|
2216
|
+
return [
|
|
2217
|
+
{
|
|
2218
|
+
name: statement.name.text,
|
|
2219
|
+
sys: KindBranchScanner.#sysOf(file),
|
|
2220
|
+
file,
|
|
2221
|
+
line: sourceFile.getLineAndCharacterOfPosition(statement.getStart(sourceFile)).line + 1,
|
|
2222
|
+
module: `${path7.posix.dirname(file)}/`,
|
|
2223
|
+
values
|
|
2224
|
+
}
|
|
2225
|
+
];
|
|
2226
|
+
});
|
|
2227
|
+
}
|
|
2228
|
+
static #sysOf(file) {
|
|
2229
|
+
return file.split("/").slice(0, 2).join("/");
|
|
2230
|
+
}
|
|
2231
|
+
static #enumValuesOf(statement) {
|
|
2232
|
+
for (const clause of statement.heritageClauses ?? [])
|
|
2233
|
+
for (const { expression } of clause.types) {
|
|
2234
|
+
if (!ts15.isCallExpression(expression) || !ts15.isIdentifier(expression.expression))
|
|
2235
|
+
continue;
|
|
2236
|
+
if (expression.expression.text !== "enumOf")
|
|
2237
|
+
continue;
|
|
2238
|
+
let list = expression.arguments[1];
|
|
2239
|
+
while (list && (ts15.isAsExpression(list) || ts15.isParenthesizedExpression(list)))
|
|
2240
|
+
list = list.expression;
|
|
2241
|
+
if (!list || !ts15.isArrayLiteralExpression(list))
|
|
2242
|
+
return null;
|
|
2243
|
+
return list.elements.filter(ts15.isStringLiteralLike).map(({ text }) => text);
|
|
2244
|
+
}
|
|
2245
|
+
return null;
|
|
2246
|
+
}
|
|
2247
|
+
}
|
|
2248
|
+
|
|
2249
|
+
// pkgs/@akanjs/devkit/maintainabilityExceptionScanner.ts
|
|
2250
|
+
import { existsSync as existsSync2 } from "fs";
|
|
2251
|
+
import { readdir, readFile as readFile2 } from "fs/promises";
|
|
2252
|
+
import path8 from "path";
|
|
2253
|
+
class MaintainabilityExceptionScanner {
|
|
2254
|
+
static rule = "akan.baseline.exceptions";
|
|
2255
|
+
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.";
|
|
2256
|
+
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.";
|
|
2257
|
+
async scan(workspaceRoot) {
|
|
2258
|
+
const sysPaths = await Promise.all(["apps", "libs"].map(async (sysRoot) => {
|
|
2259
|
+
const absoluteRoot = path8.join(workspaceRoot, sysRoot);
|
|
2260
|
+
if (!existsSync2(absoluteRoot))
|
|
2261
|
+
return [];
|
|
2262
|
+
const entries = await readdir(absoluteRoot, { withFileTypes: true });
|
|
2263
|
+
return entries.filter((entry) => entry.isDirectory()).map((entry) => `${sysRoot}/${entry.name}`);
|
|
2264
|
+
}));
|
|
2265
|
+
const warnings = await Promise.all(sysPaths.flat().map((sysPath) => MaintainabilityExceptionScanner.#scanSys(workspaceRoot, sysPath)));
|
|
2266
|
+
return warnings.flat();
|
|
2267
|
+
}
|
|
2268
|
+
static async#scanSys(workspaceRoot, sysPath) {
|
|
2269
|
+
const file = `${sysPath}/${MaintainabilityBaseline.fileName}`;
|
|
2270
|
+
const absolutePath = path8.join(workspaceRoot, file);
|
|
2271
|
+
if (!existsSync2(absolutePath))
|
|
2272
|
+
return [];
|
|
2273
|
+
const text = await readFile2(absolutePath, "utf8");
|
|
2274
|
+
let baseline;
|
|
2275
|
+
try {
|
|
2276
|
+
baseline = MaintainabilityBaseline.parse(text, file);
|
|
2277
|
+
} catch {
|
|
2278
|
+
return [];
|
|
2279
|
+
}
|
|
2280
|
+
const lines = text.split(/\r?\n/);
|
|
2281
|
+
return [...baseline.entriesByRule()].map(([rule, entries]) => MaintainabilityExceptionScanner.#warningOf(sysPath, file, lines, rule, entries));
|
|
2282
|
+
}
|
|
2283
|
+
static #warningOf(sysPath, file, lines, rule, entries) {
|
|
2284
|
+
const reasonedNum = entries.filter(({ reason }) => reason !== undefined).length;
|
|
2285
|
+
const adoptedNum = entries.length - reasonedNum;
|
|
2286
|
+
const listed = entries.map(({ key, reason }) => reason === undefined ? key : `${key} (${JSON.stringify(reason)})`);
|
|
2287
|
+
const locations = entries.map(({ key }) => ({
|
|
2288
|
+
file,
|
|
2289
|
+
line: MaintainabilityExceptionScanner.#lineOf(lines, rule, key)
|
|
2290
|
+
}));
|
|
2291
|
+
return {
|
|
2292
|
+
rule: MaintainabilityExceptionScanner.rule,
|
|
2293
|
+
scope: "file",
|
|
2294
|
+
severity: "warning",
|
|
2295
|
+
file,
|
|
2296
|
+
line: locations[0]?.line ?? 1,
|
|
2297
|
+
message: `${sysPath} carries ${reasonedNum} reasoned exception${reasonedNum === 1 ? "" : "s"} and ${adoptedNum} adopted-debt entr${adoptedNum === 1 ? "y" : "ies"} for ${rule}: ${listed.join(", ")}.`,
|
|
2298
|
+
locations,
|
|
2299
|
+
fix: MaintainabilityBaseline.reasonedRules.has(rule) ? MaintainabilityExceptionScanner.#shapeFix : MaintainabilityExceptionScanner.#correctnessFix
|
|
2300
|
+
};
|
|
2301
|
+
}
|
|
2302
|
+
static #lineOf(lines, rule, key) {
|
|
2303
|
+
const from = Math.max(lines.findIndex((line) => line.includes(`${JSON.stringify(rule)}:`)), 0);
|
|
2304
|
+
return Math.max(lines.findIndex((line, idx) => idx >= from && line.includes(`${JSON.stringify(key)}:`)) + 1, 1);
|
|
2305
|
+
}
|
|
2306
|
+
}
|
|
2307
|
+
|
|
2308
|
+
// pkgs/@akanjs/devkit/ssrScanner.ts
|
|
2309
|
+
import ts17 from "typescript";
|
|
2310
|
+
|
|
2311
|
+
// pkgs/@akanjs/devkit/renderMutationScanner.ts
|
|
2312
|
+
import ts16 from "typescript";
|
|
2313
|
+
|
|
2314
|
+
class RenderMutationScanner {
|
|
2315
|
+
static rule = "akan.ssr.render-mutation";
|
|
2316
|
+
static fix = "Send the write from an explicit user action, such as a button that calls a store action. Only a write that is harmless to repeat and safe for anyone to trigger may stay in the render, with `{ duringRender: true }` as the call's option.";
|
|
2317
|
+
static #builders = new Set(["page", "layout", "rootLayout"]);
|
|
2318
|
+
static #stages = new Set(["render", "guard", "head", "loading", "notFound", "error"]);
|
|
2319
|
+
#mutations;
|
|
2320
|
+
constructor(mutations) {
|
|
2321
|
+
this.#mutations = mutations;
|
|
2322
|
+
}
|
|
2323
|
+
scan(sourceFiles) {
|
|
2324
|
+
return sourceFiles.filter(({ file }) => /^(apps|libs)\/[^/]+\/page\/.+(?<!\.test|\.spec)\.tsx$/.test(file)).flatMap((sourceFile) => this.#scanRoute(sourceFile));
|
|
2325
|
+
}
|
|
2326
|
+
#scanRoute({ file, sourceFile }) {
|
|
2327
|
+
const fetchNames = RenderMutationScanner.#fetchBindingsOf(sourceFile);
|
|
2328
|
+
if (!fetchNames.size)
|
|
2329
|
+
return [];
|
|
2330
|
+
const functions = RenderMutationScanner.#functionsOf(sourceFile);
|
|
2331
|
+
const calls = new Set;
|
|
2332
|
+
const helpers = new Set;
|
|
2333
|
+
const visit = (node, follow) => {
|
|
2334
|
+
if (RenderMutationScanner.#isEventHandler(node))
|
|
2335
|
+
return;
|
|
2336
|
+
if (this.#isRenderMutation(file, node, fetchNames))
|
|
2337
|
+
calls.add(node);
|
|
2338
|
+
const helper = follow ? RenderMutationScanner.#helperOf(node, functions) : undefined;
|
|
2339
|
+
if (helper)
|
|
2340
|
+
helpers.add(helper);
|
|
2341
|
+
ts16.forEachChild(node, (child) => visit(child, follow));
|
|
2342
|
+
};
|
|
2343
|
+
for (const body of RenderMutationScanner.#renderBodiesOf(sourceFile, functions))
|
|
2344
|
+
visit(body, true);
|
|
2345
|
+
for (const helper of helpers)
|
|
2346
|
+
visit(helper, false);
|
|
2347
|
+
return [...calls].sort((a, b) => a.getStart(sourceFile) - b.getStart(sourceFile)).map((call) => ({
|
|
2348
|
+
rule: RenderMutationScanner.rule,
|
|
2349
|
+
scope: "ssr",
|
|
2350
|
+
severity: "warning",
|
|
2351
|
+
file,
|
|
2352
|
+
line: sourceFile.getLineAndCharacterOfPosition(call.getStart(sourceFile)).line + 1,
|
|
2353
|
+
message: `${call.expression.getText(sourceFile)}() is a mutation sent while the route renders: anyone who opens a link to this page would perform it, and the call is refused unless it passes { duringRender: true }.`,
|
|
2354
|
+
fix: RenderMutationScanner.fix
|
|
2355
|
+
}));
|
|
2356
|
+
}
|
|
2357
|
+
#isRenderMutation(file, node, fetchNames) {
|
|
2358
|
+
if (!ts16.isCallExpression(node))
|
|
2359
|
+
return false;
|
|
2360
|
+
const name = RenderMutationScanner.#endpointOf(node.expression, fetchNames);
|
|
2361
|
+
if (!name || !this.#mutations.isMutation(file, name))
|
|
2362
|
+
return false;
|
|
2363
|
+
return !RenderMutationScanner.#optsIn(node, this.#mutations.policyIndexOf(file, name));
|
|
2364
|
+
}
|
|
2365
|
+
static #isEventHandler(node) {
|
|
2366
|
+
return ts16.isJsxAttribute(node) && ts16.isIdentifier(node.name) && /^on[A-Z]/.test(node.name.text);
|
|
2367
|
+
}
|
|
2368
|
+
static #endpointOf(callee, fetchNames) {
|
|
2369
|
+
if (ts16.isPropertyAccessExpression(callee))
|
|
2370
|
+
return RenderMutationScanner.#isFetch(callee.expression, fetchNames) ? callee.name.text : null;
|
|
2371
|
+
if (ts16.isElementAccessExpression(callee) && ts16.isStringLiteralLike(callee.argumentExpression))
|
|
2372
|
+
return RenderMutationScanner.#isFetch(callee.expression, fetchNames) ? callee.argumentExpression.text : null;
|
|
2373
|
+
return null;
|
|
2374
|
+
}
|
|
2375
|
+
static #isFetch(expression, fetchNames) {
|
|
2376
|
+
return ts16.isIdentifier(expression) && fetchNames.has(expression.text);
|
|
2377
|
+
}
|
|
2378
|
+
static #optsIn(call, policyIndex) {
|
|
2379
|
+
if (policyIndex === null)
|
|
2380
|
+
return false;
|
|
2381
|
+
const leading = call.arguments.slice(0, policyIndex + 1);
|
|
2382
|
+
if (leading.some((argument) => ts16.isSpreadElement(argument)))
|
|
2383
|
+
return true;
|
|
2384
|
+
const policy = leading[policyIndex];
|
|
2385
|
+
return policy ? RenderMutationScanner.#policyOptsIn(policy) : false;
|
|
2386
|
+
}
|
|
2387
|
+
static #policyOptsIn(argument) {
|
|
2388
|
+
const policy = RenderMutationScanner.#unwrap(argument);
|
|
2389
|
+
if (!ts16.isObjectLiteralExpression(policy))
|
|
2390
|
+
return !RenderMutationScanner.#cannotBePolicy(policy);
|
|
2391
|
+
return policy.properties.some((property) => {
|
|
2392
|
+
if (ts16.isSpreadAssignment(property))
|
|
2393
|
+
return true;
|
|
2394
|
+
if (!ts16.isPropertyAssignment(property) && !ts16.isShorthandPropertyAssignment(property))
|
|
2395
|
+
return false;
|
|
2396
|
+
if (!(ts16.isIdentifier(property.name) || ts16.isStringLiteral(property.name)))
|
|
2397
|
+
return false;
|
|
2398
|
+
if (property.name.text !== "duringRender")
|
|
2399
|
+
return false;
|
|
2400
|
+
if (ts16.isShorthandPropertyAssignment(property))
|
|
2401
|
+
return true;
|
|
2402
|
+
const value = RenderMutationScanner.#unwrap(property.initializer);
|
|
2403
|
+
return value.kind !== ts16.SyntaxKind.FalseKeyword && !(ts16.isIdentifier(value) && value.text === "undefined");
|
|
2404
|
+
});
|
|
2405
|
+
}
|
|
2406
|
+
static #unwrap(expression) {
|
|
2407
|
+
let current = expression;
|
|
2408
|
+
while (ts16.isParenthesizedExpression(current) || ts16.isAsExpression(current) || ts16.isSatisfiesExpression(current) || ts16.isNonNullExpression(current) || ts16.isTypeAssertionExpression(current))
|
|
2409
|
+
current = current.expression;
|
|
2410
|
+
return current;
|
|
2411
|
+
}
|
|
2412
|
+
static #cannotBePolicy(expression) {
|
|
2413
|
+
if (ts16.isIdentifier(expression))
|
|
2414
|
+
return expression.text === "undefined";
|
|
2415
|
+
return ts16.isLiteralExpression(expression) || ts16.isNoSubstitutionTemplateLiteral(expression) || ts16.isTemplateExpression(expression) || ts16.isArrayLiteralExpression(expression) || ts16.isArrowFunction(expression) || ts16.isFunctionExpression(expression) || ts16.isVoidExpression(expression) || ts16.isPrefixUnaryExpression(expression) || [ts16.SyntaxKind.NullKeyword, ts16.SyntaxKind.TrueKeyword, ts16.SyntaxKind.FalseKeyword].includes(expression.kind);
|
|
2416
|
+
}
|
|
2417
|
+
static #fetchBindingsOf(sourceFile) {
|
|
2418
|
+
const names = new Set;
|
|
2419
|
+
for (const statement of sourceFile.statements) {
|
|
2420
|
+
if (!ts16.isImportDeclaration(statement) || statement.importClause?.isTypeOnly)
|
|
2421
|
+
continue;
|
|
2422
|
+
const bindings = statement.importClause?.namedBindings;
|
|
2423
|
+
if (!bindings || !ts16.isNamedImports(bindings))
|
|
2424
|
+
continue;
|
|
2425
|
+
for (const element of bindings.elements)
|
|
2426
|
+
if (!element.isTypeOnly && (element.propertyName ?? element.name).text === "fetch")
|
|
2427
|
+
names.add(element.name.text);
|
|
2428
|
+
}
|
|
2429
|
+
return names;
|
|
2430
|
+
}
|
|
2431
|
+
static #functionsOf(sourceFile) {
|
|
2432
|
+
const functions = new Map;
|
|
2433
|
+
for (const statement of sourceFile.statements) {
|
|
2434
|
+
if (ts16.isFunctionDeclaration(statement) && statement.name && statement.body)
|
|
2435
|
+
functions.set(statement.name.text, statement.body);
|
|
2436
|
+
if (!ts16.isVariableStatement(statement))
|
|
2437
|
+
continue;
|
|
2438
|
+
for (const declaration of statement.declarationList.declarations) {
|
|
2439
|
+
const initializer = declaration.initializer && RenderMutationScanner.#unwrap(declaration.initializer);
|
|
2440
|
+
if (!ts16.isIdentifier(declaration.name) || !initializer)
|
|
2441
|
+
continue;
|
|
2442
|
+
if (ts16.isArrowFunction(initializer) || ts16.isFunctionExpression(initializer))
|
|
2443
|
+
functions.set(declaration.name.text, initializer.body);
|
|
2444
|
+
}
|
|
2445
|
+
}
|
|
2446
|
+
return functions;
|
|
2447
|
+
}
|
|
2448
|
+
static #helperOf(node, functions) {
|
|
2449
|
+
const callee = ts16.isCallExpression(node) ? node.expression : ts16.isJsxSelfClosingElement(node) || ts16.isJsxOpeningElement(node) ? node.tagName : undefined;
|
|
2450
|
+
return callee && ts16.isIdentifier(callee) ? functions.get(callee.text) : undefined;
|
|
2451
|
+
}
|
|
2452
|
+
static #renderBodiesOf(sourceFile, functions) {
|
|
2453
|
+
const bodies = [];
|
|
2454
|
+
const bodyOf = (node) => ts16.isIdentifier(node) ? functions.get(node.text) : node;
|
|
2455
|
+
const visit = (node) => {
|
|
2456
|
+
if (ts16.isCallExpression(node) && ts16.isPropertyAccessExpression(node.expression) && RenderMutationScanner.#stages.has(node.expression.name.text) && RenderMutationScanner.#isRouteChain(node.expression.expression))
|
|
2457
|
+
for (const argument of node.arguments) {
|
|
2458
|
+
const body = bodyOf(argument);
|
|
2459
|
+
if (body)
|
|
2460
|
+
bodies.push(body);
|
|
2461
|
+
}
|
|
2462
|
+
ts16.forEachChild(node, visit);
|
|
2463
|
+
};
|
|
2464
|
+
visit(sourceFile);
|
|
2465
|
+
for (const statement of sourceFile.statements) {
|
|
2466
|
+
const legacy = RenderMutationScanner.#legacyPageOf(statement, functions);
|
|
2467
|
+
if (legacy)
|
|
2468
|
+
bodies.push(legacy);
|
|
2469
|
+
}
|
|
2470
|
+
return bodies;
|
|
2471
|
+
}
|
|
2472
|
+
static #isRouteChain(expression) {
|
|
2473
|
+
let current = expression;
|
|
2474
|
+
while (ts16.isCallExpression(current)) {
|
|
2475
|
+
if (ts16.isIdentifier(current.expression))
|
|
2476
|
+
return RenderMutationScanner.#builders.has(current.expression.text);
|
|
2477
|
+
if (!ts16.isPropertyAccessExpression(current.expression))
|
|
2478
|
+
return false;
|
|
2479
|
+
current = current.expression.expression;
|
|
2480
|
+
}
|
|
2481
|
+
return false;
|
|
2482
|
+
}
|
|
2483
|
+
static #legacyPageOf(statement, functions) {
|
|
2484
|
+
if (ts16.isFunctionDeclaration(statement))
|
|
2485
|
+
return statement.modifiers?.some((modifier) => modifier.kind === ts16.SyntaxKind.DefaultKeyword) ? statement.body : undefined;
|
|
2486
|
+
if (!ts16.isExportAssignment(statement))
|
|
2487
|
+
return;
|
|
2488
|
+
const expression = RenderMutationScanner.#unwrap(statement.expression);
|
|
2489
|
+
if (ts16.isIdentifier(expression))
|
|
2490
|
+
return functions.get(expression.text);
|
|
2491
|
+
return ts16.isArrowFunction(expression) || ts16.isFunctionExpression(expression) ? expression.body : undefined;
|
|
2492
|
+
}
|
|
2493
|
+
}
|
|
2494
|
+
|
|
2495
|
+
// pkgs/@akanjs/devkit/ssrScanner.ts
|
|
2496
|
+
var STATIC_COMPONENT_MIN_MASS = 4;
|
|
2497
|
+
var MIXED_COMPONENT_MIN_MASS = 10;
|
|
2498
|
+
var MIXED_COMPONENT_MAX_TOUCHES = 2;
|
|
2499
|
+
var MODULE_SERVER_VIEW_MIN_CLIENT_MASS = 12;
|
|
2500
|
+
var fileWarning = (rule, scope, file, message, line) => line === undefined ? { rule, scope, severity: "warning", file, message } : { rule, scope, severity: "warning", file, line, message };
|
|
2501
|
+
|
|
2502
|
+
class SsrScanner {
|
|
2503
|
+
static #serverSafeCalls = new Set(["usePage", "getSelf", "useServer"]);
|
|
2504
|
+
static #clientGlobals = new Set("window document navigator localStorage sessionStorage location history screen matchMedia IntersectionObserver".split(" ").concat("ResizeObserver MutationObserver requestAnimationFrame WebSocket".split(" ")));
|
|
2505
|
+
static #clientRuntimeImports = new Set(["st", "fetch"]);
|
|
2506
|
+
static #mountWriteFix = "Send the write from an explicit user action, such as a button that calls a store action. Do not move it into the route: a write there runs for anyone who opens a link to the page.";
|
|
2507
|
+
scan(sourceFiles) {
|
|
2508
|
+
const mutations = new SignalMutationIndex(sourceFiles);
|
|
2509
|
+
const componentFiles = sourceFiles.filter((sourceFile) => this.#isBalancedFile(sourceFile.file));
|
|
2510
|
+
return {
|
|
2511
|
+
warnings: [
|
|
2512
|
+
...componentFiles.flatMap((sourceFile) => this.#scanFile(sourceFile, mutations)),
|
|
2513
|
+
...this.#scanModules(componentFiles),
|
|
2514
|
+
...new RenderMutationScanner(mutations).scan(sourceFiles)
|
|
2515
|
+
],
|
|
2516
|
+
balance: this.#measureBalance(componentFiles)
|
|
2517
|
+
};
|
|
2518
|
+
}
|
|
2519
|
+
#scanFile(sourceFile, mutations) {
|
|
2520
|
+
if (!this.#hasUseClient(sourceFile.sourceFile))
|
|
2521
|
+
return [];
|
|
2522
|
+
const vendorNames = this.#getVendorNames(sourceFile.sourceFile);
|
|
2523
|
+
const hasVendorImport = this.#hasVendorImport(sourceFile.sourceFile);
|
|
2524
|
+
const importsClientRuntime = this.#importsClientRuntime(sourceFile.sourceFile);
|
|
2525
|
+
const components = this.#getComponents(sourceFile, vendorNames);
|
|
2526
|
+
const warnings = [];
|
|
2527
|
+
if (!hasVendorImport && !importsClientRuntime && this.#getTouches(sourceFile.sourceFile, sourceFile.sourceFile).length === 0 && !this.#isConventionClientFile(sourceFile.file)) {
|
|
2528
|
+
warnings.push(fileWarning("akan.ssr.unnecessary-use-client", "ssr", sourceFile.file, `"use client" is declared but the file uses no client-only capability (hook, event handler, store, or browser API).`, 1));
|
|
2529
|
+
}
|
|
2530
|
+
for (const component of components) {
|
|
2531
|
+
if (component.vendorTags)
|
|
2532
|
+
continue;
|
|
2533
|
+
if (component.touches.length === 0 && component.mass >= STATIC_COMPONENT_MIN_MASS) {
|
|
2534
|
+
warnings.push(fileWarning("akan.ssr.client-static-component", "ssr", sourceFile.file, `Client component "${component.name}" renders ${component.mass} JSX elements with no client-only capability. It is server-renderable markup sitting in the client bundle.`, component.line));
|
|
2535
|
+
continue;
|
|
2536
|
+
}
|
|
2537
|
+
if (component.touches.length >= 1 && component.touches.length <= MIXED_COMPONENT_MAX_TOUCHES && component.mass >= MIXED_COMPONENT_MIN_MASS) {
|
|
2538
|
+
warnings.push(fileWarning("akan.ssr.client-static-markup", "ssr", sourceFile.file, `Client component "${component.name}" renders ${component.mass} JSX elements around only ${component.touches.length} client-only touch (${[...new Set(component.touches)].join(", ")}). Most of this subtree does not need the client bundle.`, component.line));
|
|
2539
|
+
}
|
|
2540
|
+
}
|
|
2541
|
+
warnings.push(...this.#getMountLoadWarnings(sourceFile, mutations));
|
|
2542
|
+
warnings.push(...this.#getTemplateStateWarnings(sourceFile));
|
|
2543
|
+
return warnings;
|
|
2544
|
+
}
|
|
2545
|
+
#scanModules(sourceFiles) {
|
|
2546
|
+
const modules = new Map;
|
|
2547
|
+
for (const sourceFile of sourceFiles) {
|
|
2548
|
+
const moduleDir = this.#getModuleDir(sourceFile.file);
|
|
2549
|
+
if (!moduleDir)
|
|
2550
|
+
continue;
|
|
2551
|
+
const entry = modules.get(moduleDir) ?? { clientMass: 0, serverFiles: 0, line: sourceFile.file };
|
|
2552
|
+
if (this.#hasUseClient(sourceFile.sourceFile))
|
|
2553
|
+
entry.clientMass += this.#getMass(sourceFile.sourceFile);
|
|
2554
|
+
else if (/\.(Unit|View)\.tsx$/.test(sourceFile.file))
|
|
2555
|
+
entry.serverFiles += 1;
|
|
2556
|
+
modules.set(moduleDir, entry);
|
|
2557
|
+
}
|
|
2558
|
+
return [...modules].filter(([, entry]) => entry.serverFiles === 0 && entry.clientMass >= MODULE_SERVER_VIEW_MIN_CLIENT_MASS).map(([moduleDir, entry]) => fileWarning("akan.ssr.module-missing-server-view", "ssr", entry.line, `Module "${moduleDir}" renders ${entry.clientMass} JSX elements from client files only; it declares no Unit or View server component.`));
|
|
2559
|
+
}
|
|
2560
|
+
#getMountLoadWarnings(sourceFile, mutations) {
|
|
2561
|
+
const warnings = [];
|
|
2562
|
+
SsrScanner.#walk(sourceFile.sourceFile, (node) => {
|
|
2563
|
+
if (!this.#isMountEffect(sourceFile.sourceFile, node))
|
|
2564
|
+
return;
|
|
2565
|
+
for (const load of this.#getLoadCalls(sourceFile.sourceFile, node)) {
|
|
2566
|
+
const line = this.#getLine(sourceFile.sourceFile, load.node);
|
|
2567
|
+
warnings.push(load.callee.startsWith("fetch.") && mutations.isMutation(sourceFile.file, load.callee.slice("fetch.".length)) ? {
|
|
2568
|
+
...fileWarning("akan.ssr.client-mount-load", "ssr", sourceFile.file, `Mount-only effect sends the mutation ${load.callee}() each time the component mounts. A write is not data the route can load.`, line),
|
|
2569
|
+
fix: SsrScanner.#mountWriteFix
|
|
2570
|
+
} : fileWarning("akan.ssr.client-mount-load", "ssr", sourceFile.file, `Mount-only effect loads server data with ${load.callee}(). The route can fetch this before the first byte instead.`, line));
|
|
2571
|
+
}
|
|
2572
|
+
});
|
|
2573
|
+
return warnings;
|
|
2574
|
+
}
|
|
2575
|
+
#isMountEffect(sourceFile, node) {
|
|
2576
|
+
if (!ts17.isCallExpression(node))
|
|
2577
|
+
return false;
|
|
2578
|
+
const callee = node.expression.getText(sourceFile);
|
|
2579
|
+
if (callee !== "useEffect" && callee !== "useLayoutEffect")
|
|
2580
|
+
return false;
|
|
2581
|
+
const deps = node.arguments[1];
|
|
2582
|
+
return !!deps && ts17.isArrayLiteralExpression(deps) && deps.elements.length === 0;
|
|
2583
|
+
}
|
|
2584
|
+
#getLoadCalls(sourceFile, node) {
|
|
2585
|
+
const calls = [];
|
|
2586
|
+
SsrScanner.#walk(node, (child) => {
|
|
2587
|
+
if (!ts17.isCallExpression(child))
|
|
2588
|
+
return;
|
|
2589
|
+
const callee = child.expression.getText(sourceFile);
|
|
2590
|
+
if (/^fetch\.[a-z]/.test(callee) || /^st\.do\.(init|get|view|load|list|count|insight)[A-Z]/.test(callee))
|
|
2591
|
+
calls.push({ callee, node: child });
|
|
2592
|
+
});
|
|
2593
|
+
return calls;
|
|
2594
|
+
}
|
|
2595
|
+
#getTemplateStateWarnings(sourceFile) {
|
|
2596
|
+
if (!sourceFile.file.endsWith(".Template.tsx"))
|
|
2597
|
+
return [];
|
|
2598
|
+
const warnings = [];
|
|
2599
|
+
SsrScanner.#walk(sourceFile.sourceFile, (node) => {
|
|
2600
|
+
if (ts17.isCallExpression(node) && node.expression.getText(sourceFile.sourceFile) === "useState")
|
|
2601
|
+
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)));
|
|
2602
|
+
});
|
|
2603
|
+
return warnings;
|
|
2604
|
+
}
|
|
2605
|
+
#measureBalance(sourceFiles) {
|
|
2606
|
+
const scopes = new Map;
|
|
2607
|
+
for (const sourceFile of sourceFiles) {
|
|
2608
|
+
const segments = sourceFile.file.split("/");
|
|
2609
|
+
const scope = `${segments[0]}/${segments[1]}`;
|
|
2610
|
+
const entry = scopes.get(scope) ?? { serverMass: 0, clientMass: 0 };
|
|
2611
|
+
const mass = this.#getMass(sourceFile.sourceFile);
|
|
2612
|
+
if (this.#hasUseClient(sourceFile.sourceFile))
|
|
2613
|
+
entry.clientMass += mass;
|
|
2614
|
+
else
|
|
2615
|
+
entry.serverMass += mass;
|
|
2616
|
+
scopes.set(scope, entry);
|
|
2617
|
+
}
|
|
2618
|
+
const entries = [...scopes].map(([scope, mass]) => ({ scope, ...mass, serverShare: getShare(mass.serverMass, mass.clientMass) })).sort((a, b) => a.scope.localeCompare(b.scope));
|
|
2619
|
+
if (entries.length < 2)
|
|
2620
|
+
return entries;
|
|
2621
|
+
const serverMass = entries.reduce((sum, entry) => sum + entry.serverMass, 0);
|
|
2622
|
+
const clientMass = entries.reduce((sum, entry) => sum + entry.clientMass, 0);
|
|
2623
|
+
return [...entries, { scope: "workspace", serverMass, clientMass, serverShare: getShare(serverMass, clientMass) }];
|
|
2624
|
+
}
|
|
2625
|
+
#getComponents(sourceFile, vendorNames) {
|
|
2626
|
+
const components = [];
|
|
2627
|
+
for (const statement of sourceFile.sourceFile.statements) {
|
|
2628
|
+
for (const { name, node } of this.#getComponentNodes(statement)) {
|
|
2629
|
+
if (!/^[A-Z]/.test(name))
|
|
2630
|
+
continue;
|
|
2631
|
+
components.push({
|
|
2632
|
+
name,
|
|
2633
|
+
line: this.#getLine(sourceFile.sourceFile, node),
|
|
2634
|
+
mass: this.#getMass(node),
|
|
2635
|
+
touches: this.#getTouches(sourceFile.sourceFile, node),
|
|
2636
|
+
vendorTags: [...this.#getTagNames(sourceFile.sourceFile, node)].some((tag) => vendorNames.has(tag))
|
|
2637
|
+
});
|
|
2638
|
+
}
|
|
2639
|
+
}
|
|
2640
|
+
return components;
|
|
2641
|
+
}
|
|
2642
|
+
#getComponentNodes(statement) {
|
|
2643
|
+
if (ts17.isFunctionDeclaration(statement) && statement.body)
|
|
2644
|
+
return [{ name: statement.name?.text ?? "default", node: statement.body }];
|
|
2645
|
+
if (!ts17.isVariableStatement(statement))
|
|
2646
|
+
return [];
|
|
2647
|
+
return statement.declarationList.declarations.flatMap((declaration) => {
|
|
2648
|
+
if (!ts17.isIdentifier(declaration.name) || !declaration.initializer)
|
|
2649
|
+
return [];
|
|
2650
|
+
if (!ts17.isArrowFunction(declaration.initializer) && !ts17.isFunctionExpression(declaration.initializer))
|
|
2651
|
+
return [];
|
|
2652
|
+
return [{ name: declaration.name.text, node: declaration.initializer }];
|
|
2653
|
+
});
|
|
2654
|
+
}
|
|
2655
|
+
#getTouches(sourceFile, node) {
|
|
2656
|
+
const touches = [];
|
|
2657
|
+
SsrScanner.#walk(node, (child) => {
|
|
2658
|
+
if (ts17.isCallExpression(child)) {
|
|
2659
|
+
const callee = child.expression.getText(sourceFile);
|
|
2660
|
+
const bareName = callee.split(".").pop() ?? callee;
|
|
2661
|
+
if (callee === "createContext" || callee === "lazy")
|
|
2662
|
+
touches.push(callee);
|
|
2663
|
+
else if (/^use[A-Z]/.test(bareName) && !SsrScanner.#serverSafeCalls.has(bareName))
|
|
2664
|
+
touches.push(bareName);
|
|
2665
|
+
}
|
|
2666
|
+
if (ts17.isJsxAttribute(child) && /^on[A-Z]/.test(child.name.getText(sourceFile)))
|
|
2667
|
+
touches.push(child.name.getText(sourceFile));
|
|
2668
|
+
if (ts17.isPropertyAccessExpression(child)) {
|
|
2669
|
+
const root = getAccessRoot(child);
|
|
2670
|
+
if (root === "st")
|
|
2671
|
+
touches.push("st");
|
|
2672
|
+
else if (SsrScanner.#clientGlobals.has(root))
|
|
2673
|
+
touches.push(root);
|
|
2674
|
+
}
|
|
2675
|
+
});
|
|
2676
|
+
return touches;
|
|
2677
|
+
}
|
|
2678
|
+
#getTagNames(sourceFile, node) {
|
|
2679
|
+
const tags = new Set;
|
|
2680
|
+
SsrScanner.#walk(node, (child) => {
|
|
2681
|
+
if (ts17.isJsxOpeningElement(child) || ts17.isJsxSelfClosingElement(child))
|
|
2682
|
+
tags.add(child.tagName.getText(sourceFile).split(".")[0]);
|
|
2683
|
+
});
|
|
2684
|
+
return tags;
|
|
2685
|
+
}
|
|
2686
|
+
#getMass(node) {
|
|
2687
|
+
let mass = 0;
|
|
2688
|
+
SsrScanner.#walk(node, (child) => {
|
|
2689
|
+
if (ts17.isJsxOpeningElement(child) || ts17.isJsxSelfClosingElement(child))
|
|
2690
|
+
mass += 1;
|
|
2691
|
+
});
|
|
2692
|
+
return mass;
|
|
2693
|
+
}
|
|
2694
|
+
static #walk(node, visit) {
|
|
2695
|
+
const walk = (child) => {
|
|
2696
|
+
visit(child);
|
|
2697
|
+
ts17.forEachChild(child, walk);
|
|
2698
|
+
};
|
|
2699
|
+
ts17.forEachChild(node, walk);
|
|
2700
|
+
}
|
|
2701
|
+
#hasUseClient(sourceFile) {
|
|
2702
|
+
const first = sourceFile.statements[0];
|
|
2703
|
+
if (!first || !ts17.isExpressionStatement(first) || !ts17.isStringLiteral(first.expression))
|
|
2704
|
+
return false;
|
|
2705
|
+
return first.expression.text === "use client";
|
|
2706
|
+
}
|
|
2707
|
+
#hasVendorImport(sourceFile) {
|
|
2708
|
+
return sourceFile.statements.some((statement) => ts17.isImportDeclaration(statement) && isVendorSpecifier(getSpecifier(statement)));
|
|
2709
|
+
}
|
|
2710
|
+
#getVendorNames(sourceFile) {
|
|
2711
|
+
const names = new Set;
|
|
2712
|
+
for (const statement of sourceFile.statements) {
|
|
2713
|
+
if (!ts17.isImportDeclaration(statement) || !isVendorSpecifier(getSpecifier(statement)))
|
|
2714
|
+
continue;
|
|
2715
|
+
const clause = statement.importClause;
|
|
2716
|
+
if (clause?.name)
|
|
2717
|
+
names.add(clause.name.text);
|
|
2718
|
+
if (clause?.namedBindings && ts17.isNamespaceImport(clause.namedBindings))
|
|
2719
|
+
names.add(clause.namedBindings.name.text);
|
|
2720
|
+
if (clause?.namedBindings && ts17.isNamedImports(clause.namedBindings))
|
|
2721
|
+
for (const element of clause.namedBindings.elements)
|
|
2722
|
+
names.add(element.name.text);
|
|
2723
|
+
}
|
|
2724
|
+
return names;
|
|
2725
|
+
}
|
|
2726
|
+
#importsClientRuntime(sourceFile) {
|
|
2727
|
+
for (const statement of sourceFile.statements) {
|
|
2728
|
+
if (!ts17.isImportDeclaration(statement))
|
|
2729
|
+
continue;
|
|
2730
|
+
const bindings = statement.importClause?.namedBindings;
|
|
2731
|
+
if (!bindings || !ts17.isNamedImports(bindings))
|
|
2732
|
+
continue;
|
|
2733
|
+
if (bindings.elements.some((element) => SsrScanner.#clientRuntimeImports.has(element.name.text)))
|
|
2734
|
+
return true;
|
|
2735
|
+
}
|
|
2736
|
+
return false;
|
|
2737
|
+
}
|
|
2738
|
+
#isConventionClientFile(file) {
|
|
2739
|
+
if (file.endsWith("/index_.tsx"))
|
|
2740
|
+
return true;
|
|
2741
|
+
return /\.(Zone|Template|Util)\.tsx$/.test(file) && this.#getModuleDir(file) !== null;
|
|
2742
|
+
}
|
|
2743
|
+
#isBalancedFile(file) {
|
|
2744
|
+
if (!file.endsWith(".tsx") || file.endsWith(".test.tsx") || file.endsWith(".spec.tsx"))
|
|
2745
|
+
return false;
|
|
2746
|
+
const segments = file.split("/");
|
|
2747
|
+
if (segments[0] !== "apps" && segments[0] !== "libs")
|
|
2748
|
+
return false;
|
|
2749
|
+
return segments[2] === "ui" || segments[2] === "lib";
|
|
2750
|
+
}
|
|
2751
|
+
#getModuleDir(file) {
|
|
2752
|
+
const segments = file.split("/");
|
|
2753
|
+
const libIndex = segments.indexOf("lib");
|
|
2754
|
+
if (libIndex < 1 || segments.length <= libIndex + 2)
|
|
2755
|
+
return null;
|
|
2756
|
+
const moduleName = segments[libIndex + 1];
|
|
2757
|
+
if (moduleName.startsWith("_"))
|
|
2758
|
+
return null;
|
|
2759
|
+
return segments.slice(0, libIndex + 2).join("/");
|
|
2760
|
+
}
|
|
2761
|
+
#getLine(sourceFile, node) {
|
|
2762
|
+
return sourceFile.getLineAndCharacterOfPosition(node.getStart(sourceFile)).line + 1;
|
|
2763
|
+
}
|
|
2764
|
+
}
|
|
2765
|
+
var SSR_SERVER_SHARE_TARGET = 0.5;
|
|
2766
|
+
function formatSsrBalance(balance) {
|
|
2767
|
+
if (balance.length === 0)
|
|
2768
|
+
return ["No component files found."];
|
|
2769
|
+
return balance.map((entry) => {
|
|
2770
|
+
const total = entry.serverMass + entry.clientMass;
|
|
2771
|
+
const share = `${Math.round(entry.serverShare * 100)}% server`;
|
|
2772
|
+
const counts = `${entry.serverMass} of ${total} JSX elements, ${entry.clientMass} client`;
|
|
2773
|
+
const flag = entry.serverShare < SSR_SERVER_SHARE_TARGET ? ` <- below the ${Math.round(SSR_SERVER_SHARE_TARGET * 100)}% target` : "";
|
|
2774
|
+
return ` ${entry.scope}: ${share} (${counts})${flag}`;
|
|
2775
|
+
});
|
|
2776
|
+
}
|
|
2777
|
+
function getShare(serverMass, clientMass) {
|
|
2778
|
+
const total = serverMass + clientMass;
|
|
2779
|
+
return total === 0 ? 1 : serverMass / total;
|
|
2780
|
+
}
|
|
2781
|
+
function getSpecifier(statement) {
|
|
2782
|
+
return ts17.isStringLiteral(statement.moduleSpecifier) ? statement.moduleSpecifier.text : "";
|
|
2783
|
+
}
|
|
2784
|
+
function isVendorSpecifier(specifier) {
|
|
2785
|
+
if (specifier === "" || specifier.startsWith(".") || specifier.startsWith("/"))
|
|
2786
|
+
return false;
|
|
2787
|
+
if (specifier === "react" || specifier === "react-dom" || specifier.startsWith("react/"))
|
|
2788
|
+
return false;
|
|
2789
|
+
if (specifier.startsWith("node:"))
|
|
2790
|
+
return false;
|
|
2791
|
+
return !/^(akanjs|@akanjs|@libs|@apps|@contract)(\/|$)/.test(specifier);
|
|
2792
|
+
}
|
|
2793
|
+
function getAccessRoot(node) {
|
|
2794
|
+
let current = node;
|
|
2795
|
+
while (ts17.isPropertyAccessExpression(current))
|
|
2796
|
+
current = current.expression;
|
|
2797
|
+
return ts17.isIdentifier(current) ? current.text : "";
|
|
2798
|
+
}
|
|
2799
|
+
|
|
2800
|
+
// pkgs/@akanjs/devkit/testOnlyExportScanner.ts
|
|
2801
|
+
import ts18 from "typescript";
|
|
2802
|
+
|
|
2803
|
+
class TestOnlyExportScanner {
|
|
2804
|
+
static rule = "akan.global.test-only-export";
|
|
2805
|
+
static #facets = new Set(["common", "webkit", "srvkit", "ui"]);
|
|
2806
|
+
scan(sourceFiles) {
|
|
2807
|
+
const liveFileNumByName = new Map;
|
|
2808
|
+
const testRefsByName = new Map;
|
|
2809
|
+
for (const { file, sourceFile } of sourceFiles) {
|
|
2810
|
+
const isTest = TestOnlyExportScanner.#isTest(file);
|
|
2811
|
+
for (const [name, line] of TestOnlyExportScanner.#identifierLinesOf(sourceFile)) {
|
|
2812
|
+
if (!isTest)
|
|
2813
|
+
liveFileNumByName.set(name, (liveFileNumByName.get(name) ?? 0) + 1);
|
|
2814
|
+
else if (testRefsByName.has(name))
|
|
2815
|
+
testRefsByName.get(name)?.push({ file, line });
|
|
2816
|
+
else
|
|
2817
|
+
testRefsByName.set(name, [{ file, line }]);
|
|
2818
|
+
}
|
|
2819
|
+
}
|
|
2820
|
+
return sourceFiles.filter(({ file }) => TestOnlyExportScanner.#isFacetSource(file)).flatMap(({ file, sourceFile }) => {
|
|
2821
|
+
const declarations = TestOnlyExportScanner.#exportedDeclarationsOf(sourceFile);
|
|
2822
|
+
return declarations.filter(({ name }) => (liveFileNumByName.get(name) ?? 0) <= 1).filter(({ name }) => !TestOnlyExportScanner.#isUsedInFile(sourceFile, name, declarations)).flatMap(({ name, line }) => {
|
|
2823
|
+
const testRefs = testRefsByName.get(name);
|
|
2824
|
+
if (!testRefs?.length)
|
|
2825
|
+
return [];
|
|
2826
|
+
return [
|
|
2827
|
+
{
|
|
2828
|
+
rule: TestOnlyExportScanner.rule,
|
|
2829
|
+
scope: "global",
|
|
2830
|
+
severity: "warning",
|
|
2831
|
+
file,
|
|
2832
|
+
line,
|
|
2833
|
+
message: `Exported "${name}" is referenced only by tests: ${testRefs.map((ref) => ref.file).join(", ")}.`,
|
|
2834
|
+
locations: testRefs
|
|
2835
|
+
}
|
|
2836
|
+
];
|
|
2837
|
+
});
|
|
2838
|
+
});
|
|
2839
|
+
}
|
|
2840
|
+
static #isTest(file) {
|
|
2841
|
+
return /\.(test|spec)\.tsx?$/.test(file);
|
|
2842
|
+
}
|
|
2843
|
+
static #isFacetSource(file) {
|
|
2844
|
+
const segments = file.split("/");
|
|
2845
|
+
if (segments[0] !== "apps")
|
|
2846
|
+
return false;
|
|
2847
|
+
return TestOnlyExportScanner.#facets.has(segments[2] ?? "") && !TestOnlyExportScanner.#isTest(file);
|
|
2848
|
+
}
|
|
2849
|
+
static #identifierLinesOf(sourceFile) {
|
|
2850
|
+
const lines = new Map;
|
|
2851
|
+
const visit = (node) => {
|
|
2852
|
+
if (ts18.isIdentifier(node) && !lines.has(node.text))
|
|
2853
|
+
lines.set(node.text, sourceFile.getLineAndCharacterOfPosition(node.getStart(sourceFile)).line + 1);
|
|
2854
|
+
ts18.forEachChild(node, visit);
|
|
2855
|
+
};
|
|
2856
|
+
visit(sourceFile);
|
|
2857
|
+
return lines;
|
|
2858
|
+
}
|
|
2859
|
+
static #exportedDeclarationsOf(sourceFile) {
|
|
2860
|
+
return sourceFile.statements.flatMap((statement) => {
|
|
2861
|
+
if (!TestOnlyExportScanner.#isNamedExport(statement))
|
|
2862
|
+
return [];
|
|
2863
|
+
return TestOnlyExportScanner.#declaredNamesOf(statement).map((identifier) => ({
|
|
2864
|
+
name: identifier.text,
|
|
2865
|
+
line: sourceFile.getLineAndCharacterOfPosition(identifier.getStart(sourceFile)).line + 1,
|
|
2866
|
+
statement
|
|
2867
|
+
}));
|
|
2868
|
+
});
|
|
2869
|
+
}
|
|
2870
|
+
static #isNamedExport(statement) {
|
|
2871
|
+
if (!ts18.canHaveModifiers(statement))
|
|
2872
|
+
return false;
|
|
2873
|
+
const modifiers = ts18.getModifiers(statement) ?? [];
|
|
2874
|
+
return modifiers.some((modifier) => modifier.kind === ts18.SyntaxKind.ExportKeyword) && !modifiers.some((modifier) => modifier.kind === ts18.SyntaxKind.DefaultKeyword);
|
|
2875
|
+
}
|
|
2876
|
+
static #declaredNamesOf(statement) {
|
|
2877
|
+
if (ts18.isVariableStatement(statement))
|
|
2878
|
+
return statement.declarationList.declarations.map((declaration) => declaration.name).filter((name) => ts18.isIdentifier(name));
|
|
2879
|
+
if (ts18.isFunctionDeclaration(statement) || ts18.isClassDeclaration(statement) || ts18.isInterfaceDeclaration(statement) || ts18.isTypeAliasDeclaration(statement) || ts18.isEnumDeclaration(statement))
|
|
2880
|
+
return statement.name ? [statement.name] : [];
|
|
2881
|
+
return [];
|
|
2882
|
+
}
|
|
2883
|
+
static #isUsedInFile(sourceFile, name, declarations) {
|
|
2884
|
+
const ownStatements = new Set(declarations.filter((entry) => entry.name === name).map((entry) => entry.statement));
|
|
2885
|
+
let used = false;
|
|
2886
|
+
const visit = (node) => {
|
|
2887
|
+
if (used || ownStatements.has(node))
|
|
2888
|
+
return;
|
|
2889
|
+
if (ts18.isIdentifier(node) && node.text === name)
|
|
2890
|
+
used = true;
|
|
2891
|
+
else
|
|
2892
|
+
ts18.forEachChild(node, visit);
|
|
2893
|
+
};
|
|
2894
|
+
visit(sourceFile);
|
|
2895
|
+
return used;
|
|
2896
|
+
}
|
|
2897
|
+
}
|
|
2898
|
+
|
|
2899
|
+
// pkgs/@akanjs/devkit/qualityScanner.ts
|
|
2900
|
+
var MAX_FILE_LINES = 2000;
|
|
2901
|
+
var PLACEHOLDER_EXPORT_NAMES = new Set([
|
|
2902
|
+
"aa",
|
|
2903
|
+
"dumb",
|
|
2904
|
+
"dumb2",
|
|
2905
|
+
"someBaseLogic",
|
|
2906
|
+
"someCommonLogic",
|
|
2907
|
+
"someFrontendLogic",
|
|
2908
|
+
"someBackendLogic"
|
|
2909
|
+
]);
|
|
2910
|
+
var SUGGESTED_RULES = [
|
|
2911
|
+
"Keep generated scanSync index files out of hand-written changes; generated indexes should only contain one-depth export statements.",
|
|
2912
|
+
"Generated Akan index files should not contain placeholder exports such as aa, dumb, dumb2, or some*Logic.",
|
|
2913
|
+
"Dictionary text should not contain scaffold wording, misspellings, or stale copied domain nouns.",
|
|
2914
|
+
"Warn earlier on very long Akan files: 500 lines for services, 800 lines for Template/Zone files, and 1000 lines for Util files.",
|
|
2915
|
+
"Global declarations, Window augmentation, and prototype mutation should stay in explicitly approved low-level integration files.",
|
|
2916
|
+
"Keep app root folders small and conventional: application code belongs under common, env, lib, page, plugin, private, public, script, srvkit, ui, or webkit.",
|
|
2917
|
+
"Keep apps/*/lib and libs/*/lib root files limited to generated support facets such as cnst.ts, db.ts, dict.ts, sig.ts, srv.ts, st.ts, useClient.ts, and useServer.ts.",
|
|
2918
|
+
"Use domain module folders consistently: lib/<model> for database modules, lib/_<service> for service modules, and lib/__scalar/<scalar> for scalar modules.",
|
|
2919
|
+
"Keep module UI filenames predictable: database modules use <Model>.Template/Unit/Util/View/Zone.tsx, service modules use <Service>.Util/Zone.tsx, and scalar modules use <Scalar>.Template/Unit.tsx.",
|
|
2920
|
+
"Hand a form control its store setter by reference so the field publishes an agent tool; put normalization in the control's transform prop and a multi-write in a _postSet<Field> hook on the store.",
|
|
2921
|
+
"Move shared app and lib utilities to common/ instead of creating apps/*/base or libs/*/base.",
|
|
2922
|
+
"Avoid large mixed-purpose class files; class export files should import helpers from neighboring utility files instead of declaring them inline."
|
|
2923
|
+
];
|
|
2924
|
+
var CONVENTION_SUFFIXES = [
|
|
2925
|
+
".constant.ts",
|
|
2926
|
+
".dictionary.ts",
|
|
2927
|
+
".document.ts",
|
|
2928
|
+
".service.ts",
|
|
2929
|
+
".signal.ts",
|
|
2930
|
+
".store.ts"
|
|
2931
|
+
];
|
|
2932
|
+
var RULE_FIXES = {
|
|
2933
|
+
"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.",
|
|
2934
|
+
"akan.global.duplicate-exported-function-body": "Extract the shared implementation into a single exported helper and import it, instead of copying the body.",
|
|
2935
|
+
"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.",
|
|
2936
|
+
"akan.file.recommended-max-lines": "Split the file by responsibility \u2014 move Zones, Utils, or subcomponents into sibling files.",
|
|
2937
|
+
"akan.file.max-lines": "Break the file into smaller focused modules; keep one primary responsibility per file.",
|
|
2938
|
+
"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.",
|
|
2939
|
+
"akan.file.placeholder-export": "Remove the placeholder export; generated indexes should only re-export real modules.",
|
|
2940
|
+
"akan.file.bang-comment-in-client": "Rewrite the marker as `// FIXME:` or `// TODO:`. Keep the bang form for server, srvkit, and CLI files.",
|
|
2941
|
+
"akan.file.dictionary-stale-text": "Replace the scaffold text with real localized copy for this dictionary entry.",
|
|
2942
|
+
"akan.file.global-declaration": "Move the global declaration into an approved low-level integration file (e.g. webkit) and keep it isolated.",
|
|
2943
|
+
"akan.file.window-augmentation": "Move the Window augmentation into an approved browser integration file and keep it isolated.",
|
|
2944
|
+
"akan.file.prototype-mutation": "Avoid prototype mutation, or isolate it in an approved low-level integration file.",
|
|
2945
|
+
"akan.file.class-export-global-declaration": "Move the helper to a sibling file and import it into the class module.",
|
|
2946
|
+
"akan.agent.unpublished-form-setter": "Pass the setter by reference where the wrapper only forwards (onChange={st.do.setTitleOnTask}); move normalization into the control's own transform prop; move a multi-write into a _postSet<Field> hook on the store, keeping the generated setter on the control.",
|
|
2947
|
+
"akan.file.component-internal-declaration": "Move the type or helper to a type/util file in ui/, webkit/, or common/ by purpose. If it is the component's props, declare it as `interface <Component>Props`.",
|
|
2948
|
+
"akan.file.component-export": "Move the value or type to a util/constant/type file in ui/, webkit/, or common/ and import it. Adding `export` is not a valid fix \u2014 only PascalCase components and their `<Component>Props` interface belong here.",
|
|
2949
|
+
"akan.layout.app-root-file": "Move the file into a conventional app folder (common, env, lib, page, private, public, script, srvkit, ui, or webkit).",
|
|
2950
|
+
"akan.layout.app-root-folder": "Move the folder's contents into a conventional app folder (common, env, lib, page, private, public, script, srvkit, ui, or webkit) and delete it.",
|
|
2951
|
+
"akan.layout.lib-root-file": "Move the file into a conventional lib folder (common, env, lib, page, private, public, srvkit, ui, or webkit).",
|
|
2952
|
+
"akan.layout.lib-root-folder": "Move the folder's contents into a conventional lib folder (common, env, lib, page, private, public, srvkit, ui, or webkit) and delete it.",
|
|
2953
|
+
"akan.layout.lib-facet-file": "Move the file into a domain module folder under lib/ (a test beside the file it covers, or into srvkit/ when it drives several modules); keep the lib facet root limited to generated support facets.",
|
|
2954
|
+
"akan.layout.facet-index-shadow": "Delete the hand-written index file and run akan sync; move a namespace it builds into <facet>/<Folder>/index.tsx.",
|
|
2955
|
+
"akan.layout.module-ui-file": "Rename the file to an allowed module UI name, or move it to ui/ if it is not a module component.",
|
|
2956
|
+
"akan.ssr.unnecessary-use-client": 'Delete the "use client" directive so the file renders on the server. If it exists only to wrap one client child, drop the wrapper and use the child directly.',
|
|
2957
|
+
"akan.ssr.client-static-component": "Move the component to a server file \u2014 a <Model>.Unit.tsx / <Model>.View.tsx for a module, or a ui/ file with no directive \u2014 and reference it from the client file.",
|
|
2958
|
+
"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.",
|
|
2959
|
+
"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.",
|
|
2960
|
+
"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.",
|
|
2961
|
+
"akan.ssr.template-client-state": "Bind the field to the store instead: `value={xForm.field}` with `onChange={st.do.setFieldOnX}`.",
|
|
2962
|
+
"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").',
|
|
2963
|
+
"akan.comment.deprecated-marker": "Replace the comment with `/** @deprecated <what to use instead> */` on the declaration, so every use site shows it struck through."
|
|
2964
|
+
};
|
|
2965
|
+
function getRuleFix(rule) {
|
|
2966
|
+
if (rule.startsWith("akan.convention"))
|
|
2967
|
+
return "Keep only the model's allowed declarations in this file; move other logic to the matching domain file (service, document, store, etc.).";
|
|
2968
|
+
return RULE_FIXES[rule];
|
|
2969
|
+
}
|
|
2970
|
+
|
|
2971
|
+
class AkanQualityScanner {
|
|
2972
|
+
async scan(workspaceRoot) {
|
|
2973
|
+
const targetFiles = await this.#collectTargetFiles(workspaceRoot);
|
|
2974
|
+
const sourceFiles = await Promise.all(targetFiles.filter((file) => !AbstractDoc.isAbstractPath(file)).map((file) => this.#readSourceFile(workspaceRoot, file)));
|
|
2975
|
+
const abstractFiles = await Promise.all(targetFiles.filter((file) => AbstractDoc.isAbstractPath(file)).map((file) => this.#readTextFile(workspaceRoot, file)));
|
|
2976
|
+
const ssr = new SsrScanner().scan(sourceFiles);
|
|
2977
|
+
const warnings = [
|
|
2978
|
+
...this.#scanGlobalQuality(sourceFiles),
|
|
2979
|
+
...sourceFiles.flatMap((sourceFile) => this.#scanSingleFileQuality(sourceFile)),
|
|
2980
|
+
...sourceFiles.flatMap((sourceFile) => this.#scanComponentQuality(sourceFile)),
|
|
2981
|
+
...sourceFiles.flatMap((sourceFile) => this.#scanConventionQuality(sourceFile)),
|
|
2982
|
+
...sourceFiles.flatMap((sourceFile) => this.#scanLayoutQuality(sourceFile)),
|
|
2983
|
+
...abstractFiles.flatMap((abstractFile) => this.#scanAbstractQuality(abstractFile)),
|
|
2984
|
+
...new FormSetterScanner().scan(sourceFiles),
|
|
2985
|
+
...new CommentDensityScanner().scan(sourceFiles),
|
|
2986
|
+
...new DeprecatedCommentScanner().scan(sourceFiles),
|
|
2987
|
+
...await new MaintainabilityExceptionScanner().scan(workspaceRoot),
|
|
2988
|
+
...ssr.warnings
|
|
2989
|
+
];
|
|
2990
|
+
return {
|
|
2991
|
+
workspaceRoot,
|
|
2992
|
+
scannedFiles: sourceFiles.length + abstractFiles.length,
|
|
2993
|
+
warnings: warnings.map((warning) => ({ ...warning, fix: warning.fix ?? getRuleFix(warning.rule) })).sort(compareWarnings),
|
|
2994
|
+
ssrBalance: ssr.balance,
|
|
2995
|
+
suggestedRules: SUGGESTED_RULES
|
|
2996
|
+
};
|
|
2997
|
+
}
|
|
2998
|
+
async#collectTargetFiles(workspaceRoot) {
|
|
2999
|
+
const ignoreFilter = ignore().add(await this.#readGitIgnore(workspaceRoot));
|
|
3000
|
+
const files = [];
|
|
3001
|
+
for (const targetRoot of ["apps", "libs"]) {
|
|
3002
|
+
const absoluteTargetRoot = path9.join(workspaceRoot, targetRoot);
|
|
3003
|
+
if (!await isDirectory(absoluteTargetRoot))
|
|
3004
|
+
continue;
|
|
3005
|
+
await this.#walkTargetFiles(workspaceRoot, absoluteTargetRoot, ignoreFilter, files);
|
|
3006
|
+
}
|
|
3007
|
+
return files.sort((a, b) => a < b ? -1 : a > b ? 1 : 0);
|
|
3008
|
+
}
|
|
3009
|
+
async#readGitIgnore(workspaceRoot) {
|
|
3010
|
+
const gitIgnorePath = path9.join(workspaceRoot, ".gitignore");
|
|
3011
|
+
if (!await Bun.file(gitIgnorePath).exists())
|
|
3012
|
+
return [];
|
|
3013
|
+
return (await readFile3(gitIgnorePath, "utf8")).split(/\r?\n/);
|
|
3014
|
+
}
|
|
3015
|
+
async#walkTargetFiles(workspaceRoot, currentPath, ignoreFilter, files) {
|
|
3016
|
+
const entries = await readdir2(currentPath, { withFileTypes: true });
|
|
3017
|
+
for (const entry of entries) {
|
|
3018
|
+
const absolutePath = path9.join(currentPath, entry.name);
|
|
3019
|
+
const relativePath = toPosix(path9.relative(workspaceRoot, absolutePath));
|
|
3020
|
+
if (shouldSkipPath(relativePath, entry.isDirectory(), ignoreFilter))
|
|
3021
|
+
continue;
|
|
3022
|
+
if (entry.isDirectory()) {
|
|
3023
|
+
await this.#walkTargetFiles(workspaceRoot, absolutePath, ignoreFilter, files);
|
|
3024
|
+
continue;
|
|
3025
|
+
}
|
|
3026
|
+
if ((relativePath.endsWith(".ts") || relativePath.endsWith(".tsx")) && !relativePath.endsWith(".d.ts")) {
|
|
3027
|
+
files.push(relativePath);
|
|
3028
|
+
} else if (AbstractDoc.isAbstractPath(relativePath)) {
|
|
3029
|
+
files.push(relativePath);
|
|
3030
|
+
}
|
|
3031
|
+
}
|
|
3032
|
+
}
|
|
3033
|
+
async#readSourceFile(workspaceRoot, file) {
|
|
3034
|
+
const absolutePath = path9.join(workspaceRoot, file);
|
|
3035
|
+
const content = await readFile3(absolutePath, "utf8");
|
|
3036
|
+
return {
|
|
3037
|
+
file,
|
|
3038
|
+
absolutePath,
|
|
3039
|
+
content,
|
|
3040
|
+
sourceFile: ts19.createSourceFile(file, content, ts19.ScriptTarget.Latest, true, getScriptKind(file))
|
|
3041
|
+
};
|
|
3042
|
+
}
|
|
3043
|
+
async#readTextFile(workspaceRoot, file) {
|
|
3044
|
+
return { file, content: await readFile3(path9.join(workspaceRoot, file), "utf8") };
|
|
3045
|
+
}
|
|
3046
|
+
#scanGlobalQuality(sourceFiles) {
|
|
3047
|
+
const exportedFunctionLikes = sourceFiles.flatMap((sourceFile) => getExportedFunctionLikes(sourceFile));
|
|
3048
|
+
const warnings = [];
|
|
3049
|
+
const nameCheckedDeclarations = exportedFunctionLikes.filter((declaration) => !declaration.duplicateNameExempt);
|
|
3050
|
+
for (const [name, declarations] of groupBy(nameCheckedDeclarations, (declaration) => declaration.name)) {
|
|
3051
|
+
if (declarations.length < 2)
|
|
3052
|
+
continue;
|
|
3053
|
+
warnings.push({
|
|
3054
|
+
rule: "akan.global.duplicate-exported-function-name",
|
|
3055
|
+
scope: "global",
|
|
3056
|
+
severity: "warning",
|
|
3057
|
+
message: `Exported function or class name "${name}" is declared in ${declarations.length} files.`,
|
|
3058
|
+
locations: declarations.map(({ file, line }) => ({ file, line }))
|
|
3059
|
+
});
|
|
3060
|
+
}
|
|
3061
|
+
const declarationsWithBody = exportedFunctionLikes.filter((declaration) => declaration.bodyFingerprint);
|
|
3062
|
+
for (const [fingerprint, declarations] of groupBy(declarationsWithBody, (declaration) => declaration.bodyFingerprint ?? "")) {
|
|
3063
|
+
const uniqueNames = new Set(declarations.map((declaration) => declaration.name));
|
|
3064
|
+
if (declarations.length < 2 || uniqueNames.size < 2 || fingerprint === "")
|
|
3065
|
+
continue;
|
|
3066
|
+
warnings.push({
|
|
3067
|
+
rule: "akan.global.duplicate-exported-function-body",
|
|
3068
|
+
scope: "global",
|
|
3069
|
+
severity: "warning",
|
|
3070
|
+
message: `Exported functions/classes share the same implementation body: ${declarations.map((declaration) => declaration.name).join(", ")}.`,
|
|
3071
|
+
locations: declarations.map(({ file, line }) => ({ file, line }))
|
|
3072
|
+
});
|
|
3073
|
+
}
|
|
3074
|
+
warnings.push(...new TestOnlyExportScanner().scan(sourceFiles));
|
|
3075
|
+
warnings.push(...new KindBranchScanner().scan(sourceFiles));
|
|
3076
|
+
return warnings;
|
|
3077
|
+
}
|
|
3078
|
+
#scanSingleFileQuality(sourceFile) {
|
|
3079
|
+
const warnings = [];
|
|
3080
|
+
const lineCount = sourceFile.content.split(/\r?\n/).length;
|
|
3081
|
+
const recommendedLineLimit = getRecommendedLineLimit(sourceFile.file);
|
|
3082
|
+
if (recommendedLineLimit && lineCount > recommendedLineLimit)
|
|
3083
|
+
warnings.push(fileWarning("akan.file.recommended-max-lines", "file", sourceFile.file, `File has ${lineCount} lines. Recommended limit for this file type is ${recommendedLineLimit} lines.`));
|
|
3084
|
+
if (lineCount > MAX_FILE_LINES)
|
|
3085
|
+
warnings.push(fileWarning("akan.file.max-lines", "file", sourceFile.file, `File has ${lineCount} lines. Keep single files under ${MAX_FILE_LINES} lines.`));
|
|
3086
|
+
warnings.push(...getBangCommentWarnings(sourceFile));
|
|
3087
|
+
warnings.push(...getPlaceholderExportWarnings(sourceFile));
|
|
3088
|
+
warnings.push(...getDictionaryTextWarnings(sourceFile));
|
|
3089
|
+
warnings.push(...getGlobalMutationWarnings(sourceFile));
|
|
3090
|
+
const exportedClassNames = getExportedClassNames(sourceFile.sourceFile);
|
|
3091
|
+
if (exportedClassNames.length === 0)
|
|
3092
|
+
return warnings;
|
|
3093
|
+
const allowedInterfaceNames = new Set(exportedClassNames.map((name) => `${name}Options`));
|
|
3094
|
+
for (const declaration of getTopLevelDeclarations(sourceFile)) {
|
|
3095
|
+
if (declaration.kind === "class" && exportedClassNames.includes(declaration.name))
|
|
3096
|
+
continue;
|
|
3097
|
+
if (declaration.kind === "interface" && allowedInterfaceNames.has(declaration.name))
|
|
3098
|
+
continue;
|
|
3099
|
+
if ((declaration.kind === "interface" || declaration.kind === "type") && !declaration.exported)
|
|
3100
|
+
continue;
|
|
3101
|
+
warnings.push(fileWarning("akan.file.class-export-global-declaration", "file", sourceFile.file, `Class export files should not declare top-level ${declaration.kind} "${declaration.name}". Move helpers to another file and import them.`, declaration.line));
|
|
3102
|
+
}
|
|
3103
|
+
return warnings;
|
|
3104
|
+
}
|
|
3105
|
+
#scanComponentQuality(sourceFile) {
|
|
3106
|
+
if (!isComponentDeclarationFile(sourceFile.file))
|
|
3107
|
+
return [];
|
|
3108
|
+
const isPage = isPageRouteFile(sourceFile.file);
|
|
3109
|
+
const declarations = getComponentFileDeclarations(sourceFile.sourceFile);
|
|
3110
|
+
const compoundComponentNames = getCompoundComponentNames(sourceFile.sourceFile);
|
|
3111
|
+
const componentNames = declarations.filter((declaration) => declaration.exported && isComponentValueKind(declaration.kind)).filter((declaration) => isPascalCaseName(declaration.name)).map((declaration) => declaration.name);
|
|
3112
|
+
const allowedComponentNames = new Set([...componentNames, ...compoundComponentNames]);
|
|
3113
|
+
const allowedPropsInterfaces = new Set([...allowedComponentNames].map((name) => `${name}Props`));
|
|
3114
|
+
const warnings = [];
|
|
3115
|
+
for (const declaration of declarations) {
|
|
3116
|
+
if (declaration.isDefaultExport)
|
|
3117
|
+
continue;
|
|
3118
|
+
if (declaration.kind === "interface" && allowedPropsInterfaces.has(declaration.name))
|
|
3119
|
+
continue;
|
|
3120
|
+
if (declaration.exported) {
|
|
3121
|
+
if (isAllowedComponentExport(declaration, isPage))
|
|
3122
|
+
continue;
|
|
3123
|
+
warnings.push(fileWarning("akan.file.component-export", "file", sourceFile.file, `Component file exports ${declaration.kind} "${declaration.name}", which is not a PascalCase component${isPage ? " or reserved route export" : ""}.`, declaration.line));
|
|
3124
|
+
continue;
|
|
3125
|
+
}
|
|
3126
|
+
if (isComponentValueKind(declaration.kind) && compoundComponentNames.has(declaration.name))
|
|
3127
|
+
continue;
|
|
3128
|
+
if (isRestrictedInternalKind(declaration.kind))
|
|
3129
|
+
warnings.push(fileWarning("akan.file.component-internal-declaration", "file", sourceFile.file, `Component file declares non-exported ${declaration.kind} "${declaration.name}". Only "interface <Component>Props" may stay internal.`, declaration.line));
|
|
3130
|
+
}
|
|
3131
|
+
return warnings;
|
|
3132
|
+
}
|
|
3133
|
+
#scanConventionQuality(sourceFile) {
|
|
3134
|
+
const suffix = CONVENTION_SUFFIXES.find((candidate) => sourceFile.file.endsWith(candidate));
|
|
3135
|
+
if (!suffix)
|
|
3136
|
+
return [];
|
|
3137
|
+
const modelName = toPascalCase(path9.basename(sourceFile.file, suffix));
|
|
3138
|
+
return getTopLevelDeclarations(sourceFile).filter((declaration) => !isAllowedConventionDeclaration(suffix, modelName, declaration)).map((declaration) => fileWarning(`akan.convention${suffix.replace(".ts", "")}`, "convention", sourceFile.file, `${path9.basename(sourceFile.file)} should not declare top-level ${declaration.kind} "${declaration.name}". Allowed declarations: ${getConventionDescription(suffix, modelName)}.`, declaration.line));
|
|
3139
|
+
}
|
|
3140
|
+
#scanAbstractQuality({ file, content }) {
|
|
3141
|
+
const lineCount = AbstractDoc.lineCountOf(content);
|
|
3142
|
+
if (lineCount <= AbstractDoc.maxLines)
|
|
3143
|
+
return [];
|
|
3144
|
+
return [
|
|
3145
|
+
fileWarning("akan.file.abstract-max-lines", "file", file, `Abstract has ${lineCount} lines. Keep abstracts under ${AbstractDoc.maxLines} lines and compact them periodically.`)
|
|
3146
|
+
];
|
|
3147
|
+
}
|
|
3148
|
+
#scanLayoutQuality(sourceFile) {
|
|
3149
|
+
const warnings = [];
|
|
3150
|
+
const rootEntry = getSysRootEntry(sourceFile.file);
|
|
3151
|
+
if (rootEntry) {
|
|
3152
|
+
const { type, name, isDir } = rootEntry;
|
|
3153
|
+
const allowed = isDir ? rootAllowedDirs[type].has(name) : rootAllowedFiles[type].has(name);
|
|
3154
|
+
const kind = isDir ? "folder" : "file";
|
|
3155
|
+
if (!allowed)
|
|
3156
|
+
warnings.push(fileWarning(`akan.layout.${type}-root-${kind}`, "layout", sourceFile.file, `Unexpected ${type} root ${kind} "${name}". ${rootEntryHintOf(type, name) ?? `Keep ${type} code in conventional ${type} folders.`}`));
|
|
3157
|
+
}
|
|
3158
|
+
const facetShadow = rootEntry?.isDir ? facetIndexShadowOf(sourceFile.file.split("/").slice(2).join("/")) : null;
|
|
3159
|
+
if (facetShadow)
|
|
3160
|
+
warnings.push(fileWarning("akan.layout.facet-index-shadow", "layout", sourceFile.file, `${path9.basename(sourceFile.file)} ${facetShadow}.`));
|
|
3161
|
+
const libFacetFile = getLibFacetRootFile(sourceFile.file);
|
|
3162
|
+
if (libFacetFile && !isAllowedLibFacetRootFile(libFacetFile))
|
|
3163
|
+
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."}`));
|
|
3164
|
+
const moduleUiWarning = getModuleUiWarning(sourceFile.file);
|
|
3165
|
+
if (moduleUiWarning)
|
|
3166
|
+
warnings.push(moduleUiWarning);
|
|
3167
|
+
return warnings;
|
|
3168
|
+
}
|
|
3169
|
+
}
|
|
3170
|
+
function formatQualityScanResult(result) {
|
|
3171
|
+
const sections = [
|
|
3172
|
+
"Akan Code Quality Scan",
|
|
3173
|
+
`workspace: ${result.workspaceRoot}`,
|
|
3174
|
+
`scanned files: ${result.scannedFiles}`,
|
|
3175
|
+
`warnings: ${result.warnings.length}`,
|
|
3176
|
+
"",
|
|
3177
|
+
"Warnings:",
|
|
3178
|
+
"",
|
|
3179
|
+
...formatQualityWarnings(result.warnings),
|
|
3180
|
+
"",
|
|
3181
|
+
"SSR balance (component files, JSX elements rendered per side):",
|
|
3182
|
+
"",
|
|
3183
|
+
...formatSsrBalance(result.ssrBalance),
|
|
3184
|
+
"",
|
|
3185
|
+
"Suggested quality rules:",
|
|
3186
|
+
"",
|
|
3187
|
+
...result.suggestedRules.map((rule) => ` - ${rule}`)
|
|
3188
|
+
];
|
|
3189
|
+
return sections.join(`
|
|
3190
|
+
`);
|
|
3191
|
+
}
|
|
3192
|
+
function formatSsrScanResult(result) {
|
|
3193
|
+
const sections = [
|
|
3194
|
+
"Akan SSR Balance Scan",
|
|
3195
|
+
`workspace: ${result.workspaceRoot}`,
|
|
3196
|
+
`scanned files: ${result.scannedFiles}`,
|
|
3197
|
+
`ssr warnings: ${result.warnings.length}`,
|
|
3198
|
+
"",
|
|
3199
|
+
"Server render share (component files, JSX elements rendered per side):",
|
|
3200
|
+
"",
|
|
3201
|
+
...formatSsrBalance(result.ssrBalance),
|
|
3202
|
+
"",
|
|
3203
|
+
"Warnings:",
|
|
3204
|
+
"",
|
|
3205
|
+
...formatQualityWarnings(result.warnings)
|
|
3206
|
+
];
|
|
3207
|
+
return sections.join(`
|
|
3208
|
+
`);
|
|
3209
|
+
}
|
|
3210
|
+
function formatQualityWarnings(warnings) {
|
|
3211
|
+
if (warnings.length === 0)
|
|
3212
|
+
return ["No warnings found."];
|
|
3213
|
+
return warnings.flatMap((warning) => {
|
|
3214
|
+
const location = formatQualityLocation(warning.file, warning.line);
|
|
3215
|
+
const lines = [`${location} - warning ${warning.rule}: ${warning.message}`];
|
|
3216
|
+
if (warning.locations?.length) {
|
|
3217
|
+
lines.push(...warning.locations.map(({ file, line }) => ` note: related location ${formatQualityLocation(file, line)}`));
|
|
3218
|
+
}
|
|
3219
|
+
if (warning.fix)
|
|
3220
|
+
lines.push(` fix: ${warning.fix}`);
|
|
3221
|
+
return lines;
|
|
3222
|
+
});
|
|
3223
|
+
}
|
|
3224
|
+
function formatQualityLocation(file, line) {
|
|
3225
|
+
return `${file ?? "<global>"}:${line ?? 1}:1`;
|
|
3226
|
+
}
|
|
3227
|
+
function getExportedFunctionLikes(sourceFile) {
|
|
3228
|
+
const declarations = [];
|
|
3229
|
+
const nameExempt = isPageRouteFile(sourceFile.file) || isUiComponentFile(sourceFile.file);
|
|
3230
|
+
const add = (name, kind, node, body, isEnumClass = false) => declarations.push({
|
|
3231
|
+
name,
|
|
3232
|
+
kind,
|
|
3233
|
+
file: sourceFile.file,
|
|
3234
|
+
line: getLine(sourceFile.sourceFile, node),
|
|
3235
|
+
bodyFingerprint: getBodyFingerprint(sourceFile.sourceFile, body),
|
|
3236
|
+
duplicateNameExempt: nameExempt || isConventionDuplicateNameExempt(sourceFile.file, isEnumClass)
|
|
3237
|
+
});
|
|
3238
|
+
for (const statement of sourceFile.sourceFile.statements) {
|
|
3239
|
+
if (ts19.isFunctionDeclaration(statement) && statement.name && isExported(statement))
|
|
3240
|
+
add(statement.name.text, "function", statement, statement.body);
|
|
3241
|
+
if (ts19.isClassDeclaration(statement) && statement.name && isExported(statement))
|
|
3242
|
+
add(statement.name.text, "class", statement, statement, isEnumClassStatement(sourceFile.sourceFile, statement));
|
|
3243
|
+
if (ts19.isVariableStatement(statement) && isExported(statement)) {
|
|
3244
|
+
for (const declaration of statement.declarationList.declarations) {
|
|
3245
|
+
if (!ts19.isIdentifier(declaration.name) || !isFunctionLikeInitializer(declaration.initializer))
|
|
3246
|
+
continue;
|
|
3247
|
+
add(declaration.name.text, "function-variable", declaration, declaration.initializer);
|
|
3248
|
+
}
|
|
3249
|
+
}
|
|
3250
|
+
}
|
|
3251
|
+
return declarations;
|
|
3252
|
+
}
|
|
3253
|
+
function sysSegments(file) {
|
|
3254
|
+
const segments = file.split("/");
|
|
3255
|
+
return segments[0] === "apps" || segments[0] === "libs" ? segments : null;
|
|
3256
|
+
}
|
|
3257
|
+
function isPageRouteFile(file) {
|
|
3258
|
+
return sysSegments(file)?.[2] === "page";
|
|
3259
|
+
}
|
|
3260
|
+
function isUiComponentFile(file) {
|
|
3261
|
+
return sysSegments(file)?.[2] === "ui";
|
|
3262
|
+
}
|
|
3263
|
+
function isConventionDuplicateNameExempt(file, isEnumClass) {
|
|
3264
|
+
if (!sysSegments(file)?.includes("lib"))
|
|
3265
|
+
return false;
|
|
3266
|
+
if (file.endsWith(".tsx") || /\.(document|service|signal|store)\.ts$/.test(file))
|
|
3267
|
+
return true;
|
|
3268
|
+
if (file.endsWith(".constant.ts"))
|
|
3269
|
+
return !isEnumClass;
|
|
3270
|
+
return false;
|
|
3271
|
+
}
|
|
3272
|
+
function isEnumClassStatement(sourceFile, statement) {
|
|
3273
|
+
if (!ts19.isClassDeclaration(statement))
|
|
3274
|
+
return false;
|
|
3275
|
+
const heritageClause = statement.heritageClauses?.find((clause) => clause.token === ts19.SyntaxKind.ExtendsKeyword);
|
|
3276
|
+
const expression = heritageClause?.types[0]?.expression;
|
|
3277
|
+
return !!expression && expression.getText(sourceFile).startsWith("enumOf(");
|
|
3278
|
+
}
|
|
3279
|
+
function getExportedClassNames(sourceFile) {
|
|
3280
|
+
return sourceFile.statements.filter((statement) => ts19.isClassDeclaration(statement)).filter((statement) => isExported(statement)).map((statement) => statement.name?.text).filter((name) => !!name);
|
|
3281
|
+
}
|
|
3282
|
+
function isComponentDeclarationFile(file) {
|
|
3283
|
+
if (!file.endsWith(".tsx"))
|
|
3284
|
+
return false;
|
|
3285
|
+
const segments = file.split("/");
|
|
3286
|
+
const [root, , area] = segments;
|
|
3287
|
+
if (root !== "apps" && root !== "libs")
|
|
3288
|
+
return false;
|
|
3289
|
+
if (area === "lib" || area === "ui")
|
|
3290
|
+
return true;
|
|
3291
|
+
return root === "apps" && area === "page";
|
|
3292
|
+
}
|
|
3293
|
+
function getComponentFileDeclarations(sourceFile) {
|
|
3294
|
+
const reExportedNames = new Set;
|
|
3295
|
+
for (const statement of sourceFile.statements) {
|
|
3296
|
+
if (ts19.isExportDeclaration(statement) && statement.exportClause && ts19.isNamedExports(statement.exportClause)) {
|
|
3297
|
+
for (const element of statement.exportClause.elements)
|
|
3298
|
+
reExportedNames.add((element.propertyName ?? element.name).text);
|
|
3299
|
+
}
|
|
3300
|
+
}
|
|
3301
|
+
const declarations = [];
|
|
3302
|
+
for (const statement of sourceFile.statements) {
|
|
3303
|
+
const isDefaultExport = isDefaultExportStatement(statement);
|
|
3304
|
+
const inlineExported = isExported(statement);
|
|
3305
|
+
const add = (name, kind, line) => declarations.push({ name, kind, line, exported: inlineExported || reExportedNames.has(name), isDefaultExport });
|
|
3306
|
+
if (ts19.isInterfaceDeclaration(statement))
|
|
3307
|
+
add(statement.name.text, "interface", getLine(sourceFile, statement));
|
|
3308
|
+
else if (ts19.isTypeAliasDeclaration(statement))
|
|
3309
|
+
add(statement.name.text, "type", getLine(sourceFile, statement));
|
|
3310
|
+
else if (ts19.isEnumDeclaration(statement))
|
|
3311
|
+
add(statement.name.text, "enum", getLine(sourceFile, statement));
|
|
3312
|
+
else if (ts19.isFunctionDeclaration(statement) && statement.name)
|
|
3313
|
+
add(statement.name.text, "function", getLine(sourceFile, statement));
|
|
3314
|
+
else if (ts19.isClassDeclaration(statement) && statement.name)
|
|
3315
|
+
add(statement.name.text, "class", getLine(sourceFile, statement));
|
|
3316
|
+
else if (ts19.isVariableStatement(statement)) {
|
|
3317
|
+
for (const declaration of statement.declarationList.declarations) {
|
|
3318
|
+
if (!ts19.isIdentifier(declaration.name))
|
|
3319
|
+
continue;
|
|
3320
|
+
const kind = isFunctionLikeInitializer(declaration.initializer) ? "function" : "variable";
|
|
3321
|
+
add(declaration.name.text, kind, getLine(sourceFile, declaration));
|
|
3322
|
+
}
|
|
3323
|
+
}
|
|
3324
|
+
}
|
|
3325
|
+
return declarations;
|
|
3326
|
+
}
|
|
3327
|
+
function getCompoundComponentNames(sourceFile) {
|
|
3328
|
+
const names = new Set;
|
|
3329
|
+
for (const statement of sourceFile.statements) {
|
|
3330
|
+
if (!ts19.isExpressionStatement(statement))
|
|
3331
|
+
continue;
|
|
3332
|
+
const { expression } = statement;
|
|
3333
|
+
if (!ts19.isBinaryExpression(expression) || expression.operatorToken.kind !== ts19.SyntaxKind.EqualsToken)
|
|
3334
|
+
continue;
|
|
3335
|
+
if (!ts19.isPropertyAccessExpression(expression.left) || !isPascalCaseName(expression.left.name.text))
|
|
3336
|
+
continue;
|
|
3337
|
+
names.add(expression.left.name.text);
|
|
3338
|
+
if (ts19.isIdentifier(expression.right) && isPascalCaseName(expression.right.text))
|
|
3339
|
+
names.add(expression.right.text);
|
|
3340
|
+
}
|
|
3341
|
+
return names;
|
|
3342
|
+
}
|
|
3343
|
+
function isComponentValueKind(kind) {
|
|
3344
|
+
return kind === "variable" || kind === "function" || kind === "class";
|
|
3345
|
+
}
|
|
3346
|
+
function isRestrictedInternalKind(kind) {
|
|
3347
|
+
return kind === "interface" || kind === "type" || kind === "function";
|
|
3348
|
+
}
|
|
3349
|
+
function isAllowedComponentExport(declaration, isPage) {
|
|
3350
|
+
if (isComponentValueKind(declaration.kind) && isPascalCaseName(declaration.name))
|
|
3351
|
+
return true;
|
|
3352
|
+
return isPage && RESERVED_ROUTE_CONFIG_EXPORTS.has(declaration.name);
|
|
3353
|
+
}
|
|
3354
|
+
function isPascalCaseName(name) {
|
|
3355
|
+
return /^[A-Z]/.test(name) && !/^[A-Z0-9_]+$/.test(name);
|
|
3356
|
+
}
|
|
3357
|
+
function isDefaultExportStatement(statement) {
|
|
3358
|
+
if (ts19.isExportAssignment(statement))
|
|
3359
|
+
return !statement.isExportEquals;
|
|
3360
|
+
if (!ts19.canHaveModifiers(statement))
|
|
3361
|
+
return false;
|
|
3362
|
+
return !!ts19.getModifiers(statement)?.some((modifier) => modifier.kind === ts19.SyntaxKind.DefaultKeyword);
|
|
3363
|
+
}
|
|
3364
|
+
function getBangCommentWarnings(sourceFile) {
|
|
3365
|
+
if (!isClientReachableFile(sourceFile.file))
|
|
3366
|
+
return [];
|
|
3367
|
+
return findPatternLines(sourceFile.content, /(?:^|[^\s/][ \t]+)\/[*/]!/).map((line) => fileWarning("akan.file.bang-comment-in-client", "file", sourceFile.file, "A `//!` or `/*!` marker survives minification and ships to the browser.", line));
|
|
3368
|
+
}
|
|
3369
|
+
function isClientReachableFile(file) {
|
|
3370
|
+
if (/\.(test|spec)\.tsx?$/.test(file))
|
|
3371
|
+
return false;
|
|
3372
|
+
if (/\.(constant|store)\.ts$/.test(file))
|
|
3373
|
+
return true;
|
|
3374
|
+
if (/\.(Template|Unit|Util|View|Zone)\.tsx$/.test(file))
|
|
3375
|
+
return true;
|
|
3376
|
+
const segments = file.split("/");
|
|
3377
|
+
if (segments.includes("ui") || segments.includes("webkit"))
|
|
3378
|
+
return /\.tsx?$/.test(file);
|
|
3379
|
+
if (segments.includes("common"))
|
|
3380
|
+
return file.endsWith(".ts");
|
|
3381
|
+
return segments.includes("page") && file.endsWith(".tsx");
|
|
3382
|
+
}
|
|
3383
|
+
function getPlaceholderExportWarnings(sourceFile) {
|
|
3384
|
+
if (!sourceFile.file.endsWith("/index.ts") && !sourceFile.file.endsWith("/index.tsx"))
|
|
3385
|
+
return [];
|
|
3386
|
+
return getTopLevelDeclarations(sourceFile).filter((declaration) => declaration.exported && PLACEHOLDER_EXPORT_NAMES.has(declaration.name)).map((declaration) => fileWarning("akan.file.placeholder-export", "file", sourceFile.file, `Generated or barrel index file should not export placeholder "${declaration.name}".`, declaration.line));
|
|
3387
|
+
}
|
|
3388
|
+
function getDictionaryTextWarnings(sourceFile) {
|
|
3389
|
+
if (!sourceFile.file.endsWith(".dictionary.ts"))
|
|
3390
|
+
return [];
|
|
3391
|
+
const stalePatterns = [{ pattern: /\b[A-Z][A-Za-z0-9]* description\b/, label: "scaffold description text" }];
|
|
3392
|
+
return stalePatterns.flatMap(({ pattern, label }) => findPatternLines(sourceFile.content, pattern).map((line) => fileWarning("akan.file.dictionary-stale-text", "file", sourceFile.file, `Dictionary text appears to contain ${label}.`, line)));
|
|
3393
|
+
}
|
|
3394
|
+
function getGlobalMutationWarnings(sourceFile) {
|
|
3395
|
+
const warnings = [];
|
|
3396
|
+
for (const statement of sourceFile.sourceFile.statements) {
|
|
3397
|
+
const warn = (rule, message) => warnings.push(fileWarning(rule, "file", sourceFile.file, message, getLine(sourceFile.sourceFile, statement)));
|
|
3398
|
+
if (ts19.isModuleDeclaration(statement) && statement.name.getText(sourceFile.sourceFile) === "global")
|
|
3399
|
+
warn("akan.file.global-declaration", "Global declarations require an explicit low-level integration allowlist.");
|
|
3400
|
+
if (ts19.isInterfaceDeclaration(statement) && statement.name.text === "Window")
|
|
3401
|
+
warn("akan.file.window-augmentation", "Window augmentation should be isolated to approved browser integration files.");
|
|
3402
|
+
if (ts19.isExpressionStatement(statement) && statement.expression.getText(sourceFile.sourceFile).includes(".prototype."))
|
|
3403
|
+
warn("akan.file.prototype-mutation", "Prototype mutation should be avoided or isolated to approved low-level integration files.");
|
|
3404
|
+
}
|
|
3405
|
+
return warnings;
|
|
3406
|
+
}
|
|
3407
|
+
function getTopLevelDeclarations(sourceFile) {
|
|
3408
|
+
return sourceFile.sourceFile.statements.flatMap((statement) => getTopLevelDeclaration(sourceFile.sourceFile, statement));
|
|
3409
|
+
}
|
|
3410
|
+
function getTopLevelDeclaration(sourceFile, statement) {
|
|
3411
|
+
const line = getLine(sourceFile, statement);
|
|
3412
|
+
const declared = (name, kind, at = line) => ({
|
|
3413
|
+
name,
|
|
3414
|
+
kind,
|
|
3415
|
+
line: at,
|
|
3416
|
+
exported: isExported(statement),
|
|
3417
|
+
node: statement
|
|
3418
|
+
});
|
|
3419
|
+
if (ts19.isClassDeclaration(statement) && statement.name)
|
|
3420
|
+
return [declared(statement.name.text, "class")];
|
|
3421
|
+
if (ts19.isFunctionDeclaration(statement) && statement.name)
|
|
3422
|
+
return [declared(statement.name.text, "function")];
|
|
3423
|
+
if (ts19.isInterfaceDeclaration(statement))
|
|
3424
|
+
return [declared(statement.name.text, "interface")];
|
|
3425
|
+
if (ts19.isTypeAliasDeclaration(statement))
|
|
3426
|
+
return [declared(statement.name.text, "type")];
|
|
3427
|
+
if (ts19.isEnumDeclaration(statement))
|
|
3428
|
+
return [declared(statement.name.text, "enum")];
|
|
3429
|
+
if (ts19.isVariableStatement(statement))
|
|
3430
|
+
return statement.declarationList.declarations.filter((declaration) => ts19.isIdentifier(declaration.name)).map((declaration) => declared(declaration.name.text, "variable", getLine(sourceFile, declaration)));
|
|
3431
|
+
if (ts19.isExportDeclaration(statement))
|
|
3432
|
+
return [{ name: "export declaration", kind: "export", line, exported: true, node: statement }];
|
|
3433
|
+
return [];
|
|
3434
|
+
}
|
|
3435
|
+
function getConventionClassNames(suffix, model) {
|
|
3436
|
+
if (suffix === ".constant.ts")
|
|
3437
|
+
return [`${model}Input`, `${model}Object`, model, `Light${model}`, `${model}Insight`];
|
|
3438
|
+
if (suffix === ".document.ts")
|
|
3439
|
+
return [`${model}Filter`, model, `${model}Model`];
|
|
3440
|
+
if (suffix === ".service.ts")
|
|
3441
|
+
return [`${model}Service`];
|
|
3442
|
+
if (suffix === ".signal.ts")
|
|
3443
|
+
return [`${model}Internal`, `${model}Slice`, `${model}Endpoint`];
|
|
3444
|
+
if (suffix === ".store.ts")
|
|
3445
|
+
return [`${model}Store`];
|
|
3446
|
+
return [];
|
|
3447
|
+
}
|
|
3448
|
+
function isAllowedConventionDeclaration(suffix, modelName, declaration) {
|
|
3449
|
+
if (suffix === ".dictionary.ts")
|
|
3450
|
+
return isExportedConst(declaration) && declaration.name === "dictionary";
|
|
3451
|
+
if (declaration.kind !== "class")
|
|
3452
|
+
return false;
|
|
3453
|
+
if (getConventionClassNames(suffix, modelName).includes(declaration.name))
|
|
3454
|
+
return true;
|
|
3455
|
+
return suffix === ".constant.ts" && isEnumClassStatement(declaration.node.getSourceFile(), declaration.node);
|
|
3456
|
+
}
|
|
3457
|
+
function getConventionDescription(suffix, modelName) {
|
|
3458
|
+
if (suffix === ".dictionary.ts")
|
|
3459
|
+
return "export const dictionary";
|
|
3460
|
+
const names = [
|
|
3461
|
+
...getConventionClassNames(suffix, modelName),
|
|
3462
|
+
...suffix === ".constant.ts" ? ["enumOf classes"] : []
|
|
3463
|
+
];
|
|
3464
|
+
return names.length > 1 ? `${names.slice(0, -1).join(", ")}, or ${names.at(-1)}` : names[0];
|
|
3465
|
+
}
|
|
3466
|
+
var sysRootTypes = { apps: "app", libs: "lib" };
|
|
3467
|
+
function getSysRootEntry(file) {
|
|
3468
|
+
const segments = file.split("/");
|
|
3469
|
+
const root = segments[0];
|
|
3470
|
+
const name = segments[2];
|
|
3471
|
+
if (!root || !name || segments.length < 3)
|
|
3472
|
+
return null;
|
|
3473
|
+
const type = sysRootTypes[root];
|
|
3474
|
+
if (!type)
|
|
3475
|
+
return null;
|
|
3476
|
+
return { type, name, isDir: segments.length > 3 };
|
|
3477
|
+
}
|
|
3478
|
+
function getLibFacetRootFile(file) {
|
|
3479
|
+
const segments = file.split("/");
|
|
3480
|
+
if ((segments[0] === "libs" || segments[0] === "apps") && segments.length === 4 && segments[2] === "lib")
|
|
3481
|
+
return segments[3];
|
|
3482
|
+
return null;
|
|
3483
|
+
}
|
|
3484
|
+
function getModuleUiWarning(file) {
|
|
3485
|
+
if (!file.endsWith(".tsx"))
|
|
3486
|
+
return null;
|
|
3487
|
+
const moduleInfo = getModuleInfo(file);
|
|
3488
|
+
if (!moduleInfo)
|
|
3489
|
+
return null;
|
|
3490
|
+
const { moduleName, fileName, kind } = moduleInfo;
|
|
3491
|
+
const pascalName = toPascalCase(moduleName.replace(/^_+/, ""));
|
|
3492
|
+
const allowedSuffixes = kind === "database" ? ["Template", "Unit", "Util", "View", "Zone"] : kind === "service" ? ["Util", "Zone"] : ["Template", "Unit"];
|
|
3493
|
+
const allowedFileNames = new Set(allowedSuffixes.map((suffix) => `${pascalName}.${suffix}.tsx`));
|
|
3494
|
+
if (allowedFileNames.has(fileName) || fileName.endsWith(".test.tsx") || fileName.endsWith(".spec.tsx"))
|
|
3495
|
+
return null;
|
|
3496
|
+
return fileWarning("akan.layout.module-ui-file", "layout", file, `Unexpected ${kind} module UI filename "${fileName}". Expected one of: ${[...allowedFileNames].join(", ")}.`);
|
|
3497
|
+
}
|
|
3498
|
+
function getModuleInfo(file) {
|
|
3499
|
+
const segments = file.split("/");
|
|
3500
|
+
const libIndex = segments.indexOf("lib");
|
|
3501
|
+
if (libIndex < 0)
|
|
3502
|
+
return null;
|
|
3503
|
+
const moduleName = segments[libIndex + 1];
|
|
3504
|
+
if (moduleName === "__scalar") {
|
|
3505
|
+
if (segments.length !== libIndex + 4)
|
|
3506
|
+
return null;
|
|
3507
|
+
return { moduleName: segments[libIndex + 2], fileName: segments[libIndex + 3], kind: "scalar" };
|
|
3508
|
+
}
|
|
3509
|
+
if (segments.length !== libIndex + 3)
|
|
3510
|
+
return null;
|
|
3511
|
+
const fileName = segments[libIndex + 2];
|
|
3512
|
+
if (moduleName.startsWith("__"))
|
|
3513
|
+
return { moduleName, fileName, kind: "scalar" };
|
|
3514
|
+
if (moduleName.startsWith("_"))
|
|
3515
|
+
return { moduleName, fileName, kind: "service" };
|
|
3516
|
+
return { moduleName, fileName, kind: "database" };
|
|
3517
|
+
}
|
|
3518
|
+
function isExportedConst(declaration) {
|
|
3519
|
+
return declaration.exported && ts19.isVariableStatement(declaration.node) && (declaration.node.declarationList.flags & ts19.NodeFlags.Const) !== 0;
|
|
3520
|
+
}
|
|
3521
|
+
function isExported(node) {
|
|
3522
|
+
return !!(ts19.getCombinedModifierFlags(node) & ts19.ModifierFlags.Export);
|
|
3523
|
+
}
|
|
3524
|
+
function isFunctionLikeInitializer(node) {
|
|
3525
|
+
return !!node && (ts19.isArrowFunction(node) || ts19.isFunctionExpression(node));
|
|
3526
|
+
}
|
|
3527
|
+
function getBodyFingerprint(sourceFile, node) {
|
|
3528
|
+
if (!node)
|
|
3529
|
+
return;
|
|
3530
|
+
const normalizedBody = node.getText(sourceFile).replace(/\s+/g, " ").trim();
|
|
3531
|
+
if (normalizedBody.length < 80)
|
|
3532
|
+
return;
|
|
3533
|
+
return createHash("sha256").update(normalizedBody).digest("hex");
|
|
3534
|
+
}
|
|
3535
|
+
function shouldSkipPath(relativePath, isDirectory, ignoreFilter) {
|
|
3536
|
+
const ignorePath = isDirectory ? `${relativePath}/` : relativePath;
|
|
3537
|
+
return relativePath === ".git" || relativePath.includes("/.git/") || relativePath.includes("/node_modules/") || ignoreFilter.ignores(relativePath) || ignoreFilter.ignores(ignorePath);
|
|
3538
|
+
}
|
|
3539
|
+
async function isDirectory(absolutePath) {
|
|
3540
|
+
try {
|
|
3541
|
+
return (await stat(absolutePath)).isDirectory();
|
|
3542
|
+
} catch {
|
|
3543
|
+
return false;
|
|
3544
|
+
}
|
|
3545
|
+
}
|
|
3546
|
+
function getScriptKind(file) {
|
|
3547
|
+
return file.endsWith(".tsx") ? ts19.ScriptKind.TSX : ts19.ScriptKind.TS;
|
|
3548
|
+
}
|
|
3549
|
+
function getLine(sourceFile, node) {
|
|
3550
|
+
return sourceFile.getLineAndCharacterOfPosition(node.getStart(sourceFile)).line + 1;
|
|
3551
|
+
}
|
|
3552
|
+
function getRecommendedLineLimit(file) {
|
|
3553
|
+
if (file.endsWith(".service.ts"))
|
|
3554
|
+
return 500;
|
|
3555
|
+
if (file.endsWith(".Template.tsx") || file.endsWith(".Zone.tsx"))
|
|
3556
|
+
return 800;
|
|
3557
|
+
if (file.endsWith(".Util.tsx"))
|
|
3558
|
+
return 1000;
|
|
3559
|
+
return null;
|
|
3560
|
+
}
|
|
3561
|
+
function findPatternLines(content, pattern) {
|
|
3562
|
+
return content.split(/\r?\n/).flatMap((line, index) => pattern.test(line) ? [index + 1] : []);
|
|
3563
|
+
}
|
|
3564
|
+
function toPascalCase(value) {
|
|
3565
|
+
return value.replace(/(^|[-_./])([a-zA-Z0-9])/g, (_, __, char) => char.toUpperCase()).replace(/[-_./]/g, "");
|
|
3566
|
+
}
|
|
3567
|
+
function toPosix(value) {
|
|
3568
|
+
return value.split(path9.sep).join("/");
|
|
3569
|
+
}
|
|
3570
|
+
function groupBy(items, getKey) {
|
|
3571
|
+
const grouped = new Map;
|
|
3572
|
+
for (const item of items) {
|
|
3573
|
+
const key = getKey(item);
|
|
3574
|
+
grouped.set(key, [...grouped.get(key) ?? [], item]);
|
|
3575
|
+
}
|
|
3576
|
+
return grouped;
|
|
3577
|
+
}
|
|
3578
|
+
function compareWarnings(a, b) {
|
|
3579
|
+
return a.scope.localeCompare(b.scope) || (a.file ?? "").localeCompare(b.file ?? "") || (a.line ?? 0) - (b.line ?? 0) || a.rule.localeCompare(b.rule);
|
|
3580
|
+
}
|
|
3581
|
+
|
|
3582
|
+
export { MaintainabilityBaseline, defaultMaxDiagnostics, WorkspaceRunner, AkanQualityScanner, formatQualityScanResult, formatSsrScanResult };
|