deps-conflict-resolver 1.1.1 → 1.1.2

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/README.en.md CHANGED
@@ -10,7 +10,7 @@ A Webpack and Vite plugin that automatically resolves peer dependency conflicts
10
10
 
11
11
  ## Features
12
12
 
13
- - **Recursive Dependency Analysis**: Deep traversal of the entire dependency tree, including nested sub-dependencies
13
+ - **Recursive Dependency Analysis**: Deep traversal of the entire dependency tree, including nested sub-dependencies, while preserving nested instances by their installed paths
14
14
  - **Smart Conflict Detection**: Automatically identifies peer dependency version conflicts against the host project
15
15
  - **Automatic Alias Installation**: Creates aliases for conflicting dependencies and installs the appropriate versions
16
16
  - **Module Resolution Redirection**: At build time, redirects module imports from conflicting libraries to their aliased versions
@@ -105,7 +105,7 @@ const resolved = resolver.resolveModule('vue', '/path/to/importer.js');
105
105
  | `projectRoot` | `string` | `process.cwd()` | Project root directory path |
106
106
  | `autoInstall` | `boolean` | `true` | Whether to auto-install missing aliased dependencies |
107
107
  | `packageManager` | `'auto' \| 'npm' \| 'yarn' \| 'pnpm'` | `'auto'` | Package manager type. `'auto'` detects automatically |
108
- | `registry` | `string` | Auto-detected | npm registry URL. Falls back to `.npmrc` if not specified |
108
+ | `registry` | `string` | Auto-detected | npm registry URL; an explicit value is used for both version queries and alias installation |
109
109
  | `debug` | `boolean` | `false` | Whether to enable debug logging |
110
110
  | `aliasPrefix` | `string` | `'aliased-'` | Prefix for generated alias names |
111
111
  | `excludeRedirects` | `Record<string, string[]>` | `{}` | Exclude specific packages from the redirect list. Keys are original package names, values are importer package names to exclude. Example: `{ vue: ['vue-demi', 'pinia'] }` |
@@ -132,9 +132,11 @@ The plugin supports automatic detection of the package manager and registry:
132
132
 
133
133
  1. Project-level `.npmrc` file
134
134
  2. User-level `~/.npmrc` file
135
- 3. `.yarnrc.yml` in yarn projects
135
+ 3. User-level `.pnpmrc` for pnpm or `.yarnrc.yml` in yarn projects
136
136
  4. Falls back to `https://registry.npmjs.org`
137
137
 
138
+ An explicit `registry` option overrides this detection. The resolver uses it for remote version queries, and the package manager uses the same registry when installing aliases.
139
+
138
140
  ## How It Works
139
141
 
140
142
  ### 1. Dependency Analysis
@@ -158,7 +160,7 @@ Compares installed versions in the host project against peer dependency requirem
158
160
 
159
161
  ### 3. Version Resolution
160
162
 
161
- Fetches available versions from the npm registry and selects the best version that satisfies all peer dependency ranges:
163
+ Before making a remote request, the resolver checks installed local and workspace npm aliases whose package identity and version satisfy the conflicting range. A matching alias is reused offline with no registry access or reinstall; only unresolved requests query the registry and select the best version that satisfies all peer dependency ranges:
162
164
 
163
165
  - `vue@^2.0.0` → selects `vue@2.7.14`
164
166
  - `vue-router@^3.0.0` → selects `vue-router@3.6.5`
@@ -186,12 +188,14 @@ import Vue from 'vue'; // → resolves to vue (3.x)
186
188
 
187
189
  ### Behavioral Boundaries
188
190
 
189
- - **Conflict Detection Scope**: Only the first-level `peerDependencies` of user-specified `dependencies` are checked for version conflicts against the host project. Sub-dependency `peerDependencies` do not trigger alias installation.
191
+ - **Conflict Detection Scope**: Only the first-level `peerDependencies` of user-specified `dependencies` are checked for version conflicts against the host project. Sub-dependency `peerDependencies` still contribute to graph construction and runtime redirect matching, but do not independently trigger alias installation. First-level peers marked `optional: true` are skipped entirely: they produce no conflict, missing-peer warning, or alias.
190
192
  - **Redirect Scope**: Packages that declare conflicting peers and all their sub-dependencies (`dependencies` + `peerDependencies` recursively) are added to the redirect candidate list. The conflict target packages themselves (e.g., `vue`, `vue-router`) are automatically excluded during collection to prevent host project imports from being incorrectly redirected.
