@ariestools/toolchain 8.7.1 → 8.7.3

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.
Files changed (59) hide show
  1. package/README.md +44 -0
  2. package/dist/actions/api-exposure/analyzer/analyzePackage.d.ts.map +1 -1
  3. package/dist/actions/api-exposure/reporters.d.ts.map +1 -1
  4. package/dist/actions/api-exposure/scoring.d.ts +1 -0
  5. package/dist/actions/api-exposure/scoring.d.ts.map +1 -1
  6. package/dist/actions/api-exposure/types.d.ts +3 -0
  7. package/dist/actions/api-exposure/types.d.ts.map +1 -1
  8. package/dist/actions/deplint/deplint.d.ts +3 -1
  9. package/dist/actions/deplint/deplint.d.ts.map +1 -1
  10. package/dist/actions/deplint/engine.d.ts +2 -2
  11. package/dist/actions/deplint/engine.d.ts.map +1 -1
  12. package/dist/actions/deplint/findFiles.d.ts.map +1 -1
  13. package/dist/actions/deplint/getCliReferencedPackagesFromFiles.d.ts.map +1 -1
  14. package/dist/actions/deplint/getImportsFromFile.d.ts.map +1 -1
  15. package/dist/actions/deplint/getStorybookConfigImports.d.ts.map +1 -1
  16. package/dist/actions/deplint/index.d.ts +2 -0
  17. package/dist/actions/deplint/index.d.ts.map +1 -1
  18. package/dist/actions/deplint/reporters.d.ts +6 -1
  19. package/dist/actions/deplint/reporters.d.ts.map +1 -1
  20. package/dist/actions/deplint/runDeplint.d.ts +4 -0
  21. package/dist/actions/deplint/runDeplint.d.ts.map +1 -0
  22. package/dist/actions/deplint/snapshot.d.ts +7 -0
  23. package/dist/actions/deplint/snapshot.d.ts.map +1 -1
  24. package/dist/actions/deplint/sourceFileCache.d.ts +11 -0
  25. package/dist/actions/deplint/sourceFileCache.d.ts.map +1 -0
  26. package/dist/actions/deplint/types.d.ts +31 -0
  27. package/dist/actions/deplint/types.d.ts.map +1 -1
  28. package/dist/actions/license.d.ts +2 -1
  29. package/dist/actions/license.d.ts.map +1 -1
  30. package/dist/actions/lintNextWorker.d.ts.map +1 -1
  31. package/dist/actions/package/compile/MonolithConfig.d.ts +10 -0
  32. package/dist/actions/package/compile/MonolithConfig.d.ts.map +1 -1
  33. package/dist/actions/package/compile/XyConfig.d.ts +2 -0
  34. package/dist/actions/package/compile/XyConfig.d.ts.map +1 -1
  35. package/dist/actions/package/compile/index.d.ts +1 -0
  36. package/dist/actions/package/compile/index.d.ts.map +1 -1
  37. package/dist/actions/package/compile/monolithCopyEntries.d.ts +14 -0
  38. package/dist/actions/package/compile/monolithCopyEntries.d.ts.map +1 -0
  39. package/dist/actions/package/compile/packageCompileMonolith.d.ts.map +1 -1
  40. package/dist/actions/package/expectedCompileOutputs.d.ts +1 -0
  41. package/dist/actions/package/expectedCompileOutputs.d.ts.map +1 -1
  42. package/dist/actions/package/exportMapPublint.d.ts.map +1 -1
  43. package/dist/bin/package/build.mjs +118 -14
  44. package/dist/bin/package/build.mjs.map +1 -1
  45. package/dist/bin/package/compile.mjs +84 -6
  46. package/dist/bin/package/compile.mjs.map +1 -1
  47. package/dist/bin/package/publint.mjs +95 -14
  48. package/dist/bin/package/publint.mjs.map +1 -1
  49. package/dist/bin/package/recompile.mjs +84 -6
  50. package/dist/bin/package/recompile.mjs.map +1 -1
  51. package/dist/bin/package/sync-layout.mjs +23 -6
  52. package/dist/bin/package/sync-layout.mjs.map +1 -1
  53. package/dist/bin/xy.mjs +1929 -1704
  54. package/dist/bin/xy.mjs.map +1 -1
  55. package/dist/lib/licenseCheck/checkLicenses.d.ts +17 -1
  56. package/dist/lib/licenseCheck/checkLicenses.d.ts.map +1 -1
  57. package/dist/lib/loadConfig.d.ts.map +1 -1
  58. package/dist/xy/lint/deplintCommand.d.ts.map +1 -1
  59. package/package.json +5 -5
package/dist/bin/xy.mjs CHANGED
@@ -71,9 +71,9 @@ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__ge
71
71
  var __require = /* #__PURE__ */ (() => createRequire(import.meta.url))();
72
72
  //#endregion
73
73
  //#region src/lib/bundledCliPath.ts
74
- const require$9 = createRequire(import.meta.url);
74
+ const require$8 = createRequire(import.meta.url);
75
75
  function toolchainPackageRoot() {
76
- return PATH.dirname(require$9.resolve("@ariestools/toolchain/package.json"));
76
+ return PATH.dirname(require$8.resolve("@ariestools/toolchain/package.json"));
77
77
  }
