@akanjs/cli 3.1.1-rc.16 → 3.1.1-rc.18
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
|
@@ -1,1788 +0,0 @@
|
|
|
1
|
-
// @bun
|
|
2
|
-
import {
|
|
3
|
-
Workspace,
|
|
4
|
-
script,
|
|
5
|
-
command
|
|
6
|
-
} from "./index-00ke4phc.js";
|
|
7
|
-
import"./index-52w0fvh8.js";
|
|
8
|
-
import {
|
|
9
|
-
rootAllowedFiles,
|
|
10
|
-
rootAllowedDirs,
|
|
11
|
-
isAllowedLibFacetRootFile,
|
|
12
|
-
libFacetRootHintOf,
|
|
13
|
-
facetIndexShadowOf,
|
|
14
|
-
rootEntryHintOf,
|
|
15
|
-
AppExecutor,
|
|
16
|
-
LibExecutor
|
|
17
|
-
} from "./index-921cxqrd.js";
|
|
18
|
-
import {
|
|
19
|
-
MaintainabilityBaseline,
|
|
20
|
-
AbstractDoc,
|
|
21
|
-
SignalMutationIndex,
|
|
22
|
-
WorkspaceRunner
|
|
23
|
-
} from "./index-hvg3esm0.js";
|
|
24
|
-
import"./index-62md4dwy.js";
|
|
25
|
-
import"./index-hj6w4ka1.js";
|
|
26
|
-
import"./index-vgt25eh1.js";
|
|
27
|
-
|
|
28
|
-
// pkgs/@akanjs/devkit/qualityScanner.ts
|
|
29
|
-
import { createHash } from "crypto";
|
|
30
|
-
import { readdir as readdir2, readFile as readFile2, stat } from "fs/promises";
|
|
31
|
-
import path4 from "path";
|
|
32
|
-
import { RESERVED_ROUTE_CONFIG_EXPORTS } from "akanjs/common";
|
|
33
|
-
import ignore from "ignore";
|
|
34
|
-
import ts8 from "typescript";
|
|
35
|
-
|
|
36
|
-
// pkgs/@akanjs/devkit/commentDensityScanner.ts
|
|
37
|
-
import path from "path";
|
|
38
|
-
import ts2 from "typescript";
|
|
39
|
-
|
|
40
|
-
// pkgs/@akanjs/devkit/sourceComments.ts
|
|
41
|
-
import ts from "typescript";
|
|
42
|
-
|
|
43
|
-
class SourceComments {
|
|
44
|
-
static #scanner = ts.createScanner(ts.ScriptTarget.Latest, false);
|
|
45
|
-
static of(sourceFile) {
|
|
46
|
-
const comments = [];
|
|
47
|
-
const scanGap = (start, end) => {
|
|
48
|
-
if (end <= start)
|
|
49
|
-
return;
|
|
50
|
-
const scanner = SourceComments.#scanner;
|
|
51
|
-
scanner.setText(sourceFile.text, start, end - start);
|
|
52
|
-
for (let kind = scanner.scan();kind !== ts.SyntaxKind.EndOfFileToken; kind = scanner.scan()) {
|
|
53
|
-
if (kind !== ts.SyntaxKind.SingleLineCommentTrivia && kind !== ts.SyntaxKind.MultiLineCommentTrivia)
|
|
54
|
-
continue;
|
|
55
|
-
comments.push(SourceComments.#commentOf(sourceFile, scanner.getTokenStart(), scanner.getTokenText()));
|
|
56
|
-
}
|
|
57
|
-
scanner.setText(undefined);
|
|
58
|
-
};
|
|
59
|
-
const visit = (node) => {
|
|
60
|
-
if (node.kind === ts.SyntaxKind.JsxText)
|
|
61
|
-
return;
|
|
62
|
-
if (ts.isToken(node)) {
|
|
63
|
-
scanGap(node.pos, node.getStart(sourceFile));
|
|
64
|
-
return;
|
|
65
|
-
}
|
|
66
|
-
const children = [];
|
|
67
|
-
ts.forEachChild(node, (child) => {
|
|
68
|
-
children.push(child);
|
|
69
|
-
}, (nodes) => {
|
|
70
|
-
children.push(...nodes);
|
|
71
|
-
});
|
|
72
|
-
let cursor = node.pos;
|
|
73
|
-
for (const child of children) {
|
|
74
|
-
scanGap(cursor, child.pos);
|
|
75
|
-
visit(child);
|
|
76
|
-
cursor = Math.max(cursor, child.end);
|
|
77
|
-
}
|
|
78
|
-
scanGap(cursor, node.end);
|
|
79
|
-
};
|
|
80
|
-
visit(sourceFile);
|
|
81
|
-
return comments;
|
|
82
|
-
}
|
|
83
|
-
static #commentOf(sourceFile, pos, raw) {
|
|
84
|
-
return {
|
|
85
|
-
raw,
|
|
86
|
-
line: sourceFile.getLineAndCharacterOfPosition(pos).line + 1,
|
|
87
|
-
isJsDoc: raw.startsWith("/**") && !raw.startsWith("/**/"),
|
|
88
|
-
body: SourceComments.#bodyOf(raw)
|
|
89
|
-
};
|
|
90
|
-
}
|
|
91
|
-
static #bodyOf(raw) {
|
|
92
|
-
if (raw.startsWith("//"))
|
|
93
|
-
return [raw.replace(/^\/\/+/, "").trim()];
|
|
94
|
-
return raw.slice(2, raw.endsWith("*/") ? -2 : undefined).split(/\r?\n/).map((line) => line.replace(/^\s*\*+/, "").trim());
|
|
95
|
-
}
|
|
96
|
-
}
|
|
97
|
-
|
|
98
|
-
// pkgs/@akanjs/devkit/commentDensityScanner.ts
|
|
99
|
-
class CommentDensityScanner {
|
|
100
|
-
static rule = "akan.comment.density";
|
|
101
|
-
static maxShare = 0.01;
|
|
102
|
-
static minCommentLineNum = 5;
|
|
103
|
-
static #directive = /^(?:biome-ignore|@ts-(?:expect-error|ignore|nocheck|check)\b|eslint-(?:disable|enable)|<reference\b)/;
|
|
104
|
-
static #scaffoldMarkers = new Set(["state", "action"]);
|
|
105
|
-
scan(sourceFiles) {
|
|
106
|
-
const tallies = new Map;
|
|
107
|
-
for (const sourceFile of sourceFiles) {
|
|
108
|
-
const unit = CommentDensityScanner.#unitOf(sourceFile.file);
|
|
109
|
-
if (!unit || !CommentDensityScanner.#isMeasured(sourceFile))
|
|
110
|
-
continue;
|
|
111
|
-
const tally = tallies.get(unit) ?? { lineNum: 0, commentLineNum: 0, files: [] };
|
|
112
|
-
const commentLines = CommentDensityScanner.#commentLinesOf(sourceFile);
|
|
113
|
-
tally.lineNum += sourceFile.content.split(/\r?\n/).filter((line) => line.trim() !== "").length;
|
|
114
|
-
tally.commentLineNum += commentLines.length;
|
|
115
|
-
if (commentLines[0] !== undefined)
|
|
116
|
-
tally.files.push({ file: sourceFile.file, line: commentLines[0], commentLineNum: commentLines.length });
|
|
117
|
-
tallies.set(unit, tally);
|
|
118
|
-
}
|
|
119
|
-
return [...tallies].filter(([, tally]) => CommentDensityScanner.#isDense(tally)).map(([unit, tally]) => CommentDensityScanner.#warningOf(unit, tally));
|
|
120
|
-
}
|
|
121
|
-
static #commentLinesOf({ file, sourceFile }) {
|
|
122
|
-
const isRecipe = file.includes("/ui/Recipe/");
|
|
123
|
-
const lines = new Set;
|
|
124
|
-
for (const comment of SourceComments.of(sourceFile)) {
|
|
125
|
-
if (CommentDensityScanner.#isExempt(comment))
|
|
126
|
-
continue;
|
|
127
|
-
const contentIdxs = comment.body.flatMap((text, idx) => text ? [idx] : []);
|
|
128
|
-
const countedIdxs = isRecipe && comment.isJsDoc ? contentIdxs.slice(1) : contentIdxs;
|
|
129
|
-
for (const idx of countedIdxs)
|
|
130
|
-
lines.add(comment.line + idx);
|
|
131
|
-
}
|
|
132
|
-
return [...lines].sort((a, b) => a - b);
|
|
133
|
-
}
|
|
134
|
-
static #isExempt({ raw, body }) {
|
|
135
|
-
const head = body.find((text) => text !== "") ?? "";
|
|
136
|
-
if (CommentDensityScanner.#directive.test(head))
|
|
137
|
-
return true;
|
|
138
|
-
return raw.startsWith("//") && CommentDensityScanner.#scaffoldMarkers.has(head.toLowerCase());
|
|
139
|
-
}
|
|
140
|
-
static #isDense({ lineNum, commentLineNum }) {
|
|
141
|
-
return commentLineNum >= CommentDensityScanner.minCommentLineNum && commentLineNum > lineNum * CommentDensityScanner.maxShare;
|
|
142
|
-
}
|
|
143
|
-
static #warningOf(unit, { lineNum, commentLineNum, files }) {
|
|
144
|
-
const [primary] = [...files].sort((a, b) => b.commentLineNum - a.commentLineNum);
|
|
145
|
-
const share = (commentLineNum / lineNum * 100).toFixed(2);
|
|
146
|
-
return {
|
|
147
|
-
rule: CommentDensityScanner.rule,
|
|
148
|
-
scope: "comment",
|
|
149
|
-
severity: "warning",
|
|
150
|
-
file: primary?.file ?? unit,
|
|
151
|
-
line: primary?.line,
|
|
152
|
-
message: `${unit} is ${share}% comments (${commentLineNum} of ${lineNum} non-blank lines); product lib/ and ui/ code stays under ${CommentDensityScanner.maxShare * 100}%.`,
|
|
153
|
-
...files.length > 1 ? { locations: files.map(({ file, line }) => ({ file, line })) } : {}
|
|
154
|
-
};
|
|
155
|
-
}
|
|
156
|
-
static #unitOf(file) {
|
|
157
|
-
const segments = file.split("/");
|
|
158
|
-
if (segments[0] !== "apps" && segments[0] !== "libs" || segments.length < 4)
|
|
159
|
-
return null;
|
|
160
|
-
if (segments[2] === "ui")
|
|
161
|
-
return segments.slice(0, 4).join("/");
|
|
162
|
-
if (segments[2] !== "lib")
|
|
163
|
-
return null;
|
|
164
|
-
const depth = segments[3] === "__scalar" ? 5 : 4;
|
|
165
|
-
return segments.length > depth ? segments.slice(0, depth).join("/") : null;
|
|
166
|
-
}
|
|
167
|
-
static #isMeasured({ file, sourceFile }) {
|
|
168
|
-
if (/\.(test|spec)\.tsx?$/.test(file) || path.basename(file) === "guards.ts")
|
|
169
|
-
return false;
|
|
170
|
-
return !sourceFile.statements.every((statement) => ts2.isExportDeclaration(statement) || ts2.isExpressionStatement(statement) && ts2.isStringLiteral(statement.expression));
|
|
171
|
-
}
|
|
172
|
-
}
|
|
173
|
-
|
|
174
|
-
// pkgs/@akanjs/devkit/deprecatedCommentScanner.ts
|
|
175
|
-
class DeprecatedCommentScanner {
|
|
176
|
-
static rule = "akan.comment.deprecated-marker";
|
|
177
|
-
static #marker = /^[!?*\s]*(?:(?:TODO|FIXME|XXX|NOTE)\b\s*:?\s*)?@?deprecated\b/i;
|
|
178
|
-
scan(sourceFiles) {
|
|
179
|
-
return sourceFiles.filter(({ file }) => /^(apps|libs)\//.test(file) && !/\.(test|spec)\.tsx?$/.test(file)).flatMap(({ file, sourceFile }) => SourceComments.of(sourceFile).filter((comment) => DeprecatedCommentScanner.#isLooseMarker(comment)).map((comment) => ({
|
|
180
|
-
rule: DeprecatedCommentScanner.rule,
|
|
181
|
-
scope: "comment",
|
|
182
|
-
severity: "warning",
|
|
183
|
-
file,
|
|
184
|
-
line: comment.line,
|
|
185
|
-
message: `"${comment.raw.split(/\r?\n/)[0]?.trim().slice(0, 80)}" marks nothing at the use sites; editors strike through only a JSDoc @deprecated tag.`
|
|
186
|
-
})));
|
|
187
|
-
}
|
|
188
|
-
static #isLooseMarker({ isJsDoc, body }) {
|
|
189
|
-
const text = body.filter((line) => line !== "").join(" ");
|
|
190
|
-
if (isJsDoc && /(^|\s)@deprecated\b/.test(text))
|
|
191
|
-
return false;
|
|
192
|
-
return DeprecatedCommentScanner.#marker.test(text);
|
|
193
|
-
}
|
|
194
|
-
}
|
|
195
|
-
|
|
196
|
-
// pkgs/@akanjs/devkit/formSetterScanner.ts
|
|
197
|
-
import ts3 from "typescript";
|
|
198
|
-
|
|
199
|
-
class FormSetterScanner {
|
|
200
|
-
static #fieldSetter = /^set[A-Za-z0-9_$]*On[A-Za-z0-9_$]*$/;
|
|
201
|
-
scan(sourceFiles) {
|
|
202
|
-
return sourceFiles.filter((sourceFile) => sourceFile.file.endsWith(".tsx")).flatMap((f) => this.#scanFile(f));
|
|
203
|
-
}
|
|
204
|
-
#scanFile({ file, sourceFile }) {
|
|
205
|
-
const wrapped = [];
|
|
206
|
-
const visit = (node) => {
|
|
207
|
-
if (ts3.isJsxAttribute(node)) {
|
|
208
|
-
const setter = FormSetterScanner.#wrappedSetterOf(node);
|
|
209
|
-
if (setter)
|
|
210
|
-
wrapped.push({ setter, line: FormSetterScanner.#lineOf(sourceFile, node) });
|
|
211
|
-
}
|
|
212
|
-
ts3.forEachChild(node, visit);
|
|
213
|
-
};
|
|
214
|
-
visit(sourceFile);
|
|
215
|
-
if (!wrapped.length)
|
|
216
|
-
return [];
|
|
217
|
-
const setters = [...new Set(wrapped.map((entry) => entry.setter))].sort();
|
|
218
|
-
return [
|
|
219
|
-
{
|
|
220
|
-
rule: "akan.agent.unpublished-form-setter",
|
|
221
|
-
scope: "agent",
|
|
222
|
-
severity: "warning",
|
|
223
|
-
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(", ")}.`,
|
|
224
|
-
file,
|
|
225
|
-
line: wrapped[0]?.line,
|
|
226
|
-
locations: wrapped.map(({ line }) => ({ file, line }))
|
|
227
|
-
}
|
|
228
|
-
];
|
|
229
|
-
}
|
|
230
|
-
static #wrappedSetterOf(attribute) {
|
|
231
|
-
if (!ts3.isIdentifier(attribute.name) || !/^on[A-Z]/.test(attribute.name.text))
|
|
232
|
-
return null;
|
|
233
|
-
const initializer = attribute.initializer;
|
|
234
|
-
if (!initializer || !ts3.isJsxExpression(initializer) || !initializer.expression)
|
|
235
|
-
return null;
|
|
236
|
-
const handler = initializer.expression;
|
|
237
|
-
if (!ts3.isArrowFunction(handler) && !ts3.isFunctionExpression(handler))
|
|
238
|
-
return null;
|
|
239
|
-
if (!handler.parameters.length)
|
|
240
|
-
return null;
|
|
241
|
-
return FormSetterScanner.#setterCallIn(handler.body);
|
|
242
|
-
}
|
|
243
|
-
static #setterCallIn(node) {
|
|
244
|
-
let found = null;
|
|
245
|
-
const visit = (current) => {
|
|
246
|
-
if (found)
|
|
247
|
-
return;
|
|
248
|
-
if (ts3.isCallExpression(current) && ts3.isPropertyAccessExpression(current.expression)) {
|
|
249
|
-
const { expression, name } = current.expression;
|
|
250
|
-
if (ts3.isPropertyAccessExpression(expression) && ts3.isIdentifier(expression.expression) && expression.expression.text === "st" && expression.name.text === "do" && FormSetterScanner.#fieldSetter.test(name.text)) {
|
|
251
|
-
found = name.text;
|
|
252
|
-
return;
|
|
253
|
-
}
|
|
254
|
-
}
|
|
255
|
-
ts3.forEachChild(current, visit);
|
|
256
|
-
};
|
|
257
|
-
visit(node);
|
|
258
|
-
return found;
|
|
259
|
-
}
|
|
260
|
-
static #lineOf(sourceFile, node) {
|
|
261
|
-
return sourceFile.getLineAndCharacterOfPosition(node.getStart(sourceFile)).line + 1;
|
|
262
|
-
}
|
|
263
|
-
}
|
|
264
|
-
|
|
265
|
-
// pkgs/@akanjs/devkit/kindBranchScanner.ts
|
|
266
|
-
import path2 from "path";
|
|
267
|
-
import ts4 from "typescript";
|
|
268
|
-
|
|
269
|
-
class KindBranchScanner {
|
|
270
|
-
static rule = "akan.global.kind-branch";
|
|
271
|
-
static minFileNum = 3;
|
|
272
|
-
static #kindName = /(Kind|Type|Mode)$/;
|
|
273
|
-
static #kindSubject = /^(kind|type|mode)$|[a-z](Kind|Type|Mode)$/;
|
|
274
|
-
static #equalities = new Set([
|
|
275
|
-
ts4.SyntaxKind.EqualsEqualsEqualsToken,
|
|
276
|
-
ts4.SyntaxKind.ExclamationEqualsEqualsToken,
|
|
277
|
-
ts4.SyntaxKind.EqualsEqualsToken,
|
|
278
|
-
ts4.SyntaxKind.ExclamationEqualsToken
|
|
279
|
-
]);
|
|
280
|
-
scan(sourceFiles) {
|
|
281
|
-
const enums = sourceFiles.flatMap((sourceFile) => KindBranchScanner.#enumsOf(sourceFile));
|
|
282
|
-
const ownersByValue = new Map;
|
|
283
|
-
for (const declaration of enums)
|
|
284
|
-
for (const value of declaration.values)
|
|
285
|
-
ownersByValue.set(value, [...ownersByValue.get(value) ?? [], declaration]);
|
|
286
|
-
const sitesByGroup = new Map;
|
|
287
|
-
for (const sourceFile of sourceFiles) {
|
|
288
|
-
if (!/^(apps|libs)\//.test(sourceFile.file) || /\.(test|spec)\.tsx?$/.test(sourceFile.file))
|
|
289
|
-
continue;
|
|
290
|
-
const sys = KindBranchScanner.#sysOf(sourceFile.file);
|
|
291
|
-
for (const site of KindBranchScanner.#sitesIn(sourceFile, ownersByValue)) {
|
|
292
|
-
const owners = (ownersByValue.get(site.value) ?? []).filter((owner) => owner.sys === sys || owner.sys.startsWith("libs/") && sys.startsWith("apps/"));
|
|
293
|
-
if (!owners.length || owners.some(({ module }) => site.file.startsWith(module)))
|
|
294
|
-
continue;
|
|
295
|
-
const group = owners.map(({ name, file }) => `${file}#${name}`).join(",");
|
|
296
|
-
const entry = sitesByGroup.get(group) ?? { owners, sites: [] };
|
|
297
|
-
entry.sites.push(site);
|
|
298
|
-
sitesByGroup.set(group, entry);
|
|
299
|
-
}
|
|
300
|
-
}
|
|
301
|
-
return [...sitesByGroup.values()].flatMap(({ owners, sites }) => KindBranchScanner.#warningOf(owners, sites));
|
|
302
|
-
}
|
|
303
|
-
static #warningOf(owners, sites) {
|
|
304
|
-
const filesByValue = new Map;
|
|
305
|
-
for (const { value, file } of sites)
|
|
306
|
-
filesByValue.set(value, (filesByValue.get(value) ?? new Set).add(file));
|
|
307
|
-
const values = [...filesByValue].filter(([, files]) => files.size >= KindBranchScanner.minFileNum).map(([value]) => value).sort((a, b) => a < b ? -1 : a > b ? 1 : 0);
|
|
308
|
-
const [owner] = owners;
|
|
309
|
-
if (!owner || !values.length)
|
|
310
|
-
return [];
|
|
311
|
-
const branched = sites.filter(({ value }) => values.includes(value));
|
|
312
|
-
const fileNum = new Set(branched.map(({ file }) => file)).size;
|
|
313
|
-
const enumNames = owners.map(({ name }) => `cnst.${name}`).join(" / ");
|
|
314
|
-
return [
|
|
315
|
-
{
|
|
316
|
-
rule: KindBranchScanner.rule,
|
|
317
|
-
scope: "global",
|
|
318
|
-
severity: "warning",
|
|
319
|
-
file: owner.file,
|
|
320
|
-
line: owner.line,
|
|
321
|
-
message: `${values.map((value) => `"${value}"`).join(", ")} of ${enumNames} ${values.length > 1 ? "are" : "is"} branched on in ${fileNum} files outside the enum's module.`,
|
|
322
|
-
locations: branched.map(({ file, line }) => ({ file, line })),
|
|
323
|
-
fix: `Declare one table keyed by the kind, \`{ [kind in cnst.${owner.name}["value"]]: \u2026 }\` (a component, label or handler per kind), and look the kind up in it instead of comparing it in each file.`
|
|
324
|
-
}
|
|
325
|
-
];
|
|
326
|
-
}
|
|
327
|
-
static #sitesIn({ file, sourceFile }, ownersByValue) {
|
|
328
|
-
const sites = [];
|
|
329
|
-
const record = (literal, subject) => {
|
|
330
|
-
if (!ts4.isStringLiteralLike(literal) || !ownersByValue.has(literal.text))
|
|
331
|
-
return;
|
|
332
|
-
if (!KindBranchScanner.#isKindSubject(subject))
|
|
333
|
-
return;
|
|
334
|
-
sites.push({
|
|
335
|
-
value: literal.text,
|
|
336
|
-
file,
|
|
337
|
-
line: sourceFile.getLineAndCharacterOfPosition(literal.getStart(sourceFile)).line + 1
|
|
338
|
-
});
|
|
339
|
-
};
|
|
340
|
-
const visit = (node) => {
|
|
341
|
-
if (ts4.isBinaryExpression(node) && KindBranchScanner.#equalities.has(node.operatorToken.kind)) {
|
|
342
|
-
record(node.left, node.right);
|
|
343
|
-
record(node.right, node.left);
|
|
344
|
-
} else if (ts4.isCaseClause(node) && ts4.isSwitchStatement(node.parent.parent))
|
|
345
|
-
record(node.expression, node.parent.parent.expression);
|
|
346
|
-
ts4.forEachChild(node, visit);
|
|
347
|
-
};
|
|
348
|
-
visit(sourceFile);
|
|
349
|
-
return sites;
|
|
350
|
-
}
|
|
351
|
-
static #isKindSubject(subject) {
|
|
352
|
-
let current = subject;
|
|
353
|
-
while (ts4.isParenthesizedExpression(current) || ts4.isAsExpression(current) || ts4.isNonNullExpression(current))
|
|
354
|
-
current = current.expression;
|
|
355
|
-
const name = ts4.isIdentifier(current) ? current.text : ts4.isPropertyAccessExpression(current) ? current.name.text : ts4.isElementAccessExpression(current) && ts4.isStringLiteralLike(current.argumentExpression) ? current.argumentExpression.text : "";
|
|
356
|
-
return KindBranchScanner.#kindSubject.test(name);
|
|
357
|
-
}
|
|
358
|
-
static #enumsOf({ file, sourceFile }) {
|
|
359
|
-
if (!/^(apps|libs)\/[^/]+\/lib\/.+\.constant\.ts$/.test(file))
|
|
360
|
-
return [];
|
|
361
|
-
return sourceFile.statements.flatMap((statement) => {
|
|
362
|
-
if (!ts4.isClassDeclaration(statement) || !statement.name)
|
|
363
|
-
return [];
|
|
364
|
-
if (!KindBranchScanner.#kindName.test(statement.name.text))
|
|
365
|
-
return [];
|
|
366
|
-
const values = KindBranchScanner.#enumValuesOf(statement);
|
|
367
|
-
if (!values)
|
|
368
|
-
return [];
|
|
369
|
-
return [
|
|
370
|
-
{
|
|
371
|
-
name: statement.name.text,
|
|
372
|
-
sys: KindBranchScanner.#sysOf(file),
|
|
373
|
-
file,
|
|
374
|
-
line: sourceFile.getLineAndCharacterOfPosition(statement.getStart(sourceFile)).line + 1,
|
|
375
|
-
module: `${path2.posix.dirname(file)}/`,
|
|
376
|
-
values
|
|
377
|
-
}
|
|
378
|
-
];
|
|
379
|
-
});
|
|
380
|
-
}
|
|
381
|
-
static #sysOf(file) {
|
|
382
|
-
return file.split("/").slice(0, 2).join("/");
|
|
383
|
-
}
|
|
384
|
-
static #enumValuesOf(statement) {
|
|
385
|
-
for (const clause of statement.heritageClauses ?? [])
|
|
386
|
-
for (const { expression } of clause.types) {
|
|
387
|
-
if (!ts4.isCallExpression(expression) || !ts4.isIdentifier(expression.expression))
|
|
388
|
-
continue;
|
|
389
|
-
if (expression.expression.text !== "enumOf")
|
|
390
|
-
continue;
|
|
391
|
-
let list = expression.arguments[1];
|
|
392
|
-
while (list && (ts4.isAsExpression(list) || ts4.isParenthesizedExpression(list)))
|
|
393
|
-
list = list.expression;
|
|
394
|
-
if (!list || !ts4.isArrayLiteralExpression(list))
|
|
395
|
-
return null;
|
|
396
|
-
return list.elements.filter(ts4.isStringLiteralLike).map(({ text }) => text);
|
|
397
|
-
}
|
|
398
|
-
return null;
|
|
399
|
-
}
|
|
400
|
-
}
|
|
401
|
-
|
|
402
|
-
// pkgs/@akanjs/devkit/maintainabilityExceptionScanner.ts
|
|
403
|
-
import { existsSync } from "fs";
|
|
404
|
-
import { readdir, readFile } from "fs/promises";
|
|
405
|
-
import path3 from "path";
|
|
406
|
-
class MaintainabilityExceptionScanner {
|
|
407
|
-
static rule = "akan.baseline.exceptions";
|
|
408
|
-
static #shapeFix = "Many reasoned exceptions under one rule mean its threshold is wrong: fix the limit in MaintainabilityLimits rather than record another. Otherwise shrink the code, and `akan lint` lowers each entry and drops it once it passes.";
|
|
409
|
-
static #correctnessFix = "A write rule takes no exception: send the writes through one store action and one endpoint (`akan workflow plan add-mutation`), and `akan lint` drops the entry.";
|
|
410
|
-
async scan(workspaceRoot) {
|
|
411
|
-
const sysPaths = await Promise.all(["apps", "libs"].map(async (sysRoot) => {
|
|
412
|
-
const absoluteRoot = path3.join(workspaceRoot, sysRoot);
|
|
413
|
-
if (!existsSync(absoluteRoot))
|
|
414
|
-
return [];
|
|
415
|
-
const entries = await readdir(absoluteRoot, { withFileTypes: true });
|
|
416
|
-
return entries.filter((entry) => entry.isDirectory()).map((entry) => `${sysRoot}/${entry.name}`);
|
|
417
|
-
}));
|
|
418
|
-
const warnings = await Promise.all(sysPaths.flat().map((sysPath) => MaintainabilityExceptionScanner.#scanSys(workspaceRoot, sysPath)));
|
|
419
|
-
return warnings.flat();
|
|
420
|
-
}
|
|
421
|
-
static async#scanSys(workspaceRoot, sysPath) {
|
|
422
|
-
const file = `${sysPath}/${MaintainabilityBaseline.fileName}`;
|
|
423
|
-
const absolutePath = path3.join(workspaceRoot, file);
|
|
424
|
-
if (!existsSync(absolutePath))
|
|
425
|
-
return [];
|
|
426
|
-
const text = await readFile(absolutePath, "utf8");
|
|
427
|
-
let baseline;
|
|
428
|
-
try {
|
|
429
|
-
baseline = MaintainabilityBaseline.parse(text, file);
|
|
430
|
-
} catch {
|
|
431
|
-
return [];
|
|
432
|
-
}
|
|
433
|
-
const lines = text.split(/\r?\n/);
|
|
434
|
-
return [...baseline.entriesByRule()].map(([rule, entries]) => MaintainabilityExceptionScanner.#warningOf(sysPath, file, lines, rule, entries));
|
|
435
|
-
}
|
|
436
|
-
static #warningOf(sysPath, file, lines, rule, entries) {
|
|
437
|
-
const reasonedNum = entries.filter(({ reason }) => reason !== undefined).length;
|
|
438
|
-
const adoptedNum = entries.length - reasonedNum;
|
|
439
|
-
const listed = entries.map(({ key, reason }) => reason === undefined ? key : `${key} (${JSON.stringify(reason)})`);
|
|
440
|
-
const locations = entries.map(({ key }) => ({
|
|
441
|
-
file,
|
|
442
|
-
line: MaintainabilityExceptionScanner.#lineOf(lines, rule, key)
|
|
443
|
-
}));
|
|
444
|
-
return {
|
|
445
|
-
rule: MaintainabilityExceptionScanner.rule,
|
|
446
|
-
scope: "file",
|
|
447
|
-
severity: "warning",
|
|
448
|
-
file,
|
|
449
|
-
line: locations[0]?.line ?? 1,
|
|
450
|
-
message: `${sysPath} carries ${reasonedNum} reasoned exception${reasonedNum === 1 ? "" : "s"} and ${adoptedNum} adopted-debt entr${adoptedNum === 1 ? "y" : "ies"} for ${rule}: ${listed.join(", ")}.`,
|
|
451
|
-
locations,
|
|
452
|
-
fix: MaintainabilityBaseline.reasonedRules.has(rule) ? MaintainabilityExceptionScanner.#shapeFix : MaintainabilityExceptionScanner.#correctnessFix
|
|
453
|
-
};
|
|
454
|
-
}
|
|
455
|
-
static #lineOf(lines, rule, key) {
|
|
456
|
-
const from = Math.max(lines.findIndex((line) => line.includes(`${JSON.stringify(rule)}:`)), 0);
|
|
457
|
-
return Math.max(lines.findIndex((line, idx) => idx >= from && line.includes(`${JSON.stringify(key)}:`)) + 1, 1);
|
|
458
|
-
}
|
|
459
|
-
}
|
|
460
|
-
|
|
461
|
-
// pkgs/@akanjs/devkit/ssrScanner.ts
|
|
462
|
-
import ts6 from "typescript";
|
|
463
|
-
|
|
464
|
-
// pkgs/@akanjs/devkit/renderMutationScanner.ts
|
|
465
|
-
import ts5 from "typescript";
|
|
466
|
-
|
|
467
|
-
class RenderMutationScanner {
|
|
468
|
-
static rule = "akan.ssr.render-mutation";
|
|
469
|
-
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.";
|
|
470
|
-
static #builders = new Set(["page", "layout", "rootLayout"]);
|
|
471
|
-
static #stages = new Set(["render", "guard", "head", "loading", "notFound", "error"]);
|
|
472
|
-
#mutations;
|
|
473
|
-
constructor(mutations) {
|
|
474
|
-
this.#mutations = mutations;
|
|
475
|
-
}
|
|
476
|
-
scan(sourceFiles) {
|
|
477
|
-
return sourceFiles.filter(({ file }) => /^(apps|libs)\/[^/]+\/page\/.+(?<!\.test|\.spec)\.tsx$/.test(file)).flatMap((sourceFile) => this.#scanRoute(sourceFile));
|
|
478
|
-
}
|
|
479
|
-
#scanRoute({ file, sourceFile }) {
|
|
480
|
-
const fetchNames = RenderMutationScanner.#fetchBindingsOf(sourceFile);
|
|
481
|
-
if (!fetchNames.size)
|
|
482
|
-
return [];
|
|
483
|
-
const functions = RenderMutationScanner.#functionsOf(sourceFile);
|
|
484
|
-
const calls = new Set;
|
|
485
|
-
const helpers = new Set;
|
|
486
|
-
const visit = (node, follow) => {
|
|
487
|
-
if (RenderMutationScanner.#isEventHandler(node))
|
|
488
|
-
return;
|
|
489
|
-
if (this.#isRenderMutation(file, node, fetchNames))
|
|
490
|
-
calls.add(node);
|
|
491
|
-
const helper = follow ? RenderMutationScanner.#helperOf(node, functions) : undefined;
|
|
492
|
-
if (helper)
|
|
493
|
-
helpers.add(helper);
|
|
494
|
-
ts5.forEachChild(node, (child) => visit(child, follow));
|
|
495
|
-
};
|
|
496
|
-
for (const body of RenderMutationScanner.#renderBodiesOf(sourceFile, functions))
|
|
497
|
-
visit(body, true);
|
|
498
|
-
for (const helper of helpers)
|
|
499
|
-
visit(helper, false);
|
|
500
|
-
return [...calls].sort((a, b) => a.getStart(sourceFile) - b.getStart(sourceFile)).map((call) => ({
|
|
501
|
-
rule: RenderMutationScanner.rule,
|
|
502
|
-
scope: "ssr",
|
|
503
|
-
severity: "warning",
|
|
504
|
-
file,
|
|
505
|
-
line: sourceFile.getLineAndCharacterOfPosition(call.getStart(sourceFile)).line + 1,
|
|
506
|
-
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 }.`,
|
|
507
|
-
fix: RenderMutationScanner.fix
|
|
508
|
-
}));
|
|
509
|
-
}
|
|
510
|
-
#isRenderMutation(file, node, fetchNames) {
|
|
511
|
-
if (!ts5.isCallExpression(node))
|
|
512
|
-
return false;
|
|
513
|
-
const name = RenderMutationScanner.#endpointOf(node.expression, fetchNames);
|
|
514
|
-
if (!name || !this.#mutations.isMutation(file, name))
|
|
515
|
-
return false;
|
|
516
|
-
return !RenderMutationScanner.#optsIn(node, this.#mutations.policyIndexOf(file, name));
|
|
517
|
-
}
|
|
518
|
-
static #isEventHandler(node) {
|
|
519
|
-
return ts5.isJsxAttribute(node) && ts5.isIdentifier(node.name) && /^on[A-Z]/.test(node.name.text);
|
|
520
|
-
}
|
|
521
|
-
static #endpointOf(callee, fetchNames) {
|
|
522
|
-
if (ts5.isPropertyAccessExpression(callee))
|
|
523
|
-
return RenderMutationScanner.#isFetch(callee.expression, fetchNames) ? callee.name.text : null;
|
|
524
|
-
if (ts5.isElementAccessExpression(callee) && ts5.isStringLiteralLike(callee.argumentExpression))
|
|
525
|
-
return RenderMutationScanner.#isFetch(callee.expression, fetchNames) ? callee.argumentExpression.text : null;
|
|
526
|
-
return null;
|
|
527
|
-
}
|
|
528
|
-
static #isFetch(expression, fetchNames) {
|
|
529
|
-
return ts5.isIdentifier(expression) && fetchNames.has(expression.text);
|
|
530
|
-
}
|
|
531
|
-
static #optsIn(call, policyIndex) {
|
|
532
|
-
if (policyIndex === null)
|
|
533
|
-
return false;
|
|
534
|
-
const leading = call.arguments.slice(0, policyIndex + 1);
|
|
535
|
-
if (leading.some((argument) => ts5.isSpreadElement(argument)))
|
|
536
|
-
return true;
|
|
537
|
-
const policy = leading[policyIndex];
|
|
538
|
-
return policy ? RenderMutationScanner.#policyOptsIn(policy) : false;
|
|
539
|
-
}
|
|
540
|
-
static #policyOptsIn(argument) {
|
|
541
|
-
const policy = RenderMutationScanner.#unwrap(argument);
|
|
542
|
-
if (!ts5.isObjectLiteralExpression(policy))
|
|
543
|
-
return !RenderMutationScanner.#cannotBePolicy(policy);
|
|
544
|
-
return policy.properties.some((property) => {
|
|
545
|
-
if (ts5.isSpreadAssignment(property))
|
|
546
|
-
return true;
|
|
547
|
-
if (!ts5.isPropertyAssignment(property) && !ts5.isShorthandPropertyAssignment(property))
|
|
548
|
-
return false;
|
|
549
|
-
if (!(ts5.isIdentifier(property.name) || ts5.isStringLiteral(property.name)))
|
|
550
|
-
return false;
|
|
551
|
-
if (property.name.text !== "duringRender")
|
|
552
|
-
return false;
|
|
553
|
-
if (ts5.isShorthandPropertyAssignment(property))
|
|
554
|
-
return true;
|
|
555
|
-
const value = RenderMutationScanner.#unwrap(property.initializer);
|
|
556
|
-
return value.kind !== ts5.SyntaxKind.FalseKeyword && !(ts5.isIdentifier(value) && value.text === "undefined");
|
|
557
|
-
});
|
|
558
|
-
}
|
|
559
|
-
static #unwrap(expression) {
|
|
560
|
-
let current = expression;
|
|
561
|
-
while (ts5.isParenthesizedExpression(current) || ts5.isAsExpression(current) || ts5.isSatisfiesExpression(current) || ts5.isNonNullExpression(current) || ts5.isTypeAssertionExpression(current))
|
|
562
|
-
current = current.expression;
|
|
563
|
-
return current;
|
|
564
|
-
}
|
|
565
|
-
static #cannotBePolicy(expression) {
|
|
566
|
-
if (ts5.isIdentifier(expression))
|
|
567
|
-
return expression.text === "undefined";
|
|
568
|
-
return ts5.isLiteralExpression(expression) || ts5.isNoSubstitutionTemplateLiteral(expression) || ts5.isTemplateExpression(expression) || ts5.isArrayLiteralExpression(expression) || ts5.isArrowFunction(expression) || ts5.isFunctionExpression(expression) || ts5.isVoidExpression(expression) || ts5.isPrefixUnaryExpression(expression) || [ts5.SyntaxKind.NullKeyword, ts5.SyntaxKind.TrueKeyword, ts5.SyntaxKind.FalseKeyword].includes(expression.kind);
|
|
569
|
-
}
|
|
570
|
-
static #fetchBindingsOf(sourceFile) {
|
|
571
|
-
const names = new Set;
|
|
572
|
-
for (const statement of sourceFile.statements) {
|
|
573
|
-
if (!ts5.isImportDeclaration(statement) || statement.importClause?.isTypeOnly)
|
|
574
|
-
continue;
|
|
575
|
-
const bindings = statement.importClause?.namedBindings;
|
|
576
|
-
if (!bindings || !ts5.isNamedImports(bindings))
|
|
577
|
-
continue;
|
|
578
|
-
for (const element of bindings.elements)
|
|
579
|
-
if (!element.isTypeOnly && (element.propertyName ?? element.name).text === "fetch")
|
|
580
|
-
names.add(element.name.text);
|
|
581
|
-
}
|
|
582
|
-
return names;
|
|
583
|
-
}
|
|
584
|
-
static #functionsOf(sourceFile) {
|
|
585
|
-
const functions = new Map;
|
|
586
|
-
for (const statement of sourceFile.statements) {
|
|
587
|
-
if (ts5.isFunctionDeclaration(statement) && statement.name && statement.body)
|
|
588
|
-
functions.set(statement.name.text, statement.body);
|
|
589
|
-
if (!ts5.isVariableStatement(statement))
|
|
590
|
-
continue;
|
|
591
|
-
for (const declaration of statement.declarationList.declarations) {
|
|
592
|
-
const initializer = declaration.initializer && RenderMutationScanner.#unwrap(declaration.initializer);
|
|
593
|
-
if (!ts5.isIdentifier(declaration.name) || !initializer)
|
|
594
|
-
continue;
|
|
595
|
-
if (ts5.isArrowFunction(initializer) || ts5.isFunctionExpression(initializer))
|
|
596
|
-
functions.set(declaration.name.text, initializer.body);
|
|
597
|
-
}
|
|
598
|
-
}
|
|
599
|
-
return functions;
|
|
600
|
-
}
|
|
601
|
-
static #helperOf(node, functions) {
|
|
602
|
-
const callee = ts5.isCallExpression(node) ? node.expression : ts5.isJsxSelfClosingElement(node) || ts5.isJsxOpeningElement(node) ? node.tagName : undefined;
|
|
603
|
-
return callee && ts5.isIdentifier(callee) ? functions.get(callee.text) : undefined;
|
|
604
|
-
}
|
|
605
|
-
static #renderBodiesOf(sourceFile, functions) {
|
|
606
|
-
const bodies = [];
|
|
607
|
-
const bodyOf = (node) => ts5.isIdentifier(node) ? functions.get(node.text) : node;
|
|
608
|
-
const visit = (node) => {
|
|
609
|
-
if (ts5.isCallExpression(node) && ts5.isPropertyAccessExpression(node.expression) && RenderMutationScanner.#stages.has(node.expression.name.text) && RenderMutationScanner.#isRouteChain(node.expression.expression))
|
|
610
|
-
for (const argument of node.arguments) {
|
|
611
|
-
const body = bodyOf(argument);
|
|
612
|
-
if (body)
|
|
613
|
-
bodies.push(body);
|
|
614
|
-
}
|
|
615
|
-
ts5.forEachChild(node, visit);
|
|
616
|
-
};
|
|
617
|
-
visit(sourceFile);
|
|
618
|
-
for (const statement of sourceFile.statements) {
|
|
619
|
-
const legacy = RenderMutationScanner.#legacyPageOf(statement, functions);
|
|
620
|
-
if (legacy)
|
|
621
|
-
bodies.push(legacy);
|
|
622
|
-
}
|
|
623
|
-
return bodies;
|
|
624
|
-
}
|
|
625
|
-
static #isRouteChain(expression) {
|
|
626
|
-
let current = expression;
|
|
627
|
-
while (ts5.isCallExpression(current)) {
|
|
628
|
-
if (ts5.isIdentifier(current.expression))
|
|
629
|
-
return RenderMutationScanner.#builders.has(current.expression.text);
|
|
630
|
-
if (!ts5.isPropertyAccessExpression(current.expression))
|
|
631
|
-
return false;
|
|
632
|
-
current = current.expression.expression;
|
|
633
|
-
}
|
|
634
|
-
return false;
|
|
635
|
-
}
|
|
636
|
-
static #legacyPageOf(statement, functions) {
|
|
637
|
-
if (ts5.isFunctionDeclaration(statement))
|
|
638
|
-
return statement.modifiers?.some((modifier) => modifier.kind === ts5.SyntaxKind.DefaultKeyword) ? statement.body : undefined;
|
|
639
|
-
if (!ts5.isExportAssignment(statement))
|
|
640
|
-
return;
|
|
641
|
-
const expression = RenderMutationScanner.#unwrap(statement.expression);
|
|
642
|
-
if (ts5.isIdentifier(expression))
|
|
643
|
-
return functions.get(expression.text);
|
|
644
|
-
return ts5.isArrowFunction(expression) || ts5.isFunctionExpression(expression) ? expression.body : undefined;
|
|
645
|
-
}
|
|
646
|
-
}
|
|
647
|
-
|
|
648
|
-
// pkgs/@akanjs/devkit/ssrScanner.ts
|
|
649
|
-
var STATIC_COMPONENT_MIN_MASS = 4;
|
|
650
|
-
var MIXED_COMPONENT_MIN_MASS = 10;
|
|
651
|
-
var MIXED_COMPONENT_MAX_TOUCHES = 2;
|
|
652
|
-
var MODULE_SERVER_VIEW_MIN_CLIENT_MASS = 12;
|
|
653
|
-
var fileWarning = (rule, scope, file, message, line) => line === undefined ? { rule, scope, severity: "warning", file, message } : { rule, scope, severity: "warning", file, line, message };
|
|
654
|
-
|
|
655
|
-
class SsrScanner {
|
|
656
|
-
static #serverSafeCalls = new Set(["usePage", "getSelf", "useServer"]);
|
|
657
|
-
static #clientGlobals = new Set("window document navigator localStorage sessionStorage location history screen matchMedia IntersectionObserver".split(" ").concat("ResizeObserver MutationObserver requestAnimationFrame WebSocket".split(" ")));
|
|
658
|
-
static #clientRuntimeImports = new Set(["st", "fetch"]);
|
|
659
|
-
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.";
|
|
660
|
-
scan(sourceFiles) {
|
|
661
|
-
const mutations = new SignalMutationIndex(sourceFiles);
|
|
662
|
-
const componentFiles = sourceFiles.filter((sourceFile) => this.#isBalancedFile(sourceFile.file));
|
|
663
|
-
return {
|
|
664
|
-
warnings: [
|
|
665
|
-
...componentFiles.flatMap((sourceFile) => this.#scanFile(sourceFile, mutations)),
|
|
666
|
-
...this.#scanModules(componentFiles),
|
|
667
|
-
...new RenderMutationScanner(mutations).scan(sourceFiles)
|
|
668
|
-
],
|
|
669
|
-
balance: this.#measureBalance(componentFiles)
|
|
670
|
-
};
|
|
671
|
-
}
|
|
672
|
-
#scanFile(sourceFile, mutations) {
|
|
673
|
-
if (!this.#hasUseClient(sourceFile.sourceFile))
|
|
674
|
-
return [];
|
|
675
|
-
const vendorNames = this.#getVendorNames(sourceFile.sourceFile);
|
|
676
|
-
const hasVendorImport = this.#hasVendorImport(sourceFile.sourceFile);
|
|
677
|
-
const importsClientRuntime = this.#importsClientRuntime(sourceFile.sourceFile);
|
|
678
|
-
const components = this.#getComponents(sourceFile, vendorNames);
|
|
679
|
-
const warnings = [];
|
|
680
|
-
if (!hasVendorImport && !importsClientRuntime && this.#getTouches(sourceFile.sourceFile, sourceFile.sourceFile).length === 0 && !this.#isConventionClientFile(sourceFile.file)) {
|
|
681
|
-
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));
|
|
682
|
-
}
|
|
683
|
-
for (const component of components) {
|
|
684
|
-
if (component.vendorTags)
|
|
685
|
-
continue;
|
|
686
|
-
if (component.touches.length === 0 && component.mass >= STATIC_COMPONENT_MIN_MASS) {
|
|
687
|
-
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));
|
|
688
|
-
continue;
|
|
689
|
-
}
|
|
690
|
-
if (component.touches.length >= 1 && component.touches.length <= MIXED_COMPONENT_MAX_TOUCHES && component.mass >= MIXED_COMPONENT_MIN_MASS) {
|
|
691
|
-
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));
|
|
692
|
-
}
|
|
693
|
-
}
|
|
694
|
-
warnings.push(...this.#getMountLoadWarnings(sourceFile, mutations));
|
|
695
|
-
warnings.push(...this.#getTemplateStateWarnings(sourceFile));
|
|
696
|
-
return warnings;
|
|
697
|
-
}
|
|
698
|
-
#scanModules(sourceFiles) {
|
|
699
|
-
const modules = new Map;
|
|
700
|
-
for (const sourceFile of sourceFiles) {
|
|
701
|
-
const moduleDir = this.#getModuleDir(sourceFile.file);
|
|
702
|
-
if (!moduleDir)
|
|
703
|
-
continue;
|
|
704
|
-
const entry = modules.get(moduleDir) ?? { clientMass: 0, serverFiles: 0, line: sourceFile.file };
|
|
705
|
-
if (this.#hasUseClient(sourceFile.sourceFile))
|
|
706
|
-
entry.clientMass += this.#getMass(sourceFile.sourceFile);
|
|
707
|
-
else if (/\.(Unit|View)\.tsx$/.test(sourceFile.file))
|
|
708
|
-
entry.serverFiles += 1;
|
|
709
|
-
modules.set(moduleDir, entry);
|
|
710
|
-
}
|
|
711
|
-
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.`));
|
|
712
|
-
}
|
|
713
|
-
#getMountLoadWarnings(sourceFile, mutations) {
|
|
714
|
-
const warnings = [];
|
|
715
|
-
SsrScanner.#walk(sourceFile.sourceFile, (node) => {
|
|
716
|
-
if (!this.#isMountEffect(sourceFile.sourceFile, node))
|
|
717
|
-
return;
|
|
718
|
-
for (const load of this.#getLoadCalls(sourceFile.sourceFile, node)) {
|
|
719
|
-
const line = this.#getLine(sourceFile.sourceFile, load.node);
|
|
720
|
-
warnings.push(load.callee.startsWith("fetch.") && mutations.isMutation(sourceFile.file, load.callee.slice("fetch.".length)) ? {
|
|
721
|
-
...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),
|
|
722
|
-
fix: SsrScanner.#mountWriteFix
|
|
723
|
-
} : 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));
|
|
724
|
-
}
|
|
725
|
-
});
|
|
726
|
-
return warnings;
|
|
727
|
-
}
|
|
728
|
-
#isMountEffect(sourceFile, node) {
|
|
729
|
-
if (!ts6.isCallExpression(node))
|
|
730
|
-
return false;
|
|
731
|
-
const callee = node.expression.getText(sourceFile);
|
|
732
|
-
if (callee !== "useEffect" && callee !== "useLayoutEffect")
|
|
733
|
-
return false;
|
|
734
|
-
const deps = node.arguments[1];
|
|
735
|
-
return !!deps && ts6.isArrayLiteralExpression(deps) && deps.elements.length === 0;
|
|
736
|
-
}
|
|
737
|
-
#getLoadCalls(sourceFile, node) {
|
|
738
|
-
const calls = [];
|
|
739
|
-
SsrScanner.#walk(node, (child) => {
|
|
740
|
-
if (!ts6.isCallExpression(child))
|
|
741
|
-
return;
|
|
742
|
-
const callee = child.expression.getText(sourceFile);
|
|
743
|
-
if (/^fetch\.[a-z]/.test(callee) || /^st\.do\.(init|get|view|load|list|count|insight)[A-Z]/.test(callee))
|
|
744
|
-
calls.push({ callee, node: child });
|
|
745
|
-
});
|
|
746
|
-
return calls;
|
|
747
|
-
}
|
|
748
|
-
#getTemplateStateWarnings(sourceFile) {
|
|
749
|
-
if (!sourceFile.file.endsWith(".Template.tsx"))
|
|
750
|
-
return [];
|
|
751
|
-
const warnings = [];
|
|
752
|
-
SsrScanner.#walk(sourceFile.sourceFile, (node) => {
|
|
753
|
-
if (ts6.isCallExpression(node) && node.expression.getText(sourceFile.sourceFile) === "useState")
|
|
754
|
-
warnings.push(fileWarning("akan.ssr.template-client-state", "ssr", sourceFile.file, "Template holds form state in useState. Templates are store-driven and carry no local state.", this.#getLine(sourceFile.sourceFile, node)));
|
|
755
|
-
});
|
|
756
|
-
return warnings;
|
|
757
|
-
}
|
|
758
|
-
#measureBalance(sourceFiles) {
|
|
759
|
-
const scopes = new Map;
|
|
760
|
-
for (const sourceFile of sourceFiles) {
|
|
761
|
-
const segments = sourceFile.file.split("/");
|
|
762
|
-
const scope = `${segments[0]}/${segments[1]}`;
|
|
763
|
-
const entry = scopes.get(scope) ?? { serverMass: 0, clientMass: 0 };
|
|
764
|
-
const mass = this.#getMass(sourceFile.sourceFile);
|
|
765
|
-
if (this.#hasUseClient(sourceFile.sourceFile))
|
|
766
|
-
entry.clientMass += mass;
|
|
767
|
-
else
|
|
768
|
-
entry.serverMass += mass;
|
|
769
|
-
scopes.set(scope, entry);
|
|
770
|
-
}
|
|
771
|
-
const entries = [...scopes].map(([scope, mass]) => ({ scope, ...mass, serverShare: getShare(mass.serverMass, mass.clientMass) })).sort((a, b) => a.scope.localeCompare(b.scope));
|
|
772
|
-
if (entries.length < 2)
|
|
773
|
-
return entries;
|
|
774
|
-
const serverMass = entries.reduce((sum, entry) => sum + entry.serverMass, 0);
|
|
775
|
-
const clientMass = entries.reduce((sum, entry) => sum + entry.clientMass, 0);
|
|
776
|
-
return [...entries, { scope: "workspace", serverMass, clientMass, serverShare: getShare(serverMass, clientMass) }];
|
|
777
|
-
}
|
|
778
|
-
#getComponents(sourceFile, vendorNames) {
|
|
779
|
-
const components = [];
|
|
780
|
-
for (const statement of sourceFile.sourceFile.statements) {
|
|
781
|
-
for (const { name, node } of this.#getComponentNodes(statement)) {
|
|
782
|
-
if (!/^[A-Z]/.test(name))
|
|
783
|
-
continue;
|
|
784
|
-
components.push({
|
|
785
|
-
name,
|
|
786
|
-
line: this.#getLine(sourceFile.sourceFile, node),
|
|
787
|
-
mass: this.#getMass(node),
|
|
788
|
-
touches: this.#getTouches(sourceFile.sourceFile, node),
|
|
789
|
-
vendorTags: [...this.#getTagNames(sourceFile.sourceFile, node)].some((tag) => vendorNames.has(tag))
|
|
790
|
-
});
|
|
791
|
-
}
|
|
792
|
-
}
|
|
793
|
-
return components;
|
|
794
|
-
}
|
|
795
|
-
#getComponentNodes(statement) {
|
|
796
|
-
if (ts6.isFunctionDeclaration(statement) && statement.body)
|
|
797
|
-
return [{ name: statement.name?.text ?? "default", node: statement.body }];
|
|
798
|
-
if (!ts6.isVariableStatement(statement))
|
|
799
|
-
return [];
|
|
800
|
-
return statement.declarationList.declarations.flatMap((declaration) => {
|
|
801
|
-
if (!ts6.isIdentifier(declaration.name) || !declaration.initializer)
|
|
802
|
-
return [];
|
|
803
|
-
if (!ts6.isArrowFunction(declaration.initializer) && !ts6.isFunctionExpression(declaration.initializer))
|
|
804
|
-
return [];
|
|
805
|
-
return [{ name: declaration.name.text, node: declaration.initializer }];
|
|
806
|
-
});
|
|
807
|
-
}
|
|
808
|
-
#getTouches(sourceFile, node) {
|
|
809
|
-
const touches = [];
|
|
810
|
-
SsrScanner.#walk(node, (child) => {
|
|
811
|
-
if (ts6.isCallExpression(child)) {
|
|
812
|
-
const callee = child.expression.getText(sourceFile);
|
|
813
|
-
const bareName = callee.split(".").pop() ?? callee;
|
|
814
|
-
if (callee === "createContext" || callee === "lazy")
|
|
815
|
-
touches.push(callee);
|
|
816
|
-
else if (/^use[A-Z]/.test(bareName) && !SsrScanner.#serverSafeCalls.has(bareName))
|
|
817
|
-
touches.push(bareName);
|
|
818
|
-
}
|
|
819
|
-
if (ts6.isJsxAttribute(child) && /^on[A-Z]/.test(child.name.getText(sourceFile)))
|
|
820
|
-
touches.push(child.name.getText(sourceFile));
|
|
821
|
-
if (ts6.isPropertyAccessExpression(child)) {
|
|
822
|
-
const root = getAccessRoot(child);
|
|
823
|
-
if (root === "st")
|
|
824
|
-
touches.push("st");
|
|
825
|
-
else if (SsrScanner.#clientGlobals.has(root))
|
|
826
|
-
touches.push(root);
|
|
827
|
-
}
|
|
828
|
-
});
|
|
829
|
-
return touches;
|
|
830
|
-
}
|
|
831
|
-
#getTagNames(sourceFile, node) {
|
|
832
|
-
const tags = new Set;
|
|
833
|
-
SsrScanner.#walk(node, (child) => {
|
|
834
|
-
if (ts6.isJsxOpeningElement(child) || ts6.isJsxSelfClosingElement(child))
|
|
835
|
-
tags.add(child.tagName.getText(sourceFile).split(".")[0]);
|
|
836
|
-
});
|
|
837
|
-
return tags;
|
|
838
|
-
}
|
|
839
|
-
#getMass(node) {
|
|
840
|
-
let mass = 0;
|
|
841
|
-
SsrScanner.#walk(node, (child) => {
|
|
842
|
-
if (ts6.isJsxOpeningElement(child) || ts6.isJsxSelfClosingElement(child))
|
|
843
|
-
mass += 1;
|
|
844
|
-
});
|
|
845
|
-
return mass;
|
|
846
|
-
}
|
|
847
|
-
static #walk(node, visit) {
|
|
848
|
-
const walk = (child) => {
|
|
849
|
-
visit(child);
|
|
850
|
-
ts6.forEachChild(child, walk);
|
|
851
|
-
};
|
|
852
|
-
ts6.forEachChild(node, walk);
|
|
853
|
-
}
|
|
854
|
-
#hasUseClient(sourceFile) {
|
|
855
|
-
const first = sourceFile.statements[0];
|
|
856
|
-
if (!first || !ts6.isExpressionStatement(first) || !ts6.isStringLiteral(first.expression))
|
|
857
|
-
return false;
|
|
858
|
-
return first.expression.text === "use client";
|
|
859
|
-
}
|
|
860
|
-
#hasVendorImport(sourceFile) {
|
|
861
|
-
return sourceFile.statements.some((statement) => ts6.isImportDeclaration(statement) && isVendorSpecifier(getSpecifier(statement)));
|
|
862
|
-
}
|
|
863
|
-
#getVendorNames(sourceFile) {
|
|
864
|
-
const names = new Set;
|
|
865
|
-
for (const statement of sourceFile.statements) {
|
|
866
|
-
if (!ts6.isImportDeclaration(statement) || !isVendorSpecifier(getSpecifier(statement)))
|
|
867
|
-
continue;
|
|
868
|
-
const clause = statement.importClause;
|
|
869
|
-
if (clause?.name)
|
|
870
|
-
names.add(clause.name.text);
|
|
871
|
-
if (clause?.namedBindings && ts6.isNamespaceImport(clause.namedBindings))
|
|
872
|
-
names.add(clause.namedBindings.name.text);
|
|
873
|
-
if (clause?.namedBindings && ts6.isNamedImports(clause.namedBindings))
|
|
874
|
-
for (const element of clause.namedBindings.elements)
|
|
875
|
-
names.add(element.name.text);
|
|
876
|
-
}
|
|
877
|
-
return names;
|
|
878
|
-
}
|
|
879
|
-
#importsClientRuntime(sourceFile) {
|
|
880
|
-
for (const statement of sourceFile.statements) {
|
|
881
|
-
if (!ts6.isImportDeclaration(statement))
|
|
882
|
-
continue;
|
|
883
|
-
const bindings = statement.importClause?.namedBindings;
|
|
884
|
-
if (!bindings || !ts6.isNamedImports(bindings))
|
|
885
|
-
continue;
|
|
886
|
-
if (bindings.elements.some((element) => SsrScanner.#clientRuntimeImports.has(element.name.text)))
|
|
887
|
-
return true;
|
|
888
|
-
}
|
|
889
|
-
return false;
|
|
890
|
-
}
|
|
891
|
-
#isConventionClientFile(file) {
|
|
892
|
-
if (file.endsWith("/index_.tsx"))
|
|
893
|
-
return true;
|
|
894
|
-
return /\.(Zone|Template|Util)\.tsx$/.test(file) && this.#getModuleDir(file) !== null;
|
|
895
|
-
}
|
|
896
|
-
#isBalancedFile(file) {
|
|
897
|
-
if (!file.endsWith(".tsx") || file.endsWith(".test.tsx") || file.endsWith(".spec.tsx"))
|
|
898
|
-
return false;
|
|
899
|
-
const segments = file.split("/");
|
|
900
|
-
if (segments[0] !== "apps" && segments[0] !== "libs")
|
|
901
|
-
return false;
|
|
902
|
-
return segments[2] === "ui" || segments[2] === "lib";
|
|
903
|
-
}
|
|
904
|
-
#getModuleDir(file) {
|
|
905
|
-
const segments = file.split("/");
|
|
906
|
-
const libIndex = segments.indexOf("lib");
|
|
907
|
-
if (libIndex < 1 || segments.length <= libIndex + 2)
|
|
908
|
-
return null;
|
|
909
|
-
const moduleName = segments[libIndex + 1];
|
|
910
|
-
if (moduleName.startsWith("_"))
|
|
911
|
-
return null;
|
|
912
|
-
return segments.slice(0, libIndex + 2).join("/");
|
|
913
|
-
}
|
|
914
|
-
#getLine(sourceFile, node) {
|
|
915
|
-
return sourceFile.getLineAndCharacterOfPosition(node.getStart(sourceFile)).line + 1;
|
|
916
|
-
}
|
|
917
|
-
}
|
|
918
|
-
var SSR_SERVER_SHARE_TARGET = 0.5;
|
|
919
|
-
function formatSsrBalance(balance) {
|
|
920
|
-
if (balance.length === 0)
|
|
921
|
-
return ["No component files found."];
|
|
922
|
-
return balance.map((entry) => {
|
|
923
|
-
const total = entry.serverMass + entry.clientMass;
|
|
924
|
-
const share = `${Math.round(entry.serverShare * 100)}% server`;
|
|
925
|
-
const counts = `${entry.serverMass} of ${total} JSX elements, ${entry.clientMass} client`;
|
|
926
|
-
const flag = entry.serverShare < SSR_SERVER_SHARE_TARGET ? ` <- below the ${Math.round(SSR_SERVER_SHARE_TARGET * 100)}% target` : "";
|
|
927
|
-
return ` ${entry.scope}: ${share} (${counts})${flag}`;
|
|
928
|
-
});
|
|
929
|
-
}
|
|
930
|
-
function getShare(serverMass, clientMass) {
|
|
931
|
-
const total = serverMass + clientMass;
|
|
932
|
-
return total === 0 ? 1 : serverMass / total;
|
|
933
|
-
}
|
|
934
|
-
function getSpecifier(statement) {
|
|
935
|
-
return ts6.isStringLiteral(statement.moduleSpecifier) ? statement.moduleSpecifier.text : "";
|
|
936
|
-
}
|
|
937
|
-
function isVendorSpecifier(specifier) {
|
|
938
|
-
if (specifier === "" || specifier.startsWith(".") || specifier.startsWith("/"))
|
|
939
|
-
return false;
|
|
940
|
-
if (specifier === "react" || specifier === "react-dom" || specifier.startsWith("react/"))
|
|
941
|
-
return false;
|
|
942
|
-
if (specifier.startsWith("node:"))
|
|
943
|
-
return false;
|
|
944
|
-
return !/^(akanjs|@akanjs|@libs|@apps|@contract)(\/|$)/.test(specifier);
|
|
945
|
-
}
|
|
946
|
-
function getAccessRoot(node) {
|
|
947
|
-
let current = node;
|
|
948
|
-
while (ts6.isPropertyAccessExpression(current))
|
|
949
|
-
current = current.expression;
|
|
950
|
-
return ts6.isIdentifier(current) ? current.text : "";
|
|
951
|
-
}
|
|
952
|
-
|
|
953
|
-
// pkgs/@akanjs/devkit/testOnlyExportScanner.ts
|
|
954
|
-
import ts7 from "typescript";
|
|
955
|
-
|
|
956
|
-
class TestOnlyExportScanner {
|
|
957
|
-
static rule = "akan.global.test-only-export";
|
|
958
|
-
static #facets = new Set(["common", "webkit", "srvkit", "ui"]);
|
|
959
|
-
scan(sourceFiles) {
|
|
960
|
-
const liveFileNumByName = new Map;
|
|
961
|
-
const testRefsByName = new Map;
|
|
962
|
-
for (const { file, sourceFile } of sourceFiles) {
|
|
963
|
-
const isTest = TestOnlyExportScanner.#isTest(file);
|
|
964
|
-
for (const [name, line] of TestOnlyExportScanner.#identifierLinesOf(sourceFile)) {
|
|
965
|
-
if (!isTest)
|
|
966
|
-
liveFileNumByName.set(name, (liveFileNumByName.get(name) ?? 0) + 1);
|
|
967
|
-
else if (testRefsByName.has(name))
|
|
968
|
-
testRefsByName.get(name)?.push({ file, line });
|
|
969
|
-
else
|
|
970
|
-
testRefsByName.set(name, [{ file, line }]);
|
|
971
|
-
}
|
|
972
|
-
}
|
|
973
|
-
return sourceFiles.filter(({ file }) => TestOnlyExportScanner.#isFacetSource(file)).flatMap(({ file, sourceFile }) => {
|
|
974
|
-
const declarations = TestOnlyExportScanner.#exportedDeclarationsOf(sourceFile);
|
|
975
|
-
return declarations.filter(({ name }) => (liveFileNumByName.get(name) ?? 0) <= 1).filter(({ name }) => !TestOnlyExportScanner.#isUsedInFile(sourceFile, name, declarations)).flatMap(({ name, line }) => {
|
|
976
|
-
const testRefs = testRefsByName.get(name);
|
|
977
|
-
if (!testRefs?.length)
|
|
978
|
-
return [];
|
|
979
|
-
return [
|
|
980
|
-
{
|
|
981
|
-
rule: TestOnlyExportScanner.rule,
|
|
982
|
-
scope: "global",
|
|
983
|
-
severity: "warning",
|
|
984
|
-
file,
|
|
985
|
-
line,
|
|
986
|
-
message: `Exported "${name}" is referenced only by tests: ${testRefs.map((ref) => ref.file).join(", ")}.`,
|
|
987
|
-
locations: testRefs
|
|
988
|
-
}
|
|
989
|
-
];
|
|
990
|
-
});
|
|
991
|
-
});
|
|
992
|
-
}
|
|
993
|
-
static #isTest(file) {
|
|
994
|
-
return /\.(test|spec)\.tsx?$/.test(file);
|
|
995
|
-
}
|
|
996
|
-
static #isFacetSource(file) {
|
|
997
|
-
const segments = file.split("/");
|
|
998
|
-
if (segments[0] !== "apps")
|
|
999
|
-
return false;
|
|
1000
|
-
return TestOnlyExportScanner.#facets.has(segments[2] ?? "") && !TestOnlyExportScanner.#isTest(file);
|
|
1001
|
-
}
|
|
1002
|
-
static #identifierLinesOf(sourceFile) {
|
|
1003
|
-
const lines = new Map;
|
|
1004
|
-
const visit = (node) => {
|
|
1005
|
-
if (ts7.isIdentifier(node) && !lines.has(node.text))
|
|
1006
|
-
lines.set(node.text, sourceFile.getLineAndCharacterOfPosition(node.getStart(sourceFile)).line + 1);
|
|
1007
|
-
ts7.forEachChild(node, visit);
|
|
1008
|
-
};
|
|
1009
|
-
visit(sourceFile);
|
|
1010
|
-
return lines;
|
|
1011
|
-
}
|
|
1012
|
-
static #exportedDeclarationsOf(sourceFile) {
|
|
1013
|
-
return sourceFile.statements.flatMap((statement) => {
|
|
1014
|
-
if (!TestOnlyExportScanner.#isNamedExport(statement))
|
|
1015
|
-
return [];
|
|
1016
|
-
return TestOnlyExportScanner.#declaredNamesOf(statement).map((identifier) => ({
|
|
1017
|
-
name: identifier.text,
|
|
1018
|
-
line: sourceFile.getLineAndCharacterOfPosition(identifier.getStart(sourceFile)).line + 1,
|
|
1019
|
-
statement
|
|
1020
|
-
}));
|
|
1021
|
-
});
|
|
1022
|
-
}
|
|
1023
|
-
static #isNamedExport(statement) {
|
|
1024
|
-
if (!ts7.canHaveModifiers(statement))
|
|
1025
|
-
return false;
|
|
1026
|
-
const modifiers = ts7.getModifiers(statement) ?? [];
|
|
1027
|
-
return modifiers.some((modifier) => modifier.kind === ts7.SyntaxKind.ExportKeyword) && !modifiers.some((modifier) => modifier.kind === ts7.SyntaxKind.DefaultKeyword);
|
|
1028
|
-
}
|
|
1029
|
-
static #declaredNamesOf(statement) {
|
|
1030
|
-
if (ts7.isVariableStatement(statement))
|
|
1031
|
-
return statement.declarationList.declarations.map((declaration) => declaration.name).filter((name) => ts7.isIdentifier(name));
|
|
1032
|
-
if (ts7.isFunctionDeclaration(statement) || ts7.isClassDeclaration(statement) || ts7.isInterfaceDeclaration(statement) || ts7.isTypeAliasDeclaration(statement) || ts7.isEnumDeclaration(statement))
|
|
1033
|
-
return statement.name ? [statement.name] : [];
|
|
1034
|
-
return [];
|
|
1035
|
-
}
|
|
1036
|
-
static #isUsedInFile(sourceFile, name, declarations) {
|
|
1037
|
-
const ownStatements = new Set(declarations.filter((entry) => entry.name === name).map((entry) => entry.statement));
|
|
1038
|
-
let used = false;
|
|
1039
|
-
const visit = (node) => {
|
|
1040
|
-
if (used || ownStatements.has(node))
|
|
1041
|
-
return;
|
|
1042
|
-
if (ts7.isIdentifier(node) && node.text === name)
|
|
1043
|
-
used = true;
|
|
1044
|
-
else
|
|
1045
|
-
ts7.forEachChild(node, visit);
|
|
1046
|
-
};
|
|
1047
|
-
visit(sourceFile);
|
|
1048
|
-
return used;
|
|
1049
|
-
}
|
|
1050
|
-
}
|
|
1051
|
-
|
|
1052
|
-
// pkgs/@akanjs/devkit/qualityScanner.ts
|
|
1053
|
-
var MAX_FILE_LINES = 2000;
|
|
1054
|
-
var PLACEHOLDER_EXPORT_NAMES = new Set([
|
|
1055
|
-
"aa",
|
|
1056
|
-
"dumb",
|
|
1057
|
-
"dumb2",
|
|
1058
|
-
"someBaseLogic",
|
|
1059
|
-
"someCommonLogic",
|
|
1060
|
-
"someFrontendLogic",
|
|
1061
|
-
"someBackendLogic"
|
|
1062
|
-
]);
|
|
1063
|
-
var SUGGESTED_RULES = [
|
|
1064
|
-
"Keep generated scanSync index files out of hand-written changes; generated indexes should only contain one-depth export statements.",
|
|
1065
|
-
"Generated Akan index files should not contain placeholder exports such as aa, dumb, dumb2, or some*Logic.",
|
|
1066
|
-
"Dictionary text should not contain scaffold wording, misspellings, or stale copied domain nouns.",
|
|
1067
|
-
"Warn earlier on very long Akan files: 500 lines for services, 800 lines for Template/Zone files, and 1000 lines for Util files.",
|
|
1068
|
-
"Global declarations, Window augmentation, and prototype mutation should stay in explicitly approved low-level integration files.",
|
|
1069
|
-
"Keep app root folders small and conventional: application code belongs under common, env, lib, page, plugin, private, public, script, srvkit, ui, or webkit.",
|
|
1070
|
-
"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.",
|
|
1071
|
-
"Use domain module folders consistently: lib/<model> for database modules, lib/_<service> for service modules, and lib/__scalar/<scalar> for scalar modules.",
|
|
1072
|
-
"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.",
|
|
1073
|
-
"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.",
|
|
1074
|
-
"Move shared app and lib utilities to common/ instead of creating apps/*/base or libs/*/base.",
|
|
1075
|
-
"Avoid large mixed-purpose class files; class export files should import helpers from neighboring utility files instead of declaring them inline."
|
|
1076
|
-
];
|
|
1077
|
-
var CONVENTION_SUFFIXES = [
|
|
1078
|
-
".constant.ts",
|
|
1079
|
-
".dictionary.ts",
|
|
1080
|
-
".document.ts",
|
|
1081
|
-
".service.ts",
|
|
1082
|
-
".signal.ts",
|
|
1083
|
-
".store.ts"
|
|
1084
|
-
];
|
|
1085
|
-
var RULE_FIXES = {
|
|
1086
|
-
"akan.global.duplicate-exported-function-name": "Rename one of the exports, or if they are the same thing, extract it into one shared module and import it in both places.",
|
|
1087
|
-
"akan.global.duplicate-exported-function-body": "Extract the shared implementation into a single exported helper and import it, instead of copying the body.",
|
|
1088
|
-
"akan.global.test-only-export": "Delete the export together with its test. If a live caller in the same file needs it, keep it unexported and test it through that caller.",
|
|
1089
|
-
"akan.file.recommended-max-lines": "Split the file by responsibility \u2014 move Zones, Utils, or subcomponents into sibling files.",
|
|
1090
|
-
"akan.file.max-lines": "Break the file into smaller focused modules; keep one primary responsibility per file.",
|
|
1091
|
-
"akan.file.abstract-max-lines": "Trim the abstract by hand to a title, one sentence naming what the module owns, a `## Rules` list of the invariants the source cannot show, and an optional workflow chain.",
|
|
1092
|
-
"akan.file.placeholder-export": "Remove the placeholder export; generated indexes should only re-export real modules.",
|
|
1093
|
-
"akan.file.bang-comment-in-client": "Rewrite the marker as `// FIXME:` or `// TODO:`. Keep the bang form for server, srvkit, and CLI files.",
|
|
1094
|
-
"akan.file.dictionary-stale-text": "Replace the scaffold text with real localized copy for this dictionary entry.",
|
|
1095
|
-
"akan.file.global-declaration": "Move the global declaration into an approved low-level integration file (e.g. webkit) and keep it isolated.",
|
|
1096
|
-
"akan.file.window-augmentation": "Move the Window augmentation into an approved browser integration file and keep it isolated.",
|
|
1097
|
-
"akan.file.prototype-mutation": "Avoid prototype mutation, or isolate it in an approved low-level integration file.",
|
|
1098
|
-
"akan.file.class-export-global-declaration": "Move the helper to a sibling file and import it into the class module.",
|
|
1099
|
-
"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.",
|
|
1100
|
-
"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`.",
|
|
1101
|
-
"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.",
|
|
1102
|
-
"akan.layout.app-root-file": "Move the file into a conventional app folder (common, env, lib, page, private, public, script, srvkit, ui, or webkit).",
|
|
1103
|
-
"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.",
|
|
1104
|
-
"akan.layout.lib-root-file": "Move the file into a conventional lib folder (common, env, lib, page, private, public, srvkit, ui, or webkit).",
|
|
1105
|
-
"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.",
|
|
1106
|
-
"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.",
|
|
1107
|
-
"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.",
|
|
1108
|
-
"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.",
|
|
1109
|
-
"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.',
|
|
1110
|
-
"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.",
|
|
1111
|
-
"akan.ssr.client-static-markup": "Keep the interactive element in the client component and hoist the static subtree into a server component, then accept it as `children` or render it through a Unit/View reference.",
|
|
1112
|
-
"akan.ssr.client-mount-load": "Load the data in the route with `fetch.initX(...)` / `fetch.viewX(...)` and pass the init/view object down as a prop; the client store hydrates from it and the effect goes away.",
|
|
1113
|
-
"akan.ssr.module-missing-server-view": "Add a <Model>.Unit.tsx for list/card rendering and a <Model>.View.tsx for the detail surface, then have the Zone delegate to them.",
|
|
1114
|
-
"akan.ssr.template-client-state": "Bind the field to the store instead: `value={xForm.field}` with `onChange={st.do.setFieldOnX}`.",
|
|
1115
|
-
"akan.comment.density": 'Delete comments that restate the code, label a section, or narrate a step; keep only those carrying a fact the code cannot show, such as a vendor quirk or security reasoning (AGENTS.md "Comments").',
|
|
1116
|
-
"akan.comment.deprecated-marker": "Replace the comment with `/** @deprecated <what to use instead> */` on the declaration, so every use site shows it struck through."
|
|
1117
|
-
};
|
|
1118
|
-
function getRuleFix(rule) {
|
|
1119
|
-
if (rule.startsWith("akan.convention"))
|
|
1120
|
-
return "Keep only the model's allowed declarations in this file; move other logic to the matching domain file (service, document, store, etc.).";
|
|
1121
|
-
return RULE_FIXES[rule];
|
|
1122
|
-
}
|
|
1123
|
-
|
|
1124
|
-
class AkanQualityScanner {
|
|
1125
|
-
async scan(workspaceRoot) {
|
|
1126
|
-
const targetFiles = await this.#collectTargetFiles(workspaceRoot);
|
|
1127
|
-
const sourceFiles = await Promise.all(targetFiles.filter((file) => !AbstractDoc.isAbstractPath(file)).map((file) => this.#readSourceFile(workspaceRoot, file)));
|
|
1128
|
-
const abstractFiles = await Promise.all(targetFiles.filter((file) => AbstractDoc.isAbstractPath(file)).map((file) => this.#readTextFile(workspaceRoot, file)));
|
|
1129
|
-
const ssr = new SsrScanner().scan(sourceFiles);
|
|
1130
|
-
const warnings = [
|
|
1131
|
-
...this.#scanGlobalQuality(sourceFiles),
|
|
1132
|
-
...sourceFiles.flatMap((sourceFile) => this.#scanSingleFileQuality(sourceFile)),
|
|
1133
|
-
...sourceFiles.flatMap((sourceFile) => this.#scanComponentQuality(sourceFile)),
|
|
1134
|
-
...sourceFiles.flatMap((sourceFile) => this.#scanConventionQuality(sourceFile)),
|
|
1135
|
-
...sourceFiles.flatMap((sourceFile) => this.#scanLayoutQuality(sourceFile)),
|
|
1136
|
-
...abstractFiles.flatMap((abstractFile) => this.#scanAbstractQuality(abstractFile)),
|
|
1137
|
-
...new FormSetterScanner().scan(sourceFiles),
|
|
1138
|
-
...new CommentDensityScanner().scan(sourceFiles),
|
|
1139
|
-
...new DeprecatedCommentScanner().scan(sourceFiles),
|
|
1140
|
-
...await new MaintainabilityExceptionScanner().scan(workspaceRoot),
|
|
1141
|
-
...ssr.warnings
|
|
1142
|
-
];
|
|
1143
|
-
return {
|
|
1144
|
-
workspaceRoot,
|
|
1145
|
-
scannedFiles: sourceFiles.length + abstractFiles.length,
|
|
1146
|
-
warnings: warnings.map((warning) => ({ ...warning, fix: warning.fix ?? getRuleFix(warning.rule) })).sort(compareWarnings),
|
|
1147
|
-
ssrBalance: ssr.balance,
|
|
1148
|
-
suggestedRules: SUGGESTED_RULES
|
|
1149
|
-
};
|
|
1150
|
-
}
|
|
1151
|
-
async#collectTargetFiles(workspaceRoot) {
|
|
1152
|
-
const ignoreFilter = ignore().add(await this.#readGitIgnore(workspaceRoot));
|
|
1153
|
-
const files = [];
|
|
1154
|
-
for (const targetRoot of ["apps", "libs"]) {
|
|
1155
|
-
const absoluteTargetRoot = path4.join(workspaceRoot, targetRoot);
|
|
1156
|
-
if (!await isDirectory(absoluteTargetRoot))
|
|
1157
|
-
continue;
|
|
1158
|
-
await this.#walkTargetFiles(workspaceRoot, absoluteTargetRoot, ignoreFilter, files);
|
|
1159
|
-
}
|
|
1160
|
-
return files.sort((a, b) => a < b ? -1 : a > b ? 1 : 0);
|
|
1161
|
-
}
|
|
1162
|
-
async#readGitIgnore(workspaceRoot) {
|
|
1163
|
-
const gitIgnorePath = path4.join(workspaceRoot, ".gitignore");
|
|
1164
|
-
if (!await Bun.file(gitIgnorePath).exists())
|
|
1165
|
-
return [];
|
|
1166
|
-
return (await readFile2(gitIgnorePath, "utf8")).split(/\r?\n/);
|
|
1167
|
-
}
|
|
1168
|
-
async#walkTargetFiles(workspaceRoot, currentPath, ignoreFilter, files) {
|
|
1169
|
-
const entries = await readdir2(currentPath, { withFileTypes: true });
|
|
1170
|
-
for (const entry of entries) {
|
|
1171
|
-
const absolutePath = path4.join(currentPath, entry.name);
|
|
1172
|
-
const relativePath = toPosix(path4.relative(workspaceRoot, absolutePath));
|
|
1173
|
-
if (shouldSkipPath(relativePath, entry.isDirectory(), ignoreFilter))
|
|
1174
|
-
continue;
|
|
1175
|
-
if (entry.isDirectory()) {
|
|
1176
|
-
await this.#walkTargetFiles(workspaceRoot, absolutePath, ignoreFilter, files);
|
|
1177
|
-
continue;
|
|
1178
|
-
}
|
|
1179
|
-
if ((relativePath.endsWith(".ts") || relativePath.endsWith(".tsx")) && !relativePath.endsWith(".d.ts")) {
|
|
1180
|
-
files.push(relativePath);
|
|
1181
|
-
} else if (AbstractDoc.isAbstractPath(relativePath)) {
|
|
1182
|
-
files.push(relativePath);
|
|
1183
|
-
}
|
|
1184
|
-
}
|
|
1185
|
-
}
|
|
1186
|
-
async#readSourceFile(workspaceRoot, file) {
|
|
1187
|
-
const absolutePath = path4.join(workspaceRoot, file);
|
|
1188
|
-
const content = await readFile2(absolutePath, "utf8");
|
|
1189
|
-
return {
|
|
1190
|
-
file,
|
|
1191
|
-
absolutePath,
|
|
1192
|
-
content,
|
|
1193
|
-
sourceFile: ts8.createSourceFile(file, content, ts8.ScriptTarget.Latest, true, getScriptKind(file))
|
|
1194
|
-
};
|
|
1195
|
-
}
|
|
1196
|
-
async#readTextFile(workspaceRoot, file) {
|
|
1197
|
-
return { file, content: await readFile2(path4.join(workspaceRoot, file), "utf8") };
|
|
1198
|
-
}
|
|
1199
|
-
#scanGlobalQuality(sourceFiles) {
|
|
1200
|
-
const exportedFunctionLikes = sourceFiles.flatMap((sourceFile) => getExportedFunctionLikes(sourceFile));
|
|
1201
|
-
const warnings = [];
|
|
1202
|
-
const nameCheckedDeclarations = exportedFunctionLikes.filter((declaration) => !declaration.duplicateNameExempt);
|
|
1203
|
-
for (const [name, declarations] of groupBy(nameCheckedDeclarations, (declaration) => declaration.name)) {
|
|
1204
|
-
if (declarations.length < 2)
|
|
1205
|
-
continue;
|
|
1206
|
-
warnings.push({
|
|
1207
|
-
rule: "akan.global.duplicate-exported-function-name",
|
|
1208
|
-
scope: "global",
|
|
1209
|
-
severity: "warning",
|
|
1210
|
-
message: `Exported function or class name "${name}" is declared in ${declarations.length} files.`,
|
|
1211
|
-
locations: declarations.map(({ file, line }) => ({ file, line }))
|
|
1212
|
-
});
|
|
1213
|
-
}
|
|
1214
|
-
const declarationsWithBody = exportedFunctionLikes.filter((declaration) => declaration.bodyFingerprint);
|
|
1215
|
-
for (const [fingerprint, declarations] of groupBy(declarationsWithBody, (declaration) => declaration.bodyFingerprint ?? "")) {
|
|
1216
|
-
const uniqueNames = new Set(declarations.map((declaration) => declaration.name));
|
|
1217
|
-
if (declarations.length < 2 || uniqueNames.size < 2 || fingerprint === "")
|
|
1218
|
-
continue;
|
|
1219
|
-
warnings.push({
|
|
1220
|
-
rule: "akan.global.duplicate-exported-function-body",
|
|
1221
|
-
scope: "global",
|
|
1222
|
-
severity: "warning",
|
|
1223
|
-
message: `Exported functions/classes share the same implementation body: ${declarations.map((declaration) => declaration.name).join(", ")}.`,
|
|
1224
|
-
locations: declarations.map(({ file, line }) => ({ file, line }))
|
|
1225
|
-
});
|
|
1226
|
-
}
|
|
1227
|
-
warnings.push(...new TestOnlyExportScanner().scan(sourceFiles));
|
|
1228
|
-
warnings.push(...new KindBranchScanner().scan(sourceFiles));
|
|
1229
|
-
return warnings;
|
|
1230
|
-
}
|
|
1231
|
-
#scanSingleFileQuality(sourceFile) {
|
|
1232
|
-
const warnings = [];
|
|
1233
|
-
const lineCount = sourceFile.content.split(/\r?\n/).length;
|
|
1234
|
-
const recommendedLineLimit = getRecommendedLineLimit(sourceFile.file);
|
|
1235
|
-
if (recommendedLineLimit && lineCount > recommendedLineLimit)
|
|
1236
|
-
warnings.push(fileWarning("akan.file.recommended-max-lines", "file", sourceFile.file, `File has ${lineCount} lines. Recommended limit for this file type is ${recommendedLineLimit} lines.`));
|
|
1237
|
-
if (lineCount > MAX_FILE_LINES)
|
|
1238
|
-
warnings.push(fileWarning("akan.file.max-lines", "file", sourceFile.file, `File has ${lineCount} lines. Keep single files under ${MAX_FILE_LINES} lines.`));
|
|
1239
|
-
warnings.push(...getBangCommentWarnings(sourceFile));
|
|
1240
|
-
warnings.push(...getPlaceholderExportWarnings(sourceFile));
|
|
1241
|
-
warnings.push(...getDictionaryTextWarnings(sourceFile));
|
|
1242
|
-
warnings.push(...getGlobalMutationWarnings(sourceFile));
|
|
1243
|
-
const exportedClassNames = getExportedClassNames(sourceFile.sourceFile);
|
|
1244
|
-
if (exportedClassNames.length === 0)
|
|
1245
|
-
return warnings;
|
|
1246
|
-
const allowedInterfaceNames = new Set(exportedClassNames.map((name) => `${name}Options`));
|
|
1247
|
-
for (const declaration of getTopLevelDeclarations(sourceFile)) {
|
|
1248
|
-
if (declaration.kind === "class" && exportedClassNames.includes(declaration.name))
|
|
1249
|
-
continue;
|
|
1250
|
-
if (declaration.kind === "interface" && allowedInterfaceNames.has(declaration.name))
|
|
1251
|
-
continue;
|
|
1252
|
-
if ((declaration.kind === "interface" || declaration.kind === "type") && !declaration.exported)
|
|
1253
|
-
continue;
|
|
1254
|
-
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));
|
|
1255
|
-
}
|
|
1256
|
-
return warnings;
|
|
1257
|
-
}
|
|
1258
|
-
#scanComponentQuality(sourceFile) {
|
|
1259
|
-
if (!isComponentDeclarationFile(sourceFile.file))
|
|
1260
|
-
return [];
|
|
1261
|
-
const isPage = isPageRouteFile(sourceFile.file);
|
|
1262
|
-
const declarations = getComponentFileDeclarations(sourceFile.sourceFile);
|
|
1263
|
-
const compoundComponentNames = getCompoundComponentNames(sourceFile.sourceFile);
|
|
1264
|
-
const componentNames = declarations.filter((declaration) => declaration.exported && isComponentValueKind(declaration.kind)).filter((declaration) => isPascalCaseName(declaration.name)).map((declaration) => declaration.name);
|
|
1265
|
-
const allowedComponentNames = new Set([...componentNames, ...compoundComponentNames]);
|
|
1266
|
-
const allowedPropsInterfaces = new Set([...allowedComponentNames].map((name) => `${name}Props`));
|
|
1267
|
-
const warnings = [];
|
|
1268
|
-
for (const declaration of declarations) {
|
|
1269
|
-
if (declaration.isDefaultExport)
|
|
1270
|
-
continue;
|
|
1271
|
-
if (declaration.kind === "interface" && allowedPropsInterfaces.has(declaration.name))
|
|
1272
|
-
continue;
|
|
1273
|
-
if (declaration.exported) {
|
|
1274
|
-
if (isAllowedComponentExport(declaration, isPage))
|
|
1275
|
-
continue;
|
|
1276
|
-
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));
|
|
1277
|
-
continue;
|
|
1278
|
-
}
|
|
1279
|
-
if (isComponentValueKind(declaration.kind) && compoundComponentNames.has(declaration.name))
|
|
1280
|
-
continue;
|
|
1281
|
-
if (isRestrictedInternalKind(declaration.kind))
|
|
1282
|
-
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));
|
|
1283
|
-
}
|
|
1284
|
-
return warnings;
|
|
1285
|
-
}
|
|
1286
|
-
#scanConventionQuality(sourceFile) {
|
|
1287
|
-
const suffix = CONVENTION_SUFFIXES.find((candidate) => sourceFile.file.endsWith(candidate));
|
|
1288
|
-
if (!suffix)
|
|
1289
|
-
return [];
|
|
1290
|
-
const modelName = toPascalCase(path4.basename(sourceFile.file, suffix));
|
|
1291
|
-
return getTopLevelDeclarations(sourceFile).filter((declaration) => !isAllowedConventionDeclaration(suffix, modelName, declaration)).map((declaration) => fileWarning(`akan.convention${suffix.replace(".ts", "")}`, "convention", sourceFile.file, `${path4.basename(sourceFile.file)} should not declare top-level ${declaration.kind} "${declaration.name}". Allowed declarations: ${getConventionDescription(suffix, modelName)}.`, declaration.line));
|
|
1292
|
-
}
|
|
1293
|
-
#scanAbstractQuality({ file, content }) {
|
|
1294
|
-
const lineCount = AbstractDoc.lineCountOf(content);
|
|
1295
|
-
if (lineCount <= AbstractDoc.maxLines)
|
|
1296
|
-
return [];
|
|
1297
|
-
return [
|
|
1298
|
-
fileWarning("akan.file.abstract-max-lines", "file", file, `Abstract has ${lineCount} lines. Keep abstracts under ${AbstractDoc.maxLines} lines and compact them periodically.`)
|
|
1299
|
-
];
|
|
1300
|
-
}
|
|
1301
|
-
#scanLayoutQuality(sourceFile) {
|
|
1302
|
-
const warnings = [];
|
|
1303
|
-
const rootEntry = getSysRootEntry(sourceFile.file);
|
|
1304
|
-
if (rootEntry) {
|
|
1305
|
-
const { type, name, isDir } = rootEntry;
|
|
1306
|
-
const allowed = isDir ? rootAllowedDirs[type].has(name) : rootAllowedFiles[type].has(name);
|
|
1307
|
-
const kind = isDir ? "folder" : "file";
|
|
1308
|
-
if (!allowed)
|
|
1309
|
-
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.`}`));
|
|
1310
|
-
}
|
|
1311
|
-
const facetShadow = rootEntry?.isDir ? facetIndexShadowOf(sourceFile.file.split("/").slice(2).join("/")) : null;
|
|
1312
|
-
if (facetShadow)
|
|
1313
|
-
warnings.push(fileWarning("akan.layout.facet-index-shadow", "layout", sourceFile.file, `${path4.basename(sourceFile.file)} ${facetShadow}.`));
|
|
1314
|
-
const libFacetFile = getLibFacetRootFile(sourceFile.file);
|
|
1315
|
-
if (libFacetFile && !isAllowedLibFacetRootFile(libFacetFile))
|
|
1316
|
-
warnings.push(fileWarning("akan.layout.lib-facet-file", "layout", sourceFile.file, `Unexpected lib facet root file "${libFacetFile}". ${libFacetRootHintOf(libFacetFile) ?? "Keep direct lib/ root files limited to generated support facets."}`));
|
|
1317
|
-
const moduleUiWarning = getModuleUiWarning(sourceFile.file);
|
|
1318
|
-
if (moduleUiWarning)
|
|
1319
|
-
warnings.push(moduleUiWarning);
|
|
1320
|
-
return warnings;
|
|
1321
|
-
}
|
|
1322
|
-
}
|
|
1323
|
-
function formatQualityScanResult(result) {
|
|
1324
|
-
const sections = [
|
|
1325
|
-
"Akan Code Quality Scan",
|
|
1326
|
-
`workspace: ${result.workspaceRoot}`,
|
|
1327
|
-
`scanned files: ${result.scannedFiles}`,
|
|
1328
|
-
`warnings: ${result.warnings.length}`,
|
|
1329
|
-
"",
|
|
1330
|
-
"Warnings:",
|
|
1331
|
-
"",
|
|
1332
|
-
...formatQualityWarnings(result.warnings),
|
|
1333
|
-
"",
|
|
1334
|
-
"SSR balance (component files, JSX elements rendered per side):",
|
|
1335
|
-
"",
|
|
1336
|
-
...formatSsrBalance(result.ssrBalance),
|
|
1337
|
-
"",
|
|
1338
|
-
"Suggested quality rules:",
|
|
1339
|
-
"",
|
|
1340
|
-
...result.suggestedRules.map((rule) => ` - ${rule}`)
|
|
1341
|
-
];
|
|
1342
|
-
return sections.join(`
|
|
1343
|
-
`);
|
|
1344
|
-
}
|
|
1345
|
-
function formatSsrScanResult(result) {
|
|
1346
|
-
const sections = [
|
|
1347
|
-
"Akan SSR Balance Scan",
|
|
1348
|
-
`workspace: ${result.workspaceRoot}`,
|
|
1349
|
-
`scanned files: ${result.scannedFiles}`,
|
|
1350
|
-
`ssr warnings: ${result.warnings.length}`,
|
|
1351
|
-
"",
|
|
1352
|
-
"Server render share (component files, JSX elements rendered per side):",
|
|
1353
|
-
"",
|
|
1354
|
-
...formatSsrBalance(result.ssrBalance),
|
|
1355
|
-
"",
|
|
1356
|
-
"Warnings:",
|
|
1357
|
-
"",
|
|
1358
|
-
...formatQualityWarnings(result.warnings)
|
|
1359
|
-
];
|
|
1360
|
-
return sections.join(`
|
|
1361
|
-
`);
|
|
1362
|
-
}
|
|
1363
|
-
function formatQualityWarnings(warnings) {
|
|
1364
|
-
if (warnings.length === 0)
|
|
1365
|
-
return ["No warnings found."];
|
|
1366
|
-
return warnings.flatMap((warning) => {
|
|
1367
|
-
const location = formatQualityLocation(warning.file, warning.line);
|
|
1368
|
-
const lines = [`${location} - warning ${warning.rule}: ${warning.message}`];
|
|
1369
|
-
if (warning.locations?.length) {
|
|
1370
|
-
lines.push(...warning.locations.map(({ file, line }) => ` note: related location ${formatQualityLocation(file, line)}`));
|
|
1371
|
-
}
|
|
1372
|
-
if (warning.fix)
|
|
1373
|
-
lines.push(` fix: ${warning.fix}`);
|
|
1374
|
-
return lines;
|
|
1375
|
-
});
|
|
1376
|
-
}
|
|
1377
|
-
function formatQualityLocation(file, line) {
|
|
1378
|
-
return `${file ?? "<global>"}:${line ?? 1}:1`;
|
|
1379
|
-
}
|
|
1380
|
-
function getExportedFunctionLikes(sourceFile) {
|
|
1381
|
-
const declarations = [];
|
|
1382
|
-
const nameExempt = isPageRouteFile(sourceFile.file) || isUiComponentFile(sourceFile.file);
|
|
1383
|
-
const add = (name, kind, node, body, isEnumClass = false) => declarations.push({
|
|
1384
|
-
name,
|
|
1385
|
-
kind,
|
|
1386
|
-
file: sourceFile.file,
|
|
1387
|
-
line: getLine(sourceFile.sourceFile, node),
|
|
1388
|
-
bodyFingerprint: getBodyFingerprint(sourceFile.sourceFile, body),
|
|
1389
|
-
duplicateNameExempt: nameExempt || isConventionDuplicateNameExempt(sourceFile.file, isEnumClass)
|
|
1390
|
-
});
|
|
1391
|
-
for (const statement of sourceFile.sourceFile.statements) {
|
|
1392
|
-
if (ts8.isFunctionDeclaration(statement) && statement.name && isExported(statement))
|
|
1393
|
-
add(statement.name.text, "function", statement, statement.body);
|
|
1394
|
-
if (ts8.isClassDeclaration(statement) && statement.name && isExported(statement))
|
|
1395
|
-
add(statement.name.text, "class", statement, statement, isEnumClassStatement(sourceFile.sourceFile, statement));
|
|
1396
|
-
if (ts8.isVariableStatement(statement) && isExported(statement)) {
|
|
1397
|
-
for (const declaration of statement.declarationList.declarations) {
|
|
1398
|
-
if (!ts8.isIdentifier(declaration.name) || !isFunctionLikeInitializer(declaration.initializer))
|
|
1399
|
-
continue;
|
|
1400
|
-
add(declaration.name.text, "function-variable", declaration, declaration.initializer);
|
|
1401
|
-
}
|
|
1402
|
-
}
|
|
1403
|
-
}
|
|
1404
|
-
return declarations;
|
|
1405
|
-
}
|
|
1406
|
-
function sysSegments(file) {
|
|
1407
|
-
const segments = file.split("/");
|
|
1408
|
-
return segments[0] === "apps" || segments[0] === "libs" ? segments : null;
|
|
1409
|
-
}
|
|
1410
|
-
function isPageRouteFile(file) {
|
|
1411
|
-
return sysSegments(file)?.[2] === "page";
|
|
1412
|
-
}
|
|
1413
|
-
function isUiComponentFile(file) {
|
|
1414
|
-
return sysSegments(file)?.[2] === "ui";
|
|
1415
|
-
}
|
|
1416
|
-
function isConventionDuplicateNameExempt(file, isEnumClass) {
|
|
1417
|
-
if (!sysSegments(file)?.includes("lib"))
|
|
1418
|
-
return false;
|
|
1419
|
-
if (file.endsWith(".tsx") || /\.(document|service|signal|store)\.ts$/.test(file))
|
|
1420
|
-
return true;
|
|
1421
|
-
if (file.endsWith(".constant.ts"))
|
|
1422
|
-
return !isEnumClass;
|
|
1423
|
-
return false;
|
|
1424
|
-
}
|
|
1425
|
-
function isEnumClassStatement(sourceFile, statement) {
|
|
1426
|
-
if (!ts8.isClassDeclaration(statement))
|
|
1427
|
-
return false;
|
|
1428
|
-
const heritageClause = statement.heritageClauses?.find((clause) => clause.token === ts8.SyntaxKind.ExtendsKeyword);
|
|
1429
|
-
const expression = heritageClause?.types[0]?.expression;
|
|
1430
|
-
return !!expression && expression.getText(sourceFile).startsWith("enumOf(");
|
|
1431
|
-
}
|
|
1432
|
-
function getExportedClassNames(sourceFile) {
|
|
1433
|
-
return sourceFile.statements.filter((statement) => ts8.isClassDeclaration(statement)).filter((statement) => isExported(statement)).map((statement) => statement.name?.text).filter((name) => !!name);
|
|
1434
|
-
}
|
|
1435
|
-
function isComponentDeclarationFile(file) {
|
|
1436
|
-
if (!file.endsWith(".tsx"))
|
|
1437
|
-
return false;
|
|
1438
|
-
const segments = file.split("/");
|
|
1439
|
-
const [root, , area] = segments;
|
|
1440
|
-
if (root !== "apps" && root !== "libs")
|
|
1441
|
-
return false;
|
|
1442
|
-
if (area === "lib" || area === "ui")
|
|
1443
|
-
return true;
|
|
1444
|
-
return root === "apps" && area === "page";
|
|
1445
|
-
}
|
|
1446
|
-
function getComponentFileDeclarations(sourceFile) {
|
|
1447
|
-
const reExportedNames = new Set;
|
|
1448
|
-
for (const statement of sourceFile.statements) {
|
|
1449
|
-
if (ts8.isExportDeclaration(statement) && statement.exportClause && ts8.isNamedExports(statement.exportClause)) {
|
|
1450
|
-
for (const element of statement.exportClause.elements)
|
|
1451
|
-
reExportedNames.add((element.propertyName ?? element.name).text);
|
|
1452
|
-
}
|
|
1453
|
-
}
|
|
1454
|
-
const declarations = [];
|
|
1455
|
-
for (const statement of sourceFile.statements) {
|
|
1456
|
-
const isDefaultExport = isDefaultExportStatement(statement);
|
|
1457
|
-
const inlineExported = isExported(statement);
|
|
1458
|
-
const add = (name, kind, line) => declarations.push({ name, kind, line, exported: inlineExported || reExportedNames.has(name), isDefaultExport });
|
|
1459
|
-
if (ts8.isInterfaceDeclaration(statement))
|
|
1460
|
-
add(statement.name.text, "interface", getLine(sourceFile, statement));
|
|
1461
|
-
else if (ts8.isTypeAliasDeclaration(statement))
|
|
1462
|
-
add(statement.name.text, "type", getLine(sourceFile, statement));
|
|
1463
|
-
else if (ts8.isEnumDeclaration(statement))
|
|
1464
|
-
add(statement.name.text, "enum", getLine(sourceFile, statement));
|
|
1465
|
-
else if (ts8.isFunctionDeclaration(statement) && statement.name)
|
|
1466
|
-
add(statement.name.text, "function", getLine(sourceFile, statement));
|
|
1467
|
-
else if (ts8.isClassDeclaration(statement) && statement.name)
|
|
1468
|
-
add(statement.name.text, "class", getLine(sourceFile, statement));
|
|
1469
|
-
else if (ts8.isVariableStatement(statement)) {
|
|
1470
|
-
for (const declaration of statement.declarationList.declarations) {
|
|
1471
|
-
if (!ts8.isIdentifier(declaration.name))
|
|
1472
|
-
continue;
|
|
1473
|
-
const kind = isFunctionLikeInitializer(declaration.initializer) ? "function" : "variable";
|
|
1474
|
-
add(declaration.name.text, kind, getLine(sourceFile, declaration));
|
|
1475
|
-
}
|
|
1476
|
-
}
|
|
1477
|
-
}
|
|
1478
|
-
return declarations;
|
|
1479
|
-
}
|
|
1480
|
-
function getCompoundComponentNames(sourceFile) {
|
|
1481
|
-
const names = new Set;
|
|
1482
|
-
for (const statement of sourceFile.statements) {
|
|
1483
|
-
if (!ts8.isExpressionStatement(statement))
|
|
1484
|
-
continue;
|
|
1485
|
-
const { expression } = statement;
|
|
1486
|
-
if (!ts8.isBinaryExpression(expression) || expression.operatorToken.kind !== ts8.SyntaxKind.EqualsToken)
|
|
1487
|
-
continue;
|
|
1488
|
-
if (!ts8.isPropertyAccessExpression(expression.left) || !isPascalCaseName(expression.left.name.text))
|
|
1489
|
-
continue;
|
|
1490
|
-
names.add(expression.left.name.text);
|
|
1491
|
-
if (ts8.isIdentifier(expression.right) && isPascalCaseName(expression.right.text))
|
|
1492
|
-
names.add(expression.right.text);
|
|
1493
|
-
}
|
|
1494
|
-
return names;
|
|
1495
|
-
}
|
|
1496
|
-
function isComponentValueKind(kind) {
|
|
1497
|
-
return kind === "variable" || kind === "function" || kind === "class";
|
|
1498
|
-
}
|
|
1499
|
-
function isRestrictedInternalKind(kind) {
|
|
1500
|
-
return kind === "interface" || kind === "type" || kind === "function";
|
|
1501
|
-
}
|
|
1502
|
-
function isAllowedComponentExport(declaration, isPage) {
|
|
1503
|
-
if (isComponentValueKind(declaration.kind) && isPascalCaseName(declaration.name))
|
|
1504
|
-
return true;
|
|
1505
|
-
return isPage && RESERVED_ROUTE_CONFIG_EXPORTS.has(declaration.name);
|
|
1506
|
-
}
|
|
1507
|
-
function isPascalCaseName(name) {
|
|
1508
|
-
return /^[A-Z]/.test(name) && !/^[A-Z0-9_]+$/.test(name);
|
|
1509
|
-
}
|
|
1510
|
-
function isDefaultExportStatement(statement) {
|
|
1511
|
-
if (ts8.isExportAssignment(statement))
|
|
1512
|
-
return !statement.isExportEquals;
|
|
1513
|
-
if (!ts8.canHaveModifiers(statement))
|
|
1514
|
-
return false;
|
|
1515
|
-
return !!ts8.getModifiers(statement)?.some((modifier) => modifier.kind === ts8.SyntaxKind.DefaultKeyword);
|
|
1516
|
-
}
|
|
1517
|
-
function getBangCommentWarnings(sourceFile) {
|
|
1518
|
-
if (!isClientReachableFile(sourceFile.file))
|
|
1519
|
-
return [];
|
|
1520
|
-
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));
|
|
1521
|
-
}
|
|
1522
|
-
function isClientReachableFile(file) {
|
|
1523
|
-
if (/\.(test|spec)\.tsx?$/.test(file))
|
|
1524
|
-
return false;
|
|
1525
|
-
if (/\.(constant|store)\.ts$/.test(file))
|
|
1526
|
-
return true;
|
|
1527
|
-
if (/\.(Template|Unit|Util|View|Zone)\.tsx$/.test(file))
|
|
1528
|
-
return true;
|
|
1529
|
-
const segments = file.split("/");
|
|
1530
|
-
if (segments.includes("ui") || segments.includes("webkit"))
|
|
1531
|
-
return /\.tsx?$/.test(file);
|
|
1532
|
-
if (segments.includes("common"))
|
|
1533
|
-
return file.endsWith(".ts");
|
|
1534
|
-
return segments.includes("page") && file.endsWith(".tsx");
|
|
1535
|
-
}
|
|
1536
|
-
function getPlaceholderExportWarnings(sourceFile) {
|
|
1537
|
-
if (!sourceFile.file.endsWith("/index.ts") && !sourceFile.file.endsWith("/index.tsx"))
|
|
1538
|
-
return [];
|
|
1539
|
-
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));
|
|
1540
|
-
}
|
|
1541
|
-
function getDictionaryTextWarnings(sourceFile) {
|
|
1542
|
-
if (!sourceFile.file.endsWith(".dictionary.ts"))
|
|
1543
|
-
return [];
|
|
1544
|
-
const stalePatterns = [{ pattern: /\b[A-Z][A-Za-z0-9]* description\b/, label: "scaffold description text" }];
|
|
1545
|
-
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)));
|
|
1546
|
-
}
|
|
1547
|
-
function getGlobalMutationWarnings(sourceFile) {
|
|
1548
|
-
const warnings = [];
|
|
1549
|
-
for (const statement of sourceFile.sourceFile.statements) {
|
|
1550
|
-
const warn = (rule, message) => warnings.push(fileWarning(rule, "file", sourceFile.file, message, getLine(sourceFile.sourceFile, statement)));
|
|
1551
|
-
if (ts8.isModuleDeclaration(statement) && statement.name.getText(sourceFile.sourceFile) === "global")
|
|
1552
|
-
warn("akan.file.global-declaration", "Global declarations require an explicit low-level integration allowlist.");
|
|
1553
|
-
if (ts8.isInterfaceDeclaration(statement) && statement.name.text === "Window")
|
|
1554
|
-
warn("akan.file.window-augmentation", "Window augmentation should be isolated to approved browser integration files.");
|
|
1555
|
-
if (ts8.isExpressionStatement(statement) && statement.expression.getText(sourceFile.sourceFile).includes(".prototype."))
|
|
1556
|
-
warn("akan.file.prototype-mutation", "Prototype mutation should be avoided or isolated to approved low-level integration files.");
|
|
1557
|
-
}
|
|
1558
|
-
return warnings;
|
|
1559
|
-
}
|
|
1560
|
-
function getTopLevelDeclarations(sourceFile) {
|
|
1561
|
-
return sourceFile.sourceFile.statements.flatMap((statement) => getTopLevelDeclaration(sourceFile.sourceFile, statement));
|
|
1562
|
-
}
|
|
1563
|
-
function getTopLevelDeclaration(sourceFile, statement) {
|
|
1564
|
-
const line = getLine(sourceFile, statement);
|
|
1565
|
-
const declared = (name, kind, at = line) => ({
|
|
1566
|
-
name,
|
|
1567
|
-
kind,
|
|
1568
|
-
line: at,
|
|
1569
|
-
exported: isExported(statement),
|
|
1570
|
-
node: statement
|
|
1571
|
-
});
|
|
1572
|
-
if (ts8.isClassDeclaration(statement) && statement.name)
|
|
1573
|
-
return [declared(statement.name.text, "class")];
|
|
1574
|
-
if (ts8.isFunctionDeclaration(statement) && statement.name)
|
|
1575
|
-
return [declared(statement.name.text, "function")];
|
|
1576
|
-
if (ts8.isInterfaceDeclaration(statement))
|
|
1577
|
-
return [declared(statement.name.text, "interface")];
|
|
1578
|
-
if (ts8.isTypeAliasDeclaration(statement))
|
|
1579
|
-
return [declared(statement.name.text, "type")];
|
|
1580
|
-
if (ts8.isEnumDeclaration(statement))
|
|
1581
|
-
return [declared(statement.name.text, "enum")];
|
|
1582
|
-
if (ts8.isVariableStatement(statement))
|
|
1583
|
-
return statement.declarationList.declarations.filter((declaration) => ts8.isIdentifier(declaration.name)).map((declaration) => declared(declaration.name.text, "variable", getLine(sourceFile, declaration)));
|
|
1584
|
-
if (ts8.isExportDeclaration(statement))
|
|
1585
|
-
return [{ name: "export declaration", kind: "export", line, exported: true, node: statement }];
|
|
1586
|
-
return [];
|
|
1587
|
-
}
|
|
1588
|
-
function getConventionClassNames(suffix, model) {
|
|
1589
|
-
if (suffix === ".constant.ts")
|
|
1590
|
-
return [`${model}Input`, `${model}Object`, model, `Light${model}`, `${model}Insight`];
|
|
1591
|
-
if (suffix === ".document.ts")
|
|
1592
|
-
return [`${model}Filter`, model, `${model}Model`];
|
|
1593
|
-
if (suffix === ".service.ts")
|
|
1594
|
-
return [`${model}Service`];
|
|
1595
|
-
if (suffix === ".signal.ts")
|
|
1596
|
-
return [`${model}Internal`, `${model}Slice`, `${model}Endpoint`];
|
|
1597
|
-
if (suffix === ".store.ts")
|
|
1598
|
-
return [`${model}Store`];
|
|
1599
|
-
return [];
|
|
1600
|
-
}
|
|
1601
|
-
function isAllowedConventionDeclaration(suffix, modelName, declaration) {
|
|
1602
|
-
if (suffix === ".dictionary.ts")
|
|
1603
|
-
return isExportedConst(declaration) && declaration.name === "dictionary";
|
|
1604
|
-
if (declaration.kind !== "class")
|
|
1605
|
-
return false;
|
|
1606
|
-
if (getConventionClassNames(suffix, modelName).includes(declaration.name))
|
|
1607
|
-
return true;
|
|
1608
|
-
return suffix === ".constant.ts" && isEnumClassStatement(declaration.node.getSourceFile(), declaration.node);
|
|
1609
|
-
}
|
|
1610
|
-
function getConventionDescription(suffix, modelName) {
|
|
1611
|
-
if (suffix === ".dictionary.ts")
|
|
1612
|
-
return "export const dictionary";
|
|
1613
|
-
const names = [
|
|
1614
|
-
...getConventionClassNames(suffix, modelName),
|
|
1615
|
-
...suffix === ".constant.ts" ? ["enumOf classes"] : []
|
|
1616
|
-
];
|
|
1617
|
-
return names.length > 1 ? `${names.slice(0, -1).join(", ")}, or ${names.at(-1)}` : names[0];
|
|
1618
|
-
}
|
|
1619
|
-
var sysRootTypes = { apps: "app", libs: "lib" };
|
|
1620
|
-
function getSysRootEntry(file) {
|
|
1621
|
-
const segments = file.split("/");
|
|
1622
|
-
const root = segments[0];
|
|
1623
|
-
const name = segments[2];
|
|
1624
|
-
if (!root || !name || segments.length < 3)
|
|
1625
|
-
return null;
|
|
1626
|
-
const type = sysRootTypes[root];
|
|
1627
|
-
if (!type)
|
|
1628
|
-
return null;
|
|
1629
|
-
return { type, name, isDir: segments.length > 3 };
|
|
1630
|
-
}
|
|
1631
|
-
function getLibFacetRootFile(file) {
|
|
1632
|
-
const segments = file.split("/");
|
|
1633
|
-
if ((segments[0] === "libs" || segments[0] === "apps") && segments.length === 4 && segments[2] === "lib")
|
|
1634
|
-
return segments[3];
|
|
1635
|
-
return null;
|
|
1636
|
-
}
|
|
1637
|
-
function getModuleUiWarning(file) {
|
|
1638
|
-
if (!file.endsWith(".tsx"))
|
|
1639
|
-
return null;
|
|
1640
|
-
const moduleInfo = getModuleInfo(file);
|
|
1641
|
-
if (!moduleInfo)
|
|
1642
|
-
return null;
|
|
1643
|
-
const { moduleName, fileName, kind } = moduleInfo;
|
|
1644
|
-
const pascalName = toPascalCase(moduleName.replace(/^_+/, ""));
|
|
1645
|
-
const allowedSuffixes = kind === "database" ? ["Template", "Unit", "Util", "View", "Zone"] : kind === "service" ? ["Util", "Zone"] : ["Template", "Unit"];
|
|
1646
|
-
const allowedFileNames = new Set(allowedSuffixes.map((suffix) => `${pascalName}.${suffix}.tsx`));
|
|
1647
|
-
if (allowedFileNames.has(fileName) || fileName.endsWith(".test.tsx") || fileName.endsWith(".spec.tsx"))
|
|
1648
|
-
return null;
|
|
1649
|
-
return fileWarning("akan.layout.module-ui-file", "layout", file, `Unexpected ${kind} module UI filename "${fileName}". Expected one of: ${[...allowedFileNames].join(", ")}.`);
|
|
1650
|
-
}
|
|
1651
|
-
function getModuleInfo(file) {
|
|
1652
|
-
const segments = file.split("/");
|
|
1653
|
-
const libIndex = segments.indexOf("lib");
|
|
1654
|
-
if (libIndex < 0)
|
|
1655
|
-
return null;
|
|
1656
|
-
const moduleName = segments[libIndex + 1];
|
|
1657
|
-
if (moduleName === "__scalar") {
|
|
1658
|
-
if (segments.length !== libIndex + 4)
|
|
1659
|
-
return null;
|
|
1660
|
-
return { moduleName: segments[libIndex + 2], fileName: segments[libIndex + 3], kind: "scalar" };
|
|
1661
|
-
}
|
|
1662
|
-
if (segments.length !== libIndex + 3)
|
|
1663
|
-
return null;
|
|
1664
|
-
const fileName = segments[libIndex + 2];
|
|
1665
|
-
if (moduleName.startsWith("__"))
|
|
1666
|
-
return { moduleName, fileName, kind: "scalar" };
|
|
1667
|
-
if (moduleName.startsWith("_"))
|
|
1668
|
-
return { moduleName, fileName, kind: "service" };
|
|
1669
|
-
return { moduleName, fileName, kind: "database" };
|
|
1670
|
-
}
|
|
1671
|
-
function isExportedConst(declaration) {
|
|
1672
|
-
return declaration.exported && ts8.isVariableStatement(declaration.node) && (declaration.node.declarationList.flags & ts8.NodeFlags.Const) !== 0;
|
|
1673
|
-
}
|
|
1674
|
-
function isExported(node) {
|
|
1675
|
-
return !!(ts8.getCombinedModifierFlags(node) & ts8.ModifierFlags.Export);
|
|
1676
|
-
}
|
|
1677
|
-
function isFunctionLikeInitializer(node) {
|
|
1678
|
-
return !!node && (ts8.isArrowFunction(node) || ts8.isFunctionExpression(node));
|
|
1679
|
-
}
|
|
1680
|
-
function getBodyFingerprint(sourceFile, node) {
|
|
1681
|
-
if (!node)
|
|
1682
|
-
return;
|
|
1683
|
-
const normalizedBody = node.getText(sourceFile).replace(/\s+/g, " ").trim();
|
|
1684
|
-
if (normalizedBody.length < 80)
|
|
1685
|
-
return;
|
|
1686
|
-
return createHash("sha256").update(normalizedBody).digest("hex");
|
|
1687
|
-
}
|
|
1688
|
-
function shouldSkipPath(relativePath, isDirectory, ignoreFilter) {
|
|
1689
|
-
const ignorePath = isDirectory ? `${relativePath}/` : relativePath;
|
|
1690
|
-
return relativePath === ".git" || relativePath.includes("/.git/") || relativePath.includes("/node_modules/") || ignoreFilter.ignores(relativePath) || ignoreFilter.ignores(ignorePath);
|
|
1691
|
-
}
|
|
1692
|
-
async function isDirectory(absolutePath) {
|
|
1693
|
-
try {
|
|
1694
|
-
return (await stat(absolutePath)).isDirectory();
|
|
1695
|
-
} catch {
|
|
1696
|
-
return false;
|
|
1697
|
-
}
|
|
1698
|
-
}
|
|
1699
|
-
function getScriptKind(file) {
|
|
1700
|
-
return file.endsWith(".tsx") ? ts8.ScriptKind.TSX : ts8.ScriptKind.TS;
|
|
1701
|
-
}
|
|
1702
|
-
function getLine(sourceFile, node) {
|
|
1703
|
-
return sourceFile.getLineAndCharacterOfPosition(node.getStart(sourceFile)).line + 1;
|
|
1704
|
-
}
|
|
1705
|
-
function getRecommendedLineLimit(file) {
|
|
1706
|
-
if (file.endsWith(".service.ts"))
|
|
1707
|
-
return 500;
|
|
1708
|
-
if (file.endsWith(".Template.tsx") || file.endsWith(".Zone.tsx"))
|
|
1709
|
-
return 800;
|
|
1710
|
-
if (file.endsWith(".Util.tsx"))
|
|
1711
|
-
return 1000;
|
|
1712
|
-
return null;
|
|
1713
|
-
}
|
|
1714
|
-
function findPatternLines(content, pattern) {
|
|
1715
|
-
return content.split(/\r?\n/).flatMap((line, index) => pattern.test(line) ? [index + 1] : []);
|
|
1716
|
-
}
|
|
1717
|
-
function toPascalCase(value) {
|
|
1718
|
-
return value.replace(/(^|[-_./])([a-zA-Z0-9])/g, (_, __, char) => char.toUpperCase()).replace(/[-_./]/g, "");
|
|
1719
|
-
}
|
|
1720
|
-
function toPosix(value) {
|
|
1721
|
-
return value.split(path4.sep).join("/");
|
|
1722
|
-
}
|
|
1723
|
-
function groupBy(items, getKey) {
|
|
1724
|
-
const grouped = new Map;
|
|
1725
|
-
for (const item of items) {
|
|
1726
|
-
const key = getKey(item);
|
|
1727
|
-
grouped.set(key, [...grouped.get(key) ?? [], item]);
|
|
1728
|
-
}
|
|
1729
|
-
return grouped;
|
|
1730
|
-
}
|
|
1731
|
-
function compareWarnings(a, b) {
|
|
1732
|
-
return a.scope.localeCompare(b.scope) || (a.file ?? "").localeCompare(b.file ?? "") || (a.line ?? 0) - (b.line ?? 0) || a.rule.localeCompare(b.rule);
|
|
1733
|
-
}
|
|
1734
|
-
|
|
1735
|
-
// pkgs/@akanjs/cli/quality/quality.script.ts
|
|
1736
|
-
import { Logger } from "akanjs/common";
|
|
1737
|
-
class QualityScript extends script("quality", [WorkspaceRunner]) {
|
|
1738
|
-
async scan(workspace, format = "text") {
|
|
1739
|
-
const spinner = workspace.spinning("Scanning Akan code quality...");
|
|
1740
|
-
const result = await new AkanQualityScanner().scan(workspace.workspaceRoot);
|
|
1741
|
-
spinner.succeed(`Quality scan completed (${result.scannedFiles} files, ${result.warnings.length} warnings)`);
|
|
1742
|
-
Logger.rawLog(format === "json" ? JSON.stringify(result, null, 2) : formatQualityScanResult(result));
|
|
1743
|
-
}
|
|
1744
|
-
async ssr(workspace, format = "text") {
|
|
1745
|
-
const spinner = workspace.spinning("Measuring Akan server/client render balance...");
|
|
1746
|
-
const scanned = await new AkanQualityScanner().scan(workspace.workspaceRoot);
|
|
1747
|
-
const result = { ...scanned, warnings: scanned.warnings.filter((warning) => warning.scope === "ssr") };
|
|
1748
|
-
spinner.succeed(`SSR scan completed (${result.scannedFiles} files, ${result.warnings.length} warnings)`);
|
|
1749
|
-
Logger.rawLog(format === "json" ? JSON.stringify(result, null, 2) : formatSsrScanResult(result));
|
|
1750
|
-
}
|
|
1751
|
-
async baseline(workspace, { force = false } = {}) {
|
|
1752
|
-
const [appNames, libNames] = await workspace.getExecs();
|
|
1753
|
-
const execs = [
|
|
1754
|
-
...appNames.map((appName) => AppExecutor.from(workspace, appName)),
|
|
1755
|
-
...libNames.map((libName) => LibExecutor.from(workspace, libName))
|
|
1756
|
-
];
|
|
1757
|
-
const { fileName } = MaintainabilityBaseline;
|
|
1758
|
-
for (const exec of execs) {
|
|
1759
|
-
const contract = await this.workspaceRunner.maintainabilityContractOf(exec);
|
|
1760
|
-
const { result, violations } = await contract.seed({ force });
|
|
1761
|
-
const outcome = {
|
|
1762
|
-
written: `wrote ${fileName} with ${violations.length} entries`,
|
|
1763
|
-
kept: `kept the existing ${fileName} (${violations.length} current violations); --force rewrites it`,
|
|
1764
|
-
removed: `no violations, removed ${fileName}`,
|
|
1765
|
-
clean: "no violations"
|
|
1766
|
-
}[result];
|
|
1767
|
-
Logger.rawLog(`${contract.sysPath}: ${outcome}`);
|
|
1768
|
-
}
|
|
1769
|
-
}
|
|
1770
|
-
}
|
|
1771
|
-
|
|
1772
|
-
// pkgs/@akanjs/cli/quality/quality.command.ts
|
|
1773
|
-
class QualityCommand extends command("quality", [QualityScript], ({ public: target }) => ({
|
|
1774
|
-
quality: target({ desc: "Scan apps and libs for Akan code quality warnings" }).arg("action", String, { desc: "quality action", default: "scan", enum: ["scan", "ssr", "baseline"] }).option("format", String, { desc: "output format", default: "text", enum: ["text", "json"] }).option("force", Boolean, { flag: "F", desc: "baseline: rewrite an existing akan.baseline.json", default: false }).with(Workspace).exec(async function(action, format, force, workspace) {
|
|
1775
|
-
if (action === "scan")
|
|
1776
|
-
await this.qualityScript.scan(workspace, format);
|
|
1777
|
-
else if (action === "ssr")
|
|
1778
|
-
await this.qualityScript.ssr(workspace, format);
|
|
1779
|
-
else if (action === "baseline")
|
|
1780
|
-
await this.qualityScript.baseline(workspace, { force });
|
|
1781
|
-
else
|
|
1782
|
-
throw new Error(`Unknown quality action: ${action}. Use "scan", "ssr" or "baseline".`);
|
|
1783
|
-
})
|
|
1784
|
-
})) {
|
|
1785
|
-
}
|
|
1786
|
-
export {
|
|
1787
|
-
QualityCommand
|
|
1788
|
-
};
|