193
+ - **Nested Versions**: The installed dependency graph is keyed by normalized package directories, and each child is resolved relative to its owning package. Nested instances with the same name but different versions remain distinct; generated redirect rules prefer importer-path matching. Consequently, `excludeRedirects` applies to concrete package instances and their subtrees rather than globally deduplicating by name.
191
194
  - **`excludeRedirects`**: Removes specified packages from the redirect candidate list. Useful for shared packages (e.g., `vue-demi`, `pinia`) that actually use the host's Vue 3 version at runtime.
192
195
  - **`includeRedirects`**: Forces specified packages into the redirect list. Useful when semver ranges are too broad (e.g., `vue: ">=2.5.0"` satisfies both Vue 2 and Vue 3) but the package still needs the older version at runtime. `includeRedirects` is applied before `excludeRedirects`.
193
- - **Alias Installation**: Aliases are only auto-installed for dependencies that are "declared by the host project with a version conflict." Undeclared peer dependencies only emit a warning without auto-installation.
194
- - **Dependency Graph Deduplication**: The dependency tree traversal deduplicates by package name (each package is analyzed only once). In rare cases where multiple different versions of the same package name are nested, only the first resolved version is analyzed. This has minimal impact on redirect results since redirect matching is based on package name, not version.
196
+ - **Alias Installation and Reuse**: Aliases are only auto-installed for dependencies that are "declared by the host project with a version conflict." Undeclared peer dependencies only emit a warning without auto-installation. A matching installed local or workspace alias is reused without registry access or installation; a declared but uninstalled workspace alias is not reusable. If an existing alias directory has the wrong identity or version, the resolver reports a collision and leaves that directory unchanged rather than replacing it.
197
+ - **Registry**: An explicit `registry` value controls both remote version resolution and package-manager alias installation; automatic detection is used only when it is omitted.
198
+ - **Initialization Failure Policy**: `createResolver()` and the Vite plugin propagate initialization failures to the caller. The Webpack plugin remains fail-open: initialization or module-resolution errors are logged and compilation continues without aliases for that generation. Each Webpack `watchRun` invalidates the previous generation, waits for a fresh analysis, and can retry on the next watch cycle if initialization fails.
195
199
 
196
200
  ## Advanced Usage
197
201
 