78
78
  function bundledCliPath(name) {
79
79
  return PATH.resolve(toolchainPackageRoot(), "dist/bin", name);
@@ -6669,9 +6669,9 @@ var require_semver = /* @__PURE__ */ __commonJSMin(((exports, module) => {
6669
6669
  }));
6670
6670
  //#endregion
6671
6671
  //#region src/lib/toolchainVersion.ts
6672
- const require$8 = createRequire(import.meta.url);
6672
+ const require$7 = createRequire(import.meta.url);
6673
6673
  function bundledToolchainVersion() {
6674
- const pkgPath = require$8.resolve("@ariestools/toolchain/package.json");
6674
+ const pkgPath = require$7.resolve("@ariestools/toolchain/package.json");
6675
6675
  const pkg = JSON.parse(readFileSync(pkgPath, "utf8"));
6676
6676
  if (pkg.version == null || pkg.version.length === 0) throw new Error("Could not read @ariestools/toolchain version");
6677
6677
  return pkg.version;
@@ -6818,8 +6818,8 @@ function setGitConfig(key, value) {
6818
6818
  }
6819
6819
  //#endregion
6820
6820
  //#region src/lib/gitignoreTemplate.ts
6821
- const require$7 = createRequire(import.meta.url);
6822
- const packageRoot$1 = PATH.dirname(require$7.resolve("@ariestools/toolchain/package.json"));
6821
+ const require$6 = createRequire(import.meta.url);
6822
+ const packageRoot$1 = PATH.dirname(require$6.resolve("@ariestools/toolchain/package.json"));
6823
6823
  const templatesDir = PATH.resolve(packageRoot$1, "templates", "gitignore");
6824
6824
  const gitignoreTemplate = () => readFileSync(PATH.resolve(templatesDir, "template.gitignore"), "utf8");
6825
6825
  //#endregion
@@ -6866,13 +6866,30 @@ function isAllowedLicense(license, allowed) {
6866
6866
  const trimmed = license.trim();
6867
6867
  return (trimmed.startsWith("(") && trimmed.endsWith(")") ? trimmed.slice(1, -1).trim() : trimmed).split(/\s+OR\s+/i).some((branch) => allowed.has(branch.trim()));
6868
6868
  }
6869
+ /** Effective allowlist for a workspace: (allowOnly ?? defaults) + allow − deny. */
6870
+ function resolveAllowedLicenses(config) {
6871
+ const base = config?.allowOnly ?? DEFAULT_ALLOWED_LICENSES;
6872
+ const allowed = /* @__PURE__ */ new Set([...base, ...config?.allow ?? []]);
6873
+ const denied = config?.deny ?? [];
6874
+ for (const identifier of denied) allowed.delete(identifier);
6875
+ return allowed;
6876
+ }
6877
+ /** Matches `name@version` keys against bare-name or pinned ignore entries. */
6878
+ function isIgnoredPackage(key, ignore) {
6879
+ if (ignore.size === 0) return false;
6880
+ if (ignore.has(key)) return true;
6881
+ const at = key.lastIndexOf("@");
6882
+ return at > 0 && ignore.has(key.slice(0, at));
6883
+ }
6869
6884
  /**
6870
6885
  * Returns findings for packages whose declared licenses are not on the
6871
6886
  * allowlist. Empty license arrays are treated as allowed (unknown).
6872
6887
  */
6873
- function findDisallowedLicenses(packages, allowed = new Set(DEFAULT_ALLOWED_LICENSES)) {
6888
+ function findDisallowedLicenses(packages, allowed = new Set(DEFAULT_ALLOWED_LICENSES), ignorePackages = []) {
6874
6889
  const findings = [];
6890
+ const ignore = new Set(ignorePackages);
6875
6891
  for (const [packageName, info] of Object.entries(packages)) {
6892
+ if (isIgnoredPackage(packageName, ignore)) continue;
6876
6893
  const licenses = Array.isArray(info.licenses) ? info.licenses : info.licenses === void 0 ? [] : [info.licenses];
6877
6894
  for (const license of licenses) if (!isAllowedLicense(license, allowed)) findings.push({
6878
6895
  packageName,
@@ -11939,22 +11956,33 @@ function ruleConfigPath(configKey, ruleId) {
11939
11956
  var import_dist$1 = require_dist$1();
11940
11957
  const configState = {
11941
11958
  config: void 0,
11959
+ /** In-flight root load so concurrent callers share one cosmiconfig search. */
11960
+ loadPromise: void 0,
11942
11961
  rootConfigPath: void 0
11943
11962
  };
11944
11963
  const workspaceConfigCache = /* @__PURE__ */ new Map();
11964
+ /** In-flight workspace loads — concurrent jobs for the same dir share one search. */
11965
+ const workspaceConfigLoadPromises = /* @__PURE__ */ new Map();
11945
11966
  const deprecationWarned = /* @__PURE__ */ new Set();
11946
11967
  function isRecord$6(value) {
11947
11968
  return typeof value === "object" && value !== null && !Array.isArray(value);
11948
11969
  }
11949
- function createExplorer() {
11950
- return (0, import_dist$1.cosmiconfig)("xy", {
11970
+ const explorerState = {};
11971
+ function getExplorer() {
11972
+ explorerState.current ??= (0, import_dist$1.cosmiconfig)("xy", {
11951
11973
  cache: true,
11952
11974
  loaders: { ".ts": TypeScriptLoader() }
11953
11975
  });
11976
+ return explorerState.current;
11954
11977
  }
11955
- const loadConfig = async (params) => {
11956
- if (configState.config === void 0) {
11957
- const cosmicConfigResult = await createExplorer().search();
11978
+ async function ensureRootConfigLoaded() {
11979
+ if (configState.config !== void 0) return;
11980
+ if (configState.loadPromise !== void 0) {
11981
+ await configState.loadPromise;
11982
+ return;
11983
+ }
11984
+ configState.loadPromise = (async () => {
11985
+ const cosmicConfigResult = await getExplorer().search();
11958
11986
  configState.config = cosmicConfigResult?.config ?? {};
11959
11987
  configState.rootConfigPath = cosmicConfigResult?.filepath;
11960
11988
  const configFilePath = cosmicConfigResult?.filepath;
@@ -11962,8 +11990,16 @@ const loadConfig = async (params) => {
11962
11990
  console.log(chalk.green(`Loaded config from ${configFilePath}`));
11963
11991
  if (Boolean(configState.config.verbose)) console.log(chalk.gray(JSON.stringify(configState.config, null, 2)));
11964
11992
  }
11993
+ })();
11994
+ try {
11995
+ await configState.loadPromise;
11996
+ } finally {
11997
+ configState.loadPromise = void 0;
11965
11998
  }
11966
- return deepMerge(configState.config, params ?? {});
11999
+ }
12000
+ const loadConfig = async (params) => {
12001
+ await ensureRootConfigLoaded();
12002
+ return deepMerge(configState.config ?? {}, params ?? {});
11967
12003
  };
11968
12004
  /**
11969
12005
  * Loads the xy.config from a specific workspace directory.
@@ -11973,14 +12009,25 @@ const loadConfig = async (params) => {
11973
12009
  async function loadWorkspaceConfig(workspaceDir) {
11974
12010
  const cached = workspaceConfigCache.get(workspaceDir);
11975
12011
  if (cached !== void 0) return cached;
11976
- const result = await createExplorer().search(workspaceDir);
11977
- if (!result || result.filepath === configState.rootConfigPath) {
11978
- workspaceConfigCache.set(workspaceDir, {});
11979
- return {};
12012
+ const inFlight = workspaceConfigLoadPromises.get(workspaceDir);
12013
+ if (inFlight !== void 0) return inFlight;
12014
+ const loadPromise = (async () => {
12015
+ await ensureRootConfigLoaded();
12016
+ const result = await getExplorer().search(workspaceDir);
12017
+ if (!result || result.filepath === configState.rootConfigPath) {
12018
+ workspaceConfigCache.set(workspaceDir, {});
12019
+ return {};
12020
+ }
12021
+ const wsConfig = result.config ?? {};
12022
+ workspaceConfigCache.set(workspaceDir, wsConfig);
12023
+ return wsConfig;
12024
+ })();
12025
+ workspaceConfigLoadPromises.set(workspaceDir, loadPromise);
12026
+ try {
12027
+ return await loadPromise;
12028
+ } finally {
12029
+ workspaceConfigLoadPromises.delete(workspaceDir);
11980
12030
  }
11981
- const wsConfig = result.config ?? {};
11982
- workspaceConfigCache.set(workspaceDir, wsConfig);
11983
- return wsConfig;
11984
12031
  }
11985
12032
  /** Deprecated top-level fields that should be under `commands`. */
11986
12033
  const DEPRECATED_COMMAND_FIELDS = /* @__PURE__ */ new Set(["deplint", "publint"]);
@@ -13556,7 +13603,7 @@ function isMatch(input, pattern, options = {}) {
13556
13603
  //#endregion
13557
13604
  //#region src/lib/npmLatestVersion.ts
13558
13605
  const REGISTRY_BASE$3 = "https://registry.npmjs.org";
13559
- const cache$2 = /* @__PURE__ */ new Map();
13606
+ const cache$3 = /* @__PURE__ */ new Map();
13560
13607
  async function fetchUncached$1(packageName) {
13561
13608
  try {
13562
13609
  const url = `${REGISTRY_BASE$3}/${encodeURIComponent(packageName)}/latest`;
@@ -13568,10 +13615,10 @@ async function fetchUncached$1(packageName) {
13568
13615
  }
13569
13616
  }
13570
13617
  function fetchLatestPackageVersion(packageName) {
13571
- const existing = cache$2.get(packageName);
13618
+ const existing = cache$3.get(packageName);
13572
13619
  if (existing) return existing;
13573
13620
  const pending = fetchUncached$1(packageName);
13574
- cache$2.set(packageName, pending);
13621
+ cache$3.set(packageName, pending);
13575
13622
  return pending;
13576
13623
  }
13577
13624
  //#endregion
@@ -20421,8 +20468,8 @@ async function withEnvelope(command, action) {
20421
20468
  }
20422
20469
  //#endregion
20423
20470
  //#region src/lib/repoTemplates.ts
20424
- const require$6 = createRequire(import.meta.url);
20425
- const packageRoot = PATH.dirname(require$6.resolve("@ariestools/toolchain/package.json"));
20471
+ const require$5 = createRequire(import.meta.url);
20472
+ const packageRoot = PATH.dirname(require$5.resolve("@ariestools/toolchain/package.json"));
20426
20473
  const repoTemplatesDir = PATH.resolve(packageRoot, "templates", "repo");
20427
20474
  function collectFiles$1(dir, prefix) {
20428
20475
  const results = [];
@@ -23736,11 +23783,13 @@ function scoreDependency(findings, thresholds) {
23736
23783
  let crs = 0;
23737
23784
  let treeShakingModifier = 0;
23738
23785
  let aeiInfinite = false;
23786
+ let crsInfinite = false;
23739
23787
  for (const finding of findings) {
23740
23788
  const rule = getAeiRule(finding.ruleId);
23741
23789
  if (rule === void 0) throw new TypeError(`Finding references unknown api-exposure rule "${finding.ruleId}"`);
23742
23790
  if (finding.infinite) {
23743
- aeiInfinite = true;
23791
+ if (rule.kind === "exposure" || rule.kind === "modifier") aeiInfinite = true;
23792
+ else crsInfinite = true;
23744
23793
  continue;
23745
23794
  }
23746
23795
  if (rule.kind === "exposure" || rule.kind === "modifier") {
@@ -23748,11 +23797,12 @@ function scoreDependency(findings, thresholds) {
23748
23797
  if (rule.kind === "modifier") treeShakingModifier += finding.weight;
23749
23798
  } else crs += finding.weight;
23750
23799
  }
23751
- const recommendation = aeiInfinite ? "peer" : combineBands(aeiBandForScore(aei, thresholds), crsBandForScore(crs));
23800
+ const recommendation = aeiInfinite || crsInfinite ? "peer" : combineBands(aeiBandForScore(aei, thresholds), crsBandForScore(crs));
23752
23801
  return {
23753
23802
  aei,
23754
23803
  aeiInfinite,
23755
23804
  crs,
23805
+ crsInfinite,
23756
23806
  recommendation,
23757
23807
  treeShakingModifier
23758
23808
  };
@@ -24436,6 +24486,11 @@ function couplingSourceFiles(workspaceDir, programFiles) {
24436
24486
  return findFilesByGlob(workspaceDir, "./src/**/*.{ts,tsx,mts,cts}", ["**/node_modules/**"]).filter((file) => !file.endsWith(".d.ts"));
24437
24487
  }
24438
24488
  const PROVIDED_CLOSURE_DEPTH = 2;
24489
+ const PROVIDED_CANDIDATE_BANDS = /* @__PURE__ */ new Set([
24490
+ "review",
24491
+ "probably-peer",
24492
+ "peer"
24493
+ ]);
24439
24494
  /**
24440
24495
  * True when `target` is provided by the dependency closure of one of the
24441
24496
  * package's declared deps (depth-limited, mirroring the peer-chain walk).
@@ -24511,6 +24566,7 @@ function assessDependency({ config, dependency, isSelfOrInternal, isTerminal, ra
24511
24566
  aei: score.aei,
24512
24567
  aeiInfinite: score.aeiInfinite,
24513
24568
  crs: score.crs,
24569
+ crsInfinite: score.crsInfinite,
24514
24570
  currentSection: currentSectionOf(dependency, sections),
24515
24571
  dependency,
24516
24572
  findings,
@@ -24531,7 +24587,7 @@ function resolveRecommendation(scored, findings, { config, dependency, isSelfOrI
24531
24587
  if (isTerminal === true) return ["dependency", "terminal"];
24532
24588
  if (isSelfOrInternal(dependency)) return ["dependency", "workspace-internal"];
24533
24589
  if (dependency.startsWith("@types/")) return ["dependency", "types-package"];
24534
- if ((scored === "peer" || scored === "probably-peer") && currentSectionOf(dependency, sections) === "unlisted" && findings.every((finding) => finding.ruleId !== "aei.signal.required-peer") && isProvidedByDeclaredDeps(workspaceDir, [...sections.dependencies, ...sections.peerDependencies], dependency)) return config.ruleFor("aei.exposure.provided-transitive", dependency)?.enabled === true ? ["review", "provided"] : void 0;
24590
+ if (PROVIDED_CANDIDATE_BANDS.has(scored) && currentSectionOf(dependency, sections) === "unlisted" && findings.every((finding) => finding.ruleId !== "aei.signal.required-peer") && isProvidedByDeclaredDeps(workspaceDir, [...sections.dependencies, ...sections.peerDependencies], dependency)) return config.ruleFor("aei.exposure.provided-transitive", dependency)?.enabled === true ? ["review", "provided"] : void 0;
24535
24591
  return [scored, "score"];
24536
24592
  }
24537
24593
  /**
@@ -24601,7 +24657,7 @@ function bandColor(band) {
24601
24657
  }
24602
24658
  }
24603
24659
  function formatScore(assessment) {
24604
- return `AEI ${assessment.aeiInfinite ? `${assessment.aei} (∞)` : String(assessment.aei)} CRS ${assessment.crs}`;
24660
+ return `AEI ${assessment.aeiInfinite ? `${assessment.aei} (∞)` : String(assessment.aei)} CRS ${assessment.crsInfinite ? `${assessment.crs} (∞)` : String(assessment.crs)}`;
24605
24661
  }
24606
24662
  function renderAssessment(assessment, verbose) {
24607
24663
  const color = bandColor(assessment.recommendation);
@@ -24874,7 +24930,7 @@ function getReExportSpecs(file) {
24874
24930
  }
24875
24931
  //#endregion
24876
24932
  //#region src/actions/barrel/resolveBarrel.ts
24877
- const require$5 = createRequire(import.meta.url);
24933
+ const require$4 = createRequire(import.meta.url);
24878
24934
  function findPackageRoot(entry, pkg) {
24879
24935
  let dir = PATH.dirname(entry);
24880
24936
  for (;;) {
@@ -24896,10 +24952,10 @@ function findPackageRoot(entry, pkg) {
24896
24952
  */
24897
24953
  function resolvePackageDir(pkg, fromDir) {
24898
24954
  try {
24899
- return PATH.dirname(require$5.resolve(`${pkg}/package.json`, { paths: [fromDir] }));
24955
+ return PATH.dirname(require$4.resolve(`${pkg}/package.json`, { paths: [fromDir] }));
24900
24956
  } catch {}
24901
24957
  try {
24902
- return findPackageRoot(require$5.resolve(pkg, { paths: [fromDir] }), pkg);
24958
+ return findPackageRoot(require$4.resolve(pkg, { paths: [fromDir] }), pkg);
24903
24959
  } catch {
24904
24960
  return;
24905
24961
  }
@@ -24955,6 +25011,38 @@ function analyzeBarrel(barrelPkg, fromDir, scopePrefix) {
24955
25011
  return [...collected].toSorted((a, b) => a.localeCompare(b));
24956
25012
  }
24957
25013
  //#endregion
25014
+ //#region src/actions/deplint/sourceFileCache.ts
25015
+ const cache$2 = /* @__PURE__ */ new Map();
25016
+ function scriptKindForPath(filePath) {
25017
+ if (/\.(?:mjs|cjs|js)$/i.test(filePath)) return ts.ScriptKind.JS;
25018
+ if (/\.tsx$/i.test(filePath)) return ts.ScriptKind.TSX;
25019
+ if (/\.jsx$/i.test(filePath)) return ts.ScriptKind.JSX;
25020
+ }
25021
+ function getCachedSourceFile(filePath) {
25022
+ const cached = cache$2.get(filePath);
25023
+ if (cached !== void 0) return cached;
25024
+ const sourceCode = fs.readFileSync(filePath, "utf8");
25025
+ const entry = {
25026
+ sourceCode,
25027
+ sourceFile: ts.createSourceFile(PATH.basename(filePath), sourceCode, ts.ScriptTarget.Latest, true, scriptKindForPath(filePath))
25028
+ };
25029
+ cache$2.set(filePath, entry);
25030
+ return entry;
25031
+ }
25032
+ /** Like getCachedSourceFile, but returns undefined when the file cannot be read. */
25033
+ function tryGetCachedSourceFile(filePath) {
25034
+ const cached = cache$2.get(filePath);
25035
+ if (cached !== void 0) return cached;
25036
+ try {
25037
+ return getCachedSourceFile(filePath);
25038
+ } catch {
25039
+ return;
25040
+ }
25041
+ }
25042
+ function clearSourceFileCache() {
25043
+ cache$2.clear();
25044
+ }
25045
+ //#endregion
24958
25046
  //#region src/actions/deplint/findFiles.ts
24959
25047
  const codeExtensions$1 = "*.{ts,tsx,mts,cts,js,mjs,cjs}";
24960
25048
  const codeExtensionRe = /\.(?:ts|tsx|mts|cts|js|mjs|cjs)$/i;
@@ -25083,9 +25171,7 @@ function resolveRuntimeEntry(location, entry) {
25083
25171
  return resolved != null && resolved.length > 0 ? [resolved] : [];
25084
25172
  }
25085
25173
  function collectLocalImportSpecifiers(filePath) {
25086
- const sourceCode = fs.readFileSync(filePath, "utf8");
25087
- const isJsFile = /\.(?:js|mjs|cjs)$/i.test(filePath);
25088
- const sourceFile = ts.createSourceFile(PATH.basename(filePath), sourceCode, ts.ScriptTarget.Latest, true, isJsFile ? ts.ScriptKind.JS : void 0);
25174
+ const { sourceFile } = getCachedSourceFile(filePath);
25089
25175
  const imports = [];
25090
25176
  function addModuleSpecifier(moduleSpecifier) {
25091
25177
  if (moduleSpecifier && ts.isStringLiteral(moduleSpecifier) && moduleSpecifier.text.startsWith(".")) imports.push(moduleSpecifier.text);
@@ -26886,340 +26972,982 @@ const compileAll = ({ shouldExitOnFail, jobs, isVerbose, incremental, incrementa
26886
26972
  return shouldExitOnFail === void 0 ? safeExitAsync(action) : safeExitAsync(action, shouldExitOnFail);
26887
26973
  };
26888
26974
  //#endregion
26889
- //#region ../../node_modules/.pnpm/sort-object-keys@2.1.0/node_modules/sort-object-keys/index.js
26890
- const has = (object, key) => Object.prototype.hasOwnProperty.call(object, key);
26891
- function sortObjectByKeyNameList(object, sortWith) {
26892
- let keys, sortFn, key;
26893
- if (typeof sortWith === "function") sortFn = sortWith;
26894
- else keys = sortWith;
26895
- const total = {};
26896
- for (key of [...keys ?? [], ...Object.keys(object).sort(sortFn)]) if (has(object, key)) total[key] = object[key];
26897
- return total;
26975
+ //#region src/actions/deplint/reporters.ts
26976
+ function pluralize(word, count) {
26977
+ return `${word}${count === 1 ? "" : "s"}`;
26898
26978
  }
26899
- //#endregion
26900
- //#region ../../node_modules/.pnpm/detect-indent@7.0.2/node_modules/detect-indent/index.js
26901
- const INDENT_REGEX = /^(?:( )+|\t+)/;
26902
- const INDENT_TYPE_SPACE = "space";
26903
- const INDENT_TYPE_TAB = "tab";
26904
- function shouldIgnoreSingleSpace(ignoreSingleSpaces, indentType, value) {
26905
- return ignoreSingleSpaces && indentType === INDENT_TYPE_SPACE && value === 1;
26979
+ function formatDuration$2(ms) {
26980
+ if (ms < 10) return `${ms.toFixed(1)}ms`;
26981
+ if (ms < 1e3) return `${Math.round(ms)}ms`;
26982
+ return `${(ms / 1e3).toFixed(2)}s`;
26906
26983
  }
26907
- /**
26908
- Make a Map that counts how many indents/unindents have occurred for a given size and how many lines follow a given indentation.
26909
-
26910
- The key is a concatenation of the indentation type (s = space and t = tab) and the size of the indents/unindents.
26911
-
26912
- ```
26913
- indents = {
26914
- t3: [1, 0],
26915
- t4: [1, 5],
26916
- s5: [1, 0],
26917
- s12: [1, 0],
26984
+ function formatWorkspaceList(workspaces) {
26985
+ const names = workspaces.map((workspace) => workspace.name);
26986
+ if (names.length <= 5) return names.join(", ");
26987
+ return `${names.slice(0, 5).join(", ")} +${names.length - 5} more`;
26918
26988
  }
26919
- ```
26920
- */
26921
- function makeIndentsMap(string, ignoreSingleSpaces) {
26922
- const indents = /* @__PURE__ */ new Map();
26923
- let previousSize = 0;
26924
- let previousIndentType;
26925
- let key;
26926
- for (const line of string.split(/\n/g)) {
26927
- if (!line) continue;
26928
- const matches = line.match(INDENT_REGEX);
26929
- if (matches === null) {
26930
- previousSize = 0;
26931
- previousIndentType = "";
26932
- } else {
26933
- const indent = matches[0].length;
26934
- const indentType = matches[1] ? INDENT_TYPE_SPACE : INDENT_TYPE_TAB;
26935
- if (shouldIgnoreSingleSpace(ignoreSingleSpaces, indentType, indent)) continue;
26936
- if (indentType !== previousIndentType) previousSize = 0;
26937
- previousIndentType = indentType;
26938
- let use = 1;
26939
- let weight = 0;
26940
- const indentDifference = indent - previousSize;
26941
- previousSize = indent;
26942
- if (indentDifference === 0) {
26943
- use = 0;
26944
- weight = 1;
26945
- } else {
26946
- const absoluteIndentDifference = Math.abs(indentDifference);
26947
- if (shouldIgnoreSingleSpace(ignoreSingleSpaces, indentType, absoluteIndentDifference)) continue;
26948
- key = encodeIndentsKey(indentType, absoluteIndentDifference);
26949
- }
26950
- const entry = indents.get(key);
26951
- indents.set(key, entry === void 0 ? [1, 0] : [entry[0] + use, entry[1] + weight]);
26989
+ function groupedDiagnostics(diagnostics) {
26990
+ const workspaces = /* @__PURE__ */ new Map();
26991
+ for (const diagnostic of diagnostics) {
26992
+ const key = diagnostic.workspace.location;
26993
+ let workspaceGroup = workspaces.get(key);
26994
+ if (!workspaceGroup) {
26995
+ workspaceGroup = {
26996
+ diagnostics: 0,
26997
+ rules: /* @__PURE__ */ new Map(),
26998
+ workspace: diagnostic.workspace
26999
+ };
27000
+ workspaces.set(key, workspaceGroup);
26952
27001
  }
27002
+ workspaceGroup.diagnostics += 1;
27003
+ const rules = workspaceGroup.rules;
27004
+ const ruleDiagnostics = rules.get(diagnostic.id) ?? [];
27005
+ ruleDiagnostics.push(diagnostic);
27006
+ rules.set(diagnostic.id, ruleDiagnostics);
26953
27007
  }
26954
- return indents;
26955
- }
26956
- function encodeIndentsKey(indentType, indentAmount) {
26957
- return (indentType === INDENT_TYPE_SPACE ? "s" : "t") + String(indentAmount);
27008
+ return workspaces.values().toArray();
26958
27009
  }
26959
- function decodeIndentsKey(indentsKey) {
26960
- return {
26961
- type: indentsKey[0] === "s" ? INDENT_TYPE_SPACE : INDENT_TYPE_TAB,
26962
- amount: Number(indentsKey.slice(1))
26963
- };
27010
+ function createHumanDeplintProgressReporter({ isVerbose = false } = {}) {
27011
+ return (event) => renderHumanDeplintProgressEvent(event, isVerbose);
26964
27012
  }
26965
- function getMostUsedKey(indents) {
26966
- let result;
26967
- let maxUsed = 0;
26968
- let maxWeight = 0;
26969
- for (const [key, [usedCount, weight]] of indents) if (usedCount > maxUsed || usedCount === maxUsed && weight > maxWeight) {
26970
- maxUsed = usedCount;
26971
- maxWeight = weight;
26972
- result = key;
27013
+ function renderHumanDeplintProgressEvent(event, isVerbose) {
27014
+ switch (event.type) {
27015
+ case "run-start":
27016
+ renderRunStart(event);
27017
+ break;
27018
+ case "workspace-start":
27019
+ renderWorkspaceHeader(event);
27020
+ if (isVerbose) renderVerboseWorkspaceDetails(event);
27021
+ break;
27022
+ case "fix-start":
27023
+ renderFixStart(event);
27024
+ break;
27025
+ case "fix-end":
27026
+ renderFixEnd(event);
27027
+ break;
27028
+ default: if (isVerbose) renderVerboseProgressEvent(event);
26973
27029
  }
26974
- return result;
26975
27030
  }
26976
- function makeIndentString(type, amount) {
26977
- return (type === INDENT_TYPE_SPACE ? " " : " ").repeat(amount);
27031
+ function renderRunStart(event) {
27032
+ const categories = event.activeCategories.join(", ");
27033
+ const fixDetail = event.fix ? ` with --fix (max ${event.maxFixPasses} fix ${pluralize("pass", event.maxFixPasses)})` : "";
27034
+ console.info(`Deplint: checking ${event.workspaces.length} ${pluralize("workspace", event.workspaces.length)} [${categories}]${fixDetail}`);
27035
+ console.info(`Workspaces: ${formatWorkspaceList(event.workspaces)}`);
26978
27036
  }
26979
- function detectIndent(string) {
26980
- if (typeof string !== "string") throw new TypeError("Expected a string");
26981
- let indents = makeIndentsMap(string, true);
26982
- if (indents.size === 0) indents = makeIndentsMap(string, false);
26983
- const keyOfMostUsedIndent = getMostUsedKey(indents);
26984
- let type;
26985
- let amount = 0;
26986
- let indent = "";
26987
- if (keyOfMostUsedIndent !== void 0) {
26988
- ({type, amount} = decodeIndentsKey(keyOfMostUsedIndent));
26989
- indent = makeIndentString(type, amount);
27037
+ function renderFixStart(event) {
27038
+ console.info(`Deplint: fix pass ${event.fixPass} resolving ${event.diagnostics} ${pluralize("diagnostic", event.diagnostics)}`);
27039
+ }
27040
+ function renderFixEnd(event) {
27041
+ console.info(`Deplint: fix pass ${event.fixPass} applied ${event.appliedFixes} ${pluralize("fix", event.appliedFixes)}`);
27042
+ }
27043
+ function renderVerboseProgressEvent(event) {
27044
+ switch (event.type) {
27045
+ case "pass-start":
27046
+ console.info(chalk.dim(`Deplint pass ${event.pass}: evaluating ${event.workspaces.length} ${pluralize("workspace", event.workspaces.length)}`));
27047
+ break;
27048
+ case "pass-end":
27049
+ console.info(chalk.dim(`Deplint pass ${event.pass}: ${event.diagnostics} ${pluralize("diagnostic", event.diagnostics)}, ${event.rulesEvaluated} ${pluralize("rule", event.rulesEvaluated)} evaluated, ${event.rulesSkipped} skipped`));
27050
+ break;
27051
+ case "workspace-end":
27052
+ console.info(chalk.dim(`[${event.workspace.name}] pass ${event.pass}: ${event.diagnostics} ${pluralize("diagnostic", event.diagnostics)}`));
27053
+ break;
27054
+ case "rule-start":
27055
+ console.info(chalk.dim(` rule ${event.ruleIndex}/${event.ruleTotal}: ${event.rule.id}`));
27056
+ break;
27057
+ case "rule-end":
27058
+ console.info(chalk.dim(` ${event.diagnostics} ${pluralize("finding", event.diagnostics)} in ${event.elapsedMs}ms`));
27059
+ break;
27060
+ case "rule-skip":
27061
+ console.info(chalk.dim(` skip ${event.ruleIndex}/${event.ruleTotal}: ${event.rule.id} (${event.reason})`));
27062
+ break;
26990
27063
  }
26991
- return {
26992
- amount,
26993
- type,
26994
- indent
26995
- };
26996
27064
  }
26997
- //#endregion
26998
- //#region ../../node_modules/.pnpm/detect-newline@4.0.1/node_modules/detect-newline/index.js
26999
- function detectNewline(string) {
27000
- if (typeof string !== "string") throw new TypeError("Expected a string");
27001
- const newlines = string.match(/(?:\r?\n)/g) || [];
27002
- if (newlines.length === 0) return;
27003
- const crlf = newlines.filter((newline) => newline === "\r\n").length;
27004
- return crlf > newlines.length - crlf ? "\r\n" : "\n";
27065
+ function renderWorkspaceHeader(event) {
27066
+ console.info(`[${chalk.blue(event.workspace.name)}] package ${event.workspaceIndex}/${event.workspaceTotal}: ${event.workspace.location} (${event.context.packageKind})`);
27005
27067
  }
27006
- function detectNewlineGraceful(string) {
27007
- return typeof string === "string" && detectNewline(string) || "\n";
27068
+ function renderVerboseWorkspaceDetails(event) {
27069
+ const forcedRefs = event.context.forceDeps + event.context.forceDevs + event.context.forcePeers + event.context.forcePeerOptional;
27070
+ console.info(chalk.dim(` files: ${event.context.allFiles} all, ${event.context.distFiles} dist; deps: ${event.context.dependencies}, dev: ${event.context.devDependencies}, peer: ${event.context.peerDependencies}; exclude: ${event.context.excludeCount}, forced refs: ${forcedRefs}`));
27008
27071
  }
27009
- //#endregion
27010
- //#region ../../node_modules/.pnpm/git-hooks-list@4.2.1/node_modules/git-hooks-list/index.json
27011
- var git_hooks_list_default = [
27012
- "applypatch-msg",
27013
- "pre-applypatch",
27014
- "post-applypatch",
27015
- "pre-commit",
27016
- "pre-merge-commit",
27017
- "prepare-commit-msg",
27018
- "commit-msg",
27019
- "post-commit",
27020
- "pre-rebase",
27021
- "post-checkout",
27022
- "post-merge",
27023
- "pre-push",
27024
- "pre-receive",
27025
- "update",
27026
- "proc-receive",
27027
- "post-receive",
27028
- "post-update",
27029
- "reference-transaction",
27030
- "push-to-checkout",
27031
- "pre-auto-gc",
27032
- "post-rewrite",
27033
- "sendemail-validate",
27034
- "fsmonitor-watchman",
27035
- "p4-changelist",
27036
- "p4-prepare-changelist",
27037
- "p4-post-changelist",
27038
- "p4-pre-submit",
27039
- "post-index-change"
27040
- ];
27041
- //#endregion
27042
- //#region ../../node_modules/.pnpm/is-plain-obj@4.1.0/node_modules/is-plain-obj/index.js
27043
- function isPlainObject(value) {
27044
- if (typeof value !== "object" || value === null) return false;
27045
- const prototype = Object.getPrototypeOf(value);
27046
- return (prototype === null || prototype === Object.prototype || Object.getPrototypeOf(prototype) === null) && !(Symbol.toStringTag in value) && !(Symbol.iterator in value);
27072
+ const humanDeplintReporter = { render(result) {
27073
+ for (const fix of result.appliedFixes) console.log(`[${chalk.blue(fix.workspace.name)}] Fixed: ${fix.detail} ${chalk.green(fix.dependency)}`);
27074
+ for (const workspaceGroup of groupedDiagnostics(result.diagnostics)) {
27075
+ console.log(`[${chalk.blue(workspaceGroup.workspace.name)}] ${workspaceGroup.diagnostics} ${pluralize("problem", workspaceGroup.diagnostics)}`);
27076
+ for (const [ruleId, diagnostics] of workspaceGroup.rules) {
27077
+ console.log(` ${chalk.cyan(ruleId)} (${diagnostics.length})`);
27078
+ for (const diagnostic of diagnostics) {
27079
+ console.log(` ${diagnostic.message}`);
27080
+ if (diagnostic.fixable) console.log(` ${chalk.dim("fixable with `--fix`")}`);
27081
+ const evidence = diagnostic.evidence ?? [];
27082
+ for (const line of evidence) console.log(` ${line}`);
27083
+ console.log(` ${chalk.yellow(diagnostic.file)}`);
27084
+ }
27085
+ }
27086
+ console.log("");
27087
+ }
27088
+ if (result.summary.problemCount > 0) {
27089
+ const summaryMessage = [
27090
+ `✖ ${result.summary.problemCount} ${pluralize("problem", result.summary.problemCount)}`,
27091
+ `(${result.summary.errorCount} ${pluralize("error", result.summary.errorCount)},`,
27092
+ `${result.summary.warningCount} ${pluralize("warning", result.summary.warningCount)})`
27093
+ ].join(" ");
27094
+ const colorizeSummary = (message) => {
27095
+ if (result.summary.errorCount > 0) return chalk.red(message);
27096
+ return chalk.yellow(message);
27097
+ };
27098
+ console.warn(colorizeSummary(summaryMessage));
27099
+ if (result.summary.fixableErrorCount > 0 || result.summary.fixableWarningCount > 0) {
27100
+ const fixableMessage = [
27101
+ ` ${result.summary.fixableErrorCount} ${pluralize("error", result.summary.fixableErrorCount)}`,
27102
+ `and ${result.summary.fixableWarningCount} ${pluralize("warning", result.summary.fixableWarningCount)}`,
27103
+ "potentially fixable with the `--fix` option."
27104
+ ].join(" ");
27105
+ console.warn(colorizeSummary(fixableMessage));
27106
+ }
27107
+ if (result.summary.diagnosticsByRule !== void 0) {
27108
+ const byRule = Object.entries(result.summary.diagnosticsByRule).map(([rule, count]) => `${rule}: ${count}`).join(", ");
27109
+ if (byRule.length > 0) console.warn(colorizeSummary(` By rule: ${byRule}`));
27110
+ }
27111
+ if (result.summary.passesRun !== void 0 && result.summary.rulesEvaluated !== void 0) console.warn(chalk.dim(` Checked ${result.summary.workspacesChecked} ${pluralize("workspace", result.summary.workspacesChecked)} across ${result.summary.passesRun} ${pluralize("pass", result.summary.passesRun)}; ${result.summary.rulesEvaluated} ${pluralize("rule", result.summary.rulesEvaluated)} evaluated, ${result.summary.rulesSkipped ?? 0} skipped.`));
27112
+ return;
27113
+ }
27114
+ const detail = result.summary.passesRun === void 0 ? "" : chalk.dim(` Checked ${result.summary.workspacesChecked} ${pluralize("workspace", result.summary.workspacesChecked)} across ${result.summary.passesRun} ${pluralize("pass", result.summary.passesRun)}.`);
27115
+ const summaryMessage = `(${result.summary.errorCount} ${pluralize("error", result.summary.errorCount)}, ${result.summary.warningCount} ${pluralize("warning", result.summary.warningCount)})`;
27116
+ console.info(`Deplint: Found no dependency problems. ${chalk.green("✔")} ${summaryMessage}${detail}`);
27117
+ } };
27118
+ const jsonDeplintReporter = { render(result) {
27119
+ console.log(JSON.stringify(result, null, 2));
27120
+ } };
27121
+ function getDeplintReporter(format) {
27122
+ return format === "json" ? jsonDeplintReporter : humanDeplintReporter;
27047
27123
  }
27048
- //#endregion
27049
- //#region ../../node_modules/.pnpm/sort-package-json@4.0.0/node_modules/sort-package-json/index.js
27050
- var import_compare = /* @__PURE__ */ __toESM(require_compare(), 1);
27051
- var import_min_version = /* @__PURE__ */ __toESM(require_min_version(), 1);
27052
- const pipe = (fns) => (x, ...args) => fns.reduce((result, fn) => fn(result, ...args), x);
27053
- const onArray = (fn) => (x) => Array.isArray(x) ? fn(x) : x;
27054
- const onStringArray = (fn) => (x) => Array.isArray(x) && x.every((item) => typeof item === "string") ? fn(x) : x;
27055
- const uniq = onStringArray((xs) => [...new Set(xs)]);
27056
- const uniqAndSortArray = pipe([uniq, onStringArray((array) => array.toSorted())]);
27057
- const onObject = (fn) => (x, ...args) => isPlainObject(x) ? fn(x, ...args) : x;
27058
- const sortObjectBy = (comparator, deep) => {
27059
- const over = onObject((object) => {
27060
- if (deep) object = Object.fromEntries(Object.entries(object).map(([key, value]) => [key, over(value)]));
27061
- return sortObjectByKeyNameList(object, comparator);
27062
- });
27063
- return over;
27064
- };
27065
- const sortObject = sortObjectBy();
27066
- const sortURLObject = sortObjectBy(["type", "url"]);
27067
- const sortPeopleObject = sortObjectBy([
27068
- "name",
27069
- "email",
27070
- "url"
27071
- ]);
27072
- const sortDirectories = sortObjectBy([
27073
- "lib",
27074
- "bin",
27075
- "man",
27076
- "doc",
27077
- "example",
27078
- "test"
27079
- ]);
27080
- const overProperty = (property, over) => onObject((object, ...args) => Object.hasOwn(object, property) ? {
27081
- ...object,
27082
- [property]: over(object[property], ...args)
27083
- } : object);
27084
- const sortGitHooks = sortObjectBy(git_hooks_list_default);
27085
- const parseNameAndVersionRange = (specifier) => {
27086
- const [nameAndVersion] = specifier.split(">");
27087
- const atMatches = [...nameAndVersion.matchAll("@")];
27088
- if (!atMatches.length || atMatches.length === 1 && atMatches[0].index === 0) return { name: specifier };
27089
- const splitIndex = atMatches.pop().index;
27090
- return {
27091
- name: nameAndVersion.substring(0, splitIndex),
27092
- range: nameAndVersion.substring(splitIndex + 1)
27093
- };
27094
- };
27095
- const sortObjectBySemver = sortObjectBy((a, b) => {
27096
- const { name: aName, range: aRange } = parseNameAndVersionRange(a);
27097
- const { name: bName, range: bRange } = parseNameAndVersionRange(b);
27098
- if (aName !== bName) return aName.localeCompare(bName, "en");
27099
- if (!aRange) return -1;
27100
- if (!bRange) return 1;
27101
- return (0, import_compare.default)((0, import_min_version.default)(aRange), (0, import_min_version.default)(bRange));
27102
- });
27103
- const getPackageName = (ident) => {
27104
- const index = ident.indexOf("@", ident.startsWith("@") ? 1 : 0);
27105
- return index === -1 ? ident : ident.slice(0, index);
27106
- };
27107
- const sortObjectByIdent = (a, b) => {
27108
- const packageNameA = getPackageName(a);
27109
- const packageNameB = getPackageName(b);
27110
- if (packageNameA < packageNameB) return -1;
27111
- if (packageNameA > packageNameB) return 1;
27112
- return 0;
27113
- };
27114
- const cache$1 = /* @__PURE__ */ new Map();
27115
- const hasYarnOrPnpmFiles = () => {
27116
- const cwd = process.cwd();
27117
- if (!cache$1.has(cwd)) cache$1.set(cwd, fs.existsSync("yarn.lock") || fs.existsSync(".yarn/") || fs.existsSync(".yarnrc.yml") || fs.existsSync("pnpm-lock.yaml") || fs.existsSync("pnpm-workspace.yaml"));
27118
- return cache$1.get(cwd);
27119
- };
27120
- /**
27121
- * Detects the package manager from package.json and lock files
27122
- * @param {object} packageJson - The parsed package.json object
27123
- * @returns {boolean} - The detected package manager. Default to npm if not detected.
27124
- */
27125
- function shouldSortDependenciesLikeNpm(packageJson) {
27126
- if (typeof packageJson.packageManager === "string") return packageJson.packageManager.startsWith("npm@");
27127
- if (packageJson.devEngines?.packageManager?.name) return packageJson.devEngines.packageManager.name === "npm";
27128
- if (packageJson.pnpm) return false;
27129
- if (packageJson.engines?.npm) return true;
27130
- if (hasYarnOrPnpmFiles()) return false;
27131
- return true;
27124
+ function sumWorkspacePhase(profiles, key) {
27125
+ return profiles.reduce((sum, profile) => sum + profile[key], 0);
27126
+ }
27127
+ function formatWorkspaceProfileLine(profile) {
27128
+ const slowRules = profile.slowRules.length === 0 ? "" : chalk.dim(` slow: ${profile.slowRules.map((rule) => `${rule.id} ${formatDuration$2(rule.elapsedMs)}`).join(", ")}`);
27129
+ return ` [${profile.workspace}] config ${formatDuration$2(profile.configMs)} · files ${formatDuration$2(profile.findFilesMs)} · imports ${formatDuration$2(profile.importsMs)} · meta ${formatDuration$2(profile.packageMetaMs)} · rules ${formatDuration$2(profile.rulesMs)} · total ${formatDuration$2(profile.totalMs)}` + chalk.dim(` (${profile.allFiles} src, ${profile.distFiles} runtime)`) + slowRules;
27132
27130
  }
27133
27131
  /**
27134
- * Sort dependencies alphabetically, detecting package manager to use the
27135
- * appropriate comparison. npm uses locale-aware comparison, yarn and pnpm use
27136
- * simple string comparison
27137
- */
27138
- const sortDependencies = onObject((dependencies, packageJson) => {
27139
- if (Object.keys(dependencies).length < 2) return dependencies;
27140
- if (shouldSortDependenciesLikeNpm(packageJson)) return sortObjectByKeyNameList(dependencies, (a, b) => a.localeCompare(b, "en"));
27141
- return sortObjectByKeyNameList(dependencies);
27142
- });
27143
- /**
27144
- * "workspaces" can be an array (npm or yarn classic) or an object (pnpm/bun).
27145
- * In the case of an array, we do not want to alphabetically sort it in case
27146
- * scripts need to run in a specific order.
27147
- *
27148
- * @see https://docs.npmjs.com/cli/v7/using-npm/workspaces?v=true#running-commands-in-the-context-of-workspaces
27132
+ * Prints a human-readable timing breakdown collected when `--profile` is set.
27149
27133
  */
27150
- const sortWorkspaces = pipe([
27151
- sortObjectBy(["packages", "catalog"]),
27152
- overProperty("packages", uniqAndSortArray),
27153
- overProperty("catalog", sortDependencies)
27154
- ]);
27155
- const sortEslintConfig = pipe([
27156
- sortObjectBy([
27157
- "files",
27158
- "excludedFiles",
27159
- "env",
27160
- "parser",
27161
- "parserOptions",
27162
- "settings",
27163
- "plugins",
27164
- "extends",
27165
- "rules",
27166
- "overrides",
27167
- "globals",
27168
- "processor",
27169
- "noInlineConfig",
27170
- "reportUnusedDisableDirectives"
27171
- ]),
27172
- overProperty("env", sortObject),
27173
- overProperty("globals", sortObject),
27174
- overProperty("overrides", onArray((overrides) => overrides.map(sortEslintConfig))),
27175
- overProperty("parserOptions", sortObject),
27176
- overProperty("rules", sortObjectBy((rule1, rule2) => rule1.split("/").length - rule2.split("/").length || rule1.localeCompare(rule2))),
27177
- overProperty("settings", sortObject)
27134
+ function printDeplintProfile(profile) {
27135
+ if (profile.workspaces.length === 0) return;
27136
+ const sorted = profile.workspaces.toSorted((a, b) => b.totalMs - a.totalMs);
27137
+ console.log(chalk.cyan("Deplint profile"));
27138
+ console.log(chalk.gray(` packages: ${sorted.length} · wall ${formatDuration$2(profile.wallMs)} · cpu Σ ${formatDuration$2(profile.cpuMs)} · config Σ ${formatDuration$2(sorted.reduce((sum, workspaceProfile) => sum + workspaceProfile.configMs, 0))} · files Σ ${formatDuration$2(sumWorkspacePhase(sorted, "findFilesMs"))} · imports Σ ${formatDuration$2(sumWorkspacePhase(sorted, "importsMs"))} · rules Σ ${formatDuration$2(sumWorkspacePhase(sorted, "rulesMs"))}`));
27139
+ console.log(chalk.gray(" (config = xy config + rules load; files = glob + runtime reachability AST; imports = external import AST scan; meta = package.json / transitive peers; cpu Σ can exceed wall when --jobs > 1)"));
27140
+ for (const workspaceProfile of sorted) console.log(chalk.gray(formatWorkspaceProfileLine(workspaceProfile)));
27141
+ }
27142
+ function printDeplintProfileFromResult(result) {
27143
+ if (result.profile === void 0) return;
27144
+ printDeplintProfile(result.profile);
27145
+ }
27146
+ //#endregion
27147
+ //#region src/actions/deplint/ruleConfig.ts
27148
+ const VALID_RULE_LEVELS$1 = /* @__PURE__ */ new Set([
27149
+ "off",
27150
+ "warn",
27151
+ "error"
27178
27152
  ]);
27179
- const sortVSCodeBadgeObject = sortObjectBy([
27180
- "description",
27181
- "url",
27182
- "href"
27153
+ const VALID_RANGE_BOUNDS = /* @__PURE__ */ new Set([
27154
+ "infer",
27155
+ "major",
27156
+ "minor"
27183
27157
  ]);
27184
- const sortPrettierConfig = pipe([onObject((config) => sortObjectByKeyNameList(config, [...Object.keys(config).filter((key) => key !== "overrides").sort(), "overrides"])), overProperty("overrides", onArray((overrides) => overrides.map(pipe([sortObject, overProperty("options", sortObject)]))))]);
27185
- const sortVolta = sortObjectBy([
27186
- "node",
27187
- "npm",
27188
- "yarn"
27158
+ const VALID_RANGE_FORMS = /* @__PURE__ */ new Set(["broad", "shorthand"]);
27159
+ const VALID_WORKSPACE_PROTOCOLS = /* @__PURE__ */ new Set([
27160
+ "workspace:~",
27161
+ "workspace:^",
27162
+ "workspace:*"
27189
27163
  ]);
27190
- const sortWireitScript = pipe([
27191
- sortObjectBy([
27192
- "command",
27193
- "dependencies",
27194
- "files",
27195
- "output"
27164
+ const deprecatedDeplintRuleWarnings = /* @__PURE__ */ new Set();
27165
+ const BUILT_IN_RULE_OPTION_KEYS = {
27166
+ "dep.dependencies.range-style": /* @__PURE__ */ new Set(["ignore"]),
27167
+ "dep.devDependencies.range-style": /* @__PURE__ */ new Set(["ignore"]),
27168
+ "dep.peerDependencies.range-style": /* @__PURE__ */ new Set([
27169
+ "bound",
27170
+ "form",
27171
+ "ignore"
27196
27172
  ]),
27197
- overProperty("dependencies", onArray((deps) => deps.map(sortObjectBy(["script", "cascade"])))),
27198
- overProperty("env", onObject((env) => sortObjectByKeyNameList(Object.fromEntries(Object.entries(env).map(([key, value]) => [key, sortObjectBy(["external", "default"])(value)]))))),
27199
- overProperty("service", pipe([sortObjectBy(["readyWhen"]), overProperty("readyWhen", sortObject)]))
27200
- ]);
27201
- const sortWireit = onObject((wireit) => sortObjectByKeyNameList(Object.fromEntries(Object.entries(wireit).map(([name, config]) => [name, sortWireitScript(config)]))));
27202
- const sortDevEngines = overProperty("packageManager", sortObjectBy([
27203
- "name",
27204
- "version",
27205
- "onFail"
27206
- ]));
27207
- const sortPnpmConfig = pipe([sortObjectBy([
27208
- "peerDependencyRules",
27209
- "neverBuiltDependencies",
27210
- "onlyBuiltDependencies",
27211
- "onlyBuiltDependenciesFile",
27212
- "allowedDeprecatedVersions",
27213
- "allowNonAppliedPatches",
27214
- "updateConfig",
27215
- "auditConfig",
27216
- "requiredScripts",
27217
- "supportedArchitectures",
27218
- "overrides",
27219
- "patchedDependencies",
27220
- "packageExtensions"
27221
- ], true), overProperty("overrides", sortObjectBySemver)]);
27222
- const defaultNpmScripts = /* @__PURE__ */ new Set([
27173
+ "dep.workspace.protocol": /* @__PURE__ */ new Set(["ignore", "protocol"])
27174
+ };
27175
+ function isRecord$4(value) {
27176
+ return typeof value === "object" && value !== null && !Array.isArray(value);
27177
+ }
27178
+ function isRuleLevel$3(value) {
27179
+ return typeof value === "string" && VALID_RULE_LEVELS$1.has(value);
27180
+ }
27181
+ function severityFromLevel$1(level) {
27182
+ return level === "warn" ? "warning" : "error";
27183
+ }
27184
+ function formatRuleConfigLocation$1(ruleId) {
27185
+ return `commands.deplint.rules["${ruleId}"]`;
27186
+ }
27187
+ function deprecatedDeplintRuleAlias(ruleId) {
27188
+ return ruleId.startsWith("dep.") ? `deplint.${ruleId.slice(4)}` : void 0;
27189
+ }
27190
+ function canonicalDeplintRuleId(ruleId) {
27191
+ return ruleId.startsWith("deplint.") ? `dep.${ruleId.slice(8)}` : ruleId;
27192
+ }
27193
+ function warnDeprecatedDeplintRuleId(ruleId, canonicalRuleId) {
27194
+ const key = `${ruleId}:${canonicalRuleId}`;
27195
+ if (deprecatedDeplintRuleWarnings.has(key)) return;
27196
+ deprecatedDeplintRuleWarnings.add(key);
27197
+ console.warn(`Deprecated: commands.deplint.rules["${ruleId}"] is deprecated; use commands.deplint.rules["${canonicalRuleId}"] instead.`);
27198
+ }
27199
+ function parseRuleConfig$1(ruleId, value) {
27200
+ if (typeof value === "string") {
27201
+ if (!isRuleLevel$3(value)) throw new TypeError(`${formatRuleConfigLocation$1(ruleId)} must be one of "off", "warn", or "error"`);
27202
+ return {
27203
+ level: value,
27204
+ options: {}
27205
+ };
27206
+ }
27207
+ if (Array.isArray(value)) {
27208
+ if (value.length !== 2) throw new TypeError(`${formatRuleConfigLocation$1(ruleId)} tuple must be [level, options]`);
27209
+ const level = value[0];
27210
+ if (!isRuleLevel$3(level)) throw new TypeError(`${formatRuleConfigLocation$1(ruleId)} level must be one of "off", "warn", or "error"`);
27211
+ const options = value[1];
27212
+ if (!isRecord$4(options)) throw new TypeError(`${formatRuleConfigLocation$1(ruleId)} options must be an object`);
27213
+ return {
27214
+ level,
27215
+ options: { ...options }
27216
+ };
27217
+ }
27218
+ throw new TypeError(`${formatRuleConfigLocation$1(ruleId)} must be a level or [level, options] tuple`);
27219
+ }
27220
+ function validateIgnore$1(ruleId, options) {
27221
+ if (options.ignore === void 0) return;
27222
+ if (!Array.isArray(options.ignore) || options.ignore.some((pattern) => typeof pattern !== "string")) throw new TypeError(`${formatRuleConfigLocation$1(ruleId)}.ignore must be an array of strings`);
27223
+ }
27224
+ function validateBuiltInOptions(ruleId, options, builtInRuleIds) {
27225
+ validateIgnore$1(ruleId, options);
27226
+ if (!builtInRuleIds.has(ruleId)) return;
27227
+ const allowedKeys = BUILT_IN_RULE_OPTION_KEYS[ruleId] ?? /* @__PURE__ */ new Set(["ignore"]);
27228
+ for (const key of Object.keys(options)) if (!allowedKeys.has(key)) throw new TypeError(`${formatRuleConfigLocation$1(ruleId)} has unknown option "${key}"`);
27229
+ if (ruleId === "dep.peerDependencies.range-style" && options.bound !== void 0 && (typeof options.bound !== "string" || !VALID_RANGE_BOUNDS.has(options.bound))) throw new TypeError(`${formatRuleConfigLocation$1(ruleId)}.bound must be "infer", "major", or "minor"`);
27230
+ if (ruleId === "dep.peerDependencies.range-style" && options.form !== void 0 && (typeof options.form !== "string" || !VALID_RANGE_FORMS.has(options.form))) throw new TypeError(`${formatRuleConfigLocation$1(ruleId)}.form must be "broad" or "shorthand"`);
27231
+ if (ruleId === "dep.workspace.protocol" && options.protocol !== void 0 && (typeof options.protocol !== "string" || !VALID_WORKSPACE_PROTOCOLS.has(options.protocol))) throw new TypeError(`${formatRuleConfigLocation$1(ruleId)}.protocol must be "workspace:~", "workspace:^", or "workspace:*"`);
27232
+ }
27233
+ function normalizeRuleConfigs(ruleConfigs, ruleIds) {
27234
+ const normalized = {};
27235
+ for (const [ruleId, config] of Object.entries(ruleConfigs)) {
27236
+ const canonicalId = canonicalDeplintRuleId(ruleId);
27237
+ if (!ruleIds.has(canonicalId)) {
27238
+ normalized[ruleId] = config;
27239
+ continue;
27240
+ }
27241
+ if (canonicalId !== ruleId && ruleConfigs[canonicalId] !== void 0) continue;
27242
+ if (canonicalId !== ruleId) warnDeprecatedDeplintRuleId(ruleId, canonicalId);
27243
+ normalized[canonicalId] = config;
27244
+ }
27245
+ return normalized;
27246
+ }
27247
+ function normalizeDeplintRules(rules, config, builtInRuleIds) {
27248
+ const ruleIds = new Set(rules.map((rule) => rule.id));
27249
+ const ruleConfigs = normalizeRuleConfigs(config?.rules ?? {}, ruleIds);
27250
+ const unknownRuleIds = Object.keys(ruleConfigs).filter((ruleId) => !ruleIds.has(ruleId));
27251
+ if (unknownRuleIds.length > 0) throw new TypeError(`Unknown deplint rule ${unknownRuleIds.map((ruleId) => `"${ruleId}"`).join(", ")} in commands.deplint.rules`);
27252
+ return rules.map((rule) => {
27253
+ const legacyRuleId = deprecatedDeplintRuleAlias(rule.id);
27254
+ const ruleConfig = ruleConfigs[rule.id] ?? (legacyRuleId === void 0 ? void 0 : ruleConfigs[legacyRuleId]);
27255
+ if (ruleConfig === void 0) return {
27256
+ ...rule,
27257
+ enabled: true,
27258
+ meta: {
27259
+ ...rule.meta,
27260
+ severity: "warning"
27261
+ },
27262
+ options: {}
27263
+ };
27264
+ const { level, options } = parseRuleConfig$1(rule.id, ruleConfig);
27265
+ validateBuiltInOptions(rule.id, options, builtInRuleIds);
27266
+ return {
27267
+ ...rule,
27268
+ enabled: level !== "off",
27269
+ meta: level === "off" ? { ...rule.meta } : {
27270
+ ...rule.meta,
27271
+ severity: severityFromLevel$1(level)
27272
+ },
27273
+ options
27274
+ };
27275
+ });
27276
+ }
27277
+ function isDependencyIgnoredByRule(dependency, options) {
27278
+ if (dependency == null || dependency.length === 0) return false;
27279
+ return options?.ignore?.some((pattern) => pattern === dependency || isMatch(dependency, pattern)) ?? false;
27280
+ }
27281
+ //#endregion
27282
+ //#region src/actions/deplint/getExtendsFromTsconfigs.ts
27283
+ init_index_min();
27284
+ const isExternalReference = (ref) => !ref.startsWith(".") && !ref.startsWith("/");
27285
+ function parseExtendsField(value) {
27286
+ if (typeof value === "string") return [value];
27287
+ if (Array.isArray(value)) return value.filter((v) => typeof v === "string");
27288
+ return [];
27289
+ }
27290
+ function parseTypesField(value) {
27291
+ if (Array.isArray(value)) return value.filter((v) => typeof v === "string");
27292
+ return [];
27293
+ }
27294
+ function parsePathsField(value) {
27295
+ if (typeof value !== "object" || value === null) return [];
27296
+ return Object.keys(value);
27297
+ }
27298
+ function enqueueResolvedTsconfigExtend(file, ref, discovered, queue) {
27299
+ if (isExternalReference(ref)) return;
27300
+ const resolved = PATH.resolve(PATH.dirname(file), ref);
27301
+ if (fs.existsSync(resolved) && !discovered.has(resolved)) queue.push(resolved);
27302
+ }
27303
+ function collectTsconfigFiles(location) {
27304
+ const discovered = /* @__PURE__ */ new Set();
27305
+ const queue = ts$1("./tsconfig*.json", {
27306
+ cwd: location,
27307
+ absolute: true
27308
+ });
27309
+ while (queue.length > 0) {
27310
+ const file = queue.pop();
27311
+ if (file === void 0 || discovered.has(file)) continue;
27312
+ discovered.add(file);
27313
+ try {
27314
+ const parsed = parseTsconfig(file);
27315
+ for (const ref of parseExtendsField(parsed.extends)) enqueueResolvedTsconfigExtend(file, ref, discovered, queue);
27316
+ } catch {}
27317
+ }
27318
+ return [...discovered];
27319
+ }
27320
+ /**
27321
+ * Returns true when `importPath` matches a TypeScript `compilerOptions.paths` key.
27322
+ * Wildcard `*` matches one or more trailing path segments.
27323
+ */
27324
+ function isMatchingTsconfigPathPattern(pattern, importPath) {
27325
+ const patternParts = pattern.split("/");
27326
+ const importParts = importPath.split("/");
27327
+ let patternIndex = 0;
27328
+ let importIndex = 0;
27329
+ while (patternIndex < patternParts.length && importIndex < importParts.length) {
27330
+ const patternPart = patternParts[patternIndex];
27331
+ if (patternPart === "*") {
27332
+ if (patternIndex === patternParts.length - 1) return true;
27333
+ patternIndex++;
27334
+ importIndex++;
27335
+ continue;
27336
+ }
27337
+ if (patternPart !== importParts[importIndex]) return false;
27338
+ patternIndex++;
27339
+ importIndex++;
27340
+ }
27341
+ if (patternIndex === patternParts.length - 1 && patternParts[patternIndex] === "*") return true;
27342
+ return patternIndex === patternParts.length && importIndex === importParts.length;
27343
+ }
27344
+ function isTsconfigPathAlias(importPath, pathPatterns) {
27345
+ return pathPatterns.some((pattern) => isMatchingTsconfigPathPattern(pattern, importPath));
27346
+ }
27347
+ function parseTsconfig(file) {
27348
+ const cleaned = fs.readFileSync(file, "utf8").replaceAll(/\/\/.*/g, "").replaceAll(/,\s*([}\]])/g, "$1");
27349
+ return JSON.parse(cleaned);
27350
+ }
27351
+ function getPathsFromTsconfigs(location) {
27352
+ const patterns = /* @__PURE__ */ new Set();
27353
+ for (const file of collectTsconfigFiles(location)) try {
27354
+ const compilerOptions = parseTsconfig(file).compilerOptions;
27355
+ const pathPatterns = parsePathsField(compilerOptions?.paths);
27356
+ for (const pattern of pathPatterns) patterns.add(pattern);
27357
+ } catch {}
27358
+ return [...patterns];
27359
+ }
27360
+ function getExtendsFromTsconfigs(location) {
27361
+ const packages = /* @__PURE__ */ new Set();
27362
+ for (const file of collectTsconfigFiles(location)) try {
27363
+ const refs = parseExtendsField(parseTsconfig(file).extends);
27364
+ for (const ref of refs) if (isExternalReference(ref)) packages.add(getBasePackageName(ref));
27365
+ } catch {}
27366
+ return [...packages];
27367
+ }
27368
+ function getTypesFromTsconfigs(location) {
27369
+ const packages = /* @__PURE__ */ new Set();
27370
+ for (const file of collectTsconfigFiles(location)) try {
27371
+ const compilerOptions = parseTsconfig(file).compilerOptions;
27372
+ const refs = parseTypesField(compilerOptions?.types);
27373
+ for (const ref of refs) packages.add(getBasePackageName(ref));
27374
+ } catch {}
27375
+ return [...packages];
27376
+ }
27377
+ //#endregion
27378
+ //#region src/actions/deplint/getImportsFromFile.ts
27379
+ function isTypeOnlyImportClause(clause) {
27380
+ if (clause === void 0) return false;
27381
+ if ("phaseModifier" in clause) {
27382
+ const mod = clause.phaseModifier;
27383
+ return (typeof mod === "number" ? mod : mod?.kind) === ts.SyntaxKind.TypeKeyword;
27384
+ }
27385
+ return clause.isTypeOnly ?? false;
27386
+ }
27387
+ function getImportsFromFile(filePath, importPaths, typeImportPaths) {
27388
+ const { sourceFile } = getCachedSourceFile(filePath);
27389
+ const imports = [];
27390
+ const typeImports = [];
27391
+ const isDeclarationFile = filePath.endsWith(".d.ts") || filePath.endsWith(".d.mts") || filePath.endsWith(".d.cts");
27392
+ function visit(node) {
27393
+ if (ts.isImportDeclaration(node) || ts.isExportDeclaration(node)) {
27394
+ const moduleSpecifier = node.moduleSpecifier?.getFullText();
27395
+ const isTypeImport = ts.isImportDeclaration(node) ? isTypeOnlyImportClause(node.importClause) : false;
27396
+ if (typeof moduleSpecifier === "string") {
27397
+ const trimmed = moduleSpecifier.replaceAll(/['"]/g, "").trim();
27398
+ if (isTypeImport || isDeclarationFile) typeImports.push(trimmed);
27399
+ else imports.push(trimmed);
27400
+ }
27401
+ } else if (ts.isCallExpression(node) && node.expression.kind === ts.SyntaxKind.ImportKeyword) {
27402
+ const [arg] = node.arguments;
27403
+ if (ts.isStringLiteral(arg)) imports.push(arg.text);
27404
+ } else if (ts.isCallExpression(node) && ts.isIdentifier(node.expression) && node.expression.text === "require" && node.arguments.length > 0 && ts.isStringLiteral(node.arguments[0])) imports.push(node.arguments[0].text);
27405
+ ts.forEachChild(node, visit);
27406
+ }
27407
+ visit(sourceFile);
27408
+ for (const ref of sourceFile.typeReferenceDirectives) typeImports.push(ref.fileName);
27409
+ const importsStartsWithExcludes = [
27410
+ ".",
27411
+ "#",
27412
+ "node:"
27413
+ ];
27414
+ const isValidImport = (imp) => importsStartsWithExcludes.every((exc) => !imp.startsWith(exc)) && !imp.includes("*") && !imp.includes("!");
27415
+ const cleanedImports = imports.filter(isValidImport).map(getBasePackageName);
27416
+ const cleanedTypeImports = typeImports.filter(isValidImport).map(getBasePackageName);
27417
+ for (const imp of cleanedImports) {
27418
+ importPaths[imp] ??= [];
27419
+ importPaths[imp].push(filePath);
27420
+ }
27421
+ for (const imp of cleanedTypeImports) {
27422
+ typeImportPaths[imp] ??= [];
27423
+ typeImportPaths[imp].push(filePath);
27424
+ }
27425
+ return [cleanedImports, cleanedTypeImports];
27426
+ }
27427
+ //#endregion
27428
+ //#region src/actions/deplint/getStorybookConfigImports.ts
27429
+ const storybookMainPattern = /(?:^|[\\/])\.storybook[\\/]main\.[cm]?[jt]sx?$/;
27430
+ const npmPackageNamePattern = /^@?[a-z0-9][\w./-]*$/i;
27431
+ function isStorybookMainFile(filePath) {
27432
+ return storybookMainPattern.test(filePath);
27433
+ }
27434
+ function getPropertyName$1(prop) {
27435
+ if (ts.isIdentifier(prop.name)) return prop.name.text;
27436
+ if (ts.isStringLiteral(prop.name) || ts.isNoSubstitutionTemplateLiteral(prop.name)) return prop.name.text;
27437
+ }
27438
+ function pushIfPackage(text, collected) {
27439
+ const trimmed = text.trim();
27440
+ if (trimmed.length === 0) return;
27441
+ if (trimmed.startsWith(".") || trimmed.startsWith("/") || trimmed.startsWith("node:")) return;
27442
+ if (!npmPackageNamePattern.test(trimmed)) return;
27443
+ collected.push(trimmed);
27444
+ }
27445
+ function extractFromEntry(node, collected) {
27446
+ if (ts.isStringLiteral(node) || ts.isNoSubstitutionTemplateLiteral(node)) {
27447
+ pushIfPackage(node.text, collected);
27448
+ return;
27449
+ }
27450
+ if (ts.isObjectLiteralExpression(node)) {
27451
+ for (const prop of node.properties) if (ts.isPropertyAssignment(prop) && getPropertyName$1(prop) === "name") extractFromEntry(prop.initializer, collected);
27452
+ return;
27453
+ }
27454
+ if (ts.isCallExpression(node)) {
27455
+ for (const arg of node.arguments) if (ts.isStringLiteral(arg) || ts.isNoSubstitutionTemplateLiteral(arg)) pushIfPackage(arg.text, collected);
27456
+ return;
27457
+ }
27458
+ if (ts.isArrayLiteralExpression(node)) for (const element of node.elements) extractFromEntry(element, collected);
27459
+ }
27460
+ function getStorybookConfigImports(filePath, importPaths) {
27461
+ if (!isStorybookMainFile(filePath)) return [];
27462
+ const cached = tryGetCachedSourceFile(filePath);
27463
+ if (cached === void 0) return [];
27464
+ const { sourceFile } = cached;
27465
+ const collected = [];
27466
+ function visit(node) {
27467
+ if (ts.isPropertyAssignment(node)) {
27468
+ const name = getPropertyName$1(node);
27469
+ if (name === "addons") {
27470
+ if (ts.isArrayLiteralExpression(node.initializer)) for (const element of node.initializer.elements) extractFromEntry(element, collected);
27471
+ } else if (name === "framework" || name === "builder") extractFromEntry(node.initializer, collected);
27472
+ }
27473
+ ts.forEachChild(node, visit);
27474
+ }
27475
+ visit(sourceFile);
27476
+ const cleaned = [...new Set(collected.map(getBasePackageName))];
27477
+ for (const imp of cleaned) {
27478
+ importPaths[imp] ??= [];
27479
+ if (!importPaths[imp].includes(filePath)) importPaths[imp].push(filePath);
27480
+ }
27481
+ return cleaned;
27482
+ }
27483
+ //#endregion
27484
+ //#region src/actions/deplint/getExternalImportsFromFiles.ts
27485
+ const internalImportPrefixes = [
27486
+ ".",
27487
+ "#",
27488
+ "node:"
27489
+ ];
27490
+ const removeInternalImports = (imports) => {
27491
+ return imports.filter((imp) => internalImportPrefixes.every((prefix) => !imp.startsWith(prefix)));
27492
+ };
27493
+ const removeTsconfigPathAliases = (imports, pathPatterns) => {
27494
+ if (pathPatterns.length === 0) return imports;
27495
+ return imports.filter((imp) => !isTsconfigPathAlias(imp, pathPatterns));
27496
+ };
27497
+ const isDeclarationFile$1 = (file) => file.endsWith(".d.ts") || file.endsWith(".d.cts") || file.endsWith(".d.mts");
27498
+ const toolingConfigFilePattern = /(?:^|[\\/])xy\.config\.[cm]?[jt]sx?$/;
27499
+ const isToolingConfigFile = (file) => toolingConfigFilePattern.test(file);
27500
+ function excludeToolingConfigImports(paths) {
27501
+ const filtered = {};
27502
+ for (const [imp, files] of Object.entries(paths)) {
27503
+ const kept = files.filter((file) => !isToolingConfigFile(file));
27504
+ if (kept.length > 0) filtered[imp] = kept;
27505
+ }
27506
+ return filtered;
27507
+ }
27508
+ function formatExportPath$2(pathParts) {
27509
+ return pathParts.map((part, index) => {
27510
+ if (index === 0) return part;
27511
+ if (part.startsWith("[")) return part;
27512
+ return /^[a-zA-Z_$][\w$]*$/.test(part) ? `.${part}` : `[${JSON.stringify(part)}]`;
27513
+ }).join("");
27514
+ }
27515
+ function collectExportTargets$1(value, pathParts = ["exports"]) {
27516
+ if (typeof value === "string") {
27517
+ if (!value.startsWith("./")) return [];
27518
+ return [{
27519
+ path: formatExportPath$2(pathParts),
27520
+ target: value
27521
+ }];
27522
+ }
27523
+ if (Array.isArray(value)) return value.flatMap((entry, index) => collectExportTargets$1(entry, [...pathParts, `[${index}]`]));
27524
+ if (typeof value !== "object" || value === null) return [];
27525
+ return Object.entries(value).flatMap(([key, nested]) => collectExportTargets$1(nested, [...pathParts, key]));
27526
+ }
27527
+ function hasExportTarget(location, target) {
27528
+ if (target.includes("*")) return findFilesByGlob(location, target).length > 0;
27529
+ return fs.existsSync(PATH.resolve(location, target));
27530
+ }
27531
+ function readPackageJson$5(location) {
27532
+ try {
27533
+ return JSON.parse(fs.readFileSync(`${location}/package.json`, "utf8"));
27534
+ } catch {
27535
+ return;
27536
+ }
27537
+ }
27538
+ function warnMissingExportTargets(name, location) {
27539
+ const targets = collectExportTargets$1(readPackageJson$5(location)?.exports);
27540
+ const warnedTargets = /* @__PURE__ */ new Set();
27541
+ const prefix = name != null && name.length > 0 ? `[${chalk.blue(name)}] ` : "";
27542
+ for (const { path: exportPath, target } of targets) {
27543
+ if (warnedTargets.has(target)) continue;
27544
+ warnedTargets.add(target);
27545
+ if (hasExportTarget(location, target)) continue;
27546
+ const description = target.includes("*") ? "pattern matched no files" : "file missing";
27547
+ console.warn(`${prefix}${chalk.yellow(`deplint: package.json export ${description}: ${target} (${exportPath})`)}`);
27548
+ }
27549
+ }
27550
+ function hasShippedTsconfig(location) {
27551
+ return (readPackageJson$5(location)?.files)?.some((f) => f === "tsconfig.json" || f.includes("tsconfig")) ?? false;
27552
+ }
27553
+ function getEffectiveRuntimeImportPaths({ distImportPaths, distTypeImportPaths, hasDist, hasRuntimeRoots, srcImportPaths, srcTypeImportPaths }) {
27554
+ if (hasDist) return {
27555
+ importPaths: distImportPaths,
27556
+ typeImportPaths: distTypeImportPaths
27557
+ };
27558
+ if (!hasRuntimeRoots) return {
27559
+ importPaths: {},
27560
+ typeImportPaths: {}
27561
+ };
27562
+ return {
27563
+ importPaths: excludeToolingConfigImports(srcImportPaths),
27564
+ typeImportPaths: excludeToolingConfigImports(srcTypeImportPaths)
27565
+ };
27566
+ }
27567
+ function getExternalImportsFromFiles({ allFiles, distFiles, hasRuntimeRoots = true, location, name, tsconfigExtends = [], tsconfigPaths = [], tsconfigTypes = [] }) {
27568
+ const srcImportPaths = {};
27569
+ const srcTypeImportPaths = {};
27570
+ for (const path of allFiles) {
27571
+ getImportsFromFile(path, srcImportPaths, srcTypeImportPaths);
27572
+ getStorybookConfigImports(path, srcImportPaths);
27573
+ }
27574
+ const allImportPaths = { ...srcImportPaths };
27575
+ for (const [key, paths] of Object.entries(srcTypeImportPaths)) allImportPaths[key] = [...allImportPaths[key] ?? [], ...paths];
27576
+ const distImportPaths = {};
27577
+ const distTypeImportPaths = {};
27578
+ const hasDist = distFiles.length > 0;
27579
+ if (hasDist) {
27580
+ const distTypeFiles = distFiles.filter(isDeclarationFile$1);
27581
+ const distCodeFiles = distFiles.filter((file) => !isDeclarationFile$1(file));
27582
+ for (const path of distCodeFiles) getImportsFromFile(path, distImportPaths, distImportPaths);
27583
+ for (const path of distTypeFiles) getImportsFromFile(path, distTypeImportPaths, distTypeImportPaths);
27584
+ }
27585
+ warnMissingExportTargets(name, location);
27586
+ const { importPaths: effectiveDistImportPaths, typeImportPaths: effectiveDistTypeImportPaths } = getEffectiveRuntimeImportPaths({
27587
+ distImportPaths,
27588
+ distTypeImportPaths,
27589
+ hasDist,
27590
+ hasRuntimeRoots,
27591
+ srcImportPaths,
27592
+ srcTypeImportPaths
27593
+ });
27594
+ const allImports = Object.keys(allImportPaths);
27595
+ const distImports = Object.keys(effectiveDistImportPaths);
27596
+ const externalAllImports = removeTsconfigPathAliases(removeInternalImports(allImports), tsconfigPaths);
27597
+ const externalDistImports = removeTsconfigPathAliases(removeInternalImports(distImports), tsconfigPaths);
27598
+ const externalDistTypeImports = removeTsconfigPathAliases(removeInternalImports(Object.keys(effectiveDistTypeImportPaths)), tsconfigPaths);
27599
+ const isDistTsconfig = hasShippedTsconfig(location);
27600
+ for (const ext of tsconfigExtends) {
27601
+ if (!externalAllImports.includes(ext)) externalAllImports.push(ext);
27602
+ if (isDistTsconfig && !externalDistImports.includes(ext)) externalDistImports.push(ext);
27603
+ }
27604
+ for (const typ of tsconfigTypes) if (!externalAllImports.includes(typ)) externalAllImports.push(typ);
27605
+ return {
27606
+ allImportPaths,
27607
+ allImports,
27608
+ distImportPaths: effectiveDistImportPaths,
27609
+ distImports,
27610
+ externalAllImports,
27611
+ externalDistImports,
27612
+ externalDistTypeImports,
27613
+ tsconfigExtends: [...tsconfigExtends]
27614
+ };
27615
+ }
27616
+ //#endregion
27617
+ //#region ../../node_modules/.pnpm/sort-object-keys@2.1.0/node_modules/sort-object-keys/index.js
27618
+ const has = (object, key) => Object.prototype.hasOwnProperty.call(object, key);
27619
+ function sortObjectByKeyNameList(object, sortWith) {
27620
+ let keys, sortFn, key;
27621
+ if (typeof sortWith === "function") sortFn = sortWith;
27622
+ else keys = sortWith;
27623
+ const total = {};
27624
+ for (key of [...keys ?? [], ...Object.keys(object).sort(sortFn)]) if (has(object, key)) total[key] = object[key];
27625
+ return total;
27626
+ }
27627
+ //#endregion
27628
+ //#region ../../node_modules/.pnpm/detect-indent@7.0.2/node_modules/detect-indent/index.js
27629
+ const INDENT_REGEX = /^(?:( )+|\t+)/;
27630
+ const INDENT_TYPE_SPACE = "space";
27631
+ const INDENT_TYPE_TAB = "tab";
27632
+ function shouldIgnoreSingleSpace(ignoreSingleSpaces, indentType, value) {
27633
+ return ignoreSingleSpaces && indentType === INDENT_TYPE_SPACE && value === 1;
27634
+ }
27635
+ /**
27636
+ Make a Map that counts how many indents/unindents have occurred for a given size and how many lines follow a given indentation.
27637
+
27638
+ The key is a concatenation of the indentation type (s = space and t = tab) and the size of the indents/unindents.
27639
+
27640
+ ```
27641
+ indents = {
27642
+ t3: [1, 0],
27643
+ t4: [1, 5],
27644
+ s5: [1, 0],
27645
+ s12: [1, 0],
27646
+ }
27647
+ ```
27648
+ */
27649
+ function makeIndentsMap(string, ignoreSingleSpaces) {
27650
+ const indents = /* @__PURE__ */ new Map();
27651
+ let previousSize = 0;
27652
+ let previousIndentType;
27653
+ let key;
27654
+ for (const line of string.split(/\n/g)) {
27655
+ if (!line) continue;
27656
+ const matches = line.match(INDENT_REGEX);
27657
+ if (matches === null) {
27658
+ previousSize = 0;
27659
+ previousIndentType = "";
27660
+ } else {
27661
+ const indent = matches[0].length;
27662
+ const indentType = matches[1] ? INDENT_TYPE_SPACE : INDENT_TYPE_TAB;
27663
+ if (shouldIgnoreSingleSpace(ignoreSingleSpaces, indentType, indent)) continue;
27664
+ if (indentType !== previousIndentType) previousSize = 0;
27665
+ previousIndentType = indentType;
27666
+ let use = 1;
27667
+ let weight = 0;
27668
+ const indentDifference = indent - previousSize;
27669
+ previousSize = indent;
27670
+ if (indentDifference === 0) {
27671
+ use = 0;
27672
+ weight = 1;
27673
+ } else {
27674
+ const absoluteIndentDifference = Math.abs(indentDifference);
27675
+ if (shouldIgnoreSingleSpace(ignoreSingleSpaces, indentType, absoluteIndentDifference)) continue;
27676
+ key = encodeIndentsKey(indentType, absoluteIndentDifference);
27677
+ }
27678
+ const entry = indents.get(key);
27679
+ indents.set(key, entry === void 0 ? [1, 0] : [entry[0] + use, entry[1] + weight]);
27680
+ }
27681
+ }
27682
+ return indents;
27683
+ }
27684
+ function encodeIndentsKey(indentType, indentAmount) {
27685
+ return (indentType === INDENT_TYPE_SPACE ? "s" : "t") + String(indentAmount);
27686
+ }
27687
+ function decodeIndentsKey(indentsKey) {
27688
+ return {
27689
+ type: indentsKey[0] === "s" ? INDENT_TYPE_SPACE : INDENT_TYPE_TAB,
27690
+ amount: Number(indentsKey.slice(1))
27691
+ };
27692
+ }
27693
+ function getMostUsedKey(indents) {
27694
+ let result;
27695
+ let maxUsed = 0;
27696
+ let maxWeight = 0;
27697
+ for (const [key, [usedCount, weight]] of indents) if (usedCount > maxUsed || usedCount === maxUsed && weight > maxWeight) {
27698
+ maxUsed = usedCount;
27699
+ maxWeight = weight;
27700
+ result = key;
27701
+ }
27702
+ return result;
27703
+ }
27704
+ function makeIndentString(type, amount) {
27705
+ return (type === INDENT_TYPE_SPACE ? " " : " ").repeat(amount);
27706
+ }
27707
+ function detectIndent(string) {
27708
+ if (typeof string !== "string") throw new TypeError("Expected a string");
27709
+ let indents = makeIndentsMap(string, true);
27710
+ if (indents.size === 0) indents = makeIndentsMap(string, false);
27711
+ const keyOfMostUsedIndent = getMostUsedKey(indents);
27712
+ let type;
27713
+ let amount = 0;
27714
+ let indent = "";
27715
+ if (keyOfMostUsedIndent !== void 0) {
27716
+ ({type, amount} = decodeIndentsKey(keyOfMostUsedIndent));
27717
+ indent = makeIndentString(type, amount);
27718
+ }
27719
+ return {
27720
+ amount,
27721
+ type,
27722
+ indent
27723
+ };
27724
+ }
27725
+ //#endregion
27726
+ //#region ../../node_modules/.pnpm/detect-newline@4.0.1/node_modules/detect-newline/index.js
27727
+ function detectNewline(string) {
27728
+ if (typeof string !== "string") throw new TypeError("Expected a string");
27729
+ const newlines = string.match(/(?:\r?\n)/g) || [];
27730
+ if (newlines.length === 0) return;
27731
+ const crlf = newlines.filter((newline) => newline === "\r\n").length;
27732
+ return crlf > newlines.length - crlf ? "\r\n" : "\n";
27733
+ }
27734
+ function detectNewlineGraceful(string) {
27735
+ return typeof string === "string" && detectNewline(string) || "\n";
27736
+ }
27737
+ //#endregion
27738
+ //#region ../../node_modules/.pnpm/git-hooks-list@4.2.1/node_modules/git-hooks-list/index.json
27739
+ var git_hooks_list_default = [
27740
+ "applypatch-msg",
27741
+ "pre-applypatch",
27742
+ "post-applypatch",
27743
+ "pre-commit",
27744
+ "pre-merge-commit",
27745
+ "prepare-commit-msg",
27746
+ "commit-msg",
27747
+ "post-commit",
27748
+ "pre-rebase",
27749
+ "post-checkout",
27750
+ "post-merge",
27751
+ "pre-push",
27752
+ "pre-receive",
27753
+ "update",
27754
+ "proc-receive",
27755
+ "post-receive",
27756
+ "post-update",
27757
+ "reference-transaction",
27758
+ "push-to-checkout",
27759
+ "pre-auto-gc",
27760
+ "post-rewrite",
27761
+ "sendemail-validate",
27762
+ "fsmonitor-watchman",
27763
+ "p4-changelist",
27764
+ "p4-prepare-changelist",
27765
+ "p4-post-changelist",
27766
+ "p4-pre-submit",
27767
+ "post-index-change"
27768
+ ];
27769
+ //#endregion
27770
+ //#region ../../node_modules/.pnpm/is-plain-obj@4.1.0/node_modules/is-plain-obj/index.js
27771
+ function isPlainObject(value) {
27772
+ if (typeof value !== "object" || value === null) return false;
27773
+ const prototype = Object.getPrototypeOf(value);
27774
+ return (prototype === null || prototype === Object.prototype || Object.getPrototypeOf(prototype) === null) && !(Symbol.toStringTag in value) && !(Symbol.iterator in value);
27775
+ }
27776
+ //#endregion
27777
+ //#region ../../node_modules/.pnpm/sort-package-json@4.0.0/node_modules/sort-package-json/index.js
27778
+ var import_compare = /* @__PURE__ */ __toESM(require_compare(), 1);
27779
+ var import_min_version = /* @__PURE__ */ __toESM(require_min_version(), 1);
27780
+ const pipe = (fns) => (x, ...args) => fns.reduce((result, fn) => fn(result, ...args), x);
27781
+ const onArray = (fn) => (x) => Array.isArray(x) ? fn(x) : x;
27782
+ const onStringArray = (fn) => (x) => Array.isArray(x) && x.every((item) => typeof item === "string") ? fn(x) : x;
27783
+ const uniq = onStringArray((xs) => [...new Set(xs)]);
27784
+ const uniqAndSortArray = pipe([uniq, onStringArray((array) => array.toSorted())]);
27785
+ const onObject = (fn) => (x, ...args) => isPlainObject(x) ? fn(x, ...args) : x;
27786
+ const sortObjectBy = (comparator, deep) => {
27787
+ const over = onObject((object) => {
27788
+ if (deep) object = Object.fromEntries(Object.entries(object).map(([key, value]) => [key, over(value)]));
27789
+ return sortObjectByKeyNameList(object, comparator);
27790
+ });
27791
+ return over;
27792
+ };
27793
+ const sortObject = sortObjectBy();
27794
+ const sortURLObject = sortObjectBy(["type", "url"]);
27795
+ const sortPeopleObject = sortObjectBy([
27796
+ "name",
27797
+ "email",
27798
+ "url"
27799
+ ]);
27800
+ const sortDirectories = sortObjectBy([
27801
+ "lib",
27802
+ "bin",
27803
+ "man",
27804
+ "doc",
27805
+ "example",
27806
+ "test"
27807
+ ]);
27808
+ const overProperty = (property, over) => onObject((object, ...args) => Object.hasOwn(object, property) ? {
27809
+ ...object,
27810
+ [property]: over(object[property], ...args)
27811
+ } : object);
27812
+ const sortGitHooks = sortObjectBy(git_hooks_list_default);
27813
+ const parseNameAndVersionRange = (specifier) => {
27814
+ const [nameAndVersion] = specifier.split(">");
27815
+ const atMatches = [...nameAndVersion.matchAll("@")];
27816
+ if (!atMatches.length || atMatches.length === 1 && atMatches[0].index === 0) return { name: specifier };
27817
+ const splitIndex = atMatches.pop().index;
27818
+ return {
27819
+ name: nameAndVersion.substring(0, splitIndex),
27820
+ range: nameAndVersion.substring(splitIndex + 1)
27821
+ };
27822
+ };
27823
+ const sortObjectBySemver = sortObjectBy((a, b) => {
27824
+ const { name: aName, range: aRange } = parseNameAndVersionRange(a);
27825
+ const { name: bName, range: bRange } = parseNameAndVersionRange(b);
27826
+ if (aName !== bName) return aName.localeCompare(bName, "en");
27827
+ if (!aRange) return -1;
27828
+ if (!bRange) return 1;
27829
+ return (0, import_compare.default)((0, import_min_version.default)(aRange), (0, import_min_version.default)(bRange));
27830
+ });
27831
+ const getPackageName = (ident) => {
27832
+ const index = ident.indexOf("@", ident.startsWith("@") ? 1 : 0);
27833
+ return index === -1 ? ident : ident.slice(0, index);
27834
+ };
27835
+ const sortObjectByIdent = (a, b) => {
27836
+ const packageNameA = getPackageName(a);
27837
+ const packageNameB = getPackageName(b);
27838
+ if (packageNameA < packageNameB) return -1;
27839
+ if (packageNameA > packageNameB) return 1;
27840
+ return 0;
27841
+ };
27842
+ const cache$1 = /* @__PURE__ */ new Map();
27843
+ const hasYarnOrPnpmFiles = () => {
27844
+ const cwd = process.cwd();
27845
+ if (!cache$1.has(cwd)) cache$1.set(cwd, fs.existsSync("yarn.lock") || fs.existsSync(".yarn/") || fs.existsSync(".yarnrc.yml") || fs.existsSync("pnpm-lock.yaml") || fs.existsSync("pnpm-workspace.yaml"));
27846
+ return cache$1.get(cwd);
27847
+ };
27848
+ /**
27849
+ * Detects the package manager from package.json and lock files
27850
+ * @param {object} packageJson - The parsed package.json object
27851
+ * @returns {boolean} - The detected package manager. Default to npm if not detected.
27852
+ */
27853
+ function shouldSortDependenciesLikeNpm(packageJson) {
27854
+ if (typeof packageJson.packageManager === "string") return packageJson.packageManager.startsWith("npm@");
27855
+ if (packageJson.devEngines?.packageManager?.name) return packageJson.devEngines.packageManager.name === "npm";
27856
+ if (packageJson.pnpm) return false;
27857
+ if (packageJson.engines?.npm) return true;
27858
+ if (hasYarnOrPnpmFiles()) return false;
27859
+ return true;
27860
+ }
27861
+ /**
27862
+ * Sort dependencies alphabetically, detecting package manager to use the
27863
+ * appropriate comparison. npm uses locale-aware comparison, yarn and pnpm use
27864
+ * simple string comparison
27865
+ */
27866
+ const sortDependencies = onObject((dependencies, packageJson) => {
27867
+ if (Object.keys(dependencies).length < 2) return dependencies;
27868
+ if (shouldSortDependenciesLikeNpm(packageJson)) return sortObjectByKeyNameList(dependencies, (a, b) => a.localeCompare(b, "en"));
27869
+ return sortObjectByKeyNameList(dependencies);
27870
+ });
27871
+ /**
27872
+ * "workspaces" can be an array (npm or yarn classic) or an object (pnpm/bun).
27873
+ * In the case of an array, we do not want to alphabetically sort it in case
27874
+ * scripts need to run in a specific order.
27875
+ *
27876
+ * @see https://docs.npmjs.com/cli/v7/using-npm/workspaces?v=true#running-commands-in-the-context-of-workspaces
27877
+ */
27878
+ const sortWorkspaces = pipe([
27879
+ sortObjectBy(["packages", "catalog"]),
27880
+ overProperty("packages", uniqAndSortArray),
27881
+ overProperty("catalog", sortDependencies)
27882
+ ]);
27883
+ const sortEslintConfig = pipe([
27884
+ sortObjectBy([
27885
+ "files",
27886
+ "excludedFiles",
27887
+ "env",
27888
+ "parser",
27889
+ "parserOptions",
27890
+ "settings",
27891
+ "plugins",
27892
+ "extends",
27893
+ "rules",
27894
+ "overrides",
27895
+ "globals",
27896
+ "processor",
27897
+ "noInlineConfig",
27898
+ "reportUnusedDisableDirectives"
27899
+ ]),
27900
+ overProperty("env", sortObject),
27901
+ overProperty("globals", sortObject),
27902
+ overProperty("overrides", onArray((overrides) => overrides.map(sortEslintConfig))),
27903
+ overProperty("parserOptions", sortObject),
27904
+ overProperty("rules", sortObjectBy((rule1, rule2) => rule1.split("/").length - rule2.split("/").length || rule1.localeCompare(rule2))),
27905
+ overProperty("settings", sortObject)
27906
+ ]);
27907
+ const sortVSCodeBadgeObject = sortObjectBy([
27908
+ "description",
27909
+ "url",
27910
+ "href"
27911
+ ]);
27912
+ const sortPrettierConfig = pipe([onObject((config) => sortObjectByKeyNameList(config, [...Object.keys(config).filter((key) => key !== "overrides").sort(), "overrides"])), overProperty("overrides", onArray((overrides) => overrides.map(pipe([sortObject, overProperty("options", sortObject)]))))]);
27913
+ const sortVolta = sortObjectBy([
27914
+ "node",
27915
+ "npm",
27916
+ "yarn"
27917
+ ]);
27918
+ const sortWireitScript = pipe([
27919
+ sortObjectBy([
27920
+ "command",
27921
+ "dependencies",
27922
+ "files",
27923
+ "output"
27924
+ ]),
27925
+ overProperty("dependencies", onArray((deps) => deps.map(sortObjectBy(["script", "cascade"])))),
27926
+ overProperty("env", onObject((env) => sortObjectByKeyNameList(Object.fromEntries(Object.entries(env).map(([key, value]) => [key, sortObjectBy(["external", "default"])(value)]))))),
27927
+ overProperty("service", pipe([sortObjectBy(["readyWhen"]), overProperty("readyWhen", sortObject)]))
27928
+ ]);
27929
+ const sortWireit = onObject((wireit) => sortObjectByKeyNameList(Object.fromEntries(Object.entries(wireit).map(([name, config]) => [name, sortWireitScript(config)]))));
27930
+ const sortDevEngines = overProperty("packageManager", sortObjectBy([
27931
+ "name",
27932
+ "version",
27933
+ "onFail"
27934
+ ]));
27935
+ const sortPnpmConfig = pipe([sortObjectBy([
27936
+ "peerDependencyRules",
27937
+ "neverBuiltDependencies",
27938
+ "onlyBuiltDependencies",
27939
+ "onlyBuiltDependenciesFile",
27940
+ "allowedDeprecatedVersions",
27941
+ "allowNonAppliedPatches",
27942
+ "updateConfig",
27943
+ "auditConfig",
27944
+ "requiredScripts",
27945
+ "supportedArchitectures",
27946
+ "overrides",
27947
+ "patchedDependencies",
27948
+ "packageExtensions"
27949
+ ], true), overProperty("overrides", sortObjectBySemver)]);
27950
+ const defaultNpmScripts = /* @__PURE__ */ new Set([
27223
27951
  "install",
27224
27952
  "pack",
27225
27953
  "prepare",
@@ -27591,803 +28319,263 @@ const fields = [
27591
28319
  {
27592
28320
  key: "publishConfig",
27593
28321
  over: sortObject
27594
- },
27595
- { key: "icon" },
27596
- {
27597
- key: "badges",
27598
- over: onArray((badge) => badge.map(sortVSCodeBadgeObject))
27599
- },
27600
- {
27601
- key: "galleryBanner",
27602
- over: sortObject
27603
- },
27604
- { key: "preview" },
27605
- { key: "markdown" },
27606
- {
27607
- key: "pnpm",
27608
- over: sortPnpmConfig
27609
- }
27610
- ];
27611
- const defaultSortOrder = fields.map(({ key }) => key);
27612
- const overFields = pipe(fields.map(({ key, over }) => over ? overProperty(key, over) : void 0).filter(Boolean));
27613
- function editStringJSON(json, over) {
27614
- if (typeof json === "string") {
27615
- const { indent, type } = detectIndent(json);
27616
- const endCharacters = json.slice(-1) === "\n" ? "\n" : "";
27617
- const newline = detectNewlineGraceful(json);
27618
- json = JSON.parse(json);
27619
- let result = JSON.stringify(over(json), null, type === "tab" ? " " : indent) + endCharacters;
27620
- if (newline === "\r\n") result = result.replace(/\n/g, newline);
27621
- return result;
27622
- }
27623
- return over(json);
27624
- }
27625
- function sortPackageJson(jsonIsh, options = {}) {
27626
- return editStringJSON(jsonIsh, onObject((json) => {
27627
- let sortOrder = options.sortOrder || defaultSortOrder;
27628
- if (Array.isArray(sortOrder)) {
27629
- const keys = Object.keys(json);
27630
- const { privateKeys = [], publicKeys = [] } = Object.groupBy(keys, (key) => key[0] === "_" ? "privateKeys" : "publicKeys");
27631
- sortOrder = [
27632
- ...sortOrder,
27633
- ...defaultSortOrder,
27634
- ...publicKeys.sort(),
27635
- ...privateKeys.sort()
27636
- ];
27637
- }
27638
- return overFields(sortObjectByKeyNameList(json, sortOrder), json);
27639
- }));
27640
- }
27641
- //#endregion
27642
- //#region src/actions/deplint/packageJsonEditor.ts
27643
- function readPackageJson$5(location) {
27644
- return JSON.parse(fs.readFileSync(`${location}/package.json`, "utf8"));
27645
- }
27646
- function writePackageJson$2(location, pkg) {
27647
- const sorted = sortPackageJson(JSON.stringify(pkg, null, 2));
27648
- fs.writeFileSync(`${location}/package.json`, `${sorted}\n`);
27649
- }
27650
- /**
27651
- * Move a dependency from one section to another (e.g. dependencies → devDependencies).
27652
- * When moving out of `peerDependencies`, the corresponding
27653
- * `peerDependenciesMeta` entry is cleared so it does not dangle.
27654
- */
27655
- function moveDep(pkg, dep, from, to) {
27656
- const fromSection = pkg[from];
27657
- if (!fromSection || !Object.hasOwn(fromSection, dep)) return;
27658
- const version = fromSection[dep];
27659
- delete fromSection[dep];
27660
- if (Object.keys(fromSection).length === 0) delete pkg[from];
27661
- const toSection = pkg[to] ?? {};
27662
- toSection[dep] = version;
27663
- pkg[to] = toSection;
27664
- if (from === "peerDependencies" && to !== "peerDependencies") removePeerMeta(pkg, dep);
27665
- }
27666
- /**
27667
- * Remove a dependency from a section. When the section is `peerDependencies`,
27668
- * also strip any matching `peerDependenciesMeta` entry so meta does not
27669
- * dangle for a peer that is no longer declared.
27670
- */
27671
- function removeDep(pkg, dep, section) {
27672
- const sectionObj = pkg[section];
27673
- if (!sectionObj || !Object.hasOwn(sectionObj, dep)) return;
27674
- delete sectionObj[dep];
27675
- if (Object.keys(sectionObj).length === 0) delete pkg[section];
27676
- if (section === "peerDependencies") removePeerMeta(pkg, dep);
27677
- }
27678
- /**
27679
- * Add a dependency to a section with a resolved version.
27680
- */
27681
- function addDep(pkg, dep, version, section) {
27682
- const sectionObj = pkg[section] ?? {};
27683
- sectionObj[dep] = version;
27684
- pkg[section] = sectionObj;
27685
- }
27686
- /**
27687
- * Set or clear `peerDependenciesMeta[dep].optional`. Only meaningful for
27688
- * peers declared in `peerDependencies`.
27689
- *
27690
- * - `optional === true` → ensure `{ optional: true }` is set.
27691
- * - `optional === false` → clear any optional flag (and the entry itself if
27692
- * it would otherwise be `{}`).
27693
- * - `optional === undefined` → no-op; existing meta is preserved.
27694
- */
27695
- function setPeerOptional(pkg, dep, optional) {
27696
- if (optional === void 0) return;
27697
- if (optional) {
27698
- const meta = pkg.peerDependenciesMeta ?? {};
27699
- const entry = meta[dep] ?? {};
27700
- entry.optional = true;
27701
- meta[dep] = entry;
27702
- pkg.peerDependenciesMeta = meta;
27703
- return;
27704
- }
27705
- const meta = pkg.peerDependenciesMeta;
27706
- if (!meta || !Object.hasOwn(meta, dep)) return;
27707
- delete meta[dep].optional;
27708
- if (Object.keys(meta[dep]).length === 0) delete meta[dep];
27709
- if (Object.keys(meta).length === 0) delete pkg.peerDependenciesMeta;
27710
- }
27711
- function removePeerMeta(pkg, dep) {
27712
- const meta = pkg.peerDependenciesMeta;
27713
- if (!meta || !Object.hasOwn(meta, dep)) return;
27714
- delete meta[dep];
27715
- if (Object.keys(meta).length === 0) delete pkg.peerDependenciesMeta;
27716
- }
27717
- const OPAQUE_VERSION_PREFIXES = [
27718
- "catalog:",
27719
- "file:",
27720
- "link:",
27721
- "npm:",
27722
- "patch:",
27723
- "portal:",
27724
- "workspace:"
27725
- ];
27726
- function normalizedVersionSpec(version) {
27727
- const normalized = version?.trim();
27728
- return normalized != null && normalized.length > 0 ? normalized : void 0;
27729
- }
27730
- function isOpaqueVersionSpec(version) {
27731
- const spec = normalizedVersionSpec(version);
27732
- if (spec === void 0) return true;
27733
- if (OPAQUE_VERSION_PREFIXES.some((prefix) => spec.startsWith(prefix))) return true;
27734
- if (spec.includes("://")) return true;
27735
- if (/^(?:git\+|git:|github:|gitlab:|bitbucket:|ssh:)/.test(spec)) return true;
27736
- return /^[\w.-]+\/[\w./-]+(?:#.+)?$/.test(spec);
27737
- }
27738
- function resolveRangeLowerBound(version) {
27739
- const spec = normalizedVersionSpec(version);
27740
- if (spec === void 0 || spec === "*" || isOpaqueVersionSpec(spec)) return void 0;
27741
- try {
27742
- return import_semver.default.minVersion(spec)?.version;
27743
- } catch {
27744
- return;
27745
- }
27746
- }
27747
- function formatFullVersion(version) {
27748
- if (version == null || version.length === 0) return void 0;
27749
- return import_semver.default.parse(version)?.version;
27750
- }
27751
- /**
27752
- * Format an installed version as a broad peerDependency range. The upper
27753
- * bound is the next major (`'major'`, default) or next minor (`'minor'`):
27754
- * 5.5.1, 'major' -> '>=5.5.1 <6'
27755
- * 0.5.1, 'major' -> '>=0.5.1 <1'
27756
- * 7.11.5, 'minor' -> '>=7.11.5 <7.12'
27757
- * 5.5.1-beta.0, 'major' -> '>=5.5.1-beta.0 <6'
27758
- * Falls back to `~<version>` if the version cannot be parsed.
27759
- */
27760
- function formatPeerRange(version, boundType = "major") {
27761
- const parsed = import_semver.default.parse(version);
27762
- if (!parsed) return `~${version}`;
27763
- if (boundType === "minor") return `>=${parsed.version} <${parsed.major}.${parsed.minor + 1}`;
27764
- return `>=${parsed.version} <${parsed.major + 1}`;
27765
- }
27766
- /**
27767
- * Pick the peer-range upper-bound style based on the devDependency's range
27768
- * prefix. `~` devDeps narrow to the next minor; everything else (including
27769
- * `^`, exact pins, and absent ranges) defaults to the next major.
27770
- */
27771
- function inferPeerBoundType(devRange) {
27772
- return devRange?.startsWith("~") ?? false ? "minor" : "major";
27773
- }
27774
- function readInstalledVersion(location, dep) {
27775
- const depPkgPath = findDepPackageJson(location, dep);
27776
- if (depPkgPath == null || depPkgPath.length === 0) return void 0;
27777
- try {
27778
- return JSON.parse(fs.readFileSync(depPkgPath, "utf8")).version;
27779
- } catch {
27780
- return;
28322
+ },
28323
+ { key: "icon" },
28324
+ {
28325
+ key: "badges",
28326
+ over: onArray((badge) => badge.map(sortVSCodeBadgeObject))
28327
+ },
28328
+ {
28329
+ key: "galleryBanner",
28330
+ over: sortObject
28331
+ },
28332
+ { key: "preview" },
28333
+ { key: "markdown" },
28334
+ {
28335
+ key: "pnpm",
28336
+ over: sortPnpmConfig
27781
28337
  }
28338
+ ];
28339
+ const defaultSortOrder = fields.map(({ key }) => key);
28340
+ const overFields = pipe(fields.map(({ key, over }) => over ? overProperty(key, over) : void 0).filter(Boolean));
28341
+ function editStringJSON(json, over) {
28342
+ if (typeof json === "string") {
28343
+ const { indent, type } = detectIndent(json);
28344
+ const endCharacters = json.slice(-1) === "\n" ? "\n" : "";
28345
+ const newline = detectNewlineGraceful(json);
28346
+ json = JSON.parse(json);
28347
+ let result = JSON.stringify(over(json), null, type === "tab" ? " " : indent) + endCharacters;
28348
+ if (newline === "\r\n") result = result.replace(/\n/g, newline);
28349
+ return result;
28350
+ }
28351
+ return over(json);
27782
28352
  }
27783
- /**
27784
- * Pick the lower bound to anchor a peerDependency range to. Prefers the
27785
- * `minVersion` of the sibling devDependency range (so the peer covers the
27786
- * full range the library has been tested against), falling back to the
27787
- * current peer range and then the installed version when no usable devRange
27788
- * is available.
27789
- */
27790
- function resolvePeerLowerBound(location, dep, devRange, peerRange) {
27791
- const devLower = resolveRangeLowerBound(devRange);
27792
- if (devLower) return devLower;
27793
- const peerLower = resolveRangeLowerBound(peerRange);
27794
- if (peerLower) return peerLower;
27795
- return readInstalledVersion(location, dep);
27796
- }
27797
- /**
27798
- * Compute the expected dependency/devDependency range. External package
27799
- * entries use a tilde range pinned to a full three-part lower bound.
27800
- */
27801
- function resolveExpectedDependencyVersion(location, dep, range) {
27802
- const version = formatFullVersion(resolveRangeLowerBound(range) ?? readInstalledVersion(location, dep));
27803
- return version ? `~${version}` : "*";
28353
+ function sortPackageJson(jsonIsh, options = {}) {
28354
+ return editStringJSON(jsonIsh, onObject((json) => {
28355
+ let sortOrder = options.sortOrder || defaultSortOrder;
28356
+ if (Array.isArray(sortOrder)) {
28357
+ const keys = Object.keys(json);
28358
+ const { privateKeys = [], publicKeys = [] } = Object.groupBy(keys, (key) => key[0] === "_" ? "privateKeys" : "publicKeys");
28359
+ sortOrder = [
28360
+ ...sortOrder,
28361
+ ...defaultSortOrder,
28362
+ ...publicKeys.sort(),
28363
+ ...privateKeys.sort()
28364
+ ];
28365
+ }
28366
+ return overFields(sortObjectByKeyNameList(json, sortOrder), json);
28367
+ }));
27804
28368
  }
27805
- /**
27806
- * Resolve the version for a missing devDependency or dependency.
27807
- * Looks in node_modules first, then falls back to '*'.
27808
- */
27809
- function resolveDepVersion(location, dep) {
27810
- return resolveExpectedDependencyVersion(location, dep);
28369
+ //#endregion
28370
+ //#region src/actions/deplint/packageJsonEditor.ts
28371
+ function readPackageJson$4(location) {
28372
+ return JSON.parse(fs.readFileSync(`${location}/package.json`, "utf8"));
27811
28373
  }
27812
- /**
27813
- * Compute the expected peerDependency range for a dep. Anchored at the
27814
- * devDependency's `minVersion` when available (so the peer range is a
27815
- * superset of devDep), otherwise the installed version. Produces
27816
- * `>=<lowerBound> <<major+1>`; falls back to '*' if nothing is known.
27817
- */
27818
- function resolveExpectedPeerVersion(location, dep, devRange, boundType) {
27819
- const lower = resolvePeerLowerBound(location, dep, devRange);
27820
- return lower != null && lower.length > 0 ? formatPeerRange(lower, boundType ?? inferPeerBoundType(devRange)) : "*";
28374
+ function writePackageJson$2(location, pkg) {
28375
+ const sorted = sortPackageJson(JSON.stringify(pkg, null, 2));
28376
+ fs.writeFileSync(`${location}/package.json`, `${sorted}\n`);
27821
28377
  }
27822
28378
  /**
27823
- * Compute the non-broad peerDependency range for a dep. The result is a
27824
- * caret range anchored at a full three-part lower bound. Prefer the sibling
27825
- * devDependency floor; fall back to the current peer range and then the
27826
- * installed version.
28379
+ * Move a dependency from one section to another (e.g. dependencies → devDependencies).
28380
+ * When moving out of `peerDependencies`, the corresponding
28381
+ * `peerDependenciesMeta` entry is cleared so it does not dangle.
27827
28382
  */
27828
- function resolveExpectedPeerShorthandVersion(location, dep, devRange, peerRange) {
27829
- const lower = resolvePeerLowerBound(location, dep, devRange, peerRange);
27830
- if (lower == null || lower.length === 0) return "*";
27831
- const version = formatFullVersion(lower);
27832
- return version ? `^${version}` : "*";
28383
+ function moveDep(pkg, dep, from, to) {
28384
+ const fromSection = pkg[from];
28385
+ if (!fromSection || !Object.hasOwn(fromSection, dep)) return;
28386
+ const version = fromSection[dep];
28387
+ delete fromSection[dep];
28388
+ if (Object.keys(fromSection).length === 0) delete pkg[from];
28389
+ const toSection = pkg[to] ?? {};
28390
+ toSection[dep] = version;
28391
+ pkg[to] = toSection;
28392
+ if (from === "peerDependencies" && to !== "peerDependencies") removePeerMeta(pkg, dep);
27833
28393
  }
27834
28394
  /**
27835
- * Single entry-point used by every rule that writes a peerDependency range.
27836
- * Produces the form configured for `dep.peerDependencies.range-style`
27837
- * directly, so the range-style rule never has to follow up another rule's
27838
- * fix in a second pass. That removes the 2-pass cascade that could oscillate
27839
- * when an upstream rule re-fired on every pass.
28395
+ * Remove a dependency from a section. When the section is `peerDependencies`,
28396
+ * also strip any matching `peerDependenciesMeta` entry so meta does not
28397
+ * dangle for a peer that is no longer declared.
27840
28398
  */
27841
- function resolvePeerVersionForFix(location, dep, devRange, form, boundType) {
27842
- return form === "broad" ? resolveExpectedPeerVersion(location, dep, devRange, boundType) : resolveExpectedPeerShorthandVersion(location, dep, devRange);
28399
+ function removeDep(pkg, dep, section) {
28400
+ const sectionObj = pkg[section];
28401
+ if (!sectionObj || !Object.hasOwn(sectionObj, dep)) return;
28402
+ delete sectionObj[dep];
28403
+ if (Object.keys(sectionObj).length === 0) delete pkg[section];
28404
+ if (section === "peerDependencies") removePeerMeta(pkg, dep);
27843
28405
  }
27844
28406
  /**
27845
- * Compute the expected devDependency range for a dep when bumping to match
27846
- * the installed peer. Returns `~<major>.<minor>` (e.g. `~7.6`); falls back to
27847
- * `~<version>` if parsing fails or '*' if no installed version is found.
28407
+ * Add a dependency to a section with a resolved version.
27848
28408
  */
27849
- function resolveExpectedDevVersion(location, dep) {
27850
- return resolveExpectedDependencyVersion(location, dep);
27851
- }
27852
- //#endregion
27853
- //#region src/actions/deplint/packageEditor.ts
27854
- var DeplintPackageEditor = class {
27855
- dirty = false;
27856
- pkg;
27857
- workspace;
27858
- constructor(workspace) {
27859
- this.workspace = workspace;
27860
- this.pkg = readPackageJson$5(workspace.location);
27861
- }
27862
- applyFix(fix) {
27863
- const before = JSON.stringify(this.pkg);
27864
- switch (fix.action) {
27865
- case "add":
27866
- addDep(this.pkg, fix.dependency, fix.version, fix.section);
27867
- if (fix.section === "peerDependencies") setPeerOptional(this.pkg, fix.dependency, fix.optional);
27868
- break;
27869
- case "move":
27870
- moveDep(this.pkg, fix.dependency, fix.fromSection, fix.toSection);
27871
- if (fix.version !== void 0 && this.pkg[fix.toSection]?.[fix.dependency] !== void 0) this.pkg[fix.toSection][fix.dependency] = fix.version;
27872
- if (fix.toSection === "peerDependencies") setPeerOptional(this.pkg, fix.dependency, fix.optional);
27873
- break;
27874
- case "remove":
27875
- removeDep(this.pkg, fix.dependency, fix.section);
27876
- break;
27877
- case "set-version":
27878
- if (this.pkg[fix.section]?.[fix.dependency] !== void 0) addDep(this.pkg, fix.dependency, fix.version, fix.section);
27879
- break;
27880
- case "resolve-peer-bump": break;
27881
- }
27882
- if (JSON.stringify(this.pkg) === before) return void 0;
27883
- this.dirty = true;
27884
- return {
27885
- dependency: fix.dependency,
27886
- detail: fix.detail,
27887
- workspace: this.workspace
27888
- };
27889
- }
27890
- save() {
27891
- if (!this.dirty) return;
27892
- writePackageJson$2(this.workspace.location, this.pkg);
27893
- }
27894
- };
27895
- //#endregion
27896
- //#region src/actions/deplint/fixer.ts
27897
- function applyDeplintFixes(diagnostics) {
27898
- const editors = /* @__PURE__ */ new Map();
27899
- const applied = [];
27900
- for (const diagnostic of diagnostics) {
27901
- const fixes = diagnostic.fixes ?? [];
27902
- for (const fix of fixes) {
27903
- const workspaceKey = diagnostic.workspace.location;
27904
- let editor = editors.get(workspaceKey);
27905
- if (!editor) {
27906
- editor = new DeplintPackageEditor(diagnostic.workspace);
27907
- editors.set(workspaceKey, editor);
27908
- }
27909
- const appliedFix = editor.applyFix(fix);
27910
- if (appliedFix) applied.push(appliedFix);
27911
- }
27912
- }
27913
- for (const editor of editors.values()) editor.save();
27914
- return applied;
27915
- }
27916
- //#endregion
27917
- //#region src/actions/deplint/ruleConfig.ts
27918
- const VALID_RULE_LEVELS$1 = /* @__PURE__ */ new Set([
27919
- "off",
27920
- "warn",
27921
- "error"
27922
- ]);
27923
- const VALID_RANGE_BOUNDS = /* @__PURE__ */ new Set([
27924
- "infer",
27925
- "major",
27926
- "minor"
27927
- ]);
27928
- const VALID_RANGE_FORMS = /* @__PURE__ */ new Set(["broad", "shorthand"]);
27929
- const VALID_WORKSPACE_PROTOCOLS = /* @__PURE__ */ new Set([
27930
- "workspace:~",
27931
- "workspace:^",
27932
- "workspace:*"
27933
- ]);
27934
- const deprecatedDeplintRuleWarnings = /* @__PURE__ */ new Set();
27935
- const BUILT_IN_RULE_OPTION_KEYS = {
27936
- "dep.dependencies.range-style": /* @__PURE__ */ new Set(["ignore"]),
27937
- "dep.devDependencies.range-style": /* @__PURE__ */ new Set(["ignore"]),
27938
- "dep.peerDependencies.range-style": /* @__PURE__ */ new Set([
27939
- "bound",
27940
- "form",
27941
- "ignore"
27942
- ]),
27943
- "dep.workspace.protocol": /* @__PURE__ */ new Set(["ignore", "protocol"])
27944
- };
27945
- function isRecord$4(value) {
27946
- return typeof value === "object" && value !== null && !Array.isArray(value);
27947
- }
27948
- function isRuleLevel$3(value) {
27949
- return typeof value === "string" && VALID_RULE_LEVELS$1.has(value);
27950
- }
27951
- function severityFromLevel$1(level) {
27952
- return level === "warn" ? "warning" : "error";
27953
- }
27954
- function formatRuleConfigLocation$1(ruleId) {
27955
- return `commands.deplint.rules["${ruleId}"]`;
27956
- }
27957
- function deprecatedDeplintRuleAlias(ruleId) {
27958
- return ruleId.startsWith("dep.") ? `deplint.${ruleId.slice(4)}` : void 0;
27959
- }
27960
- function canonicalDeplintRuleId(ruleId) {
27961
- return ruleId.startsWith("deplint.") ? `dep.${ruleId.slice(8)}` : ruleId;
27962
- }
27963
- function warnDeprecatedDeplintRuleId(ruleId, canonicalRuleId) {
27964
- const key = `${ruleId}:${canonicalRuleId}`;
27965
- if (deprecatedDeplintRuleWarnings.has(key)) return;
27966
- deprecatedDeplintRuleWarnings.add(key);
27967
- console.warn(`Deprecated: commands.deplint.rules["${ruleId}"] is deprecated; use commands.deplint.rules["${canonicalRuleId}"] instead.`);
27968
- }
27969
- function parseRuleConfig$1(ruleId, value) {
27970
- if (typeof value === "string") {
27971
- if (!isRuleLevel$3(value)) throw new TypeError(`${formatRuleConfigLocation$1(ruleId)} must be one of "off", "warn", or "error"`);
27972
- return {
27973
- level: value,
27974
- options: {}
27975
- };
27976
- }
27977
- if (Array.isArray(value)) {
27978
- if (value.length !== 2) throw new TypeError(`${formatRuleConfigLocation$1(ruleId)} tuple must be [level, options]`);
27979
- const level = value[0];
27980
- if (!isRuleLevel$3(level)) throw new TypeError(`${formatRuleConfigLocation$1(ruleId)} level must be one of "off", "warn", or "error"`);
27981
- const options = value[1];
27982
- if (!isRecord$4(options)) throw new TypeError(`${formatRuleConfigLocation$1(ruleId)} options must be an object`);
27983
- return {
27984
- level,
27985
- options: { ...options }
27986
- };
27987
- }
27988
- throw new TypeError(`${formatRuleConfigLocation$1(ruleId)} must be a level or [level, options] tuple`);
27989
- }
27990
- function validateIgnore$1(ruleId, options) {
27991
- if (options.ignore === void 0) return;
27992
- if (!Array.isArray(options.ignore) || options.ignore.some((pattern) => typeof pattern !== "string")) throw new TypeError(`${formatRuleConfigLocation$1(ruleId)}.ignore must be an array of strings`);
27993
- }
27994
- function validateBuiltInOptions(ruleId, options, builtInRuleIds) {
27995
- validateIgnore$1(ruleId, options);
27996
- if (!builtInRuleIds.has(ruleId)) return;
27997
- const allowedKeys = BUILT_IN_RULE_OPTION_KEYS[ruleId] ?? /* @__PURE__ */ new Set(["ignore"]);
27998
- for (const key of Object.keys(options)) if (!allowedKeys.has(key)) throw new TypeError(`${formatRuleConfigLocation$1(ruleId)} has unknown option "${key}"`);
27999
- if (ruleId === "dep.peerDependencies.range-style" && options.bound !== void 0 && (typeof options.bound !== "string" || !VALID_RANGE_BOUNDS.has(options.bound))) throw new TypeError(`${formatRuleConfigLocation$1(ruleId)}.bound must be "infer", "major", or "minor"`);
28000
- if (ruleId === "dep.peerDependencies.range-style" && options.form !== void 0 && (typeof options.form !== "string" || !VALID_RANGE_FORMS.has(options.form))) throw new TypeError(`${formatRuleConfigLocation$1(ruleId)}.form must be "broad" or "shorthand"`);
28001
- if (ruleId === "dep.workspace.protocol" && options.protocol !== void 0 && (typeof options.protocol !== "string" || !VALID_WORKSPACE_PROTOCOLS.has(options.protocol))) throw new TypeError(`${formatRuleConfigLocation$1(ruleId)}.protocol must be "workspace:~", "workspace:^", or "workspace:*"`);
28002
- }
28003
- function normalizeRuleConfigs(ruleConfigs, ruleIds) {
28004
- const normalized = {};
28005
- for (const [ruleId, config] of Object.entries(ruleConfigs)) {
28006
- const canonicalId = canonicalDeplintRuleId(ruleId);
28007
- if (!ruleIds.has(canonicalId)) {
28008
- normalized[ruleId] = config;
28009
- continue;
28010
- }
28011
- if (canonicalId !== ruleId && ruleConfigs[canonicalId] !== void 0) continue;
28012
- if (canonicalId !== ruleId) warnDeprecatedDeplintRuleId(ruleId, canonicalId);
28013
- normalized[canonicalId] = config;
28014
- }
28015
- return normalized;
28016
- }
28017
- function normalizeDeplintRules(rules, config, builtInRuleIds) {
28018
- const ruleIds = new Set(rules.map((rule) => rule.id));
28019
- const ruleConfigs = normalizeRuleConfigs(config?.rules ?? {}, ruleIds);
28020
- const unknownRuleIds = Object.keys(ruleConfigs).filter((ruleId) => !ruleIds.has(ruleId));
28021
- if (unknownRuleIds.length > 0) throw new TypeError(`Unknown deplint rule ${unknownRuleIds.map((ruleId) => `"${ruleId}"`).join(", ")} in commands.deplint.rules`);
28022
- return rules.map((rule) => {
28023
- const legacyRuleId = deprecatedDeplintRuleAlias(rule.id);
28024
- const ruleConfig = ruleConfigs[rule.id] ?? (legacyRuleId === void 0 ? void 0 : ruleConfigs[legacyRuleId]);
28025
- if (ruleConfig === void 0) return {
28026
- ...rule,
28027
- enabled: true,
28028
- meta: {
28029
- ...rule.meta,
28030
- severity: "warning"
28031
- },
28032
- options: {}
28033
- };
28034
- const { level, options } = parseRuleConfig$1(rule.id, ruleConfig);
28035
- validateBuiltInOptions(rule.id, options, builtInRuleIds);
28036
- return {
28037
- ...rule,
28038
- enabled: level !== "off",
28039
- meta: level === "off" ? { ...rule.meta } : {
28040
- ...rule.meta,
28041
- severity: severityFromLevel$1(level)
28042
- },
28043
- options
28044
- };
28045
- });
28046
- }
28047
- function isDependencyIgnoredByRule(dependency, options) {
28048
- if (dependency == null || dependency.length === 0) return false;
28049
- return options?.ignore?.some((pattern) => pattern === dependency || isMatch(dependency, pattern)) ?? false;
28050
- }
28051
- //#endregion
28052
- //#region src/actions/deplint/getExtendsFromTsconfigs.ts
28053
- init_index_min();
28054
- const isExternalReference = (ref) => !ref.startsWith(".") && !ref.startsWith("/");
28055
- function parseExtendsField(value) {
28056
- if (typeof value === "string") return [value];
28057
- if (Array.isArray(value)) return value.filter((v) => typeof v === "string");
28058
- return [];
28059
- }
28060
- function parseTypesField(value) {
28061
- if (Array.isArray(value)) return value.filter((v) => typeof v === "string");
28062
- return [];
28063
- }
28064
- function parsePathsField(value) {
28065
- if (typeof value !== "object" || value === null) return [];
28066
- return Object.keys(value);
28067
- }
28068
- function enqueueResolvedTsconfigExtend(file, ref, discovered, queue) {
28069
- if (isExternalReference(ref)) return;
28070
- const resolved = PATH.resolve(PATH.dirname(file), ref);
28071
- if (fs.existsSync(resolved) && !discovered.has(resolved)) queue.push(resolved);
28072
- }
28073
- function collectTsconfigFiles(location) {
28074
- const discovered = /* @__PURE__ */ new Set();
28075
- const queue = ts$1("./tsconfig*.json", {
28076
- cwd: location,
28077
- absolute: true
28078
- });
28079
- while (queue.length > 0) {
28080
- const file = queue.pop();
28081
- if (file === void 0 || discovered.has(file)) continue;
28082
- discovered.add(file);
28083
- try {
28084
- const parsed = parseTsconfig(file);
28085
- for (const ref of parseExtendsField(parsed.extends)) enqueueResolvedTsconfigExtend(file, ref, discovered, queue);
28086
- } catch {}
28087
- }
28088
- return [...discovered];
28409
+ function addDep(pkg, dep, version, section) {
28410
+ const sectionObj = pkg[section] ?? {};
28411
+ sectionObj[dep] = version;
28412
+ pkg[section] = sectionObj;
28089
28413
  }
28090
28414
  /**
28091
- * Returns true when `importPath` matches a TypeScript `compilerOptions.paths` key.
28092
- * Wildcard `*` matches one or more trailing path segments.
28093
- */
28094
- function isMatchingTsconfigPathPattern(pattern, importPath) {
28095
- const patternParts = pattern.split("/");
28096
- const importParts = importPath.split("/");
28097
- let patternIndex = 0;
28098
- let importIndex = 0;
28099
- while (patternIndex < patternParts.length && importIndex < importParts.length) {
28100
- const patternPart = patternParts[patternIndex];
28101
- if (patternPart === "*") {
28102
- if (patternIndex === patternParts.length - 1) return true;
28103
- patternIndex++;
28104
- importIndex++;
28105
- continue;
28106
- }
28107
- if (patternPart !== importParts[importIndex]) return false;
28108
- patternIndex++;
28109
- importIndex++;
28110
- }
28111
- if (patternIndex === patternParts.length - 1 && patternParts[patternIndex] === "*") return true;
28112
- return patternIndex === patternParts.length && importIndex === importParts.length;
28113
- }
28114
- function isTsconfigPathAlias(importPath, pathPatterns) {
28115
- return pathPatterns.some((pattern) => isMatchingTsconfigPathPattern(pattern, importPath));
28116
- }
28117
- function parseTsconfig(file) {
28118
- const cleaned = fs.readFileSync(file, "utf8").replaceAll(/\/\/.*/g, "").replaceAll(/,\s*([}\]])/g, "$1");
28119
- return JSON.parse(cleaned);
28120
- }
28121
- function getPathsFromTsconfigs(location) {
28122
- const patterns = /* @__PURE__ */ new Set();
28123
- for (const file of collectTsconfigFiles(location)) try {
28124
- const compilerOptions = parseTsconfig(file).compilerOptions;
28125
- const pathPatterns = parsePathsField(compilerOptions?.paths);
28126
- for (const pattern of pathPatterns) patterns.add(pattern);
28127
- } catch {}
28128
- return [...patterns];
28129
- }
28130
- function getExtendsFromTsconfigs(location) {
28131
- const packages = /* @__PURE__ */ new Set();
28132
- for (const file of collectTsconfigFiles(location)) try {
28133
- const refs = parseExtendsField(parseTsconfig(file).extends);
28134
- for (const ref of refs) if (isExternalReference(ref)) packages.add(getBasePackageName(ref));
28135
- } catch {}
28136
- return [...packages];
28137
- }
28138
- function getTypesFromTsconfigs(location) {
28139
- const packages = /* @__PURE__ */ new Set();
28140
- for (const file of collectTsconfigFiles(location)) try {
28141
- const compilerOptions = parseTsconfig(file).compilerOptions;
28142
- const refs = parseTypesField(compilerOptions?.types);
28143
- for (const ref of refs) packages.add(getBasePackageName(ref));
28144
- } catch {}
28145
- return [...packages];
28146
- }
28147
- //#endregion
28148
- //#region src/actions/deplint/getImportsFromFile.ts
28149
- function isTypeOnlyImportClause(clause) {
28150
- if (clause === void 0) return false;
28151
- if ("phaseModifier" in clause) {
28152
- const mod = clause.phaseModifier;
28153
- return (typeof mod === "number" ? mod : mod?.kind) === ts.SyntaxKind.TypeKeyword;
28154
- }
28155
- return clause.isTypeOnly ?? false;
28156
- }
28157
- function getImportsFromFile(filePath, importPaths, typeImportPaths) {
28158
- const sourceCode = fs.readFileSync(filePath, "utf8");
28159
- const isJsFile = filePath.endsWith(".mjs") || filePath.endsWith(".cjs");
28160
- const sourceFile = ts.createSourceFile(PATH.basename(filePath), sourceCode, ts.ScriptTarget.Latest, true, isJsFile ? ts.ScriptKind.JS : void 0);
28161
- const imports = [];
28162
- const typeImports = [];
28163
- const isDeclarationFile = filePath.endsWith(".d.ts") || filePath.endsWith(".d.mts") || filePath.endsWith(".d.cts");
28164
- function visit(node) {
28165
- if (ts.isImportDeclaration(node) || ts.isExportDeclaration(node)) {
28166
- const moduleSpecifier = node.moduleSpecifier?.getFullText();
28167
- const isTypeImport = ts.isImportDeclaration(node) ? isTypeOnlyImportClause(node.importClause) : false;
28168
- if (typeof moduleSpecifier === "string") {
28169
- const trimmed = moduleSpecifier.replaceAll(/['"]/g, "").trim();
28170
- if (isTypeImport || isDeclarationFile) typeImports.push(trimmed);
28171
- else imports.push(trimmed);
28172
- }
28173
- } else if (ts.isCallExpression(node) && node.expression.kind === ts.SyntaxKind.ImportKeyword) {
28174
- const [arg] = node.arguments;
28175
- if (ts.isStringLiteral(arg)) imports.push(arg.text);
28176
- } else if (ts.isCallExpression(node) && ts.isIdentifier(node.expression) && node.expression.text === "require" && node.arguments.length > 0 && ts.isStringLiteral(node.arguments[0])) imports.push(node.arguments[0].text);
28177
- ts.forEachChild(node, visit);
28178
- }
28179
- visit(sourceFile);
28180
- for (const ref of sourceFile.typeReferenceDirectives) typeImports.push(ref.fileName);
28181
- const importsStartsWithExcludes = [
28182
- ".",
28183
- "#",
28184
- "node:"
28185
- ];
28186
- const isValidImport = (imp) => importsStartsWithExcludes.every((exc) => !imp.startsWith(exc)) && !imp.includes("*") && !imp.includes("!");
28187
- const cleanedImports = imports.filter(isValidImport).map(getBasePackageName);
28188
- const cleanedTypeImports = typeImports.filter(isValidImport).map(getBasePackageName);
28189
- for (const imp of cleanedImports) {
28190
- importPaths[imp] ??= [];
28191
- importPaths[imp].push(filePath);
28192
- }
28193
- for (const imp of cleanedTypeImports) {
28194
- typeImportPaths[imp] ??= [];
28195
- typeImportPaths[imp].push(filePath);
28196
- }
28197
- return [cleanedImports, cleanedTypeImports];
28198
- }
28199
- //#endregion
28200
- //#region src/actions/deplint/getStorybookConfigImports.ts
28201
- const storybookMainPattern = /(?:^|[\\/])\.storybook[\\/]main\.[cm]?[jt]sx?$/;
28202
- const npmPackageNamePattern = /^@?[a-z0-9][\w./-]*$/i;
28203
- function isStorybookMainFile(filePath) {
28204
- return storybookMainPattern.test(filePath);
28205
- }
28206
- function getPropertyName$1(prop) {
28207
- if (ts.isIdentifier(prop.name)) return prop.name.text;
28208
- if (ts.isStringLiteral(prop.name) || ts.isNoSubstitutionTemplateLiteral(prop.name)) return prop.name.text;
28209
- }
28210
- function pushIfPackage(text, collected) {
28211
- const trimmed = text.trim();
28212
- if (trimmed.length === 0) return;
28213
- if (trimmed.startsWith(".") || trimmed.startsWith("/") || trimmed.startsWith("node:")) return;
28214
- if (!npmPackageNamePattern.test(trimmed)) return;
28215
- collected.push(trimmed);
28216
- }
28217
- function extractFromEntry(node, collected) {
28218
- if (ts.isStringLiteral(node) || ts.isNoSubstitutionTemplateLiteral(node)) {
28219
- pushIfPackage(node.text, collected);
28220
- return;
28221
- }
28222
- if (ts.isObjectLiteralExpression(node)) {
28223
- for (const prop of node.properties) if (ts.isPropertyAssignment(prop) && getPropertyName$1(prop) === "name") extractFromEntry(prop.initializer, collected);
28224
- return;
28225
- }
28226
- if (ts.isCallExpression(node)) {
28227
- for (const arg of node.arguments) if (ts.isStringLiteral(arg) || ts.isNoSubstitutionTemplateLiteral(arg)) pushIfPackage(arg.text, collected);
28415
+ * Set or clear `peerDependenciesMeta[dep].optional`. Only meaningful for
28416
+ * peers declared in `peerDependencies`.
28417
+ *
28418
+ * - `optional === true` → ensure `{ optional: true }` is set.
28419
+ * - `optional === false` → clear any optional flag (and the entry itself if
28420
+ * it would otherwise be `{}`).
28421
+ * - `optional === undefined` → no-op; existing meta is preserved.
28422
+ */
28423
+ function setPeerOptional(pkg, dep, optional) {
28424
+ if (optional === void 0) return;
28425
+ if (optional) {
28426
+ const meta = pkg.peerDependenciesMeta ?? {};
28427
+ const entry = meta[dep] ?? {};
28428
+ entry.optional = true;
28429
+ meta[dep] = entry;
28430
+ pkg.peerDependenciesMeta = meta;
28228
28431
  return;
28229
28432
  }
28230
- if (ts.isArrayLiteralExpression(node)) for (const element of node.elements) extractFromEntry(element, collected);
28433
+ const meta = pkg.peerDependenciesMeta;
28434
+ if (!meta || !Object.hasOwn(meta, dep)) return;
28435
+ delete meta[dep].optional;
28436
+ if (Object.keys(meta[dep]).length === 0) delete meta[dep];
28437
+ if (Object.keys(meta).length === 0) delete pkg.peerDependenciesMeta;
28231
28438
  }
28232
- function getStorybookConfigImports(filePath, importPaths) {
28233
- if (!isStorybookMainFile(filePath)) return [];
28234
- let sourceCode;
28235
- try {
28236
- sourceCode = fs.readFileSync(filePath, "utf8");
28237
- } catch {
28238
- return [];
28239
- }
28240
- const sourceFile = ts.createSourceFile(PATH.basename(filePath), sourceCode, ts.ScriptTarget.Latest, true);
28241
- const collected = [];
28242
- function visit(node) {
28243
- if (ts.isPropertyAssignment(node)) {
28244
- const name = getPropertyName$1(node);
28245
- if (name === "addons") {
28246
- if (ts.isArrayLiteralExpression(node.initializer)) for (const element of node.initializer.elements) extractFromEntry(element, collected);
28247
- } else if (name === "framework" || name === "builder") extractFromEntry(node.initializer, collected);
28248
- }
28249
- ts.forEachChild(node, visit);
28250
- }
28251
- visit(sourceFile);
28252
- const cleaned = [...new Set(collected.map(getBasePackageName))];
28253
- for (const imp of cleaned) {
28254
- importPaths[imp] ??= [];
28255
- if (!importPaths[imp].includes(filePath)) importPaths[imp].push(filePath);
28256
- }
28257
- return cleaned;
28439
+ function removePeerMeta(pkg, dep) {
28440
+ const meta = pkg.peerDependenciesMeta;
28441
+ if (!meta || !Object.hasOwn(meta, dep)) return;
28442
+ delete meta[dep];
28443
+ if (Object.keys(meta).length === 0) delete pkg.peerDependenciesMeta;
28258
28444
  }
28259
- //#endregion
28260
- //#region src/actions/deplint/getExternalImportsFromFiles.ts
28261
- const internalImportPrefixes = [
28262
- ".",
28263
- "#",
28264
- "node:"
28445
+ const OPAQUE_VERSION_PREFIXES = [
28446
+ "catalog:",
28447
+ "file:",
28448
+ "link:",
28449
+ "npm:",
28450
+ "patch:",
28451
+ "portal:",
28452
+ "workspace:"
28265
28453
  ];
28266
- const removeInternalImports = (imports) => {
28267
- return imports.filter((imp) => internalImportPrefixes.every((prefix) => !imp.startsWith(prefix)));
28268
- };
28269
- const removeTsconfigPathAliases = (imports, pathPatterns) => {
28270
- if (pathPatterns.length === 0) return imports;
28271
- return imports.filter((imp) => !isTsconfigPathAlias(imp, pathPatterns));
28272
- };
28273
- const isDeclarationFile$1 = (file) => file.endsWith(".d.ts") || file.endsWith(".d.cts") || file.endsWith(".d.mts");
28274
- const toolingConfigFilePattern = /(?:^|[\\/])xy\.config\.[cm]?[jt]sx?$/;
28275
- const isToolingConfigFile = (file) => toolingConfigFilePattern.test(file);
28276
- function excludeToolingConfigImports(paths) {
28277
- const filtered = {};
28278
- for (const [imp, files] of Object.entries(paths)) {
28279
- const kept = files.filter((file) => !isToolingConfigFile(file));
28280
- if (kept.length > 0) filtered[imp] = kept;
28281
- }
28282
- return filtered;
28454
+ function normalizedVersionSpec(version) {
28455
+ const normalized = version?.trim();
28456
+ return normalized != null && normalized.length > 0 ? normalized : void 0;
28283
28457
  }
28284
- function formatExportPath$2(pathParts) {
28285
- return pathParts.map((part, index) => {
28286
- if (index === 0) return part;
28287
- if (part.startsWith("[")) return part;
28288
- return /^[a-zA-Z_$][\w$]*$/.test(part) ? `.${part}` : `[${JSON.stringify(part)}]`;
28289
- }).join("");
28458
+ function isOpaqueVersionSpec(version) {
28459
+ const spec = normalizedVersionSpec(version);
28460
+ if (spec === void 0) return true;
28461
+ if (OPAQUE_VERSION_PREFIXES.some((prefix) => spec.startsWith(prefix))) return true;
28462
+ if (spec.includes("://")) return true;
28463
+ if (/^(?:git\+|git:|github:|gitlab:|bitbucket:|ssh:)/.test(spec)) return true;
28464
+ return /^[\w.-]+\/[\w./-]+(?:#.+)?$/.test(spec);
28290
28465
  }
28291
- function collectExportTargets$1(value, pathParts = ["exports"]) {
28292
- if (typeof value === "string") {
28293
- if (!value.startsWith("./")) return [];
28294
- return [{
28295
- path: formatExportPath$2(pathParts),
28296
- target: value
28297
- }];
28466
+ function resolveRangeLowerBound(version) {
28467
+ const spec = normalizedVersionSpec(version);
28468
+ if (spec === void 0 || spec === "*" || isOpaqueVersionSpec(spec)) return void 0;
28469
+ try {
28470
+ return import_semver.default.minVersion(spec)?.version;
28471
+ } catch {
28472
+ return;
28298
28473
  }
28299
- if (Array.isArray(value)) return value.flatMap((entry, index) => collectExportTargets$1(entry, [...pathParts, `[${index}]`]));
28300
- if (typeof value !== "object" || value === null) return [];
28301
- return Object.entries(value).flatMap(([key, nested]) => collectExportTargets$1(nested, [...pathParts, key]));
28302
28474
  }
28303
- function hasExportTarget(location, target) {
28304
- if (target.includes("*")) return findFilesByGlob(location, target).length > 0;
28305
- return fs.existsSync(PATH.resolve(location, target));
28475
+ function formatFullVersion(version) {
28476
+ if (version == null || version.length === 0) return void 0;
28477
+ return import_semver.default.parse(version)?.version;
28306
28478
  }
28307
- function readPackageJson$4(location) {
28479
+ /**
28480
+ * Format an installed version as a broad peerDependency range. The upper
28481
+ * bound is the next major (`'major'`, default) or next minor (`'minor'`):
28482
+ * 5.5.1, 'major' -> '>=5.5.1 <6'
28483
+ * 0.5.1, 'major' -> '>=0.5.1 <1'
28484
+ * 7.11.5, 'minor' -> '>=7.11.5 <7.12'
28485
+ * 5.5.1-beta.0, 'major' -> '>=5.5.1-beta.0 <6'
28486
+ * Falls back to `~<version>` if the version cannot be parsed.
28487
+ */
28488
+ function formatPeerRange(version, boundType = "major") {
28489
+ const parsed = import_semver.default.parse(version);
28490
+ if (!parsed) return `~${version}`;
28491
+ if (boundType === "minor") return `>=${parsed.version} <${parsed.major}.${parsed.minor + 1}`;
28492
+ return `>=${parsed.version} <${parsed.major + 1}`;
28493
+ }
28494
+ /**
28495
+ * Pick the peer-range upper-bound style based on the devDependency's range
28496
+ * prefix. `~` devDeps narrow to the next minor; everything else (including
28497
+ * `^`, exact pins, and absent ranges) defaults to the next major.
28498
+ */
28499
+ function inferPeerBoundType(devRange) {
28500
+ return devRange?.startsWith("~") ?? false ? "minor" : "major";
28501
+ }
28502
+ function readInstalledVersion(location, dep) {
28503
+ const depPkgPath = findDepPackageJson(location, dep);
28504
+ if (depPkgPath == null || depPkgPath.length === 0) return void 0;
28308
28505
  try {
28309
- return JSON.parse(fs.readFileSync(`${location}/package.json`, "utf8"));
28506
+ return JSON.parse(fs.readFileSync(depPkgPath, "utf8")).version;
28310
28507
  } catch {
28311
28508
  return;
28312
28509
  }
28313
28510
  }
28314
- function warnMissingExportTargets(name, location) {
28315
- const targets = collectExportTargets$1(readPackageJson$4(location)?.exports);
28316
- const warnedTargets = /* @__PURE__ */ new Set();
28317
- const prefix = name != null && name.length > 0 ? `[${chalk.blue(name)}] ` : "";
28318
- for (const { path: exportPath, target } of targets) {
28319
- if (warnedTargets.has(target)) continue;
28320
- warnedTargets.add(target);
28321
- if (hasExportTarget(location, target)) continue;
28322
- const description = target.includes("*") ? "pattern matched no files" : "file missing";
28323
- console.warn(`${prefix}${chalk.yellow(`deplint: package.json export ${description}: ${target} (${exportPath})`)}`);
28324
- }
28511
+ /**
28512
+ * Pick the lower bound to anchor a peerDependency range to. Prefers the
28513
+ * `minVersion` of the sibling devDependency range (so the peer covers the
28514
+ * full range the library has been tested against), falling back to the
28515
+ * current peer range and then the installed version when no usable devRange
28516
+ * is available.
28517
+ */
28518
+ function resolvePeerLowerBound(location, dep, devRange, peerRange) {
28519
+ const devLower = resolveRangeLowerBound(devRange);
28520
+ if (devLower) return devLower;
28521
+ const peerLower = resolveRangeLowerBound(peerRange);
28522
+ if (peerLower) return peerLower;
28523
+ return readInstalledVersion(location, dep);
28325
28524
  }
28326
- function hasShippedTsconfig(location) {
28327
- return (readPackageJson$4(location)?.files)?.some((f) => f === "tsconfig.json" || f.includes("tsconfig")) ?? false;
28525
+ /**
28526
+ * Compute the expected dependency/devDependency range. External package
28527
+ * entries use a tilde range pinned to a full three-part lower bound.
28528
+ */
28529
+ function resolveExpectedDependencyVersion(location, dep, range) {
28530
+ const version = formatFullVersion(resolveRangeLowerBound(range) ?? readInstalledVersion(location, dep));
28531
+ return version ? `~${version}` : "*";
28328
28532
  }
28329
- function getEffectiveRuntimeImportPaths({ distImportPaths, distTypeImportPaths, hasDist, hasRuntimeRoots, srcImportPaths, srcTypeImportPaths }) {
28330
- if (hasDist) return {
28331
- importPaths: distImportPaths,
28332
- typeImportPaths: distTypeImportPaths
28333
- };
28334
- if (!hasRuntimeRoots) return {
28335
- importPaths: {},
28336
- typeImportPaths: {}
28337
- };
28338
- return {
28339
- importPaths: excludeToolingConfigImports(srcImportPaths),
28340
- typeImportPaths: excludeToolingConfigImports(srcTypeImportPaths)
28341
- };
28533
+ /**
28534
+ * Resolve the version for a missing devDependency or dependency.
28535
+ * Looks in node_modules first, then falls back to '*'.
28536
+ */
28537
+ function resolveDepVersion(location, dep) {
28538
+ return resolveExpectedDependencyVersion(location, dep);
28342
28539
  }
28343
- function getExternalImportsFromFiles({ allFiles, distFiles, hasRuntimeRoots = true, location, name, tsconfigExtends = [], tsconfigPaths = [], tsconfigTypes = [] }) {
28344
- const srcImportPaths = {};
28345
- const srcTypeImportPaths = {};
28346
- for (const path of allFiles) {
28347
- getImportsFromFile(path, srcImportPaths, srcTypeImportPaths);
28348
- getStorybookConfigImports(path, srcImportPaths);
28349
- }
28350
- const allImportPaths = { ...srcImportPaths };
28351
- for (const [key, paths] of Object.entries(srcTypeImportPaths)) allImportPaths[key] = [...allImportPaths[key] ?? [], ...paths];
28352
- const distImportPaths = {};
28353
- const distTypeImportPaths = {};
28354
- const hasDist = distFiles.length > 0;
28355
- if (hasDist) {
28356
- const distTypeFiles = distFiles.filter(isDeclarationFile$1);
28357
- const distCodeFiles = distFiles.filter((file) => !isDeclarationFile$1(file));
28358
- for (const path of distCodeFiles) getImportsFromFile(path, distImportPaths, distImportPaths);
28359
- for (const path of distTypeFiles) getImportsFromFile(path, distTypeImportPaths, distTypeImportPaths);
28360
- }
28361
- warnMissingExportTargets(name, location);
28362
- const { importPaths: effectiveDistImportPaths, typeImportPaths: effectiveDistTypeImportPaths } = getEffectiveRuntimeImportPaths({
28363
- distImportPaths,
28364
- distTypeImportPaths,
28365
- hasDist,
28366
- hasRuntimeRoots,
28367
- srcImportPaths,
28368
- srcTypeImportPaths
28369
- });
28370
- const allImports = Object.keys(allImportPaths);
28371
- const distImports = Object.keys(effectiveDistImportPaths);
28372
- const externalAllImports = removeTsconfigPathAliases(removeInternalImports(allImports), tsconfigPaths);
28373
- const externalDistImports = removeTsconfigPathAliases(removeInternalImports(distImports), tsconfigPaths);
28374
- const externalDistTypeImports = removeTsconfigPathAliases(removeInternalImports(Object.keys(effectiveDistTypeImportPaths)), tsconfigPaths);
28375
- const isDistTsconfig = hasShippedTsconfig(location);
28376
- for (const ext of tsconfigExtends) {
28377
- if (!externalAllImports.includes(ext)) externalAllImports.push(ext);
28378
- if (isDistTsconfig && !externalDistImports.includes(ext)) externalDistImports.push(ext);
28379
- }
28380
- for (const typ of tsconfigTypes) if (!externalAllImports.includes(typ)) externalAllImports.push(typ);
28381
- return {
28382
- allImportPaths,
28383
- allImports,
28384
- distImportPaths: effectiveDistImportPaths,
28385
- distImports,
28386
- externalAllImports,
28387
- externalDistImports,
28388
- externalDistTypeImports,
28389
- tsconfigExtends: [...tsconfigExtends]
28390
- };
28540
+ /**
28541
+ * Compute the expected peerDependency range for a dep. Anchored at the
28542
+ * devDependency's `minVersion` when available (so the peer range is a
28543
+ * superset of devDep), otherwise the installed version. Produces
28544
+ * `>=<lowerBound> <<major+1>`; falls back to '*' if nothing is known.
28545
+ */
28546
+ function resolveExpectedPeerVersion(location, dep, devRange, boundType) {
28547
+ const lower = resolvePeerLowerBound(location, dep, devRange);
28548
+ return lower != null && lower.length > 0 ? formatPeerRange(lower, boundType ?? inferPeerBoundType(devRange)) : "*";
28549
+ }
28550
+ /**
28551
+ * Compute the non-broad peerDependency range for a dep. The result is a
28552
+ * caret range anchored at a full three-part lower bound. Prefer the sibling
28553
+ * devDependency floor; fall back to the current peer range and then the
28554
+ * installed version.
28555
+ */
28556
+ function resolveExpectedPeerShorthandVersion(location, dep, devRange, peerRange) {
28557
+ const lower = resolvePeerLowerBound(location, dep, devRange, peerRange);
28558
+ if (lower == null || lower.length === 0) return "*";
28559
+ const version = formatFullVersion(lower);
28560
+ return version ? `^${version}` : "*";
28561
+ }
28562
+ /**
28563
+ * Single entry-point used by every rule that writes a peerDependency range.
28564
+ * Produces the form configured for `dep.peerDependencies.range-style`
28565
+ * directly, so the range-style rule never has to follow up another rule's
28566
+ * fix in a second pass. That removes the 2-pass cascade that could oscillate
28567
+ * when an upstream rule re-fired on every pass.
28568
+ */
28569
+ function resolvePeerVersionForFix(location, dep, devRange, form, boundType) {
28570
+ return form === "broad" ? resolveExpectedPeerVersion(location, dep, devRange, boundType) : resolveExpectedPeerShorthandVersion(location, dep, devRange);
28571
+ }
28572
+ /**
28573
+ * Compute the expected devDependency range for a dep when bumping to match
28574
+ * the installed peer. Returns `~<major>.<minor>` (e.g. `~7.6`); falls back to
28575
+ * `~<version>` if parsing fails or '*' if no installed version is found.
28576
+ */
28577
+ function resolveExpectedDevVersion(location, dep) {
28578
+ return resolveExpectedDependencyVersion(location, dep);
28391
28579
  }
28392
28580
  //#endregion
28393
28581
  //#region src/actions/deplint/checkPackage/getMismatchedPeerDevVersions.ts
@@ -28660,14 +28848,9 @@ const allExecFunctions = shellCommandFunctions.union(directExecFunctions);
28660
28848
  */
28661
28849
  function getCommandTokensFromFile(filePath) {
28662
28850
  const tokens = /* @__PURE__ */ new Set();
28663
- let sourceCode;
28664
- try {
28665
- sourceCode = fs.readFileSync(filePath, "utf8");
28666
- } catch {
28667
- return tokens;
28668
- }
28669
- const isMjsFile = filePath.endsWith(".mjs");
28670
- const sourceFile = ts.createSourceFile(PATH.basename(filePath), sourceCode, ts.ScriptTarget.Latest, true, isMjsFile ? ts.ScriptKind.JS : void 0);
28851
+ const cached = tryGetCachedSourceFile(filePath);
28852
+ if (cached === void 0) return tokens;
28853
+ const { sourceFile } = cached;
28671
28854
  function visit(node) {
28672
28855
  if (ts.isCallExpression(node) && node.arguments.length > 0) {
28673
28856
  const fnName = getFunctionName(node.expression);
@@ -29627,277 +29810,96 @@ const workspaceVersionProblemsRule = {
29627
29810
  data: {
29628
29811
  ...finding,
29629
29812
  expectedVersion
29630
- },
29631
- dependency: finding.dep,
29632
- message: `Workspace dependency ${finding.dep} in ${finding.section} should use ${configuredProtocol} — found ${finding.version}`
29633
- });
29634
- }
29635
- },
29636
- resolveFixes(diagnostic) {
29637
- const data = diagnostic.data;
29638
- return data ? [{
29639
- action: "set-version",
29640
- dependency: data.dep,
29641
- detail: `set ${data.expectedVersion ?? "workspace:~"} for ${data.section}`,
29642
- section: data.section,
29643
- version: data.expectedVersion ?? "workspace:~"
29644
- }] : [];
29645
- }
29646
- };
29647
- function shouldSkipExternalRangeStyle(context, dep, current) {
29648
- return current === void 0 || isOpaqueVersionSpec(current) || (context.workspaceNames?.has(dep) ?? false);
29649
- }
29650
- function shouldSkipPeerRangeStyle(context, dep, current) {
29651
- return (context.exclude?.has(dep) ?? false) || current === void 0 || isOpaqueVersionSpec(current) || (context.workspaceNames?.has(dep) ?? false);
29652
- }
29653
- function expectedPeerRangeStyle(context, dep, devRange, peerRange, form, boundType) {
29654
- return form === "broad" ? resolveExpectedPeerVersion(context.workspace.location, dep, devRange, boundType) : resolveExpectedPeerShorthandVersion(context.workspace.location, dep, devRange, peerRange);
29655
- }
29656
- const builtInDeplintPlugin = {
29657
- name: "builtin",
29658
- rules: [
29659
- unlistedDependenciesRule,
29660
- unusedDependenciesRule,
29661
- misplacedDependenciesRule,
29662
- {
29663
- category: "dependencies",
29664
- id: "dep.dependencies.aei-review",
29665
- meta: {
29666
- description: "Dependencies whose API Exposure Index score is borderline — placement needs manual review",
29667
- fixable: [],
29668
- severity: "warning"
29669
- },
29670
- evaluate(context) {
29671
- if (context.classifierMode !== "aei" || context.isTerminalPackage) return;
29672
- const candidates = /* @__PURE__ */ new Set([...context.packageParams.dependencies, ...context.packageParams.peerDependencies]);
29673
- for (const dep of candidates) {
29674
- if (context.forceDeps.has(dep) || context.forceDevs.has(dep) || context.forcePeers.has(dep)) continue;
29675
- if (context.packageParams.dependencyVersions[dep]?.startsWith("workspace:")) continue;
29676
- if (context.workspaceNames?.has(dep) ?? false) continue;
29677
- if (dep.startsWith("@types/")) continue;
29678
- if (context.classifyDependency(dep) !== "review") continue;
29679
- context.report({
29680
- dependency: dep,
29681
- message: `AEI score for ${dep} is borderline — review whether it belongs in dependencies or peerDependencies (run \`xy api-exposure --dep ${dep}\` for the evidence)`
29682
- });
29683
- }
29684
- }
29685
- },
29686
- dependencyRangeStyleRule,
29687
- unlistedDevDependenciesRule,
29688
- unusedDevDependenciesRule,
29689
- redundantDevDependenciesRule,
29690
- devDependencyRangeStyleRule,
29691
- unsatisfiedPeersRule,
29692
- unusedPeerDependenciesRule,
29693
- unrequestedPeerDependenciesRule,
29694
- misplacedPeerDependenciesRule,
29695
- redundantPeerDependenciesRule,
29696
- mismatchedPeerDevVersionsRule,
29697
- peerDependencyRangeStyleRule,
29698
- workspaceVersionProblemsRule
29699
- ]
29700
- };
29701
- //#endregion
29702
- //#region src/actions/deplint/loader.ts
29703
- function resolvePluginSpecifier(specifier) {
29704
- if (specifier.startsWith(".") || PATH.isAbsolute(specifier)) return pathToFileURL(PATH.resolve(specifier)).href;
29705
- return specifier;
29706
- }
29707
- function isPlugin(value) {
29708
- return typeof value === "object" && value !== null && "name" in value && "rules" in value && Array.isArray(value.rules);
29709
- }
29710
- async function loadDeplintRules(config) {
29711
- const plugins = [builtInDeplintPlugin];
29712
- const pluginSpecifiers = config?.plugins ?? [];
29713
- for (const specifier of pluginSpecifiers) {
29714
- const pluginModule = await import(resolvePluginSpecifier(specifier));
29715
- const plugin = pluginModule.default ?? pluginModule.plugin;
29716
- if (!isPlugin(plugin)) throw new TypeError(`Invalid deplint plugin "${specifier}" - expected a plugin with a name and rules array`);
29717
- plugins.push(plugin);
29718
- }
29719
- return normalizeDeplintRules(plugins.flatMap((plugin) => plugin.rules), config, new Set(builtInDeplintPlugin.rules.map((rule) => rule.id)));
29720
- }
29721
- //#endregion
29722
- //#region src/actions/deplint/fetchPackageManifest.ts
29723
- /**
29724
- * Fetches npm registry manifests for deplint's peer-dependency resolution.
29725
- *
29726
- * Unlike `lib/updo/fetchRegistryInfo`, which returns only version strings
29727
- * and dist-tags, this helper preserves each version's `peerDependencies`
29728
- * block. That's what we need to answer the question: "what's the latest
29729
- * version of package X whose peer range accepts peer Y at version Z?"
29730
- *
29731
- * Results are cached per-process so repeated lookups within a single
29732
- * deplint run hit the registry at most once per package.
29733
- */
29734
- const REGISTRY_BASE = "https://registry.npmjs.org";
29735
- const cache = /* @__PURE__ */ new Map();
29736
- async function fetchUncached(packageName) {
29737
- try {
29738
- const url = `${REGISTRY_BASE}/${encodeURIComponent(packageName)}`;
29739
- const res = await fetch(url, { headers: { Accept: "application/vnd.npm.install-v1+json" } });
29740
- if (!res.ok) return void 0;
29741
- const data = await res.json();
29742
- const versionsMap = data.versions ?? {};
29743
- const versions = Object.entries(versionsMap).map(([version, manifest]) => ({
29744
- peerDependencies: manifest.peerDependencies ?? {},
29745
- version
29746
- }));
29747
- return {
29748
- distTags: data["dist-tags"] ?? {},
29749
- versions
29750
- };
29751
- } catch {
29752
- return;
29753
- }
29754
- }
29755
- function fetchPackageManifest(packageName) {
29756
- const existing = cache.get(packageName);
29757
- if (existing) return existing;
29758
- const pending = fetchUncached(packageName);
29759
- cache.set(packageName, pending);
29760
- return pending;
29761
- }
29762
- async function fetchPackageManifests(packageNames, concurrency = 16) {
29763
- const unique = [...new Set(packageNames)];
29764
- const results = /* @__PURE__ */ new Map();
29765
- await runWithConcurrency(unique, concurrency, async (name) => {
29766
- results.set(name, await fetchPackageManifest(name));
29767
- });
29768
- return results;
29769
- }
29770
- //#endregion
29771
- //#region src/actions/deplint/resolvePeerBumpFixes.ts
29772
- /**
29773
- * Resolves `resolve-peer-bump` fixes by consulting the npm registry.
29774
- *
29775
- * A `resolve-peer-bump` fix says "the installed peer X@v doesn't satisfy the
29776
- * range that the currently installed version of the requiring dep D declares —
29777
- * bump our declared range for D." To pick a concrete target range, we fetch
29778
- * D's registry manifest and find the highest published version whose
29779
- * `peerDependencies[X]` range accepts v. We then express our new declared
29780
- * range using D's actual version numbers (not the peer's — that was the old
29781
- * bug).
29782
- *
29783
- * If no published version of D accepts the installed peer, the fix is dropped
29784
- * and the mismatch remains visible in the next deplint pass as a warning.
29785
- */
29786
- function keyOf(k) {
29787
- return `${k.dependency}|${k.peer}|${k.installedPeerVersion}|${k.currentRange}`;
29788
- }
29789
- function collectPeerBumpFixes(diagnostics) {
29790
- const fixes = [];
29791
- const packageNames = /* @__PURE__ */ new Set();
29792
- for (const diagnostic of diagnostics) {
29793
- const peerBumpFixes = (diagnostic.fixes ?? []).filter((candidate) => candidate.action === "resolve-peer-bump");
29794
- for (const fix of peerBumpFixes) {
29795
- fixes.push(fix);
29796
- packageNames.add(fix.dependency);
29797
- }
29798
- }
29799
- return {
29800
- fixes,
29801
- packageNames: [...packageNames]
29802
- };
29803
- }
29804
- function canAcceptPeer(version, peer, installedPeerVersion) {
29805
- const range = version.peerDependencies[peer];
29806
- if (!range || range === "*") return true;
29807
- if (range.startsWith("workspace:")) return true;
29808
- try {
29809
- return import_semver.default.satisfies(installedPeerVersion, range, { includePrerelease: true });
29810
- } catch {
29811
- return false;
29812
- }
29813
- }
29814
- function pickHighest(versions) {
29815
- if (versions.length === 0) return void 0;
29816
- const stable = versions.filter((v) => import_semver.default.prerelease(v) === null);
29817
- return (stable.length > 0 ? stable : versions).toSorted(import_semver.default.rcompare)[0];
29818
- }
29819
- /**
29820
- * Returns a version to bump to ONLY if doing so would meaningfully change what
29821
- * `pnpm install` resolves — i.e., a newer version of the requiring dep exists
29822
- * whose peer range accepts the installed peer. If the best peer-compatible
29823
- * version is older than (or equal to) what the current range already resolves
29824
- * to, we emit nothing: "downgrade to fix a peer warning" is a user decision,
29825
- * not an automatic one.
29826
- */
29827
- function pickUpgradeTarget(manifest, peer, installedPeerVersion, currentRange) {
29828
- const valid = manifest.versions.filter((v) => import_semver.default.valid(v.version) !== null);
29829
- const currentBest = pickHighest(valid.filter((v) => import_semver.default.satisfies(v.version, currentRange, { includePrerelease: true })).filter((v) => canAcceptPeer(v, peer, installedPeerVersion)).map((v) => v.version));
29830
- const absoluteBest = pickHighest(valid.filter((v) => canAcceptPeer(v, peer, installedPeerVersion)).map((v) => v.version));
29831
- if (absoluteBest == null || absoluteBest.length === 0) return void 0;
29832
- if (currentBest != null && currentBest.length > 0 && import_semver.default.gte(currentBest, absoluteBest)) return void 0;
29833
- let currentMin;
29834
- try {
29835
- currentMin = import_semver.default.minVersion(currentRange)?.version;
29836
- } catch {}
29837
- if (currentMin != null && currentMin.length > 0 && import_semver.default.lt(absoluteBest, currentMin)) return void 0;
29838
- return absoluteBest;
29839
- }
29840
- function buildBumpedRange(resolvedVersion, section) {
29841
- return section === "peerDependencies" ? `^${resolvedVersion}` : `~${resolvedVersion}`;
29842
- }
29843
- function resolveOneFix(fix, manifest, resolutionCache, loggedKeys) {
29844
- const cacheKey = keyOf(fix);
29845
- const isFirstSeen = !resolutionCache.has(cacheKey);
29846
- let resolvedVersion;
29847
- if (isFirstSeen) {
29848
- resolvedVersion = manifest ? pickUpgradeTarget(manifest, fix.peer, fix.installedPeerVersion, fix.currentRange) : void 0;
29849
- resolutionCache.set(cacheKey, resolvedVersion);
29850
- } else resolvedVersion = resolutionCache.get(cacheKey);
29851
- if (resolvedVersion == null || resolvedVersion.length === 0) {
29852
- if (!loggedKeys.has(cacheKey)) {
29853
- loggedKeys.add(cacheKey);
29854
- console.log(` ${chalk.dim(`No newer version of ${fix.dependency} accepts peer ${fix.peer}@${fix.installedPeerVersion} beyond current range ${fix.currentRange} — skipping bump (fix peer manually)`)}`);
29813
+ },
29814
+ dependency: finding.dep,
29815
+ message: `Workspace dependency ${finding.dep} in ${finding.section} should use ${configuredProtocol} — found ${finding.version}`
29816
+ });
29855
29817
  }
29856
- return;
29818
+ },
29819
+ resolveFixes(diagnostic) {
29820
+ const data = diagnostic.data;
29821
+ return data ? [{
29822
+ action: "set-version",
29823
+ dependency: data.dep,
29824
+ detail: `set ${data.expectedVersion ?? "workspace:~"} for ${data.section}`,
29825
+ section: data.section,
29826
+ version: data.expectedVersion ?? "workspace:~"
29827
+ }] : [];
29857
29828
  }
29858
- const bumped = buildBumpedRange(resolvedVersion, fix.section);
29859
- if (bumped === fix.currentRange) return void 0;
29860
- return {
29861
- action: "set-version",
29862
- dependency: fix.dependency,
29863
- detail: `bumped ${fix.section} range to ${bumped} so ${fix.dependency}@${resolvedVersion} is installed (accepts peer ${fix.peer}@${fix.installedPeerVersion})`,
29864
- section: fix.section,
29865
- version: bumped
29866
- };
29829
+ };
29830
+ function shouldSkipExternalRangeStyle(context, dep, current) {
29831
+ return current === void 0 || isOpaqueVersionSpec(current) || (context.workspaceNames?.has(dep) ?? false);
29867
29832
  }
29868
- /**
29869
- * Caches survive across multiple calls in one `deplint` invocation so the
29870
- * fix-loop's re-passes don't re-log "skipping bump" for the same unresolved
29871
- * lookups each time. Cleared between CLI runs via `clearPeerBumpCache` (only
29872
- * wired up in tests; a fresh process starts empty).
29873
- */
29874
- const resolutionCache = /* @__PURE__ */ new Map();
29875
- const loggedKeys = /* @__PURE__ */ new Set();
29876
- function replacePeerBumpFixes(fixes, manifests, resolutionCache, loggedKeys) {
29877
- const replacement = [];
29878
- for (const fix of fixes) {
29879
- if (fix.action !== "resolve-peer-bump") {
29880
- replacement.push(fix);
29881
- continue;
29882
- }
29883
- const resolved = resolveOneFix(fix, manifests.get(fix.dependency), resolutionCache, loggedKeys);
29884
- if (resolved) replacement.push(resolved);
29885
- }
29886
- return replacement;
29833
+ function shouldSkipPeerRangeStyle(context, dep, current) {
29834
+ return (context.exclude?.has(dep) ?? false) || current === void 0 || isOpaqueVersionSpec(current) || (context.workspaceNames?.has(dep) ?? false);
29887
29835
  }
29888
- /**
29889
- * Mutates `diagnostics` in place: every `resolve-peer-bump` fix is replaced
29890
- * with either a concrete `set-version` fix or removed entirely if no
29891
- * published version of the requiring dep accepts the installed peer.
29892
- */
29893
- async function resolvePeerBumpFixes(diagnostics) {
29894
- const { fixes, packageNames } = collectPeerBumpFixes(diagnostics);
29895
- if (fixes.length === 0) return;
29896
- const manifests = await fetchPackageManifests(packageNames);
29897
- for (const diagnostic of diagnostics) {
29898
- if (!diagnostic.fixes) continue;
29899
- diagnostic.fixes = replacePeerBumpFixes(diagnostic.fixes, manifests, resolutionCache, loggedKeys);
29836
+ function expectedPeerRangeStyle(context, dep, devRange, peerRange, form, boundType) {
29837
+ return form === "broad" ? resolveExpectedPeerVersion(context.workspace.location, dep, devRange, boundType) : resolveExpectedPeerShorthandVersion(context.workspace.location, dep, devRange, peerRange);
29838
+ }
29839
+ const builtInDeplintPlugin = {
29840
+ name: "builtin",
29841
+ rules: [
29842
+ unlistedDependenciesRule,
29843
+ unusedDependenciesRule,
29844
+ misplacedDependenciesRule,
29845
+ {
29846
+ category: "dependencies",
29847
+ id: "dep.dependencies.aei-review",
29848
+ meta: {
29849
+ description: "Dependencies whose API Exposure Index score is borderline — placement needs manual review",
29850
+ fixable: [],
29851
+ severity: "warning"
29852
+ },
29853
+ evaluate(context) {
29854
+ if (context.classifierMode !== "aei" || context.isTerminalPackage) return;
29855
+ const candidates = /* @__PURE__ */ new Set([...context.packageParams.dependencies, ...context.packageParams.peerDependencies]);
29856
+ for (const dep of candidates) {
29857
+ if (context.forceDeps.has(dep) || context.forceDevs.has(dep) || context.forcePeers.has(dep)) continue;
29858
+ if (context.packageParams.dependencyVersions[dep]?.startsWith("workspace:")) continue;
29859
+ if (context.workspaceNames?.has(dep) ?? false) continue;
29860
+ if (dep.startsWith("@types/")) continue;
29861
+ if (context.classifyDependency(dep) !== "review") continue;
29862
+ context.report({
29863
+ dependency: dep,
29864
+ message: `AEI score for ${dep} is borderline — review whether it belongs in dependencies or peerDependencies (run \`xy api-exposure --dep ${dep}\` for the evidence)`
29865
+ });
29866
+ }
29867
+ }
29868
+ },
29869
+ dependencyRangeStyleRule,
29870
+ unlistedDevDependenciesRule,
29871
+ unusedDevDependenciesRule,
29872
+ redundantDevDependenciesRule,
29873
+ devDependencyRangeStyleRule,
29874
+ unsatisfiedPeersRule,
29875
+ unusedPeerDependenciesRule,
29876
+ unrequestedPeerDependenciesRule,
29877
+ misplacedPeerDependenciesRule,
29878
+ redundantPeerDependenciesRule,
29879
+ mismatchedPeerDevVersionsRule,
29880
+ peerDependencyRangeStyleRule,
29881
+ workspaceVersionProblemsRule
29882
+ ]
29883
+ };
29884
+ //#endregion
29885
+ //#region src/actions/deplint/loader.ts
29886
+ function resolvePluginSpecifier(specifier) {
29887
+ if (specifier.startsWith(".") || PATH.isAbsolute(specifier)) return pathToFileURL(PATH.resolve(specifier)).href;
29888
+ return specifier;
29889
+ }
29890
+ function isPlugin(value) {
29891
+ return typeof value === "object" && value !== null && "name" in value && "rules" in value && Array.isArray(value.rules);
29892
+ }
29893
+ async function loadDeplintRules(config) {
29894
+ const plugins = [builtInDeplintPlugin];
29895
+ const pluginSpecifiers = config?.plugins ?? [];
29896
+ for (const specifier of pluginSpecifiers) {
29897
+ const pluginModule = await import(resolvePluginSpecifier(specifier));
29898
+ const plugin = pluginModule.default ?? pluginModule.plugin;
29899
+ if (!isPlugin(plugin)) throw new TypeError(`Invalid deplint plugin "${specifier}" - expected a plugin with a name and rules array`);
29900
+ plugins.push(plugin);
29900
29901
  }
29902
+ return normalizeDeplintRules(plugins.flatMap((plugin) => plugin.rules), config, new Set(builtInDeplintPlugin.rules.map((rule) => rule.id)));
29901
29903
  }
29902
29904
  //#endregion
29903
29905
  //#region src/actions/deplint/snapshot.ts
@@ -29954,8 +29956,11 @@ function buildDependencyClassifier(workspace, options, isTerminal, peerDependenc
29954
29956
  };
29955
29957
  }
29956
29958
  function buildWorkspaceContext(workspace, options = {}) {
29957
- const { sourceExclude, terminalOverride } = options;
29959
+ const { sourceExclude, terminalOverride, phases } = options;
29960
+ const findFilesStarted = performance.now();
29958
29961
  const { allFiles, distFiles, runtimeRoots } = findFiles(workspace.location, sourceExclude);
29962
+ if (phases !== void 0) phases.findFilesMs = performance.now() - findFilesStarted;
29963
+ const importsStarted = performance.now();
29959
29964
  const tsconfigExtends = getExtendsFromTsconfigs(workspace.location);
29960
29965
  const tsconfigPaths = getPathsFromTsconfigs(workspace.location);
29961
29966
  const tsconfigTypes = getTypesFromTsconfigs(workspace.location);
@@ -29969,11 +29974,14 @@ function buildWorkspaceContext(workspace, options = {}) {
29969
29974
  tsconfigPaths,
29970
29975
  tsconfigTypes
29971
29976
  });
29977
+ if (phases !== void 0) phases.importsMs = performance.now() - importsStarted;
29978
+ const packageMetaStarted = performance.now();
29972
29979
  const packageJsonPath = `${workspace.location}/package.json`;
29973
29980
  const packageParams = getDependenciesFromPackageJson(packageJsonPath);
29974
29981
  const requiredTransitivePeers = getRequiredNonOptionalTransitivePeers(workspace.location, packageParams);
29975
29982
  const runtimeRootedRequired = getRuntimeRootedNonOptionalTransitivePeers(workspace.location, packageParams);
29976
29983
  const packageClassification = classifyDeplintPackage(workspace.location, terminalOverride);
29984
+ if (phases !== void 0) phases.packageMetaMs = performance.now() - packageMetaStarted;
29977
29985
  return {
29978
29986
  classifierMode: options.classifier ?? "legacy",
29979
29987
  classifyDependency: buildDependencyClassifier(workspace, options, packageClassification.isTerminalPackage, packageParams.peerDependencies, sourceParams.externalDistImports),
@@ -30003,7 +30011,7 @@ function buildWorkspaceContext(workspace, options = {}) {
30003
30011
  }
30004
30012
  //#endregion
30005
30013
  //#region src/actions/deplint/engine.ts
30006
- const MAX_FIX_PASSES = 5;
30014
+ const PROFILE_SLOW_RULE_LIMIT = 5;
30007
30015
  function resolveDeplintCheckFlags({ deps = false, devDeps = false, peerDeps = false } = {}) {
30008
30016
  const isNoneExplicit = !(deps || devDeps || peerDeps);
30009
30017
  const isCheckDependencies = deps || isNoneExplicit;
@@ -30060,6 +30068,7 @@ function normalizeConfigList(values) {
30060
30068
  return values.filter((value) => typeof value === "string").map((value) => value.trim()).filter(Boolean);
30061
30069
  }
30062
30070
  async function loadWorkspaceEvaluationContext(workspace, options, workspaceNames) {
30071
+ const configStarted = performance.now();
30063
30072
  const wsConfig = await loadWorkspaceCommandConfig(workspace.location, "deplint");
30064
30073
  const rules = await loadDeplintRules(wsConfig);
30065
30074
  const classifier = options.classifier ?? wsConfig.classifier ?? "legacy";
@@ -30075,7 +30084,15 @@ async function loadWorkspaceEvaluationContext(workspace, options, workspaceNames
30075
30084
  for (const [name, cfg] of packageEntries) if (typeof cfg.peerOptional === "boolean") forcePeerOptional.set(name, cfg.peerOptional);
30076
30085
  const rangeStyleOptions = rules.find((rule) => rule.id === "dep.peerDependencies.range-style")?.options ?? {};
30077
30086
  const peerRangeForm = resolvePeerRangeFormOption(rangeStyleOptions);
30087
+ const peerRangeBound = resolvePeerRangeBoundOption(rangeStyleOptions);
30088
+ const configMs = performance.now() - configStarted;
30089
+ const contextPhases = {
30090
+ findFilesMs: 0,
30091
+ importsMs: 0,
30092
+ packageMetaMs: 0
30093
+ };
30078
30094
  return {
30095
+ configMs,
30079
30096
  context: buildWorkspaceContext(workspace, {
30080
30097
  apiExposureConfig,
30081
30098
  classifier,
@@ -30083,15 +30100,429 @@ async function loadWorkspaceEvaluationContext(workspace, options, workspaceNames
30083
30100
  forceDevs,
30084
30101
  forcePeerOptional,
30085
30102
  forcePeers,
30086
- peerRangeBound: resolvePeerRangeBoundOption(rangeStyleOptions),
30103
+ peerRangeBound,
30087
30104
  peerRangeForm,
30105
+ phases: options.profile === true ? contextPhases : void 0,
30088
30106
  sourceExclude,
30089
30107
  terminalOverride: wsConfig.terminal,
30090
30108
  workspaceNames
30091
30109
  }),
30110
+ contextPhases,
30092
30111
  rules
30093
30112
  };
30094
30113
  }
30114
+ async function evaluateWorkspace(workspace, workspaceIndex, workspaceTotal, options, workspaceNames, pass, emitProgress) {
30115
+ const workspaceStarted = performance.now();
30116
+ const diagnostics = [];
30117
+ const progressEvents = [];
30118
+ const progress = (event) => {
30119
+ progressEvents.push(event);
30120
+ emitProgress(event);
30121
+ };
30122
+ let rulesEvaluated = 0;
30123
+ let rulesSkipped = 0;
30124
+ const ruleTimings = [];
30125
+ const { configMs, context, contextPhases, rules } = await loadWorkspaceEvaluationContext(workspace, options, workspaceNames);
30126
+ const workspaceDiagnosticStart = diagnostics.length;
30127
+ progress({
30128
+ context: buildWorkspaceProgressContext(context),
30129
+ pass,
30130
+ type: "workspace-start",
30131
+ workspace,
30132
+ workspaceIndex: workspaceIndex + 1,
30133
+ workspaceTotal
30134
+ });
30135
+ for (const [ruleIndex, rule] of rules.entries()) {
30136
+ const ruleProgress = buildRuleProgress(rule);
30137
+ if (rule.enabled === false) {
30138
+ rulesSkipped += 1;
30139
+ progress({
30140
+ pass,
30141
+ reason: "rule disabled",
30142
+ rule: ruleProgress,
30143
+ ruleIndex: ruleIndex + 1,
30144
+ ruleTotal: rules.length,
30145
+ type: "rule-skip",
30146
+ workspace
30147
+ });
30148
+ } else if (shouldRunDeplintRule(rule.category, rule.id, options)) {
30149
+ rulesEvaluated += 1;
30150
+ progress({
30151
+ pass,
30152
+ rule: ruleProgress,
30153
+ ruleIndex: ruleIndex + 1,
30154
+ ruleTotal: rules.length,
30155
+ type: "rule-start",
30156
+ workspace
30157
+ });
30158
+ const startedAt = performance.now();
30159
+ const diagnosticStart = diagnostics.length;
30160
+ await rule.evaluate({
30161
+ ...context,
30162
+ options: rule.options ?? {},
30163
+ report: ({ data, dependency, evidence, file, message }) => {
30164
+ if (isDependencyIgnoredByRule(dependency, rule.options)) return;
30165
+ diagnostics.push({
30166
+ data,
30167
+ dependency,
30168
+ evidence,
30169
+ file: file ?? context.packageJsonPath,
30170
+ fixable: isRuleFixable(rule),
30171
+ id: rule.id,
30172
+ message,
30173
+ severity: rule.meta.severity,
30174
+ workspace: context.workspace
30175
+ });
30176
+ }
30177
+ });
30178
+ const elapsedMs = performance.now() - startedAt;
30179
+ if (options.profile === true) ruleTimings.push({
30180
+ elapsedMs,
30181
+ id: rule.id
30182
+ });
30183
+ progress({
30184
+ diagnostics: diagnostics.length - diagnosticStart,
30185
+ elapsedMs: Math.round(elapsedMs),
30186
+ pass,
30187
+ rule: ruleProgress,
30188
+ ruleIndex: ruleIndex + 1,
30189
+ ruleTotal: rules.length,
30190
+ type: "rule-end",
30191
+ workspace
30192
+ });
30193
+ } else {
30194
+ rulesSkipped += 1;
30195
+ progress({
30196
+ pass,
30197
+ reason: "section filter",
30198
+ rule: ruleProgress,
30199
+ ruleIndex: ruleIndex + 1,
30200
+ ruleTotal: rules.length,
30201
+ type: "rule-skip",
30202
+ workspace
30203
+ });
30204
+ }
30205
+ }
30206
+ progress({
30207
+ diagnostics: diagnostics.length - workspaceDiagnosticStart,
30208
+ pass,
30209
+ type: "workspace-end",
30210
+ workspace
30211
+ });
30212
+ const rulesMs = ruleTimings.reduce((sum, rule) => sum + rule.elapsedMs, 0);
30213
+ return {
30214
+ context,
30215
+ diagnostics,
30216
+ profile: options.profile === true ? {
30217
+ allFiles: context.fileContext.allFiles.length,
30218
+ configMs,
30219
+ distFiles: context.fileContext.distFiles.length,
30220
+ findFilesMs: contextPhases.findFilesMs,
30221
+ importsMs: contextPhases.importsMs,
30222
+ packageMetaMs: contextPhases.packageMetaMs,
30223
+ rulesMs,
30224
+ slowRules: ruleTimings.toSorted((a, b) => b.elapsedMs - a.elapsedMs).slice(0, PROFILE_SLOW_RULE_LIMIT).filter((rule) => rule.elapsedMs >= 1),
30225
+ totalMs: performance.now() - workspaceStarted,
30226
+ workspace: workspace.name,
30227
+ workspaceLocation: workspace.location
30228
+ } : void 0,
30229
+ progressEvents,
30230
+ rules,
30231
+ rulesEvaluated,
30232
+ rulesSkipped
30233
+ };
30234
+ }
30235
+ async function evaluateWorkspaces(workspaces, options, workspaceNames, pass = 1, progress) {
30236
+ const diagnostics = [];
30237
+ const contextsByWorkspace = /* @__PURE__ */ new Map();
30238
+ const rulesById = /* @__PURE__ */ new Map();
30239
+ const profiles = [];
30240
+ const results = Array.from({ length: workspaces.length }, () => ({
30241
+ context: void 0,
30242
+ diagnostics: [],
30243
+ progressEvents: [],
30244
+ rules: [],
30245
+ rulesEvaluated: 0,
30246
+ rulesSkipped: 0
30247
+ }));
30248
+ let rulesEvaluated = 0;
30249
+ let rulesSkipped = 0;
30250
+ const concurrency = Math.max(1, options.jobs ?? 1);
30251
+ const isEmitProgressImmediately = concurrency === 1;
30252
+ const noopProgress = (_event) => void 0;
30253
+ await runWithConcurrency(workspaces.map((workspace, workspaceIndex) => ({
30254
+ workspace,
30255
+ workspaceIndex
30256
+ })), concurrency, async ({ workspace, workspaceIndex }) => {
30257
+ results[workspaceIndex] = await evaluateWorkspace(workspace, workspaceIndex, workspaces.length, options, workspaceNames, pass, isEmitProgressImmediately ? progress ?? noopProgress : noopProgress);
30258
+ });
30259
+ for (const result of results) {
30260
+ if (!isEmitProgressImmediately) for (const event of result.progressEvents) progress?.(event);
30261
+ const { context, rules } = result;
30262
+ contextsByWorkspace.set(context.workspace.location, context);
30263
+ diagnostics.push(...result.diagnostics);
30264
+ rulesEvaluated += result.rulesEvaluated;
30265
+ rulesSkipped += result.rulesSkipped;
30266
+ if (result.profile !== void 0) profiles.push(result.profile);
30267
+ for (const rule of rules) rulesById.set(rule.id, rule);
30268
+ }
30269
+ return {
30270
+ contextsByWorkspace,
30271
+ diagnostics,
30272
+ profiles,
30273
+ rulesById,
30274
+ rulesEvaluated,
30275
+ rulesSkipped
30276
+ };
30277
+ }
30278
+ //#endregion
30279
+ //#region src/actions/deplint/packageEditor.ts
30280
+ var DeplintPackageEditor = class {
30281
+ dirty = false;
30282
+ pkg;
30283
+ workspace;
30284
+ constructor(workspace) {
30285
+ this.workspace = workspace;
30286
+ this.pkg = readPackageJson$4(workspace.location);
30287
+ }
30288
+ applyFix(fix) {
30289
+ const before = JSON.stringify(this.pkg);
30290
+ switch (fix.action) {
30291
+ case "add":
30292
+ addDep(this.pkg, fix.dependency, fix.version, fix.section);
30293
+ if (fix.section === "peerDependencies") setPeerOptional(this.pkg, fix.dependency, fix.optional);
30294
+ break;
30295
+ case "move":
30296
+ moveDep(this.pkg, fix.dependency, fix.fromSection, fix.toSection);
30297
+ if (fix.version !== void 0 && this.pkg[fix.toSection]?.[fix.dependency] !== void 0) this.pkg[fix.toSection][fix.dependency] = fix.version;
30298
+ if (fix.toSection === "peerDependencies") setPeerOptional(this.pkg, fix.dependency, fix.optional);
30299
+ break;
30300
+ case "remove":
30301
+ removeDep(this.pkg, fix.dependency, fix.section);
30302
+ break;
30303
+ case "set-version":
30304
+ if (this.pkg[fix.section]?.[fix.dependency] !== void 0) addDep(this.pkg, fix.dependency, fix.version, fix.section);
30305
+ break;
30306
+ case "resolve-peer-bump": break;
30307
+ }
30308
+ if (JSON.stringify(this.pkg) === before) return void 0;
30309
+ this.dirty = true;
30310
+ return {
30311
+ dependency: fix.dependency,
30312
+ detail: fix.detail,
30313
+ workspace: this.workspace
30314
+ };
30315
+ }
30316
+ save() {
30317
+ if (!this.dirty) return;
30318
+ writePackageJson$2(this.workspace.location, this.pkg);
30319
+ }
30320
+ };
30321
+ //#endregion
30322
+ //#region src/actions/deplint/fixer.ts
30323
+ function applyDeplintFixes(diagnostics) {
30324
+ const editors = /* @__PURE__ */ new Map();
30325
+ const applied = [];
30326
+ for (const diagnostic of diagnostics) {
30327
+ const fixes = diagnostic.fixes ?? [];
30328
+ for (const fix of fixes) {
30329
+ const workspaceKey = diagnostic.workspace.location;
30330
+ let editor = editors.get(workspaceKey);
30331
+ if (!editor) {
30332
+ editor = new DeplintPackageEditor(diagnostic.workspace);
30333
+ editors.set(workspaceKey, editor);
30334
+ }
30335
+ const appliedFix = editor.applyFix(fix);
30336
+ if (appliedFix) applied.push(appliedFix);
30337
+ }
30338
+ }
30339
+ for (const editor of editors.values()) editor.save();
30340
+ return applied;
30341
+ }
30342
+ //#endregion
30343
+ //#region src/actions/deplint/fetchPackageManifest.ts
30344
+ /**
30345
+ * Fetches npm registry manifests for deplint's peer-dependency resolution.
30346
+ *
30347
+ * Unlike `lib/updo/fetchRegistryInfo`, which returns only version strings
30348
+ * and dist-tags, this helper preserves each version's `peerDependencies`
30349
+ * block. That's what we need to answer the question: "what's the latest
30350
+ * version of package X whose peer range accepts peer Y at version Z?"
30351
+ *
30352
+ * Results are cached per-process so repeated lookups within a single
30353
+ * deplint run hit the registry at most once per package.
30354
+ */
30355
+ const REGISTRY_BASE = "https://registry.npmjs.org";
30356
+ const cache = /* @__PURE__ */ new Map();
30357
+ async function fetchUncached(packageName) {
30358
+ try {
30359
+ const url = `${REGISTRY_BASE}/${encodeURIComponent(packageName)}`;
30360
+ const res = await fetch(url, { headers: { Accept: "application/vnd.npm.install-v1+json" } });
30361
+ if (!res.ok) return void 0;
30362
+ const data = await res.json();
30363
+ const versionsMap = data.versions ?? {};
30364
+ const versions = Object.entries(versionsMap).map(([version, manifest]) => ({
30365
+ peerDependencies: manifest.peerDependencies ?? {},
30366
+ version
30367
+ }));
30368
+ return {
30369
+ distTags: data["dist-tags"] ?? {},
30370
+ versions
30371
+ };
30372
+ } catch {
30373
+ return;
30374
+ }
30375
+ }
30376
+ function fetchPackageManifest(packageName) {
30377
+ const existing = cache.get(packageName);
30378
+ if (existing) return existing;
30379
+ const pending = fetchUncached(packageName);
30380
+ cache.set(packageName, pending);
30381
+ return pending;
30382
+ }
30383
+ async function fetchPackageManifests(packageNames, concurrency = 16) {
30384
+ const unique = [...new Set(packageNames)];
30385
+ const results = /* @__PURE__ */ new Map();
30386
+ await runWithConcurrency(unique, concurrency, async (name) => {
30387
+ results.set(name, await fetchPackageManifest(name));
30388
+ });
30389
+ return results;
30390
+ }
30391
+ //#endregion
30392
+ //#region src/actions/deplint/resolvePeerBumpFixes.ts
30393
+ /**
30394
+ * Resolves `resolve-peer-bump` fixes by consulting the npm registry.
30395
+ *
30396
+ * A `resolve-peer-bump` fix says "the installed peer X@v doesn't satisfy the
30397
+ * range that the currently installed version of the requiring dep D declares —
30398
+ * bump our declared range for D." To pick a concrete target range, we fetch
30399
+ * D's registry manifest and find the highest published version whose
30400
+ * `peerDependencies[X]` range accepts v. We then express our new declared
30401
+ * range using D's actual version numbers (not the peer's — that was the old
30402
+ * bug).
30403
+ *
30404
+ * If no published version of D accepts the installed peer, the fix is dropped
30405
+ * and the mismatch remains visible in the next deplint pass as a warning.
30406
+ */
30407
+ function keyOf(k) {
30408
+ return `${k.dependency}|${k.peer}|${k.installedPeerVersion}|${k.currentRange}`;
30409
+ }
30410
+ function collectPeerBumpFixes(diagnostics) {
30411
+ const fixes = [];
30412
+ const packageNames = /* @__PURE__ */ new Set();
30413
+ for (const diagnostic of diagnostics) {
30414
+ const peerBumpFixes = (diagnostic.fixes ?? []).filter((candidate) => candidate.action === "resolve-peer-bump");
30415
+ for (const fix of peerBumpFixes) {
30416
+ fixes.push(fix);
30417
+ packageNames.add(fix.dependency);
30418
+ }
30419
+ }
30420
+ return {
30421
+ fixes,
30422
+ packageNames: [...packageNames]
30423
+ };
30424
+ }
30425
+ function canAcceptPeer(version, peer, installedPeerVersion) {
30426
+ const range = version.peerDependencies[peer];
30427
+ if (!range || range === "*") return true;
30428
+ if (range.startsWith("workspace:")) return true;
30429
+ try {
30430
+ return import_semver.default.satisfies(installedPeerVersion, range, { includePrerelease: true });
30431
+ } catch {
30432
+ return false;
30433
+ }
30434
+ }
30435
+ function pickHighest(versions) {
30436
+ if (versions.length === 0) return void 0;
30437
+ const stable = versions.filter((v) => import_semver.default.prerelease(v) === null);
30438
+ return (stable.length > 0 ? stable : versions).toSorted(import_semver.default.rcompare)[0];
30439
+ }
30440
+ /**
30441
+ * Returns a version to bump to ONLY if doing so would meaningfully change what
30442
+ * `pnpm install` resolves — i.e., a newer version of the requiring dep exists
30443
+ * whose peer range accepts the installed peer. If the best peer-compatible
30444
+ * version is older than (or equal to) what the current range already resolves
30445
+ * to, we emit nothing: "downgrade to fix a peer warning" is a user decision,
30446
+ * not an automatic one.
30447
+ */
30448
+ function pickUpgradeTarget(manifest, peer, installedPeerVersion, currentRange) {
30449
+ const valid = manifest.versions.filter((v) => import_semver.default.valid(v.version) !== null);
30450
+ const currentBest = pickHighest(valid.filter((v) => import_semver.default.satisfies(v.version, currentRange, { includePrerelease: true })).filter((v) => canAcceptPeer(v, peer, installedPeerVersion)).map((v) => v.version));
30451
+ const absoluteBest = pickHighest(valid.filter((v) => canAcceptPeer(v, peer, installedPeerVersion)).map((v) => v.version));
30452
+ if (absoluteBest == null || absoluteBest.length === 0) return void 0;
30453
+ if (currentBest != null && currentBest.length > 0 && import_semver.default.gte(currentBest, absoluteBest)) return void 0;
30454
+ let currentMin;
30455
+ try {
30456
+ currentMin = import_semver.default.minVersion(currentRange)?.version;
30457
+ } catch {}
30458
+ if (currentMin != null && currentMin.length > 0 && import_semver.default.lt(absoluteBest, currentMin)) return void 0;
30459
+ return absoluteBest;
30460
+ }
30461
+ function buildBumpedRange(resolvedVersion, section) {
30462
+ return section === "peerDependencies" ? `^${resolvedVersion}` : `~${resolvedVersion}`;
30463
+ }
30464
+ function resolveOneFix(fix, manifest, resolutionCache, loggedKeys) {
30465
+ const cacheKey = keyOf(fix);
30466
+ const isFirstSeen = !resolutionCache.has(cacheKey);
30467
+ let resolvedVersion;
30468
+ if (isFirstSeen) {
30469
+ resolvedVersion = manifest ? pickUpgradeTarget(manifest, fix.peer, fix.installedPeerVersion, fix.currentRange) : void 0;
30470
+ resolutionCache.set(cacheKey, resolvedVersion);
30471
+ } else resolvedVersion = resolutionCache.get(cacheKey);
30472
+ if (resolvedVersion == null || resolvedVersion.length === 0) {
30473
+ if (!loggedKeys.has(cacheKey)) {
30474
+ loggedKeys.add(cacheKey);
30475
+ console.log(` ${chalk.dim(`No newer version of ${fix.dependency} accepts peer ${fix.peer}@${fix.installedPeerVersion} beyond current range ${fix.currentRange} — skipping bump (fix peer manually)`)}`);
30476
+ }
30477
+ return;
30478
+ }
30479
+ const bumped = buildBumpedRange(resolvedVersion, fix.section);
30480
+ if (bumped === fix.currentRange) return void 0;
30481
+ return {
30482
+ action: "set-version",
30483
+ dependency: fix.dependency,
30484
+ detail: `bumped ${fix.section} range to ${bumped} so ${fix.dependency}@${resolvedVersion} is installed (accepts peer ${fix.peer}@${fix.installedPeerVersion})`,
30485
+ section: fix.section,
30486
+ version: bumped
30487
+ };
30488
+ }
30489
+ /**
30490
+ * Caches survive across multiple calls in one `deplint` invocation so the
30491
+ * fix-loop's re-passes don't re-log "skipping bump" for the same unresolved
30492
+ * lookups each time. Cleared between CLI runs via `clearPeerBumpCache` (only
30493
+ * wired up in tests; a fresh process starts empty).
30494
+ */
30495
+ const resolutionCache = /* @__PURE__ */ new Map();
30496
+ const loggedKeys = /* @__PURE__ */ new Set();
30497
+ function replacePeerBumpFixes(fixes, manifests, resolutionCache, loggedKeys) {
30498
+ const replacement = [];
30499
+ for (const fix of fixes) {
30500
+ if (fix.action !== "resolve-peer-bump") {
30501
+ replacement.push(fix);
30502
+ continue;
30503
+ }
30504
+ const resolved = resolveOneFix(fix, manifests.get(fix.dependency), resolutionCache, loggedKeys);
30505
+ if (resolved) replacement.push(resolved);
30506
+ }
30507
+ return replacement;
30508
+ }
30509
+ /**
30510
+ * Mutates `diagnostics` in place: every `resolve-peer-bump` fix is replaced
30511
+ * with either a concrete `set-version` fix or removed entirely if no
30512
+ * published version of the requiring dep accepts the installed peer.
30513
+ */
30514
+ async function resolvePeerBumpFixes(diagnostics) {
30515
+ const { fixes, packageNames } = collectPeerBumpFixes(diagnostics);
30516
+ if (fixes.length === 0) return;
30517
+ const manifests = await fetchPackageManifests(packageNames);
30518
+ for (const diagnostic of diagnostics) {
30519
+ if (!diagnostic.fixes) continue;
30520
+ diagnostic.fixes = replacePeerBumpFixes(diagnostic.fixes, manifests, resolutionCache, loggedKeys);
30521
+ }
30522
+ }
30523
+ //#endregion
30524
+ //#region src/actions/deplint/runDeplint.ts
30525
+ const MAX_FIX_PASSES = 5;
30095
30526
  async function resolveDiagnosticFixes(diagnostics, rulesById, contextsByWorkspace) {
30096
30527
  const resolvedDiagnostics = await Promise.all(diagnostics.map(async (diagnostic) => {
30097
30528
  const rule = rulesById.get(diagnostic.id);
@@ -30122,151 +30553,37 @@ async function resolveDiagnosticFixes(diagnostics, rulesById, contextsByWorkspac
30122
30553
  fixable: (diagnostic.fixes?.length ?? 0) > 0
30123
30554
  }));
30124
30555
  }
30125
- async function evaluateWorkspace(workspace, workspaceIndex, workspaceTotal, options, workspaceNames, pass, emitProgress) {
30126
- const diagnostics = [];
30127
- const progressEvents = [];
30128
- const progress = (event) => {
30129
- progressEvents.push(event);
30130
- emitProgress(event);
30131
- };
30132
- let rulesEvaluated = 0;
30133
- let rulesSkipped = 0;
30134
- const { context, rules } = await loadWorkspaceEvaluationContext(workspace, options, workspaceNames);
30135
- const workspaceDiagnosticStart = diagnostics.length;
30136
- progress({
30137
- context: buildWorkspaceProgressContext(context),
30138
- pass,
30139
- type: "workspace-start",
30140
- workspace,
30141
- workspaceIndex: workspaceIndex + 1,
30142
- workspaceTotal
30143
- });
30144
- for (const [ruleIndex, rule] of rules.entries()) {
30145
- const ruleProgress = buildRuleProgress(rule);
30146
- if (rule.enabled === false) {
30147
- rulesSkipped += 1;
30148
- progress({
30149
- pass,
30150
- reason: "rule disabled",
30151
- rule: ruleProgress,
30152
- ruleIndex: ruleIndex + 1,
30153
- ruleTotal: rules.length,
30154
- type: "rule-skip",
30155
- workspace
30156
- });
30157
- } else if (shouldRunDeplintRule(rule.category, rule.id, options)) {
30158
- rulesEvaluated += 1;
30159
- progress({
30160
- pass,
30161
- rule: ruleProgress,
30162
- ruleIndex: ruleIndex + 1,
30163
- ruleTotal: rules.length,
30164
- type: "rule-start",
30165
- workspace
30166
- });
30167
- const startedAt = Date.now();
30168
- const diagnosticStart = diagnostics.length;
30169
- await rule.evaluate({
30170
- ...context,
30171
- options: rule.options ?? {},
30172
- report: ({ data, dependency, evidence, file, message }) => {
30173
- if (isDependencyIgnoredByRule(dependency, rule.options)) return;
30174
- diagnostics.push({
30175
- data,
30176
- dependency,
30177
- evidence,
30178
- file: file ?? context.packageJsonPath,
30179
- fixable: isRuleFixable(rule),
30180
- id: rule.id,
30181
- message,
30182
- severity: rule.meta.severity,
30183
- workspace: context.workspace
30184
- });
30185
- }
30186
- });
30187
- progress({
30188
- diagnostics: diagnostics.length - diagnosticStart,
30189
- elapsedMs: Date.now() - startedAt,
30190
- pass,
30191
- rule: ruleProgress,
30192
- ruleIndex: ruleIndex + 1,
30193
- ruleTotal: rules.length,
30194
- type: "rule-end",
30195
- workspace
30196
- });
30197
- } else {
30198
- rulesSkipped += 1;
30199
- progress({
30200
- pass,
30201
- reason: "section filter",
30202
- rule: ruleProgress,
30203
- ruleIndex: ruleIndex + 1,
30204
- ruleTotal: rules.length,
30205
- type: "rule-skip",
30206
- workspace
30207
- });
30208
- }
30209
- }
30210
- progress({
30211
- diagnostics: diagnostics.length - workspaceDiagnosticStart,
30212
- pass,
30213
- type: "workspace-end",
30214
- workspace
30215
- });
30556
+ function buildSummary({ appliedFixes, diagnostics, fixPassesRun, passesRun, rulesEvaluated, rulesSkipped, workspacesChecked }) {
30557
+ const diagnosticsByRule = {};
30558
+ for (const diagnostic of diagnostics) diagnosticsByRule[diagnostic.id] = (diagnosticsByRule[diagnostic.id] ?? 0) + 1;
30216
30559
  return {
30217
- context,
30218
- diagnostics,
30219
- progressEvents,
30220
- rules,
30560
+ appliedFixes: appliedFixes.length,
30561
+ diagnosticsByRule,
30562
+ errorCount: diagnostics.filter((diagnostic) => diagnostic.severity === "error").length,
30563
+ fixableErrorCount: diagnostics.filter((diagnostic) => diagnostic.severity === "error" && diagnostic.fixable).length,
30564
+ fixableWarningCount: diagnostics.filter((diagnostic) => diagnostic.severity === "warning" && diagnostic.fixable).length,
30565
+ fixPassesRun,
30566
+ passesRun,
30567
+ problemCount: diagnostics.length,
30221
30568
  rulesEvaluated,
30222
- rulesSkipped
30569
+ rulesSkipped,
30570
+ warningCount: diagnostics.filter((diagnostic) => diagnostic.severity === "warning").length,
30571
+ workspacesChecked
30223
30572
  };
30224
30573
  }
30225
- async function evaluateWorkspaces(workspaces, options, workspaceNames, pass = 1, progress) {
30226
- const diagnostics = [];
30227
- const contextsByWorkspace = /* @__PURE__ */ new Map();
30228
- const rulesById = /* @__PURE__ */ new Map();
30229
- const results = Array.from({ length: workspaces.length }, () => ({
30230
- context: void 0,
30231
- diagnostics: [],
30232
- progressEvents: [],
30233
- rules: [],
30234
- rulesEvaluated: 0,
30235
- rulesSkipped: 0
30236
- }));
30237
- let rulesEvaluated = 0;
30238
- let rulesSkipped = 0;
30239
- const concurrency = Math.max(1, options.jobs ?? 1);
30240
- const isEmitProgressImmediately = concurrency === 1;
30241
- const noopProgress = (_event) => void 0;
30242
- await runWithConcurrency(workspaces.map((workspace, workspaceIndex) => ({
30243
- workspace,
30244
- workspaceIndex
30245
- })), concurrency, async ({ workspace, workspaceIndex }) => {
30246
- results[workspaceIndex] = await evaluateWorkspace(workspace, workspaceIndex, workspaces.length, options, workspaceNames, pass, isEmitProgressImmediately ? progress ?? noopProgress : noopProgress);
30247
- });
30248
- for (const result of results) {
30249
- if (!isEmitProgressImmediately) for (const event of result.progressEvents) progress?.(event);
30250
- const { context, rules } = result;
30251
- contextsByWorkspace.set(context.workspace.location, context);
30252
- diagnostics.push(...result.diagnostics);
30253
- rulesEvaluated += result.rulesEvaluated;
30254
- rulesSkipped += result.rulesSkipped;
30255
- for (const rule of rules) rulesById.set(rule.id, rule);
30256
- }
30574
+ function buildRunProfile(options, firstPassProfiles, wallMs) {
30575
+ if (options.profile !== true) return void 0;
30257
30576
  return {
30258
- contextsByWorkspace,
30259
- diagnostics,
30260
- rulesById,
30261
- rulesEvaluated,
30262
- rulesSkipped
30577
+ cpuMs: firstPassProfiles.reduce((sum, workspaceProfile) => sum + workspaceProfile.totalMs, 0),
30578
+ wallMs,
30579
+ workspaces: firstPassProfiles
30263
30580
  };
30264
30581
  }
30265
30582
  async function runDeplint(workspaces, options, workspaceNames) {
30583
+ const runStarted = performance.now();
30266
30584
  const progress = options.progress;
30267
- const flags = resolveDeplintCheckFlags(options);
30268
30585
  progress?.({
30269
- activeCategories: getActiveDeplintCategories(flags),
30586
+ activeCategories: getActiveDeplintCategories(resolveDeplintCheckFlags(options)),
30270
30587
  fix: options.fix === true,
30271
30588
  maxFixPasses: MAX_FIX_PASSES,
30272
30589
  type: "run-start",
@@ -30294,7 +30611,9 @@ async function runDeplint(workspaces, options, workspaceNames) {
30294
30611
  });
30295
30612
  return evaluation;
30296
30613
  }
30297
- let { contextsByWorkspace, diagnostics, rulesById } = await evaluatePass(1);
30614
+ const firstPass = await evaluatePass(1);
30615
+ const firstPassProfiles = firstPass.profiles;
30616
+ let { contextsByWorkspace, diagnostics, rulesById } = firstPass;
30298
30617
  const appliedFixes = [];
30299
30618
  let fixPassesRun = 0;
30300
30619
  for (let fixPass = 1; (options.fix ?? false) && diagnostics.length > 0 && fixPass <= MAX_FIX_PASSES; fixPass++) {
@@ -30319,178 +30638,23 @@ async function runDeplint(workspaces, options, workspaceNames) {
30319
30638
  }
30320
30639
  ({contextsByWorkspace, diagnostics, rulesById} = await evaluatePass(fixPass + 1));
30321
30640
  }
30322
- const errorCount = diagnostics.filter((diagnostic) => diagnostic.severity === "error").length;
30323
- const fixableErrorCount = diagnostics.filter((diagnostic) => diagnostic.severity === "error" && diagnostic.fixable).length;
30324
- const fixableWarningCount = diagnostics.filter((diagnostic) => diagnostic.severity === "warning" && diagnostic.fixable).length;
30325
- const problemCount = diagnostics.length;
30326
- const warningCount = diagnostics.filter((diagnostic) => diagnostic.severity === "warning").length;
30327
- const diagnosticsByRule = {};
30328
- for (const diagnostic of diagnostics) diagnosticsByRule[diagnostic.id] = (diagnosticsByRule[diagnostic.id] ?? 0) + 1;
30641
+ clearSourceFileCache();
30329
30642
  return {
30330
30643
  appliedFixes,
30331
30644
  diagnostics,
30332
- summary: {
30333
- appliedFixes: appliedFixes.length,
30334
- diagnosticsByRule,
30335
- errorCount,
30336
- fixableErrorCount,
30337
- fixableWarningCount,
30645
+ profile: buildRunProfile(options, firstPassProfiles, performance.now() - runStarted),
30646
+ summary: buildSummary({
30647
+ appliedFixes,
30648
+ diagnostics,
30338
30649
  fixPassesRun,
30339
30650
  passesRun,
30340
- problemCount,
30341
30651
  rulesEvaluated,
30342
30652
  rulesSkipped,
30343
- warningCount,
30344
30653
  workspacesChecked: workspaces.length
30345
- }
30654
+ })
30346
30655
  };
30347
30656
  }
30348
30657
  //#endregion
30349
- //#region src/actions/deplint/reporters.ts
30350
- function pluralize(word, count) {
30351
- return `${word}${count === 1 ? "" : "s"}`;
30352
- }
30353
- function formatWorkspaceList(workspaces) {
30354
- const names = workspaces.map((workspace) => workspace.name);
30355
- if (names.length <= 5) return names.join(", ");
30356
- return `${names.slice(0, 5).join(", ")} +${names.length - 5} more`;
30357
- }
30358
- function groupedDiagnostics(diagnostics) {
30359
- const workspaces = /* @__PURE__ */ new Map();
30360
- for (const diagnostic of diagnostics) {
30361
- const key = diagnostic.workspace.location;
30362
- let workspaceGroup = workspaces.get(key);
30363
- if (!workspaceGroup) {
30364
- workspaceGroup = {
30365
- diagnostics: 0,
30366
- rules: /* @__PURE__ */ new Map(),
30367
- workspace: diagnostic.workspace
30368
- };
30369
- workspaces.set(key, workspaceGroup);
30370
- }
30371
- workspaceGroup.diagnostics += 1;
30372
- const rules = workspaceGroup.rules;
30373
- const ruleDiagnostics = rules.get(diagnostic.id) ?? [];
30374
- ruleDiagnostics.push(diagnostic);
30375
- rules.set(diagnostic.id, ruleDiagnostics);
30376
- }
30377
- return workspaces.values().toArray();
30378
- }
30379
- function createHumanDeplintProgressReporter({ isVerbose = false } = {}) {
30380
- return (event) => renderHumanDeplintProgressEvent(event, isVerbose);
30381
- }
30382
- function renderHumanDeplintProgressEvent(event, isVerbose) {
30383
- switch (event.type) {
30384
- case "run-start":
30385
- renderRunStart(event);
30386
- break;
30387
- case "workspace-start":
30388
- renderWorkspaceHeader(event);
30389
- if (isVerbose) renderVerboseWorkspaceDetails(event);
30390
- break;
30391
- case "fix-start":
30392
- renderFixStart(event);
30393
- break;
30394
- case "fix-end":
30395
- renderFixEnd(event);
30396
- break;
30397
- default: if (isVerbose) renderVerboseProgressEvent(event);
30398
- }
30399
- }
30400
- function renderRunStart(event) {
30401
- const categories = event.activeCategories.join(", ");
30402
- const fixDetail = event.fix ? ` with --fix (max ${event.maxFixPasses} fix ${pluralize("pass", event.maxFixPasses)})` : "";
30403
- console.info(`Deplint: checking ${event.workspaces.length} ${pluralize("workspace", event.workspaces.length)} [${categories}]${fixDetail}`);
30404
- console.info(`Workspaces: ${formatWorkspaceList(event.workspaces)}`);
30405
- }
30406
- function renderFixStart(event) {
30407
- console.info(`Deplint: fix pass ${event.fixPass} resolving ${event.diagnostics} ${pluralize("diagnostic", event.diagnostics)}`);
30408
- }
30409
- function renderFixEnd(event) {
30410
- console.info(`Deplint: fix pass ${event.fixPass} applied ${event.appliedFixes} ${pluralize("fix", event.appliedFixes)}`);
30411
- }
30412
- function renderVerboseProgressEvent(event) {
30413
- switch (event.type) {
30414
- case "pass-start":
30415
- console.info(chalk.dim(`Deplint pass ${event.pass}: evaluating ${event.workspaces.length} ${pluralize("workspace", event.workspaces.length)}`));
30416
- break;
30417
- case "pass-end":
30418
- console.info(chalk.dim(`Deplint pass ${event.pass}: ${event.diagnostics} ${pluralize("diagnostic", event.diagnostics)}, ${event.rulesEvaluated} ${pluralize("rule", event.rulesEvaluated)} evaluated, ${event.rulesSkipped} skipped`));
30419
- break;
30420
- case "workspace-end":
30421
- console.info(chalk.dim(`[${event.workspace.name}] pass ${event.pass}: ${event.diagnostics} ${pluralize("diagnostic", event.diagnostics)}`));
30422
- break;
30423
- case "rule-start":
30424
- console.info(chalk.dim(` rule ${event.ruleIndex}/${event.ruleTotal}: ${event.rule.id}`));
30425
- break;
30426
- case "rule-end":
30427
- console.info(chalk.dim(` ${event.diagnostics} ${pluralize("finding", event.diagnostics)} in ${event.elapsedMs}ms`));
30428
- break;
30429
- case "rule-skip":
30430
- console.info(chalk.dim(` skip ${event.ruleIndex}/${event.ruleTotal}: ${event.rule.id} (${event.reason})`));
30431
- break;
30432
- }
30433
- }
30434
- function renderWorkspaceHeader(event) {
30435
- console.info(`[${chalk.blue(event.workspace.name)}] package ${event.workspaceIndex}/${event.workspaceTotal}: ${event.workspace.location} (${event.context.packageKind})`);
30436
- }
30437
- function renderVerboseWorkspaceDetails(event) {
30438
- const forcedRefs = event.context.forceDeps + event.context.forceDevs + event.context.forcePeers + event.context.forcePeerOptional;
30439
- console.info(chalk.dim(` files: ${event.context.allFiles} all, ${event.context.distFiles} dist; deps: ${event.context.dependencies}, dev: ${event.context.devDependencies}, peer: ${event.context.peerDependencies}; exclude: ${event.context.excludeCount}, forced refs: ${forcedRefs}`));
30440
- }
30441
- const humanDeplintReporter = { render(result) {
30442
- for (const fix of result.appliedFixes) console.log(`[${chalk.blue(fix.workspace.name)}] Fixed: ${fix.detail} ${chalk.green(fix.dependency)}`);
30443
- for (const workspaceGroup of groupedDiagnostics(result.diagnostics)) {
30444
- console.log(`[${chalk.blue(workspaceGroup.workspace.name)}] ${workspaceGroup.diagnostics} ${pluralize("problem", workspaceGroup.diagnostics)}`);
30445
- for (const [ruleId, diagnostics] of workspaceGroup.rules) {
30446
- console.log(` ${chalk.cyan(ruleId)} (${diagnostics.length})`);
30447
- for (const diagnostic of diagnostics) {
30448
- console.log(` ${diagnostic.message}`);
30449
- if (diagnostic.fixable) console.log(` ${chalk.dim("fixable with `--fix`")}`);
30450
- const evidence = diagnostic.evidence ?? [];
30451
- for (const line of evidence) console.log(` ${line}`);
30452
- console.log(` ${chalk.yellow(diagnostic.file)}`);
30453
- }
30454
- }
30455
- console.log("");
30456
- }
30457
- if (result.summary.problemCount > 0) {
30458
- const summaryMessage = [
30459
- `✖ ${result.summary.problemCount} ${pluralize("problem", result.summary.problemCount)}`,
30460
- `(${result.summary.errorCount} ${pluralize("error", result.summary.errorCount)},`,
30461
- `${result.summary.warningCount} ${pluralize("warning", result.summary.warningCount)})`
30462
- ].join(" ");
30463
- const colorizeSummary = (message) => {
30464
- if (result.summary.errorCount > 0) return chalk.red(message);
30465
- return chalk.yellow(message);
30466
- };
30467
- console.warn(colorizeSummary(summaryMessage));
30468
- if (result.summary.fixableErrorCount > 0 || result.summary.fixableWarningCount > 0) {
30469
- const fixableMessage = [
30470
- ` ${result.summary.fixableErrorCount} ${pluralize("error", result.summary.fixableErrorCount)}`,
30471
- `and ${result.summary.fixableWarningCount} ${pluralize("warning", result.summary.fixableWarningCount)}`,
30472
- "potentially fixable with the `--fix` option."
30473
- ].join(" ");
30474
- console.warn(colorizeSummary(fixableMessage));
30475
- }
30476
- if (result.summary.diagnosticsByRule !== void 0) {
30477
- const byRule = Object.entries(result.summary.diagnosticsByRule).map(([rule, count]) => `${rule}: ${count}`).join(", ");
30478
- if (byRule.length > 0) console.warn(colorizeSummary(` By rule: ${byRule}`));
30479
- }
30480
- if (result.summary.passesRun !== void 0 && result.summary.rulesEvaluated !== void 0) console.warn(chalk.dim(` Checked ${result.summary.workspacesChecked} ${pluralize("workspace", result.summary.workspacesChecked)} across ${result.summary.passesRun} ${pluralize("pass", result.summary.passesRun)}; ${result.summary.rulesEvaluated} ${pluralize("rule", result.summary.rulesEvaluated)} evaluated, ${result.summary.rulesSkipped ?? 0} skipped.`));
30481
- return;
30482
- }
30483
- const detail = result.summary.passesRun === void 0 ? "" : chalk.dim(` Checked ${result.summary.workspacesChecked} ${pluralize("workspace", result.summary.workspacesChecked)} across ${result.summary.passesRun} ${pluralize("pass", result.summary.passesRun)}.`);
30484
- const summaryMessage = `(${result.summary.errorCount} ${pluralize("error", result.summary.errorCount)}, ${result.summary.warningCount} ${pluralize("warning", result.summary.warningCount)})`;
30485
- console.info(`Deplint: Found no dependency problems. ${chalk.green("✔")} ${summaryMessage}${detail}`);
30486
- } };
30487
- const jsonDeplintReporter = { render(result) {
30488
- console.log(JSON.stringify(result, null, 2));
30489
- } };
30490
- function getDeplintReporter(format) {
30491
- return format === "json" ? jsonDeplintReporter : humanDeplintReporter;
30492
- }
30493
- //#endregion
30494
30658
  //#region src/actions/deplint/deplint.ts
30495
30659
  function emptyResult$7() {
30496
30660
  return {
@@ -30518,7 +30682,7 @@ function resolveTargetWorkspaces(targetPackage, inputWorkspaces) {
30518
30682
  workspaceNames
30519
30683
  };
30520
30684
  }
30521
- const deplint = async ({ pkg, classifier, deps, devDeps, fix, peerDeps, verbose, cliExclude, format, jobs, workspaces: inputWorkspaces }) => {
30685
+ const deplint = async ({ pkg, classifier, deps, devDeps, fix, peerDeps, profile, verbose, cliExclude, format, jobs, workspaces: inputWorkspaces }) => {
30522
30686
  const effectiveFormat = format ?? (isJsonMode() ? "json" : "human");
30523
30687
  const targetPackage = typeof pkg === "string" && pkg.length > 0 && pkg !== "undefined" ? pkg : void 0;
30524
30688
  const { targetWorkspaces, workspaceNames } = resolveTargetWorkspaces(targetPackage, inputWorkspaces);
@@ -30532,11 +30696,15 @@ const deplint = async ({ pkg, classifier, deps, devDeps, fix, peerDeps, verbose,
30532
30696
  fix,
30533
30697
  jobs,
30534
30698
  peerDeps,
30699
+ profile,
30535
30700
  progress: effectiveFormat === "human" ? createHumanDeplintProgressReporter({ isVerbose: verbose }) : void 0,
30536
30701
  reporter: effectiveFormat,
30537
30702
  verbose
30538
30703
  }, workspaceNames);
30539
- if (!isJsonMode()) getDeplintReporter(effectiveFormat).render(result);
30704
+ if (!isJsonMode()) {
30705
+ getDeplintReporter(effectiveFormat).render(result);
30706
+ if (profile === true && effectiveFormat === "human") printDeplintProfileFromResult(result);
30707
+ }
30540
30708
  if ((fix ?? false) && result.summary.appliedFixes > 0) shouldRunInstall();
30541
30709
  const exitCode = result.summary.errorCount + (isStrictMode() ? result.summary.warningCount : 0);
30542
30710
  return {
@@ -30552,15 +30720,6 @@ const deplint = async ({ pkg, classifier, deps, devDeps, fix, peerDeps, verbose,
30552
30720
  //#region src/actions/lintNextWorker.ts
30553
30721
  const lintNextIgnorePatterns = ["packages/**"];
30554
30722
  const lintNextResultMarker = "__XY_LINT_NEXT_RESULT__";
30555
- const require$4 = createRequire(import.meta.url);
30556
- function resolveChalkImportUrl() {
30557
- try {
30558
- return pathToFileURL(require$4.resolve("chalk")).href;
30559
- } catch {
30560
- return pathToFileURL(require$4.resolve("chalk", { paths: [process.cwd()] })).href;
30561
- }
30562
- }
30563
- const chalkImportUrl = resolveChalkImportUrl();
30564
30723
  /**
30565
30724
  * Long-lived worker: loads ESLint once, then processes NDJSON jobs from stdin.
30566
30725
  * Sharing a process amortizes plugin/config module load across packages
@@ -30589,7 +30748,20 @@ const cycleRuleFilePatterns = ${JSON.stringify([
30589
30748
  "**/*.d.cts"
30590
30749
  ])}
30591
30750
  const defaultIgnorePatterns = ${JSON.stringify(lintNextIgnorePatterns)}
30592
- const { default: chalk } = await import(process.env.XY_LINT_NEXT_CHALK_URL)
30751
+ // Diagnostics only need a few foreground colors; inline ANSI wrappers avoid
30752
+ // importing chalk (inlined into the bundled CLI, so not resolvable on disk).
30753
+ const useColor = process.env.NO_COLOR === undefined
30754
+ && process.env.FORCE_COLOR !== undefined && process.env.FORCE_COLOR !== '0'
30755
+ const CLOSE = '\u001B[39m'
30756
+ // Nested colors compose as strings, so re-open the outer color where an inner
30757
+ // one closed (chalk's own nesting strategy) instead of tracking a stack.
30758
+ const paint = (code) => {
30759
+ const open = '\u001B[' + code + 'm'
30760
+ return useColor ? (text) => open + String(text).replaceAll(CLOSE, open) + CLOSE : (text) => String(text)
30761
+ }
30762
+ const chalk = {
30763
+ gray: paint(90), green: paint(32), red: paint(31), white: paint(37), yellow: paint(33),
30764
+ }
30593
30765
  const colors = ['white', 'yellow', 'red']
30594
30766
  const severity = ['none', 'warning', 'error']
30595
30767
 
@@ -30900,8 +31072,7 @@ var LintWorkerPool = class {
30900
31072
  spawnWorker(id) {
30901
31073
  const env = {
30902
31074
  ...process.env,
30903
- FORCE_COLOR: "3",
30904
- XY_LINT_NEXT_CHALK_URL: chalkImportUrl
31075
+ FORCE_COLOR: String(chalk.level)
30905
31076
  };
30906
31077
  delete env.NO_COLOR;
30907
31078
  delete env.NODE_DISABLE_COLORS;
@@ -31952,6 +32123,44 @@ const resolveCompilePlatforms = (compile) => {
31952
32123
  };
31953
32124
  };
31954
32125
  //#endregion
32126
+ //#region src/actions/package/compile/monolithCopyEntries.ts
32127
+ const copyPlatforms = /* @__PURE__ */ new Set([
32128
+ "browser",
32129
+ "neutral",
32130
+ "node"
32131
+ ]);
32132
+ function isPathInside(parent, candidate) {
32133
+ const relative = PATH.relative(parent, candidate);
32134
+ return relative.length > 0 && relative !== ".." && !relative.startsWith(`..${PATH.sep}`) && !PATH.isAbsolute(relative);
32135
+ }
32136
+ /** Resolves configured copy destinations without requiring their sources to exist. */
32137
+ function listMonolithCopyEntries(packageDir, config) {
32138
+ const distDir = PATH.resolve(packageDir, "dist");
32139
+ const entries = [];
32140
+ const configuredCopyEntries = Object.entries(config.copyEntries ?? {});
32141
+ for (const [platformName, configuredEntries] of configuredCopyEntries) {
32142
+ if (!copyPlatforms.has(platformName)) throw new Error(`Unsupported monolith copy entry platform "${platformName}"`);
32143
+ const platform = platformName;
32144
+ const platformDir = PATH.join(distDir, platform);
32145
+ for (const [output, source] of Object.entries(configuredEntries)) {
32146
+ if (output.length === 0) throw new Error(`Monolith copy entry for ${platform} has an empty output path`);
32147
+ if (source.length === 0) throw new Error(`Monolith copy entry "${output}" has an empty source`);
32148
+ if (PATH.isAbsolute(output)) throw new Error(`Monolith copy entry output must be relative: "${output}"`);
32149
+ const destination = PATH.resolve(platformDir, output);
32150
+ if (!isPathInside(platformDir, destination)) throw new Error(`Monolith copy entry output escapes dist/${platform}: "${output}"`);
32151
+ const normalizedOutput = PATH.relative(platformDir, destination).split(PATH.sep).join("/");
32152
+ entries.push({
32153
+ destination,
32154
+ output: normalizedOutput,
32155
+ platform,
32156
+ source,
32157
+ subpath: `./${normalizedOutput}`
32158
+ });
32159
+ }
32160
+ }
32161
+ return entries;
32162
+ }
32163
+ //#endregion
31955
32164
  //#region src/actions/package/compile/PublintConfig.ts
31956
32165
  const ALL_PUBLINT_CHECKS = [
31957
32166
  "compileTargets",
@@ -32286,10 +32495,22 @@ async function collectExpectedCompileOutputs(pkgDir) {
32286
32495
  const compile = (await loadMergedWorkspaceConfig(pkgDir)).compile;
32287
32496
  if (compile === void 0) return [];
32288
32497
  const platforms = resolveCompilePlatforms(compile);
32498
+ const copiedOutputs = compile.mode === "monolith" && compile.monolith !== void 0 ? listMonolithCopyEntries(pkgDir, compile.monolith).filter((entry) => fs.existsSync(entry.destination) && fs.statSync(entry.destination).isFile()).map((entry) => {
32499
+ const declarationFile = pairedDeclarationFile(entry.destination);
32500
+ return {
32501
+ entry: entry.output,
32502
+ isPrimaryIndex: false,
32503
+ platform: entry.platform,
32504
+ runtime: relativeExportsTarget(pkgDir, entry.destination),
32505
+ suggestedSubpath: entry.subpath,
32506
+ types: declarationFile === void 0 ? void 0 : relativeExportsTarget(pkgDir, declarationFile)
32507
+ };
32508
+ }) : [];
32289
32509
  return [
32290
32510
  ...collectOutputsForPlatform(pkgDir, "node", platforms.node, compile),
32291
32511
  ...collectOutputsForPlatform(pkgDir, "browser", platforms.browser, compile),
32292
- ...collectOutputsForPlatform(pkgDir, "neutral", platforms.neutral, compile)
32512
+ ...collectOutputsForPlatform(pkgDir, "neutral", platforms.neutral, compile),
32513
+ ...copiedOutputs
32293
32514
  ];
32294
32515
  }
32295
32516
  //#endregion
@@ -32492,6 +32713,7 @@ function setConditionExport(subpathExport, platform, kind, target) {
32492
32713
  if (conditionExport[kind] === void 0) conditionExport[kind] = target;
32493
32714
  }
32494
32715
  function preferredSubpath(expected) {
32716
+ if (expected.suggestedSubpath !== void 0) return expected.suggestedSubpath;
32495
32717
  if (expected.isPrimaryIndex) return ".";
32496
32718
  return `./${PATH.posix.parse(expected.runtime).name}`;
32497
32719
  }
@@ -38698,15 +38920,17 @@ function install() {
38698
38920
  //#region src/actions/license.ts
38699
38921
  /**
38700
38922
  * `xy license` — walk each workspace's production dependency tree and flag
38701
- * packages whose package.json license is outside the allowlist.
38923
+ * packages whose package.json license is outside the allowlist. The allowlist
38924
+ * and package exceptions come from `commands.license` in xy.config.
38702
38925
  */
38703
38926
  const license = async (pkg) => {
38704
38927
  const workspaceList = getPackageManager().listWorkspaces().filter(({ name }) => pkg === void 0 || name === pkg);
38705
- const allowed = new Set(DEFAULT_ALLOWED_LICENSES);
38706
38928
  console.log(chalk.green("License Checker"));
38707
38929
  let exitCode = 0;
38708
38930
  for (const { location, name } of workspaceList) try {
38709
- const findings = findDisallowedLicenses(collectProductionLicenses(location), allowed);
38931
+ const config = await loadWorkspaceCommandConfig(location, "license");
38932
+ const allowed = resolveAllowedLicenses(config);
38933
+ const findings = findDisallowedLicenses(collectProductionLicenses(location), allowed, config.ignorePackages ?? []);
38710
38934
  console.log(chalk.green(`License Checker [${name}]`));
38711
38935
  for (const finding of findings) console.warn(chalk.yellow(`${finding.packageName}: Package License not allowed [${finding.license}]`));
38712
38936
  if (findings.length > 0) exitCode = findings.length;
@@ -50472,6 +50696,7 @@ const deplintCommand = {
50472
50696
  jobs: argv.jobs,
50473
50697
  peerDeps: !!Boolean(argv.peerDeps),
50474
50698
  pkg,
50699
+ profile: !!Boolean(argv.profile),
50475
50700
  verbose: !!Boolean(argv.verbose)
50476
50701
  }));
50477
50702
  }
@@ -56153,7 +56378,7 @@ const xyParseOptions = () => {
56153
56378
  }).option("profile", {
56154
56379
  alias: "p",
56155
56380
  default: false,
56156
- description: "Emit per-package timing profile (lint: config / lint / spawn phases)",
56381
+ description: "Emit per-package timing profile (lint phases; deplint: files / imports / rules)",
56157
56382
  type: "boolean"
56158
56383
  }).option("json", {
56159
56384
  default: false,