-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathfrontendFeatureDetector.ts
More file actions
379 lines (327 loc) · 13.8 KB
/
Copy pathfrontendFeatureDetector.ts
File metadata and controls
379 lines (327 loc) · 13.8 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
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
import type { RouteInfo } from "./routeDetector.js";
import type { FileAnalysis, ScannedFile } from "../analysis/index.js";
import type { FileGraph } from "../graph/dependencyGraph.js";
import { buildReverseGraph } from "../graph/index.js";
import { singularize } from "../analysis/extractors/fallbackExtractor.js";
import type { FeatureInfo } from "../features/featureDetector.js";
// ---------------------------------------------------------------------------
// Constants
// ---------------------------------------------------------------------------
/**
* Top-level page segments that aren't really a distinct product feature —
* either infrastructure (auth callbacks) or too generic to name a feature
* after on their own. Deliberately short: pages are usually meaningful
* (unlike the wider NON_RESOURCE_SEGMENTS list used for API-derived CRUD
* entities in capabilityDetector.ts) — "settings" or "profile" *are* real
* pages users navigate to, so they stay in.
*/
const NON_FEATURE_PAGE_SEGMENTS = new Set([
"auth", "oauth", "callback",
"api", "static", "assets", "public",
]);
// ---------------------------------------------------------------------------
// Barrel file detection
// ---------------------------------------------------------------------------
/**
* isPureBarrelFile — heuristic for files that exist solely to re-export
* symbols from other modules (index.ts barrel files). Two checks:
* 1. No value-level symbols (functions, classes, consts) — only re-exports.
* 2. Export-dominance: majority of non-empty, non-comment lines are
* `export * from` or `export { ... } from` re-export statements.
*
* A barrel file that also defines local values is NOT treated as a barrel —
* it has its own logic and should participate in ownership normally.
*/
function isPureBarrelFile(
analysis: FileAnalysis | undefined,
content: string
): boolean {
if (!analysis) return false;
if (analysis.symbols.length > 0) return false;
if (analysis.imports.length === 0) return false;
// Export-dominance check: count re-export lines vs total meaningful lines
const lines = content.split("\n");
const meaningful = lines.filter((line) => {
const trimmed = line.trim();
return trimmed.length > 0 && !trimmed.startsWith("//") && !trimmed.startsWith("/*") && !trimmed.startsWith("*");
});
if (meaningful.length === 0) return false;
const reExportCount = meaningful.filter((line) =>
/^\s*export\s+(\*\s+from|{[^}]*}\s+from)/.test(line)
).length;
return reExportCount / meaningful.length > 0.5;
}
// ---------------------------------------------------------------------------
// Detector
// ---------------------------------------------------------------------------
/**
* detectFrontendPageFeatures — turn Next.js App/Pages Router page routes into
* features, independent of whether any database entity was found.
*
* Why this needs to be independent: entity-derived features (Prisma/SQL/
* route-hint) only run as a fallback chain that stops at the first non-empty
* source. A project with even one Prisma model (e.g. a NextAuth Session
* table) never reaches route-hint fallback, so page-only features like
* "Quran" or "Dzikir" — which have zero database presence — never surfaced
* at all. This runs unconditionally and merges alongside whatever else was
* found, so a mostly-frontend project doesn't get its features dominated by
* whatever thin backend evidence happens to exist.
*/
export function detectFrontendPageFeatures(
routes: RouteInfo[],
fileGraph: FileGraph,
analyses: Record<string, FileAnalysis>,
files: ScannedFile[]
): FeatureInfo[] {
const pageRoutes = routes.filter((route) => route.kind === "page");
if (pageRoutes.length === 0) return [];
const routesBySegment = groupBySegment(pageRoutes);
const reverseGraph = buildReverseGraph(fileGraph);
const barrelFiles = new Set(
files
.filter((f) => isPureBarrelFile(analyses[f.path], f.content))
.map((f) => f.path)
);
const features: FeatureInfo[] = [];
for (const [segment, segmentRoutes] of routesBySegment) {
const seedFiles = [...new Set(segmentRoutes.map((route) => route.file))].sort();
const ownedFiles = collectOwnedFiles(seedFiles, fileGraph, reverseGraph, barrelFiles);
const name = singularize(segment);
features.push({
name,
purpose: `Frontend page${segmentRoutes.length > 1 ? "s" : ""} under "${segment}".`,
files: ownedFiles,
entryPoint: seedFiles[0],
entryPoints: seedFiles.slice(0, 2),
businessFlow: [],
searchTerms: [...new Set([segment.toLowerCase(), name.toLowerCase()])],
confidence: "medium",
evidence: ownedFiles
});
}
return features;
}
// ---------------------------------------------------------------------------
// Internals
// ---------------------------------------------------------------------------
function groupBySegment(pageRoutes: RouteInfo[]): Map<string, RouteInfo[]> {
const bySegment = new Map<string, RouteInfo[]>();
for (const route of pageRoutes) {
const segments = route.path.split("/").filter(Boolean);
const topSegment = segments[0];
if (!topSegment) continue; // root "/" — no distinct feature name to derive
if (topSegment.startsWith("[")) continue; // dynamic-only, e.g. /[locale]
if (NON_FEATURE_PAGE_SEGMENTS.has(topSegment.toLowerCase())) continue;
const list = bySegment.get(topSegment) ?? [];
list.push(route);
bySegment.set(topSegment, list);
}
return bySegment;
}
// ---------------------------------------------------------------------------
// React Router (client-side routing)
// ---------------------------------------------------------------------------
/**
* Matches the common ways a path gets paired with a component reference in
* React Router — JSX `<Route path="..." element={<Foo />} />` / `component={Foo}`,
* and object/data-router configs `{ path: "...", element: <Foo /> }` /
* `{ path: "...", Component: Foo }`. Not a JSX/AST parser — same "common
* conventions, not full coverage" approach as the SQL table-name extraction.
* Assumes `path` appears before the element/component reference, which is
* the idiomatic order in real code; reversed ordering is a known v1 miss.
*/
const CLIENT_ROUTE_PATTERNS = [
/<Route\s+[^>]*?path=["'`]([^"'`]+)["'`][^>]*?element=\{<(\w+)/g,
/<Route\s+[^>]*?path=["'`]([^"'`]+)["'`][^>]*?component=\{?(\w+)/g,
/\{\s*path:\s*["'`]([^"'`]+)["'`][^}]*?element:\s*<(\w+)/g,
/\{\s*path:\s*["'`]([^"'`]+)["'`][^}]*?Component:\s*(\w+)/g,
// Vue Router — identifier form (component already imported above).
/\{\s*path:\s*["'`]([^"'`]+)["'`][^}]*?component:\s*(\w+)\s*[,}]/g,
];
// Vue Router — lazy import form: `component: () => import("./views/About.vue")`.
// Captures the relative specifier instead of an identifier, so it resolves
// through resolveRouteSpecifierFile rather than the identifier matcher.
const LAZY_ROUTE_PATTERN =
/\{\s*path:\s*["'`]([^"'`]+)["'`][^}]*?component:\s*\(\)\s*=>\s*import\(\s*["'`]([^"'`]+)["'`]\s*\)/g;
// svelte-spa-router — object map form: `const routes = { '/about': About }`.
// Too generic to trust on its own (any "string-key : identifier" object could
// match), so it only runs on files that import svelte-spa-router.
const SVELTE_SPA_ROUTER_PATTERN = /["'`](\/[^"'`]*)["'`]\s*:\s*(\w+)/g;
const SVELTE_SPA_ROUTER_IMPORT =
/from\s+["']svelte-spa-router["']|require\(\s*["']svelte-spa-router["']\s*\)/;
type ClientRoute = {
path: string;
component: string;
/** Relative import specifier for lazy imports (e.g. "./views/About.vue"). */
specifier?: string;
definedIn: string;
};
function findClientRoutes(files: ScannedFile[]): ClientRoute[] {
const routes: ClientRoute[] = [];
for (const file of files) {
for (const pattern of CLIENT_ROUTE_PATTERNS) {
pattern.lastIndex = 0;
let match = pattern.exec(file.content);
while (match) {
routes.push({ path: match[1], component: match[2], definedIn: file.path });
match = pattern.exec(file.content);
}
}
LAZY_ROUTE_PATTERN.lastIndex = 0;
let match = LAZY_ROUTE_PATTERN.exec(file.content);
while (match) {
routes.push({ path: match[1], component: "", specifier: match[2], definedIn: file.path });
match = LAZY_ROUTE_PATTERN.exec(file.content);
}
if (SVELTE_SPA_ROUTER_IMPORT.test(file.content)) {
SVELTE_SPA_ROUTER_PATTERN.lastIndex = 0;
let svelteMatch = SVELTE_SPA_ROUTER_PATTERN.exec(file.content);
while (svelteMatch) {
routes.push({ path: svelteMatch[1], component: svelteMatch[2], definedIn: file.path });
svelteMatch = SVELTE_SPA_ROUTER_PATTERN.exec(file.content);
}
}
}
return routes;
}
/**
* A route only gives an identifier ("QuranPage"), not a file. Resolve it by
* checking what the defining file actually imports — the dependency graph
* already has that edge, so this is a lookup, not new import resolution.
*/
function resolveRouteComponentFile(route: ClientRoute, fileGraph: FileGraph): string | undefined {
const imported = fileGraph[route.definedIn] ?? [];
const target = route.component.toLowerCase();
return imported.find((file) => {
const stem = file.slice(file.lastIndexOf("/") + 1).replace(/\.[^/.]+$/, "");
return stem.toLowerCase() === target;
});
}
/**
* Vue Router's lazy form captures a relative specifier ("./views/About.vue"),
* not an identifier — the graph's resolved imports won't match it directly.
* Resolve the specifier against the defining file's folder and match the
* scanned file list, covering explicit .vue extensions and omitted ones.
*/
function resolveRouteSpecifierFile(route: ClientRoute, files: ScannedFile[]): string | undefined {
const available = new Set(files.map((file) => file.path));
const baseParts = route.definedIn.split("/");
baseParts.pop();
const normalized = normalizeRoutePath([...baseParts, route.specifier ?? ""].join("/"));
const candidates = [
normalized,
`${normalized}.vue`,
`${normalized}.ts`,
`${normalized}.tsx`,
`${normalized}.js`,
`${normalized}.jsx`,
`${normalized}/index.vue`,
`${normalized}/index.ts`,
`${normalized}/index.js`
];
return candidates.find((candidate) => available.has(candidate));
}
function normalizeRoutePath(path: string): string {
const parts: string[] = [];
for (const part of path.split("/")) {
if (part === "." || part === "") {
continue;
}
if (part === "..") {
parts.pop();
continue;
}
parts.push(part);
}
return parts.join("/");
}
/**
* detectClientRouteFeatures — same purpose and output shape as
* detectFrontendPageFeatures, for SPAs with no file-based routing (Vite +
* React Router). Route paths come from parsing route definitions instead of
* folder conventions; ownership uses the exact same reverse-graph rule.
*/
export function detectClientRouteFeatures(
files: ScannedFile[],
fileGraph: FileGraph,
analyses: Record<string, FileAnalysis>
): FeatureInfo[] {
const routes = findClientRoutes(files);
if (routes.length === 0) return [];
const bySegment = new Map<string, string[]>();
for (const route of routes) {
const segments = route.path.split("/").filter(Boolean);
const topSegment = segments[0];
if (!topSegment || topSegment.startsWith(":") || topSegment.startsWith("*")) continue;
if (NON_FEATURE_PAGE_SEGMENTS.has(topSegment.toLowerCase())) continue;
const resolvedFile = route.specifier
? resolveRouteSpecifierFile(route, files)
: resolveRouteComponentFile(route, fileGraph);
if (!resolvedFile) continue;
const seeds = bySegment.get(topSegment) ?? [];
if (!seeds.includes(resolvedFile)) seeds.push(resolvedFile);
bySegment.set(topSegment, seeds);
}
const reverseGraph = buildReverseGraph(fileGraph);
const barrelFiles = new Set(
files
.filter((f) => isPureBarrelFile(analyses[f.path], f.content))
.map((f) => f.path)
);
const features: FeatureInfo[] = [];
for (const [segment, seedFiles] of bySegment) {
if (seedFiles.length === 0) continue;
const ownedFiles = collectOwnedFiles(seedFiles, fileGraph, reverseGraph, barrelFiles);
const name = singularize(segment);
features.push({
name,
purpose: `Client-side route${seedFiles.length > 1 ? "s" : ""} under "${segment}".`,
files: ownedFiles,
entryPoint: seedFiles[0],
entryPoints: seedFiles.slice(0, 2),
businessFlow: [],
searchTerms: [...new Set([segment.toLowerCase(), name.toLowerCase()])],
confidence: "medium",
evidence: ownedFiles
});
}
return features;
}
/**
* collectOwnedFiles — seed files plus every file reachable from them whose
* *every* referrer is also within that reachable set. A component (or
* store, or any other file) imported by this route/page and nothing else is
* "owned"; a file also imported by a different page or feature is shared
* and stays out — false-negative (feature looks smaller than it is) over
* false-positive (feature claims a shared file it doesn't really own).
*/
function collectOwnedFiles(
seedFiles: string[],
graph: FileGraph,
reverseGraph: FileGraph,
barrelFiles: Set<string>
): string[] {
const reachable = new Set<string>(seedFiles);
const queue = [...seedFiles];
while (queue.length > 0) {
const current = queue.shift() as string;
if (barrelFiles.has(current)) continue; // JANGAN ekspansi children barrel
for (const next of graph[current] ?? []) {
if (!reachable.has(next)) {
reachable.add(next);
queue.push(next);
}
}
}
const seedSet = new Set(seedFiles);
const owned = new Set<string>(seedFiles);
for (const file of reachable) {
if (seedSet.has(file)) continue;
const referrers = reverseGraph[file] ?? [];
const hasExternalReferrer = referrers.some((referrer) => !reachable.has(referrer));
if (!hasExternalReferrer) {
owned.add(file);
}
}
return [...owned].sort();
}