@mandujs/core 0.23.0 → 0.24.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.
@@ -15,6 +15,11 @@ import type {
15
15
  HMRReplayEnvelope,
16
16
  } from "./hmr-types";
17
17
  import { MAX_REPLAY_BUFFER, REPLAY_MAX_AGE_MS } from "./hmr-types";
18
+ import {
19
+ ReverseImportGraph,
20
+ scanFileImports,
21
+ DEFAULT_MAX_CLOSURE_DEPTH,
22
+ } from "./reverse-import-graph";
18
23
  import path from "path";
19
24
  import fs from "fs";
20
25
 
@@ -312,6 +317,9 @@ export const _testOnly_DEFAULT_COMMON_DIRS = DEFAULT_COMMON_DIRS;
312
317
  /** Test-only accessor for the watch exclude segments (B1 coverage). */
313
318
  export const _testOnly_WATCH_EXCLUDE_SEGMENTS = WATCH_EXCLUDE_SEGMENTS;
314
319
 
320
+ /** Test-only re-export for #189 reverse import-graph coverage. */
321
+ export { ReverseImportGraph, scanFileImports } from "./reverse-import-graph";
322
+
315
323
  /**
316
324
  * Phase 7.0 R2 Agent D — classification helper mirroring the in-bundler
317
325
  * `classifyBatch` priority rules WITHOUT the project-specific maps
@@ -570,6 +578,99 @@ export async function startDevBundler(options: DevBundlerOptions): Promise<DevBu
570
578
  await addCommonDir(dir);
571
579
  }
572
580
 
581
+ // #189 — reverse import-graph for transitive invalidation.
582
+ //
583
+ // Built-time index of `importee -> Set<importer>` edges for every
584
+ // known SSR / API / client / common-dir root. On an unknown-file
585
+ // change (a leaf utility that none of our sets recognize) we walk
586
+ // the transitive importer closure and re-dispatch the change
587
+ // against every ancestor that IS known — so a deep edit to
588
+ // `app/_utils/translations/ko.ts` still re-evaluates the barrel
589
+ // in `app/_utils/translations/index.ts` that imported it.
590
+ //
591
+ // The initial population is best-effort (filesystem scan may
592
+ // surface typed-only stubs that have no source yet); misses simply
593
+ // keep the legacy "silent drop" behavior so no project is made
594
+ // worse by turning this on.
595
+ const reverseGraph = new ReverseImportGraph();
596
+
597
+ /**
598
+ * Re-scan a single file's imports and update its row in the
599
+ * reverse graph. Called on startup for every known root, and
600
+ * again each time a file change is dispatched so the graph
601
+ * tracks refactors (an import being added / removed) in real
602
+ * time.
603
+ *
604
+ * Errors are swallowed — a missing file / permission issue must
605
+ * not break the HMR dispatch for the rest of the project.
606
+ */
607
+ const refreshReverseGraphEdges = async (filePath: string): Promise<void> => {
608
+ try {
609
+ const imports = await scanFileImports(filePath);
610
+ reverseGraph.update(filePath, imports);
611
+ } catch {
612
+ // scanFileImports already swallows fs errors; this extra guard
613
+ // catches anything pathological (e.g. a symlink loop).
614
+ }
615
+ };
616
+
617
+ /**
618
+ * Populate the reverse graph transitively from every known root.
619
+ *
620
+ * The BFS walks each root's outgoing imports, scans every
621
+ * discovered intermediate, and keeps going until the frontier is
622
+ * empty or we hit the depth cap. Without this transitive seed,
623
+ * a deep edit (root -> barrel -> leaf) would see
624
+ * `reverseGraph.directImporters(leaf) === {}` because only the
625
+ * root's edges got recorded — exactly the bug #189 describes.
626
+ *
627
+ * The walk is I/O-bound but bounded: each node is visited at most
628
+ * once (`visited` set) and we cap the seeding at
629
+ * `DEFAULT_MAX_CLOSURE_DEPTH` hops to keep startup cost predictable
630
+ * on projects with dense import graphs. Subsequent edits still
631
+ * extend the graph via `refreshReverseGraphEdges` in `_doBuild`.
632
+ */
633
+ const seedReverseGraph = async (): Promise<void> => {
634
+ const roots = new Set<string>();
635
+ for (const rootPath of serverModuleSet) roots.add(rootPath);
636
+ for (const rootPath of apiModuleSet) roots.add(rootPath);
637
+ for (const rootPath of clientModuleToRoute.keys()) roots.add(rootPath);
638
+
639
+ const visited = new Set<string>();
640
+ let frontier = Array.from(roots);
641
+
642
+ for (
643
+ let depth = 0;
644
+ depth < DEFAULT_MAX_CLOSURE_DEPTH && frontier.length > 0;
645
+ depth++
646
+ ) {
647
+ // Scan the current frontier in parallel — these are independent
648
+ // file reads. The scan returns the RESOLVED absolute importee
649
+ // paths, which become the next frontier.
650
+ const scans = await Promise.all(
651
+ frontier.map(async (filePath) => {
652
+ if (visited.has(filePath)) return [];
653
+ visited.add(filePath);
654
+ try {
655
+ const imports = await scanFileImports(filePath);
656
+ reverseGraph.update(filePath, imports);
657
+ return imports;
658
+ } catch {
659
+ return [];
660
+ }
661
+ }),
662
+ );
663
+
664
+ const next: string[] = [];
665
+ for (const group of scans) {
666
+ for (const dep of group) {
667
+ if (!visited.has(dep)) next.push(dep);
668
+ }
669
+ }
670
+ frontier = next;
671
+ }
672
+ };
673
+
573
674
  // 파일 감시 설정
