@akanjs/devkit 3.2.0-rc.31 → 3.2.0-rc.32

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.
@@ -1,8 +1,7 @@
1
1
  import { createHash } from "node:crypto";
2
- import { readdir, readFile, stat } from "node:fs/promises";
2
+ import { readFile } from "node:fs/promises";
3
3
  import path from "node:path";
4
4
  import { RESERVED_ROUTE_CONFIG_EXPORTS } from "akanjs/common";
5
- import ignore from "ignore";
6
5
  import ts from "typescript";
7
6
  import {
8
7
  facetIndexShadowOf,
@@ -20,6 +19,7 @@ import { KindBranchScanner } from "./kindBranchScanner";
20
19
  import { MaintainabilityExceptionScanner } from "./maintainabilityExceptionScanner";
21
20
  import { fileWarning, formatSsrBalance, type SsrBalanceEntry, SsrScanner } from "./ssrScanner";
22
21
  import { TestOnlyExportScanner } from "./testOnlyExportScanner";
22
+ import { WorkspaceSourceFiles } from "./workspaceSourceFiles";
23
23
 
24
24
  type QualitySeverity = "warning";
25
25
  type QualityScope = "global" | "file" | "convention" | "layout" | "ssr" | "agent" | "comment";
@@ -184,11 +184,10 @@ function getRuleFix(rule: string): string | undefined {
184
184
 
185
185
  export class AkanQualityScanner {
186
186
  async scan(workspaceRoot: string): Promise<QualityScanResult> {
187
- const targetFiles = await this.#collectTargetFiles(workspaceRoot);
187
+ const workspaceFiles = new WorkspaceSourceFiles(workspaceRoot);
188
+ const targetFiles = await workspaceFiles.collect();
188
189
  const sourceFiles = await Promise.all(
189
- targetFiles
190
- .filter((file) => !AbstractDoc.isAbstractPath(file))
191
- .map((file) => this.#readSourceFile(workspaceRoot, file)),
190
+ targetFiles.filter((file) => !AbstractDoc.isAbstractPath(file)).map((file) => workspaceFiles.read(file)),
192
191
  );
193
192
  const abstractFiles = await Promise.all(
194
193
  targetFiles
@@ -221,56 +220,18 @@ export class AkanQualityScanner {
221
220
  };
222
221
  }
223
222
 
224
- async #collectTargetFiles(workspaceRoot: string) {
225
- const ignoreFilter = ignore().add(await this.#readGitIgnore(workspaceRoot));
226
- const files: string[] = [];
227
- for (const targetRoot of ["apps", "libs"]) {
228
- const absoluteTargetRoot = path.join(workspaceRoot, targetRoot);
229
- if (!(await isDirectory(absoluteTargetRoot))) continue;
230
- await this.#walkTargetFiles(workspaceRoot, absoluteTargetRoot, ignoreFilter, files);
231
- }
232
- return files.sort((a, b) => (a < b ? -1 : a > b ? 1 : 0));
233
- }
234
-
235
- async #readGitIgnore(workspaceRoot: string) {
236
- const gitIgnorePath = path.join(workspaceRoot, ".gitignore");
237
- if (!(await Bun.file(gitIgnorePath).exists())) return [];
238
- return (await readFile(gitIgnorePath, "utf8")).split(/\r?\n/);
239
- }
240
-
241
- async #walkTargetFiles(
242
- workspaceRoot: string,
243
- currentPath: string,
244
- ignoreFilter: ReturnType<typeof ignore>,
245
- files: string[],
246
- ) {
247
- const entries = await readdir(currentPath, { withFileTypes: true });
248
- for (const entry of entries) {
249
- const absolutePath = path.join(currentPath, entry.name);
250
- const relativePath = toPosix(path.relative(workspaceRoot, absolutePath));
251
- if (shouldSkipPath(relativePath, entry.isDirectory(), ignoreFilter)) continue;
252
-
253
- if (entry.isDirectory()) {
254
- await this.#walkTargetFiles(workspaceRoot, absolutePath, ignoreFilter, files);
255
- continue;
256
- }
257
- if ((relativePath.endsWith(".ts") || relativePath.endsWith(".tsx")) && !relativePath.endsWith(".d.ts")) {
258
- files.push(relativePath);
259
- } else if (AbstractDoc.isAbstractPath(relativePath)) {
260
- files.push(relativePath);
261
- }
262
- }
263
- }
264
-
265
- async #readSourceFile(workspaceRoot: string, file: string): Promise<SourceFileInfo> {
266
- const absolutePath = path.join(workspaceRoot, file);
267
- const content = await readFile(absolutePath, "utf8");
268
- return {
269
- file,
270
- absolutePath,
271
- content,
272
- sourceFile: ts.createSourceFile(file, content, ts.ScriptTarget.Latest, true, getScriptKind(file)),
273
- };
223
+ //? An SSR rule reads the file, its module folder and the signals its fetch calls name, which sit in its own app or
224
+ //? lib or under libs/, so no other file can change a warning on a file under `dirs`.
225
+ async scanSsr(workspaceRoot: string, dirs: string[]): Promise<QualityWarning[]> {
226
+ const workspaceFiles = new WorkspaceSourceFiles(workspaceRoot);
227
+ const read = (file: string) =>
228
+ !AbstractDoc.isAbstractPath(file) &&
229
+ (dirs.some((dir) => file.startsWith(`${dir}/`)) || /^libs\/[^/]+\/lib\/.+\.signal\.ts$/.test(file));
230
+ const files = (await workspaceFiles.collect([...dirs, "libs"])).filter(read);
231
+ const { warnings } = new SsrScanner().scan(await Promise.all(files.map((file) => workspaceFiles.read(file))));
232
+ return warnings
233
+ .map((warning) => ({ ...warning, fix: warning.fix ?? getRuleFix(warning.rule) }))
234
+ .sort(compareWarnings);
274
235
  }
275
236
 
276
237
  async #readTextFile(workspaceRoot: string, file: string): Promise<TextFileInfo> {
@@ -918,29 +879,6 @@ function getBodyFingerprint(sourceFile: ts.SourceFile, node: ts.Node | undefined
918
879
  return createHash("sha256").update(normalizedBody).digest("hex");
919
880
  }
920
881
 
921
- function shouldSkipPath(relativePath: string, isDirectory: boolean, ignoreFilter: ReturnType<typeof ignore>) {
922
- const ignorePath = isDirectory ? `${relativePath}/` : relativePath;
923
- return (
924
- relativePath === ".git" ||
925
- relativePath.includes("/.git/") ||
926
- relativePath.includes("/node_modules/") ||
927
- ignoreFilter.ignores(relativePath) ||
928
- ignoreFilter.ignores(ignorePath)
929
- );
930
- }
931
-
932
- async function isDirectory(absolutePath: string) {
933
- try {
934
- return (await stat(absolutePath)).isDirectory();
935
- } catch {
936
- return false;
937
- }
938
- }
939
-
940
- function getScriptKind(file: string) {
941
- return file.endsWith(".tsx") ? ts.ScriptKind.TSX : ts.ScriptKind.TS;
942
- }
943
-
944
882
  function getLine(sourceFile: ts.SourceFile, node: ts.Node) {
945
883
  return sourceFile.getLineAndCharacterOfPosition(node.getStart(sourceFile)).line + 1;
946
884
  }
@@ -960,10 +898,6 @@ function toPascalCase(value: string) {
960
898
  return value.replace(/(^|[-_./])([a-zA-Z0-9])/g, (_, __, char: string) => char.toUpperCase()).replace(/[-_./]/g, "");
961
899
  }
962
900
 
963
- function toPosix(value: string) {
964
- return value.split(path.sep).join("/");
965
- }
966
-
967
901
  function groupBy<T>(items: T[], getKey: (item: T) => string) {
968
902
  const grouped = new Map<string, T[]>();
969
903
  for (const item of items) {
@@ -0,0 +1,82 @@
1
+ import { readdir, readFile, stat } from "node:fs/promises";
2
+ import path from "node:path";
3
+ import ignore from "ignore";
4
+ import ts from "typescript";
5
+ import { AbstractDoc } from "./abstractDoc";
6
+ import type { SourceFileInfo } from "./qualityScanner";
7
+
8
+ type IgnoreFilter = ReturnType<typeof ignore>;
9
+
10
+ export class WorkspaceSourceFiles {
11
+ readonly #workspaceRoot: string;
12
+
13
+ constructor(workspaceRoot: string) {
14
+ this.#workspaceRoot = workspaceRoot;
15
+ }
16
+
17
+ async collect(dirs: string[] = ["apps", "libs"]) {
18
+ const ignoreFilter = ignore().add(await this.#readGitIgnore());
19
+ const files = new Set<string>();
20
+ for (const dir of dirs) {
21
+ const absoluteDir = path.join(this.#workspaceRoot, dir);
22
+ if (await WorkspaceSourceFiles.#isDirectory(absoluteDir)) await this.#walk(absoluteDir, ignoreFilter, files);
23
+ }
24
+ return [...files].sort((a, b) => (a < b ? -1 : a > b ? 1 : 0));
25
+ }
26
+
27
+ async read(file: string): Promise<SourceFileInfo> {
28
+ const absolutePath = path.join(this.#workspaceRoot, file);
29
+ const content = await readFile(absolutePath, "utf8");
30
+ const scriptKind = file.endsWith(".tsx") ? ts.ScriptKind.TSX : ts.ScriptKind.TS;
31
+ return {
32
+ file,
33
+ absolutePath,
34
+ content,
35
+ sourceFile: ts.createSourceFile(file, content, ts.ScriptTarget.Latest, true, scriptKind),
36
+ };
37
+ }
38
+
39
+ async #readGitIgnore() {
40
+ const gitIgnorePath = path.join(this.#workspaceRoot, ".gitignore");
41
+ if (!(await Bun.file(gitIgnorePath).exists())) return [];
42
+ return (await readFile(gitIgnorePath, "utf8")).split(/\r?\n/);
43
+ }
44
+
45
+ async #walk(currentPath: string, ignoreFilter: IgnoreFilter, files: Set<string>) {
46
+ const entries = await readdir(currentPath, { withFileTypes: true });
47
+ for (const entry of entries) {
48
+ const absolutePath = path.join(currentPath, entry.name);
49
+ const relativePath = path.relative(this.#workspaceRoot, absolutePath).split(path.sep).join("/");
50
+ if (WorkspaceSourceFiles.#shouldSkip(relativePath, entry.isDirectory(), ignoreFilter)) continue;
51
+
52
+ if (entry.isDirectory()) {
53
+ await this.#walk(absolutePath, ignoreFilter, files);
54
+ continue;
55
+ }
56
+ if ((relativePath.endsWith(".ts") || relativePath.endsWith(".tsx")) && !relativePath.endsWith(".d.ts")) {
57
+ files.add(relativePath);
58
+ } else if (AbstractDoc.isAbstractPath(relativePath)) {
59
+ files.add(relativePath);
60
+ }
61
+ }
62
+ }
63
+
64
+ static #shouldSkip(relativePath: string, isDirectory: boolean, ignoreFilter: IgnoreFilter) {
65
+ const ignorePath = isDirectory ? `${relativePath}/` : relativePath;
66
+ return (
67
+ relativePath === ".git" ||
68
+ relativePath.includes("/.git/") ||
69
+ relativePath.includes("/node_modules/") ||
70
+ ignoreFilter.ignores(relativePath) ||
71
+ ignoreFilter.ignores(ignorePath)
72
+ );
73
+ }
74
+
75
+ static async #isDirectory(absolutePath: string) {
76
+ try {
77
+ return (await stat(absolutePath)).isDirectory();
78
+ } catch {
79
+ return false;
80
+ }
81
+ }
82
+ }
@@ -31,6 +31,28 @@ describe("ProjectTypecheck", () => {
31
31
  expect((error as Error).message).not.toContain("old.test.ts");
32
32
  }, 60_000);
33
33
 
34
+ test("checks a package whose tsconfig names no include, caching outside it", async () => {
35
+ const root = await makeTempRoot();
36
+ const dir = path.join(root, "pkgs/tool");
37
+ await write(
38
+ path.join(dir, "tsconfig.json"),
39
+ JSON.stringify({ compilerOptions: { strict: true, types: [], target: "esnext", module: "esnext" } }),
40
+ );
41
+ await write(path.join(dir, "index.ts"), 'export const port: number = "8282";\n');
42
+ const cacheDir = path.join(root, ".akan/typecheck/pkgs/tool");
43
+
44
+ const error = await new ProjectTypecheck(dir, root, { ...process.env })
45
+ .checkIncremental(path.join(dir, "tsconfig.json"), cacheDir, "records")
46
+ .catch((e: unknown) => e);
47
+
48
+ expect(error).toBeInstanceOf(TypecheckFailure);
49
+ expect((error as TypecheckFailure).records.map(({ file, code }) => [file, code])).toEqual([
50
+ ["pkgs/tool/index.ts", "TS2322"],
51
+ ]);
52
+ expect(await Bun.file(path.join(cacheDir, "tsconfig.tsbuildinfo")).exists()).toBe(true);
53
+ expect(await Bun.file(path.join(dir, "tsconfig.tsbuildinfo")).exists()).toBe(false);
54
+ }, 60_000);
55
+
34
56
  test("hands back one record per diagnostic when asked for records", async () => {
35
57
  const { root, dir } = await project();
36
58
  const error = await new ProjectTypecheck(dir, root, { ...process.env })
@@ -50,13 +50,21 @@ export class ProjectTypecheck {
50
50
  return tsconfigPath;
51
51
  }
52
52
 
53
- async check(tsconfigPath: string, report: "pretty" | "records" = "pretty") {
53
+ //? The project's own tsconfig, not one extending it from the cache folder: there the default `include` would
54
+ //? resolve from that folder, which holds no source.
55
+ async checkIncremental(tsconfigPath: string, cacheDir: string, report: "pretty" | "records" = "pretty") {
56
+ await mkdir(cacheDir, { recursive: true });
57
+ await this.check(tsconfigPath, report, path.join(cacheDir, "tsconfig.tsbuildinfo"));
58
+ }
59
+
60
+ async check(tsconfigPath: string, report: "pretty" | "records" = "pretty", tsBuildInfoFile?: string) {
54
61
  const proc = Bun.spawn([process.execPath, await ProjectTypecheck.workerEntry(this.workspaceRoot)], {
55
62
  cwd: this.workspaceRoot,
56
63
  env: {
57
64
  ...this.env,
58
65
  AKAN_COMMAND_TYPE: "typecheck",
59
66
  AKAN_TYPECHECK_TSCONFIG: tsconfigPath,
67
+ ...(tsBuildInfoFile ? { AKAN_TYPECHECK_BUILDINFO: tsBuildInfoFile } : {}),
60
68
  ...(report === "records" ? { AKAN_TYPECHECK_FORMAT: "json", AKAN_TYPECHECK_ROOT: this.workspaceRoot } : {}),
61
69
  },
62
70
  stdout: "pipe",
@@ -167,12 +167,13 @@ export class TypeChecker {
167
167
  }
168
168
  }
169
169
 
170
- static checkProject(configPath: string): ProjectTypecheckResult {
170
+ static checkProject(configPath: string, overrides: ts.CompilerOptions = {}): ProjectTypecheckResult {
171
171
  const parsedConfig = TypeChecker.parseConfig(configPath);
172
- const host = ts.createIncrementalCompilerHost(parsedConfig.options);
172
+ const options = { ...parsedConfig.options, ...overrides };
173
+ const host = ts.createIncrementalCompilerHost(options);
173
174
  const builderProgram = ts.createIncrementalProgram({
174
175
  rootNames: parsedConfig.fileNames,
175
- options: parsedConfig.options,
176
+ options,
176
177
  projectReferences: parsedConfig.projectReferences,
177
178
  configFileParsingDiagnostics: parsedConfig.errors,
178
179
  host,
@@ -24,7 +24,11 @@ try {
24
24
 
25
25
  const configPath = process.env.AKAN_TYPECHECK_TSCONFIG;
26
26
  if (!configPath) throw new Error("AKAN_TYPECHECK_TSCONFIG is required");
27
- const result = TypeChecker.checkProject(configPath);
27
+ const tsBuildInfoFile = process.env.AKAN_TYPECHECK_BUILDINFO;
28
+ const result = TypeChecker.checkProject(
29
+ configPath,
30
+ tsBuildInfoFile ? { noEmit: true, incremental: true, tsBuildInfoFile } : {},
31
+ );
28
32
  if (process.env.AKAN_TYPECHECK_FORMAT === "json") {
29
33
  //? Not process.cwd(): that is the realpath (/private/var on macOS) while TypeScript keeps the spelling it was given.
30
34
  const root = process.env.AKAN_TYPECHECK_ROOT ?? process.cwd();