deps-conflict-resolver 1.2.0 → 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/cli.js ADDED
@@ -0,0 +1,4407 @@
1
+ #!/usr/bin/env node
2
+ import { resolve, join, dirname, basename, posix, relative, win32 } from 'path';
3
+ import { realpathSync, existsSync, readFileSync, promises, statSync } from 'fs';
4
+ import { createRequire } from 'module';
5
+ import { pathToFileURL } from 'url';
6
+ import { parse } from 'yaml';
7
+ import semver from 'semver';
8
+ import { spawn } from 'child_process';
9
+ import { createHash, randomUUID } from 'crypto';
10
+ import { userInfo, tmpdir, hostname } from 'os';
11
+ import { performance } from 'perf_hooks';
12
+
13
+ // src/constants.ts
14
+ var DEFAULT_NPM_REGISTRY = "https://registry.npmjs.org";
15
+ var LOCK_FILE_MAP = {
16
+ "pnpm-lock.yaml": "pnpm",
17
+ "yarn.lock": "yarn",
18
+ "package-lock.json": "npm",
19
+ "npm-shrinkwrap.json": "npm"
20
+ };
21
+ var DEFAULT_NPM_REGISTRY_TIMEOUT_MS = 1e4;
22
+
23
+ // src/utils/logger.ts
24
+ var DEFAULT_GLOBAL_LEVEL = 2 /* INFO */ | 4 /* WARN */ | 8 /* ERROR */;
25
+ var __GLOBAL_LEVEL__ = DEFAULT_GLOBAL_LEVEL;
26
+ var Logger = class {
27
+ prefix;
28
+ levelOverride;
29
+ constructor(config = {}) {
30
+ this.prefix = config.prefix ?? "[deps-conflict-resolver]";
31
+ this.levelOverride = config.level;
32
+ }
33
+ /**
34
+ * 设置日志级别
35
+ */
36
+ setLevel(level) {
37
+ __GLOBAL_LEVEL__ = level;
38
+ this.levelOverride = void 0;
39
+ }
40
+ getEffectiveLevel() {
41
+ return this.levelOverride ?? __GLOBAL_LEVEL__;
42
+ }
43
+ /**
44
+ * 调试日志
45
+ */
46
+ debug(...args) {
47
+ if (this.getEffectiveLevel() & 1 /* DEBUG */) {
48
+ console.debug(this.formatPrefix("DEBUG"), ...args);
49
+ }
50
+ }
51
+ /**
52
+ * 信息日志
53
+ */
54
+ info(...args) {
55
+ if (this.getEffectiveLevel() & 2 /* INFO */) {
56
+ console.info(this.formatPrefix("INFO"), ...args);
57
+ }
58
+ }
59
+ /**
60
+ * 警告日志
61
+ */
62
+ warn(...args) {
63
+ if (this.getEffectiveLevel() & 4 /* WARN */) {
64
+ console.warn(this.formatPrefix("WARN"), ...args);
65
+ }
66
+ }
67
+ /**
68
+ * 错误日志
69
+ */
70
+ error(...args) {
71
+ if (this.getEffectiveLevel() & 8 /* ERROR */) {
72
+ console.error(this.formatPrefix("ERROR"), ...args);
73
+ }
74
+ }
75
+ /**
76
+ * 格式化前缀
77
+ */
78
+ formatPrefix(level) {
79
+ return `${this.prefix} [${level}]`;
80
+ }
81
+ };
82
+ function createLogger(subPrefix, debug = false) {
83
+ return new Logger({
84
+ prefix: `[deps-conflict-resolver:${subPrefix}]`,
85
+ // debug=true 时强制当前 logger 输出所有日志;否则使用全局级别(默认 INFO/WARN/ERROR)
86
+ level: debug ? 15 /* ALL */ : void 0
87
+ });
88
+ }
89
+
90
+ // src/utils/lru-cache.ts
91
+ var LruCache = class {
92
+ map = /* @__PURE__ */ new Map();
93
+ maxEntries;
94
+ constructor(options) {
95
+ this.maxEntries = options.maxEntries;
96
+ }
97
+ /**
98
+ * 当前缓存条目数
99
+ */
100
+ get size() {
101
+ return this.map.size;
102
+ }
103
+ /**
104
+ * 获取最大条目数
105
+ */
106
+ getMaxEntries() {
107
+ return this.maxEntries;
108
+ }
109
+ /**
110
+ * 动态调整最大条目数
111
+ * - 调小会立即触发淘汰
112
+ */
113
+ setMaxEntries(maxEntries) {
114
+ this.maxEntries = maxEntries;
115
+ if (this.maxEntries <= 0) {
116
+ this.map.clear();
117
+ return;
118
+ }
119
+ this.trim();
120
+ }
121
+ clear() {
122
+ this.map.clear();
123
+ }
124
+ has(key) {
125
+ return this.map.has(key);
126
+ }
127
+ /**
128
+ * 获取并刷新 LRU 顺序(命中后会变成“最近使用”)
129
+ */
130
+ get(key) {
131
+ if (this.maxEntries <= 0) {
132
+ return void 0;
133
+ }
134
+ if (!this.map.has(key)) {
135
+ return void 0;
136
+ }
137
+ const value = this.map.get(key);
138
+ this.map.delete(key);
139
+ this.map.set(key, value);
140
+ return value;
141
+ }
142
+ /**
143
+ * 写入并刷新 LRU 顺序
144
+ */
145
+ set(key, value) {
146
+ if (this.maxEntries <= 0) {
147
+ return;
148
+ }
149
+ if (this.map.has(key)) {
150
+ this.map.delete(key);
151
+ }
152
+ this.map.set(key, value);
153
+ this.trim();
154
+ }
155
+ delete(key) {
156
+ return this.map.delete(key);
157
+ }
158
+ trim() {
159
+ if (this.maxEntries <= 0) return;
160
+ while (this.map.size > this.maxEntries) {
161
+ const iter = this.map.keys().next();
162
+ if (iter.done) break;
163
+ this.map.delete(iter.value);
164
+ }
165
+ }
166
+ };
167
+
168
+ // src/utils/fs.ts
169
+ function* iterateParentDirs(startDir) {
170
+ let currentDir = startDir;
171
+ while (true) {
172
+ yield currentDir;
173
+ const parentDir = dirname(currentDir);
174
+ if (parentDir === currentDir) {
175
+ break;
176
+ }
177
+ currentDir = parentDir;
178
+ }
179
+ }
180
+ var DEFAULT_PACKAGE_JSON_CACHE_MAX_ENTRIES = 5e3;
181
+ var packageJsonCache = new LruCache({
182
+ maxEntries: DEFAULT_PACKAGE_JSON_CACHE_MAX_ENTRIES
183
+ });
184
+ var DEFAULT_REQUIRE_CACHE_MAX_ENTRIES = 200;
185
+ var requireCache = new LruCache({
186
+ maxEntries: DEFAULT_REQUIRE_CACHE_MAX_ENTRIES
187
+ });
188
+ var DEFAULT_PACKAGE_PATH_CACHE_MAX_ENTRIES = 2e4;
189
+ var packagePathCache = new LruCache({
190
+ maxEntries: DEFAULT_PACKAGE_PATH_CACHE_MAX_ENTRIES
191
+ });
192
+ function clearPackageJsonCache() {
193
+ packageJsonCache.clear();
194
+ packagePathCache.clear();
195
+ requireCache.clear();
196
+ }
197
+ function readJsonFileSync(filePath) {
198
+ try {
199
+ const content = readFileSync(filePath, "utf-8");
200
+ return JSON.parse(content);
201
+ } catch {
202
+ return null;
203
+ }
204
+ }
205
+ function fileExists(filePath) {
206
+ return existsSync(filePath);
207
+ }
208
+ function readPackageJsonCached(dir) {
209
+ const pkgPath = join(dir, "package.json");
210
+ const cached = packageJsonCache.get(pkgPath);
211
+ if (cached !== void 0) {
212
+ return cached;
213
+ }
214
+ const result = readJsonFileSync(pkgPath);
215
+ packageJsonCache.set(pkgPath, result);
216
+ return result;
217
+ }
218
+ function findProjectRoot(startDir) {
219
+ for (const dir of iterateParentDirs(startDir)) {
220
+ if (fileExists(join(dir, "package.json"))) {
221
+ return dir;
222
+ }
223
+ }
224
+ return null;
225
+ }
226
+ function findPackagePath(packageName, baseDir) {
227
+ const cacheKey = `${baseDir}\0${packageName}`;
228
+ const cached = packagePathCache.get(cacheKey);
229
+ if (cached !== void 0) {
230
+ return cached;
231
+ }
232
+ try {
233
+ let localRequire = requireCache.get(baseDir);
234
+ if (!localRequire) {
235
+ const baseUrl = pathToFileURL(join(baseDir, "package.json")).href;
236
+ localRequire = createRequire(baseUrl);
237
+ requireCache.set(baseDir, localRequire);
238
+ }
239
+ const metadataRequest = `${packageName}/package.json`;
240
+ const lookupPaths = localRequire.resolve.paths?.(metadataRequest);
241
+ if (lookupPaths) {
242
+ let visible = findSelfPackagePath(packageName, baseDir);
243
+ if (!visible) {
244
+ for (const directory of lookupPaths) {
245
+ const candidate = join(directory, packageName);
246
+ if (fileExists(candidate)) {
247
+ visible = candidate;
248
+ break;
249
+ }
250
+ }
251
+ }
252
+ let resolved2 = visible;
253
+ if (visible) {
254
+ try {
255
+ resolved2 = realpathSync(visible);
256
+ } catch {
257
+ resolved2 = resolve(visible);
258
+ }
259
+ }
260
+ packagePathCache.set(cacheKey, resolved2);
261
+ return resolved2;
262
+ }
263
+ const pkgJsonPath = localRequire.resolve(metadataRequest);
264
+ const resolved = dirname(pkgJsonPath);
265
+ packagePathCache.set(cacheKey, resolved);
266
+ return resolved;
267
+ } catch {
268
+ const resolved = findPackagePathFallback(packageName, baseDir);
269
+ packagePathCache.set(cacheKey, resolved);
270
+ return resolved;
271
+ }
272
+ }
273
+ function findSelfPackagePath(packageName, baseDir) {
274
+ for (const directory of iterateParentDirs(resolve(baseDir))) {
275
+ if (basename(directory) === "node_modules") break;
276
+ const manifest = readPackageJsonCached(directory);
277
+ if (!manifest) continue;
278
+ return manifest.name === packageName && "exports" in manifest && manifest.exports != null ? directory : null;
279
+ }
280
+ return null;
281
+ }
282
+ function findPackagePathFallback(packageName, baseDir) {
283
+ for (const dir of iterateParentDirs(baseDir)) {
284
+ const candidatePath = join(dir, "node_modules", packageName);
285
+ if (fileExists(candidatePath)) {
286
+ return candidatePath;
287
+ }
288
+ }
289
+ return null;
290
+ }
291
+ var logger = createLogger("environment-detector");
292
+ var EnvironmentDetector = class {
293
+ projectRoot;
294
+ detectionResult = null;
295
+ registryCache = null;
296
+ constructor(projectRoot) {
297
+ this.projectRoot = projectRoot;
298
+ }
299
+ /**
300
+ * 获取检测到的包管理器类型
301
+ */
302
+ getPackageManager() {
303
+ const result = this.detect();
304
+ return result.packageManager;
305
+ }
306
+ /**
307
+ * 获取检测到的 registry
308
+ */
309
+ async getRegistry() {
310
+ if (this.registryCache) {
311
+ return this.registryCache;
312
+ }
313
+ const result = this.detect();
314
+ this.registryCache = await this.detectRegistry(result.packageManager);
315
+ return this.registryCache;
316
+ }
317
+ /**
318
+ * 获取指定包管理器的 registry(兼容旧 API)
319
+ */
320
+ async getRegistryForPackageManager(packageManager) {
321
+ return this.detectRegistry(packageManager);
322
+ }
323
+ /**
324
+ * 获取完整的检测结果
325
+ */
326
+ getDetectionResult() {
327
+ return this.detect();
328
+ }
329
+ /**
330
+ * 重置缓存,强制重新检测
331
+ */
332
+ reset() {
333
+ this.detectionResult = null;
334
+ this.registryCache = null;
335
+ }
336
+ /**
337
+ * 更新项目根目录
338
+ */
339
+ setProjectRoot(projectRoot) {
340
+ this.projectRoot = projectRoot;
341
+ this.reset();
342
+ }
343
+ /**
344
+ * 检测项目使用的包管理器
345
+ *
346
+ * 检测优先级:
347
+ * 1. package.json 中的 packageManager 字段(如 "pnpm@8.0.0")- 向上遍历查找
348
+ * 2. lock 文件存在 - 向上遍历查找(支持 monorepo)
349
+ * 3. 默认为 npm
350
+ */
351
+ detect() {
352
+ if (this.detectionResult) {
353
+ return this.detectionResult;
354
+ }
355
+ for (const currentDir of iterateParentDirs(this.projectRoot)) {
356
+ const pkgJsonPath = join(currentDir, "package.json");
357
+ if (fileExists(pkgJsonPath)) {
358
+ const pkgJson = readPackageJsonCached(currentDir);
359
+ const pmField = pkgJson?.packageManager;
360
+ if (pmField) {
361
+ const pm = this.parsePackageManagerField(pmField);
362
+ if (pm) {
363
+ logger.debug(`Detected package manager from package.json: ${pm} (at ${currentDir})`);
364
+ this.detectionResult = {
365
+ packageManager: pm,
366
+ detectedFrom: "packageJson",
367
+ rootDir: currentDir
368
+ };
369
+ return this.detectionResult;
370
+ }
371
+ }
372
+ }
373
+ for (const [lockFile, pm] of Object.entries(LOCK_FILE_MAP)) {
374
+ if (fileExists(join(currentDir, lockFile))) {
375
+ logger.debug(
376
+ `Detected package manager from lock file: ${pm} (${lockFile} at ${currentDir})`
377
+ );
378
+ this.detectionResult = {
379
+ packageManager: pm,
380
+ detectedFrom: "lockfile",
381
+ rootDir: currentDir
382
+ };
383
+ return this.detectionResult;
384
+ }
385
+ }
386
+ }
387
+ logger.debug("No lock file found, defaulting to npm");
388
+ this.detectionResult = {
389
+ packageManager: "npm",
390
+ detectedFrom: "default"
391
+ };
392
+ return this.detectionResult;
393
+ }
394
+ /**
395
+ * 解析 package.json 中的 packageManager 字段
396
+ * 格式如:pnpm@8.0.0, yarn@3.2.0, npm@9.0.0
397
+ */
398
+ parsePackageManagerField(value) {
399
+ const match = value.match(/^(npm|yarn|pnpm)(@|$)/);
400
+ if (match) {
401
+ return match[1];
402
+ }
403
+ return null;
404
+ }
405
+ /**
406
+ * 检测项目使用的 registry
407
+ *
408
+ * 检测优先级:
409
+ * 1. 项目级 .npmrc(向上遍历,覆盖 monorepo 子包场景)
410
+ * 2. 用户级 .npmrc
411
+ * 3. 包管理器特定配置
412
+ * 4. 默认 registry
413
+ */
414
+ async detectRegistry(packageManager) {
415
+ const defaultRegistry = DEFAULT_NPM_REGISTRY;
416
+ for (const dir of iterateParentDirs(this.projectRoot)) {
417
+ const npmrcPath = join(dir, ".npmrc");
418
+ if (fileExists(npmrcPath)) {
419
+ const registry2 = await this.parseRegistryFromNpmrc(npmrcPath);
420
+ if (registry2) {
421
+ logger.debug(`Detected registry from .npmrc: ${registry2} (at ${dir})`);
422
+ return registry2;
423
+ }
424
+ }
425
+ }
426
+ const homeDir = process.env.HOME ?? process.env.USERPROFILE ?? "";
427
+ if (homeDir) {
428
+ const userNpmrc = join(homeDir, ".npmrc");
429
+ if (fileExists(userNpmrc)) {
430
+ const registry2 = await this.parseRegistryFromNpmrc(userNpmrc);
431
+ if (registry2) {
432
+ logger.debug(`Detected registry from user .npmrc: ${registry2}`);
433
+ return registry2;
434
+ }
435
+ }
436
+ if (packageManager === "pnpm") {
437
+ const pnpmConfig = join(homeDir, ".pnpmrc");
438
+ if (fileExists(pnpmConfig)) {
439
+ const registry2 = await this.parseRegistryFromNpmrc(pnpmConfig);
440
+ if (registry2) {
441
+ logger.debug(`Detected registry from .pnpmrc: ${registry2}`);
442
+ return registry2;
443
+ }
444
+ }
445
+ }
446
+ if (packageManager === "yarn") {
447
+ for (const dir of iterateParentDirs(this.projectRoot)) {
448
+ const yarnrc = join(dir, ".yarnrc.yml");
449
+ if (fileExists(yarnrc)) {
450
+ const registry2 = await this.parseRegistryFromYarnrc(yarnrc);
451
+ if (registry2) {
452
+ logger.debug(`Detected registry from .yarnrc.yml: ${registry2} (at ${dir})`);
453
+ return registry2;
454
+ }
455
+ }
456
+ }
457
+ }
458
+ }
459
+ logger.debug(`Using default registry: ${defaultRegistry}`);
460
+ return defaultRegistry;
461
+ }
462
+ /**
463
+ * 从 .npmrc 文件解析 registry
464
+ */
465
+ async parseRegistryFromNpmrc(filePath) {
466
+ try {
467
+ const content = await promises.readFile(filePath, "utf-8");
468
+ const lines = content.split("\n");
469
+ for (const line of lines) {
470
+ const trimmed = line.trim();
471
+ if (!trimmed || trimmed.startsWith("#") || trimmed.startsWith(";")) {
472
+ continue;
473
+ }
474
+ const match = trimmed.match(/^registry\s*=\s*(.+)$/i);
475
+ if (match?.[1]) {
476
+ return match[1].trim().replace(/["']/g, "");
477
+ }
478
+ }
479
+ } catch {
480
+ }
481
+ return null;
482
+ }
483
+ /**
484
+ * 从 .yarnrc.yml 文件解析 registry
485
+ */
486
+ async parseRegistryFromYarnrc(filePath) {
487
+ try {
488
+ const content = await promises.readFile(filePath, "utf-8");
489
+ const lines = content.split("\n");
490
+ for (const line of lines) {
491
+ const trimmed = line.trim();
492
+ const match = trimmed.match(/^npmRegistryServer:\s*["']?(.+?)["']?\s*$/);
493
+ if (match?.[1]) {
494
+ return match[1];
495
+ }
496
+ }
497
+ } catch {
498
+ }
499
+ return null;
500
+ }
501
+ };
502
+ function createEnvironmentDetector(projectRoot) {
503
+ return new EnvironmentDetector(projectRoot);
504
+ }
505
+
506
+ // src/utils/version-spec.ts
507
+ var NPM_ALIAS_PATTERN = /^npm:(@?[^@]+)@(.+)$/;
508
+ function parseNpmAlias(versionSpec) {
509
+ const match = versionSpec.match(NPM_ALIAS_PATTERN);
510
+ if (match?.[1] && match?.[2]) {
511
+ return [match[1], match[2]];
512
+ }
513
+ return null;
514
+ }
515
+
516
+ // src/core/workspace-detector.ts
517
+ var logger2 = createLogger("workspace-detector");
518
+ var PROTOCOL_PREFIXES = {
519
+ "catalog:": "catalog",
520
+ "workspace:": "workspace",
521
+ "npm:": "npm",
522
+ "file:": "file",
523
+ "link:": "link",
524
+ "portal:": "portal"
525
+ };
526
+ function extractAliasesFromDeps(deps, targetPackage, definedIn, existingAliases) {
527
+ if (!deps) return [];
528
+ const aliases = [];
529
+ for (const [aliasName, versionSpec] of Object.entries(deps)) {
530
+ if (typeof versionSpec !== "string") continue;
531
+ if (existingAliases.has(aliasName)) continue;
532
+ const parsed = parseNpmAlias(versionSpec);
533
+ if (parsed?.[0] === targetPackage) {
534
+ aliases.push({
535
+ aliasName,
536
+ targetPackage,
537
+ versionSpec: parsed[1],
538
+ definedIn,
539
+ isWorkspaceRoot: true
540
+ });
541
+ existingAliases.add(aliasName);
542
+ logger2.debug(`Found alias: ${aliasName} -> ${targetPackage}@${parsed[1]} (in ${definedIn})`);
543
+ }
544
+ }
545
+ return aliases;
546
+ }
547
+ var WorkspaceDetector = class {
548
+ projectRoot;
549
+ detectionResult = null;
550
+ constructor(projectRoot) {
551
+ this.projectRoot = projectRoot;
552
+ }
553
+ /**
554
+ * 获取 workspace 检测结果
555
+ */
556
+ detect() {
557
+ if (this.detectionResult) {
558
+ return this.detectionResult;
559
+ }
560
+ this.detectionResult = this.detectWorkspace();
561
+ return this.detectionResult;
562
+ }
563
+ /**
564
+ * 重置缓存
565
+ */
566
+ reset() {
567
+ this.detectionResult = null;
568
+ }
569
+ /**
570
+ * 解析 catalog: 协议的版本
571
+ * @param packageName 包名
572
+ * @param versionSpec 版本规格(如 "catalog:" 或 "catalog:react17")
573
+ */
574
+ resolveCatalogVersion(packageName, versionSpec) {
575
+ const result = {
576
+ original: versionSpec,
577
+ resolved: null,
578
+ catalogName: "default",
579
+ success: false
580
+ };
581
+ if (versionSpec === "catalog:" || versionSpec === "catalog:default") {
582
+ result.catalogName = "default";
583
+ } else if (versionSpec.startsWith("catalog:")) {
584
+ result.catalogName = versionSpec.slice("catalog:".length);
585
+ } else {
586
+ return result;
587
+ }
588
+ const workspace = this.detect();
589
+ if (!workspace.isMonorepo || !workspace.workspaceRoot) {
590
+ logger2.warn(`Cannot resolve catalog: protocol - not in a monorepo`);
591
+ return result;
592
+ }
593
+ if (result.catalogName === "default") {
594
+ const version = workspace.catalog?.[packageName];
595
+ if (version) {
596
+ result.resolved = version;
597
+ result.success = true;
598
+ logger2.debug(`Resolved ${packageName} from default catalog: ${version}`);
599
+ }
600
+ } else {
601
+ const namedCatalog = workspace.catalogs?.[result.catalogName];
602
+ if (namedCatalog) {
603
+ const version = namedCatalog[packageName];
604
+ if (version) {
605
+ result.resolved = version;
606
+ result.success = true;
607
+ logger2.debug(`Resolved ${packageName} from catalog:${result.catalogName}: ${version}`);
608
+ }
609
+ }
610
+ }
611
+ if (!result.success) {
612
+ logger2.warn(`Package "${packageName}" not found in catalog:${result.catalogName}`);
613
+ }
614
+ return result;
615
+ }
616
+ /**
617
+ * 解析版本规格(支持各种特殊协议)
618
+ * @param packageName 包名
619
+ * @param versionSpec 版本规格
620
+ * @returns 解析后的普通版本范围,或 null(如无法解析)
621
+ */
622
+ resolveVersionSpec(packageName, versionSpec) {
623
+ const protocol = this.getVersionProtocol(versionSpec);
624
+ switch (protocol) {
625
+ case "catalog": {
626
+ const resolution = this.resolveCatalogVersion(packageName, versionSpec);
627
+ return resolution.resolved;
628
+ }
629
+ case "workspace":
630
+ case "file":
631
+ case "link":
632
+ case "portal":
633
+ return "*";
634
+ case "npm": {
635
+ const parsed = parseNpmAlias(versionSpec);
636
+ return parsed?.[1] ?? null;
637
+ }
638
+ default:
639
+ return versionSpec;
640
+ }
641
+ }
642
+ /**
643
+ * 判断版本规格的协议类型
644
+ */
645
+ getVersionProtocol(versionSpec) {
646
+ for (const [prefix, protocol] of Object.entries(PROTOCOL_PREFIXES)) {
647
+ if (versionSpec.startsWith(prefix)) {
648
+ return protocol;
649
+ }
650
+ }
651
+ return "normal";
652
+ }
653
+ /**
654
+ * 从 workspace 根目录和 catalog 中查找已存在的别名
655
+ */
656
+ findWorkspaceAliases(targetPackage) {
657
+ const workspace = this.detect();
658
+ if (!workspace.isMonorepo || !workspace.workspaceRoot) {
659
+ return [];
660
+ }
661
+ const existingAliases = /* @__PURE__ */ new Set();
662
+ const aliases = [];
663
+ const catalogPath = join(workspace.workspaceRoot, "pnpm-workspace.yaml");
664
+ if (workspace.workspaceType === "pnpm") {
665
+ aliases.push(
666
+ ...extractAliasesFromDeps(workspace.catalog, targetPackage, catalogPath, existingAliases)
667
+ );
668
+ if (workspace.catalogs) {
669
+ for (const catalog of Object.values(workspace.catalogs)) {
670
+ aliases.push(
671
+ ...extractAliasesFromDeps(catalog, targetPackage, catalogPath, existingAliases)
672
+ );
673
+ }
674
+ }
675
+ }
676
+ const rootPkgPath = join(workspace.workspaceRoot, "package.json");
677
+ const rootPkgJson = readPackageJsonCached(workspace.workspaceRoot);
678
+ if (rootPkgJson) {
679
+ aliases.push(
680
+ ...extractAliasesFromDeps(
681
+ { ...rootPkgJson.dependencies, ...rootPkgJson.optionalDependencies },
682
+ targetPackage,
683
+ rootPkgPath,
684
+ existingAliases
685
+ ),
686
+ ...extractAliasesFromDeps(
687
+ rootPkgJson.devDependencies,
688
+ targetPackage,
689
+ rootPkgPath,
690
+ existingAliases
691
+ )
692
+ );
693
+ }
694
+ return aliases;
695
+ }
696
+ /**
697
+ * 获取 workspace 根目录
698
+ */
699
+ getWorkspaceRoot() {
700
+ const result = this.detect();
701
+ return result.workspaceRoot;
702
+ }
703
+ /**
704
+ * 检测 workspace
705
+ */
706
+ detectWorkspace() {
707
+ for (const dir of iterateParentDirs(this.projectRoot)) {
708
+ const result = this.tryDetectWorkspaceAt(dir);
709
+ if (result) {
710
+ return result;
711
+ }
712
+ }
713
+ return {
714
+ isMonorepo: false,
715
+ workspaceRoot: null,
716
+ workspaceType: "none"
717
+ };
718
+ }
719
+ /**
720
+ * 尝试在指定目录检测 workspace
721
+ */
722
+ tryDetectWorkspaceAt(dir) {
723
+ const pnpmWorkspacePath = join(dir, "pnpm-workspace.yaml");
724
+ if (fileExists(pnpmWorkspacePath)) {
725
+ const config = this.parsePnpmWorkspaceYaml(pnpmWorkspacePath);
726
+ logger2.debug(`Detected pnpm workspace at: ${dir}`);
727
+ return {
728
+ isMonorepo: true,
729
+ workspaceRoot: dir,
730
+ currentProjectPath: relative(dir, this.projectRoot) || ".",
731
+ workspaceType: "pnpm",
732
+ catalog: config.catalog,
733
+ catalogs: config.catalogs
734
+ };
735
+ }
736
+ const pkgJson = readPackageJsonCached(dir);
737
+ if (pkgJson?.workspaces) {
738
+ const isYarn = fileExists(join(dir, "yarn.lock"));
739
+ const workspaceType = isYarn ? "yarn" : "npm";
740
+ logger2.debug(`Detected ${workspaceType} workspace at: ${dir}`);
741
+ return {
742
+ isMonorepo: true,
743
+ workspaceRoot: dir,
744
+ currentProjectPath: relative(dir, this.projectRoot) || ".",
745
+ workspaceType
746
+ };
747
+ }
748
+ if (fileExists(join(dir, "lerna.json"))) {
749
+ logger2.debug(`Detected lerna workspace at: ${dir}`);
750
+ return {
751
+ isMonorepo: true,
752
+ workspaceRoot: dir,
753
+ currentProjectPath: relative(dir, this.projectRoot) || ".",
754
+ workspaceType: "lerna"
755
+ };
756
+ }
757
+ return null;
758
+ }
759
+ /**
760
+ * 解析 pnpm-workspace.yaml
761
+ */
762
+ parsePnpmWorkspaceYaml(filePath) {
763
+ try {
764
+ const content = readFileSync(filePath, "utf-8");
765
+ const parsed = parse(content);
766
+ return parsed ?? {};
767
+ } catch (error) {
768
+ logger2.warn(`Failed to parse pnpm-workspace.yaml: ${String(error)}`);
769
+ return {};
770
+ }
771
+ }
772
+ };
773
+ function createWorkspaceDetector(projectRoot) {
774
+ return new WorkspaceDetector(projectRoot);
775
+ }
776
+ function satisfies(version, range) {
777
+ try {
778
+ return semver.satisfies(version, range, { includePrerelease: false });
779
+ } catch {
780
+ return false;
781
+ }
782
+ }
783
+ function compare(v1, v2) {
784
+ try {
785
+ return semver.compare(v1, v2);
786
+ } catch {
787
+ return 0;
788
+ }
789
+ }
790
+ function findIntersection(versions, ranges) {
791
+ if (ranges.length === 0) return versions;
792
+ return versions.filter((version) => {
793
+ return ranges.every((range) => satisfies(version, range));
794
+ });
795
+ }
796
+ function findBestVersion(versions, ranges) {
797
+ const satisfyingVersions = findIntersection(versions, ranges);
798
+ if (satisfyingVersions.length === 0) {
799
+ return null;
800
+ }
801
+ let best = satisfyingVersions[0];
802
+ for (let i = 1; i < satisfyingVersions.length; i++) {
803
+ if (compare(satisfyingVersions[i], best) > 0) {
804
+ best = satisfyingVersions[i];
805
+ }
806
+ }
807
+ return best;
808
+ }
809
+ function createAliasInstallSpec(alias, packageName, version) {
810
+ return `${alias}@npm:${packageName}@${version}`;
811
+ }
812
+ function generateAliasName(packageName, version) {
813
+ let major;
814
+ try {
815
+ major = semver.major(version);
816
+ } catch {
817
+ const m = version.match(/^(\d+)/);
818
+ major = m ? Number(m[1]) : 0;
819
+ }
820
+ const cleanName = packageName.replace(/^@/, "").replace(/\//g, "-");
821
+ return `${cleanName}${major}`;
822
+ }
823
+
824
+ // src/core/registry-client.ts
825
+ var logger3 = createLogger("npm-registry");
826
+ var packageCache = /* @__PURE__ */ new Map();
827
+ var manifestCache = new LruCache({ maxEntries: 200 });
828
+ function clearNpmRegistryCache() {
829
+ packageCache.clear();
830
+ manifestCache.clear();
831
+ }
832
+ async function fetchWithTimeout(url, options = {}, consumeResponse, timeout = DEFAULT_NPM_REGISTRY_TIMEOUT_MS) {
833
+ const controller = new AbortController();
834
+ const timeoutId = setTimeout(() => controller.abort(), timeout);
835
+ try {
836
+ const response = await fetch(url, {
837
+ ...options,
838
+ signal: controller.signal
839
+ });
840
+ return await consumeResponse(response);
841
+ } finally {
842
+ clearTimeout(timeoutId);
843
+ }
844
+ }
845
+ async function fetchPackageInfo(packageName, registry2 = DEFAULT_NPM_REGISTRY) {
846
+ const cacheKey = `${registry2}:${packageName}`;
847
+ const cached = packageCache.get(cacheKey);
848
+ if (cached) {
849
+ return cached;
850
+ }
851
+ try {
852
+ const encodedName = packageName.startsWith("@") ? `@${encodeURIComponent(packageName.slice(1))}` : packageName;
853
+ const url = `${registry2.replace(/\/+$/, "")}/${encodedName}`;
854
+ logger3.debug(`Fetching package info from: ${url}`);
855
+ const { response, data } = await fetchWithTimeout(
856
+ url,
857
+ {
858
+ headers: {
859
+ Accept: "application/vnd.npm.install-v1+json"
860
+ }
861
+ },
862
+ async (fetchedResponse) => {
863
+ if (!fetchedResponse.ok) {
864
+ return { response: fetchedResponse, data: null };
865
+ }
866
+ return {
867
+ response: fetchedResponse,
868
+ data: await fetchedResponse.json()
869
+ };
870
+ }
871
+ );
872
+ if (!response.ok) {
873
+ if (response.status === 404) {
874
+ logger3.warn(`Package not found: ${packageName}`);
875
+ throw new Error(`Package not found: ${packageName} (HTTP 404)`);
876
+ }
877
+ throw new Error(`HTTP ${response.status}: ${response.statusText}`);
878
+ }
879
+ const packageInfo = {
880
+ name: data.name,
881
+ versions: Object.keys(data.versions),
882
+ versionDetails: data.versions,
883
+ distTags: data["dist-tags"]
884
+ };
885
+ const cacheEntry = {
886
+ name: packageInfo.name,
887
+ versions: packageInfo.versions,
888
+ versionDetails: {},
889
+ distTags: packageInfo.distTags
890
+ };
891
+ packageCache.set(cacheKey, cacheEntry);
892
+ return packageInfo;
893
+ } catch (error) {
894
+ if (error instanceof Error && error.name === "AbortError") {
895
+ logger3.error(
896
+ `Timeout fetching package info for ${packageName} (>${DEFAULT_NPM_REGISTRY_TIMEOUT_MS}ms)`,
897
+ error
898
+ );
899
+ } else {
900
+ logger3.error(`Failed to fetch package info for ${packageName}:`, error);
901
+ }
902
+ throw error;
903
+ }
904
+ }
905
+ var npmRegistryClient = {
906
+ async fetchAllVersions(packageName, registry2) {
907
+ const info = await fetchPackageInfo(packageName, registry2);
908
+ return info?.versions ?? [];
909
+ },
910
+ async fetchPackageManifest(packageName, version, registry2) {
911
+ const key = `${registry2}\0${packageName}\0${version}`;
912
+ const cached = manifestCache.get(key);
913
+ if (cached) return cached;
914
+ const encodedName = packageName.startsWith("@") ? `@${encodeURIComponent(packageName.slice(1))}` : encodeURIComponent(packageName);
915
+ const url = `${registry2.replace(/\/+$/, "")}/${encodedName}/${encodeURIComponent(version)}`;
916
+ const manifest = await fetchWithTimeout(
917
+ url,
918
+ {
919
+ headers: { Accept: "application/json" }
920
+ },
921
+ async (response) => {
922
+ if (!response.ok) throw new Error(`HTTP ${response.status}: ${response.statusText}`);
923
+ return await response.json();
924
+ }
925
+ );
926
+ if (manifest.name !== packageName || manifest.version !== version) {
927
+ throw new Error(`Invalid manifest for ${packageName}@${version}`);
928
+ }
929
+ manifestCache.set(key, manifest);
930
+ return manifest;
931
+ }
932
+ };
933
+ function normalizePackagePath(packagePath) {
934
+ try {
935
+ return realpathSync(packagePath);
936
+ } catch {
937
+ return resolve(packagePath);
938
+ }
939
+ }
940
+ function buildInstalledDependencyGraph(packageNames, projectRoot) {
941
+ const nodes = /* @__PURE__ */ new Map();
942
+ const roots = [];
943
+ const rootRequests = /* @__PURE__ */ new Map();
944
+ const stack = [];
945
+ for (let index = packageNames.length - 1; index >= 0; index--) {
946
+ const name = packageNames[index];
947
+ if (name) stack.push({ name, baseDir: projectRoot, parentId: null, root: true });
948
+ }
949
+ while (stack.length > 0) {
950
+ const item = stack.pop();
951
+ if (!item) continue;
952
+ const packagePath = findPackagePath(item.name, item.baseDir);
953
+ if (!packagePath) continue;
954
+ const normalizedPath = normalizePackagePath(packagePath);
955
+ if (item.root) rootRequests.set(item.name, normalizedPath);
956
+ if (item.parentId) nodes.get(item.parentId)?.resolvedChildren.set(item.name, normalizedPath);
957
+ const existingNode = nodes.get(normalizedPath);
958
+ if (existingNode) {
959
+ if (item.root) {
960
+ existingNode.parentId = null;
961
+ }
962
+ if (item.root && !roots.includes(normalizedPath)) {
963
+ roots.push(normalizedPath);
964
+ }
965
+ continue;
966
+ }
967
+ const packageJson = readPackageJsonCached(normalizedPath);
968
+ if (!packageJson) continue;
969
+ const dependencyNames = Object.keys({
970
+ ...packageJson.dependencies,
971
+ ...packageJson.optionalDependencies
972
+ });
973
+ const peerDependencyNames = Object.keys(packageJson.peerDependencies ?? {});
974
+ const node = {
975
+ id: normalizedPath,
976
+ name: item.name,
977
+ version: packageJson.version ?? "unknown",
978
+ packagePath: normalizedPath,
979
+ parentId: item.parentId,
980
+ dependencyNames,
981
+ peerDependencyNames,
982
+ resolvedChildren: /* @__PURE__ */ new Map()
983
+ };
984
+ nodes.set(normalizedPath, node);
985
+ if (item.root) roots.push(normalizedPath);
986
+ const childNames = [...dependencyNames, ...peerDependencyNames];
987
+ for (let index = childNames.length - 1; index >= 0; index--) {
988
+ const childName = childNames[index];
989
+ if (childName) {
990
+ stack.push({
991
+ name: childName,
992
+ baseDir: normalizedPath,
993
+ parentId: normalizedPath,
994
+ root: false
995
+ });
996
+ }
997
+ }
998
+ }
999
+ return { nodes, roots, rootRequests };
1000
+ }
1001
+
1002
+ // src/utils/module-request.ts
1003
+ function isVirtualModuleRequest(request) {
1004
+ return request.startsWith("\0");
1005
+ }
1006
+ function isPathLikeRequest(request) {
1007
+ if (!request) return false;
1008
+ if (request.startsWith(".")) {
1009
+ return true;
1010
+ }
1011
+ if (request.startsWith("/")) {
1012
+ return true;
1013
+ }
1014
+ if (/^[a-zA-Z]:[\\/]/.test(request)) {
1015
+ return true;
1016
+ }
1017
+ if (request.startsWith("\\\\")) {
1018
+ return true;
1019
+ }
1020
+ return false;
1021
+ }
1022
+
1023
+ // src/core/resolution-error.ts
1024
+ var ResolutionError = class extends Error {
1025
+ constructor(diagnostics) {
1026
+ super(
1027
+ diagnostics.map((diagnostic) => "[" + diagnostic.code + "] " + diagnostic.message).join("\n")
1028
+ );
1029
+ this.diagnostics = diagnostics;
1030
+ this.name = "ResolutionError";
1031
+ }
1032
+ diagnostics;
1033
+ };
1034
+
1035
+ // src/core/alias-manager.ts
1036
+ var logger4 = createLogger("alias-manager");
1037
+ var NO_RULE = { reason: "no-rule", aliases: [], matchedPaths: [] };
1038
+ var NO_IMPORTER = { reason: "no-importer", aliases: [], matchedPaths: [] };
1039
+ var UNMATCHED = { reason: "unmatched", aliases: [], matchedPaths: [] };
1040
+ function normalizePath(path) {
1041
+ const normalized = posix.normalize(path.replace(/\\/g, "/"));
1042
+ return normalized.length <= 1 ? normalized : normalized.replace(/\/+$/, "");
1043
+ }
1044
+ function isWithin(path, directory) {
1045
+ return path === directory || path.startsWith(directory.endsWith("/") ? directory : directory + "/");
1046
+ }
1047
+ function packageInstances(path) {
1048
+ const parts = path.split("/");
1049
+ const instances = [];
1050
+ for (let index = 0; index < parts.length - 1; index++) {
1051
+ if (parts[index] !== "node_modules") continue;
1052
+ const name = parts[index + 1];
1053
+ if (!name || name.startsWith(".")) continue;
1054
+ const scopedName = name.startsWith("@") ? parts[index + 2] : void 0;
1055
+ if (name.startsWith("@") && !scopedName) continue;
1056
+ const end = scopedName ? index + 3 : index + 2;
1057
+ instances.push({
1058
+ name: scopedName ? name + "/" + scopedName : name,
1059
+ path: parts.slice(0, end).join("/")
1060
+ });
1061
+ }
1062
+ return instances;
1063
+ }
1064
+ var AliasManager = class {
1065
+ constructor(options) {
1066
+ this.options = options;
1067
+ }
1068
+ options;
1069
+ aliasMappings = [];
1070
+ rulesMap = /* @__PURE__ */ new Map();
1071
+ importerCache = new LruCache({ maxEntries: 1e3 });
1072
+ pathCache = new LruCache({ maxEntries: 5e3 });
1073
+ decisionCache = new LruCache({ maxEntries: 5e3 });
1074
+ diagnostics = /* @__PURE__ */ new Map();
1075
+ initFromAnalysisResult(result) {
1076
+ this.clear();
1077
+ this.aliasMappings = result.aliasMappings;
1078
+ for (const mapping of this.aliasMappings) {
1079
+ const pathScoped = mapping.importerPaths !== void 0;
1080
+ const rule = {
1081
+ aliasName: mapping.aliasName,
1082
+ pathScoped,
1083
+ dependents: /* @__PURE__ */ new Set([
1084
+ ...pathScoped ? [] : mapping.allDependents,
1085
+ ...this.options.includeRedirects[mapping.originalName] ?? []
1086
+ ]),
1087
+ excludedPackages: new Set(this.options.excludeRedirects[mapping.originalName] ?? [])
1088
+ };
1089
+ let index = this.rulesMap.get(mapping.originalName);
1090
+ if (!index) {
1091
+ index = { paths: /* @__PURE__ */ new Map(), rules: [] };
1092
+ this.rulesMap.set(mapping.originalName, index);
1093
+ }
1094
+ index.rules.push(rule);
1095
+ for (const packagePath of mapping.importerPaths ?? []) {
1096
+ const candidates = this.pathCandidates(packagePath);
1097
+ const name = packageInstances(normalizePath(packagePath)).at(-1)?.name ?? readPackageJsonCached(packagePath)?.name;
1098
+ for (const candidate of candidates) {
1099
+ const entries = index.paths.get(candidate) ?? [];
1100
+ entries.push({ rule, scope: { path: candidate, name } });
1101
+ index.paths.set(candidate, entries);
1102
+ }
1103
+ }
1104
+ }
1105
+ logger4.info("Initialized " + this.aliasMappings.length + " alias mappings");
1106
+ }
1107
+ clear() {
1108
+ this.aliasMappings = [];
1109
+ this.rulesMap.clear();
1110
+ this.importerCache.clear();
1111
+ this.pathCache.clear();
1112
+ this.decisionCache.clear();
1113
+ this.diagnostics.clear();
1114
+ }
1115
+ pathCandidates(path, moduleId = false) {
1116
+ const cacheKey = (moduleId ? "id\0" : "path\0") + path;
1117
+ const cached = this.pathCache.get(cacheKey);
1118
+ if (cached) return cached;
1119
+ let literalPath = path;
1120
+ let realPath;
1121
+ try {
1122
+ realPath = realpathSync(path);
1123
+ } catch {
1124
+ if (moduleId) {
1125
+ const markers = [...path.matchAll(/[?#]/g)];
1126
+ for (let index = markers.length - 1; index >= 0; index--) {
1127
+ const candidate = path.slice(0, markers[index].index);
1128
+ try {
1129
+ if (!statSync(candidate).isFile()) continue;
1130
+ realPath = realpathSync(candidate);
1131
+ literalPath = candidate;
1132
+ break;
1133
+ } catch {
1134
+ }
1135
+ }
1136
+ }
1137
+ }
1138
+ const paths = /* @__PURE__ */ new Set([normalizePath(literalPath)]);
1139
+ if (realPath) paths.add(normalizePath(realPath));
1140
+ const candidates = [...paths];
1141
+ this.pathCache.set(cacheKey, candidates);
1142
+ return candidates;
1143
+ }
1144
+ importerInfo(importer) {
1145
+ const cached = this.importerCache.get(importer);
1146
+ if (cached) return cached;
1147
+ const paths = this.pathCandidates(importer, true);
1148
+ const instances = paths.flatMap(packageInstances);
1149
+ if (instances.length === 0) {
1150
+ for (const path of paths) {
1151
+ let directory = path;
1152
+ while (true) {
1153
+ const manifest = readPackageJsonCached(directory);
1154
+ if (manifest?.name) {
1155
+ instances.push({ name: manifest.name, path: directory });
1156
+ break;
1157
+ }
1158
+ const parent = posix.dirname(directory);
1159
+ if (parent === directory) break;
1160
+ directory = parent;
1161
+ }
1162
+ }
1163
+ }
1164
+ const info = { paths, instances };
1165
+ this.importerCache.set(importer, info);
1166
+ return info;
1167
+ }
1168
+ requestPackageName(request) {
1169
+ if (!request || isPathLikeRequest(request) || isVirtualModuleRequest(request)) return "";
1170
+ const base = request.split(/[?#]/, 1)[0] ?? "";
1171
+ const parts = base.split("/");
1172
+ return base.startsWith("@") ? parts.slice(0, 2).join("/") : parts[0] ?? "";
1173
+ }
1174
+ decide(packageName, importer) {
1175
+ if (!importer) return NO_IMPORTER;
1176
+ const index = this.rulesMap.get(packageName);
1177
+ if (!index) return NO_RULE;
1178
+ const cacheKey = packageName + "\0" + importer;
1179
+ const cached = this.decisionCache.get(cacheKey);
1180
+ if (cached) return cached;
1181
+ const info = this.importerInfo(importer);
1182
+ const matches = /* @__PURE__ */ new Map();
1183
+ for (const candidate of info.paths) {
1184
+ let path = candidate;
1185
+ let distance = 0;
1186
+ while (true) {
1187
+ for (const { rule, scope } of index.paths.get(path) ?? []) {
1188
+ let match = matches.get(rule);
1189
+ if (!match) {
1190
+ match = { rule, specificity: Number.NEGATIVE_INFINITY, scopes: [], excluded: false };
1191
+ matches.set(rule, match);
1192
+ }
1193
+ match.specificity = Math.max(match.specificity, -distance);
1194
+ match.scopes.push(scope);
1195
+ }
1196
+ const parent = posix.dirname(path);
1197
+ if (parent === path) break;
1198
+ path = parent;
1199
+ distance++;
1200
+ }
1201
+ }
1202
+ for (const rule of index.rules) {
1203
+ const included = info.instances.filter((instance) => rule.dependents.has(instance.name));
1204
+ let match = matches.get(rule);
1205
+ if (!match && included.length > 0) {
1206
+ match = { rule, specificity: Number.NEGATIVE_INFINITY, scopes: [], excluded: false };
1207
+ matches.set(rule, match);
1208
+ }
1209
+ if (!match) continue;
1210
+ match.excluded = match.scopes.some((scope) => scope.name && rule.excludedPackages.has(scope.name)) || info.instances.some(
1211
+ (instance) => rule.excludedPackages.has(instance.name) && (!rule.pathScoped || match.scopes.some(
1212
+ (scope) => isWithin(instance.path, scope.path) || isWithin(scope.path, instance.path)
1213
+ ) || included.some(
1214
+ (parent) => isWithin(instance.path, parent.path) || isWithin(parent.path, instance.path)
1215
+ ))
1216
+ );
1217
+ }
1218
+ let specificity = Number.NEGATIVE_INFINITY;
1219
+ let best = [];
1220
+ for (const match of matches.values()) {
1221
+ if (match.specificity > specificity) {
1222
+ specificity = match.specificity;
1223
+ best = [match];
1224
+ } else if (match.specificity === specificity) {
1225
+ best.push(match);
1226
+ }
1227
+ }
1228
+ let decision = UNMATCHED;
1229
+ if (best.length > 0) {
1230
+ const aliases = [...new Set(best.map((match) => match.rule.aliasName))].sort();
1231
+ const matchedPaths = [
1232
+ ...new Set(best.flatMap((match) => match.scopes.map((scope) => scope.path)))
1233
+ ].sort();
1234
+ decision = {
1235
+ reason: best.some((match) => match.excluded) ? "excluded" : aliases.length > 1 ? "ambiguous" : "redirected",
1236
+ aliases,
1237
+ matchedPaths
1238
+ };
1239
+ if (decision.reason === "ambiguous") {
1240
+ const key = packageName + "\0" + JSON.stringify([aliases, matchedPaths]);
1241
+ if (!this.diagnostics.has(key) && this.diagnostics.size < 1e3) {
1242
+ const diagnostic = {
1243
+ code: "AMBIGUOUS_IMPORTER",
1244
+ severity: "error",
1245
+ message: "Multiple aliases match the same importer for " + packageName + ": " + aliases.join(", "),
1246
+ packageName,
1247
+ aliases,
1248
+ importerPaths: matchedPaths
1249
+ };
1250
+ this.diagnostics.set(key, diagnostic);
1251
+ logger4.warn(diagnostic.message);
1252
+ }
1253
+ }
1254
+ }
1255
+ this.decisionCache.set(cacheKey, decision);
1256
+ return decision;
1257
+ }
1258
+ resolveModule({ request, importer }) {
1259
+ const packageName = this.requestPackageName(request);
1260
+ if (!packageName) return null;
1261
+ const decision = this.decide(packageName, importer);
1262
+ if (decision.reason === "ambiguous" && this.options.strict) {
1263
+ throw new ResolutionError(this.getDiagnostics());
1264
+ }
1265
+ return decision.reason === "redirected" ? decision.aliases[0] + request.slice(packageName.length) : null;
1266
+ }
1267
+ explainResolution(request, importer) {
1268
+ const packageName = this.requestPackageName(request);
1269
+ const decision = packageName ? this.decide(packageName, importer) : NO_RULE;
1270
+ return {
1271
+ request,
1272
+ importer,
1273
+ resolved: decision.reason === "redirected" ? decision.aliases[0] + request.slice(packageName.length) : null,
1274
+ reason: decision.reason,
1275
+ aliases: [...decision.aliases],
1276
+ matchedPaths: [...decision.matchedPaths]
1277
+ };
1278
+ }
1279
+ getDiagnostics() {
1280
+ return [...this.diagnostics.values()].map(
1281
+ (diagnostic) => Object.assign({}, diagnostic, {
1282
+ aliases: [...diagnostic.aliases ?? []],
1283
+ importerPaths: [...diagnostic.importerPaths ?? []]
1284
+ })
1285
+ );
1286
+ }
1287
+ getAliasPathMappings() {
1288
+ return this.aliasMappings.map((mapping) => ({
1289
+ aliasName: mapping.aliasName,
1290
+ originalName: mapping.originalName,
1291
+ path: findPackagePath(mapping.aliasName, this.options.projectRoot) ?? join(this.options.projectRoot, "node_modules", mapping.aliasName)
1292
+ }));
1293
+ }
1294
+ };
1295
+ function createAliasManager(options) {
1296
+ return new AliasManager(options);
1297
+ }
1298
+
1299
+ // src/core/alias-peer-resolver.ts
1300
+ function actualPath(path) {
1301
+ try {
1302
+ return realpathSync(path);
1303
+ } catch {
1304
+ return path;
1305
+ }
1306
+ }
1307
+ async function linkAliasPeers(mappings, options, registry2, diagnostics, peerConflicts = [], watchFiles) {
1308
+ if (mappings.length === 0) return;
1309
+ const readManifest = (directory) => {
1310
+ watchFiles?.add(join(actualPath(directory), "package.json"));
1311
+ return readPackageJsonCached(directory);
1312
+ };
1313
+ for (const mapping of mappings) {
1314
+ const previousPaths = new Set(Object.values(mapping.peerImporterPaths ?? {}).flat());
1315
+ if (mapping.importerPaths && previousPaths.size > 0) {
1316
+ mapping.importerPaths = mapping.importerPaths.filter((path) => !previousPaths.has(path));
1317
+ }
1318
+ mapping.peerImporterPaths = {};
1319
+ }
1320
+ const workspaceRoot = createWorkspaceDetector(options.projectRoot).getWorkspaceRoot();
1321
+ const manifests = /* @__PURE__ */ new Map();
1322
+ const installedPaths = /* @__PURE__ */ new Map();
1323
+ const consumerRequests = new Map(
1324
+ peerConflicts.map((conflict) => [conflict.packageName, conflict.requestedBy])
1325
+ );
1326
+ let contextResolver;
1327
+ for (const mapping of mappings) {
1328
+ const installedPath = findPackagePath(mapping.aliasName, options.projectRoot);
1329
+ const installed = installedPath ? readManifest(installedPath) : null;
1330
+ if (installed?.name === mapping.originalName && installed.version && satisfies(installed.version, mapping.resolvedVersion)) {
1331
+ manifests.set(mapping, installed);
1332
+ installedPaths.set(mapping, installedPath);
1333
+ continue;
1334
+ }
1335
+ if (mapping.installSpec && !options.offline && registry2.fetchPackageManifest) {
1336
+ try {
1337
+ const manifest = await registry2.fetchPackageManifest(
1338
+ mapping.originalName,
1339
+ mapping.resolvedVersion,
1340
+ options.registry
1341
+ );
1342
+ manifests.set(mapping, manifest);
1343
+ } catch (error) {
1344
+ diagnostics.push({
1345
+ code: "ALIAS_METADATA_UNAVAILABLE",
1346
+ severity: "error",
1347
+ packageName: mapping.originalName,
1348
+ aliases: [mapping.aliasName],
1349
+ message: "Cannot inspect selected version " + mapping.originalName + "@" + mapping.resolvedVersion + ": " + String(error)
1350
+ });
1351
+ }
1352
+ }
1353
+ }
1354
+ for (const [importer, manifest] of manifests) {
1355
+ const importerPaths = /* @__PURE__ */ new Set([
1356
+ join(options.projectRoot, "node_modules", importer.aliasName),
1357
+ join(actualPath(options.projectRoot), "node_modules", importer.aliasName)
1358
+ ]);
1359
+ if (workspaceRoot) importerPaths.add(join(workspaceRoot, "node_modules", importer.aliasName));
1360
+ const installedPath = installedPaths.get(importer);
1361
+ if (installedPath) importerPaths.add(actualPath(installedPath));
1362
+ const pendingInstallation = !installedPath && options.autoInstall && importer.installSpec;
1363
+ for (const [peerName, range] of Object.entries(manifest.peerDependencies ?? {})) {
1364
+ if (manifest.peerDependenciesMeta?.[peerName]?.optional) continue;
1365
+ const providers = /* @__PURE__ */ new Map();
1366
+ const providerAliases = /* @__PURE__ */ new Set();
1367
+ const checkContexts = importer.usedBy.length > 1 && consumerRequests.has(peerName);
1368
+ if (checkContexts) {
1369
+ for (const consumer of importer.usedBy) {
1370
+ const request = consumerRequests.get(peerName)?.find((entry) => entry.path.join(">") === consumer);
1371
+ if (!request) continue;
1372
+ let directory = options.projectRoot;
1373
+ for (const name of request.path) {
1374
+ const packageDirectory = findPackagePath(name, directory);
1375
+ directory = packageDirectory ? actualPath(packageDirectory) : null;
1376
+ if (!directory) break;
1377
+ }
1378
+ if (!directory) continue;
1379
+ if (!contextResolver) {
1380
+ contextResolver = new AliasManager({ ...options, strict: false });
1381
+ contextResolver.initFromAnalysisResult({
1382
+ aliasMappings: mappings,
1383
+ peerConflicts: [...peerConflicts],
1384
+ analyzedDependencies: /* @__PURE__ */ new Map(),
1385
+ missingFirstLevelPeers: []
1386
+ });
1387
+ }
1388
+ const decision = contextResolver.explainResolution(
1389
+ peerName,
1390
+ join(directory, "__peer_context__.js")
1391
+ );
1392
+ const selected = decision.reason === "redirected" || decision.reason === "ambiguous" ? mappings.filter((mapping) => decision.aliases.includes(mapping.aliasName)) : [];
1393
+ if (selected.length > 0) {
1394
+ for (const mapping of selected) {
1395
+ if (!satisfies(mapping.resolvedVersion, range)) continue;
1396
+ const path = actualPath(
1397
+ findPackagePath(mapping.aliasName, options.projectRoot) ?? join(options.projectRoot, "node_modules", mapping.aliasName)
1398
+ );
1399
+ providers.set(path, [
1400
+ ...providers.get(path) ?? [],
1401
+ consumer + " -> " + mapping.aliasName + "@" + mapping.resolvedVersion
1402
+ ]);
1403
+ providerAliases.add(mapping.aliasName);
1404
+ }
1405
+ } else {
1406
+ const path = findPackagePath(peerName, directory);
1407
+ const provider = path ? readManifest(path) : null;
1408
+ if (path && provider?.version && satisfies(provider.version, range)) {
1409
+ const identity = actualPath(path);
1410
+ providers.set(identity, [
1411
+ ...providers.get(identity) ?? [],
1412
+ consumer + " -> " + peerName + "@" + provider.version
1413
+ ]);
1414
+ }
1415
+ }
1416
+ }
1417
+ }
1418
+ if (providers.size > 1) {
1419
+ diagnostics.push({
1420
+ code: "AMBIGUOUS_IMPORTER",
1421
+ severity: "error",
1422
+ packageName: peerName,
1423
+ aliases: [...providerAliases].sort(),
1424
+ requestedBy: [importer.aliasName],
1425
+ importerPaths: [...importerPaths],
1426
+ message: "Conflicting consumer peer contexts for " + importer.aliasName + ": " + [...providers.values()].flat().join("; ")
1427
+ });
1428
+ continue;
1429
+ }
1430
+ let candidates = mappings.filter(
1431
+ (mapping) => mapping !== importer && mapping.originalName === peerName && satisfies(mapping.resolvedVersion, range)
1432
+ );
1433
+ const sharedContexts = candidates.filter(
1434
+ (candidate) => checkContexts ? providerAliases.has(candidate.aliasName) : candidate.usedBy.some((consumer) => importer.usedBy.includes(consumer))
1435
+ );
1436
+ if (sharedContexts.length > 0) {
1437
+ candidates = sharedContexts;
1438
+ } else {
1439
+ const naturalPath = findPackagePath(peerName, installedPath ?? options.projectRoot);
1440
+ const natural = naturalPath ? readManifest(naturalPath) : null;
1441
+ if (natural?.version && satisfies(natural.version, range)) continue;
1442
+ }
1443
+ if (candidates.length === 1) {
1444
+ const peer = candidates[0];
1445
+ if (peer.importerPaths === void 0) continue;
1446
+ const paths = [...importerPaths];
1447
+ peer.importerPaths = [.../* @__PURE__ */ new Set([...peer.importerPaths, ...paths])];
1448
+ peer.peerImporterPaths = {
1449
+ ...peer.peerImporterPaths,
1450
+ [importer.aliasName]: paths
1451
+ };
1452
+ continue;
1453
+ }
1454
+ if (candidates.length > 1) {
1455
+ diagnostics.push({
1456
+ code: "AMBIGUOUS_IMPORTER",
1457
+ severity: pendingInstallation ? "warning" : "error",
1458
+ packageName: peerName,
1459
+ aliases: candidates.map((candidate) => candidate.aliasName).sort(),
1460
+ requestedBy: [importer.aliasName],
1461
+ importerPaths: [...importerPaths],
1462
+ message: "Multiple peer contexts for " + importer.aliasName + " requiring " + peerName + "@" + range
1463
+ });
1464
+ continue;
1465
+ }
1466
+ diagnostics.push({
1467
+ code: "ALIAS_PEER_UNSATISFIED",
1468
+ severity: pendingInstallation ? "warning" : "error",
1469
+ packageName: peerName,
1470
+ requestedBy: [importer.aliasName],
1471
+ message: importer.aliasName + " requires " + peerName + "@" + range + (pendingInstallation ? "; provider availability will be checked after installation" : ", but no compatible alias or installed provider is available")
1472
+ });
1473
+ }
1474
+ }
1475
+ }
1476
+ function canonical(directory) {
1477
+ try {
1478
+ return realpathSync(directory);
1479
+ } catch {
1480
+ return directory;
1481
+ }
1482
+ }
1483
+ function validateSharedPeerContexts(graph, mappings, options, diagnostics, watchFiles) {
1484
+ if (mappings.length === 0 || graph.rootRequests.size < 2) return;
1485
+ const readManifest = (directory) => {
1486
+ watchFiles?.add(join(directory, "package.json"));
1487
+ return readPackageJsonCached(directory);
1488
+ };
1489
+ const aliases = /* @__PURE__ */ new Map();
1490
+ const installedMappings = mappings.filter((mapping) => {
1491
+ const path = findPackagePath(mapping.aliasName, options.projectRoot);
1492
+ if (!path) return false;
1493
+ const physical = canonical(path);
1494
+ const manifest = readManifest(physical);
1495
+ if (manifest?.name !== mapping.originalName || !manifest.version || !satisfies(manifest.version, mapping.resolvedVersion))
1496
+ return false;
1497
+ aliases.set(mapping.aliasName, {
1498
+ path: physical,
1499
+ version: manifest.version,
1500
+ label: mapping.aliasName + "@" + manifest.version
1501
+ });
1502
+ return true;
1503
+ });
1504
+ if (installedMappings.length === 0) return;
1505
+ const resolver = new AliasManager({ ...options, strict: false });
1506
+ resolver.initFromAnalysisResult({
1507
+ aliasMappings: installedMappings,
1508
+ analyzedDependencies: /* @__PURE__ */ new Map(),
1509
+ peerConflicts: [],
1510
+ missingFirstLevelPeers: []
1511
+ });
1512
+ const aliasPaths = new Set([...aliases.values()].map((provider) => provider.path));
1513
+ const originals = new Set(installedMappings.map((mapping) => mapping.originalName));
1514
+ for (const peer of originals) {
1515
+ const hasExclusions = (options.excludeRedirects[peer]?.length ?? 0) > 0;
1516
+ const roots = [];
1517
+ for (const [consumer, nodeId] of graph.rootRequests) {
1518
+ const node = graph.nodes.get(nodeId);
1519
+ if (!node) continue;
1520
+ const manifest = readManifest(node.packagePath);
1521
+ const range = manifest?.peerDependencies?.[peer];
1522
+ if (!range || manifest?.peerDependenciesMeta?.[peer]?.optional) continue;
1523
+ const decision = resolver.explainResolution(
1524
+ peer,
1525
+ join(node.packagePath, "__peer_context__.js")
1526
+ );
1527
+ if (decision.reason === "ambiguous") continue;
1528
+ let provider = decision.resolved ? aliases.get(decision.aliases[0]) : void 0;
1529
+ if (!decision.resolved) {
1530
+ const path = findPackagePath(peer, node.packagePath);
1531
+ const natural = path ? readManifest(canonical(path)) : null;
1532
+ if (path && natural?.version)
1533
+ provider = {
1534
+ path: canonical(path),
1535
+ version: natural.version,
1536
+ label: peer + "@" + natural.version
1537
+ };
1538
+ }
1539
+ if (provider && satisfies(provider.version, range))
1540
+ roots.push({ nodeId, consumer, provider });
1541
+ }
1542
+ if (new Set(roots.map(({ provider }) => provider.path)).size < 2) continue;
1543
+ const visited = /* @__PURE__ */ new Set();
1544
+ const contexts = /* @__PURE__ */ new Map();
1545
+ const pending = [...roots];
1546
+ while (pending.length > 0) {
1547
+ const context = pending.pop();
1548
+ const key = context.nodeId + "\0" + context.provider.path;
1549
+ if (visited.has(key)) continue;
1550
+ visited.add(key);
1551
+ const node = graph.nodes.get(context.nodeId);
1552
+ if (!node || originals.has(node.name)) continue;
1553
+ if (hasExclusions && resolver.explainResolution(peer, join(node.packagePath, "__peer_context__.js")).reason === "excluded")
1554
+ continue;
1555
+ const manifest = readManifest(node.packagePath);
1556
+ const range = manifest?.peerDependencies?.[peer];
1557
+ if (range && !satisfies(context.provider.version, range)) continue;
1558
+ if (range && !manifest?.peerDependenciesMeta?.[peer]?.optional && !aliasPaths.has(node.packagePath) && !options.includeRedirects[peer]?.includes(node.name)) {
1559
+ let incoming = contexts.get(node.id);
1560
+ if (!incoming) contexts.set(node.id, incoming = /* @__PURE__ */ new Map());
1561
+ incoming.set(context.provider.path, context);
1562
+ }
1563
+ for (const child of node.resolvedChildren.values())
1564
+ pending.push({ ...context, nodeId: child });
1565
+ }
1566
+ for (const [nodeId, incoming] of contexts) {
1567
+ if (incoming.size < 2) continue;
1568
+ const node = graph.nodes.get(nodeId);
1569
+ diagnostics.push({
1570
+ code: "SHARED_PEER_CONTEXT",
1571
+ severity: "warning",
1572
+ packageName: peer,
1573
+ requestedBy: [...new Set([...incoming.values()].map(({ consumer }) => consumer))],
1574
+ importerPaths: [node.packagePath],
1575
+ 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."
1576
+ });
1577
+ }
1578
+ }
1579
+ }
1580
+
1581
+ // src/core/dependency-analyzer.ts
1582
+ var logger5 = createLogger("dependency-analyzer");
1583
+ var DependencyAnalyzer = class {
1584
+ options;
1585
+ /** 主项目声明的依赖(解析后的版本,catalog: 等协议已转换) */
1586
+ declaredDeps;
1587
+ /** 主项目声明的原始依赖(未解析,保留 catalog: 等协议) */
1588
+ rawDeclaredDeps;
1589
+ /** 分析结果:存储有 peer 依赖的包信息 */
1590
+ analyzedDependencies = /* @__PURE__ */ new Map();
1591
+ /** 已访问的包名(使用包名,同一个包只分析一次) */
1592
+ visitedPackages = /* @__PURE__ */ new Set();
1593
+ /** 已安装包的信息缓存(按需填充,避免扫描整个 node_modules) */
1594
+ installedPackageCache = /* @__PURE__ */ new Map();
1595
+ /**
1596
+ * 已存在的别名映射:真实包名 -> 别名信息列表
1597
+ * 从 package.json 的 npm:package@version 格式解析得到
1598
+ * 这是最准确的别名识别方式
1599
+ */
1600
+ existingAliasesMap = /* @__PURE__ */ new Map();
1601
+ /** Workspace 检测器(用于 catalog 协议解析和 workspace 别名查找) */
1602
+ workspaceDetector;
1603
+ /** Workspace 级别的别名缓存 */
1604
+ workspaceAliasesCache = /* @__PURE__ */ new Map();
1605
+ /** workspace 根目录 package.json 声明的依赖(dependencies/devDependencies),用于“声明判断”合并 */
1606
+ workspaceRootDeclaredDeps = {};
1607
+ /** 是否已加载 workspaceRootDeclaredDeps */
1608
+ workspaceRootDeclaredLoaded = false;
1609
+ /** collectAllRelatedPackages 的 memo 缓存(单次 analyze 生命周期内有效) */
1610
+ collectCache = /* @__PURE__ */ new Map();
1611
+ /** 当前 analyze 使用的按安装路径区分的依赖图 */
1612
+ dependencyGraph = null;
1613
+ /** 注册表访问适配器(可注入以支持离线分析和确定性测试) */
1614
+ registryClient;
1615
+ graphPopulated = false;
1616
+ diagnostics = [];
1617
+ watchFiles = /* @__PURE__ */ new Set();
1618
+ injectedInstalledDeps;
1619
+ constructor(options, mainPackageJson, installedDeps, registryClient = npmRegistryClient) {
1620
+ this.options = options;
1621
+ this.registryClient = registryClient;
1622
+ this.injectedInstalledDeps = installedDeps;
1623
+ this.rawDeclaredDeps = {
1624
+ ...mainPackageJson.dependencies,
1625
+ ...mainPackageJson.devDependencies,
1626
+ ...mainPackageJson.optionalDependencies
1627
+ };
1628
+ this.declaredDeps = { ...this.rawDeclaredDeps };
1629
+ this.workspaceDetector = createWorkspaceDetector(options.projectRoot);
1630
+ this.parseExistingAliases();
1631
+ if (installedDeps) {
1632
+ for (const [name, info] of installedDeps) {
1633
+ this.installedPackageCache.set(name, info);
1634
+ }
1635
+ }
1636
+ }
1637
+ /**
1638
+ * 统一封装:在指定 baseDir 下解析包安装路径并读取 package.json
1639
+ * - 用于收敛 findPackagePath + readPackageJsonCached 的重复逻辑
1640
+ * - 返回 { packagePath: null } 表示无法 resolve 到该包
1641
+ * - 返回 { packagePath, pkgJson: null } 表示找到了目录但 package.json 无法读取/解析
1642
+ */
1643
+ resolvePackageJson(packageName, baseDir) {
1644
+ const packagePath = findPackagePath(packageName, baseDir);
1645
+ if (!packagePath) {
1646
+ return { packagePath: null, pkgJson: null };
1647
+ }
1648
+ const pkgJson = readPackageJsonCached(packagePath);
1649
+ this.watchFiles.add(join(this.normalizeInstalledPath(packagePath), "package.json"));
1650
+ return { packagePath, pkgJson };
1651
+ }
1652
+ /**
1653
+ * 加载 workspace 根目录 package.json 声明的依赖(dependencies/devDependencies)
1654
+ *
1655
+ * 目的:在 monorepo/workspace 场景下,“主工程声明”需要合并当前包与 workspace 根的声明,
1656
+ * 与 WorkspaceDetector 的 workspaceRoot 判断逻辑保持一致。
1657
+ */
1658
+ ensureWorkspaceRootDeclaredDepsLoaded() {
1659
+ if (this.workspaceRootDeclaredLoaded) {
1660
+ return;
1661
+ }
1662
+ this.workspaceRootDeclaredLoaded = true;
1663
+ const workspaceRoot = this.workspaceDetector.getWorkspaceRoot();
1664
+ if (!workspaceRoot || workspaceRoot === this.options.projectRoot) {
1665
+ return;
1666
+ }
1667
+ const rootPkgJson = readPackageJsonCached(workspaceRoot);
1668
+ if (!rootPkgJson) {
1669
+ return;
1670
+ }
1671
+ this.workspaceRootDeclaredDeps = {
1672
+ ...rootPkgJson.dependencies,
1673
+ ...rootPkgJson.devDependencies,
1674
+ ...rootPkgJson.optionalDependencies
1675
+ };
1676
+ }
1677
+ /**
1678
+ * 判断某个包是否在“主工程”声明(dependencies/devDependencies)
1679
+ *
1680
+ * 默认行为(与 workspace 判断逻辑一致):
1681
+ * - 非 workspace:只看当前 projectRoot 的 package.json
1682
+ * - workspace/monorepo:合并 projectRoot + workspaceRoot 两处 package.json 的声明
1683
+ */
1684
+ isDeclaredInMainProject(packageName) {
1685
+ return Object.prototype.hasOwnProperty.call(this.declaredDeps, packageName) || Object.prototype.hasOwnProperty.call(this.workspaceRootDeclaredDeps, packageName);
1686
+ }
1687
+ /**
1688
+ * 解析 package.json 中的 npm: 协议别名
1689
+ * 格式:aliasName: "npm:realPackage@version"
1690
+ * 这是识别别名最准确的方式
1691
+ */
1692
+ parseExistingAliases() {
1693
+ for (const [aliasName, versionSpec] of Object.entries(this.declaredDeps)) {
1694
+ if (typeof versionSpec !== "string") continue;
1695
+ const parsed = parseNpmAlias(versionSpec);
1696
+ if (parsed) {
1697
+ const [targetPackage, version] = parsed;
1698
+ const aliasInfo = {
1699
+ aliasName,
1700
+ targetPackage,
1701
+ versionSpec: version,
1702
+ installedVersion: null
1703
+ // 稍后在需要时填充
1704
+ };
1705
+ const existing = this.existingAliasesMap.get(targetPackage) ?? [];
1706
+ existing.push(aliasInfo);
1707
+ this.existingAliasesMap.set(targetPackage, existing);
1708
+ logger5.debug(`Found npm alias: ${aliasName} -> ${targetPackage}@${version}`);
1709
+ }
1710
+ }
1711
+ if (this.existingAliasesMap.size > 0) {
1712
+ logger5.debug(`Found ${this.existingAliasesMap.size} npm: protocol aliases`);
1713
+ }
1714
+ }
1715
+ /**
1716
+ * 获取别名的已安装版本(懒加载)
1717
+ */
1718
+ getAliasInstalledVersion(aliasName) {
1719
+ const cached = this.installedPackageCache.get(aliasName);
1720
+ if (cached) {
1721
+ return cached.version;
1722
+ }
1723
+ const { packagePath, pkgJson } = this.resolvePackageJson(aliasName, this.options.projectRoot);
1724
+ if (packagePath && pkgJson?.version) {
1725
+ this.installedPackageCache.set(aliasName, {
1726
+ name: aliasName,
1727
+ version: pkgJson.version,
1728
+ path: packagePath,
1729
+ isAlias: true,
1730
+ realName: pkgJson.name
1731
+ });
1732
+ return pkgJson.version;
1733
+ }
1734
+ return null;
1735
+ }
1736
+ /**
1737
+ * 解析所有 catalog: 协议的依赖版本
1738
+ * 将 catalog:xxx 转换为实际的版本范围
1739
+ */
1740
+ resolveCatalogDependencies() {
1741
+ for (const [pkgName, versionSpec] of Object.entries(this.rawDeclaredDeps)) {
1742
+ if (typeof versionSpec !== "string") continue;
1743
+ if (versionSpec.startsWith("catalog:")) {
1744
+ const resolved = this.workspaceDetector.resolveVersionSpec(pkgName, versionSpec);
1745
+ if (resolved) {
1746
+ this.declaredDeps[pkgName] = resolved;
1747
+ logger5.debug(`Resolved catalog dependency: ${pkgName} "${versionSpec}" -> "${resolved}"`);
1748
+ } else {
1749
+ logger5.warn(`Failed to resolve catalog dependency: ${pkgName}@${versionSpec}`);
1750
+ }
1751
+ } else if (versionSpec.startsWith("workspace:")) {
1752
+ const resolved = this.workspaceDetector.resolveVersionSpec(pkgName, versionSpec);
1753
+ if (resolved) {
1754
+ this.declaredDeps[pkgName] = resolved;
1755
+ logger5.debug(
1756
+ `Resolved workspace dependency: ${pkgName} "${versionSpec}" -> "${resolved}"`
1757
+ );
1758
+ }
1759
+ }
1760
+ }
1761
+ }
1762
+ /**
1763
+ * 分析依赖并找出冲突
1764
+ */
1765
+ async analyze() {
1766
+ logger5.info("Starting dependency analysis...");
1767
+ this.watchFiles.clear();
1768
+ this.watchFiles.add(join(this.options.projectRoot, "package.json"));
1769
+ try {
1770
+ this.resolveCatalogDependencies();
1771
+ this.ensureWorkspaceRootDeclaredDepsLoaded();
1772
+ const workspaceRoot = this.workspaceDetector.getWorkspaceRoot();
1773
+ if (workspaceRoot) {
1774
+ this.watchFiles.add(join(workspaceRoot, "package.json"));
1775
+ const workspaceFile = join(workspaceRoot, "pnpm-workspace.yaml");
1776
+ if (fileExists(workspaceFile)) this.watchFiles.add(workspaceFile);
1777
+ }
1778
+ this.dependencyGraph = buildInstalledDependencyGraph(
1779
+ this.options.dependencies,
1780
+ this.options.projectRoot
1781
+ );
1782
+ for (const node of this.dependencyGraph.nodes.values()) {
1783
+ this.watchFiles.add(join(node.packagePath, "package.json"));
1784
+ }
1785
+ for (const depName of this.options.dependencies) {
1786
+ this.analyzeDependencyRecursive(depName, []);
1787
+ if (!this.findGraphRoot(depName) && !this.injectedInstalledDeps?.has(depName)) {
1788
+ this.diagnostics.push({
1789
+ code: "DEPENDENCY_NOT_FOUND",
1790
+ severity: "error",
1791
+ packageName: depName,
1792
+ message: "Configured dependency not found: " + depName
1793
+ });
1794
+ }
1795
+ }
1796
+ const peerDepsMap = this.collectFirstLevelPeerDependencies();
1797
+ const peerConflicts = this.analyzePeerConflicts(peerDepsMap);
1798
+ const aliasMappings = await this.generateAliasMappings(peerConflicts);
1799
+ validateSharedPeerContexts(
1800
+ this.dependencyGraph,
1801
+ aliasMappings,
1802
+ this.options,
1803
+ this.diagnostics,
1804
+ this.watchFiles
1805
+ );
1806
+ const missingFirstLevelPeers = this.findMissingFirstLevelPeers(peerDepsMap);
1807
+ const conflictsNeedingAlias = peerConflicts.filter((c) => c.needsAlias).length;
1808
+ logger5.info(
1809
+ `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.`
1810
+ );
1811
+ return {
1812
+ watchFiles: [...this.watchFiles],
1813
+ diagnostics: this.diagnostics,
1814
+ analyzedDependencies: this.analyzedDependencies,
1815
+ peerConflicts,
1816
+ aliasMappings,
1817
+ missingFirstLevelPeers
1818
+ };
1819
+ } finally {
1820
+ clearPackageJsonCache();
1821
+ clearNpmRegistryCache();
1822
+ this.visitedPackages.clear();
1823
+ this.installedPackageCache.clear();
1824
+ this.existingAliasesMap.clear();
1825
+ this.workspaceAliasesCache.clear();
1826
+ this.workspaceRootDeclaredDeps = {};
1827
+ this.rawDeclaredDeps = {};
1828
+ this.declaredDeps = {};
1829
+ this.collectCache.clear();
1830
+ this.dependencyGraph = null;
1831
+ }
1832
+ }
1833
+ /**
1834
+ * 递归分析单个依赖及其所有子依赖
1835
+ */
1836
+ analyzeDependencyRecursive(packageName, dependencyPath) {
1837
+ const graphRoot = this.findGraphRoot(packageName);
1838
+ if (graphRoot) {
1839
+ this.populateAnalyzedDependenciesFromGraph();
1840
+ return this.analyzedDependencies.get(packageName) ?? null;
1841
+ }
1842
+ if (this.visitedPackages.has(packageName)) {
1843
+ logger5.debug(`Skipping already visited package: ${packageName}`);
1844
+ return this.analyzedDependencies.get(packageName) ?? null;
1845
+ }
1846
+ let rootInfo = null;
1847
+ const stack = [
1848
+ { name: packageName, path: dependencyPath }
1849
+ ];
1850
+ while (stack.length > 0) {
1851
+ const item = stack.pop();
1852
+ if (!item) break;
1853
+ const name = item.name;
1854
+ const path = item.path;
1855
+ if (this.visitedPackages.has(name)) {
1856
+ continue;
1857
+ }
1858
+ this.visitedPackages.add(name);
1859
+ const { packagePath, pkgJson } = this.resolvePackageJson(name, this.options.projectRoot);
1860
+ if (!packagePath) {
1861
+ logger5.debug(`Package not found: ${name}`);
1862
+ continue;
1863
+ }
1864
+ if (!pkgJson) {
1865
+ logger5.debug(`Could not read package.json for: ${name}`);
1866
+ continue;
1867
+ }
1868
+ this.cacheInstalledPackageInfo(name, packagePath, pkgJson);
1869
+ logger5.debug(`Analyzing ${name}@${pkgJson.version}`);
1870
+ const depInfo = {
1871
+ name,
1872
+ version: pkgJson.version ?? "unknown",
1873
+ dependencyPath: [...path],
1874
+ dependencies: { ...pkgJson.dependencies, ...pkgJson.optionalDependencies },
1875
+ peerDependencies: pkgJson.peerDependencies ?? {},
1876
+ peerDependenciesMeta: pkgJson.peerDependenciesMeta
1877
+ };
1878
+ this.analyzedDependencies.set(name, depInfo);
1879
+ if (name === packageName) {
1880
+ rootInfo = depInfo;
1881
+ }
1882
+ const currentPath = [...path, name];
1883
+ const depsToCheck = [
1884
+ ...Object.keys({ ...pkgJson.dependencies, ...pkgJson.optionalDependencies }),
1885
+ ...Object.keys(pkgJson.peerDependencies ?? {})
1886
+ ];
1887
+ for (const depName of depsToCheck) {
1888
+ if (this.visitedPackages.has(depName)) {
1889
+ continue;
1890
+ }
1891
+ stack.push({ name: depName, path: currentPath });
1892
+ }
1893
+ }
1894
+ return rootInfo;
1895
+ }
1896
+ findGraphRoot(packageName) {
1897
+ if (!this.dependencyGraph) return null;
1898
+ const rootId = this.dependencyGraph.rootRequests.get(packageName);
1899
+ return rootId ? this.dependencyGraph.nodes.get(rootId) ?? null : null;
1900
+ }
1901
+ getDependencyPathForGraphNode(node) {
1902
+ if (!this.dependencyGraph) return [];
1903
+ const names = [];
1904
+ let current = node;
1905
+ const visited = /* @__PURE__ */ new Set();
1906
+ while (current && !visited.has(current.id)) {
1907
+ visited.add(current.id);
1908
+ names.unshift(current.name);
1909
+ current = current.parentId ? this.dependencyGraph.nodes.get(current.parentId) : void 0;
1910
+ }
1911
+ return names.slice(0, -1);
1912
+ }
1913
+ populateAnalyzedDependenciesFromGraph() {
1914
+ if (!this.dependencyGraph || this.graphPopulated) return;
1915
+ this.graphPopulated = true;
1916
+ const rootVisibleNodeIds = /* @__PURE__ */ new Map();
1917
+ for (const node of this.dependencyGraph.nodes.values()) {
1918
+ const rootVisiblePath = findPackagePath(node.name, this.options.projectRoot);
1919
+ if (!rootVisiblePath) continue;
1920
+ const rootVisibleNode = this.dependencyGraph.nodes.get(
1921
+ this.normalizeInstalledPath(rootVisiblePath)
1922
+ );
1923
+ if (rootVisibleNode && !rootVisibleNodeIds.has(node.name)) {
1924
+ rootVisibleNodeIds.set(node.name, rootVisibleNode.id);
1925
+ }
1926
+ }
1927
+ const orderedNodes = [];
1928
+ const selectedNodeIds = /* @__PURE__ */ new Set();
1929
+ for (const nodeId of rootVisibleNodeIds.values()) {
1930
+ const node = this.dependencyGraph.nodes.get(nodeId);
1931
+ if (node && !selectedNodeIds.has(node.id)) {
1932
+ selectedNodeIds.add(node.id);
1933
+ orderedNodes.push(node);
1934
+ }
1935
+ }
1936
+ for (const node of this.dependencyGraph.nodes.values()) {
1937
+ if (!selectedNodeIds.has(node.id)) {
1938
+ orderedNodes.push(node);
1939
+ }
1940
+ }
1941
+ for (const node of orderedNodes) {
1942
+ if (this.analyzedDependencies.has(node.name)) continue;
1943
+ const packageJson = readPackageJsonCached(node.packagePath);
1944
+ if (!packageJson) continue;
1945
+ this.cacheInstalledPackageInfo(node.name, node.packagePath, packageJson);
1946
+ this.analyzedDependencies.set(node.name, {
1947
+ name: node.name,
1948
+ version: node.version,
1949
+ dependencyPath: this.getDependencyPathForGraphNode(node),
1950
+ dependencies: { ...packageJson.dependencies, ...packageJson.optionalDependencies },
1951
+ peerDependencies: packageJson.peerDependencies ?? {},
1952
+ peerDependenciesMeta: packageJson.peerDependenciesMeta
1953
+ });
1954
+ this.visitedPackages.add(node.name);
1955
+ }
1956
+ for (const [name, rootId] of this.dependencyGraph.rootRequests) {
1957
+ const node = this.dependencyGraph.nodes.get(rootId);
1958
+ if (!node || node.name === name) continue;
1959
+ const packageJson = readPackageJsonCached(node.packagePath);
1960
+ if (!packageJson) continue;
1961
+ this.cacheInstalledPackageInfo(name, node.packagePath, packageJson);
1962
+ this.analyzedDependencies.set(name, {
1963
+ name,
1964
+ version: node.version,
1965
+ dependencyPath: [],
1966
+ dependencies: { ...packageJson.dependencies, ...packageJson.optionalDependencies },
1967
+ peerDependencies: packageJson.peerDependencies ?? {},
1968
+ peerDependenciesMeta: packageJson.peerDependenciesMeta
1969
+ });
1970
+ this.visitedPackages.add(name);
1971
+ }
1972
+ }
1973
+ /**
1974
+ * 缓存已安装包的信息(用于后续查找别名等)
1975
+ */
1976
+ cacheInstalledPackageInfo(packageName, packagePath, pkgJson) {
1977
+ if (this.installedPackageCache.has(packageName)) {
1978
+ return;
1979
+ }
1980
+ const info = {
1981
+ name: packageName,
1982
+ version: pkgJson.version ?? "unknown",
1983
+ path: packagePath
1984
+ };
1985
+ if (pkgJson.name && pkgJson.name !== packageName) {
1986
+ info.isAlias = true;
1987
+ info.realName = pkgJson.name;
1988
+ }
1989
+ const declaredSpec = this.declaredDeps[packageName];
1990
+ if (typeof declaredSpec === "string" && declaredSpec.startsWith("npm:")) {
1991
+ info.isAlias = true;
1992
+ info.realName = pkgJson.name;
1993
+ }
1994
+ this.installedPackageCache.set(packageName, info);
1995
+ }
1996
+ /**
1997
+ * 收集第一层依赖的 peer 依赖
1998
+ * 只分析用户指定的 dependencies 的直接 peerDependencies,不分析子依赖的 peerDependencies
1999
+ *
2000
+ * 注意:虽然只收集第一层的 peer 依赖用于冲突检测和别名安装,
2001
+ * 但依赖树仍然会被完整构建,用于后续的重定向判断
2002
+ */
2003
+ collectFirstLevelPeerDependencies() {
2004
+ const peerDepsMap = /* @__PURE__ */ new Map();
2005
+ const hasInstalledGraphRoots = (this.dependencyGraph?.roots.length ?? 0) > 0;
2006
+ for (const depName of this.options.dependencies) {
2007
+ if (hasInstalledGraphRoots && !this.findGraphRoot(depName)) {
2008
+ logger5.debug(`Skipping non-root configured dependency: ${depName}`);
2009
+ continue;
2010
+ }
2011
+ const depInfo = this.analyzedDependencies.get(depName);
2012
+ if (!depInfo) continue;
2013
+ const peerDeps = depInfo.peerDependencies;
2014
+ const peerMeta = depInfo.peerDependenciesMeta ?? {};
2015
+ for (const [peerName, peerRange] of Object.entries(peerDeps)) {
2016
+ const isOptional = peerMeta[peerName]?.optional === true;
2017
+ if (isOptional) {
2018
+ logger5.debug(
2019
+ `Skipping optional first-level peer dependency: ${peerName}@${peerRange} required by ${depName}`
2020
+ );
2021
+ continue;
2022
+ }
2023
+ const existing = peerDepsMap.get(peerName) ?? [];
2024
+ existing.push({
2025
+ path: [depName],
2026
+ requiredRange: peerRange
2027
+ });
2028
+ peerDepsMap.set(peerName, existing);
2029
+ logger5.debug(
2030
+ `Found first-level peer dependency: ${peerName}@${peerRange} required by ${depName}${isOptional ? " (optional)" : ""}`
2031
+ );
2032
+ }
2033
+ }
2034
+ return peerDepsMap;
2035
+ }
2036
+ /**
2037
+ * 分析 peer 依赖冲突
2038
+ * 只有当主工程已安装某个依赖,且 peerDeps 要求的版本不兼容时,才需要别名
2039
+ */
2040
+ analyzePeerConflicts(peerDepsMap) {
2041
+ const conflicts = [];
2042
+ for (const [packageName, requestedBy] of peerDepsMap) {
2043
+ const isDeclared = this.isDeclaredInMainProject(packageName);
2044
+ const mainVersion = isDeclared ? this.getMainProjectVersion(packageName) : null;
2045
+ const isInstalled = mainVersion !== null;
2046
+ if (!isDeclared || !isInstalled) {
2047
+ this.diagnostics.push({
2048
+ code: isDeclared ? "PEER_NOT_INSTALLED" : "PEER_NOT_DECLARED",
2049
+ severity: "error",
2050
+ packageName,
2051
+ requestedBy: requestedBy.map((request) => request.path.join(">")),
2052
+ message: packageName + (isDeclared ? " is declared but not installed" : " is not declared by the host")
2053
+ });
2054
+ }
2055
+ const conflictingRanges = [];
2056
+ for (const request of requestedBy) {
2057
+ const resolvedRange = this.workspaceDetector.resolveVersionSpec(packageName, request.requiredRange) ?? request.requiredRange;
2058
+ if (mainVersion && satisfies(mainVersion, resolvedRange)) ; else {
2059
+ conflictingRanges.push({
2060
+ ...request,
2061
+ requiredRange: resolvedRange
2062
+ });
2063
+ }
2064
+ }
2065
+ const hasConflict = conflictingRanges.length > 0;
2066
+ const needsAlias = hasConflict && isDeclared && isInstalled;
2067
+ if (needsAlias) {
2068
+ logger5.info(
2069
+ `Peer conflict: ${packageName}@${mainVersion} - ${conflictingRanges.length} incompatible ranges`
2070
+ );
2071
+ }
2072
+ conflicts.push({
2073
+ packageName,
2074
+ mainProjectVersion: mainVersion,
2075
+ requiredRange: this.mergeRequiredRanges(requestedBy),
2076
+ requestedBy,
2077
+ conflictingRanges,
2078
+ hasConflict,
2079
+ needsAlias
2080
+ });
2081
+ }
2082
+ return conflicts;
2083
+ }
2084
+ /**
2085
+ * 获取已安装的包版本(从 node_modules 读取实际版本)
2086
+ * 返回 null 表示包未安装
2087
+ */
2088
+ getMainProjectVersion(packageName) {
2089
+ const { packagePath, pkgJson } = this.resolvePackageJson(packageName, this.options.projectRoot);
2090
+ if (packagePath && pkgJson?.version) {
2091
+ this.installedPackageCache.set(packageName, {
2092
+ name: packageName,
2093
+ version: pkgJson.version,
2094
+ path: packagePath
2095
+ });
2096
+ return pkgJson.version;
2097
+ }
2098
+ const cached = this.injectedInstalledDeps?.get(packageName);
2099
+ if (cached) {
2100
+ return cached.version;
2101
+ }
2102
+ return null;
2103
+ }
2104
+ /**
2105
+ * 合并多个版本范围为描述字符串
2106
+ */
2107
+ mergeRequiredRanges(requests) {
2108
+ const ranges = [...new Set(requests.map((r) => r.requiredRange))];
2109
+ return ranges.join(" || ");
2110
+ }
2111
+ /**
2112
+ * 生成别名映射
2113
+ */
2114
+ async generateAliasMappings(conflicts) {
2115
+ const aliasMappings = [];
2116
+ const usedAliasNames = /* @__PURE__ */ new Set();
2117
+ const aliasNeeded = conflicts.filter((c) => c.needsAlias);
2118
+ const allConflictPackageNames = aliasNeeded.map((c) => c.packageName);
2119
+ for (const conflict of aliasNeeded) {
2120
+ const mappings = await this.createAliasMappingsForConflict(
2121
+ conflict,
2122
+ allConflictPackageNames,
2123
+ usedAliasNames
2124
+ );
2125
+ aliasMappings.push(...mappings);
2126
+ }
2127
+ await linkAliasPeers(
2128
+ aliasMappings,
2129
+ this.options,
2130
+ this.registryClient,
2131
+ this.diagnostics,
2132
+ conflicts,
2133
+ this.watchFiles
2134
+ );
2135
+ return aliasMappings;
2136
+ }
2137
+ /**
2138
+ * 为单个冲突创建别名映射
2139
+ */
2140
+ async createAliasMappingsForConflict(conflict, allConflictPackageNames, usedAliasNames) {
2141
+ const { packageName, conflictingRanges } = conflict;
2142
+ logger5.info(`Creating alias for "${packageName}"`);
2143
+ const workspaceRoot = this.workspaceDetector.getWorkspaceRoot();
2144
+ if (workspaceRoot) {
2145
+ logger5.info(` Workspace root detected: ${workspaceRoot}`);
2146
+ const wsAliases = this.findWorkspaceAliasesForPackage(packageName);
2147
+ if (wsAliases.length > 0) {
2148
+ logger5.info(` Found ${wsAliases.length} workspace alias(es) for ${packageName}:`);
2149
+ for (const a of wsAliases) {
2150
+ logger5.info(
2151
+ ` - ${a.aliasName}: npm:${packageName}@${a.versionSpec} (defined in: ${a.definedIn})`
2152
+ );
2153
+ }
2154
+ } else {
2155
+ logger5.info(
2156
+ ` No workspace aliases found for ${packageName} (expected npm:${packageName}@version format in root package.json)`
2157
+ );
2158
+ }
2159
+ } else {
2160
+ logger5.info(` Not in a monorepo workspace`);
2161
+ }
2162
+ const localAliases = this.existingAliasesMap.get(packageName);
2163
+ if (localAliases && localAliases.length > 0) {
2164
+ logger5.info(` Found ${localAliases.length} local alias(es) for ${packageName}:`);
2165
+ for (const a of localAliases) {
2166
+ logger5.info(
2167
+ ` - ${a.aliasName}: npm:${packageName}@${a.versionSpec} (installed: ${a.installedVersion ?? "not installed"})`
2168
+ );
2169
+ }
2170
+ }
2171
+ const existingAliasNames = this.getExistingAliasNames(packageName);
2172
+ const mappings = [];
2173
+ const installedAliasMatches = this.findInstalledAliasMatches(packageName);
2174
+ const installedAliasesByName = /* @__PURE__ */ new Map();
2175
+ for (const installedAlias of installedAliasMatches) {
2176
+ const aliases = installedAliasesByName.get(installedAlias.name);
2177
+ if (aliases) {
2178
+ aliases.push(installedAlias);
2179
+ } else {
2180
+ installedAliasesByName.set(installedAlias.name, [installedAlias]);
2181
+ }
2182
+ }
2183
+ for (const [aliasName, aliases] of installedAliasesByName) {
2184
+ const identities = new Set(
2185
+ aliases.map(
2186
+ (alias) => `${alias.installedPath ? this.normalizeInstalledPath(alias.installedPath) : alias.scope}\0${alias.version}`
2187
+ )
2188
+ );
2189
+ if (identities.size < 2) continue;
2190
+ this.diagnostics.push({
2191
+ code: "AMBIGUOUS_ALIAS_SCOPE",
2192
+ severity: "error",
2193
+ packageName,
2194
+ aliases: [aliasName],
2195
+ message: "Alias resolves to multiple installed identities: " + aliasName
2196
+ });
2197
+ logger5.warn(
2198
+ `Alias reuse skipped: ${JSON.stringify({
2199
+ code: "AMBIGUOUS_ALIAS_SCOPE",
2200
+ packageName,
2201
+ aliasName,
2202
+ candidates: aliases.map((alias) => ({
2203
+ installedPath: alias.installedPath ?? null,
2204
+ scope: alias.scope,
2205
+ version: alias.version
2206
+ }))
2207
+ })}`
2208
+ );
2209
+ return [];
2210
+ }
2211
+ const reusedAliasGroups = /* @__PURE__ */ new Map();
2212
+ const unresolvedRequests = [];
2213
+ for (const request of conflictingRanges) {
2214
+ const existingAlias = this.findExistingAliasForRanges(
2215
+ packageName,
2216
+ [request.requiredRange],
2217
+ /* @__PURE__ */ new Set()
2218
+ );
2219
+ if (!existingAlias) {
2220
+ unresolvedRequests.push(request);
2221
+ continue;
2222
+ }
2223
+ usedAliasNames.add(existingAlias.name);
2224
+ const aliasIdentity = `${existingAlias.name}\0${existingAlias.installedPath ? this.normalizeInstalledPath(existingAlias.installedPath) : existingAlias.scope}\0${existingAlias.version}`;
2225
+ const reusedGroup = reusedAliasGroups.get(aliasIdentity);
2226
+ if (reusedGroup) {
2227
+ reusedGroup.requests.push(request);
2228
+ } else {
2229
+ reusedAliasGroups.set(aliasIdentity, {
2230
+ alias: existingAlias,
2231
+ requests: [request]
2232
+ });
2233
+ }
2234
+ }
2235
+ const reusedGroupsByAliasName = /* @__PURE__ */ new Map();
2236
+ for (const reusedGroup of reusedAliasGroups.values()) {
2237
+ const groups = reusedGroupsByAliasName.get(reusedGroup.alias.name);
2238
+ if (groups) {
2239
+ groups.push(reusedGroup);
2240
+ } else {
2241
+ reusedGroupsByAliasName.set(reusedGroup.alias.name, [reusedGroup]);
2242
+ }
2243
+ }
2244
+ for (const [aliasName, groups] of reusedGroupsByAliasName) {
2245
+ if (groups.length < 2) continue;
2246
+ this.diagnostics.push({
2247
+ code: "AMBIGUOUS_ALIAS_SCOPE",
2248
+ severity: "error",
2249
+ packageName,
2250
+ aliases: [aliasName],
2251
+ message: "Alias resolves to multiple installed identities: " + aliasName
2252
+ });
2253
+ logger5.warn(
2254
+ `Alias reuse skipped: ${JSON.stringify({
2255
+ code: "AMBIGUOUS_ALIAS_SCOPE",
2256
+ packageName,
2257
+ aliasName,
2258
+ candidates: groups.map(({ alias, requests }) => ({
2259
+ installedPath: alias.installedPath ?? null,
2260
+ scope: alias.scope,
2261
+ version: alias.version,
2262
+ requesters: requests.map((request) => request.path.join(">"))
2263
+ }))
2264
+ })}`
2265
+ );
2266
+ return [];
2267
+ }
2268
+ for (const reusedGroup of reusedAliasGroups.values()) {
2269
+ mappings.push(
2270
+ this.buildAliasMapping(
2271
+ packageName,
2272
+ reusedGroup.alias.name,
2273
+ reusedGroup.alias.version,
2274
+ "",
2275
+ // 不需要安装
2276
+ reusedGroup.requests,
2277
+ allConflictPackageNames
2278
+ )
2279
+ );
2280
+ }
2281
+ if (unresolvedRequests.length === 0) {
2282
+ return mappings;
2283
+ }
2284
+ if (this.options.offline) {
2285
+ this.diagnostics.push({
2286
+ code: "OFFLINE_ALIAS_MISSING",
2287
+ severity: "error",
2288
+ packageName,
2289
+ requestedBy: unresolvedRequests.map((request) => request.path.join(">")),
2290
+ message: "No installed alias satisfies " + packageName + " in offline mode"
2291
+ });
2292
+ return mappings;
2293
+ }
2294
+ let versions;
2295
+ try {
2296
+ versions = await this.registryClient.fetchAllVersions(packageName, this.options.registry);
2297
+ } catch (error) {
2298
+ this.diagnostics.push({
2299
+ code: "REGISTRY_ERROR",
2300
+ severity: "error",
2301
+ packageName,
2302
+ message: "Failed to fetch versions for " + packageName + ": " + String(error)
2303
+ });
2304
+ logger5.warn(`Failed to fetch versions for ${packageName}: ${String(error)}`);
2305
+ return mappings;
2306
+ }
2307
+ if (versions.length === 0) {
2308
+ this.diagnostics.push({
2309
+ code: "NO_MATCHING_VERSION",
2310
+ severity: "error",
2311
+ packageName,
2312
+ message: "No versions available for " + packageName
2313
+ });
2314
+ logger5.warn(`No versions found for ${packageName}`);
2315
+ return mappings;
2316
+ }
2317
+ for (const request of unresolvedRequests) {
2318
+ if (!versions.some((version) => satisfies(version, request.requiredRange))) {
2319
+ this.diagnostics.push({
2320
+ code: "NO_MATCHING_VERSION",
2321
+ severity: "error",
2322
+ packageName,
2323
+ requestedBy: request.path,
2324
+ message: "No available version satisfies " + packageName + "@" + request.requiredRange
2325
+ });
2326
+ }
2327
+ }
2328
+ const rangeGroups = this.groupRangesByCompatibility(unresolvedRequests, versions);
2329
+ logger5.info(`Creating alias for "${packageName}": ${rangeGroups.length} version groups`);
2330
+ for (let i = 0; i < rangeGroups.length; i++) {
2331
+ const group = rangeGroups[i];
2332
+ if (!group || group.length === 0) continue;
2333
+ const groupRanges = [...new Set(group.map((r) => r.requiredRange))];
2334
+ logger5.debug(` Group ${i + 1}: ${groupRanges.join(", ")}`);
2335
+ const mapping = this.createAliasMappingForGroup(
2336
+ packageName,
2337
+ group,
2338
+ groupRanges,
2339
+ versions,
2340
+ existingAliasNames,
2341
+ usedAliasNames,
2342
+ allConflictPackageNames
2343
+ );
2344
+ if (mapping) {
2345
+ mappings.push(mapping);
2346
+ usedAliasNames.add(mapping.aliasName);
2347
+ }
2348
+ }
2349
+ return mappings;
2350
+ }
2351
+ /**
2352
+ * 按范围兼容性分组
2353
+ * 有交集的范围放在一组,互斥的分开
2354
+ */
2355
+ groupRangesByCompatibility(requests, availableVersions) {
2356
+ const groups = [];
2357
+ const orderedRequests = requests.map((request, index) => ({
2358
+ request,
2359
+ index,
2360
+ satisfyingVersionCount: availableVersions.filter(
2361
+ (version) => satisfies(version, request.requiredRange)
2362
+ ).length
2363
+ })).sort(
2364
+ (left, right) => left.satisfyingVersionCount - right.satisfyingVersionCount || left.index - right.index
2365
+ );
2366
+ for (const { request } of orderedRequests) {
2367
+ let added = false;
2368
+ for (const group of groups) {
2369
+ const proposedRanges = [...group, request].map((item) => item.requiredRange);
2370
+ const canJoin = findBestVersion(availableVersions, proposedRanges) !== null;
2371
+ if (canJoin) {
2372
+ group.push(request);
2373
+ added = true;
2374
+ break;
2375
+ }
2376
+ }
2377
+ if (!added) {
2378
+ if (findBestVersion(availableVersions, [request.requiredRange]) === null) {
2379
+ continue;
2380
+ }
2381
+ groups.push([request]);
2382
+ }
2383
+ }
2384
+ return groups;
2385
+ }
2386
+ /**
2387
+ * 为一个兼容组创建别名映射
2388
+ */
2389
+ createAliasMappingForGroup(packageName, group, groupRanges, versions, existingAliasNames, usedAliasNames, allConflictPackageNames) {
2390
+ const existingAlias = this.findExistingAliasForRanges(packageName, groupRanges, usedAliasNames);
2391
+ if (existingAlias) {
2392
+ logger5.debug(
2393
+ ` Reusing: ${existingAlias.name}@${existingAlias.version}${existingAlias.isWorkspaceAlias ? " (workspace)" : ""}`
2394
+ );
2395
+ return this.buildAliasMapping(
2396
+ packageName,
2397
+ existingAlias.name,
2398
+ existingAlias.version,
2399
+ "",
2400
+ // 不需要安装
2401
+ group,
2402
+ allConflictPackageNames
2403
+ );
2404
+ }
2405
+ const bestVersion = findBestVersion(versions, groupRanges);
2406
+ if (!bestVersion) {
2407
+ logger5.warn(
2408
+ ` No version satisfies all ranges [${groupRanges.join(", ")}] for ${packageName}`
2409
+ );
2410
+ return null;
2411
+ }
2412
+ const combinedExisting = /* @__PURE__ */ new Set([
2413
+ ...existingAliasNames,
2414
+ ...usedAliasNames,
2415
+ ...this.getReservedDependencyNames()
2416
+ ]);
2417
+ const aliasName = this.generateUniqueAliasName(packageName, bestVersion, combinedExisting);
2418
+ const installSpec = createAliasInstallSpec(aliasName, packageName, bestVersion);
2419
+ logger5.info(` New alias: ${aliasName}@${bestVersion}`);
2420
+ return this.buildAliasMapping(
2421
+ packageName,
2422
+ aliasName,
2423
+ bestVersion,
2424
+ installSpec,
2425
+ group,
2426
+ allConflictPackageNames
2427
+ );
2428
+ }
2429
+ /**
2430
+ * 构建 AliasMapping 对象
2431
+ */
2432
+ buildAliasMapping(packageName, aliasName, version, installSpec, group, allConflictPackageNames) {
2433
+ const usedBy = group.map((r) => r.path.join(">"));
2434
+ const usedByRoots = [
2435
+ ...new Set(group.map((r) => r.path[0]).filter((p) => p !== void 0))
2436
+ ];
2437
+ const graphInstances = this.collectGraphRelatedPackageInstances(
2438
+ usedByRoots,
2439
+ allConflictPackageNames
2440
+ );
2441
+ const allDependents = graphInstances ? [...new Set(graphInstances.map((instance) => instance.name))] : this.collectAllRelatedPackages(usedByRoots, allConflictPackageNames);
2442
+ return {
2443
+ originalName: packageName,
2444
+ aliasName,
2445
+ installSpec,
2446
+ resolvedVersion: version,
2447
+ usedBy,
2448
+ allDependents,
2449
+ ...graphInstances && graphInstances.length > 0 ? { importerPaths: [...new Set(graphInstances.map((instance) => instance.path))] } : {}
2450
+ };
2451
+ }
2452
+ /**
2453
+ * 收集所有已安装的现有别名,不按请求版本范围过滤。
2454
+ * 用于在范围筛选前识别同名 alias 的多路径/多版本歧义。
2455
+ */
2456
+ findInstalledAliasMatches(packageName) {
2457
+ const matches = [];
2458
+ const npmAliases = this.existingAliasesMap.get(packageName) ?? [];
2459
+ for (const alias of npmAliases) {
2460
+ alias.installedVersion ??= this.getAliasInstalledVersion(alias.aliasName);
2461
+ if (!alias.installedVersion) continue;
2462
+ const installedAlias = this.installedPackageCache.get(alias.aliasName);
2463
+ if (installedAlias?.realName !== packageName) continue;
2464
+ matches.push({
2465
+ name: alias.aliasName,
2466
+ version: alias.installedVersion,
2467
+ installedPath: installedAlias?.path,
2468
+ scope: "local"
2469
+ });
2470
+ }
2471
+ const workspaceAliases = this.findWorkspaceAliasesForPackage(packageName);
2472
+ const workspaceRoot = this.workspaceDetector.getWorkspaceRoot();
2473
+ for (const wsAlias of workspaceAliases) {
2474
+ let installedVersion = null;
2475
+ let installedPath;
2476
+ if (workspaceRoot) {
2477
+ const { packagePath, pkgJson } = this.resolvePackageJson(wsAlias.aliasName, workspaceRoot);
2478
+ if (packagePath) {
2479
+ if (pkgJson?.name !== packageName) continue;
2480
+ installedVersion = pkgJson?.version ?? null;
2481
+ installedPath = packagePath;
2482
+ }
2483
+ }
2484
+ if (!installedVersion) {
2485
+ installedVersion = this.getAliasInstalledVersion(wsAlias.aliasName);
2486
+ if (installedVersion) {
2487
+ const installedAlias = this.installedPackageCache.get(wsAlias.aliasName);
2488
+ installedPath = installedAlias?.path;
2489
+ if (installedAlias?.realName !== packageName) continue;
2490
+ }
2491
+ }
2492
+ if (installedVersion) {
2493
+ matches.push({
2494
+ name: wsAlias.aliasName,
2495
+ version: installedVersion,
2496
+ isWorkspaceAlias: true,
2497
+ installedPath,
2498
+ scope: "workspace"
2499
+ });
2500
+ }
2501
+ }
2502
+ return matches;
2503
+ }
2504
+ /**
2505
+ * 查找满足指定范围的现有别名(排除已使用的)
2506
+ * 优先查找当前项目的别名,然后查找 workspace 级别的别名
2507
+ */
2508
+ findExistingAliasForRanges(packageName, ranges, excludeAliases) {
2509
+ logger5.debug(
2510
+ ` Searching for existing alias for ${packageName} satisfying ranges: [${ranges.join(", ")}]`
2511
+ );
2512
+ const npmAliases = this.existingAliasesMap.get(packageName);
2513
+ if (npmAliases && npmAliases.length > 0) {
2514
+ logger5.debug(` Checking ${npmAliases.length} local alias(es)...`);
2515
+ for (const alias of npmAliases) {
2516
+ if (excludeAliases.has(alias.aliasName)) {
2517
+ logger5.debug(` Skip ${alias.aliasName}: already used`);
2518
+ continue;
2519
+ }
2520
+ alias.installedVersion ??= this.getAliasInstalledVersion(alias.aliasName);
2521
+ if (!alias.installedVersion) {
2522
+ logger5.debug(` Skip ${alias.aliasName}: not installed`);
2523
+ continue;
2524
+ }
2525
+ const installedAlias = this.installedPackageCache.get(alias.aliasName);
2526
+ if (installedAlias?.realName !== packageName) {
2527
+ logger5.debug(
2528
+ ` Skip ${alias.aliasName}: installed package name ${installedAlias?.realName ?? "unknown"} does not match ${packageName}`
2529
+ );
2530
+ continue;
2531
+ }
2532
+ const allSatisfied = ranges.every((range) => satisfies(alias.installedVersion, range));
2533
+ if (allSatisfied) {
2534
+ logger5.info(` Reusing local alias: ${alias.aliasName}@${alias.installedVersion}`);
2535
+ return {
2536
+ name: alias.aliasName,
2537
+ version: alias.installedVersion,
2538
+ installedPath: installedAlias?.path,
2539
+ scope: "local"
2540
+ };
2541
+ } else {
2542
+ logger5.debug(
2543
+ ` Skip ${alias.aliasName}@${alias.installedVersion}: version doesn't satisfy all ranges`
2544
+ );
2545
+ }
2546
+ }
2547
+ }
2548
+ const workspaceAliases = this.findWorkspaceAliasesForPackage(packageName);
2549
+ if (workspaceAliases.length > 0) {
2550
+ logger5.debug(` Checking ${workspaceAliases.length} workspace alias(es)...`);
2551
+ }
2552
+ for (const wsAlias of workspaceAliases) {
2553
+ if (excludeAliases.has(wsAlias.aliasName)) {
2554
+ logger5.debug(` Skip ${wsAlias.aliasName}: already used`);
2555
+ continue;
2556
+ }
2557
+ const { packagePath, pkgJson } = this.resolvePackageJson(
2558
+ wsAlias.aliasName,
2559
+ this.options.projectRoot
2560
+ );
2561
+ if (!packagePath || pkgJson?.name !== packageName || !pkgJson.version) continue;
2562
+ const installedVersion = pkgJson.version;
2563
+ if (ranges.every((range) => satisfies(installedVersion, range))) {
2564
+ logger5.info(` Reusing workspace alias: ${wsAlias.aliasName}@${installedVersion}`);
2565
+ return {
2566
+ name: wsAlias.aliasName,
2567
+ version: installedVersion,
2568
+ isWorkspaceAlias: true,
2569
+ installedPath: packagePath,
2570
+ scope: "workspace"
2571
+ };
2572
+ }
2573
+ }
2574
+ logger5.debug(` No existing alias found for ${packageName}`);
2575
+ return null;
2576
+ }
2577
+ /**
2578
+ * 查找 workspace 级别的别名(带缓存)
2579
+ */
2580
+ findWorkspaceAliasesForPackage(packageName) {
2581
+ if (this.workspaceAliasesCache.has(packageName)) {
2582
+ return this.workspaceAliasesCache.get(packageName);
2583
+ }
2584
+ const aliases = this.workspaceDetector.findWorkspaceAliases(packageName);
2585
+ this.workspaceAliasesCache.set(packageName, aliases);
2586
+ return aliases;
2587
+ }
2588
+ /**
2589
+ * 生成唯一的别名名称,避免与已存在的别名冲突
2590
+ */
2591
+ generateUniqueAliasName(packageName, version, existingNames) {
2592
+ const baseName = `${this.options.aliasPrefix}${generateAliasName(packageName, version)}`;
2593
+ if (!existingNames.has(baseName)) {
2594
+ return baseName;
2595
+ }
2596
+ const versionSuffix = version.replace(/\./g, "-");
2597
+ const nameWithVersion = `${this.options.aliasPrefix}${packageName.replace(/^@/, "").replace(/\//g, "-")}-${versionSuffix}`;
2598
+ if (!existingNames.has(nameWithVersion)) {
2599
+ return nameWithVersion;
2600
+ }
2601
+ let counter = 2;
2602
+ while (existingNames.has(`${baseName}-${counter}`)) {
2603
+ counter++;
2604
+ }
2605
+ return `${baseName}-${counter}`;
2606
+ }
2607
+ /**
2608
+ * 获取包的所有已存在的别名名称(不管版本是否符合)
2609
+ * 用于生成新别名时避免命名冲突
2610
+ *
2611
+ * 包含当前项目和 workspace 级别的别名
2612
+ */
2613
+ getExistingAliasNames(packageName) {
2614
+ const names = /* @__PURE__ */ new Set();
2615
+ const npmAliases = this.existingAliasesMap.get(packageName);
2616
+ if (npmAliases) {
2617
+ for (const alias of npmAliases) {
2618
+ names.add(alias.aliasName);
2619
+ }
2620
+ }
2621
+ const workspaceAliases = this.findWorkspaceAliasesForPackage(packageName);
2622
+ for (const wsAlias of workspaceAliases) {
2623
+ names.add(wsAlias.aliasName);
2624
+ }
2625
+ return names;
2626
+ }
2627
+ /**
2628
+ * Return every dependency key that the host or its workspace root owns.
2629
+ *
2630
+ * Generated aliases share the package namespace with ordinary dependency
2631
+ * keys. Keeping the complete set here prevents a generated alias from
2632
+ * silently replacing an unrelated dependency declared by the user.
2633
+ */
2634
+ getReservedDependencyNames() {
2635
+ this.ensureWorkspaceRootDeclaredDepsLoaded();
2636
+ return /* @__PURE__ */ new Set([
2637
+ ...Object.keys(this.rawDeclaredDeps),
2638
+ ...Object.keys(this.declaredDeps),
2639
+ ...Object.keys(this.workspaceRootDeclaredDeps)
2640
+ ]);
2641
+ }
2642
+ normalizeInstalledPath(packagePath) {
2643
+ try {
2644
+ return realpathSync(packagePath);
2645
+ } catch {
2646
+ return resolve(packagePath);
2647
+ }
2648
+ }
2649
+ findGraphChildNode(parent, dependencyName) {
2650
+ if (!this.dependencyGraph) return null;
2651
+ const childId = parent.resolvedChildren.get(dependencyName);
2652
+ return childId ? this.dependencyGraph.nodes.get(childId) ?? null : null;
2653
+ }
2654
+ /**
2655
+ * 收集图中指定根实例的所有后代实例。返回 null 表示当前分析没有
2656
+ * 对应的图根,调用方可为兼容旧测试/旧调用回退到名称遍历。
2657
+ */
2658
+ collectGraphRelatedPackageInstances(packageNames, excludePackages = []) {
2659
+ if (!this.dependencyGraph) return null;
2660
+ const roots = packageNames.map((packageName) => this.findGraphRoot(packageName)).filter((node) => node !== null);
2661
+ if (roots.length === 0) return null;
2662
+ const excludeSet = new Set(excludePackages);
2663
+ const visited = /* @__PURE__ */ new Set();
2664
+ const collected = [];
2665
+ const stack = roots.map((root) => root.id);
2666
+ while (stack.length > 0) {
2667
+ const nodeId = stack.pop();
2668
+ if (!nodeId || visited.has(nodeId)) continue;
2669
+ visited.add(nodeId);
2670
+ const node = this.dependencyGraph.nodes.get(nodeId);
2671
+ if (!node || excludeSet.has(node.name)) continue;
2672
+ collected.push({ name: node.name, path: node.packagePath });
2673
+ for (const dependencyName of [...node.dependencyNames, ...node.peerDependencyNames]) {
2674
+ const child = this.findGraphChildNode(node, dependencyName);
2675
+ if (child && !visited.has(child.id)) stack.push(child.id);
2676
+ }
2677
+ }
2678
+ return collected;
2679
+ }
2680
+ /**
2681
+ * 递归收集指定包的所有子依赖(dependencies + peerDependencies)
2682
+ *
2683
+ * 用于构建 allDependents 列表,这些包引用冲突依赖时都需要做重定向解析
2684
+ *
2685
+ * 逻辑说明:
2686
+ * - 冲突检测:只检测第一层依赖的 peerDependencies 与主工程的冲突
2687
+ * - 重定向范围:声明冲突 peerDep 的包及其所有子依赖都需要重定向
2688
+ * 因为这些子依赖内部引用冲突包时,也需要解析到别名版本
2689
+ * - 遇到冲突包(excludeTraversal)时,不加入 collected 也不遍历其子树,
2690
+ * 因为 analyzedDependencies 中存储的是主项目安装的版本(而非冲突库实际需要的版本),
2691
+ * 遍历它们会引入无关包(如 vue-router@5 的 peerDep pinia)
2692
+ *
2693
+ * 性能优化:优先从 analyzedDependencies 内存数据中读取,避免重复磁盘 I/O
2694
+ */
2695
+ collectAllSubDependenciesRecursive(packageName, visited, collected, baseDir, excludeTraversal) {
2696
+ const stack = [{ name: packageName, baseDir }];
2697
+ while (stack.length > 0) {
2698
+ const item = stack.pop();
2699
+ if (!item) break;
2700
+ const name = item.name;
2701
+ const currentBaseDir = item.baseDir;
2702
+ if (excludeTraversal?.has(name)) {
2703
+ continue;
2704
+ }
2705
+ collected.add(name);
2706
+ const analyzed = this.analyzedDependencies.get(name);
2707
+ if (analyzed) {
2708
+ if (visited.has(name)) {
2709
+ continue;
2710
+ }
2711
+ visited.add(name);
2712
+ for (const depName of Object.keys(analyzed.dependencies)) {
2713
+ stack.push({ name: depName, baseDir: currentBaseDir });
2714
+ }
2715
+ for (const peerName of Object.keys(analyzed.peerDependencies)) {
2716
+ stack.push({ name: peerName, baseDir: currentBaseDir });
2717
+ }
2718
+ continue;
2719
+ }
2720
+ const { packagePath, pkgJson } = this.resolvePackageJson(name, currentBaseDir);
2721
+ if (!packagePath) {
2722
+ logger5.debug(
2723
+ `Package not found for dependency collection: ${name} (from ${currentBaseDir})`
2724
+ );
2725
+ continue;
2726
+ }
2727
+ if (visited.has(packagePath)) {
2728
+ continue;
2729
+ }
2730
+ visited.add(packagePath);
2731
+ if (!pkgJson) {
2732
+ continue;
2733
+ }
2734
+ const deps = { ...pkgJson.dependencies, ...pkgJson.optionalDependencies };
2735
+ const peerDeps = pkgJson.peerDependencies ?? {};
2736
+ for (const depName of Object.keys(deps)) {
2737
+ stack.push({ name: depName, baseDir: packagePath });
2738
+ }
2739
+ for (const peerName of Object.keys(peerDeps)) {
2740
+ stack.push({ name: peerName, baseDir: packagePath });
2741
+ }
2742
+ }
2743
+ }
2744
+ /**
2745
+ * 收集多个包的所有子依赖(用于 allDependents)
2746
+ * 包括 dependencies 和 peerDependencies 递归下去的所有包
2747
+ */
2748
+ collectAllRelatedPackages(packageNames, excludePackages = []) {
2749
+ const cacheKey = JSON.stringify([packageNames.slice().sort(), excludePackages.slice().sort()]);
2750
+ const cached = this.collectCache.get(cacheKey);
2751
+ if (cached) {
2752
+ return cached;
2753
+ }
2754
+ const graphInstances = this.collectGraphRelatedPackageInstances(packageNames, excludePackages);
2755
+ if (graphInstances) {
2756
+ const result2 = [...new Set(graphInstances.map((instance) => instance.name))];
2757
+ this.collectCache.set(cacheKey, result2);
2758
+ return result2;
2759
+ }
2760
+ const collected = /* @__PURE__ */ new Set();
2761
+ const visited = /* @__PURE__ */ new Set();
2762
+ const excludeSet = new Set(excludePackages);
2763
+ for (const pkgName of packageNames) {
2764
+ this.collectAllSubDependenciesRecursive(
2765
+ pkgName,
2766
+ visited,
2767
+ collected,
2768
+ this.options.projectRoot,
2769
+ excludeSet
2770
+ );
2771
+ }
2772
+ for (const excludePkg of excludeSet) {
2773
+ collected.delete(excludePkg);
2774
+ }
2775
+ const result = Array.from(collected);
2776
+ this.collectCache.set(cacheKey, result);
2777
+ return result;
2778
+ }
2779
+ /**
2780
+ * 找出第一层依赖中缺失的 peer 依赖(无冲突)
2781
+ * 复用 collectFirstLevelPeerDependencies 已收集的 peerDepsMap,避免重复遍历
2782
+ */
2783
+ findMissingFirstLevelPeers(peerDepsMap) {
2784
+ const missing = [];
2785
+ for (const [peerName, requests] of peerDepsMap) {
2786
+ if (this.isDeclaredInMainProject(peerName)) {
2787
+ continue;
2788
+ }
2789
+ for (const request of requests) {
2790
+ const requestedBy = request.path[0];
2791
+ if (!requestedBy) continue;
2792
+ const depInfo = this.analyzedDependencies.get(requestedBy);
2793
+ const isOptional = depInfo?.peerDependenciesMeta?.[peerName]?.optional === true;
2794
+ if (isOptional) {
2795
+ continue;
2796
+ }
2797
+ missing.push({
2798
+ packageName: peerName,
2799
+ requiredRange: request.requiredRange,
2800
+ requestedBy
2801
+ });
2802
+ }
2803
+ }
2804
+ return missing;
2805
+ }
2806
+ };
2807
+ function createDependencyAnalyzer(options, preparedAliases = []) {
2808
+ const mainPackageJson = readPackageJsonCached(options.projectRoot);
2809
+ if (!mainPackageJson) {
2810
+ throw new Error(`Could not read package.json at ${options.projectRoot}`);
2811
+ }
2812
+ const declared = {
2813
+ ...mainPackageJson.dependencies,
2814
+ ...mainPackageJson.devDependencies,
2815
+ ...mainPackageJson.optionalDependencies
2816
+ };
2817
+ const additional = Object.fromEntries(
2818
+ preparedAliases.filter((mapping) => !Object.hasOwn(declared, mapping.aliasName)).map((mapping) => [
2819
+ mapping.aliasName,
2820
+ "npm:" + mapping.originalName + "@" + mapping.resolvedVersion
2821
+ ])
2822
+ );
2823
+ return new DependencyAnalyzer(options, {
2824
+ ...mainPackageJson,
2825
+ devDependencies: { ...additional, ...mainPackageJson.devDependencies }
2826
+ });
2827
+ }
2828
+ var logger6 = createLogger("package-manager-adapter");
2829
+ var PACKAGE_MANAGER_ENTRYPOINT_RULES = {
2830
+ npm: {
2831
+ cliVariables: ["NPM_CLI_JS"],
2832
+ cliBasenames: ["npm-cli.js", "npm.js"]
2833
+ },
2834
+ pnpm: {
2835
+ cliVariables: ["PNPM_CLI_JS"],
2836
+ cliBasenames: ["pnpm.cjs", "pnpm.js"]
2837
+ },
2838
+ yarn: {
2839
+ cliVariables: ["YARN_CLI_JS"],
2840
+ cliBasenames: ["yarn.js", "yarn.cjs"]
2841
+ }
2842
+ };
2843
+ var DEFAULT_TIMING = {
2844
+ timeoutMs: 12e4,
2845
+ terminateGraceMs: 5e3
2846
+ };
2847
+ function createPackageManagerAdapter(options, timing = DEFAULT_TIMING) {
2848
+ return {
2849
+ install: async (specs) => {
2850
+ const env = registryEnvironment(options.packageManager, options.registry);
2851
+ if (specs.length === 0) {
2852
+ return {
2853
+ success: true,
2854
+ exitCode: 0,
2855
+ stdout: "",
2856
+ stderr: "",
2857
+ timedOut: false
2858
+ };
2859
+ }
2860
+ const { command, args } = buildCommand(options.packageManager, specs, env);
2861
+ logger6.info(`Running: ${command} ${args.map((arg) => JSON.stringify(arg)).join(" ")}`);
2862
+ const child = spawn(command, args, {
2863
+ cwd: options.projectRoot,
2864
+ env,
2865
+ shell: false,
2866
+ stdio: ["ignore", "pipe", "pipe"],
2867
+ ...process.platform === "win32" ? {} : { detached: true }
2868
+ });
2869
+ return new Promise((resolve5) => {
2870
+ let stdout = "";
2871
+ let stderr = "";
2872
+ let terminalError;
2873
+ let timedOut = false;
2874
+ let settled = false;
2875
+ let closeSeen = false;
2876
+ let timeoutId;
2877
+ let graceId;
2878
+ const clearTimers = () => {
2879
+ if (timeoutId !== void 0) {
2880
+ clearTimeout(timeoutId);
2881
+ }
2882
+ if (graceId !== void 0) {
2883
+ clearTimeout(graceId);
2884
+ }
2885
+ };
2886
+ const finish = (exitCode) => {
2887
+ if (settled) {
2888
+ return;
2889
+ }
2890
+ settled = true;
2891
+ clearTimers();
2892
+ resolve5({
2893
+ success: !timedOut && !terminalError && exitCode === 0,
2894
+ exitCode,
2895
+ stdout,
2896
+ stderr: stderr || (terminalError?.message ?? ""),
2897
+ timedOut
2898
+ });
2899
+ };
2900
+ child.stdout?.on("data", (data) => {
2901
+ stdout += data.toString();
2902
+ });
2903
+ child.stderr?.on("data", (data) => {
2904
+ stderr += data.toString();
2905
+ });
2906
+ child.on("error", (error) => {
2907
+ terminalError = error;
2908
+ });
2909
+ child.on("close", (exitCode) => {
2910
+ closeSeen = true;
2911
+ finish(exitCode);
2912
+ });
2913
+ timeoutId = setTimeout(() => {
2914
+ if (settled || closeSeen) {
2915
+ return;
2916
+ }
2917
+ timedOut = true;
2918
+ logger6.error(`Install timeout after ${timing.timeoutMs / 1e3}s`);
2919
+ sendTerminationSignal(child, "SIGTERM");
2920
+ graceId = setTimeout(() => {
2921
+ if (!settled && !closeSeen) {
2922
+ terminateProcessTree(child);
2923
+ }
2924
+ }, timing.terminateGraceMs);
2925
+ }, timing.timeoutMs);
2926
+ });
2927
+ }
2928
+ };
2929
+ }
2930
+ function buildCommand(packageManager, specs, environment) {
2931
+ const invocation = resolvePackageManagerInvocation(packageManager, process.platform, environment);
2932
+ switch (packageManager) {
2933
+ case "pnpm":
2934
+ return {
2935
+ command: invocation.command,
2936
+ args: [...invocation.argsPrefix, "add", "--save-exact", ...specs]
2937
+ };
2938
+ case "yarn":
2939
+ return {
2940
+ command: invocation.command,
2941
+ args: [...invocation.argsPrefix, "add", "--exact", ...specs]
2942
+ };
2943
+ case "npm":
2944
+ return {
2945
+ command: invocation.command,
2946
+ args: [...invocation.argsPrefix, "install", "--legacy-peer-deps", "--save-exact", ...specs]
2947
+ };
2948
+ }
2949
+ throw new Error(`Unsupported package manager: ${String(packageManager)}`);
2950
+ }
2951
+ function resolvePackageManagerCommand(packageManager, platform = process.platform) {
2952
+ return platform === "win32" ? `${packageManager}.cmd` : packageManager;
2953
+ }
2954
+ function resolvePackageManagerInvocation(packageManager, platform = process.platform, environment = process.env) {
2955
+ if (platform !== "win32") {
2956
+ return {
2957
+ command: resolvePackageManagerCommand(packageManager, platform),
2958
+ argsPrefix: []
2959
+ };
2960
+ }
2961
+ const windowsInvocation = resolveWindowsPackageManagerInvocation(packageManager, environment);
2962
+ if (!windowsInvocation) {
2963
+ throw new Error(`Could not resolve a Node entrypoint for ${packageManager}`);
2964
+ }
2965
+ return windowsInvocation;
2966
+ }
2967
+ function resolveWindowsPackageManagerInvocation(packageManager, environment) {
2968
+ const npmExecPath = getEnvironmentValue(environment, "npm_execpath");
2969
+ if (npmExecPath && matchesPackageManagerPath(packageManager, npmExecPath)) {
2970
+ const invocation = invocationFromPackageManagerPath(packageManager, npmExecPath, "win32");
2971
+ if (invocation) {
2972
+ return invocation;
2973
+ }
2974
+ }
2975
+ const pathValue = getEnvironmentValue(environment, "PATH");
2976
+ if (!pathValue) {
2977
+ return void 0;
2978
+ }
2979
+ for (const directory of pathValue.split(";")) {
2980
+ if (!directory) {
2981
+ continue;
2982
+ }
2983
+ const shimPath = win32.join(directory, `${packageManager}.cmd`);
2984
+ if (existsSync(shimPath)) {
2985
+ const invocation = invocationFromPackageManagerPath(packageManager, shimPath, "win32");
2986
+ if (invocation) {
2987
+ return invocation;
2988
+ }
2989
+ }
2990
+ const executablePath = win32.join(directory, `${packageManager}.exe`);
2991
+ if (existsSync(executablePath)) {
2992
+ return { command: executablePath, argsPrefix: [] };
2993
+ }
2994
+ }
2995
+ return void 0;
2996
+ }
2997
+ function invocationFromPackageManagerPath(packageManager, packageManagerPath, platform) {
2998
+ const lowerPath = packageManagerPath.toLowerCase();
2999
+ if (lowerPath.endsWith(".exe")) {
3000
+ return { command: packageManagerPath, argsPrefix: [] };
3001
+ }
3002
+ if (lowerPath.endsWith(".cmd") || lowerPath.endsWith(".bat")) {
3003
+ const entrypoint = parseWindowsShimEntrypoint(packageManager, packageManagerPath, platform);
3004
+ if (!entrypoint) {
3005
+ return void 0;
3006
+ }
3007
+ return { command: process.execPath, argsPrefix: [entrypoint] };
3008
+ }
3009
+ if (isJavaScriptEntrypoint(packageManagerPath)) {
3010
+ return { command: process.execPath, argsPrefix: [packageManagerPath] };
3011
+ }
3012
+ return void 0;
3013
+ }
3014
+ function parseWindowsShimEntrypoint(packageManager, shimPath, platform) {
3015
+ let shimContents;
3016
+ try {
3017
+ shimContents = readFileSync(shimPath, "utf8");
3018
+ } catch (error) {
3019
+ logger6.debug(`Failed to read ${packageManager} shim: ${String(error)}`);
3020
+ return void 0;
3021
+ }
3022
+ const assignments = parseWindowsShimAssignments(shimContents);
3023
+ const rule = PACKAGE_MANAGER_ENTRYPOINT_RULES[packageManager];
3024
+ const allowedVariables = new Set(rule.cliVariables);
3025
+ for (const variable of rule.cliVariables) {
3026
+ const values = assignments.get(variable);
3027
+ if (!values) {
3028
+ continue;
3029
+ }
3030
+ for (const value of values) {
3031
+ const entrypoint = resolveShimTarget(
3032
+ value,
3033
+ assignments,
3034
+ shimPath,
3035
+ platform,
3036
+ allowedVariables
3037
+ );
3038
+ if (entrypoint && isKnownPackageManagerEntrypoint(packageManager, entrypoint)) {
3039
+ return entrypoint;
3040
+ }
3041
+ }
3042
+ }
3043
+ const directTargetPattern = /"((?:%~dp0|%dp0%)[\\/][^"\r\n]+\.(?:js|cjs|mjs))"/gi;
3044
+ for (const match of shimContents.matchAll(directTargetPattern)) {
3045
+ const target = match[1];
3046
+ if (target) {
3047
+ const entrypoint = resolveShimTarget(
3048
+ target,
3049
+ assignments,
3050
+ shimPath,
3051
+ platform,
3052
+ allowedVariables
3053
+ );
3054
+ if (entrypoint && isKnownPackageManagerEntrypoint(packageManager, entrypoint)) {
3055
+ return entrypoint;
3056
+ }
3057
+ }
3058
+ }
3059
+ const absoluteTargetPattern = /"([A-Za-z]:[\\/][^"\r\n]+\.(?:js|cjs|mjs))"/gi;
3060
+ for (const match of shimContents.matchAll(absoluteTargetPattern)) {
3061
+ const target = match[1];
3062
+ if (target) {
3063
+ const entrypoint = resolveShimTarget(
3064
+ target,
3065
+ assignments,
3066
+ shimPath,
3067
+ platform,
3068
+ allowedVariables
3069
+ );
3070
+ if (entrypoint && isKnownPackageManagerEntrypoint(packageManager, entrypoint)) {
3071
+ return entrypoint;
3072
+ }
3073
+ }
3074
+ }
3075
+ return void 0;
3076
+ }
3077
+ function parseWindowsShimAssignments(contents) {
3078
+ const assignments = /* @__PURE__ */ new Map();
3079
+ const assignmentPattern = /^\s*@?set\s+(?:"([A-Za-z_][A-Za-z0-9_]*)=([^"\r\n]*)"|([A-Za-z_][A-Za-z0-9_]*)=([^\r\n]*))\s*$/gim;
3080
+ for (const match of contents.matchAll(assignmentPattern)) {
3081
+ const name = (match[1] ?? match[3])?.toUpperCase();
3082
+ const value = (match[2] ?? match[4])?.trim();
3083
+ if (name && value !== void 0) {
3084
+ const values = assignments.get(name) ?? [];
3085
+ values.push(value);
3086
+ assignments.set(name, values);
3087
+ }
3088
+ }
3089
+ return assignments;
3090
+ }
3091
+ function resolveShimTarget(rawTarget, assignments, shimPath, platform, allowedVariables, seenVariables = /* @__PURE__ */ new Set()) {
3092
+ const target = rawTarget.trim().replace(/^"|"$/g, "");
3093
+ const markerMatch = target.match(/^%(?:~dp0|dp0%)([\\/].*)$/i);
3094
+ if (markerMatch?.[1]) {
3095
+ const pathModule = win32 ;
3096
+ const relativeTarget = markerMatch[1].replace(/^[\\/]/, "");
3097
+ const resolvedTarget = pathModule.resolve(pathModule.dirname(shimPath), relativeTarget);
3098
+ return isJavaScriptEntrypoint(resolvedTarget) ? resolvedTarget : void 0;
3099
+ }
3100
+ const variableMatch = target.match(/^%([A-Za-z_][A-Za-z0-9_]*)%([\\/].*)?$/);
3101
+ if (variableMatch?.[1]) {
3102
+ const variable = variableMatch[1].toUpperCase();
3103
+ if (!allowedVariables.has(variable)) {
3104
+ return void 0;
3105
+ }
3106
+ if (seenVariables.has(variable)) {
3107
+ return void 0;
3108
+ }
3109
+ const assignedValues = assignments.get(variable);
3110
+ if (!assignedValues) {
3111
+ return void 0;
3112
+ }
3113
+ const nextSeenVariables = new Set(seenVariables);
3114
+ nextSeenVariables.add(variable);
3115
+ for (const assignedValue of assignedValues) {
3116
+ const resolved = resolveShimTarget(
3117
+ `${assignedValue}${variableMatch[2] ?? ""}`,
3118
+ assignments,
3119
+ shimPath,
3120
+ platform,
3121
+ allowedVariables,
3122
+ nextSeenVariables
3123
+ );
3124
+ if (resolved) {
3125
+ return resolved;
3126
+ }
3127
+ }
3128
+ return void 0;
3129
+ }
3130
+ return isJavaScriptEntrypoint(target) ? target : void 0;
3131
+ }
3132
+ function isKnownPackageManagerEntrypoint(packageManager, filePath) {
3133
+ const fileName = win32.basename(filePath).toLowerCase();
3134
+ return PACKAGE_MANAGER_ENTRYPOINT_RULES[packageManager].cliBasenames.includes(fileName);
3135
+ }
3136
+ function matchesPackageManagerPath(packageManager, packageManagerPath, platform) {
3137
+ const pathModule = win32 ;
3138
+ const fileName = pathModule.basename(packageManagerPath).toLowerCase();
3139
+ return fileName === `${packageManager}.cmd` || fileName === `${packageManager}.exe` || isKnownPackageManagerEntrypoint(packageManager, packageManagerPath);
3140
+ }
3141
+ function isJavaScriptEntrypoint(filePath) {
3142
+ return /\.(?:js|cjs|mjs)$/i.test(filePath);
3143
+ }
3144
+ function getEnvironmentValue(environment, name) {
3145
+ const exactValue = environment[name];
3146
+ if (exactValue !== void 0) {
3147
+ return exactValue;
3148
+ }
3149
+ const lowerName = name.toLowerCase();
3150
+ const key = Object.keys(environment).find((candidate) => candidate.toLowerCase() === lowerName);
3151
+ return key ? environment[key] : void 0;
3152
+ }
3153
+ function registryEnvironment(packageManager, registry2) {
3154
+ return {
3155
+ ...process.env,
3156
+ npm_config_registry: registry2,
3157
+ // Classic Yarn reads npm's registry setting; modern Yarn uses this key.
3158
+ ...packageManager === "yarn" ? { YARN_NPM_REGISTRY_SERVER: registry2 } : {}
3159
+ };
3160
+ }
3161
+ function sendTerminationSignal(child, signal) {
3162
+ if (process.platform !== "win32" && child.pid) {
3163
+ try {
3164
+ process.kill(-child.pid, signal);
3165
+ return;
3166
+ } catch (error) {
3167
+ logger6.debug(`Failed to signal package-manager process group: ${String(error)}`);
3168
+ }
3169
+ }
3170
+ try {
3171
+ child.kill(signal);
3172
+ } catch (error) {
3173
+ logger6.debug(`Failed to signal package-manager process: ${String(error)}`);
3174
+ }
3175
+ }
3176
+ function terminateProcessTree(child) {
3177
+ if (process.platform === "win32") {
3178
+ if (!child.pid) {
3179
+ try {
3180
+ child.kill("SIGKILL");
3181
+ } catch (error) {
3182
+ logger6.debug(`Failed to terminate package-manager process: ${String(error)}`);
3183
+ }
3184
+ return;
3185
+ }
3186
+ const taskkill = spawn("taskkill", ["/pid", String(child.pid), "/t", "/f"], {
3187
+ shell: false,
3188
+ stdio: "ignore"
3189
+ });
3190
+ taskkill.on("error", (error) => {
3191
+ logger6.debug(`Failed to terminate package-manager process tree: ${error.message}`);
3192
+ });
3193
+ return;
3194
+ }
3195
+ if (child.pid) {
3196
+ try {
3197
+ process.kill(-child.pid, "SIGKILL");
3198
+ return;
3199
+ } catch (error) {
3200
+ logger6.debug(`Failed to terminate package-manager process group: ${String(error)}`);
3201
+ }
3202
+ }
3203
+ try {
3204
+ child.kill("SIGKILL");
3205
+ } catch (error) {
3206
+ logger6.debug(`Failed to terminate package-manager process: ${String(error)}`);
3207
+ }
3208
+ }
3209
+
3210
+ // src/core/package-installer.ts
3211
+ var logger7 = createLogger("package-installer");
3212
+ var INSTALL_TIMEOUT = 12e4;
3213
+ var PackageInstaller = class {
3214
+ options;
3215
+ packageManager;
3216
+ constructor(options, packageManager = createPackageManagerAdapter(options)) {
3217
+ this.options = options;
3218
+ this.packageManager = packageManager;
3219
+ }
3220
+ /**
3221
+ * 安装别名依赖
3222
+ */
3223
+ async installAliases(mappings) {
3224
+ const result = {
3225
+ success: true,
3226
+ installed: [],
3227
+ reused: [],
3228
+ failed: [],
3229
+ errors: []
3230
+ };
3231
+ if (mappings.length === 0) {
3232
+ logger7.info("No aliases to install");
3233
+ return result;
3234
+ }
3235
+ const toInstall = [];
3236
+ const reportCollision = (mapping, verification) => {
3237
+ const collision = {
3238
+ code: "ALIAS_NAME_OCCUPIED",
3239
+ aliasName: mapping.aliasName,
3240
+ expected: {
3241
+ packageName: mapping.originalName,
3242
+ version: mapping.resolvedVersion
3243
+ },
3244
+ actual: {
3245
+ packageName: verification.actualPackageName,
3246
+ version: verification.actualVersion
3247
+ },
3248
+ reason: verification.reason
3249
+ };
3250
+ result.success = false;
3251
+ result.failed.push(mapping.aliasName);
3252
+ result.errors.push(`Alias collision: ${JSON.stringify(collision)}`);
3253
+ logger7.warn(`Alias collision: ${JSON.stringify(collision)}`);
3254
+ };
3255
+ const installedAliasPath = (aliasName) => {
3256
+ const local = join(this.options.projectRoot, "node_modules", aliasName);
3257
+ return fileExists(local) ? local : findPackagePath(aliasName, this.options.projectRoot);
3258
+ };
3259
+ const reportMissing = (mapping) => {
3260
+ result.success = false;
3261
+ result.failed.push(mapping.aliasName);
3262
+ result.errors.push("Alias is not installed or resolvable: " + mapping.aliasName);
3263
+ };
3264
+ for (const m of mappings) {
3265
+ const aliasPath = installedAliasPath(m.aliasName);
3266
+ if (!m.installSpec) {
3267
+ if (!aliasPath) {
3268
+ reportMissing(m);
3269
+ continue;
3270
+ }
3271
+ const verification2 = this.verifyInstalledVersion(
3272
+ aliasPath,
3273
+ m.originalName,
3274
+ m.resolvedVersion
3275
+ );
3276
+ if (!verification2.matches) {
3277
+ reportCollision(m, verification2);
3278
+ continue;
3279
+ }
3280
+ logger7.debug(`Skipping ${m.aliasName}: reusing existing installation`);
3281
+ result.reused.push(m.aliasName);
3282
+ continue;
3283
+ }
3284
+ if (!aliasPath) {
3285
+ toInstall.push(m);
3286
+ continue;
3287
+ }
3288
+ const verification = this.verifyInstalledVersion(
3289
+ aliasPath,
3290
+ m.originalName,
3291
+ m.resolvedVersion
3292
+ );
3293
+ if (!verification.matches) {
3294
+ reportCollision(m, verification);
3295
+ continue;
3296
+ }
3297
+ logger7.debug(`${m.aliasName} already installed with correct version`);
3298
+ result.reused.push(m.aliasName);
3299
+ }
3300
+ if (toInstall.length === 0) {
3301
+ if (result.success) {
3302
+ logger7.info("All aliases already installed with correct versions");
3303
+ }
3304
+ return result;
3305
+ }
3306
+ logger7.info(`Installing ${toInstall.length} alias packages...`);
3307
+ const installSpecs = toInstall.map((m) => m.installSpec);
3308
+ let installResult;
3309
+ try {
3310
+ installResult = await this.runInstall(installSpecs);
3311
+ } finally {
3312
+ clearPackageJsonCache();
3313
+ }
3314
+ const reusedBeforeInstall = new Set(result.reused);
3315
+ result.reused = [];
3316
+ for (const mapping of mappings) {
3317
+ if (!reusedBeforeInstall.has(mapping.aliasName)) continue;
3318
+ const aliasPath = installedAliasPath(mapping.aliasName);
3319
+ if (!aliasPath) {
3320
+ reportMissing(mapping);
3321
+ continue;
3322
+ }
3323
+ const verification = this.verifyInstalledVersion(
3324
+ aliasPath,
3325
+ mapping.originalName,
3326
+ mapping.resolvedVersion
3327
+ );
3328
+ if (verification.matches) {
3329
+ result.reused.push(mapping.aliasName);
3330
+ } else {
3331
+ reportCollision(mapping, verification);
3332
+ }
3333
+ }
3334
+ if (installResult.success) {
3335
+ for (const mapping of toInstall) {
3336
+ const aliasPath = installedAliasPath(mapping.aliasName);
3337
+ if (!aliasPath) {
3338
+ reportMissing(mapping);
3339
+ continue;
3340
+ }
3341
+ const verification = this.verifyInstalledVersion(
3342
+ aliasPath,
3343
+ mapping.originalName,
3344
+ mapping.resolvedVersion
3345
+ );
3346
+ if (verification.matches) {
3347
+ result.installed.push(mapping.aliasName);
3348
+ } else {
3349
+ reportCollision(mapping, verification);
3350
+ }
3351
+ }
3352
+ if (result.installed.length > 0) {
3353
+ logger7.info(`Successfully installed: ${result.installed.join(", ")}`);
3354
+ }
3355
+ } else {
3356
+ result.success = false;
3357
+ result.failed.push(...toInstall.map((m) => m.aliasName));
3358
+ result.errors.push(...installResult.errors);
3359
+ logger7.error(`Failed to install aliases: ${installResult.errors.join(", ")}`);
3360
+ }
3361
+ return result;
3362
+ }
3363
+ /**
3364
+ * 验证已安装的别名版本是否正确
3365
+ * @returns 验证结果及已安装包信息
3366
+ */
3367
+ verifyInstalledVersion(aliasPath, expectedPackageName, expectedVersion) {
3368
+ try {
3369
+ const pkgJsonPath = join(aliasPath, "package.json");
3370
+ if (!fileExists(pkgJsonPath)) {
3371
+ return {
3372
+ matches: false,
3373
+ actualPackageName: null,
3374
+ actualVersion: null,
3375
+ reason: "missing-package-json"
3376
+ };
3377
+ }
3378
+ const pkgJson = readPackageJsonCached(aliasPath);
3379
+ if (!pkgJson) {
3380
+ logger7.debug(`Failed to verify version: unable to read/parse ${pkgJsonPath}`);
3381
+ return {
3382
+ matches: false,
3383
+ actualPackageName: null,
3384
+ actualVersion: null,
3385
+ reason: "invalid-package-json"
3386
+ };
3387
+ }
3388
+ const actualPackageName = pkgJson.name ?? null;
3389
+ const actualVersion = pkgJson.version ?? null;
3390
+ if (pkgJson.name !== expectedPackageName) {
3391
+ logger7.debug(
3392
+ `Package name mismatch: expected ${expectedPackageName}, got ${pkgJson.name ?? "unknown"}`
3393
+ );
3394
+ return {
3395
+ matches: false,
3396
+ actualPackageName,
3397
+ actualVersion,
3398
+ reason: "package-name-mismatch"
3399
+ };
3400
+ }
3401
+ const installedClean = semver.clean(pkgJson.version ?? "");
3402
+ const expectedClean = semver.clean(expectedVersion);
3403
+ if (!installedClean || !expectedClean || installedClean !== expectedClean) {
3404
+ logger7.debug(
3405
+ `Version mismatch: expected ${expectedVersion}, got ${pkgJson.version ?? "unknown"}`
3406
+ );
3407
+ return {
3408
+ matches: false,
3409
+ actualPackageName,
3410
+ actualVersion,
3411
+ reason: "version-mismatch"
3412
+ };
3413
+ }
3414
+ return {
3415
+ matches: true,
3416
+ actualPackageName,
3417
+ actualVersion,
3418
+ reason: "matched"
3419
+ };
3420
+ } catch (error) {
3421
+ logger7.debug(`Failed to verify version: ${String(error)}`);
3422
+ return {
3423
+ matches: false,
3424
+ actualPackageName: null,
3425
+ actualVersion: null,
3426
+ reason: "invalid-package-json"
3427
+ };
3428
+ }
3429
+ }
3430
+ /**
3431
+ * 执行安装命令
3432
+ */
3433
+ async runInstall(packages) {
3434
+ if (packages.length === 0) {
3435
+ return { success: true, errors: [] };
3436
+ }
3437
+ const runResult = await this.packageManager.install(packages);
3438
+ if (runResult.stdout) {
3439
+ logger7.debug(`stdout: ${runResult.stdout}`);
3440
+ }
3441
+ if (runResult.stderr) {
3442
+ logger7.debug(`stderr: ${runResult.stderr}`);
3443
+ }
3444
+ if (runResult.success) {
3445
+ logger7.info("Install completed");
3446
+ return { success: true, errors: [] };
3447
+ }
3448
+ const errorMessage = runResult.timedOut ? `Install timeout after ${INSTALL_TIMEOUT / 1e3}s` : runResult.stderr || `Process exited with code ${runResult.exitCode}`;
3449
+ logger7.error(`Install failed: ${errorMessage}`);
3450
+ return { success: false, errors: [errorMessage] };
3451
+ }
3452
+ };
3453
+ function createPackageInstaller(options) {
3454
+ return new PackageInstaller(options);
3455
+ }
3456
+ var registryKey = /* @__PURE__ */ Symbol.for("deps-conflict-resolver.project-preparation.v1");
3457
+ var registry = globalThis;
3458
+ var projects = registry[registryKey] ??= /* @__PURE__ */ new Map();
3459
+ var collectedProjects = new FinalizationRegistry(({ owner, ref }) => {
3460
+ if (projects.get(owner) === ref) projects.delete(owner);
3461
+ });
3462
+ function getProjectPreparation(projectRoot) {
3463
+ try {
3464
+ projectRoot = realpathSync(projectRoot);
3465
+ } catch {
3466
+ projectRoot = resolve(projectRoot);
3467
+ }
3468
+ let owner = createWorkspaceDetector(projectRoot).getWorkspaceRoot() ?? projectRoot;
3469
+ if (owner === projectRoot) {
3470
+ for (const directory of iterateParentDirs(projectRoot)) {
3471
+ if (Object.keys(LOCK_FILE_MAP).some((file) => existsSync(join(directory, file)))) {
3472
+ owner = directory;
3473
+ break;
3474
+ }
3475
+ }
3476
+ }
3477
+ try {
3478
+ owner = realpathSync(owner);
3479
+ } catch {
3480
+ owner = resolve(owner);
3481
+ }
3482
+ let state = projects.get(owner)?.deref();
3483
+ if (!state) {
3484
+ state = { owner, revision: 0, writing: false, tail: Promise.resolve(), observers: /* @__PURE__ */ new Set() };
3485
+ const ref = new WeakRef(state);
3486
+ projects.set(owner, ref);
3487
+ collectedProjects.register(state, { owner, ref });
3488
+ }
3489
+ return state;
3490
+ }
3491
+ async function readOwner(path) {
3492
+ try {
3493
+ const value = JSON.parse(await promises.readFile(path, "utf8"));
3494
+ 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) {
3495
+ return value;
3496
+ }
3497
+ } catch (error) {
3498
+ if (error.code === "ENOENT") return null;
3499
+ throw error;
3500
+ }
3501
+ throw new Error("Invalid dependency preparation lock record: " + path);
3502
+ }
3503
+ function exited(owner) {
3504
+ if (owner.host !== hostname()) return false;
3505
+ try {
3506
+ process.kill(owner.pid, 0);
3507
+ } catch (error) {
3508
+ return error.code === "ESRCH";
3509
+ }
3510
+ return false;
3511
+ }
3512
+ async function removeRecord(path) {
3513
+ await promises.unlink(path).catch((error) => {
3514
+ if (error.code !== "ENOENT") throw error;
3515
+ });
3516
+ }
3517
+ async function readContenders(directory, token) {
3518
+ const contenders = [];
3519
+ for (const name of await promises.readdir(directory)) {
3520
+ if (!name.endsWith(".json") || name === token + ".json") continue;
3521
+ const path = join(directory, name);
3522
+ const owner = await readOwner(path);
3523
+ if (!owner) continue;
3524
+ if (owner.token + ".json" !== name)
3525
+ throw new Error("Invalid dependency preparation lock identity: " + path);
3526
+ if (exited(owner)) {
3527
+ await removeRecord(path);
3528
+ } else contenders.push(owner);
3529
+ }
3530
+ return contenders;
3531
+ }
3532
+ async function acquireLock(owner) {
3533
+ const user = typeof process.getuid === "function" ? String(process.getuid()) : createHash("sha256").update(userInfo().username).digest("hex");
3534
+ const key = createHash("sha256").update(owner).digest("hex");
3535
+ const directory = join(tmpdir(), "deps-conflict-resolver-locks-" + user, key + ".queue");
3536
+ await promises.mkdir(directory, { recursive: true, mode: 448 });
3537
+ const token = randomUUID();
3538
+ const path = join(directory, token + ".json");
3539
+ const candidate = join(directory, token + ".tmp");
3540
+ const record = { pid: process.pid, host: hostname(), token, ticket: 0 };
3541
+ const deadline = performance.now() + 3e5;
3542
+ let published = false;
3543
+ try {
3544
+ await promises.writeFile(candidate, JSON.stringify(record), { flag: "wx", mode: 384 });
3545
+ await promises.link(candidate, path);
3546
+ published = true;
3547
+ await removeRecord(candidate);
3548
+ record.ticket = 1 + (await readContenders(directory, token)).reduce(
3549
+ (max, other) => Math.max(max, other.ticket),
3550
+ 0
3551
+ );
3552
+ if (!Number.isSafeInteger(record.ticket))
3553
+ throw new Error("Dependency preparation ticket limit exceeded in " + owner);
3554
+ await promises.writeFile(candidate, JSON.stringify(record), { flag: "wx", mode: 384 });
3555
+ await promises.rename(candidate, path);
3556
+ while (true) {
3557
+ const blocked = (await readContenders(directory, token)).some(
3558
+ (other) => other.ticket === 0 || other.ticket < record.ticket || other.ticket === record.ticket && other.token < token
3559
+ );
3560
+ if (!blocked) return () => removeRecord(path);
3561
+ if (performance.now() >= deadline)
3562
+ throw new Error(
3563
+ "Timed out waiting for dependency preparation in " + owner + " (lock: " + path + ")"
3564
+ );
3565
+ await new Promise((done) => setTimeout(done, 25));
3566
+ }
3567
+ } catch (error) {
3568
+ try {
3569
+ await removeRecord(candidate);
3570
+ } finally {
3571
+ if (published) await removeRecord(path);
3572
+ }
3573
+ throw error;
3574
+ }
3575
+ }
3576
+ async function withProjectPreparation(state, task, current) {
3577
+ const previous = state.tail;
3578
+ let finish;
3579
+ state.tail = new Promise((done) => {
3580
+ finish = done;
3581
+ });
3582
+ await previous;
3583
+ let unlock;
3584
+ let changed = false;
3585
+ try {
3586
+ unlock = await acquireLock(state.owner);
3587
+ return await task(() => {
3588
+ if (!changed) {
3589
+ state.revision++;
3590
+ changed = true;
3591
+ }
3592
+ state.writing = true;
3593
+ });
3594
+ } finally {
3595
+ try {
3596
+ if (changed) {
3597
+ for (const ref of state.observers) {
3598
+ const observer = ref.deref();
3599
+ if (!observer) state.observers.delete(ref);
3600
+ else if (observer !== current) await observer.refresh();
3601
+ }
3602
+ }
3603
+ } finally {
3604
+ state.writing = false;
3605
+ try {
3606
+ await unlock?.();
3607
+ } finally {
3608
+ finish();
3609
+ }
3610
+ }
3611
+ }
3612
+ }
3613
+ async function waitForProjectPreparation(state) {
3614
+ while (true) {
3615
+ const ready = state.tail;
3616
+ await ready;
3617
+ if (ready === state.tail) return;
3618
+ }
3619
+ }
3620
+ var logger8 = createLogger("resolver");
3621
+ var DEFAULT_OPTIONS = {
3622
+ autoInstall: true,
3623
+ debug: false,
3624
+ aliasPrefix: "aliased-"
3625
+ };
3626
+ var DepsConflictResolver = class {
3627
+ options;
3628
+ userOptions;
3629
+ hooks;
3630
+ environmentDetector = null;
3631
+ analyzer = null;
3632
+ aliasManager = null;
3633
+ installer = null;
3634
+ analysisResult = null;
3635
+ initialized = false;
3636
+ initializationPromise = null;
3637
+ installationPromise = null;
3638
+ preparing = false;
3639
+ installResult = null;
3640
+ installDiagnostics = [];
3641
+ preparation = null;
3642
+ snapshotRevision = 0;
3643
+ snapshotError = null;
3644
+ snapshotGeneration = 0;
3645
+ snapshotSignature = "";
3646
+ snapshotInvalidated = false;
3647
+ activeMappings = [];
3648
+ snapshotObserver = null;
3649
+ observer = { refresh: () => this.refreshSnapshot() };
3650
+ constructor(userOptions, hooks = {}) {
3651
+ this.userOptions = userOptions;
3652
+ this.hooks = hooks;
3653
+ if (userOptions.debug) {
3654
+ logger8.setLevel(15 /* ALL */);
3655
+ }
3656
+ }
3657
+ /**
3658
+ * 解析配置,填充默认值(异步,支持自动检测)
3659
+ */
3660
+ async resolveOptions(userOptions, projectRoot) {
3661
+ this.environmentDetector = createEnvironmentDetector(projectRoot);
3662
+ let packageManager;
3663
+ if (!userOptions.packageManager || userOptions.packageManager === "auto") {
3664
+ const detected = this.environmentDetector.getDetectionResult();
3665
+ packageManager = detected.packageManager;
3666
+ logger8.info(
3667
+ `Auto-detected package manager: ${packageManager} (from ${detected.detectedFrom})`
3668
+ );
3669
+ } else {
3670
+ packageManager = userOptions.packageManager;
3671
+ }
3672
+ let registry2;
3673
+ if (!userOptions.registry) {
3674
+ registry2 = await this.environmentDetector.getRegistryForPackageManager(packageManager);
3675
+ if (registry2 !== DEFAULT_NPM_REGISTRY) {
3676
+ logger8.info(`Auto-detected registry: ${registry2}`);
3677
+ }
3678
+ } else {
3679
+ registry2 = userOptions.registry;
3680
+ }
3681
+ return {
3682
+ ...DEFAULT_OPTIONS,
3683
+ dependencies: userOptions.dependencies,
3684
+ projectRoot,
3685
+ packageManager,
3686
+ registry: registry2,
3687
+ autoInstall: userOptions.offline ? false : userOptions.autoInstall ?? DEFAULT_OPTIONS.autoInstall,
3688
+ offline: userOptions.offline ?? false,
3689
+ strict: userOptions.strict ?? false,
3690
+ debug: userOptions.debug ?? DEFAULT_OPTIONS.debug,
3691
+ aliasPrefix: userOptions.aliasPrefix ?? DEFAULT_OPTIONS.aliasPrefix,
3692
+ excludeRedirects: userOptions.excludeRedirects ?? {},
3693
+ includeRedirects: userOptions.includeRedirects ?? {}
3694
+ };
3695
+ }
3696
+ /**
3697
+ * 初始化解析器
3698
+ */
3699
+ async initialize() {
3700
+ if (this.initialized) {
3701
+ if (this.preparation) await waitForProjectPreparation(this.preparation);
3702
+ this.snapshotCurrent();
3703
+ return;
3704
+ }
3705
+ const initialization = this.initializationPromise ??= this.initializeGeneration();
3706
+ try {
3707
+ await initialization;
3708
+ } catch (error) {
3709
+ if (this.initializationPromise === initialization) {
3710
+ this.initializationPromise = null;
3711
+ this.rollbackGeneration();
3712
+ }
3713
+ throw error;
3714
+ }
3715
+ }
3716
+ /**
3717
+ * 清理已完成的初始化状态,使下一次 initialize 创建新的分析 generation。
3718
+ *
3719
+ * 初始化尚未完成时不能失效当前 generation,否则并发调用者会观察到
3720
+ * 不一致的部分状态。
3721
+ */
3722
+ invalidate() {
3723
+ if (this.initializationPromise && !this.initialized) {
3724
+ throw new Error("Cannot invalidate while initialization is in progress");
3725
+ }
3726
+ if (this.installationPromise) {
3727
+ throw new Error("Cannot invalidate while installation is in progress");
3728
+ }
3729
+ this.initialized = false;
3730
+ this.initializationPromise = null;
3731
+ this.rollbackGeneration();
3732
+ }
3733
+ /**
3734
+ * 回滚未完成或已失效的 generation,确保外部不会观察到半成品规则。
3735
+ */
3736
+ rollbackGeneration() {
3737
+ this.initialized = false;
3738
+ if (this.snapshotObserver) this.preparation?.observers.delete(this.snapshotObserver);
3739
+ this.snapshotObserver = null;
3740
+ this.snapshotError = null;
3741
+ this.snapshotSignature = "";
3742
+ this.snapshotInvalidated = false;
3743
+ this.snapshotGeneration++;
3744
+ this.activeMappings = [];
3745
+ this.analysisResult = null;
3746
+ this.analyzer = null;
3747
+ this.aliasManager?.clear?.();
3748
+ this.aliasManager = null;
3749
+ this.installer = null;
3750
+ this.installResult = null;
3751
+ this.installDiagnostics = [];
3752
+ }
3753
+ async initializeGeneration() {
3754
+ clearPackageJsonCache();
3755
+ logger8.info("Initializing dependencies resolver...");
3756
+ const projectRoot = resolve(this.userOptions.projectRoot ?? process.cwd());
3757
+ const validRoot = findProjectRoot(projectRoot);
3758
+ if (!validRoot) {
3759
+ throw new Error(`Could not find package.json in ${projectRoot} or parent directories`);
3760
+ }
3761
+ if (validRoot !== projectRoot) {
3762
+ logger8.debug(`Adjusted project root to: ${validRoot}`);
3763
+ }
3764
+ let physicalRoot = validRoot;
3765
+ try {
3766
+ physicalRoot = realpathSync(validRoot);
3767
+ } catch {
3768
+ }
3769
+ this.options = await this.resolveOptions(this.userOptions, physicalRoot);
3770
+ if (this.options.debug) {
3771
+ logger8.setLevel(15 /* ALL */);
3772
+ }
3773
+ this.aliasManager = createAliasManager(this.options);
3774
+ this.installer = createPackageInstaller(this.options);
3775
+ this.preparation = getProjectPreparation(this.options.projectRoot);
3776
+ if (this.hooks.onAnalysisComplete) {
3777
+ this.analysisResult = await withProjectPreparation(
3778
+ this.preparation,
3779
+ () => this.analyzeCurrent()
3780
+ );
3781
+ await this.hooks.onAnalysisComplete(this.analysisResult);
3782
+ }
3783
+ await withProjectPreparation(
3784
+ this.preparation,
3785
+ async (markChanged) => {
3786
+ this.analysisResult = await this.analyzeCurrent();
3787
+ this.logMissingFirstLevelPeers(this.analysisResult);
3788
+ this.assertResolved();
3789
+ if (this.options.autoInstall) {
3790
+ const installing = this.installGeneration(markChanged);
3791
+ this.installationPromise = installing;
3792
+ try {
3793
+ await installing;
3794
+ } finally {
3795
+ this.installationPromise = null;
3796
+ }
3797
+ } else {
3798
+ this.publishWithoutInstallation();
3799
+ }
3800
+ this.observeSnapshot();
3801
+ },
3802
+ this.observer
3803
+ );
3804
+ await waitForProjectPreparation(this.preparation);
3805
+ await this.notifyInstallComplete();
3806
+ this.assertResolved();
3807
+ const unresolved = this.getDiagnostics().filter(
3808
+ (diagnostic) => diagnostic.severity === "error"
3809
+ );
3810
+ if (unresolved.length > 0) {
3811
+ logger8.warn(
3812
+ "Resolver has " + unresolved.length + " unresolved conditions: " + [...new Set(unresolved.map((diagnostic) => diagnostic.code))].join(", ") + ". Inspect getDiagnostics() or run doctor for details."
3813
+ );
3814
+ }
3815
+ this.logSharedPeerWarnings();
3816
+ this.analyzer = null;
3817
+ this.initialized = true;
3818
+ logger8.info("Dependencies resolver initialized");
3819
+ }
3820
+ /**
3821
+ * 输出第一层依赖中缺失的 peer 依赖警告(不自动安装,仅提示)
3822
+ *
3823
+ * 放在 initialize 阶段统一输出,避免各插件重复打印,且在 autoInstall=false 时也能看到提示。
3824
+ */
3825
+ logMissingFirstLevelPeers(result) {
3826
+ const missing = result.missingFirstLevelPeers;
3827
+ if (!missing || missing.length === 0) {
3828
+ return;
3829
+ }
3830
+ logger8.warn(`Found ${missing.length} unsatisfied peer dependencies (not auto-installing):`);
3831
+ for (const peer of missing) {
3832
+ logger8.warn(
3833
+ ` - ${peer.packageName}@${peer.requiredRange} (required by ${peer.requestedBy})`
3834
+ );
3835
+ }
3836
+ }
3837
+ /**
3838
+ * 安装所需依赖
3839
+ *
3840
+ * 安装策略(按用户需求):
3841
+ * 1. 只自动安装「主工程已声明的依赖 & peerDeps 要求版本与主工程版本冲突」的别名版本
3842
+ * 2. 缺失的 peer 依赖(主工程未声明):不自动安装,只警告
3843
+ * 3. 内部依赖冲突(子依赖之间的版本冲突):不自动安装,只做编译时重定向
3844
+ *
3845
+ * 这样可以避免"什么依赖都自动安装"的问题,用户可以根据警告自行决定是否安装缺失的依赖
3846
+ */
3847
+ installDependencies() {
3848
+ return this.installationPromise ??= this.prepareInstallation().finally(() => {
3849
+ this.installationPromise = null;
3850
+ });
3851
+ }
3852
+ async prepareInstallation() {
3853
+ if (!this.analysisResult || !this.installer || !this.preparation) {
3854
+ throw new Error("Resolver not initialized. Call initialize() first.");
3855
+ }
3856
+ this.preparing = true;
3857
+ try {
3858
+ await withProjectPreparation(
3859
+ this.preparation,
3860
+ async (markChanged) => {
3861
+ this.analysisResult = await this.analyzeCurrent();
3862
+ this.installDiagnostics = [];
3863
+ this.assertResolved();
3864
+ if (!this.options.offline) await this.installGeneration(markChanged);
3865
+ else this.publishWithoutInstallation();
3866
+ this.observeSnapshot();
3867
+ },
3868
+ this.observer
3869
+ );
3870
+ } finally {
3871
+ this.preparing = false;
3872
+ }
3873
+ await waitForProjectPreparation(this.preparation);
3874
+ await this.notifyInstallComplete();
3875
+ this.assertResolved();
3876
+ if (this.initialized) this.logSharedPeerWarnings();
3877
+ }
3878
+ async analyzeCurrent(offline = this.options.offline, preparedAliases = []) {
3879
+ clearPackageJsonCache();
3880
+ this.analyzer = createDependencyAnalyzer({ ...this.options, offline }, preparedAliases);
3881
+ try {
3882
+ return await this.analyzer.analyze();
3883
+ } finally {
3884
+ this.analyzer = null;
3885
+ }
3886
+ }
3887
+ publishWithoutInstallation() {
3888
+ const mappings = this.analysisResult.aliasMappings;
3889
+ this.setActiveAliasMappings(mappings.filter((mapping) => mapping.installSpec === ""));
3890
+ for (const mapping of mappings) {
3891
+ if (mapping.installSpec)
3892
+ this.installDiagnostics.push({
3893
+ code: "ALIAS_NOT_INSTALLED",
3894
+ severity: "error",
3895
+ packageName: mapping.originalName,
3896
+ aliases: [mapping.aliasName],
3897
+ message: "Alias is not active because installation is disabled: " + mapping.aliasName
3898
+ });
3899
+ }
3900
+ }
3901
+ async installGeneration(markChanged) {
3902
+ const report = {
3903
+ success: true,
3904
+ installed: [],
3905
+ reused: [],
3906
+ failed: [],
3907
+ errors: []
3908
+ };
3909
+ this.installResult = report;
3910
+ this.installDiagnostics = [];
3911
+ const blocked = /* @__PURE__ */ new Set();
3912
+ for (let attempt = 0; attempt < 2; attempt++) {
3913
+ const planned = this.analysisResult.aliasMappings;
3914
+ if (planned.some((mapping) => mapping.installSpec)) markChanged();
3915
+ let result;
3916
+ try {
3917
+ result = await this.installer.installAliases(planned);
3918
+ } catch (error) {
3919
+ this.setActiveAliasMappings([]);
3920
+ throw error;
3921
+ }
3922
+ report.success &&= result.success;
3923
+ for (const key of ["installed", "reused", "failed", "errors"]) {
3924
+ report[key] = [.../* @__PURE__ */ new Set([...report[key], ...result[key] ?? []])];
3925
+ }
3926
+ for (const aliasName of result.failed ?? []) {
3927
+ blocked.add(aliasName);
3928
+ this.installDiagnostics.push({
3929
+ code: "ALIAS_INSTALL_FAILED",
3930
+ severity: "error",
3931
+ packageName: planned.find((mapping) => mapping.aliasName === aliasName)?.originalName ?? aliasName,
3932
+ aliases: [aliasName],
3933
+ message: "Alias installation failed: " + aliasName + ". " + result.errors.join("; ")
3934
+ });
3935
+ }
3936
+ const changed = (result.installed?.length ?? 0) > 0 || (result.failed?.length ?? 0) > 0;
3937
+ if (!changed) {
3938
+ this.setActiveAliasMappings(this.filterCompletedMappings(planned, result, false), blocked);
3939
+ return;
3940
+ }
3941
+ this.analysisResult = await this.analyzeCurrent(
3942
+ result.success ? this.options.offline : true,
3943
+ this.filterCompletedMappings(planned, result, false)
3944
+ );
3945
+ const fresh = this.analysisResult.aliasMappings;
3946
+ const pending = fresh.filter(
3947
+ (mapping) => mapping.installSpec && !blocked.has(mapping.aliasName)
3948
+ );
3949
+ if (result.success && pending.length > 0 && attempt === 0) continue;
3950
+ if (result.success && pending.length > 0) {
3951
+ report.success = false;
3952
+ const message = "Dependency inputs changed during preparation; refusing to publish an unstable installation plan";
3953
+ report.errors.push(message);
3954
+ this.installDiagnostics.push({
3955
+ code: "PROJECT_STATE_CHANGED",
3956
+ severity: "error",
3957
+ packageName: this.options.dependencies.join(", "),
3958
+ message
3959
+ });
3960
+ }
3961
+ for (const mapping of planned) {
3962
+ if (blocked.has(mapping.aliasName) && !fresh.some((entry) => entry.aliasName === mapping.aliasName))
3963
+ fresh.push(mapping);
3964
+ }
3965
+ this.setActiveAliasMappings(
3966
+ fresh.filter((mapping) => !mapping.installSpec && !blocked.has(mapping.aliasName)),
3967
+ blocked
3968
+ );
3969
+ if (!report.success || pending.length === 0) return;
3970
+ }
3971
+ }
3972
+ observeSnapshot() {
3973
+ this.snapshotInvalidated = false;
3974
+ if (!this.snapshotObserver) {
3975
+ this.snapshotObserver = new WeakRef(this.observer);
3976
+ this.preparation.observers.add(this.snapshotObserver);
3977
+ }
3978
+ this.captureSnapshot();
3979
+ }
3980
+ async refreshSnapshot() {
3981
+ if (!this.analysisResult || !this.aliasManager) return;
3982
+ if (this.snapshotInvalidated) {
3983
+ this.snapshotRevision = this.preparation.revision;
3984
+ return;
3985
+ }
3986
+ const generation = this.snapshotGeneration;
3987
+ const previous = this.snapshotSignature;
3988
+ try {
3989
+ const analysis = await this.analyzeCurrent(true, this.activeMappings);
3990
+ if (generation !== this.snapshotGeneration) return;
3991
+ this.analysisResult = analysis;
3992
+ this.setActiveAliasMappings(analysis.aliasMappings.filter((mapping) => !mapping.installSpec));
3993
+ const changed = previous !== this.describeSnapshot();
3994
+ if (this.initialized && changed) {
3995
+ this.snapshotInvalidated = true;
3996
+ this.setActiveAliasMappings([]);
3997
+ this.installDiagnostics.push({
3998
+ code: "PROJECT_STATE_CHANGED",
3999
+ severity: "error",
4000
+ packageName: this.options.dependencies.join(", "),
4001
+ message: "Another preparation changed active dependency rules. Call invalidate() and initialize() before building again."
4002
+ });
4003
+ }
4004
+ } catch (error) {
4005
+ if (generation !== this.snapshotGeneration) return;
4006
+ this.snapshotInvalidated = true;
4007
+ this.setActiveAliasMappings([]);
4008
+ this.installDiagnostics.push({
4009
+ code: "PROJECT_STATE_CHANGED",
4010
+ severity: "error",
4011
+ packageName: this.options.dependencies.join(", "),
4012
+ message: "Cannot refresh dependency rules after another installation: " + String(error)
4013
+ });
4014
+ }
4015
+ this.captureSnapshot();
4016
+ }
4017
+ describeSnapshot() {
4018
+ const mappings = this.activeMappings.map((mapping) => [
4019
+ mapping.originalName,
4020
+ mapping.aliasName,
4021
+ mapping.resolvedVersion,
4022
+ [...mapping.usedBy].sort(),
4023
+ [...mapping.allDependents].sort(),
4024
+ mapping.importerPaths ? [...mapping.importerPaths].sort() : null
4025
+ ]).sort((a, b) => String(a[1]).localeCompare(String(b[1])));
4026
+ const providers = (this.aliasManager?.getAliasPathMappings() ?? []).map((mapping) => {
4027
+ let path = mapping.path;
4028
+ try {
4029
+ path = realpathSync(path);
4030
+ } catch {
4031
+ }
4032
+ return [mapping.aliasName, path, readPackageJsonCached(path)];
4033
+ }).sort((a, b) => String(a[0]).localeCompare(String(b[0])));
4034
+ return JSON.stringify([mappings, providers]);
4035
+ }
4036
+ captureSnapshot() {
4037
+ this.snapshotRevision = this.preparation.revision;
4038
+ this.snapshotSignature = this.describeSnapshot();
4039
+ const errors = this.generationDiagnostics().filter(
4040
+ (diagnostic) => diagnostic.severity === "error"
4041
+ );
4042
+ this.snapshotError = errors.length ? new ResolutionError(errors) : null;
4043
+ }
4044
+ async notifyInstallComplete() {
4045
+ if (!this.installResult || !this.hooks.onInstallComplete) return;
4046
+ await this.hooks.onInstallComplete(
4047
+ this.filterCompletedMappings(this.analysisResult.aliasMappings, this.installResult, true)
4048
+ );
4049
+ }
4050
+ snapshotCurrent() {
4051
+ if (!this.preparation) return true;
4052
+ if (this.preparation.writing || this.preparing || this.snapshotRevision !== this.preparation.revision) {
4053
+ const diagnostic = {
4054
+ code: "PROJECT_STATE_CHANGED",
4055
+ severity: "error",
4056
+ packageName: this.options.dependencies.join(", "),
4057
+ message: "Dependency preparation is changing this project; wait for preparation to finish before resolving modules"
4058
+ };
4059
+ if (this.options.strict) throw new ResolutionError([diagnostic]);
4060
+ return false;
4061
+ }
4062
+ if (this.options.strict && this.snapshotError) throw this.snapshotError;
4063
+ return true;
4064
+ }
4065
+ logSharedPeerWarnings() {
4066
+ for (const diagnostic of this.getDiagnostics()) {
4067
+ if (diagnostic.code === "SHARED_PEER_CONTEXT")
4068
+ logger8.warn(`[${diagnostic.code}] ${diagnostic.message}`);
4069
+ }
4070
+ }
4071
+ /**
4072
+ * Select only mappings whose installer outcome explicitly proved reuse or
4073
+ * installation. Hook callers retain the pre-Task-9 compatibility fallback
4074
+ * for old installer results that omitted `reused`.
4075
+ */
4076
+ filterCompletedMappings(aliasMappings, aliasResult, allowLegacyReuse) {
4077
+ const failedAliases = new Set(aliasResult.failed ?? []);
4078
+ const successfulAliases = /* @__PURE__ */ new Set([
4079
+ ...aliasResult.installed ?? [],
4080
+ ...aliasResult.reused ?? []
4081
+ ]);
4082
+ if (allowLegacyReuse && aliasResult.success !== false) {
4083
+ for (const mapping of aliasMappings) {
4084
+ if (mapping.installSpec === "" && !failedAliases.has(mapping.aliasName)) {
4085
+ successfulAliases.add(mapping.aliasName);
4086
+ }
4087
+ }
4088
+ }
4089
+ return aliasMappings.filter(
4090
+ (mapping) => successfulAliases.has(mapping.aliasName) && !failedAliases.has(mapping.aliasName)
4091
+ );
4092
+ }
4093
+ /**
4094
+ * Publish a new active mapping set while keeping the complete analysis
4095
+ * result available for diagnostics.
4096
+ */
4097
+ setActiveAliasMappings(mappings, blockedAliasNames = []) {
4098
+ if (!this.aliasManager || !this.analysisResult) {
4099
+ return;
4100
+ }
4101
+ const activeAliasNames = new Set(mappings.map((mapping) => mapping.aliasName));
4102
+ const inactiveAliasNames = new Set(blockedAliasNames);
4103
+ for (const mapping of this.analysisResult.aliasMappings) {
4104
+ if (!activeAliasNames.has(mapping.aliasName)) {
4105
+ inactiveAliasNames.add(mapping.aliasName);
4106
+ }
4107
+ }
4108
+ const activeMappings = mappings.map((mapping) => {
4109
+ if (!mapping.importerPaths || inactiveAliasNames.size === 0) {
4110
+ return mapping;
4111
+ }
4112
+ const blockedPaths = new Set(
4113
+ Object.entries(mapping.peerImporterPaths ?? {}).filter(([aliasName]) => inactiveAliasNames.has(aliasName)).flatMap(([, paths]) => paths)
4114
+ );
4115
+ return {
4116
+ ...mapping,
4117
+ peerImporterPaths: Object.fromEntries(
4118
+ Object.entries(mapping.peerImporterPaths ?? {}).filter(
4119
+ ([aliasName]) => !inactiveAliasNames.has(aliasName)
4120
+ )
4121
+ ),
4122
+ importerPaths: mapping.importerPaths.filter(
4123
+ (importerPath) => !blockedPaths.has(importerPath) && ![...inactiveAliasNames].some(
4124
+ (aliasName) => this.isAliasPackagePath(importerPath, aliasName)
4125
+ )
4126
+ )
4127
+ };
4128
+ });
4129
+ this.activeMappings = activeMappings;
4130
+ this.aliasManager.initFromAnalysisResult({
4131
+ ...this.analysisResult,
4132
+ aliasMappings: activeMappings
4133
+ });
4134
+ }
4135
+ /**
4136
+ * Check whether an importer path belongs to an alias package directory.
4137
+ * Package paths can be nested under pnpm's virtual store, so matching the
4138
+ * `node_modules/<alias>` segment is more reliable than checking a basename.
4139
+ */
4140
+ isAliasPackagePath(importerPath, aliasName) {
4141
+ const normalizedPath = importerPath.replace(/\\/g, "/").replace(/\/+$/, "");
4142
+ const marker = `node_modules/${aliasName}`;
4143
+ return normalizedPath === marker || normalizedPath.startsWith(`${marker}/`) || normalizedPath.endsWith(`/${marker}`) || normalizedPath.includes(`/${marker}/`);
4144
+ }
4145
+ /**
4146
+ * 解析模块请求
4147
+ * @returns 解析后的模块名,如果不需要重定向则返回 null
4148
+ */
4149
+ resolveModule(request, importer) {
4150
+ if (!this.initialized || !this.aliasManager) {
4151
+ return null;
4152
+ }
4153
+ if (!this.snapshotCurrent()) return null;
4154
+ if (this.hooks.beforeResolve) {
4155
+ const hookResult = this.hooks.beforeResolve(request, importer);
4156
+ if (hookResult !== void 0) {
4157
+ return hookResult;
4158
+ }
4159
+ }
4160
+ return this.aliasManager.resolveModule({ request, importer });
4161
+ }
4162
+ /**
4163
+ * 获取别名路径映射
4164
+ * 返回别名名称到实际路径的映射,供构建工具插件转换为各自的格式
4165
+ */
4166
+ getAliasPathMappings() {
4167
+ if (!this.initialized || !this.aliasManager) {
4168
+ return [];
4169
+ }
4170
+ if (!this.snapshotCurrent()) return [];
4171
+ return this.aliasManager.getAliasPathMappings();
4172
+ }
4173
+ /**
4174
+ * 获取分析结果
4175
+ */
4176
+ getAnalysisResult() {
4177
+ return this.analysisResult;
4178
+ }
4179
+ generationDiagnostics() {
4180
+ return [
4181
+ ...this.analysisResult?.diagnostics ?? [],
4182
+ ...this.installDiagnostics,
4183
+ ...this.aliasManager?.getDiagnostics?.() ?? []
4184
+ ];
4185
+ }
4186
+ /** Inspect unresolved conditions without parsing logs. */
4187
+ getDiagnostics() {
4188
+ return [
4189
+ ...this.initialized && this.preparation && (this.preparation.writing || this.preparing) ? [
4190
+ {
4191
+ code: "PROJECT_STATE_CHANGED",
4192
+ severity: "error",
4193
+ packageName: this.options.dependencies.join(", "),
4194
+ message: "Dependency preparation is in progress; wait before resolving modules"
4195
+ }
4196
+ ] : [],
4197
+ ...this.generationDiagnostics()
4198
+ ].map(
4199
+ (diagnostic) => Object.assign({}, diagnostic, {
4200
+ ...diagnostic.aliases && { aliases: [...diagnostic.aliases] },
4201
+ ...diagnostic.requestedBy && { requestedBy: [...diagnostic.requestedBy] },
4202
+ ...diagnostic.importerPaths && { importerPaths: [...diagnostic.importerPaths] }
4203
+ })
4204
+ );
4205
+ }
4206
+ assertResolved() {
4207
+ if (this.options.strict) {
4208
+ const errors = this.generationDiagnostics().filter(
4209
+ (diagnostic) => diagnostic.severity === "error"
4210
+ );
4211
+ if (errors.length > 0) throw new ResolutionError(errors);
4212
+ }
4213
+ }
4214
+ /** Explain a request; skipHook permits side-effect-free cache validation. */
4215
+ explainResolution(request, importer, options = {}) {
4216
+ if (!this.initialized || !this.aliasManager) {
4217
+ return {
4218
+ request,
4219
+ importer,
4220
+ resolved: null,
4221
+ reason: "inactive",
4222
+ aliases: [],
4223
+ matchedPaths: []
4224
+ };
4225
+ }
4226
+ if (!this.snapshotCurrent())
4227
+ return {
4228
+ request,
4229
+ importer,
4230
+ resolved: null,
4231
+ reason: "inactive",
4232
+ aliases: [],
4233
+ matchedPaths: []
4234
+ };
4235
+ if (!options.skipHook && this.hooks.beforeResolve) {
4236
+ const resolved = this.hooks.beforeResolve(request, importer);
4237
+ if (resolved !== void 0) {
4238
+ return { request, importer, resolved, reason: "hook", aliases: [], matchedPaths: [] };
4239
+ }
4240
+ }
4241
+ return this.aliasManager.explainResolution(request, importer);
4242
+ }
4243
+ getInstallResult() {
4244
+ return this.installResult && {
4245
+ ...this.installResult,
4246
+ installed: [...this.installResult.installed],
4247
+ reused: [...this.installResult.reused],
4248
+ failed: [...this.installResult.failed],
4249
+ errors: [...this.installResult.errors]
4250
+ };
4251
+ }
4252
+ /**
4253
+ * 获取配置
4254
+ */
4255
+ getOptions() {
4256
+ return { ...this.options };
4257
+ }
4258
+ };
4259
+
4260
+ // src/core/cli-runner.ts
4261
+ var HELP = [
4262
+ "Usage: deps-conflict-resolver <doctor|prepare> [packages...] [options]",
4263
+ "",
4264
+ "doctor Analyze without installing; scans runtime dependencies when none are listed.",
4265
+ "prepare Analyze and install verified aliases for the listed packages.",
4266
+ "",
4267
+ "Options:",
4268
+ " --root <directory> Project directory (defaults to cwd)",
4269
+ " --package-manager <manager> auto, npm, pnpm, or yarn",
4270
+ " --registry <url> Registry used for metadata and installation",
4271
+ " --offline Never query a registry or run installation",
4272
+ " --strict Return exit code 1 for unresolved conditions",
4273
+ " --json Emit a machine-readable report",
4274
+ " --help Show this help",
4275
+ ""
4276
+ ].join("\n");
4277
+ async function runCli(argv, output = {
4278
+ stdout: (text) => {
4279
+ process.stdout.write(text);
4280
+ },
4281
+ stderr: (text) => {
4282
+ process.stderr.write(text);
4283
+ }
4284
+ }) {
4285
+ const json = argv.includes("--json");
4286
+ try {
4287
+ if (argv.length === 0 || argv.includes("--help")) {
4288
+ output.stdout(HELP);
4289
+ return 0;
4290
+ }
4291
+ const [command, ...args] = argv;
4292
+ if (command !== "doctor" && command !== "prepare") {
4293
+ throw new Error("Unknown command: " + command + "\n" + HELP);
4294
+ }
4295
+ let root = process.cwd();
4296
+ let registry2;
4297
+ let packageManager = "auto";
4298
+ let offline = false;
4299
+ let strict = false;
4300
+ const packages = [];
4301
+ for (let index = 0; index < args.length; index++) {
4302
+ const arg = args[index];
4303
+ if (arg === "--json") continue;
4304
+ if (arg === "--offline") {
4305
+ offline = true;
4306
+ continue;
4307
+ }
4308
+ if (arg === "--strict") {
4309
+ strict = true;
4310
+ continue;
4311
+ }
4312
+ if (arg === "--root" || arg === "--registry" || arg === "--package-manager") {
4313
+ const value = args[++index];
4314
+ if (!value || value.startsWith("--")) throw new Error("Missing value for " + arg);
4315
+ if (arg === "--root") root = value;
4316
+ else if (arg === "--registry") registry2 = value;
4317
+ else {
4318
+ if (!["auto", "npm", "pnpm", "yarn"].includes(value))
4319
+ throw new Error("Unsupported package manager: " + value);
4320
+ packageManager = value;
4321
+ }
4322
+ continue;
4323
+ }
4324
+ if (arg.startsWith("-")) throw new Error("Unknown option: " + arg);
4325
+ packages.push(arg);
4326
+ }
4327
+ if (command === "prepare" && packages.length === 0) {
4328
+ throw new Error("prepare requires at least one dependency name");
4329
+ }
4330
+ const projectRoot = findProjectRoot(resolve(root));
4331
+ if (!projectRoot) throw new Error("Could not find package.json from " + root);
4332
+ const manifest = readPackageJsonCached(projectRoot);
4333
+ if (!manifest) throw new Error("Could not read package.json at " + projectRoot);
4334
+ const runtimeDependencies = { ...manifest.dependencies, ...manifest.optionalDependencies };
4335
+ const dependencies = [
4336
+ ...new Set(
4337
+ packages.length > 0 ? packages : Object.keys(runtimeDependencies).filter((name) => !runtimeDependencies[name]?.startsWith("npm:")).filter(
4338
+ (name) => !Object.hasOwn(manifest.optionalDependencies ?? {}, name) || findPackagePath(name, projectRoot) !== null
4339
+ ).sort()
4340
+ )
4341
+ ];
4342
+ createLogger("cli").setLevel(0 /* SILENT */);
4343
+ const resolver = new DepsConflictResolver({
4344
+ projectRoot,
4345
+ dependencies,
4346
+ packageManager,
4347
+ registry: registry2,
4348
+ offline,
4349
+ autoInstall: command === "prepare"
4350
+ });
4351
+ await resolver.initialize();
4352
+ const analysis = resolver.getAnalysisResult();
4353
+ const diagnostics = resolver.getDiagnostics();
4354
+ const report = {
4355
+ schemaVersion: 1,
4356
+ command,
4357
+ projectRoot,
4358
+ packageManager: resolver.getOptions().packageManager,
4359
+ dependencies,
4360
+ aliases: analysis.aliasMappings,
4361
+ activeAliases: resolver.getAliasPathMappings(),
4362
+ diagnostics,
4363
+ installation: resolver.getInstallResult()
4364
+ };
4365
+ if (json) {
4366
+ output.stdout(JSON.stringify(report, null, 2) + "\n");
4367
+ } else {
4368
+ output.stdout(
4369
+ "Analyzed " + dependencies.length + " dependencies; " + report.activeAliases.length + " active aliases; " + diagnostics.length + " diagnostics.\n"
4370
+ );
4371
+ for (const mapping of analysis.aliasMappings) {
4372
+ const active = report.activeAliases.some((entry) => entry.aliasName === mapping.aliasName);
4373
+ output.stdout(
4374
+ " " + mapping.originalName + "@" + mapping.resolvedVersion + " -> " + mapping.aliasName + (active ? " (active)" : " (requires prepare)") + "\n"
4375
+ );
4376
+ }
4377
+ for (const diagnostic of diagnostics) {
4378
+ output.stdout(" [" + diagnostic.code + "] " + diagnostic.message + "\n");
4379
+ }
4380
+ }
4381
+ return diagnostics.some((diagnostic) => diagnostic.severity === "error") && (strict || command === "prepare") ? 1 : 0;
4382
+ } catch (error) {
4383
+ const message = error instanceof Error ? error.message : String(error);
4384
+ if (json) {
4385
+ output.stdout(
4386
+ JSON.stringify(
4387
+ {
4388
+ error: message,
4389
+ diagnostics: error instanceof ResolutionError ? error.diagnostics : []
4390
+ },
4391
+ null,
4392
+ 2
4393
+ ) + "\n"
4394
+ );
4395
+ } else {
4396
+ output.stderr(message + "\n");
4397
+ }
4398
+ return 1;
4399
+ }
4400
+ }
4401
+
4402
+ // src/cli.ts
4403
+ void runCli(process.argv.slice(2)).then((code) => {
4404
+ process.exitCode = code;
4405
+ });
4406
+ //# sourceMappingURL=cli.js.map
4407
+ //# sourceMappingURL=cli.js.map