574
675
  const watchers: fs.FSWatcher[] = [];
575
676
 
@@ -974,9 +1075,157 @@ export async function startDevBundler(options: DevBundlerOptions): Promise<DevBu
974
1075
  perFileTimers.set(key, timer);
975
1076
  };
976
1077
 
1078
+ /**
1079
+ * #189 — dispatch an unknown-file change against every known root
1080
+ * that transitively imports it.
1081
+ *
1082
+ * The reverse graph answers "which SSR / API / client modules end
1083
+ * up depending on this file?" via a bounded BFS closure. Each
1084
+ * matched root is re-dispatched through the SAME callbacks a
1085
+ * direct change would fire (`onSSRChange`, `onAPIChange`, or an
1086
+ * island rebuild), so downstream behavior is identical to a
1087
+ * direct edit. This closes the "transitive ESM cache" gap
1088
+ * described in issue #189 by making sure every ancestor that
1089
+ * consumed the leaf gets its bundle rebuilt / handler re-
1090
+ * registered.
1091
+ *
1092
+ * Returns the number of roots actually dispatched so the caller
1093
+ * can decide whether to log a "no transitive importers" line or
1094
+ * stay silent. Dispatch is idempotent — each root is touched at
1095
+ * most once per change via the `dispatched` set.
1096
+ */
1097
+ const dispatchByTransitiveImporters = async (
1098
+ changedFile: string,
1099
+ ): Promise<number> => {
1100
+ const absChanged = path.resolve(rootDir, changedFile);
1101
+ // Refresh the changed file's OWN imports first. A leaf edit can
1102
+ // legitimately add or remove imports (e.g. switching a barrel
1103
+ // from `./en` to `./ko`); the reverse graph must track that so
1104
+ // the NEXT unknown-file change uses the correct set.
1105
+ await refreshReverseGraphEdges(absChanged);
1106
+
1107
+ const importers = reverseGraph.transitiveImporters(
1108
+ absChanged,
1109
+ DEFAULT_MAX_CLOSURE_DEPTH,
1110
+ );
1111
+ if (importers.size === 0) return 0;
1112
+
1113
+ // Partition importers by which known-root bucket they belong
1114
+ // to. A single file can be in multiple buckets (e.g. a shared
1115
+ // `.client.tsx` that is also referenced by a server module) —
1116
+ // iterate in priority order: SSR first (heaviest signal), then
1117
+ // API, then client islands.
1118
+ const ssrRoots: string[] = [];
1119
+ const apiRoots: string[] = [];
1120
+ const islandRoots: Array<{ routeId: string; path: string }> = [];
1121
+
1122
+ for (const importerAbs of importers) {
1123
+ if (serverModuleSet.has(importerAbs)) {
1124
+ ssrRoots.push(importerAbs);
1125
+ continue;
1126
+ }
1127
+ if (apiModuleSet.has(importerAbs)) {
1128
+ apiRoots.push(importerAbs);
1129
+ continue;
1130
+ }
1131
+ const islandRouteId = clientModuleToRoute.get(importerAbs);
1132
+ if (islandRouteId) {
1133
+ islandRoots.push({ routeId: islandRouteId, path: importerAbs });
1134
+ }
1135
+ }
1136
+
1137
+ const totalMatched = ssrRoots.length + apiRoots.length + islandRoots.length;
1138
+ if (totalMatched === 0) return 0;
1139
+
1140
+ const relFile = path.relative(rootDir, absChanged).replace(/\\/g, "/");
1141
+ console.log(
1142
+ `\n🔄 ${path.basename(changedFile)} changed — invalidating ${totalMatched} transitive importer(s) (${relFile})`,
1143
+ );
1144
+
1145
+ // SSR: fire once per distinct importer path.
1146
+ if (onSSRChange) {
1147
+ for (const ssrRoot of ssrRoots) {
1148
+ try {
1149
+ await Promise.resolve(onSSRChange(ssrRoot));
1150
+ } catch (err) {
1151
+ console.error(
1152
+ "[Mandu HMR] transitive onSSRChange threw:",
1153
+ err instanceof Error ? err.message : String(err),
1154
+ );
1155
+ }
1156
+ }
1157
+ }
1158
+
1159
+ // API: same pattern.
1160
+ if (onAPIChange) {
1161
+ for (const apiRoot of apiRoots) {
1162
+ try {
1163
+ await Promise.resolve(onAPIChange(apiRoot));
1164
+ } catch (err) {
1165
+ console.error(
1166
+ "[Mandu HMR] transitive onAPIChange threw:",
1167
+ err instanceof Error ? err.message : String(err),
1168
+ );
1169
+ }
1170
+ }
1171
+ }
1172
+
1173
+ // Islands: coalesce to a single build call when multiple routes
1174
+ // share the changed file. `buildClientBundles` with a
1175
+ // `targetRouteIds` list already dedupes internally.
1176
+ if (islandRoots.length > 0) {
1177
+ const targetIds = Array.from(new Set(islandRoots.map((r) => r.routeId)));
1178
+ const startTime = performance.now();
1179
+ try {
1180
+ const result = await buildClientBundles(manifest, rootDir, {
1181
+ minify: false,
1182
+ sourcemap: true,
1183
+ targetRouteIds: targetIds,
1184
+ });
1185
+ const buildTime = performance.now() - startTime;
1186
+ if (result.success) {
1187
+ console.log(
1188
+ `✅ Rebuilt ${targetIds.length} island(s) in ${buildTime.toFixed(0)}ms`,
1189
+ );
1190
+ for (const targetId of targetIds) {
1191
+ onRebuild?.({
1192
+ routeId: targetId,
1193
+ success: true,
1194
+ buildTime,
1195
+ });
1196
+ }
1197
+ } else {
1198
+ console.error("❌ Transitive island rebuild failed:", result.errors);
1199
+ for (const targetId of targetIds) {
1200
+ onRebuild?.({
1201
+ routeId: targetId,
1202
+ success: false,
1203
+ buildTime,
1204
+ error: result.errors.join(", "),
1205
+ });
1206
+ }
1207
+ }
1208
+ } catch (error) {
1209
+ const err = error instanceof Error ? error : new Error(String(error));
1210
+ console.error("❌ Transitive island rebuild error:", err.message);
1211
+ for (const { routeId: targetId } of islandRoots) {
1212
+ onError?.(err, targetId);
1213
+ }
1214
+ }
1215
+ }
1216
+
1217
+ return totalMatched;
1218
+ };
1219
+
977
1220
  const _doBuild = async (changedFile: string) => {
978
1221
  const normalizedPath = normalizeFsPath(changedFile);
979
1222
 
1223
+ // #189 — refresh the changed file's imports so the reverse graph
1224
+ // tracks refactors regardless of which dispatch path fires below.
1225
+ // Fire-and-forget because the scan is I/O-bound and the dispatch
1226
+ // path cannot stall on it.
1227
+ void refreshReverseGraphEdges(path.resolve(rootDir, changedFile));
1228
+
980
1229
  // 공통 컴포넌트 디렉토리 변경 → Island만 재빌드 + SSR 레지스트리 invalidate (#184, #185)
981
1230
  if (isInCommonDir(changedFile)) {
982
1231
  console.log(`\n🔄 Common file changed: ${path.basename(changedFile)}`);
@@ -1053,12 +1302,16 @@ export async function startDevBundler(options: DevBundlerOptions): Promise<DevBu
1053
1302
  // SSR 모듈 변경 감지 (page.tsx, layout.tsx) — #151
1054
1303
  if (onSSRChange && serverModuleSet.has(normalizedPath)) {
1055
1304
  console.log(`\n🔄 SSR file changed: ${path.basename(changedFile)}`);
1305
+ // Refresh the changed file's imports so the reverse graph
1306
+ // tracks refactors (a new import added to an SSR module).
1307
+ await refreshReverseGraphEdges(path.resolve(rootDir, changedFile));
1056
1308
  onSSRChange(normalizedPath);
1057
1309
  return;
1058
1310
  }
1059
1311
  // API 모듈 변경 감지 (route.ts)
1060
1312
  if (onAPIChange && apiModuleSet.has(normalizedPath)) {
1061
1313
  console.log(`\n🔄 API route changed: ${path.basename(changedFile)}`);
1314
+ await refreshReverseGraphEdges(path.resolve(rootDir, changedFile));
1062
1315
  onAPIChange(normalizedPath);
1063
1316
  return;
1064
1317
  }
@@ -1070,7 +1323,23 @@ export async function startDevBundler(options: DevBundlerOptions): Promise<DevBu
1070
1323
  // reuse its existing `handleAPIChange` plumbing.
1071
1324
  if (onAPIChange && isRouteMiddlewareFile(normalizedPath)) {
1072
1325
  console.log(`\n🔄 Middleware changed: ${path.basename(changedFile)}`);
1326
+ await refreshReverseGraphEdges(path.resolve(rootDir, changedFile));
1073
1327
  onAPIChange(normalizedPath);
1328
+ return;
1329
+ }
1330
+ // #189 — reverse import-graph fallback.
1331
+ //
1332
+ // The changed file matched none of our direct dispatch sets.
1333
+ // Before silently dropping (legacy behavior), walk the
1334
+ // reverse graph to see which known roots transitively import
1335
+ // this file and re-dispatch against each one. This is what
1336
+ // makes a deep leaf edit (e.g. a barrel's static-map entry)
1337
+ // propagate without a manual restart.
1338
+ const dispatched = await dispatchByTransitiveImporters(changedFile);
1339
+ if (dispatched === 0) {
1340
+ // No known importer — preserve the legacy silent-drop path
1341
+ // so truly unrelated file changes (editor backups, tmp
1342
+ // files that slipped through the filter) stay cheap.
1074
1343
  }
1075
1344
  return;
1076
1345
  }
@@ -1078,6 +1347,12 @@ export async function startDevBundler(options: DevBundlerOptions): Promise<DevBu
1078
1347
  const route = manifest.routes.find((r) => r.id === routeId);
1079
1348
  if (!route || !route.clientModule) return;
1080
1349
 
1350
+ // #189 — refresh the client island's outgoing imports so the
1351
+ // reverse graph tracks newly added / removed imports in the
1352
+ // island file itself. Fire-and-forget so it cannot stall the
1353
+ // rebuild.
1354
+ void refreshReverseGraphEdges(path.resolve(rootDir, changedFile));
1355
+
1081
1356
  console.log(`\n🔄 Rebuilding island: ${routeId}`);
1082
1357
  const startTime = performance.now();
1083
1358
 
@@ -1223,6 +1498,19 @@ export async function startDevBundler(options: DevBundlerOptions): Promise<DevBu
1223
1498
  }
