deps-conflict-resolver 1.1.2 → 1.3.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/dist/index.cjs CHANGED
@@ -7,6 +7,9 @@ var url = require('url');
7
7
  var yaml = require('yaml');
8
8
  var semver = require('semver');
9
9
  var child_process = require('child_process');
10
+ var crypto = require('crypto');
11
+ var os = require('os');
12
+ var perf_hooks = require('perf_hooks');
10
13
 
11
14
  function _interopDefault (e) { return e && e.__esModule ? e : { default: e }; }
12
15
 
@@ -418,10 +421,10 @@ var EnvironmentDetector = class {
418
421
  for (const dir of iterateParentDirs(this.projectRoot)) {
419
422
  const npmrcPath = path.join(dir, ".npmrc");
420
423
  if (fileExists(npmrcPath)) {
421
- const registry = await this.parseRegistryFromNpmrc(npmrcPath);
422
- if (registry) {
423
- logger.debug(`Detected registry from .npmrc: ${registry} (at ${dir})`);
424
- return registry;
424
+ const registry2 = await this.parseRegistryFromNpmrc(npmrcPath);
425
+ if (registry2) {
426
+ logger.debug(`Detected registry from .npmrc: ${registry2} (at ${dir})`);
427
+ return registry2;
425
428
  }
426
429
  }
427
430
  }
@@ -429,19 +432,19 @@ var EnvironmentDetector = class {
429
432
  if (homeDir) {
430
433
  const userNpmrc = path.join(homeDir, ".npmrc");
431
434
  if (fileExists(userNpmrc)) {
432
- const registry = await this.parseRegistryFromNpmrc(userNpmrc);
433
- if (registry) {
434
- logger.debug(`Detected registry from user .npmrc: ${registry}`);
435
- return registry;
435
+ const registry2 = await this.parseRegistryFromNpmrc(userNpmrc);
436
+ if (registry2) {
437
+ logger.debug(`Detected registry from user .npmrc: ${registry2}`);
438
+ return registry2;
436
439
  }
437
440
  }
438
441
  if (packageManager === "pnpm") {
439
442
  const pnpmConfig = path.join(homeDir, ".pnpmrc");
440
443
  if (fileExists(pnpmConfig)) {
441
- const registry = await this.parseRegistryFromNpmrc(pnpmConfig);
442
- if (registry) {
443
- logger.debug(`Detected registry from .pnpmrc: ${registry}`);
444
- return registry;
444
+ const registry2 = await this.parseRegistryFromNpmrc(pnpmConfig);
445
+ if (registry2) {
446
+ logger.debug(`Detected registry from .pnpmrc: ${registry2}`);
447
+ return registry2;
445
448
  }
446
449
  }
447
450
  }
@@ -449,10 +452,10 @@ var EnvironmentDetector = class {
449
452
  for (const dir of iterateParentDirs(this.projectRoot)) {
450
453
  const yarnrc = path.join(dir, ".yarnrc.yml");
451
454
  if (fileExists(yarnrc)) {
452
- const registry = await this.parseRegistryFromYarnrc(yarnrc);
453
- if (registry) {
454
- logger.debug(`Detected registry from .yarnrc.yml: ${registry} (at ${dir})`);
455
- return registry;
455
+ const registry2 = await this.parseRegistryFromYarnrc(yarnrc);
456
+ if (registry2) {
457
+ logger.debug(`Detected registry from .yarnrc.yml: ${registry2} (at ${dir})`);
458
+ return registry2;
456
459
  }
457
460
  }
458
461
  }
@@ -680,7 +683,7 @@ var WorkspaceDetector = class {
680
683
  if (rootPkgJson) {
681
684
  aliases.push(
682
685
  ...extractAliasesFromDeps(
683
- rootPkgJson.dependencies,
686
+ { ...rootPkgJson.dependencies, ...rootPkgJson.optionalDependencies },
684
687
  targetPackage,
685
688
  rootPkgPath,
686
689
  existingAliases
@@ -826,8 +829,10 @@ function generateAliasName(packageName, version) {
826
829
  // src/core/registry-client.ts
827
830
  var logger3 = createLogger("npm-registry");
828
831
  var packageCache = /* @__PURE__ */ new Map();
832
+ var manifestCache = new LruCache({ maxEntries: 200 });
829
833
  function clearNpmRegistryCache() {
830
834
  packageCache.clear();
835
+ manifestCache.clear();
831
836
  }
832
837
  async function fetchWithTimeout(url, options = {}, consumeResponse, timeout = DEFAULT_NPM_REGISTRY_TIMEOUT_MS) {
833
838
  const controller = new AbortController();
@@ -842,15 +847,15 @@ async function fetchWithTimeout(url, options = {}, consumeResponse, timeout = DE
842
847
  clearTimeout(timeoutId);
843
848
  }
844
849
  }
845
- async function fetchPackageInfo(packageName, registry = DEFAULT_NPM_REGISTRY) {
846
- const cacheKey = `${registry}:${packageName}`;
850
+ async function fetchPackageInfo(packageName, registry2 = DEFAULT_NPM_REGISTRY) {
851
+ const cacheKey = `${registry2}:${packageName}`;
847
852
  const cached = packageCache.get(cacheKey);
848
853
  if (cached) {
849
854
  return cached;
850
855
  }
851
856
  try {
852
857
  const encodedName = packageName.startsWith("@") ? `@${encodeURIComponent(packageName.slice(1))}` : packageName;
853
- const url = `${registry}/${encodedName}`;
858
+ const url = `${registry2.replace(/\/+$/, "")}/${encodedName}`;
854
859
  logger3.debug(`Fetching package info from: ${url}`);
855
860
  const { response, data } = await fetchWithTimeout(
856
861
  url,
@@ -872,7 +877,7 @@ async function fetchPackageInfo(packageName, registry = DEFAULT_NPM_REGISTRY) {
872
877
  if (!response.ok) {
873
878
  if (response.status === 404) {
874
879
  logger3.warn(`Package not found: ${packageName}`);
875
- return null;
880
+ throw new Error(`Package not found: ${packageName} (HTTP 404)`);
876
881
  }
877
882
  throw new Error(`HTTP ${response.status}: ${response.statusText}`);
878
883
  }
@@ -899,13 +904,35 @@ async function fetchPackageInfo(packageName, registry = DEFAULT_NPM_REGISTRY) {
899
904
  } else {
900
905
  logger3.error(`Failed to fetch package info for ${packageName}:`, error);
901
906
  }
902
- return null;
907
+ throw error;
903
908
  }
904
909
  }
905
910
  var npmRegistryClient = {
906
- async fetchAllVersions(packageName, registry) {
907
- const info = await fetchPackageInfo(packageName, registry);
911
+ async fetchAllVersions(packageName, registry2) {
912
+ const info = await fetchPackageInfo(packageName, registry2);
908
913
  return info?.versions ?? [];
914
+ },
915
+ async fetchPackageManifest(packageName, version, registry2) {
916
+ const key = `${registry2}\0${packageName}\0${version}`;
917
+ const cached = manifestCache.get(key);
918
+ if (cached) return cached;
919
+ const encodedName = packageName.startsWith("@") ? `@${encodeURIComponent(packageName.slice(1))}` : encodeURIComponent(packageName);
920
+ const url = `${registry2.replace(/\/+$/, "")}/${encodedName}/${encodeURIComponent(version)}`;
921
+ const manifest = await fetchWithTimeout(
922
+ url,
923
+ {
924
+ headers: { Accept: "application/json" }
925
+ },
926
+ async (response) => {
927
+ if (!response.ok) throw new Error(`HTTP ${response.status}: ${response.statusText}`);
928
+ return await response.json();
929
+ }
930
+ );
931
+ if (manifest.name !== packageName || manifest.version !== version) {
932
+ throw new Error(`Invalid manifest for ${packageName}@${version}`);
933
+ }
934
+ manifestCache.set(key, manifest);
935
+ return manifest;
909
936
  }
910
937
  };
911
938
  function normalizePackagePath(packagePath) {
@@ -918,6 +945,7 @@ function normalizePackagePath(packagePath) {
918
945
  function buildInstalledDependencyGraph(packageNames, projectRoot) {
919
946
  const nodes = /* @__PURE__ */ new Map();
920
947
  const roots = [];
948
+ const rootRequests = /* @__PURE__ */ new Map();
921
949
  const stack = [];
922
950
  for (let index = packageNames.length - 1; index >= 0; index--) {
923
951
  const name = packageNames[index];
@@ -929,6 +957,8 @@ function buildInstalledDependencyGraph(packageNames, projectRoot) {
929
957
  const packagePath = findPackagePath(item.name, item.baseDir);
930
958
  if (!packagePath) continue;
931
959
  const normalizedPath = normalizePackagePath(packagePath);
960
+ if (item.root) rootRequests.set(item.name, normalizedPath);
961
+ if (item.parentId) nodes.get(item.parentId)?.resolvedChildren.set(item.name, normalizedPath);
932
962
  const existingNode = nodes.get(normalizedPath);
933
963
  if (existingNode) {
934
964
  if (item.root) {
@@ -941,7 +971,10 @@ function buildInstalledDependencyGraph(packageNames, projectRoot) {
941
971
  }
942
972
  const packageJson = readPackageJsonCached(normalizedPath);
943
973
  if (!packageJson) continue;
944
- const dependencyNames = Object.keys(packageJson.dependencies ?? {});
974
+ const dependencyNames = Object.keys({
975
+ ...packageJson.dependencies,
976
+ ...packageJson.optionalDependencies
977
+ });
945
978
  const peerDependencyNames = Object.keys(packageJson.peerDependencies ?? {});
946
979
  const node = {
947
980
  id: normalizedPath,
@@ -950,7 +983,8 @@ function buildInstalledDependencyGraph(packageNames, projectRoot) {
950
983
  packagePath: normalizedPath,
951
984
  parentId: item.parentId,
952
985
  dependencyNames,
953
- peerDependencyNames
986
+ peerDependencyNames,
987
+ resolvedChildren: /* @__PURE__ */ new Map()
954
988
  };
955
989
  nodes.set(normalizedPath, node);
956
990
  if (item.root) roots.push(normalizedPath);
@@ -967,11 +1001,590 @@ function buildInstalledDependencyGraph(packageNames, projectRoot) {
967
1001
  }
968
1002
  }
969
1003
  }
970
- return { nodes, roots };
1004
+ return { nodes, roots, rootRequests };
1005
+ }
1006
+
1007
+ // src/utils/module-request.ts
1008
+ function isVirtualModuleRequest(request) {
1009
+ return request.startsWith("\0");
1010
+ }
1011
+ function isPathLikeRequest(request) {
1012
+ if (!request) return false;
1013
+ if (request.startsWith(".")) {
1014
+ return true;
1015
+ }
1016
+ if (request.startsWith("/")) {
1017
+ return true;
1018
+ }
1019
+ if (/^[a-zA-Z]:[\\/]/.test(request)) {
1020
+ return true;
1021
+ }
1022
+ if (request.startsWith("\\\\")) {
1023
+ return true;
1024
+ }
1025
+ return false;
1026
+ }
1027
+
1028
+ // src/core/resolution-error.ts
1029
+ var ResolutionError = class extends Error {
1030
+ constructor(diagnostics) {
1031
+ super(
1032
+ diagnostics.map((diagnostic) => "[" + diagnostic.code + "] " + diagnostic.message).join("\n")
1033
+ );
1034
+ this.diagnostics = diagnostics;
1035
+ this.name = "ResolutionError";
1036
+ }
1037
+ diagnostics;
1038
+ };
1039
+
1040
+ // src/core/alias-manager.ts
1041
+ var logger4 = createLogger("alias-manager");
1042
+ var NO_RULE = { reason: "no-rule", aliases: [], matchedPaths: [] };
1043
+ var NO_IMPORTER = { reason: "no-importer", aliases: [], matchedPaths: [] };
1044
+ var UNMATCHED = { reason: "unmatched", aliases: [], matchedPaths: [] };
1045
+ function normalizePath(path$1) {
1046
+ const normalized = path.posix.normalize(path$1.replace(/\\/g, "/"));
1047
+ return normalized.length <= 1 ? normalized : normalized.replace(/\/+$/, "");
1048
+ }
1049
+ function isWithin(path, directory) {
1050
+ return path === directory || path.startsWith(directory.endsWith("/") ? directory : directory + "/");
1051
+ }
1052
+ function packageInstances(path) {
1053
+ const parts = path.split("/");
1054
+ const instances = [];
1055
+ for (let index = 0; index < parts.length - 1; index++) {
1056
+ if (parts[index] !== "node_modules") continue;
1057
+ const name = parts[index + 1];
1058
+ if (!name || name.startsWith(".")) continue;
1059
+ const scopedName = name.startsWith("@") ? parts[index + 2] : void 0;
1060
+ if (name.startsWith("@") && !scopedName) continue;
1061
+ const end = scopedName ? index + 3 : index + 2;
1062
+ instances.push({
1063
+ name: scopedName ? name + "/" + scopedName : name,
1064
+ path: parts.slice(0, end).join("/")
1065
+ });
1066
+ }
1067
+ return instances;
1068
+ }
1069
+ var AliasManager = class {
1070
+ constructor(options) {
1071
+ this.options = options;
1072
+ }
1073
+ options;
1074
+ aliasMappings = [];
1075
+ rulesMap = /* @__PURE__ */ new Map();
1076
+ importerCache = new LruCache({ maxEntries: 1e3 });
1077
+ pathCache = new LruCache({ maxEntries: 5e3 });
1078
+ decisionCache = new LruCache({ maxEntries: 5e3 });
1079
+ diagnostics = /* @__PURE__ */ new Map();
1080
+ initFromAnalysisResult(result) {
1081
+ this.clear();
1082
+ this.aliasMappings = result.aliasMappings;
1083
+ for (const mapping of this.aliasMappings) {
1084
+ const pathScoped = mapping.importerPaths !== void 0;
1085
+ const rule = {
1086
+ aliasName: mapping.aliasName,
1087
+ pathScoped,
1088
+ dependents: /* @__PURE__ */ new Set([
1089
+ ...pathScoped ? [] : mapping.allDependents,
1090
+ ...this.options.includeRedirects[mapping.originalName] ?? []
1091
+ ]),
1092
+ excludedPackages: new Set(this.options.excludeRedirects[mapping.originalName] ?? [])
1093
+ };
1094
+ let index = this.rulesMap.get(mapping.originalName);
1095
+ if (!index) {
1096
+ index = { paths: /* @__PURE__ */ new Map(), rules: [] };
1097
+ this.rulesMap.set(mapping.originalName, index);
1098
+ }
1099
+ index.rules.push(rule);
1100
+ for (const packagePath of mapping.importerPaths ?? []) {
1101
+ const candidates = this.pathCandidates(packagePath);
1102
+ const name = packageInstances(normalizePath(packagePath)).at(-1)?.name ?? readPackageJsonCached(packagePath)?.name;
1103
+ for (const candidate of candidates) {
1104
+ const entries = index.paths.get(candidate) ?? [];
1105
+ entries.push({ rule, scope: { path: candidate, name } });
1106
+ index.paths.set(candidate, entries);
1107
+ }
1108
+ }
1109
+ }
1110
+ logger4.info("Initialized " + this.aliasMappings.length + " alias mappings");
1111
+ }
1112
+ clear() {
1113
+ this.aliasMappings = [];
1114
+ this.rulesMap.clear();
1115
+ this.importerCache.clear();
1116
+ this.pathCache.clear();
1117
+ this.decisionCache.clear();
1118
+ this.diagnostics.clear();
1119
+ }
1120
+ pathCandidates(path, moduleId = false) {
1121
+ const cacheKey = (moduleId ? "id\0" : "path\0") + path;
1122
+ const cached = this.pathCache.get(cacheKey);
1123
+ if (cached) return cached;
1124
+ let literalPath = path;
1125
+ let realPath;
1126
+ try {
1127
+ realPath = fs.realpathSync(path);
1128
+ } catch {
1129
+ if (moduleId) {
1130
+ const markers = [...path.matchAll(/[?#]/g)];
1131
+ for (let index = markers.length - 1; index >= 0; index--) {
1132
+ const candidate = path.slice(0, markers[index].index);
1133
+ try {
1134
+ if (!fs.statSync(candidate).isFile()) continue;
1135
+ realPath = fs.realpathSync(candidate);
1136
+ literalPath = candidate;
1137
+ break;
1138
+ } catch {
1139
+ }
1140
+ }
1141
+ }
1142
+ }
1143
+ const paths = /* @__PURE__ */ new Set([normalizePath(literalPath)]);
1144
+ if (realPath) paths.add(normalizePath(realPath));
1145
+ const candidates = [...paths];
1146
+ this.pathCache.set(cacheKey, candidates);
1147
+ return candidates;
1148
+ }
1149
+ importerInfo(importer) {
1150
+ const cached = this.importerCache.get(importer);
1151
+ if (cached) return cached;
1152
+ const paths = this.pathCandidates(importer, true);
1153
+ const instances = paths.flatMap(packageInstances);
1154
+ if (instances.length === 0) {
1155
+ for (const path$1 of paths) {
1156
+ let directory = path$1;
1157
+ while (true) {
1158
+ const manifest = readPackageJsonCached(directory);
1159
+ if (manifest?.name) {
1160
+ instances.push({ name: manifest.name, path: directory });
1161
+ break;
1162
+ }
1163
+ const parent = path.posix.dirname(directory);
1164
+ if (parent === directory) break;
1165
+ directory = parent;
1166
+ }
1167
+ }
1168
+ }
1169
+ const info = { paths, instances };
1170
+ this.importerCache.set(importer, info);
1171
+ return info;
1172
+ }
1173
+ requestPackageName(request) {
1174
+ if (!request || isPathLikeRequest(request) || isVirtualModuleRequest(request)) return "";
1175
+ const base = request.split(/[?#]/, 1)[0] ?? "";
1176
+ const parts = base.split("/");
1177
+ return base.startsWith("@") ? parts.slice(0, 2).join("/") : parts[0] ?? "";
1178
+ }
1179
+ decide(packageName, importer) {
1180
+ if (!importer) return NO_IMPORTER;
1181
+ const index = this.rulesMap.get(packageName);
1182
+ if (!index) return NO_RULE;
1183
+ const cacheKey = packageName + "\0" + importer;
1184
+ const cached = this.decisionCache.get(cacheKey);
1185
+ if (cached) return cached;
1186
+ const info = this.importerInfo(importer);
1187
+ const matches = /* @__PURE__ */ new Map();
1188
+ for (const candidate of info.paths) {
1189
+ let path$1 = candidate;
1190
+ let distance = 0;
1191
+ while (true) {
1192
+ for (const { rule, scope } of index.paths.get(path$1) ?? []) {
1193
+ let match = matches.get(rule);
1194
+ if (!match) {
1195
+ match = { rule, specificity: Number.NEGATIVE_INFINITY, scopes: [], excluded: false };
1196
+ matches.set(rule, match);
1197
+ }
1198
+ match.specificity = Math.max(match.specificity, -distance);
1199
+ match.scopes.push(scope);
1200
+ }
1201
+ const parent = path.posix.dirname(path$1);
1202
+ if (parent === path$1) break;
1203
+ path$1 = parent;
1204
+ distance++;
1205
+ }
1206
+ }
1207
+ for (const rule of index.rules) {
1208
+ const included = info.instances.filter((instance) => rule.dependents.has(instance.name));
1209
+ let match = matches.get(rule);
1210
+ if (!match && included.length > 0) {
1211
+ match = { rule, specificity: Number.NEGATIVE_INFINITY, scopes: [], excluded: false };
1212
+ matches.set(rule, match);
1213
+ }
1214
+ if (!match) continue;
1215
+ match.excluded = match.scopes.some((scope) => scope.name && rule.excludedPackages.has(scope.name)) || info.instances.some(
1216
+ (instance) => rule.excludedPackages.has(instance.name) && (!rule.pathScoped || match.scopes.some(
1217
+ (scope) => isWithin(instance.path, scope.path) || isWithin(scope.path, instance.path)
1218
+ ) || included.some(
1219
+ (parent) => isWithin(instance.path, parent.path) || isWithin(parent.path, instance.path)
1220
+ ))
1221
+ );
1222
+ }
1223
+ let specificity = Number.NEGATIVE_INFINITY;
1224
+ let best = [];
1225
+ for (const match of matches.values()) {
1226
+ if (match.specificity > specificity) {
1227
+ specificity = match.specificity;
1228
+ best = [match];
1229
+ } else if (match.specificity === specificity) {
1230
+ best.push(match);
1231
+ }
1232
+ }
1233
+ let decision = UNMATCHED;
1234
+ if (best.length > 0) {
1235
+ const aliases = [...new Set(best.map((match) => match.rule.aliasName))].sort();
1236
+ const matchedPaths = [
1237
+ ...new Set(best.flatMap((match) => match.scopes.map((scope) => scope.path)))
1238
+ ].sort();
1239
+ decision = {
1240
+ reason: best.some((match) => match.excluded) ? "excluded" : aliases.length > 1 ? "ambiguous" : "redirected",
1241
+ aliases,
1242
+ matchedPaths
1243
+ };
1244
+ if (decision.reason === "ambiguous") {
1245
+ const key = packageName + "\0" + JSON.stringify([aliases, matchedPaths]);
1246
+ if (!this.diagnostics.has(key) && this.diagnostics.size < 1e3) {
1247
+ const diagnostic = {
1248
+ code: "AMBIGUOUS_IMPORTER",
1249
+ severity: "error",
1250
+ message: "Multiple aliases match the same importer for " + packageName + ": " + aliases.join(", "),
1251
+ packageName,
1252
+ aliases,
1253
+ importerPaths: matchedPaths
1254
+ };
1255
+ this.diagnostics.set(key, diagnostic);
1256
+ logger4.warn(diagnostic.message);
1257
+ }
1258
+ }
1259
+ }
1260
+ this.decisionCache.set(cacheKey, decision);
1261
+ return decision;
1262
+ }
1263
+ resolveModule({ request, importer }) {
1264
+ const packageName = this.requestPackageName(request);
1265
+ if (!packageName) return null;
1266
+ const decision = this.decide(packageName, importer);
1267
+ if (decision.reason === "ambiguous" && this.options.strict) {
1268
+ throw new ResolutionError(this.getDiagnostics());
1269
+ }
1270
+ return decision.reason === "redirected" ? decision.aliases[0] + request.slice(packageName.length) : null;
1271
+ }
1272
+ explainResolution(request, importer) {
1273
+ const packageName = this.requestPackageName(request);
1274
+ const decision = packageName ? this.decide(packageName, importer) : NO_RULE;
1275
+ return {
1276
+ request,
1277
+ importer,
1278
+ resolved: decision.reason === "redirected" ? decision.aliases[0] + request.slice(packageName.length) : null,
1279
+ reason: decision.reason,
1280
+ aliases: [...decision.aliases],
1281
+ matchedPaths: [...decision.matchedPaths]
1282
+ };
1283
+ }
1284
+ getDiagnostics() {
1285
+ return [...this.diagnostics.values()].map(
1286
+ (diagnostic) => Object.assign({}, diagnostic, {
1287
+ aliases: [...diagnostic.aliases ?? []],
1288
+ importerPaths: [...diagnostic.importerPaths ?? []]
1289
+ })
1290
+ );
1291
+ }
1292
+ getAliasPathMappings() {
1293
+ return this.aliasMappings.map((mapping) => ({
1294
+ aliasName: mapping.aliasName,
1295
+ originalName: mapping.originalName,
1296
+ path: findPackagePath(mapping.aliasName, this.options.projectRoot) ?? path.join(this.options.projectRoot, "node_modules", mapping.aliasName)
1297
+ }));
1298
+ }
1299
+ };
1300
+ function createAliasManager(options) {
1301
+ return new AliasManager(options);
1302
+ }
1303
+
1304
+ // src/core/alias-peer-resolver.ts
1305
+ function actualPath(path) {
1306
+ try {
1307
+ return fs.realpathSync(path);
1308
+ } catch {
1309
+ return path;
1310
+ }
1311
+ }
1312
+ async function linkAliasPeers(mappings, options, registry2, diagnostics, peerConflicts = [], watchFiles) {
1313
+ if (mappings.length === 0) return;
1314
+ const readManifest = (directory) => {
1315
+ watchFiles?.add(path.join(actualPath(directory), "package.json"));
1316
+ return readPackageJsonCached(directory);
1317
+ };
1318
+ for (const mapping of mappings) {
1319
+ const previousPaths = new Set(Object.values(mapping.peerImporterPaths ?? {}).flat());
1320
+ if (mapping.importerPaths && previousPaths.size > 0) {
1321
+ mapping.importerPaths = mapping.importerPaths.filter((path) => !previousPaths.has(path));
1322
+ }
1323
+ mapping.peerImporterPaths = {};
1324
+ }
1325
+ const workspaceRoot = createWorkspaceDetector(options.projectRoot).getWorkspaceRoot();
1326
+ const manifests = /* @__PURE__ */ new Map();
1327
+ const installedPaths = /* @__PURE__ */ new Map();
1328
+ const consumerRequests = new Map(
1329
+ peerConflicts.map((conflict) => [conflict.packageName, conflict.requestedBy])
1330
+ );
1331
+ let contextResolver;
1332
+ for (const mapping of mappings) {
1333
+ const installedPath = findPackagePath(mapping.aliasName, options.projectRoot);
1334
+ const installed = installedPath ? readManifest(installedPath) : null;
1335
+ if (installed?.name === mapping.originalName && installed.version && satisfies(installed.version, mapping.resolvedVersion)) {
1336
+ manifests.set(mapping, installed);
1337
+ installedPaths.set(mapping, installedPath);
1338
+ continue;
1339
+ }
1340
+ if (mapping.installSpec && !options.offline && registry2.fetchPackageManifest) {
1341
+ try {
1342
+ const manifest = await registry2.fetchPackageManifest(
1343
+ mapping.originalName,
1344
+ mapping.resolvedVersion,
1345
+ options.registry
1346
+ );
1347
+ manifests.set(mapping, manifest);
1348
+ } catch (error) {
1349
+ diagnostics.push({
1350
+ code: "ALIAS_METADATA_UNAVAILABLE",
1351
+ severity: "error",
1352
+ packageName: mapping.originalName,
1353
+ aliases: [mapping.aliasName],
1354
+ message: "Cannot inspect selected version " + mapping.originalName + "@" + mapping.resolvedVersion + ": " + String(error)
1355
+ });
1356
+ }
1357
+ }
1358
+ }
1359
+ for (const [importer, manifest] of manifests) {
1360
+ const importerPaths = /* @__PURE__ */ new Set([
1361
+ path.join(options.projectRoot, "node_modules", importer.aliasName),
1362
+ path.join(actualPath(options.projectRoot), "node_modules", importer.aliasName)
1363
+ ]);
1364
+ if (workspaceRoot) importerPaths.add(path.join(workspaceRoot, "node_modules", importer.aliasName));
1365
+ const installedPath = installedPaths.get(importer);
1366
+ if (installedPath) importerPaths.add(actualPath(installedPath));
1367
+ const pendingInstallation = !installedPath && options.autoInstall && importer.installSpec;
1368
+ for (const [peerName, range] of Object.entries(manifest.peerDependencies ?? {})) {
1369
+ if (manifest.peerDependenciesMeta?.[peerName]?.optional) continue;
1370
+ const providers = /* @__PURE__ */ new Map();
1371
+ const providerAliases = /* @__PURE__ */ new Set();
1372
+ const checkContexts = importer.usedBy.length > 1 && consumerRequests.has(peerName);
1373
+ if (checkContexts) {
1374
+ for (const consumer of importer.usedBy) {
1375
+ const request = consumerRequests.get(peerName)?.find((entry) => entry.path.join(">") === consumer);
1376
+ if (!request) continue;
1377
+ let directory = options.projectRoot;
1378
+ for (const name of request.path) {
1379
+ const packageDirectory = findPackagePath(name, directory);
1380
+ directory = packageDirectory ? actualPath(packageDirectory) : null;
1381
+ if (!directory) break;
1382
+ }
1383
+ if (!directory) continue;
1384
+ if (!contextResolver) {
1385
+ contextResolver = new AliasManager({ ...options, strict: false });
1386
+ contextResolver.initFromAnalysisResult({
1387
+ aliasMappings: mappings,
1388
+ peerConflicts: [...peerConflicts],
1389
+ analyzedDependencies: /* @__PURE__ */ new Map(),
1390
+ missingFirstLevelPeers: []
1391
+ });
1392
+ }
1393
+ const decision = contextResolver.explainResolution(
1394
+ peerName,
1395
+ path.join(directory, "__peer_context__.js")
1396
+ );
1397
+ const selected = decision.reason === "redirected" || decision.reason === "ambiguous" ? mappings.filter((mapping) => decision.aliases.includes(mapping.aliasName)) : [];
1398
+ if (selected.length > 0) {
1399
+ for (const mapping of selected) {
1400
+ if (!satisfies(mapping.resolvedVersion, range)) continue;
1401
+ const path$1 = actualPath(
1402
+ findPackagePath(mapping.aliasName, options.projectRoot) ?? path.join(options.projectRoot, "node_modules", mapping.aliasName)
1403
+ );
1404
+ providers.set(path$1, [
1405
+ ...providers.get(path$1) ?? [],
1406
+ consumer + " -> " + mapping.aliasName + "@" + mapping.resolvedVersion
1407
+ ]);
1408
+ providerAliases.add(mapping.aliasName);
1409
+ }
1410
+ } else {
1411
+ const path = findPackagePath(peerName, directory);
1412
+ const provider = path ? readManifest(path) : null;
1413
+ if (path && provider?.version && satisfies(provider.version, range)) {
1414
+ const identity = actualPath(path);
1415
+ providers.set(identity, [
1416
+ ...providers.get(identity) ?? [],
1417
+ consumer + " -> " + peerName + "@" + provider.version
1418
+ ]);
1419
+ }
1420
+ }
1421
+ }
1422
+ }
1423
+ if (providers.size > 1) {
1424
+ diagnostics.push({
1425
+ code: "AMBIGUOUS_IMPORTER",
1426
+ severity: "error",
1427
+ packageName: peerName,
1428
+ aliases: [...providerAliases].sort(),
1429
+ requestedBy: [importer.aliasName],
1430
+ importerPaths: [...importerPaths],
1431
+ message: "Conflicting consumer peer contexts for " + importer.aliasName + ": " + [...providers.values()].flat().join("; ")
1432
+ });
1433
+ continue;
1434
+ }
1435
+ let candidates = mappings.filter(
1436
+ (mapping) => mapping !== importer && mapping.originalName === peerName && satisfies(mapping.resolvedVersion, range)
1437
+ );
1438
+ const sharedContexts = candidates.filter(
1439
+ (candidate) => checkContexts ? providerAliases.has(candidate.aliasName) : candidate.usedBy.some((consumer) => importer.usedBy.includes(consumer))
1440
+ );
1441
+ if (sharedContexts.length > 0) {
1442
+ candidates = sharedContexts;
1443
+ } else {
1444
+ const naturalPath = findPackagePath(peerName, installedPath ?? options.projectRoot);
1445
+ const natural = naturalPath ? readManifest(naturalPath) : null;
1446
+ if (natural?.version && satisfies(natural.version, range)) continue;
1447
+ }
1448
+ if (candidates.length === 1) {
1449
+ const peer = candidates[0];
1450
+ if (peer.importerPaths === void 0) continue;
1451
+ const paths = [...importerPaths];
1452
+ peer.importerPaths = [.../* @__PURE__ */ new Set([...peer.importerPaths, ...paths])];
1453
+ peer.peerImporterPaths = {
1454
+ ...peer.peerImporterPaths,
1455
+ [importer.aliasName]: paths
1456
+ };
1457
+ continue;
1458
+ }
1459
+ if (candidates.length > 1) {
1460
+ diagnostics.push({
1461
+ code: "AMBIGUOUS_IMPORTER",
1462
+ severity: pendingInstallation ? "warning" : "error",
1463
+ packageName: peerName,
1464
+ aliases: candidates.map((candidate) => candidate.aliasName).sort(),
1465
+ requestedBy: [importer.aliasName],
1466
+ importerPaths: [...importerPaths],
1467
+ message: "Multiple peer contexts for " + importer.aliasName + " requiring " + peerName + "@" + range
1468
+ });
1469
+ continue;
1470
+ }
1471
+ diagnostics.push({
1472
+ code: "ALIAS_PEER_UNSATISFIED",
1473
+ severity: pendingInstallation ? "warning" : "error",
1474
+ packageName: peerName,
1475
+ requestedBy: [importer.aliasName],
1476
+ message: importer.aliasName + " requires " + peerName + "@" + range + (pendingInstallation ? "; provider availability will be checked after installation" : ", but no compatible alias or installed provider is available")
1477
+ });
1478
+ }
1479
+ }
1480
+ }
1481
+ function canonical(directory) {
1482
+ try {
1483
+ return fs.realpathSync(directory);
1484
+ } catch {
1485
+ return directory;
1486
+ }
1487
+ }
1488
+ function validateSharedPeerContexts(graph, mappings, options, diagnostics, watchFiles) {
1489
+ if (mappings.length === 0 || graph.rootRequests.size < 2) return;
1490
+ const readManifest = (directory) => {
1491
+ watchFiles?.add(path.join(directory, "package.json"));
1492
+ return readPackageJsonCached(directory);
1493
+ };
1494
+ const aliases = /* @__PURE__ */ new Map();
1495
+ const installedMappings = mappings.filter((mapping) => {
1496
+ const path = findPackagePath(mapping.aliasName, options.projectRoot);
1497
+ if (!path) return false;
1498
+ const physical = canonical(path);
1499
+ const manifest = readManifest(physical);
1500
+ if (manifest?.name !== mapping.originalName || !manifest.version || !satisfies(manifest.version, mapping.resolvedVersion))
1501
+ return false;
1502
+ aliases.set(mapping.aliasName, {
1503
+ path: physical,
1504
+ version: manifest.version,
1505
+ label: mapping.aliasName + "@" + manifest.version
1506
+ });
1507
+ return true;
1508
+ });
1509
+ if (installedMappings.length === 0) return;
1510
+ const resolver = new AliasManager({ ...options, strict: false });
1511
+ resolver.initFromAnalysisResult({
1512
+ aliasMappings: installedMappings,
1513
+ analyzedDependencies: /* @__PURE__ */ new Map(),
1514
+ peerConflicts: [],
1515
+ missingFirstLevelPeers: []
1516
+ });
1517
+ const aliasPaths = new Set([...aliases.values()].map((provider) => provider.path));
1518
+ const originals = new Set(installedMappings.map((mapping) => mapping.originalName));
1519
+ for (const peer of originals) {
1520
+ const hasExclusions = (options.excludeRedirects[peer]?.length ?? 0) > 0;
1521
+ const roots = [];
1522
+ for (const [consumer, nodeId] of graph.rootRequests) {
1523
+ const node = graph.nodes.get(nodeId);
1524
+ if (!node) continue;
1525
+ const manifest = readManifest(node.packagePath);
1526
+ const range = manifest?.peerDependencies?.[peer];
1527
+ if (!range || manifest?.peerDependenciesMeta?.[peer]?.optional) continue;
1528
+ const decision = resolver.explainResolution(
1529
+ peer,
1530
+ path.join(node.packagePath, "__peer_context__.js")
1531
+ );
1532
+ if (decision.reason === "ambiguous") continue;
1533
+ let provider = decision.resolved ? aliases.get(decision.aliases[0]) : void 0;
1534
+ if (!decision.resolved) {
1535
+ const path = findPackagePath(peer, node.packagePath);
1536
+ const natural = path ? readManifest(canonical(path)) : null;
1537
+ if (path && natural?.version)
1538
+ provider = {
1539
+ path: canonical(path),
1540
+ version: natural.version,
1541
+ label: peer + "@" + natural.version
1542
+ };
1543
+ }
1544
+ if (provider && satisfies(provider.version, range))
1545
+ roots.push({ nodeId, consumer, provider });
1546
+ }
1547
+ if (new Set(roots.map(({ provider }) => provider.path)).size < 2) continue;
1548
+ const visited = /* @__PURE__ */ new Set();
1549
+ const contexts = /* @__PURE__ */ new Map();
1550
+ const pending = [...roots];
1551
+ while (pending.length > 0) {
1552
+ const context = pending.pop();
1553
+ const key = context.nodeId + "\0" + context.provider.path;
1554
+ if (visited.has(key)) continue;
1555
+ visited.add(key);
1556
+ const node = graph.nodes.get(context.nodeId);
1557
+ if (!node || originals.has(node.name)) continue;
1558
+ if (hasExclusions && resolver.explainResolution(peer, path.join(node.packagePath, "__peer_context__.js")).reason === "excluded")
1559
+ continue;
1560
+ const manifest = readManifest(node.packagePath);
1561
+ const range = manifest?.peerDependencies?.[peer];
1562
+ if (range && !satisfies(context.provider.version, range)) continue;
1563
+ if (range && !manifest?.peerDependenciesMeta?.[peer]?.optional && !aliasPaths.has(node.packagePath) && !options.includeRedirects[peer]?.includes(node.name)) {
1564
+ let incoming = contexts.get(node.id);
1565
+ if (!incoming) contexts.set(node.id, incoming = /* @__PURE__ */ new Map());
1566
+ incoming.set(context.provider.path, context);
1567
+ }
1568
+ for (const child of node.resolvedChildren.values())
1569
+ pending.push({ ...context, nodeId: child });
1570
+ }
1571
+ for (const [nodeId, incoming] of contexts) {
1572
+ if (incoming.size < 2) continue;
1573
+ const node = graph.nodes.get(nodeId);
1574
+ diagnostics.push({
1575
+ code: "SHARED_PEER_CONTEXT",
1576
+ severity: "warning",
1577
+ packageName: peer,
1578
+ requestedBy: [...new Set([...incoming.values()].map(({ consumer }) => consumer))],
1579
+ importerPaths: [node.packagePath],
1580
+ message: "Shared package " + node.name + " has different incoming peer contexts: " + [...incoming.values()].map(({ consumer, provider }) => consumer + " -> " + provider.label).join("; ") + ". A single physical instance cannot inherit both providers. Isolate the package or explicitly configure its redirect scope."
1581
+ });
1582
+ }
1583
+ }
971
1584
  }
972
1585
 
973
1586
  // src/core/dependency-analyzer.ts
974
- var logger4 = createLogger("dependency-analyzer");
1587
+ var logger5 = createLogger("dependency-analyzer");
975
1588
  var DependencyAnalyzer = class {
976
1589
  options;
977
1590
  /** 主项目声明的依赖(解析后的版本,catalog: 等协议已转换) */
@@ -1004,12 +1617,18 @@ var DependencyAnalyzer = class {
1004
1617
  dependencyGraph = null;
1005
1618
  /** 注册表访问适配器(可注入以支持离线分析和确定性测试) */
1006
1619
  registryClient;
1620
+ graphPopulated = false;
1621
+ diagnostics = [];
1622
+ watchFiles = /* @__PURE__ */ new Set();
1623
+ injectedInstalledDeps;
1007
1624
  constructor(options, mainPackageJson, installedDeps, registryClient = npmRegistryClient) {
1008
1625
  this.options = options;
1009
1626
  this.registryClient = registryClient;
1627
+ this.injectedInstalledDeps = installedDeps;
1010
1628
  this.rawDeclaredDeps = {
1011
1629
  ...mainPackageJson.dependencies,
1012
- ...mainPackageJson.devDependencies
1630
+ ...mainPackageJson.devDependencies,
1631
+ ...mainPackageJson.optionalDependencies
1013
1632
  };
1014
1633
  this.declaredDeps = { ...this.rawDeclaredDeps };
1015
1634
  this.workspaceDetector = createWorkspaceDetector(options.projectRoot);
@@ -1032,6 +1651,7 @@ var DependencyAnalyzer = class {
1032
1651
  return { packagePath: null, pkgJson: null };
1033
1652
  }
1034
1653
  const pkgJson = readPackageJsonCached(packagePath);
1654
+ this.watchFiles.add(path.join(this.normalizeInstalledPath(packagePath), "package.json"));
1035
1655
  return { packagePath, pkgJson };
1036
1656
  }
1037
1657
  /**
@@ -1055,7 +1675,8 @@ var DependencyAnalyzer = class {
1055
1675
  }
1056
1676
  this.workspaceRootDeclaredDeps = {
1057
1677
  ...rootPkgJson.dependencies,
1058
- ...rootPkgJson.devDependencies
1678
+ ...rootPkgJson.devDependencies,
1679
+ ...rootPkgJson.optionalDependencies
1059
1680
  };
1060
1681
  }
1061
1682
  /**
@@ -1089,11 +1710,11 @@ var DependencyAnalyzer = class {
1089
1710
  const existing = this.existingAliasesMap.get(targetPackage) ?? [];
1090
1711
  existing.push(aliasInfo);
1091
1712
  this.existingAliasesMap.set(targetPackage, existing);
1092
- logger4.debug(`Found npm alias: ${aliasName} -> ${targetPackage}@${version}`);
1713
+ logger5.debug(`Found npm alias: ${aliasName} -> ${targetPackage}@${version}`);
1093
1714
  }
1094
1715
  }
1095
1716
  if (this.existingAliasesMap.size > 0) {
1096
- logger4.debug(`Found ${this.existingAliasesMap.size} npm: protocol aliases`);
1717
+ logger5.debug(`Found ${this.existingAliasesMap.size} npm: protocol aliases`);
1097
1718
  }
1098
1719
  }
1099
1720
  /**
@@ -1128,15 +1749,15 @@ var DependencyAnalyzer = class {
1128
1749
  const resolved = this.workspaceDetector.resolveVersionSpec(pkgName, versionSpec);
1129
1750
  if (resolved) {
1130
1751
  this.declaredDeps[pkgName] = resolved;
1131
- logger4.debug(`Resolved catalog dependency: ${pkgName} "${versionSpec}" -> "${resolved}"`);
1752
+ logger5.debug(`Resolved catalog dependency: ${pkgName} "${versionSpec}" -> "${resolved}"`);
1132
1753
  } else {
1133
- logger4.warn(`Failed to resolve catalog dependency: ${pkgName}@${versionSpec}`);
1754
+ logger5.warn(`Failed to resolve catalog dependency: ${pkgName}@${versionSpec}`);
1134
1755
  }
1135
1756
  } else if (versionSpec.startsWith("workspace:")) {
1136
1757
  const resolved = this.workspaceDetector.resolveVersionSpec(pkgName, versionSpec);
1137
1758
  if (resolved) {
1138
1759
  this.declaredDeps[pkgName] = resolved;
1139
- logger4.debug(
1760
+ logger5.debug(
1140
1761
  `Resolved workspace dependency: ${pkgName} "${versionSpec}" -> "${resolved}"`
1141
1762
  );
1142
1763
  }
@@ -1147,26 +1768,54 @@ var DependencyAnalyzer = class {
1147
1768
  * 分析依赖并找出冲突
1148
1769
  */
1149
1770
  async analyze() {
1150
- logger4.info("Starting dependency analysis...");
1771
+ logger5.info("Starting dependency analysis...");
1772
+ this.watchFiles.clear();
1773
+ this.watchFiles.add(path.join(this.options.projectRoot, "package.json"));
1151
1774
  try {
1152
1775
  this.resolveCatalogDependencies();
1153
1776
  this.ensureWorkspaceRootDeclaredDepsLoaded();
1777
+ const workspaceRoot = this.workspaceDetector.getWorkspaceRoot();
1778
+ if (workspaceRoot) {
1779
+ this.watchFiles.add(path.join(workspaceRoot, "package.json"));
1780
+ const workspaceFile = path.join(workspaceRoot, "pnpm-workspace.yaml");
1781
+ if (fileExists(workspaceFile)) this.watchFiles.add(workspaceFile);
1782
+ }
1154
1783
  this.dependencyGraph = buildInstalledDependencyGraph(
1155
1784
  this.options.dependencies,
1156
1785
  this.options.projectRoot
1157
1786
  );
1787
+ for (const node of this.dependencyGraph.nodes.values()) {
1788
+ this.watchFiles.add(path.join(node.packagePath, "package.json"));
1789
+ }
1158
1790
  for (const depName of this.options.dependencies) {
1159
1791
  this.analyzeDependencyRecursive(depName, []);
1792
+ if (!this.findGraphRoot(depName) && !this.injectedInstalledDeps?.has(depName)) {
1793
+ this.diagnostics.push({
1794
+ code: "DEPENDENCY_NOT_FOUND",
1795
+ severity: "error",
1796
+ packageName: depName,
1797
+ message: "Configured dependency not found: " + depName
1798
+ });
1799
+ }
1160
1800
  }
1161
1801
  const peerDepsMap = this.collectFirstLevelPeerDependencies();
1162
1802
  const peerConflicts = this.analyzePeerConflicts(peerDepsMap);
1163
1803
  const aliasMappings = await this.generateAliasMappings(peerConflicts);
1804
+ validateSharedPeerContexts(
1805
+ this.dependencyGraph,
1806
+ aliasMappings,
1807
+ this.options,
1808
+ this.diagnostics,
1809
+ this.watchFiles
1810
+ );
1164
1811
  const missingFirstLevelPeers = this.findMissingFirstLevelPeers(peerDepsMap);
1165
1812
  const conflictsNeedingAlias = peerConflicts.filter((c) => c.needsAlias).length;
1166
- logger4.info(
1813
+ logger5.info(
1167
1814
  `Analysis complete. Found ${conflictsNeedingAlias} first-level peer conflicts needing alias, ${missingFirstLevelPeers.length} missing peers (not auto-installing). Analyzed ${this.analyzedDependencies.size} packages, visited ${this.visitedPackages.size} packages total.`
1168
1815
  );
1169
1816
  return {
1817
+ watchFiles: [...this.watchFiles],
1818
+ diagnostics: this.diagnostics,
1170
1819
  analyzedDependencies: this.analyzedDependencies,
1171
1820
  peerConflicts,
1172
1821
  aliasMappings,
@@ -1193,10 +1842,10 @@ var DependencyAnalyzer = class {
1193
1842
  const graphRoot = this.findGraphRoot(packageName);
1194
1843
  if (graphRoot) {
1195
1844
  this.populateAnalyzedDependenciesFromGraph();
1196
- return this.analyzedDependencies.get(graphRoot.name) ?? null;
1845
+ return this.analyzedDependencies.get(packageName) ?? null;
1197
1846
  }
1198
1847
  if (this.visitedPackages.has(packageName)) {
1199
- logger4.debug(`Skipping already visited package: ${packageName}`);
1848
+ logger5.debug(`Skipping already visited package: ${packageName}`);
1200
1849
  return this.analyzedDependencies.get(packageName) ?? null;
1201
1850
  }
1202
1851
  let rootInfo = null;
@@ -1214,20 +1863,20 @@ var DependencyAnalyzer = class {
1214
1863
  this.visitedPackages.add(name);
1215
1864
  const { packagePath, pkgJson } = this.resolvePackageJson(name, this.options.projectRoot);
1216
1865
  if (!packagePath) {
1217
- logger4.debug(`Package not found: ${name}`);
1866
+ logger5.debug(`Package not found: ${name}`);
1218
1867
  continue;
1219
1868
  }
1220
1869
  if (!pkgJson) {
1221
- logger4.debug(`Could not read package.json for: ${name}`);
1870
+ logger5.debug(`Could not read package.json for: ${name}`);
1222
1871
  continue;
1223
1872
  }
1224
1873
  this.cacheInstalledPackageInfo(name, packagePath, pkgJson);
1225
- logger4.debug(`Analyzing ${name}@${pkgJson.version}`);
1874
+ logger5.debug(`Analyzing ${name}@${pkgJson.version}`);
1226
1875
  const depInfo = {
1227
1876
  name,
1228
1877
  version: pkgJson.version ?? "unknown",
1229
1878
  dependencyPath: [...path],
1230
- dependencies: pkgJson.dependencies ?? {},
1879
+ dependencies: { ...pkgJson.dependencies, ...pkgJson.optionalDependencies },
1231
1880
  peerDependencies: pkgJson.peerDependencies ?? {},
1232
1881
  peerDependenciesMeta: pkgJson.peerDependenciesMeta
1233
1882
  };
@@ -1237,7 +1886,7 @@ var DependencyAnalyzer = class {
1237
1886
  }
1238
1887
  const currentPath = [...path, name];
1239
1888
  const depsToCheck = [
1240
- ...Object.keys(pkgJson.dependencies ?? {}),
1889
+ ...Object.keys({ ...pkgJson.dependencies, ...pkgJson.optionalDependencies }),
1241
1890
  ...Object.keys(pkgJson.peerDependencies ?? {})
1242
1891
  ];
1243
1892
  for (const depName of depsToCheck) {
@@ -1251,11 +1900,8 @@ var DependencyAnalyzer = class {
1251
1900
  }
1252
1901
  findGraphRoot(packageName) {
1253
1902
  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;
1903
+ const rootId = this.dependencyGraph.rootRequests.get(packageName);
1904
+ return rootId ? this.dependencyGraph.nodes.get(rootId) ?? null : null;
1259
1905
  }
1260
1906
  getDependencyPathForGraphNode(node) {
1261
1907
  if (!this.dependencyGraph) return [];
@@ -1270,7 +1916,8 @@ var DependencyAnalyzer = class {
1270
1916
  return names.slice(0, -1);
1271
1917
  }
1272
1918
  populateAnalyzedDependenciesFromGraph() {
1273
- if (!this.dependencyGraph) return;
1919
+ if (!this.dependencyGraph || this.graphPopulated) return;
1920
+ this.graphPopulated = true;
1274
1921
  const rootVisibleNodeIds = /* @__PURE__ */ new Map();
1275
1922
  for (const node of this.dependencyGraph.nodes.values()) {
1276
1923
  const rootVisiblePath = findPackagePath(node.name, this.options.projectRoot);
@@ -1305,12 +1952,28 @@ var DependencyAnalyzer = class {
1305
1952
  name: node.name,
1306
1953
  version: node.version,
1307
1954
  dependencyPath: this.getDependencyPathForGraphNode(node),
1308
- dependencies: packageJson.dependencies ?? {},
1955
+ dependencies: { ...packageJson.dependencies, ...packageJson.optionalDependencies },
1309
1956
  peerDependencies: packageJson.peerDependencies ?? {},
1310
1957
  peerDependenciesMeta: packageJson.peerDependenciesMeta
1311
1958
  });
1312
1959
  this.visitedPackages.add(node.name);
1313
1960
  }
1961
+ for (const [name, rootId] of this.dependencyGraph.rootRequests) {
1962
+ const node = this.dependencyGraph.nodes.get(rootId);
1963
+ if (!node || node.name === name) continue;
1964
+ const packageJson = readPackageJsonCached(node.packagePath);
1965
+ if (!packageJson) continue;
1966
+ this.cacheInstalledPackageInfo(name, node.packagePath, packageJson);
1967
+ this.analyzedDependencies.set(name, {
1968
+ name,
1969
+ version: node.version,
1970
+ dependencyPath: [],
1971
+ dependencies: { ...packageJson.dependencies, ...packageJson.optionalDependencies },
1972
+ peerDependencies: packageJson.peerDependencies ?? {},
1973
+ peerDependenciesMeta: packageJson.peerDependenciesMeta
1974
+ });
1975
+ this.visitedPackages.add(name);
1976
+ }
1314
1977
  }
1315
1978
  /**
1316
1979
  * 缓存已安装包的信息(用于后续查找别名等)
@@ -1331,10 +1994,7 @@ var DependencyAnalyzer = class {
1331
1994
  const declaredSpec = this.declaredDeps[packageName];
1332
1995
  if (typeof declaredSpec === "string" && declaredSpec.startsWith("npm:")) {
1333
1996
  info.isAlias = true;
1334
- const parsed = parseNpmAlias(declaredSpec);
1335
- if (parsed) {
1336
- info.realName = parsed[0];
1337
- }
1997
+ info.realName = pkgJson.name;
1338
1998
  }
1339
1999
  this.installedPackageCache.set(packageName, info);
1340
2000
  }
@@ -1350,7 +2010,7 @@ var DependencyAnalyzer = class {
1350
2010
  const hasInstalledGraphRoots = (this.dependencyGraph?.roots.length ?? 0) > 0;
1351
2011
  for (const depName of this.options.dependencies) {
1352
2012
  if (hasInstalledGraphRoots && !this.findGraphRoot(depName)) {
1353
- logger4.debug(`Skipping non-root configured dependency: ${depName}`);
2013
+ logger5.debug(`Skipping non-root configured dependency: ${depName}`);
1354
2014
  continue;
1355
2015
  }
1356
2016
  const depInfo = this.analyzedDependencies.get(depName);
@@ -1360,7 +2020,7 @@ var DependencyAnalyzer = class {
1360
2020
  for (const [peerName, peerRange] of Object.entries(peerDeps)) {
1361
2021
  const isOptional = peerMeta[peerName]?.optional === true;
1362
2022
  if (isOptional) {
1363
- logger4.debug(
2023
+ logger5.debug(
1364
2024
  `Skipping optional first-level peer dependency: ${peerName}@${peerRange} required by ${depName}`
1365
2025
  );
1366
2026
  continue;
@@ -1371,7 +2031,7 @@ var DependencyAnalyzer = class {
1371
2031
  requiredRange: peerRange
1372
2032
  });
1373
2033
  peerDepsMap.set(peerName, existing);
1374
- logger4.debug(
2034
+ logger5.debug(
1375
2035
  `Found first-level peer dependency: ${peerName}@${peerRange} required by ${depName}${isOptional ? " (optional)" : ""}`
1376
2036
  );
1377
2037
  }
@@ -1388,6 +2048,15 @@ var DependencyAnalyzer = class {
1388
2048
  const isDeclared = this.isDeclaredInMainProject(packageName);
1389
2049
  const mainVersion = isDeclared ? this.getMainProjectVersion(packageName) : null;
1390
2050
  const isInstalled = mainVersion !== null;
2051
+ if (!isDeclared || !isInstalled) {
2052
+ this.diagnostics.push({
2053
+ code: isDeclared ? "PEER_NOT_INSTALLED" : "PEER_NOT_DECLARED",
2054
+ severity: "error",
2055
+ packageName,
2056
+ requestedBy: requestedBy.map((request) => request.path.join(">")),
2057
+ message: packageName + (isDeclared ? " is declared but not installed" : " is not declared by the host")
2058
+ });
2059
+ }
1391
2060
  const conflictingRanges = [];
1392
2061
  for (const request of requestedBy) {
1393
2062
  const resolvedRange = this.workspaceDetector.resolveVersionSpec(packageName, request.requiredRange) ?? request.requiredRange;
@@ -1401,7 +2070,7 @@ var DependencyAnalyzer = class {
1401
2070
  const hasConflict = conflictingRanges.length > 0;
1402
2071
  const needsAlias = hasConflict && isDeclared && isInstalled;
1403
2072
  if (needsAlias) {
1404
- logger4.info(
2073
+ logger5.info(
1405
2074
  `Peer conflict: ${packageName}@${mainVersion} - ${conflictingRanges.length} incompatible ranges`
1406
2075
  );
1407
2076
  }
@@ -1431,7 +2100,7 @@ var DependencyAnalyzer = class {
1431
2100
  });
1432
2101
  return pkgJson.version;
1433
2102
  }
1434
- const cached = this.installedPackageCache.get(packageName);
2103
+ const cached = this.injectedInstalledDeps?.get(packageName);
1435
2104
  if (cached) {
1436
2105
  return cached.version;
1437
2106
  }
@@ -1449,88 +2118,62 @@ var DependencyAnalyzer = class {
1449
2118
  */
1450
2119
  async generateAliasMappings(conflicts) {
1451
2120
  const aliasMappings = [];
2121
+ const usedAliasNames = /* @__PURE__ */ new Set();
1452
2122
  const aliasNeeded = conflicts.filter((c) => c.needsAlias);
1453
2123
  const allConflictPackageNames = aliasNeeded.map((c) => c.packageName);
1454
2124
  for (const conflict of aliasNeeded) {
1455
- const mappings = await this.createAliasMappingsForConflict(conflict, allConflictPackageNames);
2125
+ const mappings = await this.createAliasMappingsForConflict(
2126
+ conflict,
2127
+ allConflictPackageNames,
2128
+ usedAliasNames
2129
+ );
1456
2130
  aliasMappings.push(...mappings);
1457
2131
  }
1458
- this.linkAliasPeerImporterPaths(aliasMappings);
2132
+ await linkAliasPeers(
2133
+ aliasMappings,
2134
+ this.options,
2135
+ this.registryClient,
2136
+ this.diagnostics,
2137
+ conflicts,
2138
+ this.watchFiles
2139
+ );
1459
2140
  return aliasMappings;
1460
2141
  }
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
- }
1498
2142
  /**
1499
2143
  * 为单个冲突创建别名映射
1500
2144
  */
1501
- async createAliasMappingsForConflict(conflict, allConflictPackageNames) {
2145
+ async createAliasMappingsForConflict(conflict, allConflictPackageNames, usedAliasNames) {
1502
2146
  const { packageName, conflictingRanges } = conflict;
1503
- logger4.info(`Creating alias for "${packageName}"`);
2147
+ logger5.info(`Creating alias for "${packageName}"`);
1504
2148
  const workspaceRoot = this.workspaceDetector.getWorkspaceRoot();
1505
2149
  if (workspaceRoot) {
1506
- logger4.info(` Workspace root detected: ${workspaceRoot}`);
2150
+ logger5.info(` Workspace root detected: ${workspaceRoot}`);
1507
2151
  const wsAliases = this.findWorkspaceAliasesForPackage(packageName);
1508
2152
  if (wsAliases.length > 0) {
1509
- logger4.info(` Found ${wsAliases.length} workspace alias(es) for ${packageName}:`);
2153
+ logger5.info(` Found ${wsAliases.length} workspace alias(es) for ${packageName}:`);
1510
2154
  for (const a of wsAliases) {
1511
- logger4.info(
2155
+ logger5.info(
1512
2156
  ` - ${a.aliasName}: npm:${packageName}@${a.versionSpec} (defined in: ${a.definedIn})`
1513
2157
  );
1514
2158
  }
1515
2159
  } else {
1516
- logger4.info(
2160
+ logger5.info(
1517
2161
  ` No workspace aliases found for ${packageName} (expected npm:${packageName}@version format in root package.json)`
1518
2162
  );
1519
2163
  }
1520
2164
  } else {
1521
- logger4.info(` Not in a monorepo workspace`);
2165
+ logger5.info(` Not in a monorepo workspace`);
1522
2166
  }
1523
2167
  const localAliases = this.existingAliasesMap.get(packageName);
1524
2168
  if (localAliases && localAliases.length > 0) {
1525
- logger4.info(` Found ${localAliases.length} local alias(es) for ${packageName}:`);
2169
+ logger5.info(` Found ${localAliases.length} local alias(es) for ${packageName}:`);
1526
2170
  for (const a of localAliases) {
1527
- logger4.info(
2171
+ logger5.info(
1528
2172
  ` - ${a.aliasName}: npm:${packageName}@${a.versionSpec} (installed: ${a.installedVersion ?? "not installed"})`
1529
2173
  );
1530
2174
  }
1531
2175
  }
1532
2176
  const existingAliasNames = this.getExistingAliasNames(packageName);
1533
- const usedAliasNames = /* @__PURE__ */ new Set();
1534
2177
  const mappings = [];
1535
2178
  const installedAliasMatches = this.findInstalledAliasMatches(packageName);
1536
2179
  const installedAliasesByName = /* @__PURE__ */ new Map();
@@ -1544,10 +2187,19 @@ var DependencyAnalyzer = class {
1544
2187
  }
1545
2188
  for (const [aliasName, aliases] of installedAliasesByName) {
1546
2189
  const identities = new Set(
1547
- aliases.map((alias) => `${alias.installedPath ?? alias.scope}\0${alias.version}`)
2190
+ aliases.map(
2191
+ (alias) => `${alias.installedPath ? this.normalizeInstalledPath(alias.installedPath) : alias.scope}\0${alias.version}`
2192
+ )
1548
2193
  );
1549
2194
  if (identities.size < 2) continue;
1550
- logger4.warn(
2195
+ this.diagnostics.push({
2196
+ code: "AMBIGUOUS_ALIAS_SCOPE",
2197
+ severity: "error",
2198
+ packageName,
2199
+ aliases: [aliasName],
2200
+ message: "Alias resolves to multiple installed identities: " + aliasName
2201
+ });
2202
+ logger5.warn(
1551
2203
  `Alias reuse skipped: ${JSON.stringify({
1552
2204
  code: "AMBIGUOUS_ALIAS_SCOPE",
1553
2205
  packageName,
@@ -1574,7 +2226,7 @@ var DependencyAnalyzer = class {
1574
2226
  continue;
1575
2227
  }
1576
2228
  usedAliasNames.add(existingAlias.name);
1577
- const aliasIdentity = `${existingAlias.name}\0${existingAlias.installedPath ?? existingAlias.scope}\0${existingAlias.version}`;
2229
+ const aliasIdentity = `${existingAlias.name}\0${existingAlias.installedPath ? this.normalizeInstalledPath(existingAlias.installedPath) : existingAlias.scope}\0${existingAlias.version}`;
1578
2230
  const reusedGroup = reusedAliasGroups.get(aliasIdentity);
1579
2231
  if (reusedGroup) {
1580
2232
  reusedGroup.requests.push(request);
@@ -1596,7 +2248,14 @@ var DependencyAnalyzer = class {
1596
2248
  }
1597
2249
  for (const [aliasName, groups] of reusedGroupsByAliasName) {
1598
2250
  if (groups.length < 2) continue;
1599
- logger4.warn(
2251
+ this.diagnostics.push({
2252
+ code: "AMBIGUOUS_ALIAS_SCOPE",
2253
+ severity: "error",
2254
+ packageName,
2255
+ aliases: [aliasName],
2256
+ message: "Alias resolves to multiple installed identities: " + aliasName
2257
+ });
2258
+ logger5.warn(
1600
2259
  `Alias reuse skipped: ${JSON.stringify({
1601
2260
  code: "AMBIGUOUS_ALIAS_SCOPE",
1602
2261
  packageName,
@@ -1627,24 +2286,57 @@ var DependencyAnalyzer = class {
1627
2286
  if (unresolvedRequests.length === 0) {
1628
2287
  return mappings;
1629
2288
  }
2289
+ if (this.options.offline) {
2290
+ this.diagnostics.push({
2291
+ code: "OFFLINE_ALIAS_MISSING",
2292
+ severity: "error",
2293
+ packageName,
2294
+ requestedBy: unresolvedRequests.map((request) => request.path.join(">")),
2295
+ message: "No installed alias satisfies " + packageName + " in offline mode"
2296
+ });
2297
+ return mappings;
2298
+ }
1630
2299
  let versions;
1631
2300
  try {
1632
2301
  versions = await this.registryClient.fetchAllVersions(packageName, this.options.registry);
1633
2302
  } catch (error) {
1634
- logger4.warn(`Failed to fetch versions for ${packageName}: ${String(error)}`);
2303
+ this.diagnostics.push({
2304
+ code: "REGISTRY_ERROR",
2305
+ severity: "error",
2306
+ packageName,
2307
+ message: "Failed to fetch versions for " + packageName + ": " + String(error)
2308
+ });
2309
+ logger5.warn(`Failed to fetch versions for ${packageName}: ${String(error)}`);
1635
2310
  return mappings;
1636
2311
  }
1637
2312
  if (versions.length === 0) {
1638
- logger4.warn(`No versions found for ${packageName}`);
2313
+ this.diagnostics.push({
2314
+ code: "NO_MATCHING_VERSION",
2315
+ severity: "error",
2316
+ packageName,
2317
+ message: "No versions available for " + packageName
2318
+ });
2319
+ logger5.warn(`No versions found for ${packageName}`);
1639
2320
  return mappings;
1640
2321
  }
2322
+ for (const request of unresolvedRequests) {
2323
+ if (!versions.some((version) => satisfies(version, request.requiredRange))) {
2324
+ this.diagnostics.push({
2325
+ code: "NO_MATCHING_VERSION",
2326
+ severity: "error",
2327
+ packageName,
2328
+ requestedBy: request.path,
2329
+ message: "No available version satisfies " + packageName + "@" + request.requiredRange
2330
+ });
2331
+ }
2332
+ }
1641
2333
  const rangeGroups = this.groupRangesByCompatibility(unresolvedRequests, versions);
1642
- logger4.info(`Creating alias for "${packageName}": ${rangeGroups.length} version groups`);
2334
+ logger5.info(`Creating alias for "${packageName}": ${rangeGroups.length} version groups`);
1643
2335
  for (let i = 0; i < rangeGroups.length; i++) {
1644
2336
  const group = rangeGroups[i];
1645
2337
  if (!group || group.length === 0) continue;
1646
2338
  const groupRanges = [...new Set(group.map((r) => r.requiredRange))];
1647
- logger4.debug(` Group ${i + 1}: ${groupRanges.join(", ")}`);
2339
+ logger5.debug(` Group ${i + 1}: ${groupRanges.join(", ")}`);
1648
2340
  const mapping = this.createAliasMappingForGroup(
1649
2341
  packageName,
1650
2342
  group,
@@ -1702,7 +2394,7 @@ var DependencyAnalyzer = class {
1702
2394
  createAliasMappingForGroup(packageName, group, groupRanges, versions, existingAliasNames, usedAliasNames, allConflictPackageNames) {
1703
2395
  const existingAlias = this.findExistingAliasForRanges(packageName, groupRanges, usedAliasNames);
1704
2396
  if (existingAlias) {
1705
- logger4.debug(
2397
+ logger5.debug(
1706
2398
  ` Reusing: ${existingAlias.name}@${existingAlias.version}${existingAlias.isWorkspaceAlias ? " (workspace)" : ""}`
1707
2399
  );
1708
2400
  return this.buildAliasMapping(
@@ -1717,7 +2409,7 @@ var DependencyAnalyzer = class {
1717
2409
  }
1718
2410
  const bestVersion = findBestVersion(versions, groupRanges);
1719
2411
  if (!bestVersion) {
1720
- logger4.warn(
2412
+ logger5.warn(
1721
2413
  ` No version satisfies all ranges [${groupRanges.join(", ")}] for ${packageName}`
1722
2414
  );
1723
2415
  return null;
@@ -1729,7 +2421,7 @@ var DependencyAnalyzer = class {
1729
2421
  ]);
1730
2422
  const aliasName = this.generateUniqueAliasName(packageName, bestVersion, combinedExisting);
1731
2423
  const installSpec = createAliasInstallSpec(aliasName, packageName, bestVersion);
1732
- logger4.info(` New alias: ${aliasName}@${bestVersion}`);
2424
+ logger5.info(` New alias: ${aliasName}@${bestVersion}`);
1733
2425
  return this.buildAliasMapping(
1734
2426
  packageName,
1735
2427
  aliasName,
@@ -1819,32 +2511,32 @@ var DependencyAnalyzer = class {
1819
2511
  * 优先查找当前项目的别名,然后查找 workspace 级别的别名
1820
2512
  */
1821
2513
  findExistingAliasForRanges(packageName, ranges, excludeAliases) {
1822
- logger4.debug(
2514
+ logger5.debug(
1823
2515
  ` Searching for existing alias for ${packageName} satisfying ranges: [${ranges.join(", ")}]`
1824
2516
  );
1825
2517
  const npmAliases = this.existingAliasesMap.get(packageName);
1826
2518
  if (npmAliases && npmAliases.length > 0) {
1827
- logger4.debug(` Checking ${npmAliases.length} local alias(es)...`);
2519
+ logger5.debug(` Checking ${npmAliases.length} local alias(es)...`);
1828
2520
  for (const alias of npmAliases) {
1829
2521
  if (excludeAliases.has(alias.aliasName)) {
1830
- logger4.debug(` Skip ${alias.aliasName}: already used`);
2522
+ logger5.debug(` Skip ${alias.aliasName}: already used`);
1831
2523
  continue;
1832
2524
  }
1833
2525
  alias.installedVersion ??= this.getAliasInstalledVersion(alias.aliasName);
1834
2526
  if (!alias.installedVersion) {
1835
- logger4.debug(` Skip ${alias.aliasName}: not installed`);
2527
+ logger5.debug(` Skip ${alias.aliasName}: not installed`);
1836
2528
  continue;
1837
2529
  }
1838
2530
  const installedAlias = this.installedPackageCache.get(alias.aliasName);
1839
2531
  if (installedAlias?.realName !== packageName) {
1840
- logger4.debug(
2532
+ logger5.debug(
1841
2533
  ` Skip ${alias.aliasName}: installed package name ${installedAlias?.realName ?? "unknown"} does not match ${packageName}`
1842
2534
  );
1843
2535
  continue;
1844
2536
  }
1845
2537
  const allSatisfied = ranges.every((range) => satisfies(alias.installedVersion, range));
1846
2538
  if (allSatisfied) {
1847
- logger4.info(` Reusing local alias: ${alias.aliasName}@${alias.installedVersion}`);
2539
+ logger5.info(` Reusing local alias: ${alias.aliasName}@${alias.installedVersion}`);
1848
2540
  return {
1849
2541
  name: alias.aliasName,
1850
2542
  version: alias.installedVersion,
@@ -1852,74 +2544,39 @@ var DependencyAnalyzer = class {
1852
2544
  scope: "local"
1853
2545
  };
1854
2546
  } else {
1855
- logger4.debug(
2547
+ logger5.debug(
1856
2548
  ` Skip ${alias.aliasName}@${alias.installedVersion}: version doesn't satisfy all ranges`
1857
2549
  );
1858
2550
  }
1859
2551
  }
1860
2552
  }
1861
2553
  const workspaceAliases = this.findWorkspaceAliasesForPackage(packageName);
1862
- const workspaceRoot = this.workspaceDetector.getWorkspaceRoot();
1863
2554
  if (workspaceAliases.length > 0) {
1864
- logger4.debug(` Checking ${workspaceAliases.length} workspace alias(es)...`);
2555
+ logger5.debug(` Checking ${workspaceAliases.length} workspace alias(es)...`);
1865
2556
  }
1866
2557
  for (const wsAlias of workspaceAliases) {
1867
2558
  if (excludeAliases.has(wsAlias.aliasName)) {
1868
- logger4.debug(` Skip ${wsAlias.aliasName}: already used`);
2559
+ logger5.debug(` Skip ${wsAlias.aliasName}: already used`);
1869
2560
  continue;
1870
2561
  }
1871
- let installedVersion = null;
1872
- let installedPath;
1873
- if (workspaceRoot) {
1874
- const { packagePath, pkgJson } = this.resolvePackageJson(wsAlias.aliasName, workspaceRoot);
1875
- if (packagePath) {
1876
- if (pkgJson?.name !== packageName) {
1877
- logger4.debug(
1878
- ` Skip ${wsAlias.aliasName}: installed package name ${pkgJson?.name ?? "unknown"} does not match ${packageName}`
1879
- );
1880
- continue;
1881
- }
1882
- installedVersion = pkgJson?.version ?? null;
1883
- installedPath = packagePath;
1884
- logger4.debug(
1885
- ` Found ${wsAlias.aliasName} installed at workspace root: ${installedVersion}`
1886
- );
1887
- }
1888
- }
1889
- if (!installedVersion) {
1890
- installedVersion = this.getAliasInstalledVersion(wsAlias.aliasName);
1891
- if (installedVersion) {
1892
- const installedAlias = this.installedPackageCache.get(wsAlias.aliasName);
1893
- installedPath = installedAlias?.path;
1894
- if (installedAlias?.realName !== packageName) {
1895
- logger4.debug(
1896
- ` Skip ${wsAlias.aliasName}: installed package name ${installedAlias?.realName ?? "unknown"} does not match ${packageName}`
1897
- );
1898
- continue;
1899
- }
1900
- logger4.debug(` Found ${wsAlias.aliasName} installed at project: ${installedVersion}`);
1901
- }
1902
- }
1903
- if (installedVersion) {
1904
- const allSatisfied = ranges.every((range) => satisfies(installedVersion, range));
1905
- if (allSatisfied) {
1906
- logger4.info(` Reusing workspace alias: ${wsAlias.aliasName}@${installedVersion}`);
1907
- return {
1908
- name: wsAlias.aliasName,
1909
- version: installedVersion,
1910
- isWorkspaceAlias: true,
1911
- installedPath,
1912
- scope: "workspace"
1913
- };
1914
- } else {
1915
- logger4.debug(
1916
- ` Skip ${wsAlias.aliasName}@${installedVersion}: version doesn't satisfy all ranges`
1917
- );
1918
- }
1919
- continue;
2562
+ const { packagePath, pkgJson } = this.resolvePackageJson(
2563
+ wsAlias.aliasName,
2564
+ this.options.projectRoot
2565
+ );
2566
+ if (!packagePath || pkgJson?.name !== packageName || !pkgJson.version) continue;
2567
+ const installedVersion = pkgJson.version;
2568
+ if (ranges.every((range) => satisfies(installedVersion, range))) {
2569
+ logger5.info(` Reusing workspace alias: ${wsAlias.aliasName}@${installedVersion}`);
2570
+ return {
2571
+ name: wsAlias.aliasName,
2572
+ version: installedVersion,
2573
+ isWorkspaceAlias: true,
2574
+ installedPath: packagePath,
2575
+ scope: "workspace"
2576
+ };
1920
2577
  }
1921
2578
  }
1922
- logger4.debug(` No existing alias found for ${packageName}`);
2579
+ logger5.debug(` No existing alias found for ${packageName}`);
1923
2580
  return null;
1924
2581
  }
1925
2582
  /**
@@ -1996,9 +2653,8 @@ var DependencyAnalyzer = class {
1996
2653
  }
1997
2654
  findGraphChildNode(parent, dependencyName) {
1998
2655
  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;
2656
+ const childId = parent.resolvedChildren.get(dependencyName);
2657
+ return childId ? this.dependencyGraph.nodes.get(childId) ?? null : null;
2002
2658
  }
2003
2659
  /**
2004
2660
  * 收集图中指定根实例的所有后代实例。返回 null 表示当前分析没有
@@ -2006,11 +2662,7 @@ var DependencyAnalyzer = class {
2006
2662
  */
2007
2663
  collectGraphRelatedPackageInstances(packageNames, excludePackages = []) {
2008
2664
  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);
2665
+ const roots = packageNames.map((packageName) => this.findGraphRoot(packageName)).filter((node) => node !== null);
2014
2666
  if (roots.length === 0) return null;
2015
2667
  const excludeSet = new Set(excludePackages);
2016
2668
  const visited = /* @__PURE__ */ new Set();
@@ -2072,7 +2724,7 @@ var DependencyAnalyzer = class {
2072
2724
  }
2073
2725
  const { packagePath, pkgJson } = this.resolvePackageJson(name, currentBaseDir);
2074
2726
  if (!packagePath) {
2075
- logger4.debug(
2727
+ logger5.debug(
2076
2728
  `Package not found for dependency collection: ${name} (from ${currentBaseDir})`
2077
2729
  );
2078
2730
  continue;
@@ -2084,7 +2736,7 @@ var DependencyAnalyzer = class {
2084
2736
  if (!pkgJson) {
2085
2737
  continue;
2086
2738
  }
2087
- const deps = pkgJson.dependencies ?? {};
2739
+ const deps = { ...pkgJson.dependencies, ...pkgJson.optionalDependencies };
2088
2740
  const peerDeps = pkgJson.peerDependencies ?? {};
2089
2741
  for (const depName of Object.keys(deps)) {
2090
2742
  stack.push({ name: depName, baseDir: packagePath });
@@ -2157,277 +2809,26 @@ var DependencyAnalyzer = class {
2157
2809
  return missing;
2158
2810
  }
2159
2811
  };
2160
- function createDependencyAnalyzer(options) {
2812
+ function createDependencyAnalyzer(options, preparedAliases = []) {
2161
2813
  const mainPackageJson = readPackageJsonCached(options.projectRoot);
2162
2814
  if (!mainPackageJson) {
2163
2815
  throw new Error(`Could not read package.json at ${options.projectRoot}`);
2164
2816
  }
2165
- return new DependencyAnalyzer(options, mainPackageJson);
2166
- }
2167
- var logger5 = createLogger("alias-manager");
2168
- var AliasManager = class {
2169
- options;
2170
- aliasMappings = [];
2171
- /**
2172
- * 规则索引:originalName -> 相关规则列表
2173
- * 用于在 resolveModule 时避免全量遍历所有规则,提升 dev server/HMR 场景下性能。
2174
- */
2175
- rulesMap = /* @__PURE__ */ new Map();
2176
- /**
2177
- * importer 路径 -> 包名列表 的 LRU 缓存
2178
- * dev server / HMR 场景下同一 importer 会被反复解析,缓存避免重复字符串拆分
2179
- */
2180
- importerCache = new LruCache({ maxEntries: 1e3 });
2181
- constructor(options) {
2182
- this.options = options;
2183
- }
2184
- /**
2185
- * 从分析结果初始化别名映射
2186
- */
2187
- initFromAnalysisResult(result) {
2188
- this.aliasMappings = result.aliasMappings;
2189
- this.buildRules();
2190
- logger5.info(`Initialized ${this.aliasMappings.length} alias mappings`);
2191
- }
2192
- /**
2193
- * 清理当前 generation 的别名规则。
2194
- *
2195
- * Resolver 失效或回滚时必须移除旧规则,避免失败的 generation 继续参与解析。
2196
- */
2197
- clear() {
2198
- this.aliasMappings = [];
2199
- this.rulesMap = /* @__PURE__ */ new Map();
2200
- this.importerCache.clear();
2201
- }
2202
- /**
2203
- * 基于 allDependents 构建规则(用 Set 做成员判断,避免超大正则导致的性能与长度问题)
2204
- */
2205
- buildRules() {
2206
- this.rulesMap = /* @__PURE__ */ new Map();
2207
- this.importerCache.clear();
2208
- for (const mapping of this.aliasMappings) {
2209
- const isPathScoped = mapping.importerPaths !== void 0;
2210
- const dependents = new Set(isPathScoped ? [] : mapping.allDependents ?? []);
2211
- const includeList = this.options.includeRedirects[mapping.originalName] ?? [];
2212
- if (includeList.length > 0) {
2213
- for (const dep of includeList) {
2214
- dependents.add(dep);
2215
- }
2216
- logger5.debug(`Included redirects for ${mapping.originalName}: ${includeList.join(", ")}`);
2217
- }
2218
- const excludeList = this.options.excludeRedirects[mapping.originalName] ?? [];
2219
- if (!isPathScoped && excludeList.length > 0) {
2220
- for (const dep of excludeList) {
2221
- dependents.delete(dep);
2222
- }
2223
- logger5.debug(`Excluded redirects for ${mapping.originalName}: ${excludeList.join(", ")}`);
2224
- }
2225
- const rule = {
2226
- originalName: mapping.originalName,
2227
- aliasName: mapping.aliasName,
2228
- dependents,
2229
- importerPaths: isPathScoped ? mapping.importerPaths.map((path) => this.normalizeImporterPath(path)) : void 0,
2230
- excludedPackages: new Set(excludeList)
2231
- };
2232
- const list = this.rulesMap.get(rule.originalName);
2233
- if (list) {
2234
- list.push(rule);
2235
- } else {
2236
- this.rulesMap.set(rule.originalName, [rule]);
2237
- }
2238
- }
2239
- }
2240
- /**
2241
- * 从模块请求中提取“包名部分”,用于索引命中:
2242
- * - vue/compiler-sfc -> vue
2243
- * - @scope/pkg/subpath -> @scope/pkg
2244
- * - @scope/pkg/subpath?raw -> @scope/pkg
2245
- * - virtual:xxx -> virtual:xxx
2246
- * - C:\path\to\file (Windows) -> ''(视为非包请求)
2247
- */
2248
- getRequestPackageName(request) {
2249
- if (!request) return "";
2250
- const base = request.split(/[?#]/, 1)[0] ?? "";
2251
- if (!base) return "";
2252
- if (/^[a-zA-Z]:[\\/]/.test(base)) {
2253
- return "";
2254
- }
2255
- if (base.startsWith("@")) {
2256
- const firstSlash = base.indexOf("/");
2257
- if (firstSlash === -1) return base;
2258
- const secondSlash = base.indexOf("/", firstSlash + 1);
2259
- return secondSlash === -1 ? base : base.slice(0, secondSlash);
2260
- }
2261
- const slash = base.indexOf("/");
2262
- return slash === -1 ? base : base.slice(0, slash);
2263
- }
2264
- /**
2265
- * 从 importer 路径中提取所有 node_modules 里出现过的包名(包含嵌套 node_modules)。
2266
- *
2267
- * 示例:
2268
- * - /p/node_modules/a/index.js -> ["a"]
2269
- * - /p/node_modules/a/node_modules/b/x.js -> ["a","b"]
2270
- * - /p/node_modules/@s/a/dist/index.js -> ["@s/a"]
2271
- * - /p/node_modules/.pnpm/a@1/node_modules/a/ -> ["a"](会跳过 ".pnpm")
2272
- */
2273
- normalizeImporterPath(importerPath) {
2274
- const normalized = path.posix.normalize(importerPath.replace(/\\/g, "/"));
2275
- if (normalized.length <= 1) return normalized;
2276
- return normalized.replace(/\/+$/, "");
2277
- }
2278
- extractImporterPackageInstances(importer) {
2279
- const cached = this.importerCache.get(importer);
2280
- if (cached) {
2281
- return cached;
2282
- }
2283
- const normalized = this.normalizeImporterPath(importer);
2284
- const parts = normalized.split("/");
2285
- const packages = [];
2286
- for (let i = 0; i < parts.length - 1; i++) {
2287
- if (parts[i] !== "node_modules") continue;
2288
- const next = parts[i + 1];
2289
- if (!next || next.startsWith(".")) {
2290
- continue;
2291
- }
2292
- if (next.startsWith("@")) {
2293
- const name = parts[i + 2];
2294
- if (name) {
2295
- packages.push({
2296
- name: `${next}/${name}`,
2297
- path: this.normalizeImporterPath(parts.slice(0, i + 3).join("/"))
2298
- });
2299
- }
2300
- continue;
2301
- }
2302
- packages.push({
2303
- name: next,
2304
- path: this.normalizeImporterPath(parts.slice(0, i + 2).join("/"))
2305
- });
2306
- }
2307
- this.importerCache.set(importer, packages);
2308
- return packages;
2309
- }
2310
- matchesImporterPath(importer, packagePath) {
2311
- const importerCandidates = this.getNormalizedPathCandidates(importer);
2312
- const packageCandidates = this.getNormalizedPathCandidates(packagePath);
2313
- return [...importerCandidates].some(
2314
- (normalizedImporter) => [...packageCandidates].some(
2315
- (normalizedPackagePath) => normalizedImporter === normalizedPackagePath || normalizedImporter.startsWith(`${normalizedPackagePath}/`)
2316
- )
2317
- );
2318
- }
2319
- getNormalizedPathCandidates(path) {
2320
- const candidates = /* @__PURE__ */ new Set([this.normalizeImporterPath(path)]);
2321
- try {
2322
- candidates.add(this.normalizeImporterPath(fs.realpathSync(path)));
2323
- } catch {
2324
- }
2325
- return candidates;
2326
- }
2327
- getPathScopedMatch(rule, importer, importerInstances) {
2328
- if (!rule.importerPaths) return null;
2329
- const matchedPaths = rule.importerPaths.filter(
2330
- (packagePath) => this.matchesImporterPath(importer, packagePath)
2331
- );
2332
- const includedInstances = importerInstances.filter(
2333
- (instance) => rule.dependents.has(instance.name)
2334
- );
2335
- const bestPath = matchedPaths.reduce(
2336
- (current, packagePath) => !current || packagePath.length > current.length ? packagePath : current,
2337
- null
2338
- );
2339
- if (!bestPath && includedInstances.length === 0) return null;
2340
- const nestedInstances = importerInstances.filter(
2341
- (instance) => matchedPaths.some((matchedPath) => this.matchesImporterPath(instance.path, matchedPath))
2342
- );
2343
- return {
2344
- excluded: nestedInstances.some((instance) => rule.excludedPackages.has(instance.name)) || includedInstances.some((instance) => rule.excludedPackages.has(instance.name)),
2345
- specificity: bestPath?.length ?? 0
2346
- };
2347
- }
2348
- /**
2349
- * 解析模块请求
2350
- * @returns 解析后的模块名,如果不需要重定向则返回 null
2351
- */
2352
- resolveModule(context) {
2353
- const { request, importer } = context;
2354
- if (!importer) {
2355
- return null;
2356
- }
2357
- const importerInstances = this.extractImporterPackageInstances(importer);
2358
- if (importerInstances.length === 0) {
2359
- return null;
2360
- }
2361
- const requestPackageName = this.getRequestPackageName(request);
2362
- if (!requestPackageName) {
2363
- return null;
2364
- }
2365
- const candidateRules = this.rulesMap.get(requestPackageName);
2366
- if (!candidateRules || candidateRules.length === 0) {
2367
- return null;
2368
- }
2369
- const pathMatches = candidateRules.map((rule) => ({ rule, match: this.getPathScopedMatch(rule, importer, importerInstances) })).filter(
2370
- (entry) => entry.match !== null
2371
- ).sort(
2372
- (left, right) => right.match.specificity - left.match.specificity || left.rule.aliasName.localeCompare(right.rule.aliasName)
2373
- );
2374
- for (const { rule, match } of pathMatches) {
2375
- if (match.excluded) {
2376
- return null;
2377
- }
2378
- if (request === rule.originalName) {
2379
- logger5.debug(`Resolving ${request} -> ${rule.aliasName} (from ${importer})`);
2380
- return rule.aliasName;
2381
- }
2382
- const prefix = `${rule.originalName}/`;
2383
- if (request.startsWith(prefix)) {
2384
- const resolved = `${rule.aliasName}${request.slice(rule.originalName.length)}`;
2385
- logger5.debug(`Resolving ${request} -> ${resolved} (from ${importer})`);
2386
- return resolved;
2387
- }
2388
- }
2389
- for (const rule of candidateRules) {
2390
- if (rule.importerPaths) continue;
2391
- const hasExcludedImporter = importerInstances.some(
2392
- ({ name: pkg }) => rule.excludedPackages.has(pkg)
2393
- );
2394
- const shouldRedirect = !hasExcludedImporter && importerInstances.some(({ name: pkg }) => rule.dependents.has(pkg));
2395
- if (!shouldRedirect) {
2396
- continue;
2397
- }
2398
- if (request === rule.originalName) {
2399
- logger5.debug(`Resolving ${request} -> ${rule.aliasName} (from ${importer})`);
2400
- return rule.aliasName;
2401
- }
2402
- const prefix = `${rule.originalName}/`;
2403
- if (request.startsWith(prefix)) {
2404
- const resolved = `${rule.aliasName}${request.slice(rule.originalName.length)}`;
2405
- logger5.debug(`Resolving ${request} -> ${resolved} (from ${importer})`);
2406
- return resolved;
2407
- }
2408
- }
2409
- return null;
2410
- }
2411
- /**
2412
- * 获取别名路径映射
2413
- * 返回别名名称到实际路径的映射,供构建工具插件转换为各自的格式
2414
- */
2415
- getAliasPathMappings() {
2416
- const mappings = [];
2417
- for (const mapping of this.aliasMappings) {
2418
- const aliasPath = findPackagePath(mapping.aliasName, this.options.projectRoot);
2419
- const resolvedPath = aliasPath ?? path.join(this.options.projectRoot, "node_modules", mapping.aliasName);
2420
- mappings.push({
2421
- aliasName: mapping.aliasName,
2422
- originalName: mapping.originalName,
2423
- path: resolvedPath
2424
- });
2425
- }
2426
- return mappings;
2427
- }
2428
- };
2429
- function createAliasManager(options) {
2430
- return new AliasManager(options);
2817
+ const declared = {
2818
+ ...mainPackageJson.dependencies,
2819
+ ...mainPackageJson.devDependencies,
2820
+ ...mainPackageJson.optionalDependencies
2821
+ };
2822
+ const additional = Object.fromEntries(
2823
+ preparedAliases.filter((mapping) => !Object.hasOwn(declared, mapping.aliasName)).map((mapping) => [
2824
+ mapping.aliasName,
2825
+ "npm:" + mapping.originalName + "@" + mapping.resolvedVersion
2826
+ ])
2827
+ );
2828
+ return new DependencyAnalyzer(options, {
2829
+ ...mainPackageJson,
2830
+ devDependencies: { ...additional, ...mainPackageJson.devDependencies }
2831
+ });
2431
2832
  }
2432
2833
  var logger6 = createLogger("package-manager-adapter");
2433
2834
  var PACKAGE_MANAGER_ENTRYPOINT_RULES = {
@@ -2470,7 +2871,7 @@ function createPackageManagerAdapter(options, timing = DEFAULT_TIMING) {
2470
2871
  stdio: ["ignore", "pipe", "pipe"],
2471
2872
  ...process.platform === "win32" ? {} : { detached: true }
2472
2873
  });
2473
- return new Promise((resolve3) => {
2874
+ return new Promise((resolve4) => {
2474
2875
  let stdout = "";
2475
2876
  let stderr = "";
2476
2877
  let terminalError;
@@ -2493,7 +2894,7 @@ function createPackageManagerAdapter(options, timing = DEFAULT_TIMING) {
2493
2894
  }
2494
2895
  settled = true;
2495
2896
  clearTimers();
2496
- resolve3({
2897
+ resolve4({
2497
2898
  success: !timedOut && !terminalError && exitCode === 0,
2498
2899
  exitCode,
2499
2900
  stdout,
@@ -2754,12 +3155,12 @@ function getEnvironmentValue(environment, name) {
2754
3155
  const key = Object.keys(environment).find((candidate) => candidate.toLowerCase() === lowerName);
2755
3156
  return key ? environment[key] : void 0;
2756
3157
  }
2757
- function registryEnvironment(packageManager, registry) {
3158
+ function registryEnvironment(packageManager, registry2) {
2758
3159
  return {
2759
3160
  ...process.env,
2760
- npm_config_registry: registry,
3161
+ npm_config_registry: registry2,
2761
3162
  // Classic Yarn reads npm's registry setting; modern Yarn uses this key.
2762
- ...packageManager === "yarn" ? { YARN_NPM_REGISTRY_SERVER: registry } : {}
3163
+ ...packageManager === "yarn" ? { YARN_NPM_REGISTRY_SERVER: registry2 } : {}
2763
3164
  };
2764
3165
  }
2765
3166
  function sendTerminationSignal(child, signal) {
@@ -3057,8 +3458,170 @@ var PackageInstaller = class {
3057
3458
  function createPackageInstaller(options) {
3058
3459
  return new PackageInstaller(options);
3059
3460
  }
3060
-
3061
- // src/core/resolver.ts
3461
+ var registryKey = /* @__PURE__ */ Symbol.for("deps-conflict-resolver.project-preparation.v1");
3462
+ var registry = globalThis;
3463
+ var projects = registry[registryKey] ??= /* @__PURE__ */ new Map();
3464
+ var collectedProjects = new FinalizationRegistry(({ owner, ref }) => {
3465
+ if (projects.get(owner) === ref) projects.delete(owner);
3466
+ });
3467
+ function getProjectPreparation(projectRoot) {
3468
+ try {
3469
+ projectRoot = fs.realpathSync(projectRoot);
3470
+ } catch {
3471
+ projectRoot = path.resolve(projectRoot);
3472
+ }
3473
+ let owner = createWorkspaceDetector(projectRoot).getWorkspaceRoot() ?? projectRoot;
3474
+ if (owner === projectRoot) {
3475
+ for (const directory of iterateParentDirs(projectRoot)) {
3476
+ if (Object.keys(LOCK_FILE_MAP).some((file) => fs.existsSync(path.join(directory, file)))) {
3477
+ owner = directory;
3478
+ break;
3479
+ }
3480
+ }
3481
+ }
3482
+ try {
3483
+ owner = fs.realpathSync(owner);
3484
+ } catch {
3485
+ owner = path.resolve(owner);
3486
+ }
3487
+ let state = projects.get(owner)?.deref();
3488
+ if (!state) {
3489
+ state = { owner, revision: 0, writing: false, tail: Promise.resolve(), observers: /* @__PURE__ */ new Set() };
3490
+ const ref = new WeakRef(state);
3491
+ projects.set(owner, ref);
3492
+ collectedProjects.register(state, { owner, ref });
3493
+ }
3494
+ return state;
3495
+ }
3496
+ async function readOwner(path) {
3497
+ try {
3498
+ const value = JSON.parse(await fs.promises.readFile(path, "utf8"));
3499
+ if (value && typeof value === "object" && "pid" in value && "host" in value && "token" in value && "ticket" in value && Number.isInteger(value.pid) && Number(value.pid) > 0 && typeof value.host === "string" && typeof value.token === "string" && Number.isSafeInteger(value.ticket) && Number(value.ticket) >= 0) {
3500
+ return value;
3501
+ }
3502
+ } catch (error) {
3503
+ if (error.code === "ENOENT") return null;
3504
+ throw error;
3505
+ }
3506
+ throw new Error("Invalid dependency preparation lock record: " + path);
3507
+ }
3508
+ function exited(owner) {
3509
+ if (owner.host !== os.hostname()) return false;
3510
+ try {
3511
+ process.kill(owner.pid, 0);
3512
+ } catch (error) {
3513
+ return error.code === "ESRCH";
3514
+ }
3515
+ return false;
3516
+ }
3517
+ async function removeRecord(path) {
3518
+ await fs.promises.unlink(path).catch((error) => {
3519
+ if (error.code !== "ENOENT") throw error;
3520
+ });
3521
+ }
3522
+ async function readContenders(directory, token) {
3523
+ const contenders = [];
3524
+ for (const name of await fs.promises.readdir(directory)) {
3525
+ if (!name.endsWith(".json") || name === token + ".json") continue;
3526
+ const path$1 = path.join(directory, name);
3527
+ const owner = await readOwner(path$1);
3528
+ if (!owner) continue;
3529
+ if (owner.token + ".json" !== name)
3530
+ throw new Error("Invalid dependency preparation lock identity: " + path$1);
3531
+ if (exited(owner)) {
3532
+ await removeRecord(path$1);
3533
+ } else contenders.push(owner);
3534
+ }
3535
+ return contenders;
3536
+ }
3537
+ async function acquireLock(owner) {
3538
+ const user = typeof process.getuid === "function" ? String(process.getuid()) : crypto.createHash("sha256").update(os.userInfo().username).digest("hex");
3539
+ const key = crypto.createHash("sha256").update(owner).digest("hex");
3540
+ const directory = path.join(os.tmpdir(), "deps-conflict-resolver-locks-" + user, key + ".queue");
3541
+ await fs.promises.mkdir(directory, { recursive: true, mode: 448 });
3542
+ const token = crypto.randomUUID();
3543
+ const path$1 = path.join(directory, token + ".json");
3544
+ const candidate = path.join(directory, token + ".tmp");
3545
+ const record = { pid: process.pid, host: os.hostname(), token, ticket: 0 };
3546
+ const deadline = perf_hooks.performance.now() + 3e5;
3547
+ let published = false;
3548
+ try {
3549
+ await fs.promises.writeFile(candidate, JSON.stringify(record), { flag: "wx", mode: 384 });
3550
+ await fs.promises.link(candidate, path$1);
3551
+ published = true;
3552
+ await removeRecord(candidate);
3553
+ record.ticket = 1 + (await readContenders(directory, token)).reduce(
3554
+ (max, other) => Math.max(max, other.ticket),
3555
+ 0
3556
+ );
3557
+ if (!Number.isSafeInteger(record.ticket))
3558
+ throw new Error("Dependency preparation ticket limit exceeded in " + owner);
3559
+ await fs.promises.writeFile(candidate, JSON.stringify(record), { flag: "wx", mode: 384 });
3560
+ await fs.promises.rename(candidate, path$1);
3561
+ while (true) {
3562
+ const blocked = (await readContenders(directory, token)).some(
3563
+ (other) => other.ticket === 0 || other.ticket < record.ticket || other.ticket === record.ticket && other.token < token
3564
+ );
3565
+ if (!blocked) return () => removeRecord(path$1);
3566
+ if (perf_hooks.performance.now() >= deadline)
3567
+ throw new Error(
3568
+ "Timed out waiting for dependency preparation in " + owner + " (lock: " + path$1 + ")"
3569
+ );
3570
+ await new Promise((done) => setTimeout(done, 25));
3571
+ }
3572
+ } catch (error) {
3573
+ try {
3574
+ await removeRecord(candidate);
3575
+ } finally {
3576
+ if (published) await removeRecord(path$1);
3577
+ }
3578
+ throw error;
3579
+ }
3580
+ }
3581
+ async function withProjectPreparation(state, task, current) {
3582
+ const previous = state.tail;
3583
+ let finish;
3584
+ state.tail = new Promise((done) => {
3585
+ finish = done;
3586
+ });
3587
+ await previous;
3588
+ let unlock;
3589
+ let changed = false;
3590
+ try {
3591
+ unlock = await acquireLock(state.owner);
3592
+ return await task(() => {
3593
+ if (!changed) {
3594
+ state.revision++;
3595
+ changed = true;
3596
+ }
3597
+ state.writing = true;
3598
+ });
3599
+ } finally {
3600
+ try {
3601
+ if (changed) {
3602
+ for (const ref of state.observers) {
3603
+ const observer = ref.deref();
3604
+ if (!observer) state.observers.delete(ref);
3605
+ else if (observer !== current) await observer.refresh();
3606
+ }
3607
+ }
3608
+ } finally {
3609
+ state.writing = false;
3610
+ try {
3611
+ await unlock?.();
3612
+ } finally {
3613
+ finish();
3614
+ }
3615
+ }
3616
+ }
3617
+ }
3618
+ async function waitForProjectPreparation(state) {
3619
+ while (true) {
3620
+ const ready = state.tail;
3621
+ await ready;
3622
+ if (ready === state.tail) return;
3623
+ }
3624
+ }
3062
3625
  var logger8 = createLogger("resolver");
3063
3626
  var DEFAULT_OPTIONS = {
3064
3627
  autoInstall: true,
@@ -3076,11 +3639,24 @@ var DepsConflictResolver = class {
3076
3639
  analysisResult = null;
3077
3640
  initialized = false;
3078
3641
  initializationPromise = null;
3642
+ installationPromise = null;
3643
+ preparing = false;
3644
+ installResult = null;
3645
+ installDiagnostics = [];
3646
+ preparation = null;
3647
+ snapshotRevision = 0;
3648
+ snapshotError = null;
3649
+ snapshotGeneration = 0;
3650
+ snapshotSignature = "";
3651
+ snapshotInvalidated = false;
3652
+ activeMappings = [];
3653
+ snapshotObserver = null;
3654
+ observer = { refresh: () => this.refreshSnapshot() };
3079
3655
  constructor(userOptions, hooks = {}) {
3080
3656
  this.userOptions = userOptions;
3081
3657
  this.hooks = hooks;
3082
3658
  if (userOptions.debug) {
3083
- logger8.setLevel(1 /* DEBUG */);
3659
+ logger8.setLevel(15 /* ALL */);
3084
3660
  }
3085
3661
  }
3086
3662
  /**
@@ -3098,22 +3674,24 @@ var DepsConflictResolver = class {
3098
3674
  } else {
3099
3675
  packageManager = userOptions.packageManager;
3100
3676
  }
3101
- let registry;
3677
+ let registry2;
3102
3678
  if (!userOptions.registry) {
3103
- registry = await this.environmentDetector.getRegistryForPackageManager(packageManager);
3104
- if (registry !== DEFAULT_NPM_REGISTRY) {
3105
- logger8.info(`Auto-detected registry: ${registry}`);
3679
+ registry2 = await this.environmentDetector.getRegistryForPackageManager(packageManager);
3680
+ if (registry2 !== DEFAULT_NPM_REGISTRY) {
3681
+ logger8.info(`Auto-detected registry: ${registry2}`);
3106
3682
  }
3107
3683
  } else {
3108
- registry = userOptions.registry;
3684
+ registry2 = userOptions.registry;
3109
3685
  }
3110
3686
  return {
3111
3687
  ...DEFAULT_OPTIONS,
3112
3688
  dependencies: userOptions.dependencies,
3113
3689
  projectRoot,
3114
3690
  packageManager,
3115
- registry,
3116
- autoInstall: userOptions.autoInstall ?? DEFAULT_OPTIONS.autoInstall,
3691
+ registry: registry2,
3692
+ autoInstall: userOptions.offline ? false : userOptions.autoInstall ?? DEFAULT_OPTIONS.autoInstall,
3693
+ offline: userOptions.offline ?? false,
3694
+ strict: userOptions.strict ?? false,
3117
3695
  debug: userOptions.debug ?? DEFAULT_OPTIONS.debug,
3118
3696
  aliasPrefix: userOptions.aliasPrefix ?? DEFAULT_OPTIONS.aliasPrefix,
3119
3697
  excludeRedirects: userOptions.excludeRedirects ?? {},
@@ -3125,6 +3703,8 @@ var DepsConflictResolver = class {
3125
3703
  */
3126
3704
  async initialize() {
3127
3705
  if (this.initialized) {
3706
+ if (this.preparation) await waitForProjectPreparation(this.preparation);
3707
+ this.snapshotCurrent();
3128
3708
  return;
3129
3709
  }
3130
3710
  const initialization = this.initializationPromise ??= this.initializeGeneration();
@@ -3148,6 +3728,9 @@ var DepsConflictResolver = class {
3148
3728
  if (this.initializationPromise && !this.initialized) {
3149
3729
  throw new Error("Cannot invalidate while initialization is in progress");
3150
3730
  }
3731
+ if (this.installationPromise) {
3732
+ throw new Error("Cannot invalidate while installation is in progress");
3733
+ }
3151
3734
  this.initialized = false;
3152
3735
  this.initializationPromise = null;
3153
3736
  this.rollbackGeneration();
@@ -3157,15 +3740,25 @@ var DepsConflictResolver = class {
3157
3740
  */
3158
3741
  rollbackGeneration() {
3159
3742
  this.initialized = false;
3743
+ if (this.snapshotObserver) this.preparation?.observers.delete(this.snapshotObserver);
3744
+ this.snapshotObserver = null;
3745
+ this.snapshotError = null;
3746
+ this.snapshotSignature = "";
3747
+ this.snapshotInvalidated = false;
3748
+ this.snapshotGeneration++;
3749
+ this.activeMappings = [];
3160
3750
  this.analysisResult = null;
3161
3751
  this.analyzer = null;
3162
3752
  this.aliasManager?.clear?.();
3163
3753
  this.aliasManager = null;
3164
3754
  this.installer = null;
3755
+ this.installResult = null;
3756
+ this.installDiagnostics = [];
3165
3757
  }
3166
3758
  async initializeGeneration() {
3759
+ clearPackageJsonCache();
3167
3760
  logger8.info("Initializing dependencies resolver...");
3168
- const projectRoot = this.userOptions.projectRoot ?? process.cwd();
3761
+ const projectRoot = path.resolve(this.userOptions.projectRoot ?? process.cwd());
3169
3762
  const validRoot = findProjectRoot(projectRoot);
3170
3763
  if (!validRoot) {
3171
3764
  throw new Error(`Could not find package.json in ${projectRoot} or parent directories`);
@@ -3173,25 +3766,58 @@ var DepsConflictResolver = class {
3173
3766
  if (validRoot !== projectRoot) {
3174
3767
  logger8.debug(`Adjusted project root to: ${validRoot}`);
3175
3768
  }
3176
- this.options = await this.resolveOptions(this.userOptions, validRoot);
3769
+ let physicalRoot = validRoot;
3770
+ try {
3771
+ physicalRoot = fs.realpathSync(validRoot);
3772
+ } catch {
3773
+ }
3774
+ this.options = await this.resolveOptions(this.userOptions, physicalRoot);
3177
3775
  if (this.options.debug) {
3178
- logger8.setLevel(1 /* DEBUG */);
3776
+ logger8.setLevel(15 /* ALL */);
3179
3777
  }
3180
3778
  this.aliasManager = createAliasManager(this.options);
3181
3779
  this.installer = createPackageInstaller(this.options);
3182
- this.analyzer = createDependencyAnalyzer(this.options);
3183
- this.analysisResult = await this.analyzer.analyze();
3184
- this.logMissingFirstLevelPeers(this.analysisResult);
3780
+ this.preparation = getProjectPreparation(this.options.projectRoot);
3185
3781
  if (this.hooks.onAnalysisComplete) {
3782
+ this.analysisResult = await withProjectPreparation(
3783
+ this.preparation,
3784
+ () => this.analyzeCurrent()
3785
+ );
3186
3786
  await this.hooks.onAnalysisComplete(this.analysisResult);
3187
3787
  }
3188
- if (this.options.autoInstall) {
3189
- await this.installDependencies();
3190
- } else {
3191
- this.setActiveAliasMappings(
3192
- this.analysisResult.aliasMappings.filter((mapping) => mapping.installSpec === "")
3788
+ await withProjectPreparation(
3789
+ this.preparation,
3790
+ async (markChanged) => {
3791
+ this.analysisResult = await this.analyzeCurrent();
3792
+ this.logMissingFirstLevelPeers(this.analysisResult);
3793
+ this.assertResolved();
3794
+ if (this.options.autoInstall) {
3795
+ const installing = this.installGeneration(markChanged);
3796
+ this.installationPromise = installing;
3797
+ try {
3798
+ await installing;
3799
+ } finally {
3800
+ this.installationPromise = null;
3801
+ }
3802
+ } else {
3803
+ this.publishWithoutInstallation();
3804
+ }
3805
+ this.observeSnapshot();
3806
+ },
3807
+ this.observer
3808
+ );
3809
+ await waitForProjectPreparation(this.preparation);
3810
+ await this.notifyInstallComplete();
3811
+ this.assertResolved();
3812
+ const unresolved = this.getDiagnostics().filter(
3813
+ (diagnostic) => diagnostic.severity === "error"
3814
+ );
3815
+ if (unresolved.length > 0) {
3816
+ logger8.warn(
3817
+ "Resolver has " + unresolved.length + " unresolved conditions: " + [...new Set(unresolved.map((diagnostic) => diagnostic.code))].join(", ") + ". Inspect getDiagnostics() or run doctor for details."
3193
3818
  );
3194
3819
  }
3820
+ this.logSharedPeerWarnings();
3195
3821
  this.analyzer = null;
3196
3822
  this.initialized = true;
3197
3823
  logger8.info("Dependencies resolver initialized");
@@ -3223,27 +3849,228 @@ var DepsConflictResolver = class {
3223
3849
  *
3224
3850
  * 这样可以避免"什么依赖都自动安装"的问题,用户可以根据警告自行决定是否安装缺失的依赖
3225
3851
  */
3226
- async installDependencies() {
3227
- if (!this.analysisResult || !this.installer) {
3852
+ installDependencies() {
3853
+ return this.installationPromise ??= this.prepareInstallation().finally(() => {
3854
+ this.installationPromise = null;
3855
+ });
3856
+ }
3857
+ async prepareInstallation() {
3858
+ if (!this.analysisResult || !this.installer || !this.preparation) {
3228
3859
  throw new Error("Resolver not initialized. Call initialize() first.");
3229
3860
  }
3230
- const { aliasMappings } = this.analysisResult;
3231
- let aliasResult;
3861
+ this.preparing = true;
3862
+ try {
3863
+ await withProjectPreparation(
3864
+ this.preparation,
3865
+ async (markChanged) => {
3866
+ this.analysisResult = await this.analyzeCurrent();
3867
+ this.installDiagnostics = [];
3868
+ this.assertResolved();
3869
+ if (!this.options.offline) await this.installGeneration(markChanged);
3870
+ else this.publishWithoutInstallation();
3871
+ this.observeSnapshot();
3872
+ },
3873
+ this.observer
3874
+ );
3875
+ } finally {
3876
+ this.preparing = false;
3877
+ }
3878
+ await waitForProjectPreparation(this.preparation);
3879
+ await this.notifyInstallComplete();
3880
+ this.assertResolved();
3881
+ if (this.initialized) this.logSharedPeerWarnings();
3882
+ }
3883
+ async analyzeCurrent(offline = this.options.offline, preparedAliases = []) {
3884
+ clearPackageJsonCache();
3885
+ this.analyzer = createDependencyAnalyzer({ ...this.options, offline }, preparedAliases);
3232
3886
  try {
3233
- aliasResult = await this.installer.installAliases(aliasMappings);
3887
+ return await this.analyzer.analyze();
3888
+ } finally {
3889
+ this.analyzer = null;
3890
+ }
3891
+ }
3892
+ publishWithoutInstallation() {
3893
+ const mappings = this.analysisResult.aliasMappings;
3894
+ this.setActiveAliasMappings(mappings.filter((mapping) => mapping.installSpec === ""));
3895
+ for (const mapping of mappings) {
3896
+ if (mapping.installSpec)
3897
+ this.installDiagnostics.push({
3898
+ code: "ALIAS_NOT_INSTALLED",
3899
+ severity: "error",
3900
+ packageName: mapping.originalName,
3901
+ aliases: [mapping.aliasName],
3902
+ message: "Alias is not active because installation is disabled: " + mapping.aliasName
3903
+ });
3904
+ }
3905
+ }
3906
+ async installGeneration(markChanged) {
3907
+ const report = {
3908
+ success: true,
3909
+ installed: [],
3910
+ reused: [],
3911
+ failed: [],
3912
+ errors: []
3913
+ };
3914
+ this.installResult = report;
3915
+ this.installDiagnostics = [];
3916
+ const blocked = /* @__PURE__ */ new Set();
3917
+ for (let attempt = 0; attempt < 2; attempt++) {
3918
+ const planned = this.analysisResult.aliasMappings;
3919
+ if (planned.some((mapping) => mapping.installSpec)) markChanged();
3920
+ let result;
3921
+ try {
3922
+ result = await this.installer.installAliases(planned);
3923
+ } catch (error) {
3924
+ this.setActiveAliasMappings([]);
3925
+ throw error;
3926
+ }
3927
+ report.success &&= result.success;
3928
+ for (const key of ["installed", "reused", "failed", "errors"]) {
3929
+ report[key] = [.../* @__PURE__ */ new Set([...report[key], ...result[key] ?? []])];
3930
+ }
3931
+ for (const aliasName of result.failed ?? []) {
3932
+ blocked.add(aliasName);
3933
+ this.installDiagnostics.push({
3934
+ code: "ALIAS_INSTALL_FAILED",
3935
+ severity: "error",
3936
+ packageName: planned.find((mapping) => mapping.aliasName === aliasName)?.originalName ?? aliasName,
3937
+ aliases: [aliasName],
3938
+ message: "Alias installation failed: " + aliasName + ". " + result.errors.join("; ")
3939
+ });
3940
+ }
3941
+ const changed = (result.installed?.length ?? 0) > 0 || (result.failed?.length ?? 0) > 0;
3942
+ if (!changed) {
3943
+ this.setActiveAliasMappings(this.filterCompletedMappings(planned, result, false), blocked);
3944
+ return;
3945
+ }
3946
+ this.analysisResult = await this.analyzeCurrent(
3947
+ result.success ? this.options.offline : true,
3948
+ this.filterCompletedMappings(planned, result, false)
3949
+ );
3950
+ const fresh = this.analysisResult.aliasMappings;
3951
+ const pending = fresh.filter(
3952
+ (mapping) => mapping.installSpec && !blocked.has(mapping.aliasName)
3953
+ );
3954
+ if (result.success && pending.length > 0 && attempt === 0) continue;
3955
+ if (result.success && pending.length > 0) {
3956
+ report.success = false;
3957
+ const message = "Dependency inputs changed during preparation; refusing to publish an unstable installation plan";
3958
+ report.errors.push(message);
3959
+ this.installDiagnostics.push({
3960
+ code: "PROJECT_STATE_CHANGED",
3961
+ severity: "error",
3962
+ packageName: this.options.dependencies.join(", "),
3963
+ message
3964
+ });
3965
+ }
3966
+ for (const mapping of planned) {
3967
+ if (blocked.has(mapping.aliasName) && !fresh.some((entry) => entry.aliasName === mapping.aliasName))
3968
+ fresh.push(mapping);
3969
+ }
3970
+ this.setActiveAliasMappings(
3971
+ fresh.filter((mapping) => !mapping.installSpec && !blocked.has(mapping.aliasName)),
3972
+ blocked
3973
+ );
3974
+ if (!report.success || pending.length === 0) return;
3975
+ }
3976
+ }
3977
+ observeSnapshot() {
3978
+ this.snapshotInvalidated = false;
3979
+ if (!this.snapshotObserver) {
3980
+ this.snapshotObserver = new WeakRef(this.observer);
3981
+ this.preparation.observers.add(this.snapshotObserver);
3982
+ }
3983
+ this.captureSnapshot();
3984
+ }
3985
+ async refreshSnapshot() {
3986
+ if (!this.analysisResult || !this.aliasManager) return;
3987
+ if (this.snapshotInvalidated) {
3988
+ this.snapshotRevision = this.preparation.revision;
3989
+ return;
3990
+ }
3991
+ const generation = this.snapshotGeneration;
3992
+ const previous = this.snapshotSignature;
3993
+ try {
3994
+ const analysis = await this.analyzeCurrent(true, this.activeMappings);
3995
+ if (generation !== this.snapshotGeneration) return;
3996
+ this.analysisResult = analysis;
3997
+ this.setActiveAliasMappings(analysis.aliasMappings.filter((mapping) => !mapping.installSpec));
3998
+ const changed = previous !== this.describeSnapshot();
3999
+ if (this.initialized && changed) {
4000
+ this.snapshotInvalidated = true;
4001
+ this.setActiveAliasMappings([]);
4002
+ this.installDiagnostics.push({
4003
+ code: "PROJECT_STATE_CHANGED",
4004
+ severity: "error",
4005
+ packageName: this.options.dependencies.join(", "),
4006
+ message: "Another preparation changed active dependency rules. Call invalidate() and initialize() before building again."
4007
+ });
4008
+ }
3234
4009
  } catch (error) {
4010
+ if (generation !== this.snapshotGeneration) return;
4011
+ this.snapshotInvalidated = true;
3235
4012
  this.setActiveAliasMappings([]);
3236
- throw error;
4013
+ this.installDiagnostics.push({
4014
+ code: "PROJECT_STATE_CHANGED",
4015
+ severity: "error",
4016
+ packageName: this.options.dependencies.join(", "),
4017
+ message: "Cannot refresh dependency rules after another installation: " + String(error)
4018
+ });
3237
4019
  }
3238
- const completedMappings = this.filterCompletedMappings(aliasMappings, aliasResult, false);
3239
- this.setActiveAliasMappings(completedMappings, aliasResult.failed ?? []);
3240
- if (!aliasResult.success) {
3241
- logger8.warn(`Some alias installations failed: ${aliasResult.errors.join(", ")}`);
4020
+ this.captureSnapshot();
4021
+ }
4022
+ describeSnapshot() {
4023
+ const mappings = this.activeMappings.map((mapping) => [
4024
+ mapping.originalName,
4025
+ mapping.aliasName,
4026
+ mapping.resolvedVersion,
4027
+ [...mapping.usedBy].sort(),
4028
+ [...mapping.allDependents].sort(),
4029
+ mapping.importerPaths ? [...mapping.importerPaths].sort() : null
4030
+ ]).sort((a, b) => String(a[1]).localeCompare(String(b[1])));
4031
+ const providers = (this.aliasManager?.getAliasPathMappings() ?? []).map((mapping) => {
4032
+ let path = mapping.path;
4033
+ try {
4034
+ path = fs.realpathSync(path);
4035
+ } catch {
4036
+ }
4037
+ return [mapping.aliasName, path, readPackageJsonCached(path)];
4038
+ }).sort((a, b) => String(a[0]).localeCompare(String(b[0])));
4039
+ return JSON.stringify([mappings, providers]);
4040
+ }
4041
+ captureSnapshot() {
4042
+ this.snapshotRevision = this.preparation.revision;
4043
+ this.snapshotSignature = this.describeSnapshot();
4044
+ const errors = this.generationDiagnostics().filter(
4045
+ (diagnostic) => diagnostic.severity === "error"
4046
+ );
4047
+ this.snapshotError = errors.length ? new ResolutionError(errors) : null;
4048
+ }
4049
+ async notifyInstallComplete() {
4050
+ if (!this.installResult || !this.hooks.onInstallComplete) return;
4051
+ await this.hooks.onInstallComplete(
4052
+ this.filterCompletedMappings(this.analysisResult.aliasMappings, this.installResult, true)
4053
+ );
4054
+ }
4055
+ snapshotCurrent() {
4056
+ if (!this.preparation) return true;
4057
+ if (this.preparation.writing || this.preparing || this.snapshotRevision !== this.preparation.revision) {
4058
+ const diagnostic = {
4059
+ code: "PROJECT_STATE_CHANGED",
4060
+ severity: "error",
4061
+ packageName: this.options.dependencies.join(", "),
4062
+ message: "Dependency preparation is changing this project; wait for preparation to finish before resolving modules"
4063
+ };
4064
+ if (this.options.strict) throw new ResolutionError([diagnostic]);
4065
+ return false;
3242
4066
  }
3243
- if (this.hooks.onInstallComplete) {
3244
- await this.hooks.onInstallComplete(
3245
- this.filterCompletedMappings(aliasMappings, aliasResult, true)
3246
- );
4067
+ if (this.options.strict && this.snapshotError) throw this.snapshotError;
4068
+ return true;
4069
+ }
4070
+ logSharedPeerWarnings() {
4071
+ for (const diagnostic of this.getDiagnostics()) {
4072
+ if (diagnostic.code === "SHARED_PEER_CONTEXT")
4073
+ logger8.warn(`[${diagnostic.code}] ${diagnostic.message}`);
3247
4074
  }
3248
4075
  }
3249
4076
  /**
@@ -3287,15 +4114,24 @@ var DepsConflictResolver = class {
3287
4114
  if (!mapping.importerPaths || inactiveAliasNames.size === 0) {
3288
4115
  return mapping;
3289
4116
  }
4117
+ const blockedPaths = new Set(
4118
+ Object.entries(mapping.peerImporterPaths ?? {}).filter(([aliasName]) => inactiveAliasNames.has(aliasName)).flatMap(([, paths]) => paths)
4119
+ );
3290
4120
  return {
3291
4121
  ...mapping,
4122
+ peerImporterPaths: Object.fromEntries(
4123
+ Object.entries(mapping.peerImporterPaths ?? {}).filter(
4124
+ ([aliasName]) => !inactiveAliasNames.has(aliasName)
4125
+ )
4126
+ ),
3292
4127
  importerPaths: mapping.importerPaths.filter(
3293
- (importerPath) => ![...inactiveAliasNames].some(
4128
+ (importerPath) => !blockedPaths.has(importerPath) && ![...inactiveAliasNames].some(
3294
4129
  (aliasName) => this.isAliasPackagePath(importerPath, aliasName)
3295
4130
  )
3296
4131
  )
3297
4132
  };
3298
4133
  });
4134
+ this.activeMappings = activeMappings;
3299
4135
  this.aliasManager.initFromAnalysisResult({
3300
4136
  ...this.analysisResult,
3301
4137
  aliasMappings: activeMappings
@@ -3319,6 +4155,7 @@ var DepsConflictResolver = class {
3319
4155
  if (!this.initialized || !this.aliasManager) {
3320
4156
  return null;
3321
4157
  }
4158
+ if (!this.snapshotCurrent()) return null;
3322
4159
  if (this.hooks.beforeResolve) {
3323
4160
  const hookResult = this.hooks.beforeResolve(request, importer);
3324
4161
  if (hookResult !== void 0) {
@@ -3335,6 +4172,7 @@ var DepsConflictResolver = class {
3335
4172
  if (!this.initialized || !this.aliasManager) {
3336
4173
  return [];
3337
4174
  }
4175
+ if (!this.snapshotCurrent()) return [];
3338
4176
  return this.aliasManager.getAliasPathMappings();
3339
4177
  }
3340
4178
  /**
@@ -3343,6 +4181,79 @@ var DepsConflictResolver = class {
3343
4181
  getAnalysisResult() {
3344
4182
  return this.analysisResult;
3345
4183
  }
4184
+ generationDiagnostics() {
4185
+ return [
4186
+ ...this.analysisResult?.diagnostics ?? [],
4187
+ ...this.installDiagnostics,
4188
+ ...this.aliasManager?.getDiagnostics?.() ?? []
4189
+ ];
4190
+ }
4191
+ /** Inspect unresolved conditions without parsing logs. */
4192
+ getDiagnostics() {
4193
+ return [
4194
+ ...this.initialized && this.preparation && (this.preparation.writing || this.preparing) ? [
4195
+ {
4196
+ code: "PROJECT_STATE_CHANGED",
4197
+ severity: "error",
4198
+ packageName: this.options.dependencies.join(", "),
4199
+ message: "Dependency preparation is in progress; wait before resolving modules"
4200
+ }
4201
+ ] : [],
4202
+ ...this.generationDiagnostics()
4203
+ ].map(
4204
+ (diagnostic) => Object.assign({}, diagnostic, {
4205
+ ...diagnostic.aliases && { aliases: [...diagnostic.aliases] },
4206
+ ...diagnostic.requestedBy && { requestedBy: [...diagnostic.requestedBy] },
4207
+ ...diagnostic.importerPaths && { importerPaths: [...diagnostic.importerPaths] }
4208
+ })
4209
+ );
4210
+ }
4211
+ assertResolved() {
4212
+ if (this.options.strict) {
4213
+ const errors = this.generationDiagnostics().filter(
4214
+ (diagnostic) => diagnostic.severity === "error"
4215
+ );
4216
+ if (errors.length > 0) throw new ResolutionError(errors);
4217
+ }
4218
+ }
4219
+ /** Explain a request; skipHook permits side-effect-free cache validation. */
4220
+ explainResolution(request, importer, options = {}) {
4221
+ if (!this.initialized || !this.aliasManager) {
4222
+ return {
4223
+ request,
4224
+ importer,
4225
+ resolved: null,
4226
+ reason: "inactive",
4227
+ aliases: [],
4228
+ matchedPaths: []
4229
+ };
4230
+ }
4231
+ if (!this.snapshotCurrent())
4232
+ return {
4233
+ request,
4234
+ importer,
4235
+ resolved: null,
4236
+ reason: "inactive",
4237
+ aliases: [],
4238
+ matchedPaths: []
4239
+ };
4240
+ if (!options.skipHook && this.hooks.beforeResolve) {
4241
+ const resolved = this.hooks.beforeResolve(request, importer);
4242
+ if (resolved !== void 0) {
4243
+ return { request, importer, resolved, reason: "hook", aliases: [], matchedPaths: [] };
4244
+ }
4245
+ }
4246
+ return this.aliasManager.explainResolution(request, importer);
4247
+ }
4248
+ getInstallResult() {
4249
+ return this.installResult && {
4250
+ ...this.installResult,
4251
+ installed: [...this.installResult.installed],
4252
+ reused: [...this.installResult.reused],
4253
+ failed: [...this.installResult.failed],
4254
+ errors: [...this.installResult.errors]
4255
+ };
4256
+ }
3346
4257
  /**
3347
4258
  * 获取配置
3348
4259
  */
@@ -3357,6 +4268,7 @@ async function createResolver(options, hooks) {
3357
4268
  }
3358
4269
 
3359
4270
  exports.DepsConflictResolver = DepsConflictResolver;
4271
+ exports.ResolutionError = ResolutionError;
3360
4272
  exports.WorkspaceDetector = WorkspaceDetector;
3361
4273
  exports.createResolver = createResolver;
3362
4274
  exports.createWorkspaceDetector = createWorkspaceDetector;