Repository navigation
Expand file tree
/
Copy pathruntime-cycles.mjs
More file actions
76 lines (75 loc) · 2.56 KB
/
Copy pathruntime-cycles.mjs
File metadata and controls
76 lines (75 loc) · 2.56 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
import fs from "node:fs"
import path from "node:path"
import { pathToFileURL } from "node:url"
const { default: ts } = await import(
pathToFileURL(
process.env.WIRECAT_TYPESCRIPT_API ??
(() => {
throw new Error("Set WIRECAT_TYPESCRIPT_API to TypeScript 5.9.3 lib/typescript.js")
})(),
).href
)
const walk = (d) =>
fs
.readdirSync(d, { withFileTypes: true })
.flatMap((n) => (n.isDirectory() ? walk(path.join(d, n.name)) : [path.join(d, n.name)]))
const files = walk("src").filter((f) => f.endsWith(".ts") && !f.endsWith(".test.ts"))
const graph = new Map()
for (const file of files) {
const s = fs.readFileSync(file, "utf8"),
a = ts.createSourceFile(file, s, 99, true)
const edges = []
for (const n of a.statements) {
if (ts.isImportDeclaration(n) && !n.importClause?.isTypeOnly) {
if (
n.importClause?.namedBindings &&
ts.isNamedImports(n.importClause.namedBindings) &&
n.importClause.namedBindings.elements.every((e) => e.isTypeOnly) &&
!n.importClause.name
)
continue
const p = n.moduleSpecifier.text
if (p.startsWith(".")) edges.push(path.normalize(path.join(path.dirname(file), p.replace(/\.js$/, ".ts"))))
}
if (ts.isExportDeclaration(n) && !n.isTypeOnly && n.moduleSpecifier) {
if (n.exportClause && ts.isNamedExports(n.exportClause) && n.exportClause.elements.every((e) => e.isTypeOnly))
continue
const p = n.moduleSpecifier.text
if (p.startsWith(".")) edges.push(path.normalize(path.join(path.dirname(file), p.replace(/\.js$/, ".ts"))))
}
}
graph.set(file, edges)
}
let index = 0
const indices = new Map(),
low = new Map(),
active = new Set(),
stack = [],
cycles = []
const visit = (f) => {
indices.set(f, index)
low.set(f, index++)
stack.push(f)
active.add(f)
for (const next of graph.get(f) ?? []) {
if (!graph.has(next)) continue
if (!indices.has(next)) {
visit(next)
low.set(f, Math.min(low.get(f), low.get(next)))
} else if (active.has(next)) low.set(f, Math.min(low.get(f), indices.get(next)))
}
if (low.get(f) === indices.get(f)) {
const group = []
let at
do {
at = stack.pop()
active.delete(at)
group.push(at)
} while (at !== f)
if (group.length > 1) cycles.push(group)
}
}
for (const f of files) if (!indices.has(f)) visit(f)
const relevantCycles = cycles.filter((c) => c.some((f) => f.startsWith("src/store/") || f.startsWith("src/services/")))
process.stdout.write(`${JSON.stringify(relevantCycles, null, 2)}\n`)
if (relevantCycles.length) process.exitCode = 1