@viberails/graph 0.1.0

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/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Alex Casasola
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/dist/index.cjs ADDED
@@ -0,0 +1,428 @@
1
+ "use strict";
2
+ var __defProp = Object.defineProperty;
3
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
4
+ var __getOwnPropNames = Object.getOwnPropertyNames;
5
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
6
+ var __export = (target, all) => {
7
+ for (var name in all)
8
+ __defProp(target, name, { get: all[name], enumerable: true });
9
+ };
10
+ var __copyProps = (to, from, except, desc) => {
11
+ if (from && typeof from === "object" || typeof from === "function") {
12
+ for (let key of __getOwnPropNames(from))
13
+ if (!__hasOwnProp.call(to, key) && key !== except)
14
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
15
+ }
16
+ return to;
17
+ };
18
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
19
+
20
+ // src/index.ts
21
+ var index_exports = {};
22
+ __export(index_exports, {
23
+ buildImportGraph: () => buildImportGraph,
24
+ checkBoundaries: () => checkBoundaries,
25
+ detectCycles: () => detectCycles,
26
+ inferBoundaries: () => inferBoundaries,
27
+ parseImports: () => parseImports,
28
+ resolveImport: () => resolveImport
29
+ });
30
+ module.exports = __toCommonJS(index_exports);
31
+
32
+ // src/build-graph.ts
33
+ var import_node_path2 = require("path");
34
+ var import_ts_morph2 = require("ts-morph");
35
+
36
+ // src/detect-cycles.ts
37
+ function detectCycles(edges) {
38
+ const graph = /* @__PURE__ */ new Map();
39
+ const nodes = /* @__PURE__ */ new Set();
40
+ for (const { source, target } of edges) {
41
+ nodes.add(source);
42
+ nodes.add(target);
43
+ const neighbors = graph.get(source);
44
+ if (neighbors) {
45
+ neighbors.push(target);
46
+ } else {
47
+ graph.set(source, [target]);
48
+ }
49
+ }
50
+ const WHITE = 0;
51
+ const GRAY = 1;
52
+ const BLACK = 2;
53
+ const color = /* @__PURE__ */ new Map();
54
+ for (const node of nodes) {
55
+ color.set(node, WHITE);
56
+ }
57
+ const cycles = [];
58
+ const path = [];
59
+ function dfs(node) {
60
+ color.set(node, GRAY);
61
+ path.push(node);
62
+ const neighbors = graph.get(node) ?? [];
63
+ for (const neighbor of neighbors) {
64
+ const c = color.get(neighbor);
65
+ if (c === GRAY) {
66
+ const cycleStart = path.indexOf(neighbor);
67
+ if (cycleStart !== -1) {
68
+ cycles.push(path.slice(cycleStart));
69
+ }
70
+ } else if (c === WHITE) {
71
+ dfs(neighbor);
72
+ }
73
+ }
74
+ path.pop();
75
+ color.set(node, BLACK);
76
+ }
77
+ for (const node of nodes) {
78
+ if (color.get(node) === WHITE) {
79
+ dfs(node);
80
+ }
81
+ }
82
+ return cycles;
83
+ }
84
+
85
+ // src/parse-imports.ts
86
+ var import_ts_morph = require("ts-morph");
87
+ var SKIP_EXTENSIONS = /* @__PURE__ */ new Set([
88
+ ".css",
89
+ ".scss",
90
+ ".less",
91
+ ".sass",
92
+ ".png",
93
+ ".svg",
94
+ ".jpg",
95
+ ".jpeg",
96
+ ".gif",
97
+ ".ico",
98
+ ".webp",
99
+ ".json",
100
+ ".woff",
101
+ ".woff2",
102
+ ".ttf",
103
+ ".eot"
104
+ ]);
105
+ function shouldSkip(specifier) {
106
+ const dotIndex = specifier.lastIndexOf(".");
107
+ if (dotIndex === -1) return false;
108
+ return SKIP_EXTENSIONS.has(specifier.slice(dotIndex).toLowerCase());
109
+ }
110
+ function parseImports(sourceFile) {
111
+ const edges = [];
112
+ const filePath = sourceFile.getFilePath();
113
+ for (const decl of sourceFile.getImportDeclarations()) {
114
+ const specifier = decl.getModuleSpecifierValue();
115
+ if (shouldSkip(specifier)) continue;
116
+ edges.push({
117
+ source: filePath,
118
+ target: specifier,
119
+ specifier,
120
+ typeOnly: decl.isTypeOnly(),
121
+ dynamic: false,
122
+ line: decl.getStartLineNumber()
123
+ });
124
+ }
125
+ for (const decl of sourceFile.getExportDeclarations()) {
126
+ const specifier = decl.getModuleSpecifierValue();
127
+ if (!specifier || shouldSkip(specifier)) continue;
128
+ edges.push({
129
+ source: filePath,
130
+ target: specifier,
131
+ specifier,
132
+ typeOnly: decl.isTypeOnly(),
133
+ dynamic: false,
134
+ line: decl.getStartLineNumber()
135
+ });
136
+ }
137
+ for (const call of sourceFile.getDescendantsOfKind(import_ts_morph.SyntaxKind.CallExpression)) {
138
+ if (call.getExpression().getKind() !== import_ts_morph.SyntaxKind.ImportKeyword) continue;
139
+ const args = call.getArguments();
140
+ if (args.length === 0) continue;
141
+ const arg = args[0];
142
+ if (arg.getKind() !== import_ts_morph.SyntaxKind.StringLiteral) continue;
143
+ const specifier = arg.getText().slice(1, -1);
144
+ if (shouldSkip(specifier)) continue;
145
+ edges.push({
146
+ source: filePath,
147
+ target: specifier,
148
+ specifier,
149
+ typeOnly: false,
150
+ dynamic: true,
151
+ line: call.getStartLineNumber()
152
+ });
153
+ }
154
+ return edges;
155
+ }
156
+
157
+ // src/resolve-import.ts
158
+ var import_node_module = require("module");
159
+ var import_node_path = require("path");
160
+ var BUILTINS = /* @__PURE__ */ new Set([...import_node_module.builtinModules, ...import_node_module.builtinModules.map((m) => `node:${m}`)]);
161
+ function resolveImport(specifier, fromFile, project, workspacePackages) {
162
+ if (BUILTINS.has(specifier)) {
163
+ return { kind: "builtin" };
164
+ }
165
+ const wsMatch = workspacePackages.find(
166
+ (pkg) => specifier === pkg.name || specifier.startsWith(`${pkg.name}/`)
167
+ );
168
+ if (wsMatch) {
169
+ return {
170
+ kind: "workspace",
171
+ resolvedPath: wsMatch.path,
172
+ packageName: wsMatch.name
173
+ };
174
+ }
175
+ if (specifier.startsWith(".") || specifier.startsWith("/")) {
176
+ const resolved = tryResolve(specifier, fromFile, project);
177
+ if (resolved) {
178
+ return { kind: "internal", resolvedPath: resolved };
179
+ }
180
+ return { kind: "unresolved" };
181
+ }
182
+ const aliasResolved = tryResolve(specifier, fromFile, project);
183
+ if (aliasResolved) {
184
+ return { kind: "internal", resolvedPath: aliasResolved };
185
+ }
186
+ return { kind: "external", packageName: specifier.split("/")[0] };
187
+ }
188
+ function tryResolve(specifier, fromFile, project) {
189
+ const sourceFile = project.getSourceFile(fromFile);
190
+ if (sourceFile) {
191
+ const dir = (0, import_node_path.dirname)(fromFile);
192
+ const extensions = ["", ".ts", ".tsx", ".js", ".jsx", "/index.ts", "/index.tsx", "/index.js"];
193
+ for (const ext of extensions) {
194
+ const candidate = specifier.startsWith(".") ? (0, import_node_path.resolve)(dir, specifier + ext) : specifier + ext;
195
+ const found = project.getSourceFile(candidate);
196
+ if (found) return found.getFilePath();
197
+ }
198
+ }
199
+ return void 0;
200
+ }
201
+
202
+ // src/build-graph.ts
203
+ var DEFAULT_IGNORE = [
204
+ "**/node_modules/**",
205
+ "**/dist/**",
206
+ "**/build/**",
207
+ "**/.next/**",
208
+ "**/.nuxt/**",
209
+ "**/coverage/**"
210
+ ];
211
+ async function buildImportGraph(projectRoot, options) {
212
+ const packages = options?.packages ?? [];
213
+ const shouldDetectCycles = options?.detectCycles !== false;
214
+ const ignorePatterns = options?.ignore ?? DEFAULT_IGNORE;
215
+ const project = new import_ts_morph2.Project({
216
+ tsConfigFilePath: options?.tsconfigPath,
217
+ skipAddingFilesFromTsConfig: true
218
+ });
219
+ const sourceGlobs = buildSourceGlobs(projectRoot, packages, ignorePatterns);
220
+ for (const glob of sourceGlobs) {
221
+ project.addSourceFilesAtPaths(glob);
222
+ }
223
+ const nodes = [];
224
+ const allEdges = [];
225
+ for (const sourceFile of project.getSourceFiles()) {
226
+ const filePath = sourceFile.getFilePath();
227
+ const ownerPkg = packages.find((pkg) => filePath.startsWith(pkg.path + "/"));
228
+ nodes.push({
229
+ filePath,
230
+ relativePath: (0, import_node_path2.relative)(ownerPkg?.path ?? projectRoot, filePath),
231
+ packageName: ownerPkg?.name
232
+ });
233
+ const rawEdges = parseImports(sourceFile);
234
+ for (const edge of rawEdges) {
235
+ const resolved = resolveImport(edge.target, filePath, project, packages);
236
+ if (resolved.resolvedPath) {
237
+ allEdges.push({
238
+ ...edge,
239
+ target: resolved.resolvedPath
240
+ });
241
+ } else if (resolved.kind === "external" || resolved.kind === "builtin") {
242
+ allEdges.push(edge);
243
+ }
244
+ }
245
+ }
246
+ let cycles = [];
247
+ if (shouldDetectCycles) {
248
+ const internalEdges = allEdges.filter(
249
+ (e) => e.target.startsWith("/") && !e.target.includes("node_modules")
250
+ );
251
+ cycles = detectCycles(internalEdges);
252
+ }
253
+ return { nodes, edges: allEdges, packages, cycles };
254
+ }
255
+ function buildSourceGlobs(projectRoot, packages, _ignore) {
256
+ const globs = [];
257
+ if (packages.length > 0) {
258
+ for (const pkg of packages) {
259
+ globs.push(`${pkg.path}/src/**/*.{ts,tsx,js,jsx}`);
260
+ }
261
+ } else {
262
+ globs.push(`${projectRoot}/src/**/*.{ts,tsx,js,jsx}`);
263
+ globs.push(`${projectRoot}/**/*.{ts,tsx,js,jsx}`);
264
+ }
265
+ return globs;
266
+ }
267
+
268
+ // src/check-boundaries.ts
269
+ function checkBoundaries(graph, rules) {
270
+ if (rules.length === 0) return [];
271
+ const isMonorepo = graph.packages.length > 0;
272
+ const nodeIndex = buildNodeIndex(graph.nodes);
273
+ const packagePathIndex = /* @__PURE__ */ new Map();
274
+ for (const pkg of graph.packages) {
275
+ packagePathIndex.set(pkg.path, pkg.name);
276
+ }
277
+ const denyRules = rules.filter((r) => !r.allow);
278
+ const allowRules = rules.filter((r) => r.allow);
279
+ const violations = [];
280
+ for (const edge of graph.edges) {
281
+ if (!edge.target.startsWith("/")) continue;
282
+ const sourceNode = nodeIndex.get(edge.source);
283
+ if (!sourceNode) continue;
284
+ const targetNode = nodeIndex.get(edge.target);
285
+ let targetZone;
286
+ if (isMonorepo) {
287
+ targetZone = targetNode?.packageName ?? packagePathIndex.get(edge.target);
288
+ } else {
289
+ if (targetNode) {
290
+ targetZone = getTopLevelDirectory(targetNode.relativePath);
291
+ }
292
+ }
293
+ const sourceZone = isMonorepo ? sourceNode.packageName : getTopLevelDirectory(sourceNode.relativePath);
294
+ if (!sourceZone || !targetZone || sourceZone === targetZone) continue;
295
+ const isAllowed = allowRules.some((r) => r.from === sourceZone && r.to === targetZone);
296
+ if (isAllowed) continue;
297
+ const matchedRule = denyRules.find((r) => r.from === sourceZone && r.to === targetZone);
298
+ if (matchedRule) {
299
+ violations.push({
300
+ file: edge.source,
301
+ line: edge.line,
302
+ specifier: edge.specifier,
303
+ resolvedTo: edge.target,
304
+ rule: matchedRule
305
+ });
306
+ }
307
+ }
308
+ return violations;
309
+ }
310
+ function buildNodeIndex(nodes) {
311
+ const index = /* @__PURE__ */ new Map();
312
+ for (const node of nodes) {
313
+ index.set(node.filePath, node);
314
+ }
315
+ return index;
316
+ }
317
+ function getTopLevelDirectory(relativePath) {
318
+ const normalized = relativePath.startsWith("src/") ? relativePath.slice(4) : relativePath;
319
+ const slashIndex = normalized.indexOf("/");
320
+ if (slashIndex === -1) return void 0;
321
+ return normalized.slice(0, slashIndex);
322
+ }
323
+
324
+ // src/infer-boundaries.ts
325
+ function inferBoundaries(graph) {
326
+ if (graph.packages.length > 0) {
327
+ return inferMonorepoBoundaries(graph);
328
+ }
329
+ return inferSinglePackageBoundaries(graph);
330
+ }
331
+ function buildNodeIndex2(nodes) {
332
+ const index = /* @__PURE__ */ new Map();
333
+ for (const node of nodes) {
334
+ index.set(node.filePath, node);
335
+ }
336
+ return index;
337
+ }
338
+ function inferMonorepoBoundaries(graph) {
339
+ const nodeIndex = buildNodeIndex2(graph.nodes);
340
+ const packageNames = graph.packages.map((p) => p.name);
341
+ const declaredDeps = /* @__PURE__ */ new Map();
342
+ for (const pkg of graph.packages) {
343
+ declaredDeps.set(pkg.name, new Set(pkg.internalDeps));
344
+ }
345
+ const importCounts = /* @__PURE__ */ new Map();
346
+ const key = (from, to) => `${from} -> ${to}`;
347
+ for (const edge of graph.edges) {
348
+ const sourceNode = nodeIndex.get(edge.source);
349
+ const targetNode = nodeIndex.get(edge.target);
350
+ if (!sourceNode?.packageName || !targetNode?.packageName) continue;
351
+ if (sourceNode.packageName === targetNode.packageName) continue;
352
+ const k = key(sourceNode.packageName, targetNode.packageName);
353
+ importCounts.set(k, (importCounts.get(k) ?? 0) + 1);
354
+ }
355
+ const rules = [];
356
+ for (const from of packageNames) {
357
+ for (const to of packageNames) {
358
+ if (from === to) continue;
359
+ const count = importCounts.get(key(from, to)) ?? 0;
360
+ const isDeclaredDep = declaredDeps.get(from)?.has(to) ?? false;
361
+ if (count === 0 && !isDeclaredDep) {
362
+ rules.push({
363
+ from,
364
+ to,
365
+ allow: false,
366
+ reason: `${from} should not depend on ${to}`
367
+ });
368
+ } else if (count > 0 && isDeclaredDep) {
369
+ rules.push({ from, to, allow: true });
370
+ }
371
+ }
372
+ }
373
+ return rules;
374
+ }
375
+ function getTopLevelDirectory2(relativePath) {
376
+ const normalized = relativePath.startsWith("src/") ? relativePath.slice(4) : relativePath;
377
+ const slashIndex = normalized.indexOf("/");
378
+ if (slashIndex === -1) return void 0;
379
+ return normalized.slice(0, slashIndex);
380
+ }
381
+ function inferSinglePackageBoundaries(graph) {
382
+ const nodeIndex = buildNodeIndex2(graph.nodes);
383
+ const directories = /* @__PURE__ */ new Set();
384
+ for (const node of graph.nodes) {
385
+ const dir = getTopLevelDirectory2(node.relativePath);
386
+ if (dir) directories.add(dir);
387
+ }
388
+ if (directories.size < 2) return [];
389
+ const importCounts = /* @__PURE__ */ new Map();
390
+ const key = (from, to) => `${from} -> ${to}`;
391
+ for (const edge of graph.edges) {
392
+ const sourceNode = nodeIndex.get(edge.source);
393
+ const targetNode = nodeIndex.get(edge.target);
394
+ if (!sourceNode || !targetNode) continue;
395
+ const sourceDir = getTopLevelDirectory2(sourceNode.relativePath);
396
+ const targetDir = getTopLevelDirectory2(targetNode.relativePath);
397
+ if (!sourceDir || !targetDir || sourceDir === targetDir) continue;
398
+ const k = key(sourceDir, targetDir);
399
+ importCounts.set(k, (importCounts.get(k) ?? 0) + 1);
400
+ }
401
+ const rules = [];
402
+ const dirList = [...directories].sort();
403
+ for (const from of dirList) {
404
+ for (const to of dirList) {
405
+ if (from === to) continue;
406
+ const count = importCounts.get(key(from, to)) ?? 0;
407
+ if (count === 0) {
408
+ rules.push({
409
+ from,
410
+ to,
411
+ allow: false,
412
+ reason: `${from} should not depend on ${to}`
413
+ });
414
+ }
415
+ }
416
+ }
417
+ return rules;
418
+ }
419
+ // Annotate the CommonJS export names for ESM import in node:
420
+ 0 && (module.exports = {
421
+ buildImportGraph,
422
+ checkBoundaries,
423
+ detectCycles,
424
+ inferBoundaries,
425
+ parseImports,
426
+ resolveImport
427
+ });
428
+ //# sourceMappingURL=index.cjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/index.ts","../src/build-graph.ts","../src/detect-cycles.ts","../src/parse-imports.ts","../src/resolve-import.ts","../src/check-boundaries.ts","../src/infer-boundaries.ts"],"sourcesContent":["export { buildImportGraph, type GraphOptions } from './build-graph.js';\nexport { checkBoundaries } from './check-boundaries.js';\nexport { detectCycles } from './detect-cycles.js';\nexport { inferBoundaries } from './infer-boundaries.js';\nexport { parseImports } from './parse-imports.js';\nexport { resolveImport, type ResolvedImport } from './resolve-import.js';\n","import type { ImportGraph, ImportGraphNode, WorkspacePackage } from '@viberails/types';\nimport { relative } from 'node:path';\nimport { Project } from 'ts-morph';\nimport { detectCycles } from './detect-cycles.js';\nimport { parseImports } from './parse-imports.js';\nimport { resolveImport } from './resolve-import.js';\n\n/** Options for building an import graph. */\nexport interface GraphOptions {\n /** Workspace packages to include in resolution. */\n packages?: WorkspacePackage[];\n /** Glob patterns for files to ignore. */\n ignore?: string[];\n /** Whether to detect import cycles. @default true */\n detectCycles?: boolean;\n /** Path to tsconfig.json. Auto-detected if not provided. */\n tsconfigPath?: string;\n}\n\n/** Default glob patterns for files to ignore when building the graph. */\nconst DEFAULT_IGNORE = [\n '**/node_modules/**',\n '**/dist/**',\n '**/build/**',\n '**/.next/**',\n '**/.nuxt/**',\n '**/coverage/**',\n];\n\n/**\n * Builds a complete import graph for a project.\n *\n * Creates a ts-morph Project, adds all source files, parses imports,\n * resolves specifiers, and optionally detects cycles.\n *\n * @param projectRoot - Absolute path to the project root.\n * @param options - Configuration options.\n * @returns The complete import graph.\n */\nexport async function buildImportGraph(\n projectRoot: string,\n options?: GraphOptions,\n): Promise<ImportGraph> {\n const packages = options?.packages ?? [];\n const shouldDetectCycles = options?.detectCycles !== false;\n const ignorePatterns = options?.ignore ?? DEFAULT_IGNORE;\n\n // Create ts-morph project\n const project = new Project({\n tsConfigFilePath: options?.tsconfigPath,\n skipAddingFilesFromTsConfig: true,\n });\n\n // Add source files from project root and workspace packages\n const sourceGlobs = buildSourceGlobs(projectRoot, packages, ignorePatterns);\n for (const glob of sourceGlobs) {\n project.addSourceFilesAtPaths(glob);\n }\n\n // Build nodes and edges\n const nodes: ImportGraphNode[] = [];\n const allEdges: ImportGraph['edges'] = [];\n\n for (const sourceFile of project.getSourceFiles()) {\n const filePath = sourceFile.getFilePath();\n\n // Determine which package this file belongs to\n const ownerPkg = packages.find((pkg) => filePath.startsWith(pkg.path + '/'));\n\n nodes.push({\n filePath,\n relativePath: relative(ownerPkg?.path ?? projectRoot, filePath),\n packageName: ownerPkg?.name,\n });\n\n // Parse and resolve imports\n const rawEdges = parseImports(sourceFile);\n for (const edge of rawEdges) {\n const resolved = resolveImport(edge.target, filePath, project, packages);\n\n // Only include edges with resolved file paths (skip externals/builtins)\n if (resolved.resolvedPath) {\n allEdges.push({\n ...edge,\n target: resolved.resolvedPath,\n });\n } else if (resolved.kind === 'external' || resolved.kind === 'builtin') {\n // Keep external/builtin edges with the specifier as target\n allEdges.push(edge);\n }\n }\n }\n\n // Detect cycles among internal file edges only\n let cycles: string[][] = [];\n if (shouldDetectCycles) {\n const internalEdges = allEdges.filter(\n (e) => e.target.startsWith('/') && !e.target.includes('node_modules'),\n );\n cycles = detectCycles(internalEdges);\n }\n\n return { nodes, edges: allEdges, packages, cycles };\n}\n\n/**\n * Builds glob patterns for adding source files to the ts-morph project.\n */\nfunction buildSourceGlobs(\n projectRoot: string,\n packages: WorkspacePackage[],\n _ignore: string[],\n): string[] {\n const globs: string[] = [];\n\n if (packages.length > 0) {\n // Add source files from each workspace package\n for (const pkg of packages) {\n globs.push(`${pkg.path}/src/**/*.{ts,tsx,js,jsx}`);\n }\n } else {\n // Single-package project\n globs.push(`${projectRoot}/src/**/*.{ts,tsx,js,jsx}`);\n globs.push(`${projectRoot}/**/*.{ts,tsx,js,jsx}`);\n }\n\n return globs;\n}\n","/**\n * Detects import cycles in a directed graph of file dependencies.\n * Uses DFS with three-color marking (white/gray/black) to find back edges.\n *\n * @param edges - Array of directed edges with source and target file paths.\n * @returns Array of cycles, each represented as a list of file paths.\n */\nexport function detectCycles(edges: Array<{ source: string; target: string }>): string[][] {\n // Build adjacency list\n const graph = new Map<string, string[]>();\n const nodes = new Set<string>();\n\n for (const { source, target } of edges) {\n nodes.add(source);\n nodes.add(target);\n const neighbors = graph.get(source);\n if (neighbors) {\n neighbors.push(target);\n } else {\n graph.set(source, [target]);\n }\n }\n\n const WHITE = 0; // unvisited\n const GRAY = 1; // in current DFS path\n const BLACK = 2; // fully processed\n\n const color = new Map<string, number>();\n for (const node of nodes) {\n color.set(node, WHITE);\n }\n\n const cycles: string[][] = [];\n const path: string[] = [];\n\n function dfs(node: string): void {\n color.set(node, GRAY);\n path.push(node);\n\n const neighbors = graph.get(node) ?? [];\n for (const neighbor of neighbors) {\n const c = color.get(neighbor);\n\n if (c === GRAY) {\n // Found a cycle — extract it from the path\n const cycleStart = path.indexOf(neighbor);\n if (cycleStart !== -1) {\n cycles.push(path.slice(cycleStart));\n }\n } else if (c === WHITE) {\n dfs(neighbor);\n }\n }\n\n path.pop();\n color.set(node, BLACK);\n }\n\n for (const node of nodes) {\n if (color.get(node) === WHITE) {\n dfs(node);\n }\n }\n\n return cycles;\n}\n","import type { ImportEdge } from '@viberails/types';\nimport { type SourceFile, SyntaxKind } from 'ts-morph';\n\n/** File extensions to skip (non-JS assets). */\nconst SKIP_EXTENSIONS = new Set([\n '.css',\n '.scss',\n '.less',\n '.sass',\n '.png',\n '.svg',\n '.jpg',\n '.jpeg',\n '.gif',\n '.ico',\n '.webp',\n '.json',\n '.woff',\n '.woff2',\n '.ttf',\n '.eot',\n]);\n\n/**\n * Checks whether an import specifier should be skipped (non-JS asset).\n */\nfunction shouldSkip(specifier: string): boolean {\n const dotIndex = specifier.lastIndexOf('.');\n if (dotIndex === -1) return false;\n return SKIP_EXTENSIONS.has(specifier.slice(dotIndex).toLowerCase());\n}\n\n/**\n * Parses all import statements from a ts-morph SourceFile and returns\n * them as ImportEdge objects.\n *\n * Handles static imports, default imports, namespace imports, type-only\n * imports, side-effect imports, dynamic imports, and re-exports.\n *\n * @param sourceFile - A ts-morph SourceFile to extract imports from.\n * @returns Array of ImportEdge objects for each import found.\n */\nexport function parseImports(sourceFile: SourceFile): ImportEdge[] {\n const edges: ImportEdge[] = [];\n const filePath = sourceFile.getFilePath();\n\n // Static imports (including type-only, default, namespace, side-effect)\n for (const decl of sourceFile.getImportDeclarations()) {\n const specifier = decl.getModuleSpecifierValue();\n if (shouldSkip(specifier)) continue;\n\n edges.push({\n source: filePath,\n target: specifier,\n specifier,\n typeOnly: decl.isTypeOnly(),\n dynamic: false,\n line: decl.getStartLineNumber(),\n });\n }\n\n // Re-exports: export { x } from './foo' and export * from './foo'\n for (const decl of sourceFile.getExportDeclarations()) {\n const specifier = decl.getModuleSpecifierValue();\n if (!specifier || shouldSkip(specifier)) continue;\n\n edges.push({\n source: filePath,\n target: specifier,\n specifier,\n typeOnly: decl.isTypeOnly(),\n dynamic: false,\n line: decl.getStartLineNumber(),\n });\n }\n\n // Dynamic imports: import('...')\n for (const call of sourceFile.getDescendantsOfKind(SyntaxKind.CallExpression)) {\n if (call.getExpression().getKind() !== SyntaxKind.ImportKeyword) continue;\n\n const args = call.getArguments();\n if (args.length === 0) continue;\n\n const arg = args[0];\n if (arg.getKind() !== SyntaxKind.StringLiteral) continue;\n\n const specifier = arg.getText().slice(1, -1); // Remove quotes\n if (shouldSkip(specifier)) continue;\n\n edges.push({\n source: filePath,\n target: specifier,\n specifier,\n typeOnly: false,\n dynamic: true,\n line: call.getStartLineNumber(),\n });\n }\n\n return edges;\n}\n","import type { ImportKind, WorkspacePackage } from '@viberails/types';\nimport { builtinModules } from 'node:module';\nimport { dirname, resolve } from 'node:path';\nimport type { Project } from 'ts-morph';\n\n/** Result of resolving an import specifier. */\nexport interface ResolvedImport {\n /** Classification of the import. */\n kind: ImportKind;\n /** Absolute path for internal/workspace imports. */\n resolvedPath?: string;\n /** Package name for workspace/external imports. */\n packageName?: string;\n}\n\n/** Set of Node.js builtin module names (with and without node: prefix). */\nconst BUILTINS = new Set([...builtinModules, ...builtinModules.map((m) => `node:${m}`)]);\n\n/**\n * Resolves an import specifier and classifies it.\n *\n * Classification order:\n * 1. `node:` prefix or known builtin → `builtin`\n * 2. Matches a workspace package name → `workspace`\n * 3. Relative path (`.` or `/`) → resolve via ts-morph → `internal`\n * 4. Otherwise → `external`\n * 5. If resolution fails → `unresolved`\n *\n * @param specifier - The raw import specifier as written in source.\n * @param fromFile - Absolute path of the file containing the import.\n * @param project - ts-morph Project for resolution.\n * @param workspacePackages - Known workspace packages for monorepo resolution.\n * @returns Classification and resolved path information.\n */\nexport function resolveImport(\n specifier: string,\n fromFile: string,\n project: Project,\n workspacePackages: WorkspacePackage[],\n): ResolvedImport {\n // 1. Node.js builtins\n if (BUILTINS.has(specifier)) {\n return { kind: 'builtin' };\n }\n\n // 2. Workspace packages\n const wsMatch = workspacePackages.find(\n (pkg) => specifier === pkg.name || specifier.startsWith(`${pkg.name}/`),\n );\n if (wsMatch) {\n return {\n kind: 'workspace',\n resolvedPath: wsMatch.path,\n packageName: wsMatch.name,\n };\n }\n\n // 3. Relative or absolute imports → internal\n if (specifier.startsWith('.') || specifier.startsWith('/')) {\n const resolved = tryResolve(specifier, fromFile, project);\n if (resolved) {\n return { kind: 'internal', resolvedPath: resolved };\n }\n return { kind: 'unresolved' };\n }\n\n // 4. Check if ts-morph can resolve it (e.g. path aliases)\n const aliasResolved = tryResolve(specifier, fromFile, project);\n if (aliasResolved) {\n return { kind: 'internal', resolvedPath: aliasResolved };\n }\n\n // 5. External package\n return { kind: 'external', packageName: specifier.split('/')[0] };\n}\n\n/**\n * Attempts to resolve a specifier using ts-morph's module resolution.\n * Returns the absolute path if resolved, undefined otherwise.\n */\nfunction tryResolve(specifier: string, fromFile: string, project: Project): string | undefined {\n // Try ts-morph resolution first\n const sourceFile = project.getSourceFile(fromFile);\n if (sourceFile) {\n // Try common TypeScript extensions\n const dir = dirname(fromFile);\n const extensions = ['', '.ts', '.tsx', '.js', '.jsx', '/index.ts', '/index.tsx', '/index.js'];\n\n for (const ext of extensions) {\n const candidate = specifier.startsWith('.') ? resolve(dir, specifier + ext) : specifier + ext;\n const found = project.getSourceFile(candidate);\n if (found) return found.getFilePath();\n }\n }\n\n return undefined;\n}\n","import type {\n BoundaryRule,\n BoundaryViolation,\n ImportGraph,\n ImportGraphNode,\n} from '@viberails/types';\n\n/**\n * Checks import edges against boundary rules and returns violations.\n *\n * For each edge in the graph, determines the source and target\n * package/directory and checks if any `allow: false` rule matches.\n * Skips external/builtin imports and same-package/directory edges.\n *\n * @param graph - The complete import graph for a project.\n * @param rules - Boundary rules to check against.\n * @returns An array of boundary violations.\n */\nexport function checkBoundaries(graph: ImportGraph, rules: BoundaryRule[]): BoundaryViolation[] {\n if (rules.length === 0) return [];\n\n const isMonorepo = graph.packages.length > 0;\n const nodeIndex = buildNodeIndex(graph.nodes);\n\n // Build package path → package name lookup for workspace imports\n // (workspace imports resolve to the package root path, not a file)\n const packagePathIndex = new Map<string, string>();\n for (const pkg of graph.packages) {\n packagePathIndex.set(pkg.path, pkg.name);\n }\n\n const denyRules = rules.filter((r) => !r.allow);\n const allowRules = rules.filter((r) => r.allow);\n\n const violations: BoundaryViolation[] = [];\n\n for (const edge of graph.edges) {\n // Skip external/builtin targets (not absolute paths)\n if (!edge.target.startsWith('/')) continue;\n\n const sourceNode = nodeIndex.get(edge.source);\n if (!sourceNode) continue;\n\n // Determine target zone: try node lookup first, then package path lookup\n const targetNode = nodeIndex.get(edge.target);\n let targetZone: string | undefined;\n if (isMonorepo) {\n targetZone = targetNode?.packageName ?? packagePathIndex.get(edge.target);\n } else {\n if (targetNode) {\n targetZone = getTopLevelDirectory(targetNode.relativePath);\n }\n }\n\n const sourceZone = isMonorepo\n ? sourceNode.packageName\n : getTopLevelDirectory(sourceNode.relativePath);\n\n // Skip if we can't determine zones or they're the same\n if (!sourceZone || !targetZone || sourceZone === targetZone) continue;\n\n // Check if explicitly allowed\n const isAllowed = allowRules.some((r) => r.from === sourceZone && r.to === targetZone);\n if (isAllowed) continue;\n\n // Check deny rules\n const matchedRule = denyRules.find((r) => r.from === sourceZone && r.to === targetZone);\n if (matchedRule) {\n violations.push({\n file: edge.source,\n line: edge.line,\n specifier: edge.specifier,\n resolvedTo: edge.target,\n rule: matchedRule,\n });\n }\n }\n\n return violations;\n}\n\n/**\n * Build a lookup from absolute file path to its graph node.\n */\nfunction buildNodeIndex(nodes: ImportGraphNode[]): Map<string, ImportGraphNode> {\n const index = new Map<string, ImportGraphNode>();\n for (const node of nodes) {\n index.set(node.filePath, node);\n }\n return index;\n}\n\n/**\n * Extract the top-level directory for a file's relative path.\n * Same logic as infer-boundaries — strips src/ prefix.\n */\nfunction getTopLevelDirectory(relativePath: string): string | undefined {\n const normalized = relativePath.startsWith('src/') ? relativePath.slice(4) : relativePath;\n const slashIndex = normalized.indexOf('/');\n if (slashIndex === -1) return undefined;\n return normalized.slice(0, slashIndex);\n}\n","import type { BoundaryRule, ImportGraph, ImportGraphNode } from '@viberails/types';\n\n/**\n * Infers boundary rules from existing import patterns in the graph.\n *\n * For monorepos, creates package-level rules based on which packages\n * import from each other. For single-package projects, creates\n * directory-level rules based on top-level directory imports.\n *\n * Only creates `allow: false` rules where the codebase already follows\n * the pattern (zero imports in that direction), so inferred rules never\n * produce immediate violations.\n *\n * @param graph - The complete import graph for a project.\n * @returns An array of inferred boundary rules.\n */\nexport function inferBoundaries(graph: ImportGraph): BoundaryRule[] {\n if (graph.packages.length > 0) {\n return inferMonorepoBoundaries(graph);\n }\n return inferSinglePackageBoundaries(graph);\n}\n\n/**\n * Build a lookup from absolute file path to its graph node.\n */\nfunction buildNodeIndex(nodes: ImportGraphNode[]): Map<string, ImportGraphNode> {\n const index = new Map<string, ImportGraphNode>();\n for (const node of nodes) {\n index.set(node.filePath, node);\n }\n return index;\n}\n\n/**\n * Infer boundary rules for a monorepo based on package-to-package imports.\n */\nfunction inferMonorepoBoundaries(graph: ImportGraph): BoundaryRule[] {\n const nodeIndex = buildNodeIndex(graph.nodes);\n const packageNames = graph.packages.map((p) => p.name);\n\n // Build a set of declared internal dependencies per package\n const declaredDeps = new Map<string, Set<string>>();\n for (const pkg of graph.packages) {\n declaredDeps.set(pkg.name, new Set(pkg.internalDeps));\n }\n\n // Count imports from package A to package B\n const importCounts = new Map<string, number>();\n const key = (from: string, to: string) => `${from} -> ${to}`;\n\n for (const edge of graph.edges) {\n const sourceNode = nodeIndex.get(edge.source);\n const targetNode = nodeIndex.get(edge.target);\n if (!sourceNode?.packageName || !targetNode?.packageName) continue;\n if (sourceNode.packageName === targetNode.packageName) continue;\n\n const k = key(sourceNode.packageName, targetNode.packageName);\n importCounts.set(k, (importCounts.get(k) ?? 0) + 1);\n }\n\n const rules: BoundaryRule[] = [];\n\n for (const from of packageNames) {\n for (const to of packageNames) {\n if (from === to) continue;\n\n const count = importCounts.get(key(from, to)) ?? 0;\n const isDeclaredDep = declaredDeps.get(from)?.has(to) ?? false;\n\n if (count === 0 && !isDeclaredDep) {\n // No imports and not a declared dependency — disallow\n rules.push({\n from,\n to,\n allow: false,\n reason: `${from} should not depend on ${to}`,\n });\n } else if (count > 0 && isDeclaredDep) {\n // Imports exist and it's a declared dependency — allow\n rules.push({ from, to, allow: true });\n }\n // If imports exist but NOT declared → skip rule creation\n // (would produce immediate violation, defeats auto-detection purpose)\n }\n }\n\n return rules;\n}\n\n/**\n * Extract the top-level directory for a file's relative path.\n * e.g. \"src/components/Button.tsx\" → \"components\" (strips src/ prefix)\n * \"components/Button.tsx\" → \"components\"\n * \"index.ts\" → undefined (root-level file, no directory)\n */\nfunction getTopLevelDirectory(relativePath: string): string | undefined {\n // Strip leading src/ prefix if present\n const normalized = relativePath.startsWith('src/') ? relativePath.slice(4) : relativePath;\n\n const slashIndex = normalized.indexOf('/');\n if (slashIndex === -1) return undefined;\n return normalized.slice(0, slashIndex);\n}\n\n/**\n * Infer boundary rules for a single-package project based on directory imports.\n */\nfunction inferSinglePackageBoundaries(graph: ImportGraph): BoundaryRule[] {\n const nodeIndex = buildNodeIndex(graph.nodes);\n\n // Collect all top-level directories\n const directories = new Set<string>();\n for (const node of graph.nodes) {\n const dir = getTopLevelDirectory(node.relativePath);\n if (dir) directories.add(dir);\n }\n\n // Need at least 2 directories to form boundaries\n if (directories.size < 2) return [];\n\n // Count imports from directory A to directory B\n const importCounts = new Map<string, number>();\n const key = (from: string, to: string) => `${from} -> ${to}`;\n\n for (const edge of graph.edges) {\n const sourceNode = nodeIndex.get(edge.source);\n const targetNode = nodeIndex.get(edge.target);\n if (!sourceNode || !targetNode) continue;\n\n const sourceDir = getTopLevelDirectory(sourceNode.relativePath);\n const targetDir = getTopLevelDirectory(targetNode.relativePath);\n if (!sourceDir || !targetDir || sourceDir === targetDir) continue;\n\n const k = key(sourceDir, targetDir);\n importCounts.set(k, (importCounts.get(k) ?? 0) + 1);\n }\n\n const rules: BoundaryRule[] = [];\n const dirList = [...directories].sort();\n\n for (const from of dirList) {\n for (const to of dirList) {\n if (from === to) continue;\n\n const count = importCounts.get(key(from, to)) ?? 0;\n if (count === 0) {\n // No imports exist in this direction — safe to create a boundary\n rules.push({\n from,\n to,\n allow: false,\n reason: `${from} should not depend on ${to}`,\n });\n }\n }\n }\n\n return rules;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;;;ACCA,IAAAA,oBAAyB;AACzB,IAAAC,mBAAwB;;;ACKjB,SAAS,aAAa,OAA8D;AAEzF,QAAM,QAAQ,oBAAI,IAAsB;AACxC,QAAM,QAAQ,oBAAI,IAAY;AAE9B,aAAW,EAAE,QAAQ,OAAO,KAAK,OAAO;AACtC,UAAM,IAAI,MAAM;AAChB,UAAM,IAAI,MAAM;AAChB,UAAM,YAAY,MAAM,IAAI,MAAM;AAClC,QAAI,WAAW;AACb,gBAAU,KAAK,MAAM;AAAA,IACvB,OAAO;AACL,YAAM,IAAI,QAAQ,CAAC,MAAM,CAAC;A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;AAAA,IACF;AAAA,EACF;AAEA,SAAO;AACT;","names":["import_node_path","import_ts_morph","buildNodeIndex","getTopLevelDirectory"]}
@@ -0,0 +1,107 @@
1
+ import { WorkspacePackage, ImportGraph, BoundaryRule, BoundaryViolation, ImportEdge, ImportKind } from '@viberails/types';
2
+ import { SourceFile, Project } from 'ts-morph';
3
+
4
+ /** Options for building an import graph. */
5
+ interface GraphOptions {
6
+ /** Workspace packages to include in resolution. */
7
+ packages?: WorkspacePackage[];
8
+ /** Glob patterns for files to ignore. */
9
+ ignore?: string[];
10
+ /** Whether to detect import cycles. @default true */
11
+ detectCycles?: boolean;
12
+ /** Path to tsconfig.json. Auto-detected if not provided. */
13
+ tsconfigPath?: string;
14
+ }
15
+ /**
16
+ * Builds a complete import graph for a project.
17
+ *
18
+ * Creates a ts-morph Project, adds all source files, parses imports,
19
+ * resolves specifiers, and optionally detects cycles.
20
+ *
21
+ * @param projectRoot - Absolute path to the project root.
22
+ * @param options - Configuration options.
23
+ * @returns The complete import graph.
24
+ */
25
+ declare function buildImportGraph(projectRoot: string, options?: GraphOptions): Promise<ImportGraph>;
26
+
27
+ /**
28
+ * Checks import edges against boundary rules and returns violations.
29
+ *
30
+ * For each edge in the graph, determines the source and target
31
+ * package/directory and checks if any `allow: false` rule matches.
32
+ * Skips external/builtin imports and same-package/directory edges.
33
+ *
34
+ * @param graph - The complete import graph for a project.
35
+ * @param rules - Boundary rules to check against.
36
+ * @returns An array of boundary violations.
37
+ */
38
+ declare function checkBoundaries(graph: ImportGraph, rules: BoundaryRule[]): BoundaryViolation[];
39
+
40
+ /**
41
+ * Detects import cycles in a directed graph of file dependencies.
42
+ * Uses DFS with three-color marking (white/gray/black) to find back edges.
43
+ *
44
+ * @param edges - Array of directed edges with source and target file paths.
45
+ * @returns Array of cycles, each represented as a list of file paths.
46
+ */
47
+ declare function detectCycles(edges: Array<{
48
+ source: string;
49
+ target: string;
50
+ }>): string[][];
51
+
52
+ /**
53
+ * Infers boundary rules from existing import patterns in the graph.
54
+ *
55
+ * For monorepos, creates package-level rules based on which packages
56
+ * import from each other. For single-package projects, creates
57
+ * directory-level rules based on top-level directory imports.
58
+ *
59
+ * Only creates `allow: false` rules where the codebase already follows
60
+ * the pattern (zero imports in that direction), so inferred rules never
61
+ * produce immediate violations.
62
+ *
63
+ * @param graph - The complete import graph for a project.
64
+ * @returns An array of inferred boundary rules.
65
+ */
66
+ declare function inferBoundaries(graph: ImportGraph): BoundaryRule[];
67
+
68
+ /**
69
+ * Parses all import statements from a ts-morph SourceFile and returns
70
+ * them as ImportEdge objects.
71
+ *
72
+ * Handles static imports, default imports, namespace imports, type-only
73
+ * imports, side-effect imports, dynamic imports, and re-exports.
74
+ *
75
+ * @param sourceFile - A ts-morph SourceFile to extract imports from.
76
+ * @returns Array of ImportEdge objects for each import found.
77
+ */
78
+ declare function parseImports(sourceFile: SourceFile): ImportEdge[];
79
+
80
+ /** Result of resolving an import specifier. */
81
+ interface ResolvedImport {
82
+ /** Classification of the import. */
83
+ kind: ImportKind;
84
+ /** Absolute path for internal/workspace imports. */
85
+ resolvedPath?: string;
86
+ /** Package name for workspace/external imports. */
87
+ packageName?: string;
88
+ }
89
+ /**
90
+ * Resolves an import specifier and classifies it.
91
+ *
92
+ * Classification order:
93
+ * 1. `node:` prefix or known builtin → `builtin`
94
+ * 2. Matches a workspace package name → `workspace`
95
+ * 3. Relative path (`.` or `/`) → resolve via ts-morph → `internal`
96
+ * 4. Otherwise → `external`
97
+ * 5. If resolution fails → `unresolved`
98
+ *
99
+ * @param specifier - The raw import specifier as written in source.
100
+ * @param fromFile - Absolute path of the file containing the import.
101
+ * @param project - ts-morph Project for resolution.
102
+ * @param workspacePackages - Known workspace packages for monorepo resolution.
103
+ * @returns Classification and resolved path information.
104
+ */
105
+ declare function resolveImport(specifier: string, fromFile: string, project: Project, workspacePackages: WorkspacePackage[]): ResolvedImport;
106
+
107
+ export { type GraphOptions, type ResolvedImport, buildImportGraph, checkBoundaries, detectCycles, inferBoundaries, parseImports, resolveImport };
@@ -0,0 +1,107 @@
1
+ import { WorkspacePackage, ImportGraph, BoundaryRule, BoundaryViolation, ImportEdge, ImportKind } from '@viberails/types';
2
+ import { SourceFile, Project } from 'ts-morph';
3
+
4
+ /** Options for building an import graph. */
5
+ interface GraphOptions {
6
+ /** Workspace packages to include in resolution. */
7
+ packages?: WorkspacePackage[];
8
+ /** Glob patterns for files to ignore. */
9
+ ignore?: string[];
10
+ /** Whether to detect import cycles. @default true */
11
+ detectCycles?: boolean;
12
+ /** Path to tsconfig.json. Auto-detected if not provided. */
13
+ tsconfigPath?: string;
14
+ }
15
+ /**
16
+ * Builds a complete import graph for a project.
17
+ *
18
+ * Creates a ts-morph Project, adds all source files, parses imports,
19
+ * resolves specifiers, and optionally detects cycles.
20
+ *
21
+ * @param projectRoot - Absolute path to the project root.
22
+ * @param options - Configuration options.
23
+ * @returns The complete import graph.
24
+ */
25
+ declare function buildImportGraph(projectRoot: string, options?: GraphOptions): Promise<ImportGraph>;
26
+
27
+ /**
28
+ * Checks import edges against boundary rules and returns violations.
29
+ *
30
+ * For each edge in the graph, determines the source and target
31
+ * package/directory and checks if any `allow: false` rule matches.
32
+ * Skips external/builtin imports and same-package/directory edges.
33
+ *
34
+ * @param graph - The complete import graph for a project.
35
+ * @param rules - Boundary rules to check against.
36
+ * @returns An array of boundary violations.
37
+ */
38
+ declare function checkBoundaries(graph: ImportGraph, rules: BoundaryRule[]): BoundaryViolation[];
39
+
40
+ /**
41
+ * Detects import cycles in a directed graph of file dependencies.
42
+ * Uses DFS with three-color marking (white/gray/black) to find back edges.
43
+ *
44
+ * @param edges - Array of directed edges with source and target file paths.
45
+ * @returns Array of cycles, each represented as a list of file paths.
46
+ */
47
+ declare function detectCycles(edges: Array<{
48
+ source: string;
49
+ target: string;
50
+ }>): string[][];
51
+
52
+ /**
53
+ * Infers boundary rules from existing import patterns in the graph.
54
+ *
55
+ * For monorepos, creates package-level rules based on which packages
56
+ * import from each other. For single-package projects, creates
57
+ * directory-level rules based on top-level directory imports.
58
+ *
59
+ * Only creates `allow: false` rules where the codebase already follows
60
+ * the pattern (zero imports in that direction), so inferred rules never
61
+ * produce immediate violations.
62
+ *
63
+ * @param graph - The complete import graph for a project.
64
+ * @returns An array of inferred boundary rules.
65
+ */
66
+ declare function inferBoundaries(graph: ImportGraph): BoundaryRule[];
67
+
68
+ /**
69
+ * Parses all import statements from a ts-morph SourceFile and returns
70
+ * them as ImportEdge objects.
71
+ *
72
+ * Handles static imports, default imports, namespace imports, type-only
73
+ * imports, side-effect imports, dynamic imports, and re-exports.
74
+ *
75
+ * @param sourceFile - A ts-morph SourceFile to extract imports from.
76
+ * @returns Array of ImportEdge objects for each import found.
77
+ */
78
+ declare function parseImports(sourceFile: SourceFile): ImportEdge[];
79
+
80
+ /** Result of resolving an import specifier. */
81
+ interface ResolvedImport {
82
+ /** Classification of the import. */
83
+ kind: ImportKind;
84
+ /** Absolute path for internal/workspace imports. */
85
+ resolvedPath?: string;
86
+ /** Package name for workspace/external imports. */
87
+ packageName?: string;
88
+ }
89
+ /**
90
+ * Resolves an import specifier and classifies it.
91
+ *
92
+ * Classification order:
93
+ * 1. `node:` prefix or known builtin → `builtin`
94
+ * 2. Matches a workspace package name → `workspace`
95
+ * 3. Relative path (`.` or `/`) → resolve via ts-morph → `internal`
96
+ * 4. Otherwise → `external`
97
+ * 5. If resolution fails → `unresolved`
98
+ *
99
+ * @param specifier - The raw import specifier as written in source.
100
+ * @param fromFile - Absolute path of the file containing the import.
101
+ * @param project - ts-morph Project for resolution.
102
+ * @param workspacePackages - Known workspace packages for monorepo resolution.
103
+ * @returns Classification and resolved path information.
104
+ */
105
+ declare function resolveImport(specifier: string, fromFile: string, project: Project, workspacePackages: WorkspacePackage[]): ResolvedImport;
106
+
107
+ export { type GraphOptions, type ResolvedImport, buildImportGraph, checkBoundaries, detectCycles, inferBoundaries, parseImports, resolveImport };
package/dist/index.js ADDED
@@ -0,0 +1,396 @@
1
+ // src/build-graph.ts
2
+ import { relative } from "path";
3
+ import { Project } from "ts-morph";
4
+
5
+ // src/detect-cycles.ts
6
+ function detectCycles(edges) {
7
+ const graph = /* @__PURE__ */ new Map();
8
+ const nodes = /* @__PURE__ */ new Set();
9
+ for (const { source, target } of edges) {
10
+ nodes.add(source);
11
+ nodes.add(target);
12
+ const neighbors = graph.get(source);
13
+ if (neighbors) {
14
+ neighbors.push(target);
15
+ } else {
16
+ graph.set(source, [target]);
17
+ }
18
+ }
19
+ const WHITE = 0;
20
+ const GRAY = 1;
21
+ const BLACK = 2;
22
+ const color = /* @__PURE__ */ new Map();
23
+ for (const node of nodes) {
24
+ color.set(node, WHITE);
25
+ }
26
+ const cycles = [];
27
+ const path = [];
28
+ function dfs(node) {
29
+ color.set(node, GRAY);
30
+ path.push(node);
31
+ const neighbors = graph.get(node) ?? [];
32
+ for (const neighbor of neighbors) {
33
+ const c = color.get(neighbor);
34
+ if (c === GRAY) {
35
+ const cycleStart = path.indexOf(neighbor);
36
+ if (cycleStart !== -1) {
37
+ cycles.push(path.slice(cycleStart));
38
+ }
39
+ } else if (c === WHITE) {
40
+ dfs(neighbor);
41
+ }
42
+ }
43
+ path.pop();
44
+ color.set(node, BLACK);
45
+ }
46
+ for (const node of nodes) {
47
+ if (color.get(node) === WHITE) {
48
+ dfs(node);
49
+ }
50
+ }
51
+ return cycles;
52
+ }
53
+
54
+ // src/parse-imports.ts
55
+ import { SyntaxKind } from "ts-morph";
56
+ var SKIP_EXTENSIONS = /* @__PURE__ */ new Set([
57
+ ".css",
58
+ ".scss",
59
+ ".less",
60
+ ".sass",
61
+ ".png",
62
+ ".svg",
63
+ ".jpg",
64
+ ".jpeg",
65
+ ".gif",
66
+ ".ico",
67
+ ".webp",
68
+ ".json",
69
+ ".woff",
70
+ ".woff2",
71
+ ".ttf",
72
+ ".eot"
73
+ ]);
74
+ function shouldSkip(specifier) {
75
+ const dotIndex = specifier.lastIndexOf(".");
76
+ if (dotIndex === -1) return false;
77
+ return SKIP_EXTENSIONS.has(specifier.slice(dotIndex).toLowerCase());
78
+ }
79
+ function parseImports(sourceFile) {
80
+ const edges = [];
81
+ const filePath = sourceFile.getFilePath();
82
+ for (const decl of sourceFile.getImportDeclarations()) {
83
+ const specifier = decl.getModuleSpecifierValue();
84
+ if (shouldSkip(specifier)) continue;
85
+ edges.push({
86
+ source: filePath,
87
+ target: specifier,
88
+ specifier,
89
+ typeOnly: decl.isTypeOnly(),
90
+ dynamic: false,
91
+ line: decl.getStartLineNumber()
92
+ });
93
+ }
94
+ for (const decl of sourceFile.getExportDeclarations()) {
95
+ const specifier = decl.getModuleSpecifierValue();
96
+ if (!specifier || shouldSkip(specifier)) continue;
97
+ edges.push({
98
+ source: filePath,
99
+ target: specifier,
100
+ specifier,
101
+ typeOnly: decl.isTypeOnly(),
102
+ dynamic: false,
103
+ line: decl.getStartLineNumber()
104
+ });
105
+ }
106
+ for (const call of sourceFile.getDescendantsOfKind(SyntaxKind.CallExpression)) {
107
+ if (call.getExpression().getKind() !== SyntaxKind.ImportKeyword) continue;
108
+ const args = call.getArguments();
109
+ if (args.length === 0) continue;
110
+ const arg = args[0];
111
+ if (arg.getKind() !== SyntaxKind.StringLiteral) continue;
112
+ const specifier = arg.getText().slice(1, -1);
113
+ if (shouldSkip(specifier)) continue;
114
+ edges.push({
115
+ source: filePath,
116
+ target: specifier,
117
+ specifier,
118
+ typeOnly: false,
119
+ dynamic: true,
120
+ line: call.getStartLineNumber()
121
+ });
122
+ }
123
+ return edges;
124
+ }
125
+
126
+ // src/resolve-import.ts
127
+ import { builtinModules } from "module";
128
+ import { dirname, resolve } from "path";
129
+ var BUILTINS = /* @__PURE__ */ new Set([...builtinModules, ...builtinModules.map((m) => `node:${m}`)]);
130
+ function resolveImport(specifier, fromFile, project, workspacePackages) {
131
+ if (BUILTINS.has(specifier)) {
132
+ return { kind: "builtin" };
133
+ }
134
+ const wsMatch = workspacePackages.find(
135
+ (pkg) => specifier === pkg.name || specifier.startsWith(`${pkg.name}/`)
136
+ );
137
+ if (wsMatch) {
138
+ return {
139
+ kind: "workspace",
140
+ resolvedPath: wsMatch.path,
141
+ packageName: wsMatch.name
142
+ };
143
+ }
144
+ if (specifier.startsWith(".") || specifier.startsWith("/")) {
145
+ const resolved = tryResolve(specifier, fromFile, project);
146
+ if (resolved) {
147
+ return { kind: "internal", resolvedPath: resolved };
148
+ }
149
+ return { kind: "unresolved" };
150
+ }
151
+ const aliasResolved = tryResolve(specifier, fromFile, project);
152
+ if (aliasResolved) {
153
+ return { kind: "internal", resolvedPath: aliasResolved };
154
+ }
155
+ return { kind: "external", packageName: specifier.split("/")[0] };
156
+ }
157
+ function tryResolve(specifier, fromFile, project) {
158
+ const sourceFile = project.getSourceFile(fromFile);
159
+ if (sourceFile) {
160
+ const dir = dirname(fromFile);
161
+ const extensions = ["", ".ts", ".tsx", ".js", ".jsx", "/index.ts", "/index.tsx", "/index.js"];
162
+ for (const ext of extensions) {
163
+ const candidate = specifier.startsWith(".") ? resolve(dir, specifier + ext) : specifier + ext;
164
+ const found = project.getSourceFile(candidate);
165
+ if (found) return found.getFilePath();
166
+ }
167
+ }
168
+ return void 0;
169
+ }
170
+
171
+ // src/build-graph.ts
172
+ var DEFAULT_IGNORE = [
173
+ "**/node_modules/**",
174
+ "**/dist/**",
175
+ "**/build/**",
176
+ "**/.next/**",
177
+ "**/.nuxt/**",
178
+ "**/coverage/**"
179
+ ];
180
+ async function buildImportGraph(projectRoot, options) {
181
+ const packages = options?.packages ?? [];
182
+ const shouldDetectCycles = options?.detectCycles !== false;
183
+ const ignorePatterns = options?.ignore ?? DEFAULT_IGNORE;
184
+ const project = new Project({
185
+ tsConfigFilePath: options?.tsconfigPath,
186
+ skipAddingFilesFromTsConfig: true
187
+ });
188
+ const sourceGlobs = buildSourceGlobs(projectRoot, packages, ignorePatterns);
189
+ for (const glob of sourceGlobs) {
190
+ project.addSourceFilesAtPaths(glob);
191
+ }
192
+ const nodes = [];
193
+ const allEdges = [];
194
+ for (const sourceFile of project.getSourceFiles()) {
195
+ const filePath = sourceFile.getFilePath();
196
+ const ownerPkg = packages.find((pkg) => filePath.startsWith(pkg.path + "/"));
197
+ nodes.push({
198
+ filePath,
199
+ relativePath: relative(ownerPkg?.path ?? projectRoot, filePath),
200
+ packageName: ownerPkg?.name
201
+ });
202
+ const rawEdges = parseImports(sourceFile);
203
+ for (const edge of rawEdges) {
204
+ const resolved = resolveImport(edge.target, filePath, project, packages);
205
+ if (resolved.resolvedPath) {
206
+ allEdges.push({
207
+ ...edge,
208
+ target: resolved.resolvedPath
209
+ });
210
+ } else if (resolved.kind === "external" || resolved.kind === "builtin") {
211
+ allEdges.push(edge);
212
+ }
213
+ }
214
+ }
215
+ let cycles = [];
216
+ if (shouldDetectCycles) {
217
+ const internalEdges = allEdges.filter(
218
+ (e) => e.target.startsWith("/") && !e.target.includes("node_modules")
219
+ );
220
+ cycles = detectCycles(internalEdges);
221
+ }
222
+ return { nodes, edges: allEdges, packages, cycles };
223
+ }
224
+ function buildSourceGlobs(projectRoot, packages, _ignore) {
225
+ const globs = [];
226
+ if (packages.length > 0) {
227
+ for (const pkg of packages) {
228
+ globs.push(`${pkg.path}/src/**/*.{ts,tsx,js,jsx}`);
229
+ }
230
+ } else {
231
+ globs.push(`${projectRoot}/src/**/*.{ts,tsx,js,jsx}`);
232
+ globs.push(`${projectRoot}/**/*.{ts,tsx,js,jsx}`);
233
+ }
234
+ return globs;
235
+ }
236
+
237
+ // src/check-boundaries.ts
238
+ function checkBoundaries(graph, rules) {
239
+ if (rules.length === 0) return [];
240
+ const isMonorepo = graph.packages.length > 0;
241
+ const nodeIndex = buildNodeIndex(graph.nodes);
242
+ const packagePathIndex = /* @__PURE__ */ new Map();
243
+ for (const pkg of graph.packages) {
244
+ packagePathIndex.set(pkg.path, pkg.name);
245
+ }
246
+ const denyRules = rules.filter((r) => !r.allow);
247
+ const allowRules = rules.filter((r) => r.allow);
248
+ const violations = [];
249
+ for (const edge of graph.edges) {
250
+ if (!edge.target.startsWith("/")) continue;
251
+ const sourceNode = nodeIndex.get(edge.source);
252
+ if (!sourceNode) continue;
253
+ const targetNode = nodeIndex.get(edge.target);
254
+ let targetZone;
255
+ if (isMonorepo) {
256
+ targetZone = targetNode?.packageName ?? packagePathIndex.get(edge.target);
257
+ } else {
258
+ if (targetNode) {
259
+ targetZone = getTopLevelDirectory(targetNode.relativePath);
260
+ }
261
+ }
262
+ const sourceZone = isMonorepo ? sourceNode.packageName : getTopLevelDirectory(sourceNode.relativePath);
263
+ if (!sourceZone || !targetZone || sourceZone === targetZone) continue;
264
+ const isAllowed = allowRules.some((r) => r.from === sourceZone && r.to === targetZone);
265
+ if (isAllowed) continue;
266
+ const matchedRule = denyRules.find((r) => r.from === sourceZone && r.to === targetZone);
267
+ if (matchedRule) {
268
+ violations.push({
269
+ file: edge.source,
270
+ line: edge.line,
271
+ specifier: edge.specifier,
272
+ resolvedTo: edge.target,
273
+ rule: matchedRule
274
+ });
275
+ }
276
+ }
277
+ return violations;
278
+ }
279
+ function buildNodeIndex(nodes) {
280
+ const index = /* @__PURE__ */ new Map();
281
+ for (const node of nodes) {
282
+ index.set(node.filePath, node);
283
+ }
284
+ return index;
285
+ }
286
+ function getTopLevelDirectory(relativePath) {
287
+ const normalized = relativePath.startsWith("src/") ? relativePath.slice(4) : relativePath;
288
+ const slashIndex = normalized.indexOf("/");
289
+ if (slashIndex === -1) return void 0;
290
+ return normalized.slice(0, slashIndex);
291
+ }
292
+
293
+ // src/infer-boundaries.ts
294
+ function inferBoundaries(graph) {
295
+ if (graph.packages.length > 0) {
296
+ return inferMonorepoBoundaries(graph);
297
+ }
298
+ return inferSinglePackageBoundaries(graph);
299
+ }
300
+ function buildNodeIndex2(nodes) {
301
+ const index = /* @__PURE__ */ new Map();
302
+ for (const node of nodes) {
303
+ index.set(node.filePath, node);
304
+ }
305
+ return index;
306
+ }
307
+ function inferMonorepoBoundaries(graph) {
308
+ const nodeIndex = buildNodeIndex2(graph.nodes);
309
+ const packageNames = graph.packages.map((p) => p.name);
310
+ const declaredDeps = /* @__PURE__ */ new Map();
311
+ for (const pkg of graph.packages) {
312
+ declaredDeps.set(pkg.name, new Set(pkg.internalDeps));
313
+ }
314
+ const importCounts = /* @__PURE__ */ new Map();
315
+ const key = (from, to) => `${from} -> ${to}`;
316
+ for (const edge of graph.edges) {
317
+ const sourceNode = nodeIndex.get(edge.source);
318
+ const targetNode = nodeIndex.get(edge.target);
319
+ if (!sourceNode?.packageName || !targetNode?.packageName) continue;
320
+ if (sourceNode.packageName === targetNode.packageName) continue;
321
+ const k = key(sourceNode.packageName, targetNode.packageName);
322
+ importCounts.set(k, (importCounts.get(k) ?? 0) + 1);
323
+ }
324
+ const rules = [];
325
+ for (const from of packageNames) {
326
+ for (const to of packageNames) {
327
+ if (from === to) continue;
328
+ const count = importCounts.get(key(from, to)) ?? 0;
329
+ const isDeclaredDep = declaredDeps.get(from)?.has(to) ?? false;
330
+ if (count === 0 && !isDeclaredDep) {
331
+ rules.push({
332
+ from,
333
+ to,
334
+ allow: false,
335
+ reason: `${from} should not depend on ${to}`
336
+ });
337
+ } else if (count > 0 && isDeclaredDep) {
338
+ rules.push({ from, to, allow: true });
339
+ }
340
+ }
341
+ }
342
+ return rules;
343
+ }
344
+ function getTopLevelDirectory2(relativePath) {
345
+ const normalized = relativePath.startsWith("src/") ? relativePath.slice(4) : relativePath;
346
+ const slashIndex = normalized.indexOf("/");
347
+ if (slashIndex === -1) return void 0;
348
+ return normalized.slice(0, slashIndex);
349
+ }
350
+ function inferSinglePackageBoundaries(graph) {
351
+ const nodeIndex = buildNodeIndex2(graph.nodes);
352
+ const directories = /* @__PURE__ */ new Set();
353
+ for (const node of graph.nodes) {
354
+ const dir = getTopLevelDirectory2(node.relativePath);
355
+ if (dir) directories.add(dir);
356
+ }
357
+ if (directories.size < 2) return [];
358
+ const importCounts = /* @__PURE__ */ new Map();
359
+ const key = (from, to) => `${from} -> ${to}`;
360
+ for (const edge of graph.edges) {
361
+ const sourceNode = nodeIndex.get(edge.source);
362
+ const targetNode = nodeIndex.get(edge.target);
363
+ if (!sourceNode || !targetNode) continue;
364
+ const sourceDir = getTopLevelDirectory2(sourceNode.relativePath);
365
+ const targetDir = getTopLevelDirectory2(targetNode.relativePath);
366
+ if (!sourceDir || !targetDir || sourceDir === targetDir) continue;
367
+ const k = key(sourceDir, targetDir);
368
+ importCounts.set(k, (importCounts.get(k) ?? 0) + 1);
369
+ }
370
+ const rules = [];
371
+ const dirList = [...directories].sort();
372
+ for (const from of dirList) {
373
+ for (const to of dirList) {
374
+ if (from === to) continue;
375
+ const count = importCounts.get(key(from, to)) ?? 0;
376
+ if (count === 0) {
377
+ rules.push({
378
+ from,
379
+ to,
380
+ allow: false,
381
+ reason: `${from} should not depend on ${to}`
382
+ });
383
+ }
384
+ }
385
+ }
386
+ return rules;
387
+ }
388
+ export {
389
+ buildImportGraph,
390
+ checkBoundaries,
391
+ detectCycles,
392
+ inferBoundaries,
393
+ parseImports,
394
+ resolveImport
395
+ };
396
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/build-graph.ts","../src/detect-cycles.ts","../src/parse-imports.ts","../src/resolve-import.ts","../src/check-boundaries.ts","../src/infer-boundaries.ts"],"sourcesContent":["import type { ImportGraph, ImportGraphNode, WorkspacePackage } from '@viberails/types';\nimport { relative } from 'node:path';\nimport { Project } from 'ts-morph';\nimport { detectCycles } from './detect-cycles.js';\nimport { parseImports } from './parse-imports.js';\nimport { resolveImport } from './resolve-import.js';\n\n/** Options for building an import graph. */\nexport interface GraphOptions {\n /** Workspace packages to include in resolution. */\n packages?: WorkspacePackage[];\n /** Glob patterns for files to ignore. */\n ignore?: string[];\n /** Whether to detect import cycles. @default true */\n detectCycles?: boolean;\n /** Path to tsconfig.json. Auto-detected if not provided. */\n tsconfigPath?: string;\n}\n\n/** Default glob patterns for files to ignore when building the graph. */\nconst DEFAULT_IGNORE = [\n '**/node_modules/**',\n '**/dist/**',\n '**/build/**',\n '**/.next/**',\n '**/.nuxt/**',\n '**/coverage/**',\n];\n\n/**\n * Builds a complete import graph for a project.\n *\n * Creates a ts-morph Project, adds all source files, parses imports,\n * resolves specifiers, and optionally detects cycles.\n *\n * @param projectRoot - Absolute path to the project root.\n * @param options - Configuration options.\n * @returns The complete import graph.\n */\nexport async function buildImportGraph(\n projectRoot: string,\n options?: GraphOptions,\n): Promise<ImportGraph> {\n const packages = options?.packages ?? [];\n const shouldDetectCycles = options?.detectCycles !== false;\n const ignorePatterns = options?.ignore ?? DEFAULT_IGNORE;\n\n // Create ts-morph project\n const project = new Project({\n tsConfigFilePath: options?.tsconfigPath,\n skipAddingFilesFromTsConfig: true,\n });\n\n // Add source files from project root and workspace packages\n const sourceGlobs = buildSourceGlobs(projectRoot, packages, ignorePatterns);\n for (const glob of sourceGlobs) {\n project.addSourceFilesAtPaths(glob);\n }\n\n // Build nodes and edges\n const nodes: ImportGraphNode[] = [];\n const allEdges: ImportGraph['edges'] = [];\n\n for (const sourceFile of project.getSourceFiles()) {\n const filePath = sourceFile.getFilePath();\n\n // Determine which package this file belongs to\n const ownerPkg = packages.find((pkg) => filePath.startsWith(pkg.path + '/'));\n\n nodes.push({\n filePath,\n relativePath: relative(ownerPkg?.path ?? projectRoot, filePath),\n packageName: ownerPkg?.name,\n });\n\n // Parse and resolve imports\n const rawEdges = parseImports(sourceFile);\n for (const edge of rawEdges) {\n const resolved = resolveImport(edge.target, filePath, project, packages);\n\n // Only include edges with resolved file paths (skip externals/builtins)\n if (resolved.resolvedPath) {\n allEdges.push({\n ...edge,\n target: resolved.resolvedPath,\n });\n } else if (resolved.kind === 'external' || resolved.kind === 'builtin') {\n // Keep external/builtin edges with the specifier as target\n allEdges.push(edge);\n }\n }\n }\n\n // Detect cycles among internal file edges only\n let cycles: string[][] = [];\n if (shouldDetectCycles) {\n const internalEdges = allEdges.filter(\n (e) => e.target.startsWith('/') && !e.target.includes('node_modules'),\n );\n cycles = detectCycles(internalEdges);\n }\n\n return { nodes, edges: allEdges, packages, cycles };\n}\n\n/**\n * Builds glob patterns for adding source files to the ts-morph project.\n */\nfunction buildSourceGlobs(\n projectRoot: string,\n packages: WorkspacePackage[],\n _ignore: string[],\n): string[] {\n const globs: string[] = [];\n\n if (packages.length > 0) {\n // Add source files from each workspace package\n for (const pkg of packages) {\n globs.push(`${pkg.path}/src/**/*.{ts,tsx,js,jsx}`);\n }\n } else {\n // Single-package project\n globs.push(`${projectRoot}/src/**/*.{ts,tsx,js,jsx}`);\n globs.push(`${projectRoot}/**/*.{ts,tsx,js,jsx}`);\n }\n\n return globs;\n}\n","/**\n * Detects import cycles in a directed graph of file dependencies.\n * Uses DFS with three-color marking (white/gray/black) to find back edges.\n *\n * @param edges - Array of directed edges with source and target file paths.\n * @returns Array of cycles, each represented as a list of file paths.\n */\nexport function detectCycles(edges: Array<{ source: string; target: string }>): string[][] {\n // Build adjacency list\n const graph = new Map<string, string[]>();\n const nodes = new Set<string>();\n\n for (const { source, target } of edges) {\n nodes.add(source);\n nodes.add(target);\n const neighbors = graph.get(source);\n if (neighbors) {\n neighbors.push(target);\n } else {\n graph.set(source, [target]);\n }\n }\n\n const WHITE = 0; // unvisited\n const GRAY = 1; // in current DFS path\n const BLACK = 2; // fully processed\n\n const color = new Map<string, number>();\n for (const node of nodes) {\n color.set(node, WHITE);\n }\n\n const cycles: string[][] = [];\n const path: string[] = [];\n\n function dfs(node: string): void {\n color.set(node, GRAY);\n path.push(node);\n\n const neighbors = graph.get(node) ?? [];\n for (const neighbor of neighbors) {\n const c = color.get(neighbor);\n\n if (c === GRAY) {\n // Found a cycle — extract it from the path\n const cycleStart = path.indexOf(neighbor);\n if (cycleStart !== -1) {\n cycles.push(path.slice(cycleStart));\n }\n } else if (c === WHITE) {\n dfs(neighbor);\n }\n }\n\n path.pop();\n color.set(node, BLACK);\n }\n\n for (const node of nodes) {\n if (color.get(node) === WHITE) {\n dfs(node);\n }\n }\n\n return cycles;\n}\n","import type { ImportEdge } from '@viberails/types';\nimport { type SourceFile, SyntaxKind } from 'ts-morph';\n\n/** File extensions to skip (non-JS assets). */\nconst SKIP_EXTENSIONS = new Set([\n '.css',\n '.scss',\n '.less',\n '.sass',\n '.png',\n '.svg',\n '.jpg',\n '.jpeg',\n '.gif',\n '.ico',\n '.webp',\n '.json',\n '.woff',\n '.woff2',\n '.ttf',\n '.eot',\n]);\n\n/**\n * Checks whether an import specifier should be skipped (non-JS asset).\n */\nfunction shouldSkip(specifier: string): boolean {\n const dotIndex = specifier.lastIndexOf('.');\n if (dotIndex === -1) return false;\n return SKIP_EXTENSIONS.has(specifier.slice(dotIndex).toLowerCase());\n}\n\n/**\n * Parses all import statements from a ts-morph SourceFile and returns\n * them as ImportEdge objects.\n *\n * Handles static imports, default imports, namespace imports, type-only\n * imports, side-effect imports, dynamic imports, and re-exports.\n *\n * @param sourceFile - A ts-morph SourceFile to extract imports from.\n * @returns Array of ImportEdge objects for each import found.\n */\nexport function parseImports(sourceFile: SourceFile): ImportEdge[] {\n const edges: ImportEdge[] = [];\n const filePath = sourceFile.getFilePath();\n\n // Static imports (including type-only, default, namespace, side-effect)\n for (const decl of sourceFile.getImportDeclarations()) {\n const specifier = decl.getModuleSpecifierValue();\n if (shouldSkip(specifier)) continue;\n\n edges.push({\n source: filePath,\n target: specifier,\n specifier,\n typeOnly: decl.isTypeOnly(),\n dynamic: false,\n line: decl.getStartLineNumber(),\n });\n }\n\n // Re-exports: export { x } from './foo' and export * from './foo'\n for (const decl of sourceFile.getExportDeclarations()) {\n const specifier = decl.getModuleSpecifierValue();\n if (!specifier || shouldSkip(specifier)) continue;\n\n edges.push({\n source: filePath,\n target: specifier,\n specifier,\n typeOnly: decl.isTypeOnly(),\n dynamic: false,\n line: decl.getStartLineNumber(),\n });\n }\n\n // Dynamic imports: import('...')\n for (const call of sourceFile.getDescendantsOfKind(SyntaxKind.CallExpression)) {\n if (call.getExpression().getKind() !== SyntaxKind.ImportKeyword) continue;\n\n const args = call.getArguments();\n if (args.length === 0) continue;\n\n const arg = args[0];\n if (arg.getKind() !== SyntaxKind.StringLiteral) continue;\n\n const specifier = arg.getText().slice(1, -1); // Remove quotes\n if (shouldSkip(specifier)) continue;\n\n edges.push({\n source: filePath,\n target: specifier,\n specifier,\n typeOnly: false,\n dynamic: true,\n line: call.getStartLineNumber(),\n });\n }\n\n return edges;\n}\n","import type { ImportKind, WorkspacePackage } from '@viberails/types';\nimport { builtinModules } from 'node:module';\nimport { dirname, resolve } from 'node:path';\nimport type { Project } from 'ts-morph';\n\n/** Result of resolving an import specifier. */\nexport interface ResolvedImport {\n /** Classification of the import. */\n kind: ImportKind;\n /** Absolute path for internal/workspace imports. */\n resolvedPath?: string;\n /** Package name for workspace/external imports. */\n packageName?: string;\n}\n\n/** Set of Node.js builtin module names (with and without node: prefix). */\nconst BUILTINS = new Set([...builtinModules, ...builtinModules.map((m) => `node:${m}`)]);\n\n/**\n * Resolves an import specifier and classifies it.\n *\n * Classification order:\n * 1. `node:` prefix or known builtin → `builtin`\n * 2. Matches a workspace package name → `workspace`\n * 3. Relative path (`.` or `/`) → resolve via ts-morph → `internal`\n * 4. Otherwise → `external`\n * 5. If resolution fails → `unresolved`\n *\n * @param specifier - The raw import specifier as written in source.\n * @param fromFile - Absolute path of the file containing the import.\n * @param project - ts-morph Project for resolution.\n * @param workspacePackages - Known workspace packages for monorepo resolution.\n * @returns Classification and resolved path information.\n */\nexport function resolveImport(\n specifier: string,\n fromFile: string,\n project: Project,\n workspacePackages: WorkspacePackage[],\n): ResolvedImport {\n // 1. Node.js builtins\n if (BUILTINS.has(specifier)) {\n return { kind: 'builtin' };\n }\n\n // 2. Workspace packages\n const wsMatch = workspacePackages.find(\n (pkg) => specifier === pkg.name || specifier.startsWith(`${pkg.name}/`),\n );\n if (wsMatch) {\n return {\n kind: 'workspace',\n resolvedPath: wsMatch.path,\n packageName: wsMatch.name,\n };\n }\n\n // 3. Relative or absolute imports → internal\n if (specifier.startsWith('.') || specifier.startsWith('/')) {\n const resolved = tryResolve(specifier, fromFile, project);\n if (resolved) {\n return { kind: 'internal', resolvedPath: resolved };\n }\n return { kind: 'unresolved' };\n }\n\n // 4. Check if ts-morph can resolve it (e.g. path aliases)\n const aliasResolved = tryResolve(specifier, fromFile, project);\n if (aliasResolved) {\n return { kind: 'internal', resolvedPath: aliasResolved };\n }\n\n // 5. External package\n return { kind: 'external', packageName: specifier.split('/')[0] };\n}\n\n/**\n * Attempts to resolve a specifier using ts-morph's module resolution.\n * Returns the absolute path if resolved, undefined otherwise.\n */\nfunction tryResolve(specifier: string, fromFile: string, project: Project): string | undefined {\n // Try ts-morph resolution first\n const sourceFile = project.getSourceFile(fromFile);\n if (sourceFile) {\n // Try common TypeScript extensions\n const dir = dirname(fromFile);\n const extensions = ['', '.ts', '.tsx', '.js', '.jsx', '/index.ts', '/index.tsx', '/index.js'];\n\n for (const ext of extensions) {\n const candidate = specifier.startsWith('.') ? resolve(dir, specifier + ext) : specifier + ext;\n const found = project.getSourceFile(candidate);\n if (found) return found.getFilePath();\n }\n }\n\n return undefined;\n}\n","import type {\n BoundaryRule,\n BoundaryViolation,\n ImportGraph,\n ImportGraphNode,\n} from '@viberails/types';\n\n/**\n * Checks import edges against boundary rules and returns violations.\n *\n * For each edge in the graph, determines the source and target\n * package/directory and checks if any `allow: false` rule matches.\n * Skips external/builtin imports and same-package/directory edges.\n *\n * @param graph - The complete import graph for a project.\n * @param rules - Boundary rules to check against.\n * @returns An array of boundary violations.\n */\nexport function checkBoundaries(graph: ImportGraph, rules: BoundaryRule[]): BoundaryViolation[] {\n if (rules.length === 0) return [];\n\n const isMonorepo = graph.packages.length > 0;\n const nodeIndex = buildNodeIndex(graph.nodes);\n\n // Build package path → package name lookup for workspace imports\n // (workspace imports resolve to the package root path, not a file)\n const packagePathIndex = new Map<string, string>();\n for (const pkg of graph.packages) {\n packagePathIndex.set(pkg.path, pkg.name);\n }\n\n const denyRules = rules.filter((r) => !r.allow);\n const allowRules = rules.filter((r) => r.allow);\n\n const violations: BoundaryViolation[] = [];\n\n for (const edge of graph.edges) {\n // Skip external/builtin targets (not absolute paths)\n if (!edge.target.startsWith('/')) continue;\n\n const sourceNode = nodeIndex.get(edge.source);\n if (!sourceNode) continue;\n\n // Determine target zone: try node lookup first, then package path lookup\n const targetNode = nodeIndex.get(edge.target);\n let targetZone: string | undefined;\n if (isMonorepo) {\n targetZone = targetNode?.packageName ?? packagePathIndex.get(edge.target);\n } else {\n if (targetNode) {\n targetZone = getTopLevelDirectory(targetNode.relativePath);\n }\n }\n\n const sourceZone = isMonorepo\n ? sourceNode.packageName\n : getTopLevelDirectory(sourceNode.relativePath);\n\n // Skip if we can't determine zones or they're the same\n if (!sourceZone || !targetZone || sourceZone === targetZone) continue;\n\n // Check if explicitly allowed\n const isAllowed = allowRules.some((r) => r.from === sourceZone && r.to === targetZone);\n if (isAllowed) continue;\n\n // Check deny rules\n const matchedRule = denyRules.find((r) => r.from === sourceZone && r.to === targetZone);\n if (matchedRule) {\n violations.push({\n file: edge.source,\n line: edge.line,\n specifier: edge.specifier,\n resolvedTo: edge.target,\n rule: matchedRule,\n });\n }\n }\n\n return violations;\n}\n\n/**\n * Build a lookup from absolute file path to its graph node.\n */\nfunction buildNodeIndex(nodes: ImportGraphNode[]): Map<string, ImportGraphNode> {\n const index = new Map<string, ImportGraphNode>();\n for (const node of nodes) {\n index.set(node.filePath, node);\n }\n return index;\n}\n\n/**\n * Extract the top-level directory for a file's relative path.\n * Same logic as infer-boundaries — strips src/ prefix.\n */\nfunction getTopLevelDirectory(relativePath: string): string | undefined {\n const normalized = relativePath.startsWith('src/') ? relativePath.slice(4) : relativePath;\n const slashIndex = normalized.indexOf('/');\n if (slashIndex === -1) return undefined;\n return normalized.slice(0, slashIndex);\n}\n","import type { BoundaryRule, ImportGraph, ImportGraphNode } from '@viberails/types';\n\n/**\n * Infers boundary rules from existing import patterns in the graph.\n *\n * For monorepos, creates package-level rules based on which packages\n * import from each other. For single-package projects, creates\n * directory-level rules based on top-level directory imports.\n *\n * Only creates `allow: false` rules where the codebase already follows\n * the pattern (zero imports in that direction), so inferred rules never\n * produce immediate violations.\n *\n * @param graph - The complete import graph for a project.\n * @returns An array of inferred boundary rules.\n */\nexport function inferBoundaries(graph: ImportGraph): BoundaryRule[] {\n if (graph.packages.length > 0) {\n return inferMonorepoBoundaries(graph);\n }\n return inferSinglePackageBoundaries(graph);\n}\n\n/**\n * Build a lookup from absolute file path to its graph node.\n */\nfunction buildNodeIndex(nodes: ImportGraphNode[]): Map<string, ImportGraphNode> {\n const index = new Map<string, ImportGraphNode>();\n for (const node of nodes) {\n index.set(node.filePath, node);\n }\n return index;\n}\n\n/**\n * Infer boundary rules for a monorepo based on package-to-package imports.\n */\nfunction inferMonorepoBoundaries(graph: ImportGraph): BoundaryRule[] {\n const nodeIndex = buildNodeIndex(graph.nodes);\n const packageNames = graph.packages.map((p) => p.name);\n\n // Build a set of declared internal dependencies per package\n const declaredDeps = new Map<string, Set<string>>();\n for (const pkg of graph.packages) {\n declaredDeps.set(pkg.name, new Set(pkg.internalDeps));\n }\n\n // Count imports from package A to package B\n const importCounts = new Map<string, number>();\n const key = (from: string, to: string) => `${from} -> ${to}`;\n\n for (const edge of graph.edges) {\n const sourceNode = nodeIndex.get(edge.source);\n const targetNode = nodeIndex.get(edge.target);\n if (!sourceNode?.packageName || !targetNode?.packageName) continue;\n if (sourceNode.packageName === targetNode.packageName) continue;\n\n const k = key(sourceNode.packageName, targetNode.packageName);\n importCounts.set(k, (importCounts.get(k) ?? 0) + 1);\n }\n\n const rules: BoundaryRule[] = [];\n\n for (const from of packageNames) {\n for (const to of packageNames) {\n if (from === to) continue;\n\n const count = importCounts.get(key(from, to)) ?? 0;\n const isDeclaredDep = declaredDeps.get(from)?.has(to) ?? false;\n\n if (count === 0 && !isDeclaredDep) {\n // No imports and not a declared dependency — disallow\n rules.push({\n from,\n to,\n allow: false,\n reason: `${from} should not depend on ${to}`,\n });\n } else if (count > 0 && isDeclaredDep) {\n // Imports exist and it's a declared dependency — allow\n rules.push({ from, to, allow: true });\n }\n // If imports exist but NOT declared → skip rule creation\n // (would produce immediate violation, defeats auto-detection purpose)\n }\n }\n\n return rules;\n}\n\n/**\n * Extract the top-level directory for a file's relative path.\n * e.g. \"src/components/Button.tsx\" → \"components\" (strips src/ prefix)\n * \"components/Button.tsx\" → \"components\"\n * \"index.ts\" → undefined (root-level file, no directory)\n */\nfunction getTopLevelDirectory(relativePath: string): string | undefined {\n // Strip leading src/ prefix if present\n const normalized = relativePath.startsWith('src/') ? relativePath.slice(4) : relativePath;\n\n const slashIndex = normalized.indexOf('/');\n if (slashIndex === -1) return undefined;\n return normalized.slice(0, slashIndex);\n}\n\n/**\n * Infer boundary rules for a single-package project based on directory imports.\n */\nfunction inferSinglePackageBoundaries(graph: ImportGraph): BoundaryRule[] {\n const nodeIndex = buildNodeIndex(graph.nodes);\n\n // Collect all top-level directories\n const directories = new Set<string>();\n for (const node of graph.nodes) {\n const dir = getTopLevelDirectory(node.relativePath);\n if (dir) directories.add(dir);\n }\n\n // Need at least 2 directories to form boundaries\n if (directories.size < 2) return [];\n\n // Count imports from directory A to directory B\n const importCounts = new Map<string, number>();\n const key = (from: string, to: string) => `${from} -> ${to}`;\n\n for (const edge of graph.edges) {\n const sourceNode = nodeIndex.get(edge.source);\n const targetNode = nodeIndex.get(edge.target);\n if (!sourceNode || !targetNode) continue;\n\n const sourceDir = getTopLevelDirectory(sourceNode.relativePath);\n const targetDir = getTopLevelDirectory(targetNode.relativePath);\n if (!sourceDir || !targetDir || sourceDir === targetDir) continue;\n\n const k = key(sourceDir, targetDir);\n importCounts.set(k, (importCounts.get(k) ?? 0) + 1);\n }\n\n const rules: BoundaryRule[] = [];\n const dirList = [...directories].sort();\n\n for (const from of dirList) {\n for (const to of dirList) {\n if (from === to) continue;\n\n const count = importCounts.get(key(from, to)) ?? 0;\n if (count === 0) {\n // No imports exist in this direction — safe to create a boundary\n rules.push({\n from,\n to,\n allow: false,\n reason: `${from} should not depend on ${to}`,\n });\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Aa,IAAI,CAAC,KAAK,KAAK,CAAC;AAAA,EACpD;AAEA,QAAM,QAAwB,CAAC;AAC/B,QAAM,UAAU,CAAC,GAAG,WAAW,EAAE,KAAK;AAEtC,aAAW,QAAQ,SAAS;AAC1B,eAAW,MAAM,SAAS;AACxB,UAAI,SAAS,GAAI;AAEjB,YAAM,QAAQ,aAAa,IAAI,IAAI,MAAM,EAAE,CAAC,KAAK;AACjD,UAAI,UAAU,GAAG;AAEf,cAAM,KAAK;AAAA,UACT;AAAA,UACA;AAAA,UACA,OAAO;AAAA,UACP,QAAQ,GAAG,IAAI,yBAAyB,EAAE;AAAA,QAC5C,CAAC;AAAA,MACH;AAAA,IACF;AAAA,EACF;AAEA,SAAO;AACT;","names":["buildNodeIndex","getTopLevelDirectory"]}
package/package.json ADDED
@@ -0,0 +1,39 @@
1
+ {
2
+ "name": "@viberails/graph",
3
+ "version": "0.1.0",
4
+ "type": "module",
5
+ "main": "./dist/index.cjs",
6
+ "module": "./dist/index.js",
7
+ "types": "./dist/index.d.ts",
8
+ "exports": {
9
+ ".": {
10
+ "import": {
11
+ "types": "./dist/index.d.ts",
12
+ "default": "./dist/index.js"
13
+ },
14
+ "require": {
15
+ "types": "./dist/index.d.cts",
16
+ "default": "./dist/index.cjs"
17
+ }
18
+ }
19
+ },
20
+ "files": [
21
+ "dist"
22
+ ],
23
+ "publishConfig": {
24
+ "access": "public"
25
+ },
26
+ "dependencies": {
27
+ "ts-morph": "^27.0.2",
28
+ "@viberails/types": "0.1.0"
29
+ },
30
+ "devDependencies": {
31
+ "@types/node": "^25.3.5"
32
+ },
33
+ "scripts": {
34
+ "build": "tsup",
35
+ "test": "vitest run",
36
+ "lint": "biome check src/",
37
+ "clean": "rm -rf dist"
38
+ }
39
+ }