@@ -206,9 +210,9 @@ depsConflictResolverVitePlugin({
206
210
  console.log('Found conflicts:', result.peerConflicts);
207
211
  },
208
212
 
209
- // After installation completes
210
- onInstallComplete: (installed) => {
211
- console.log('Installed aliases:', installed);
213
+ // After the installation attempt completes
214
+ onInstallComplete: (mappings) => {
215
+ console.log('Alias mappings after install attempt:', mappings);
212
216
  },
213
217
 
214
218
  // Custom module resolution
@@ -223,6 +227,8 @@ depsConflictResolverVitePlugin({
223
227
  });
224
228
  ```
225
229
 
230
+ `onInstallComplete` runs after the installation attempt; its argument is the alias mappings produced by that analysis and does not guarantee that every mapping was installed successfully (reused, installed, and failed outcomes must be checked in logs or installation results).
231
+
226
232
  ### Fine-Grained Redirect Control (includeRedirects + excludeRedirects)
227
233
 
228
234
  When a project contains both Vue 2 and Vue 3 dependencies, auto-detection may not accurately distinguish them. Use these two options for manual control:
@@ -250,7 +256,7 @@ Priority: `includeRedirects` is applied first, then `excludeRedirects`. If the s
250
256
 
251
257
  ### Reusing Existing Aliases
252
258
 
253
- If the project already has aliases installed with suitable versions (e.g., `vue2@npm:vue@2.6.14`), the plugin will automatically detect and reuse them without reinstalling.
259
+ If the project already has aliases installed with suitable versions (e.g., `vue2@npm:vue@2.6.14`), the plugin detects and reuses them before contacting the registry, without reinstalling. Workspace aliases are reusable only when actually installed and when package identity/version validation succeeds. A mismatched existing directory is reported as a collision and left unchanged.
254
260
 
255
261
  ## API Reference
256
262
 
package/README.md CHANGED
@@ -10,7 +10,7 @@
10
10
 
11
11
  ## 功能特性
12
12
 
13
- - 🔍 **递归依赖分析**:深度分析依赖树中的所有子依赖、孙依赖
13
+ - 🔍 **递归依赖分析**:深度遍历依赖树中的所有子依赖、孙依赖,并按实际安装路径区分嵌套实例
14
14
  - 🎯 **智能冲突检测**:自动识别 peer 依赖与主工程的版本冲突
15
15
  - 📦 **自动别名安装**:为冲突的依赖创建别名并自动安装合适的版本
16
16
  - 🔄 **模块解析重定向**:在运行时自动将模块引用重定向到正确的别名版本
@@ -105,7 +105,7 @@ const resolved = resolver.resolveModule('vue', '/path/to/importer.js');
105
105
  | `projectRoot` | `string` | `process.cwd()` | 项目根目录路径 |
106
106
  | `autoInstall` | `boolean` | `true` | 是否自动安装缺失的别名依赖 |
107
107
  | `packageManager` | `'auto' \| 'npm' \| 'yarn' \| 'pnpm'` | `'auto'` | 包管理器类型,`'auto'` 自动检测 |
108
- | `registry` | `string` | 自动检测 | NPM 注册表地址,不指定则自动从 .npmrc 读取 |
108
+ | `registry` | `string` | 自动检测 | NPM 注册表地址;显式指定时同时用于版本查询和别名安装 |
109
109
  | `debug` | `boolean` | `false` | 是否启用调试日志 |
110
110
  | `aliasPrefix` | `string` | `'aliased-'` | 别名前缀 |
111
111
  | `excludeRedirects` | `Record<string, string[]>` | `{}` | 从重定向列表中排除特定包。键为原始包名,值为要排除的 importer 包名列表。示例:`{ vue: ['vue-demi', 'pinia'] }` |
@@ -132,9 +132,11 @@ const resolved = resolver.resolveModule('vue', '/path/to/importer.js');
132
132
 
133
133
  1. 项目级 `.npmrc` 文件
134
134
  2. 用户级 `~/.npmrc` 文件
135
- 3. yarn 项目的 `.yarnrc.yml` 文件
135
+ 3. pnpm 的用户级 `.pnpmrc` 或 yarn 项目的 `.yarnrc.yml` 文件
136
136
  4. 默认使用 `https://registry.npmjs.org`
137
137
 
138
+ 显式设置 `registry` 时会覆盖上述自动检测结果:解析器从该地址查询可用版本,包管理器安装别名时也使用同一地址。
139
+
138
140
  ## 工作原理
139
141
 
140
142
  ### 1. 依赖分析
@@ -158,7 +160,7 @@ package-a
158
160
 
159
161
  ### 3. 版本解析
160
162
 
161
- 从 npm 注册表获取可用版本列表,找到满足所有 peer 依赖范围的最佳版本:
163
+ 先检查项目或 workspace 中已经安装、且包名和版本都匹配的 npm alias。可复用的 alias 会直接离线使用,不访问 registry,也不会重复安装;只有未匹配的请求才从 registry 获取版本列表,并找到满足所有 peer 依赖范围的最佳版本:
162
164
 
163
165
  - `vue@^2.0.0` → 选择 `vue@2.7.14`
164
166
  - `vue-router@^3.0.0` → 选择 `vue-router@3.6.5`
@@ -186,12 +188,14 @@ import Vue from 'vue'; // → 解析到 vue (3.x)
186
188
 
187
189
  ### 行为边界
188
190
 
189
- - **冲突检测范围**:只检测用户指定的 `dependencies` 的第一层 `peerDependencies` 与主工程的版本冲突。子依赖的 `peerDependencies` 不触发别名安装。
190
- - **重定向范围**:声明冲突 peer 的包及其所有子依赖(`dependencies` + `peerDependencies` 递归)都会被收入重定向候选列表。冲突包自身(如 `vue`、`vue-router`)在收集时会被自动排除,避免主工程的同名引用被错误重定向。
191
+ - **冲突检测范围**:只检测用户指定的 `dependencies` 的第一层 `peerDependencies` 与主工程的版本冲突。子依赖的 `peerDependencies` 会参与依赖图构建和运行时重定向判断,但不会单独触发别名安装。标记为 `optional: true` 的第一层 peer 会完全跳过,不产生冲突、missing 警告或 alias。
192
+ - **重定向范围**:冲突 peer 的声明包及其 `dependencies`/`peerDependencies` 会递归加入重定向候选列表;冲突目标包自身(如 `vue`、`vue-router`)会被排除,避免主工程引用被误重定向。
193
+ - **嵌套版本**:依赖图以规范化的实际安装目录为节点,并从所属包目录解析子依赖。同名但不同版本的嵌套实例会保留为不同节点,生成的重定向规则优先按 importer 路径匹配;因此 `excludeRedirects` 也会作用于具体实例及其子树,而不是简单按包名全局去重。
191
194
  - **`excludeRedirects`**:从重定向候选列表中剔除指定包,适用于运行时实际使用宿主 Vue 3 版本的共享包(如 `vue-demi`、`pinia`)。
192
195
  - **`includeRedirects`**:将指定包强制加入重定向列表,适用于 semver 范围写得过宽(如 `vue: ">=2.5.0"` 同时满足 Vue 2/3),但运行时仍需要使用旧版本的包。`includeRedirects` 在 `excludeRedirects` 之前应用。
193
- - **别名安装**:只为"主工程已声明且版本冲突"的依赖自动安装别名。未声明的 peer 依赖只会输出警告,不自动安装。
194
- - **依赖图去重**:依赖树遍历按包名去重(同名包只分析一次)。在极少数情况下,如同一包名存在多个不同版本的嵌套安装,只有第一个被解析到的版本会被分析。这对重定向结果的影响极小,因为重定向判断只基于包名匹配,不涉及版本。
196
+ - **别名安装与复用**:只为“主工程已声明且版本冲突”的依赖自动安装别名;未声明的 peer 依赖只输出警告,不自动安装。已安装且身份/版本匹配的 local 或 workspace alias 会复用(无需 registry 和安装);声明但尚未安装的 workspace alias 不算可复用。已有目录身份或版本不匹配时会报告 alias collision,并保持原目录不变,不原地覆盖。
197
+ - **Registry**:`registry` 显式配置同时约束远程版本查询和包管理器安装;未配置时才按项目/用户配置自动检测。
198
+ - **初始化失败策略**:核心 `createResolver()` 与 Vite 插件会把初始化错误交给调用方;Webpack 插件保持 fail-open,初始化或模块解析失败只记录错误并继续编译(该轮不会应用 alias)。Webpack watch 每次 `watchRun` 会先失效旧 generation,再等待新分析;新一轮失败时仍可在后续 watch 周期重试。
195
199
 
196
200
  ## 高级用法
197
201
 
@@ -206,9 +210,9 @@ depsConflictResolverVitePlugin({
206
210
  console.log('Found conflicts:', result.peerConflicts);
207
211
  },
208
212
 
209
- // 安装完成后
210
- onInstallComplete: (installed) => {
211
- console.log('Installed aliases:', installed);
213
+ // 安装尝试完成后
214
+ onInstallComplete: (mappings) => {
215
+ console.log('Alias mappings after install attempt:', mappings);
212
216
  },
213
217
 
214
218
  // 自定义模块解析
@@ -223,6 +227,8 @@ depsConflictResolverVitePlugin({
223
227
  });
224
228
  ```
225
229
 
230
+ `onInstallComplete` 在安装尝试结束后触发;其参数是本轮分析得到的 alias mappings,并不表示每个 mapping 都已成功安装(已复用、已安装和失败项需结合日志或安装结果判断)。
231
+
226
232
  ### 精细控制重定向范围(includeRedirects + excludeRedirects)
227
233
 
228
234
  当项目同时包含 Vue 2 依赖和 Vue 3 依赖时,自动检测可能无法准确区分。可以用这两个选项手动调节:
@@ -250,7 +256,7 @@ new DepsConflictResolverWebpackPlugin({
250
256
 
251
257
  ### 复用已有别名
252
258
 
253
- 如果项目中已经安装了合适版本的别名(如 `vue2@npm:vue@2.6.14`),插件会自动检测并复用,不会重复安装。
259
+ 如果项目中已经安装了合适版本的别名(如 `vue2@npm:vue@2.6.14`),插件会在访问 registry 前自动检测并复用,不会重复安装;workspace alias 只有在实际安装且包名/版本验证通过时才会复用。若现有目录不匹配,插件会报告冲突并保留原目录。
254
260
 
255
261
  ## API 参考
256
262
 
package/dist/index.cjs CHANGED
@@ -908,6 +908,67 @@ var npmRegistryClient = {
908
908
  return info?.versions ?? [];
909
909
  }
910
910
  };
911
+ function normalizePackagePath(packagePath) {
912
+ try {
913
+ return fs.realpathSync(packagePath);
914
+ } catch {
915
+ return path.resolve(packagePath);
916
+ }
917
+ }
918
+ function buildInstalledDependencyGraph(packageNames, projectRoot) {
919
+ const nodes = /* @__PURE__ */ new Map();
920
+ const roots = [];
921
+ const stack = [];
922
+ for (let index = packageNames.length - 1; index >= 0; index--) {
923
+ const name = packageNames[index];
924
+ if (name) stack.push({ name, baseDir: projectRoot, parentId: null, root: true });
925
+ }
926
+ while (stack.length > 0) {
927
+ const item = stack.pop();
928
+ if (!item) continue;
929
+ const packagePath = findPackagePath(item.name, item.baseDir);
930
+ if (!packagePath) continue;
931
+ const normalizedPath = normalizePackagePath(packagePath);
932
+ const existingNode = nodes.get(normalizedPath);
933
+ if (existingNode) {
934
+ if (item.root) {
935
+ existingNode.parentId = null;
936
+ }
937
+ if (item.root && !roots.includes(normalizedPath)) {
938
+ roots.push(normalizedPath);
939
+ }
940
+ continue;
941
+ }
942
+ const packageJson = readPackageJsonCached(normalizedPath);
943
+ if (!packageJson) continue;
944
+ const dependencyNames = Object.keys(packageJson.dependencies ?? {});
945
+ const peerDependencyNames = Object.keys(packageJson.peerDependencies ?? {});
946
+ const node = {
947
+ id: normalizedPath,
948
+ name: item.name,
949
+ version: packageJson.version ?? "unknown",
950
+ packagePath: normalizedPath,
951
+ parentId: item.parentId,
952
+ dependencyNames,
953
+ peerDependencyNames
954
+ };
955
+ nodes.set(normalizedPath, node);
956
+ if (item.root) roots.push(normalizedPath);
957
+ const childNames = [...dependencyNames, ...peerDependencyNames];
958
+ for (let index = childNames.length - 1; index >= 0; index--) {
959
+ const childName = childNames[index];
960
+ if (childName) {
961
+ stack.push({
962
+ name: childName,
963
+ baseDir: normalizedPath,
964
+ parentId: normalizedPath,
965
+ root: false
966
+ });
967
+ }
968
+ }
969
+ }
970
+ return { nodes, roots };
971
+ }
911
972
 
912
973
  // src/core/dependency-analyzer.ts
913
974
  var logger4 = createLogger("dependency-analyzer");
@@ -939,6 +1000,8 @@ var DependencyAnalyzer = class {
939
1000
  workspaceRootDeclaredLoaded = false;
940
1001
  /** collectAllRelatedPackages 的 memo 缓存(单次 analyze 生命周期内有效) */
941
1002
  collectCache = /* @__PURE__ */ new Map();
1003
+ /** 当前 analyze 使用的按安装路径区分的依赖图 */
1004
+ dependencyGraph = null;
942
1005
  /** 注册表访问适配器(可注入以支持离线分析和确定性测试) */
943
1006
  registryClient;
944
1007
  constructor(options, mainPackageJson, installedDeps, registryClient = npmRegistryClient) {
@@ -995,15 +1058,6 @@ var DependencyAnalyzer = class {
995
1058
  ...rootPkgJson.devDependencies
996
1059
  };
997
1060
  }
998
- /** Keep generated alias names clear of host and workspace dependencies. */
999
- getReservedDependencyNames() {
1000
- this.ensureWorkspaceRootDeclaredDepsLoaded();
1001
- return /* @__PURE__ */ new Set([
1002
- ...Object.keys(this.rawDeclaredDeps),
1003
- ...Object.keys(this.declaredDeps),
1004
- ...Object.keys(this.workspaceRootDeclaredDeps)
1005
- ]);
1006
- }
1007
1061
  /**
1008
1062
  * 判断某个包是否在“主工程”声明(dependencies/devDependencies)
1009
1063
  *
@@ -1097,6 +1151,10 @@ var DependencyAnalyzer = class {
1097
1151
  try {
1098
1152
  this.resolveCatalogDependencies();
1099
1153
  this.ensureWorkspaceRootDeclaredDepsLoaded();
1154
+ this.dependencyGraph = buildInstalledDependencyGraph(
1155
+ this.options.dependencies,
1156
+ this.options.projectRoot
1157
+ );
1100
1158
  for (const depName of this.options.dependencies) {
1101
1159
  this.analyzeDependencyRecursive(depName, []);
1102
1160
  }
@@ -1125,12 +1183,18 @@ var DependencyAnalyzer = class {
1125
1183
  this.rawDeclaredDeps = {};
1126
1184
  this.declaredDeps = {};
1127
1185
  this.collectCache.clear();
1186
+ this.dependencyGraph = null;
1128
1187
  }
1129
1188
  }
1130
1189
  /**
1131
1190
  * 递归分析单个依赖及其所有子依赖
1132
1191
  */
1133
1192
  analyzeDependencyRecursive(packageName, dependencyPath) {
1193
+ const graphRoot = this.findGraphRoot(packageName);
1194
+ if (graphRoot) {
1195
+ this.populateAnalyzedDependenciesFromGraph();
1196
+ return this.analyzedDependencies.get(graphRoot.name) ?? null;
1197
+ }
1134
1198
  if (this.visitedPackages.has(packageName)) {
1135
1199
  logger4.debug(`Skipping already visited package: ${packageName}`);
1136
1200
  return this.analyzedDependencies.get(packageName) ?? null;
@@ -1185,6 +1249,69 @@ var DependencyAnalyzer = class {
1185
1249
  }
1186
1250
  return rootInfo;
1187
1251
  }
1252
+ findGraphRoot(packageName) {
1253
+ if (!this.dependencyGraph) return null;
1254
+ for (const rootId of this.dependencyGraph.roots) {
1255
+ const root = this.dependencyGraph.nodes.get(rootId);
1256
+ if (root?.name === packageName) return root;
1257
+ }
1258
+ return null;
1259
+ }
1260
+ getDependencyPathForGraphNode(node) {
1261
+ if (!this.dependencyGraph) return [];
1262
+ const names = [];
1263
+ let current = node;
1264
+ const visited = /* @__PURE__ */ new Set();
1265
+ while (current && !visited.has(current.id)) {
1266
+ visited.add(current.id);
1267
+ names.unshift(current.name);
1268
+ current = current.parentId ? this.dependencyGraph.nodes.get(current.parentId) : void 0;
1269
+ }
1270
+ return names.slice(0, -1);
1271
+ }
1272
+ populateAnalyzedDependenciesFromGraph() {
1273
+ if (!this.dependencyGraph) return;
1274
+ const rootVisibleNodeIds = /* @__PURE__ */ new Map();
1275
+ for (const node of this.dependencyGraph.nodes.values()) {
1276
+ const rootVisiblePath = findPackagePath(node.name, this.options.projectRoot);
1277
+ if (!rootVisiblePath) continue;
1278
+ const rootVisibleNode = this.dependencyGraph.nodes.get(
1279
+ this.normalizeInstalledPath(rootVisiblePath)
1280
+ );
1281
+ if (rootVisibleNode && !rootVisibleNodeIds.has(node.name)) {
1282
+ rootVisibleNodeIds.set(node.name, rootVisibleNode.id);
1283
+ }
1284
+ }
1285
+ const orderedNodes = [];
1286
+ const selectedNodeIds = /* @__PURE__ */ new Set();
1287
+ for (const nodeId of rootVisibleNodeIds.values()) {
1288
+ const node = this.dependencyGraph.nodes.get(nodeId);
1289
+ if (node && !selectedNodeIds.has(node.id)) {
1290
+ selectedNodeIds.add(node.id);
1291
+ orderedNodes.push(node);
1292
+ }
1293
+ }
1294
+ for (const node of this.dependencyGraph.nodes.values()) {
1295
+ if (!selectedNodeIds.has(node.id)) {
1296
+ orderedNodes.push(node);
1297
+ }
1298
+ }
1299
+ for (const node of orderedNodes) {
1300
+ if (this.analyzedDependencies.has(node.name)) continue;
1301
+ const packageJson = readPackageJsonCached(node.packagePath);
1302
+ if (!packageJson) continue;
1303
+ this.cacheInstalledPackageInfo(node.name, node.packagePath, packageJson);
1304
+ this.analyzedDependencies.set(node.name, {
1305
+ name: node.name,
1306
+ version: node.version,
1307
+ dependencyPath: this.getDependencyPathForGraphNode(node),
1308
+ dependencies: packageJson.dependencies ?? {},
1309
+ peerDependencies: packageJson.peerDependencies ?? {},
1310
+ peerDependenciesMeta: packageJson.peerDependenciesMeta
1311
+ });
1312
+ this.visitedPackages.add(node.name);
1313
+ }
1314
+ }
1188
1315
  /**
1189
1316
  * 缓存已安装包的信息(用于后续查找别名等)
1190
1317
  */
@@ -1220,7 +1347,12 @@ var DependencyAnalyzer = class {
1220
1347
  */
1221
1348
  collectFirstLevelPeerDependencies() {
1222
1349
  const peerDepsMap = /* @__PURE__ */ new Map();
1350
+ const hasInstalledGraphRoots = (this.dependencyGraph?.roots.length ?? 0) > 0;
1223
1351
  for (const depName of this.options.dependencies) {
1352
+ if (hasInstalledGraphRoots && !this.findGraphRoot(depName)) {
1353
+ logger4.debug(`Skipping non-root configured dependency: ${depName}`);
1354
+ continue;
1355
+ }
1224
1356
  const depInfo = this.analyzedDependencies.get(depName);
1225
1357
  if (!depInfo) continue;
1226
1358
  const peerDeps = depInfo.peerDependencies;
@@ -1290,10 +1422,6 @@ var DependencyAnalyzer = class {
1290
1422
  * 返回 null 表示包未安装
1291
1423
  */
1292
1424
  getMainProjectVersion(packageName) {
1293
- const cached = this.installedPackageCache.get(packageName);
1294
- if (cached) {
1295
- return cached.version;
1296
- }
1297
1425
  const { packagePath, pkgJson } = this.resolvePackageJson(packageName, this.options.projectRoot);
1298
1426
  if (packagePath && pkgJson?.version) {
1299
1427
  this.installedPackageCache.set(packageName, {
@@ -1303,6 +1431,10 @@ var DependencyAnalyzer = class {
1303
1431
  });
1304
1432
  return pkgJson.version;
1305
1433
  }
1434
+ const cached = this.installedPackageCache.get(packageName);
1435
+ if (cached) {
1436
+ return cached.version;
1437
+ }
1306
1438
  return null;
1307
1439
  }
1308
1440
  /**
@@ -1323,8 +1455,46 @@ var DependencyAnalyzer = class {
1323
1455
  const mappings = await this.createAliasMappingsForConflict(conflict, allConflictPackageNames);
1324
1456
  aliasMappings.push(...mappings);
1325
1457
  }
1458
+ this.linkAliasPeerImporterPaths(aliasMappings);
1326
1459
  return aliasMappings;
1327
1460
  }
1461
+ getAliasCandidatePaths(aliasName) {
1462
+ const paths = /* @__PURE__ */ new Set();
1463
+ const addRootPath = (root) => {
1464
+ paths.add(path.join(root, "node_modules", aliasName));
1465
+ paths.add(path.join(this.normalizeInstalledPath(root), "node_modules", aliasName));
1466
+ };
1467
+ addRootPath(this.options.projectRoot);
1468
+ const workspaceRoot = this.workspaceDetector.getWorkspaceRoot();
1469
+ if (workspaceRoot) addRootPath(workspaceRoot);
1470
+ const installedPath = findPackagePath(aliasName, this.options.projectRoot);
1471
+ if (installedPath) paths.add(this.normalizeInstalledPath(installedPath));
1472
+ return [...paths];
1473
+ }
1474
+ /**
1475
+ * If one generated alias represents a package with a peer dependency that
1476
+ * is also aliased, its installed package directory must be an importer for
1477
+ * the peer alias. Otherwise the alias's own import resolves back to the
1478
+ * host version and breaks the peer closure.
1479
+ */
1480
+ linkAliasPeerImporterPaths(mappings) {
1481
+ if (!this.dependencyGraph || mappings.length < 2) return;
1482
+ for (const importerMapping of mappings) {
1483
+ const peerNames = new Set(
1484
+ [...this.dependencyGraph.nodes.values()].filter((node) => node.name === importerMapping.originalName).flatMap((node) => node.peerDependencyNames)
1485
+ );
1486
+ if (peerNames.size === 0) continue;
1487
+ const importerPaths = this.getAliasCandidatePaths(importerMapping.aliasName);
1488
+ for (const peerMapping of mappings) {
1489
+ if (peerMapping === importerMapping || !peerNames.has(peerMapping.originalName) || peerMapping.importerPaths === void 0) {
1490
+ continue;
1491
+ }
1492
+ peerMapping.importerPaths = [
1493
+ .../* @__PURE__ */ new Set([...peerMapping.importerPaths ?? [], ...importerPaths])
1494
+ ];
1495
+ }
1496
+ }
1497
+ }
1328
1498
  /**
1329
1499
  * 为单个冲突创建别名映射
1330
1500
  */
@@ -1577,14 +1747,19 @@ var DependencyAnalyzer = class {
1577
1747
  const usedByRoots = [
1578
1748
  ...new Set(group.map((r) => r.path[0]).filter((p) => p !== void 0))
1579
1749
  ];
1580
- const allDependents = this.collectAllRelatedPackages(usedByRoots, allConflictPackageNames);
1750
+ const graphInstances = this.collectGraphRelatedPackageInstances(
1751
+ usedByRoots,
1752
+ allConflictPackageNames
1753
+ );
1754
+ const allDependents = graphInstances ? [...new Set(graphInstances.map((instance) => instance.name))] : this.collectAllRelatedPackages(usedByRoots, allConflictPackageNames);
1581
1755
  return {
1582
1756
  originalName: packageName,
1583
1757
  aliasName,
1584
1758
  installSpec,
1585
1759
  resolvedVersion: version,
1586
1760
  usedBy,
1587
- allDependents
1761
+ allDependents,
1762
+ ...graphInstances && graphInstances.length > 0 ? { importerPaths: [...new Set(graphInstances.map((instance) => instance.path))] } : {}
1588
1763
  };
1589
1764
  }
1590
1765
  /**
@@ -1797,6 +1972,64 @@ var DependencyAnalyzer = class {
1797
1972
  }
1798
1973
  return names;
1799
1974
  }
1975
+ /**
1976
+ * Return every dependency key that the host or its workspace root owns.
1977
+ *
1978
+ * Generated aliases share the package namespace with ordinary dependency
1979
+ * keys. Keeping the complete set here prevents a generated alias from
1980
+ * silently replacing an unrelated dependency declared by the user.
1981
+ */
1982
+ getReservedDependencyNames() {
1983
+ this.ensureWorkspaceRootDeclaredDepsLoaded();
1984
+ return /* @__PURE__ */ new Set([
1985
+ ...Object.keys(this.rawDeclaredDeps),
1986
+ ...Object.keys(this.declaredDeps),
1987
+ ...Object.keys(this.workspaceRootDeclaredDeps)
1988
+ ]);
1989
+ }
1990
+ normalizeInstalledPath(packagePath) {
1991
+ try {
1992
+ return fs.realpathSync(packagePath);
1993
+ } catch {
1994
+ return path.resolve(packagePath);
1995
+ }
1996
+ }
1997
+ findGraphChildNode(parent, dependencyName) {
1998
+ if (!this.dependencyGraph) return null;
1999
+ const packagePath = findPackagePath(dependencyName, parent.packagePath);
2000
+ if (!packagePath) return null;
2001
+ return this.dependencyGraph.nodes.get(this.normalizeInstalledPath(packagePath)) ?? null;
2002
+ }
2003
+ /**
2004
+ * 收集图中指定根实例的所有后代实例。返回 null 表示当前分析没有
2005
+ * 对应的图根,调用方可为兼容旧测试/旧调用回退到名称遍历。
2006
+ */
2007
+ collectGraphRelatedPackageInstances(packageNames, excludePackages = []) {
2008
+ if (!this.dependencyGraph) return null;
2009
+ const roots = packageNames.map(
2010
+ (packageName) => this.dependencyGraph.roots.map((rootId) => this.dependencyGraph.nodes.get(rootId)).find(
2011
+ (node) => node?.name === packageName
2012
+ )
2013
+ ).filter((node) => node !== void 0);
2014
+ if (roots.length === 0) return null;
2015
+ const excludeSet = new Set(excludePackages);
2016
+ const visited = /* @__PURE__ */ new Set();
2017
+ const collected = [];
2018
+ const stack = roots.map((root) => root.id);
2019
+ while (stack.length > 0) {
2020
+ const nodeId = stack.pop();
2021
+ if (!nodeId || visited.has(nodeId)) continue;
2022
+ visited.add(nodeId);
2023
+ const node = this.dependencyGraph.nodes.get(nodeId);
2024
+ if (!node || excludeSet.has(node.name)) continue;
2025
+ collected.push({ name: node.name, path: node.packagePath });
2026
+ for (const dependencyName of [...node.dependencyNames, ...node.peerDependencyNames]) {
2027
+ const child = this.findGraphChildNode(node, dependencyName);
2028
+ if (child && !visited.has(child.id)) stack.push(child.id);
2029
+ }
2030
+ }
2031
+ return collected;
2032
+ }
1800
2033
  /**
1801
2034
  * 递归收集指定包的所有子依赖(dependencies + peerDependencies)
1802
2035
  *
@@ -1871,6 +2104,12 @@ var DependencyAnalyzer = class {
1871
2104
  if (cached) {
1872
2105
  return cached;
1873
2106
  }
2107
+ const graphInstances = this.collectGraphRelatedPackageInstances(packageNames, excludePackages);
2108
+ if (graphInstances) {
2109
+ const result2 = [...new Set(graphInstances.map((instance) => instance.name))];
2110
+ this.collectCache.set(cacheKey, result2);
2111
+ return result2;
2112
+ }
1874
2113
  const collected = /* @__PURE__ */ new Set();
1875
2114
  const visited = /* @__PURE__ */ new Set();
1876
2115
  const excludeSet = new Set(excludePackages);
@@ -2231,7 +2470,7 @@ function createPackageManagerAdapter(options, timing = DEFAULT_TIMING) {
2231
2470
  stdio: ["ignore", "pipe", "pipe"],
2232
2471
  ...process.platform === "win32" ? {} : { detached: true }
2233
2472
  });
2234
- return new Promise((resolve2) => {
2473
+ return new Promise((resolve3) => {
2235
2474
  let stdout = "";
2236
2475
  let stderr = "";
2237
2476
  let terminalError;
@@ -2254,7 +2493,7 @@ function createPackageManagerAdapter(options, timing = DEFAULT_TIMING) {
2254
2493
  }
2255
2494
  settled = true;
2256
2495
  clearTimers();
2257
- resolve2({
2496
+ resolve3({
2258
2497
  success: !timedOut && !terminalError && exitCode === 0,
2259
2498
  exitCode,
2260
2499
  stdout,