1224
1499
  }
1225
1500
 
1501
+ // #189 — seed the reverse import-graph AFTER watchers are wired so
1502
+ // any edit that lands during the scan still triggers `handleFileChange`.
1503
+ // The scan is fire-and-forget; the initial build is already complete
1504
+ // and the first user edit can't race the seed (first event goes
1505
+ // through the 100 ms debounce, by which point the scan has finished
1506
+ // for any realistic project size).
1507
+ seedReverseGraph().catch((err) => {
1508
+ console.warn(
1509
+ "[Mandu HMR] reverse import-graph seed skipped:",
1510
+ err instanceof Error ? err.message : String(err),
1511
+ );
1512
+ });
1513
+
1226
1514
  return {
1227
1515
  initialBuild,
1228
1516
  close: () => {
@@ -0,0 +1,339 @@
1
+ /**
2
+ * ReverseImportGraph — #189
3
+ *
4
+ * Tracks `importee -> Set<importer>` edges so the dev watcher can answer
5
+ * "which user modules transitively import this file?" when a file change
6
+ * misses every known root set (SSR / API / client / common-dir).
7
+ *
8
+ * # Why this exists
9
+ *
10
+ * Bun caches ES modules at the process level. When a common/shared file
11
+ * changes, `dev.ts` re-imports that file fresh, but intermediate modules
12
+ * that reference it transitively may retain their cached form. The three
13
+ * real-world patterns flagged in #189:
14
+ *
15
+ * 1. Barrel + static map — `index.ts` builds a lookup at module load,
16
+ * so a new entry in a leaf `translations/ko.ts` never shows up until
17
+ * the intermediate barrel is re-evaluated.
18
+ * 2. Deep re-export chain — `A -> B -> C -> D`. A single edit to `D`
19
+ * requires every ancestor to be refreshed.
20
+ * 3. Module-level singletons / registries whose state is captured at
21
+ * import time.
22
+ *
23
+ * The existing watcher dispatches only when the changed path itself is in
24
+ * `serverModuleSet` / `apiModuleSet` / `clientModuleToRoute` / a common
25
+ * dir. For files that live elsewhere — `app/lib/helper.ts`,
26
+ * `app/_utils/translations/ko.ts`, etc. — the event falls through and
27
+ * the user sees stale output until a manual restart.
28
+ *
29
+ * # Design
30
+ *
31
+ * - `edges: Map<importee -> Set<importer>>` — reverse index.
32
+ * - `forward: Map<importer -> Set<importee>>` — kept so that a
33
+ * subsequent `update(importer, newImports)` can tear down stale edges
34
+ * without iterating the full reverse map.
35
+ * - BFS closure for `transitiveImporters(file, maxDepth)` with an
36
+ * explicit visited set and a defensive depth cap (default 10) to
37
+ * prevent pathological full-graph walks on projects with dense
38
+ * cyclic imports. Every node visited at depth d+1 is checked against
39
+ * `visited` BEFORE enqueue so cycles terminate.
40
+ * - All keys are normalized OS-native absolute paths, lowercased on win32
41
+ * so fs.watch events match regardless of drive-letter casing.
42
+ * - The scanner is a conservative regex over `import ... from "…"`,
43
+ * `export ... from "…"`, and dynamic `import("…")`. We intentionally
44
+ * skip a full AST parse — the goal is "catch the common case cheaply"
45
+ * and the static table never drives code generation, only invalidation
46
+ * routing. A false-negative means the change falls through the existing
47
+ * silent-drop path (unchanged behavior); a false-positive triggers an
48
+ * extra rebuild (acceptable cost).
49
+ * - Only first-party (relative / alias-resolvable) imports are recorded.
50
+ * Bare `react`, `@mandujs/core`, etc. are skipped so the graph never
51
+ * tracks node_modules.
52
+ *
53
+ * # What this does NOT do
54
+ *
55
+ * - Does not resolve TypeScript path aliases from `tsconfig.json`. A
56
+ * future pass can wire the `compilerOptions.paths` map in, but the
57
+ * relative-import case covers the scenarios in the issue.
58
+ * - Does not track CSS `@import` — the CSS-update path already has its
59
+ * own mechanism in `dev.ts`.
60
+ * - Does not persist. In-memory only; rebuilt from scratch on dev-server
61
+ * start.
62
+ */
63
+
64
+ import fs from "fs";
65
+ import path from "path";
66
+
67
+ /**
68
+ * Default safety cap for `transitiveImporters` BFS. 10 hops is deep
69
+ * enough for any realistic barrel chain while stopping cold on
70
+ * degenerate graphs (e.g. a project with everything re-exporting
71
+ * everything).
72
+ */
73
+ export const DEFAULT_MAX_CLOSURE_DEPTH = 10;
74
+
75
+ /** Normalize an fs path to the form the watcher emits (forward slash, lowercase on win32). */
76
+ function normalize(p: string): string {
77
+ const abs = path.resolve(p).replace(/\\/g, "/");
78
+ return process.platform === "win32" ? abs.toLowerCase() : abs;
79
+ }
80
+
81
+ /**
82
+ * Return true for a specifier that points at a first-party module we
83
+ * can resolve on disk. Bare specifiers (`react`, `@scope/pkg`) are
84
+ * filtered out so the graph never grows with node_modules edges.
85
+ */
86
+ function isFirstPartySpecifier(spec: string): boolean {
87
+ if (spec.length === 0) return false;
88
+ // `./foo`, `../bar`, `/abs/path` — first-party for sure.
89
+ if (spec.startsWith("./") || spec.startsWith("../") || spec.startsWith("/")) {
90
+ return true;
91
+ }
92
+ // Windows absolute path. `fs.watch` never emits this shape, but a
93
+ // user file could in theory reference one — reject for the same
94
+ // reason we reject node_modules: the file isn't in the reactive tree.
95
+ if (/^[A-Za-z]:[\\/]/.test(spec)) return false;
96
+ // Everything else — bare module — is external.
97
+ return false;
98
+ }
99
+
100
+ /**
101
+ * Extensions we try (in order) when a specifier has no explicit
102
+ * extension. Mirrors the set Bun itself would walk for a relative
103
+ * import inside the monorepo.
104
+ */
105
+ const RESOLVE_EXTENSIONS = [".ts", ".tsx", ".js", ".jsx", ".mjs", ".cjs"] as const;
106
+
107
+ /**
108
+ * Resolve a relative specifier from `fromFile`'s directory to an
109
+ * absolute on-disk path. Returns `null` when the target cannot be
110
+ * found (e.g. a typed-only stub, a file the user has not yet
111
+ * written). Callers treat `null` as "skip this edge".
112
+ *
113
+ * Exported for tests; production code uses it via `scanFileImports`.
114
+ */
115
+ export function resolveRelativeImport(fromFile: string, specifier: string): string | null {
116
+ if (!isFirstPartySpecifier(specifier)) return null;
117
+ const fromDir = path.dirname(fromFile);
118
+ const base = path.resolve(fromDir, specifier);
119
+ // If the path already has a recognized extension, test it directly.
120
+ if (RESOLVE_EXTENSIONS.some((e) => base.endsWith(e))) {
121
+ return fs.existsSync(base) ? base : null;
122
+ }
123
+ // Try each extension + `/index.<ext>` so barrel directories resolve.
124
+ for (const ext of RESOLVE_EXTENSIONS) {
125
+ const candidate = base + ext;
126
+ if (fs.existsSync(candidate)) return candidate;
127
+ }
128
+ for (const ext of RESOLVE_EXTENSIONS) {
129
+ const candidate = path.join(base, "index" + ext);
130
+ if (fs.existsSync(candidate)) return candidate;
131
+ }
132
+ return null;
133
+ }
134
+
135
+ // Static-import, export-from, and dynamic import patterns. Written
136
+ // conservatively: each regex consumes a single pair of matching quotes,
137
+ // never spans newlines, and does not attempt to handle template literals
138
+ // (dynamic `import(\`…\`)` with interpolation is inherently unresolvable
139
+ // statically).
140
+ const IMPORT_PATTERNS: readonly RegExp[] = [
141
+ // `import foo from "…"` / `import { x } from "…"` / `import "…"` / `import type { x } from "…"`
142
+ /\bimport\s+(?:type\s+)?(?:[^'"\n;]*?\bfrom\s+)?['"]([^'"\n]+)['"]/g,
143
+ // `export { x } from "…"` / `export * from "…"`
144
+ /\bexport\s+(?:\*|\{[^}]*\})\s+from\s+['"]([^'"\n]+)['"]/g,
145
+ // `import("…")` — dynamic. Template literals (`) intentionally excluded.
146
+ /\bimport\s*\(\s*['"]([^'"\n]+)['"]\s*\)/g,
147
+ ];
148
+
149
+ /**
150
+ * Scan a file's source text for first-party import specifiers. Returns
151
+ * the raw specifiers (not resolved). Callers usually pair this with
152
+ * `resolveRelativeImport` to get absolute paths.
153
+ *
154
+ * The parser is intentionally regex-based — we do not want to pay the
155
+ * cost of a full AST traverse on every file change. See the module
156
+ * header for the false-positive/negative trade-off.
157
+ */
158
+ export function extractImportSpecifiers(source: string): string[] {
159
+ const out = new Set<string>();
160
+ for (const pattern of IMPORT_PATTERNS) {
161
+ // Reset lastIndex — the regex has `/g` so reuse across calls would
162
+ // otherwise skip matches in later invocations.
163
+ pattern.lastIndex = 0;
164
+ let match: RegExpExecArray | null;
165
+ while ((match = pattern.exec(source)) !== null) {
166
+ const spec = match[1];
167
+ if (typeof spec === "string" && spec.length > 0) out.add(spec);
168
+ }
169
+ }
170
+ return Array.from(out);
171
+ }
172
+
173
+ /**
174
+ * Read a file from disk and return the absolute paths of every
175
+ * resolvable first-party import it contains. Non-existent files and
176
+ * unreadable files both return an empty array (treated as "no edges
177
+ * to record"). Async so the dev server can batch this work off the
178
+ * main event loop.
179
+ */
180
+ export async function scanFileImports(filePath: string): Promise<string[]> {
181
+ let source: string;
182
+ try {
183
+ source = await fs.promises.readFile(filePath, "utf-8");
184
+ } catch {
185
+ return [];
186
+ }
187
+ const specifiers = extractImportSpecifiers(source);
188
+ const out: string[] = [];
189
+ for (const spec of specifiers) {
190
+ const resolved = resolveRelativeImport(filePath, spec);
191
+ if (resolved) out.push(resolved);
192
+ }
193
+ return out;
194
+ }
195
+
196
+ /**
197
+ * Reverse-import graph with a bounded BFS closure API. All public
198
+ * methods accept raw paths; normalization is applied internally.
199
+ */
200
+ export class ReverseImportGraph {
201
+ /** importee -> set of direct importers. */
202
+ private readonly edges = new Map<string, Set<string>>();
203
+ /** importer -> set of direct importees. Kept so `update` is O(|old imports|). */
204
+ private readonly forward = new Map<string, Set<string>>();
205
+
206
+ /**
207
+ * Replace the outgoing edges for `importerFile`. Any prior importees
208
+ * that no longer appear drop the importer from their reverse set so
209
+ * the graph doesn't accumulate stale pointers.
210
+ */
211
+ update(importerFile: string, importeePaths: Iterable<string>): void {
212
+ const importer = normalize(importerFile);
213
+
214
+ // Tear down the previous forward entries.
215
+ const prev = this.forward.get(importer);
216
+ if (prev) {
217
+ for (const importee of prev) {
218
+ const back = this.edges.get(importee);
219
+ if (!back) continue;
220
+ back.delete(importer);
221
+ if (back.size === 0) this.edges.delete(importee);
222
+ }
223
+ }
224
+
225
+ // Build the new forward entry + reverse edges. We normalize inside
226
+ // the loop so the caller can pass unnormalized paths.
227
+ const next = new Set<string>();
228
+ for (const raw of importeePaths) {
229
+ const importee = normalize(raw);
230
+ // Self-edges would create a trivial cycle the BFS has to skip.
231
+ // Drop them at insert time so the visited-check is the only
232
+ // cycle defense we need downstream.
233
+ if (importee === importer) continue;
234
+ next.add(importee);
235
+ let back = this.edges.get(importee);
236
+ if (!back) {
237
+ back = new Set<string>();
238
+ this.edges.set(importee, back);
239
+ }
240
+ back.add(importer);
241
+ }
242
+ if (next.size === 0) {
243
+ this.forward.delete(importer);
244
+ } else {
245
+ this.forward.set(importer, next);
246
+ }
247
+ }
248
+
249
+ /** Forget a single importer. Reverse edges pointing at its importees are cleaned up. */
250
+ remove(importerFile: string): void {
251
+ const importer = normalize(importerFile);
252
+ const prev = this.forward.get(importer);
253
+ if (!prev) return;
254
+ for (const importee of prev) {
255
+ const back = this.edges.get(importee);
256
+ if (!back) continue;
257
+ back.delete(importer);
258
+ if (back.size === 0) this.edges.delete(importee);
259
+ }
260
+ this.forward.delete(importer);
261
+ }
262
+
263
+ /** Direct importers of `file` — the single-hop reverse lookup. */
264
+ directImporters(file: string): ReadonlySet<string> {
265
+ const set = this.edges.get(normalize(file));
266
+ return set ?? new Set<string>();
267
+ }
268
+
269
+ /**
270
+ * Transitive importers of `file`. Returns the normalized set
271
+ * excluding `file` itself. BFS with cycle detection; every node is
272
+ * visited at most once. Capped at `maxDepth` hops so a pathological
273
+ * graph cannot degrade a single file change into a full-project walk.
274
+ *
275
+ * Depth 0 is the changed file itself (not included in the result).
276
+ * Depth 1 is the set returned by `directImporters`. Depth N is the
277
+ * set of modules whose shortest path to `file` is exactly N hops.
278
+ */
279
+ transitiveImporters(
280
+ file: string,
281
+ maxDepth: number = DEFAULT_MAX_CLOSURE_DEPTH,
282
+ ): Set<string> {
283
+ const target = normalize(file);
284
+ const result = new Set<string>();
285
+ // Guard against 0 / negative depth — those are no-ops.
286
+ if (!Number.isFinite(maxDepth) || maxDepth <= 0) return result;
287
+
288
+ let frontier = new Set<string>([target]);
289
+ const visited = new Set<string>([target]);
290
+
291
+ for (let depth = 0; depth < maxDepth && frontier.size > 0; depth++) {
292
+ const next = new Set<string>();
293
+ for (const node of frontier) {
294
+ const directs = this.edges.get(node);
295
+ if (!directs) continue;
296
+ for (const importer of directs) {
297
+ if (visited.has(importer)) continue;
298
+ visited.add(importer);
299
+ result.add(importer);
300
+ next.add(importer);
301
+ }
302
+ }
303
+ frontier = next;
304
+ }
305
+ return result;
306
+ }
307
+
308
+ /** True if any edge points at `file`. Useful for fast "do we know this file?" checks. */
309
+ knows(file: string): boolean {
310
+ const key = normalize(file);
311
+ return this.edges.has(key) || this.forward.has(key);
312
+ }
313
+
314
+ /** Drop everything (dev-server restart). */
315
+ clear(): void {
316
+ this.edges.clear();
317
+ this.forward.clear();
318
+ }
319
+
320
+ /** Total number of tracked importer modules (for diagnostics). */
321
+ get size(): number {
322
+ return this.forward.size;
323
+ }
324
+
325
+ /**
326
+ * Dump the current state as plain JSON. Intended for debug
327
+ * assertions in unit tests, not for production hot paths.
328
+ */
329
+ _inspect(): {
330
+ forward: Record<string, string[]>;
331
+ reverse: Record<string, string[]>;
332
+ } {
333
+ const forward: Record<string, string[]> = {};
334
+ for (const [k, v] of this.forward) forward[k] = Array.from(v);
335
+ const reverse: Record<string, string[]> = {};
336
+ for (const [k, v] of this.edges) reverse[k] = Array.from(v);
337
+ return { forward, reverse };
338
+ }
339
+ }