@mui/internal-code-infra 0.0.4-canary.10 → 0.0.4-canary.100

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 (145) hide show
  1. package/LICENSE +1 -1
  2. package/README.md +21 -7
  3. package/build/babel-config.d.mts +5 -1
  4. package/build/brokenLinksChecker/crawlWorker.d.mts +1 -0
  5. package/build/brokenLinksChecker/index.d.mts +192 -2
  6. package/build/changelog/fetchChangelogs.d.mts +3 -0
  7. package/build/changelog/types.d.ts +3 -1
  8. package/build/cli/cmdArgosPush.d.mts +8 -2
  9. package/build/cli/cmdBuild.d.mts +48 -2
  10. package/build/cli/cmdCopyFiles.d.mts +14 -2
  11. package/build/cli/cmdExtractErrorCodes.d.mts +2 -2
  12. package/build/cli/cmdGenerateChangelog.d.mts +17 -2
  13. package/build/cli/cmdGithubAuth.d.mts +2 -2
  14. package/build/cli/cmdListWorkspaces.d.mts +14 -2
  15. package/build/cli/cmdNetlifyIgnore.d.mts +12 -2
  16. package/build/cli/cmdPublish.d.mts +23 -4
  17. package/build/cli/cmdPublishCanary.d.mts +20 -2
  18. package/build/cli/cmdPublishNewPackage.d.mts +10 -2
  19. package/build/cli/cmdRenameScope.d.mts +18 -0
  20. package/build/cli/cmdSetVersionOverrides.d.mts +5 -2
  21. package/build/cli/cmdVale.d.mts +46 -0
  22. package/build/cli/cmdValidateBuiltTypes.d.mts +2 -2
  23. package/build/eslint/baseConfig.d.mts +3 -1
  24. package/build/eslint/mui/rules/disallow-react-api-in-server-components.d.mts +2 -2
  25. package/build/eslint/mui/rules/docgen-ignore-before-comment.d.mts +2 -2
  26. package/build/eslint/mui/rules/no-floating-cleanup.d.mts +5 -0
  27. package/build/eslint/mui/rules/no-guarded-throw.d.mts +31 -0
  28. package/build/eslint/mui/rules/no-presentation-role.d.mts +5 -0
  29. package/build/eslint/mui/rules/no-restricted-resolved-imports.d.mts +8 -2
  30. package/build/eslint/mui/rules/nodeEnvUtils.d.mts +18 -0
  31. package/build/remark/config.d.mts +43 -0
  32. package/build/remark/createLintTester.d.mts +10 -0
  33. package/build/remark/firstBlockHeading.d.mts +4 -0
  34. package/build/remark/gitDiff.d.mts +2 -0
  35. package/build/remark/noSpaceInLinks.d.mts +2 -0
  36. package/build/remark/straightQuotes.d.mts +2 -0
  37. package/build/remark/tableAlignment.d.mts +2 -0
  38. package/build/remark/terminalLanguage.d.mts +2 -0
  39. package/build/utils/babel.d.mts +7 -1
  40. package/build/utils/build.d.mts +59 -37
  41. package/build/utils/extractErrorCodes.d.mts +9 -0
  42. package/build/utils/git.d.mts +16 -0
  43. package/build/utils/github.d.mts +13 -1
  44. package/build/utils/pnpm.d.mts +176 -17
  45. package/build/utils/testUtils.d.mts +28 -0
  46. package/build/utils/typescript.d.mts +6 -16
  47. package/package.json +77 -53
  48. package/src/babel-config.mjs +3 -1
  49. package/src/brokenLinksChecker/crawlWorker.mjs +240 -0
  50. package/src/brokenLinksChecker/index.mjs +263 -188
  51. package/src/changelog/fetchChangelogs.mjs +8 -2
  52. package/src/changelog/renderChangelog.mjs +1 -1
  53. package/src/changelog/types.ts +3 -1
  54. package/src/cli/cmdBuild.mjs +51 -85
  55. package/src/cli/cmdListWorkspaces.mjs +7 -1
  56. package/src/cli/cmdNetlifyIgnore.mjs +30 -5
  57. package/src/cli/cmdPublish.mjs +79 -37
  58. package/src/cli/cmdPublishCanary.mjs +96 -24
  59. package/src/cli/cmdPublishNewPackage.mjs +31 -8
  60. package/src/cli/cmdRenameScope.mjs +76 -0
  61. package/src/cli/cmdSetVersionOverrides.mjs +8 -9
  62. package/src/cli/cmdVale.mjs +513 -0
  63. package/src/cli/index.mjs +4 -0
  64. package/src/cli/packageJson.d.ts +2 -3
  65. package/src/eslint/baseConfig.mjs +51 -19
  66. package/src/eslint/docsConfig.mjs +2 -1
  67. package/src/eslint/mui/config.mjs +24 -4
  68. package/src/eslint/mui/index.mjs +6 -0
  69. package/src/eslint/mui/rules/no-floating-cleanup.mjs +187 -0
  70. package/src/eslint/mui/rules/no-guarded-throw.mjs +115 -0
  71. package/src/eslint/mui/rules/no-presentation-role.mjs +60 -0
  72. package/src/eslint/mui/rules/nodeEnvUtils.mjs +52 -0
  73. package/src/eslint/mui/rules/require-dev-wrapper.mjs +25 -40
  74. package/src/estree-typescript.d.ts +1 -1
  75. package/src/remark/config.mjs +157 -0
  76. package/src/remark/createLintTester.mjs +19 -0
  77. package/src/remark/firstBlockHeading.mjs +87 -0
  78. package/src/remark/gitDiff.mjs +43 -0
  79. package/src/remark/noSpaceInLinks.mjs +42 -0
  80. package/src/remark/straightQuotes.mjs +31 -0
  81. package/src/remark/tableAlignment.mjs +23 -0
  82. package/src/remark/terminalLanguage.mjs +19 -0
  83. package/src/stylelint/index.mjs +2 -2
  84. package/src/untyped-plugins.d.ts +14 -14
  85. package/src/utils/build.mjs +604 -270
  86. package/src/utils/git.mjs +27 -7
  87. package/src/utils/pnpm.mjs +444 -53
  88. package/src/utils/testUtils.mjs +53 -0
  89. package/src/utils/typescript.mjs +23 -42
  90. package/vale/.vale.ini +1 -0
  91. package/vale/styles/MUI/CorrectReferenceAllCases.yml +42 -0
  92. package/vale/styles/MUI/CorrectRererenceCased.yml +14 -0
  93. package/vale/styles/MUI/GoogleLatin.yml +11 -0
  94. package/vale/styles/MUI/MuiBrandName.yml +22 -0
  95. package/vale/styles/MUI/NoBritish.yml +112 -0
  96. package/vale/styles/MUI/NoCompanyName.yml +17 -0
  97. package/build/markdownlint/duplicate-h1.d.mts +0 -56
  98. package/build/markdownlint/git-diff.d.mts +0 -11
  99. package/build/markdownlint/index.d.mts +0 -52
  100. package/build/markdownlint/straight-quotes.d.mts +0 -11
  101. package/build/markdownlint/table-alignment.d.mts +0 -11
  102. package/build/markdownlint/terminal-language.d.mts +0 -11
  103. package/src/brokenLinksChecker/__fixtures__/static-site/broken-links.html +0 -20
  104. package/src/brokenLinksChecker/__fixtures__/static-site/broken-targets.html +0 -22
  105. package/src/brokenLinksChecker/__fixtures__/static-site/example.md +0 -20
  106. package/src/brokenLinksChecker/__fixtures__/static-site/external-links.html +0 -21
  107. package/src/brokenLinksChecker/__fixtures__/static-site/ignored-page.html +0 -17
  108. package/src/brokenLinksChecker/__fixtures__/static-site/index.html +0 -28
  109. package/src/brokenLinksChecker/__fixtures__/static-site/known-targets.json +0 -5
  110. package/src/brokenLinksChecker/__fixtures__/static-site/nested/page.html +0 -21
  111. package/src/brokenLinksChecker/__fixtures__/static-site/orphaned-page.html +0 -20
  112. package/src/brokenLinksChecker/__fixtures__/static-site/page-with-api-links.html +0 -20
  113. package/src/brokenLinksChecker/__fixtures__/static-site/page-with-custom-targets.html +0 -24
  114. package/src/brokenLinksChecker/__fixtures__/static-site/page-with-ignored-content.html +0 -28
  115. package/src/brokenLinksChecker/__fixtures__/static-site/page-with-known-target-links.html +0 -19
  116. package/src/brokenLinksChecker/__fixtures__/static-site/unclosed-tags.html +0 -1
  117. package/src/brokenLinksChecker/__fixtures__/static-site/valid.html +0 -20
  118. package/src/brokenLinksChecker/__fixtures__/static-site/with-anchors.html +0 -31
  119. package/src/brokenLinksChecker/index.test.ts +0 -261
  120. package/src/changelog/categorizeCommits.test.ts +0 -319
  121. package/src/changelog/filterCommits.test.ts +0 -363
  122. package/src/changelog/parseCommitLabels.test.ts +0 -509
  123. package/src/changelog/renderChangelog.test.ts +0 -378
  124. package/src/changelog/sortSections.test.ts +0 -199
  125. package/src/eslint/mui/rules/add-undef-to-optional.test.mjs +0 -361
  126. package/src/eslint/mui/rules/consistent-production-guard.test.mjs +0 -162
  127. package/src/eslint/mui/rules/disallow-active-elements-as-key-event-target.test.mjs +0 -66
  128. package/src/eslint/mui/rules/disallow-react-api-in-server-components.test.mjs +0 -305
  129. package/src/eslint/mui/rules/docgen-ignore-before-comment.test.mjs +0 -52
  130. package/src/eslint/mui/rules/flatten-parentheses.test.mjs +0 -245
  131. package/src/eslint/mui/rules/mui-name-matches-component-name.test.mjs +0 -247
  132. package/src/eslint/mui/rules/no-empty-box.test.mjs +0 -40
  133. package/src/eslint/mui/rules/no-styled-box.test.mjs +0 -73
  134. package/src/eslint/mui/rules/require-dev-wrapper.test.mjs +0 -265
  135. package/src/eslint/mui/rules/rules-of-use-theme-variants.test.mjs +0 -149
  136. package/src/eslint/mui/rules/straight-quotes.test.mjs +0 -67
  137. package/src/markdownlint/duplicate-h1.mjs +0 -69
  138. package/src/markdownlint/git-diff.mjs +0 -31
  139. package/src/markdownlint/index.mjs +0 -62
  140. package/src/markdownlint/straight-quotes.mjs +0 -26
  141. package/src/markdownlint/table-alignment.mjs +0 -42
  142. package/src/markdownlint/terminal-language.mjs +0 -19
  143. package/src/utils/build.test.mjs +0 -705
  144. package/src/utils/template.test.mjs +0 -133
  145. package/src/utils/typescript.test.mjs +0 -380
package/src/utils/git.mjs CHANGED
@@ -24,6 +24,10 @@ export async function getRepositoryInfo(cwd = process.cwd()) {
24
24
  * @type {Set<string>}
25
25
  */
26
26
  const repoRemotes = new Set();
27
+ /**
28
+ * @type {Map<string, { owner: string, repo: string }>}
29
+ */
30
+ const validRemotes = new Map();
27
31
 
28
32
  for (const line of lines) {
29
33
  // Match pattern: "remoteName url (fetch|push)"
@@ -36,20 +40,25 @@ export async function getRepositoryInfo(cwd = process.cwd()) {
36
40
  cause[remoteName] = `Remote is not a GitHub repository under 'mui' organization: ${url}`;
37
41
  continue;
38
42
  }
39
- return {
40
- owner: parsed.owner,
41
- repo: parsed.name,
42
- remoteName,
43
- };
43
+ if (!validRemotes.has(remoteName)) {
44
+ validRemotes.set(remoteName, { owner: parsed.owner, repo: parsed.name });
45
+ }
44
46
  } catch (error) {
45
47
  cause[remoteName] = `Failed to parse URL for remote ${remoteName}: ${url}`;
46
48
  }
47
- }
48
- if (type !== '(push)') {
49
+ } else if (type !== '(push)') {
49
50
  throw new Error(`Unexpected line format for "git remote -v": "${line}"`);
50
51
  }
51
52
  }
52
53
 
54
+ const preferredOrder = ['upstream', 'origin', ...validRemotes.keys()];
55
+ for (const name of preferredOrder) {
56
+ const match = validRemotes.get(name);
57
+ if (match) {
58
+ return { ...match, remoteName: name };
59
+ }
60
+ }
61
+
53
62
  throw new Error(
54
63
  `Failed to find correct remote(s) in : ${Array.from(repoRemotes.keys()).join(', ')}`,
55
64
  { cause },
@@ -64,3 +73,14 @@ export async function getCurrentGitSha() {
64
73
  const result = await $`git rev-parse HEAD`;
65
74
  return result.stdout.trim();
66
75
  }
76
+
77
+ /**
78
+ * Check whether a tag already exists on the origin remote
79
+ * @param {string} tagName - Tag name to check (e.g. `v1.2.3`)
80
+ * @param {string} [cwd=process.cwd()]
81
+ * @returns {Promise<boolean>} True if the tag exists on origin
82
+ */
83
+ export async function remoteGitTagExists(tagName, cwd = process.cwd()) {
84
+ const { stdout } = await $({ cwd })`git ls-remote --tags origin refs/tags/${tagName}`;
85
+ return stdout.trim().length > 0;
86
+ }
@@ -1,9 +1,14 @@
1
1
  #!/usr/bin/env node
2
2
 
3
+ import { findWorkspaceDir } from '@pnpm/find-workspace-dir';
3
4
  import { $ } from 'execa';
4
5
  import * as fs from 'node:fs/promises';
5
6
  import * as path from 'node:path';
6
7
  import * as semver from 'semver';
8
+ import { parseDocument, isMap } from 'yaml';
9
+
10
+ /** Canonical npm registry URL, in the form `getPublishRegistry` returns. */
11
+ const NPMJS_REGISTRY = 'https://registry.npmjs.org/';
7
12
 
8
13
  /**
9
14
  * @typedef {Object} PrivatePackage
@@ -46,7 +51,6 @@ import * as semver from 'semver';
46
51
  * @typedef {Object} GetWorkspacePackagesOptions
47
52
  * @property {string|null} [sinceRef] - Git reference to filter changes since
48
53
  * @property {boolean} [publicOnly=false] - Whether to filter to only public packages
49
- * @property {boolean} [nonPublishedOnly=false] - Whether to filter to only non-published packages. It by default means public packages yet to be published.
50
54
  * @property {string} [cwd] - Current working directory to run pnpm command in
51
55
  * @property {string[]} [filter] - Same as filtering packages with --filter in pnpm. Only include packages matching the filter. See https://pnpm.io/filtering.
52
56
  */
@@ -59,10 +63,6 @@ import * as semver from 'semver';
59
63
  * @returns {Promise<PublicPackage[]>} Array of packages
60
64
  *
61
65
  * @overload
62
- * @param {{ nonPublishedOnly: true } & GetWorkspacePackagesOptions} [options={}] - Options for filtering packages
63
- * @returns {Promise<PublicPackage[]>} Array of packages
64
- *
65
- * @overload
66
66
  * @param {{ publicOnly?: false | undefined } & GetWorkspacePackagesOptions} [options={}] - Options for filtering packages
67
67
  * @returns {Promise<PrivatePackage[]>} Array of packages
68
68
  *
@@ -74,20 +74,38 @@ import * as semver from 'semver';
74
74
  * @returns {Promise<(PrivatePackage | PublicPackage)[]>} Array of packages
75
75
  */
76
76
  export async function getWorkspacePackages(options = {}) {
77
- const { sinceRef = null, publicOnly = false, nonPublishedOnly = false, filter = [] } = options;
77
+ const { sinceRef = null, publicOnly = false, filter = [] } = options;
78
78
 
79
- // Build command with conditional filter
80
- const filterArg = sinceRef ? ['--filter', `...[${sinceRef}]`] : [];
81
- if (filter.length > 0) {
82
- filter.forEach((f) => {
83
- filterArg.push('--filter', f);
84
- });
79
+ /**
80
+ * Run `pnpm ls` with the given --filter args and return the parsed list.
81
+ * @param {string[]} filterArg
82
+ * @returns {Promise<PnpmListResultItem[]>}
83
+ */
84
+ const listPackages = async (filterArg) => {
85
+ const result = await $({ cwd: options.cwd })`pnpm ls -r --json --depth -1 ${filterArg}`;
86
+ return JSON.parse(result.stdout);
87
+ };
88
+
89
+ // pnpm ORs --filter args, so intersect "matches filter" with "changed since ref"
90
+ // in JS. The `...[ref]` selector includes dependents of changed packages, so a
91
+ // package whose `workspace:*` dependency changed is treated as changed too. This
92
+ // keeps consumers from getting duplicate copies when only a leaf package is
93
+ // republished but its dependents still pin the previous version.
94
+ const patternFilterArg = filter.flatMap((f) => ['--filter', f]);
95
+ const [candidatePackages, changedPackages] = await Promise.all([
96
+ listPackages(patternFilterArg),
97
+ // null when no sinceRef (skip the constraint); [] when nothing changed.
98
+ sinceRef ? listPackages(['--filter', `...[${sinceRef}]`]) : Promise.resolve(null),
99
+ ]);
100
+ let packageData = candidatePackages;
101
+ if (changedPackages) {
102
+ // sinceRef given but nothing changed → no packages, regardless of filter.
103
+ if (changedPackages.length === 0) {
104
+ return [];
105
+ }
106
+ const changedPaths = new Set(changedPackages.map((pkg) => pkg.path));
107
+ packageData = packageData.filter((pkg) => changedPaths.has(pkg.path));
85
108
  }
86
- const result = options.cwd
87
- ? await $({ cwd: options.cwd })`pnpm ls -r --json --depth -1 ${filterArg}`
88
- : await $`pnpm ls -r --json --depth -1 ${filterArg}`;
89
- /** @type {PnpmListResultItem[]} */
90
- const packageData = JSON.parse(result.stdout);
91
109
 
92
110
  // Filter packages based on options
93
111
  const filteredPackages = packageData.flatMap((pkg) => {
@@ -105,24 +123,115 @@ export async function getWorkspacePackages(options = {}) {
105
123
  ];
106
124
  });
107
125
 
108
- if (nonPublishedOnly) {
109
- // Check if any of the packages are new/need manual publishing first.
110
- const filteredPublicPackages = filteredPackages.filter((pkg) => !pkg.isPrivate);
126
+ return filteredPackages;
127
+ }
111
128
 
112
- const results = await Promise.all(
113
- filteredPublicPackages.map(async (pkg) => {
114
- const url = `${process.env.npm_config_registry || 'https://registry.npmjs.org'}/${pkg.name}`;
115
- return fetch(url).then((res) => res.status === 404);
116
- }),
129
+ /**
130
+ * Resolve the registry a package will be published to.
131
+ *
132
+ * Only `publishConfig.registry` and the ambient `npm_config_registry` are
133
+ * consulted — `.npmrc` layering and `@scope:registry` entries are not.
134
+ *
135
+ * @param {string} packagePath - Path to the package directory
136
+ * @returns {Promise<string>} Normalized registry URL, ending in a slash
137
+ */
138
+ export async function getPublishRegistry(packagePath) {
139
+ const packageJson = await readPackageJson(packagePath);
140
+ const registry =
141
+ packageJson.publishConfig?.registry || process.env.npm_config_registry || NPMJS_REGISTRY;
142
+
143
+ // Normalizing through the URL parser keeps host casing and default ports from
144
+ // defeating the equality check in `requiresTrustedPublisherBootstrap`. The
145
+ // trailing slash is required because `new URL(name, base)` replaces the last
146
+ // path segment of a base that lacks one, mangling registries served under a
147
+ // path prefix such as Artifactory's `/api/npm/<repo>`.
148
+ let registryUrl;
149
+ try {
150
+ registryUrl = new URL(registry);
151
+ } catch (error) {
152
+ // Node's own message names neither the offending value nor where it came
153
+ // from, leaving the operator to bisect package.json files mid-release.
154
+ throw new Error(
155
+ `Invalid publish registry ${JSON.stringify(registry)} for the package at ${packagePath}`,
156
+ { cause: error },
117
157
  );
118
- return filteredPublicPackages.filter((_pkg, index) => !!results[index]);
119
158
  }
159
+ registryUrl.pathname = `${registryUrl.pathname.replace(/\/+$/, '')}/`;
160
+ return registryUrl.href;
161
+ }
120
162
 
121
- return filteredPackages;
163
+ /**
164
+ * Get the version to release from the workspace-root package.json.
165
+ *
166
+ * Resolves the workspace root so the version is the monorepo's regardless of
167
+ * which directory publish runs from.
168
+ *
169
+ * @param {string} [cwd] - Directory to resolve the workspace root from
170
+ * @returns {Promise<string | null>} Version string, or null when absent/invalid
171
+ */
172
+ export async function getReleaseVersion(cwd = process.cwd()) {
173
+ const workspaceDir = (await findWorkspaceDir(cwd)) ?? cwd;
174
+ const { version } = await readPackageJson(workspaceDir);
175
+ return version ? semver.valid(version) : null;
122
176
  }
123
177
 
124
178
  /**
125
- * Get package version info from registry
179
+ * Whether a registry requires a package to exist before CI can publish to it.
180
+ * @param {string} registry - Normalized registry URL
181
+ * @returns {boolean}
182
+ */
183
+ function requiresTrustedPublisherBootstrap(registry) {
184
+ // npm won't attach a Trusted Publisher to a name that doesn't exist yet. No
185
+ // other registry we publish to has an equivalent step.
186
+ return registry === NPMJS_REGISTRY;
187
+ }
188
+
189
+ /**
190
+ * Filter to the packages that must be published by hand before CI can take over.
191
+ *
192
+ * A brand new package has to be pushed once manually (see
193
+ * `code-infra publish-new-package`) before the OIDC-based workflow can publish
194
+ * it, so the release fails with a clear message instead of a confusing 404
195
+ * midway through. See {@link getPackageVersionInfo} for the version-level check.
196
+ *
197
+ * @param {PublicPackage[]} packages - Packages to check
198
+ * @returns {Promise<PublicPackage[]>} The subset needing a manual first publish
199
+ */
200
+ export async function getPackagesNeedingManualPublish(packages) {
201
+ const results = await Promise.all(
202
+ packages.map(async (pkg) => {
203
+ const registry = await getPublishRegistry(pkg.path);
204
+ if (!requiresTrustedPublisherBootstrap(registry)) {
205
+ return false;
206
+ }
207
+
208
+ // HEAD, because only the status matters — a packument runs to megabytes.
209
+ const res = await fetch(new URL(pkg.name, registry), { method: 'HEAD' });
210
+ if (res.status === 404) {
211
+ return true;
212
+ }
213
+ if (!res.ok) {
214
+ // Anything else (401, 5xx, a proxy hiccup) tells us nothing about
215
+ // whether the package exists. Treating it as "already published" would
216
+ // silently disable the check, so fail loudly instead.
217
+ throw new Error(
218
+ `Failed to check whether ${pkg.name} exists on ${registry}: HTTP ${res.status}`,
219
+ );
220
+ }
221
+ return false;
222
+ }),
223
+ );
224
+
225
+ return packages.filter((_pkg, index) => results[index]);
226
+ }
227
+
228
+ /**
229
+ * Get package version info from registry.
230
+ *
231
+ * Resolves through `pnpm view`, which reports a lookup failure the same way it
232
+ * reports a missing version. Use {@link getPackagesNeedingManualPublish} where
233
+ * absence has to be told apart from an error.
234
+ *
126
235
  * @param {string} packageName - Name of the package
127
236
  * @param {string} baseVersion - Base version to check
128
237
  * @returns {Promise<VersionInfo>} Version information
@@ -154,11 +263,17 @@ export async function getPackageVersionInfo(packageName, baseVersion) {
154
263
  }
155
264
  }
156
265
 
266
+ /**
267
+ * @typedef {Object} PublishSummaryEntry
268
+ * @property {string} name
269
+ * @property {string} version
270
+ */
271
+
157
272
  /**
158
273
  * Publish packages with the given options
159
274
  * @param {PublicPackage[]} packages - Packages to publish
160
275
  * @param {PublishOptions} [options={}] - Publishing options
161
- * @returns {Promise<void>}
276
+ * @returns {Promise<PublishSummaryEntry[]>}
162
277
  */
163
278
  export async function publishPackages(packages, options = {}) {
164
279
  const args = [];
@@ -178,7 +293,23 @@ export async function publishPackages(packages, options = {}) {
178
293
  args.push('--no-git-checks');
179
294
  }
180
295
 
181
- await $({ stdio: 'inherit' })`pnpm -r publish --access public --tag=${tag} ${args}`;
296
+ const workspaceDir = await findWorkspaceDir(process.cwd());
297
+ if (!workspaceDir) {
298
+ throw new Error('Could not find pnpm workspace root');
299
+ }
300
+ const summaryPath = path.join(workspaceDir, 'pnpm-publish-summary.json');
301
+
302
+ // Clean up any leftover summary file from a previous run
303
+ await fs.rm(summaryPath, { force: true });
304
+
305
+ await $({
306
+ stdio: 'inherit',
307
+ env: { npm_config_loglevel: 'warn' },
308
+ })`pnpm -r publish --access public --tag=${tag} --report-summary ${args}`;
309
+
310
+ const summary = JSON.parse(await fs.readFile(summaryPath, 'utf-8'));
311
+ await fs.rm(summaryPath, { force: true });
312
+ return /** @type {PublishSummaryEntry[]} */ (summary.publishedPackages);
182
313
  }
183
314
 
184
315
  /**
@@ -187,13 +318,33 @@ export async function publishPackages(packages, options = {}) {
187
318
  * @property {boolean} [includeDev=true] - Whether to include devDependencies in the traversal
188
319
  */
189
320
 
321
+ /**
322
+ * The package a `workspace:` alias spec resolves to, if it is one.
323
+ *
324
+ * @param {string} spec - Dependency spec
325
+ * @returns {string | null} The aliased package name, or null for a plain spec
326
+ */
327
+ function aliasTarget(spec) {
328
+ if (!spec.startsWith('workspace:')) {
329
+ return null;
330
+ }
331
+ const range = spec.slice('workspace:'.length);
332
+ // Search from 1 so a scoped name's own leading `@` isn't read as the separator.
333
+ const separator = range.indexOf('@', 1);
334
+ return separator === -1 ? null : range.slice(0, separator);
335
+ }
336
+
190
337
  /**
191
338
  * Get all transitive workspace dependencies for a set of packages.
192
339
  *
193
- * Traverses `dependencies`, `peerDependencies`, and optionally `devDependencies`,
194
- * following only packages that exist in `workspacePathByName`. Results are cached
195
- * per package so each package is read from disk at most once regardless of how many
196
- * roots depend on it.
340
+ * Only follows deps whose version spec starts with `workspace:` (e.g. `workspace:*`
341
+ * or `workspace:^`), meaning they are sourced directly from the monorepo. An
342
+ * alias spec (`workspace:@scope/name@range`) is followed to the package it
343
+ * targets, which need not match the dependency key. Pinned
344
+ * external versions (e.g. `^1.0.0`) are ignored even when the package name exists
345
+ * in the workspace. Traverses `dependencies` and optionally `devDependencies`.
346
+ * Results are cached per package so each package is read from disk at most once
347
+ * regardless of how many roots depend on it.
197
348
  *
198
349
  * @param {string[]} packageNames - Package names to start the traversal from
199
350
  * @param {GetTransitiveDependenciesOptions} [options]
@@ -222,12 +373,19 @@ export async function getTransitiveDependencies(packageNames, options = {}) {
222
373
  }
223
374
 
224
375
  const pkgJson = await readPackageJson(packagePath);
225
- const allDeps = new Set([
226
- ...Object.keys(pkgJson.dependencies ?? {}),
227
- ...(includeDev ? Object.keys(pkgJson.devDependencies ?? {}) : []),
228
- ...Object.keys(pkgJson.peerDependencies ?? {}),
229
- ]);
230
- const workspaceDeps = [...allDeps].filter((dep) => workspacePathByName.has(dep));
376
+ const allDepEntries = [
377
+ ...Object.entries(pkgJson.dependencies ?? {}),
378
+ ...(includeDev ? Object.entries(pkgJson.devDependencies ?? {}) : []),
379
+ ];
380
+ const workspaceDeps = allDepEntries.flatMap(([dep, spec]) => {
381
+ if (typeof spec !== 'string' || !spec.startsWith('workspace:')) {
382
+ return [];
383
+ }
384
+ // An aliased spec (`workspace:@scope/name@range`) names the workspace
385
+ // package it resolves to, which need not match the dependency key.
386
+ const name = aliasTarget(spec) ?? dep;
387
+ return workspacePathByName.has(name) ? [name] : [];
388
+ });
231
389
 
232
390
  const recursiveResults = await Promise.all(workspaceDeps.map(collectDeps));
233
391
  return new Set([...workspaceDeps, ...recursiveResults.flatMap((s) => [...s])]);
@@ -248,25 +406,30 @@ export async function getTransitiveDependencies(packageNames, options = {}) {
248
406
  }
249
407
 
250
408
  /**
251
- * Validate that a set of packages covers all of their transitive workspace dependencies,
252
- * and that none of those dependencies are private (which would make them unpublishable).
409
+ * Pure validation logic: given a publish set and workspace maps, checks that all
410
+ * transitive hard workspace dependencies are covered and none are private.
411
+ *
412
+ * A hard dependency is one listed in `dependencies` (not `peerDependencies` or
413
+ * `devDependencies`) using a `workspace:` version specifier (e.g. `workspace:*` or
414
+ * `workspace:^`). Peer dependencies are never bundled and dev dependencies are not installed
415
+ * on consumer devices - both are excluded regardless of version specifier. Pinned-version
416
+ * references in `dependencies` are also excluded - they resolve from the registry and do
417
+ * not need to be co-published.
253
418
  *
254
419
  * @param {PublicPackage[]} packages - The packages intended for publishing
420
+ * @param {Map<string, PublicPackage | PrivatePackage>} workspacePackageByName - All workspace packages by name
421
+ * @param {Map<string, string>} workspacePathByName - Map of workspace package name to directory path
255
422
  * @returns {Promise<{issues: string[]}>}
256
423
  * List of human-readable issue strings. Empty when the dependency set is valid.
424
+ * @internal
257
425
  */
258
- export async function validatePublishDependencies(packages) {
259
- const allWorkspacePackages = await getWorkspacePackages();
260
-
261
- /** @type {Map<string, PublicPackage | PrivatePackage>} */
262
- const workspacePackageByName = new Map(
263
- allWorkspacePackages.flatMap((pkg) => (pkg.name ? [[pkg.name, pkg]] : [])),
264
- );
265
- const workspacePathByName = new Map(
266
- allWorkspacePackages.flatMap((pkg) => (pkg.name ? [[pkg.name, pkg.path]] : [])),
267
- );
268
-
426
+ export async function checkPublishDependencies(
427
+ packages,
428
+ workspacePackageByName,
429
+ workspacePathByName,
430
+ ) {
269
431
  const publishedNames = new Set(packages.map((pkg) => pkg.name));
432
+
270
433
  const transitiveDeps = await getTransitiveDependencies(
271
434
  packages.map((pkg) => pkg.name),
272
435
  { includeDev: false, workspacePathByName },
@@ -307,6 +470,27 @@ export async function validatePublishDependencies(packages) {
307
470
  return { issues };
308
471
  }
309
472
 
473
+ /**
474
+ * Validate that a set of packages covers all of their transitive hard workspace dependencies,
475
+ * and that none of those dependencies are private (which would make them unpublishable).
476
+ *
477
+ * @param {PublicPackage[]} packages - The packages intended for publishing
478
+ * @returns {Promise<{issues: string[]}>}
479
+ * List of human-readable issue strings. Empty when the dependency set is valid.
480
+ */
481
+ export async function validatePublishDependencies(packages) {
482
+ const allWorkspacePackages = await getWorkspacePackages();
483
+
484
+ const workspacePackageByName = /** @type {Map<string, PublicPackage | PrivatePackage>} */ (
485
+ new Map(allWorkspacePackages.flatMap((pkg) => (pkg.name ? [[pkg.name, pkg]] : [])))
486
+ );
487
+ const workspacePathByName = new Map(
488
+ allWorkspacePackages.flatMap((pkg) => (pkg.name ? [[pkg.name, pkg.path]] : [])),
489
+ );
490
+
491
+ return checkPublishDependencies(packages, workspacePackageByName, workspacePathByName);
492
+ }
493
+
310
494
  /**
311
495
  * Read package.json from a directory
312
496
  * @param {string} packagePath - Path to package directory
@@ -328,6 +512,213 @@ export async function writePackageJson(packagePath, packageJson) {
328
512
  await fs.writeFile(path.join(packagePath, 'package.json'), content);
329
513
  }
330
514
 
515
+ /**
516
+ * Write the computed overrides into whichever manifest already defines
517
+ * overrides — preferring pnpm-workspace.yaml, falling back to package.json
518
+ * `pnpm.overrides`, defaulting to pnpm-workspace.yaml — and persist the result.
519
+ * A missing pnpm-workspace.yaml is treated as empty, so a fresh file is created
520
+ * with just the `overrides:` block. Rejects a `resolutions` field in
521
+ * package.json because pnpm 11 silently ignores it.
522
+ *
523
+ * @param {string} workspaceDir - Workspace root directory
524
+ * @param {Record<string, string>} overrides - Overrides to apply
525
+ * @returns {Promise<void>}
526
+ */
527
+ export async function writeOverridesToWorkspace(workspaceDir, overrides) {
528
+ const workspaceYamlPath = path.join(workspaceDir, 'pnpm-workspace.yaml');
529
+ const yamlPromise = fs.readFile(workspaceYamlPath, { encoding: 'utf8' }).catch((error) => {
530
+ if (/** @type {NodeJS.ErrnoException} */ (error).code !== 'ENOENT') {
531
+ throw error;
532
+ }
533
+ return '';
534
+ });
535
+ const [rootPackageJson, yamlSource] = await Promise.all([
536
+ readPackageJson(workspaceDir),
537
+ yamlPromise,
538
+ ]);
539
+
540
+ const { resolutions } = rootPackageJson;
541
+ if (resolutions && Object.keys(resolutions).length > 0) {
542
+ throw new Error(
543
+ 'Found a "resolutions" field in package.json. pnpm 11 ignores it silently. ' +
544
+ 'Move those entries into the "overrides:" key of pnpm-workspace.yaml.',
545
+ );
546
+ }
547
+
548
+ // Parsed once, reused for both the read (does it have overrides?) and the write.
549
+ const doc = parseDocument(yamlSource);
550
+ const existing = doc.get('overrides');
551
+ const workspaceHasOverrides = isMap(existing) && existing.items.length > 0;
552
+
553
+ const pnpm = /** @type {{ overrides?: Record<string, string> } | undefined} */ (
554
+ rootPackageJson.pnpm
555
+ );
556
+ const packageJsonOverrides = pnpm?.overrides;
557
+
558
+ // Write where overrides already live; default to the workspace file.
559
+ if (
560
+ !workspaceHasOverrides &&
561
+ packageJsonOverrides &&
562
+ Object.keys(packageJsonOverrides).length > 0
563
+ ) {
564
+ await writePackageJson(workspaceDir, {
565
+ ...rootPackageJson,
566
+ pnpm: { ...pnpm, overrides: { ...packageJsonOverrides, ...overrides } },
567
+ });
568
+ return;
569
+ }
570
+
571
+ for (const [name, version] of Object.entries(overrides)) {
572
+ doc.setIn(['overrides', name], version);
573
+ }
574
+ await fs.writeFile(workspaceYamlPath, doc.toString());
575
+ }
576
+
577
+ /**
578
+ * Map a package name onto a different npm scope.
579
+ * @param {string} name - Package name, e.g. `@base-ui/mosaic`
580
+ * @param {string} fromScope - Scope to replace, e.g. `@base-ui`
581
+ * @param {string} toScope - Replacement scope, e.g. `@base-ui-private`
582
+ * @returns {string | null} The renamed package, or null when the scope doesn't match
583
+ */
584
+ function renameScope(name, fromScope, toScope) {
585
+ const prefix = `${fromScope}/`;
586
+ return name.startsWith(prefix) ? `${toScope}/${name.slice(prefix.length)}` : null;
587
+ }
588
+
589
+ /**
590
+ * Move the publishable workspace packages in one scope to another.
591
+ *
592
+ * Only packages that are part of the workspace are touched, so dependencies
593
+ * that merely share the scope but come from the registry (say `@base-ui/react`
594
+ * alongside a workspace `@base-ui/mosaic`) are left alone. Dependents keep the
595
+ * original dependency name and gain a `workspace:` alias, so imports in the
596
+ * repo resolve exactly as before.
597
+ *
598
+ * @param {(PublicPackage | PrivatePackage)[]} packages - All workspace packages
599
+ * @param {string} fromScope - Scope to move away from
600
+ * @param {string} toScope - Scope to move to
601
+ * @returns {Promise<Map<string, string>>} Old package name to new package name
602
+ */
603
+ export async function renameWorkspaceScope(packages, fromScope, toScope) {
604
+ // Renaming a scope onto itself only rewrites every manifest to itself. The
605
+ // CLI rejects this earlier, but the guard belongs with the operation so a
606
+ // direct caller cannot trip the silent churn either.
607
+ if (fromScope === toScope) {
608
+ throw new Error(`Cannot rename ${fromScope} to itself.`);
609
+ }
610
+
611
+ /** @type {Map<string, string>} */
612
+ const renamed = new Map();
613
+
614
+ for (const pkg of packages) {
615
+ if (pkg.isPrivate) {
616
+ continue;
617
+ }
618
+ const newName = renameScope(pkg.name, fromScope, toScope);
619
+ if (newName) {
620
+ renamed.set(pkg.name, newName);
621
+ }
622
+ }
623
+
624
+ // A rename that lands on a name another package keeps would leave the
625
+ // workspace with two packages sharing a name. Catch it up front, before any
626
+ // manifest is written.
627
+ /** @type {Map<string, string>} */
628
+ const finalNames = new Map();
629
+ for (const pkg of packages) {
630
+ if (!pkg.name) {
631
+ continue;
632
+ }
633
+ const finalName = renamed.get(pkg.name) ?? pkg.name;
634
+ const owner = finalNames.get(finalName);
635
+ if (owner) {
636
+ throw new Error(
637
+ `Cannot rename ${fromScope} to ${toScope}: ${pkg.name} and ${owner} would both be named ${finalName}.`,
638
+ );
639
+ }
640
+ finalNames.set(finalName, pkg.name);
641
+ }
642
+
643
+ // Rewrite in memory first. A dependency that cannot be pointed at its renamed
644
+ // package has to fail before anything is written, or the workspace is left
645
+ // half renamed with nothing to restore it.
646
+ const rewritten = await Promise.all(
647
+ packages.map(async (pkg) => {
648
+ const packageJson = await readPackageJson(pkg.path);
649
+ const label = pkg.name ?? pkg.path;
650
+ /** @type {string[]} */
651
+ const problems = [];
652
+ let changed = false;
653
+
654
+ const newName = pkg.name ? renamed.get(pkg.name) : undefined;
655
+ if (newName) {
656
+ packageJson.name = newName;
657
+ changed = true;
658
+ }
659
+
660
+ // peerDependencies are deliberately absent: a peer is supplied by the
661
+ // consumer, who installs the package under its original name. An alias
662
+ // range would be unsatisfiable for them.
663
+ for (const deps of [
664
+ packageJson.dependencies,
665
+ packageJson.devDependencies,
666
+ packageJson.optionalDependencies,
667
+ ]) {
668
+ if (!deps) {
669
+ continue;
670
+ }
671
+ for (const [depName, spec] of Object.entries(deps)) {
672
+ if (!spec) {
673
+ continue;
674
+ }
675
+
676
+ const existingTarget = aliasTarget(spec);
677
+ if (existingTarget) {
678
+ if (renamed.has(existingTarget)) {
679
+ problems.push(
680
+ `"${depName}" in ${label} already aliases ${existingTarget}, which is being renamed. Point it at the package directly so it can be rewritten.`,
681
+ );
682
+ }
683
+ // Otherwise it already aliases what it should, as a re-run does.
684
+ continue;
685
+ }
686
+
687
+ const target = renamed.get(depName);
688
+ if (!target) {
689
+ continue;
690
+ }
691
+ if (!spec.startsWith('workspace:')) {
692
+ // Only `workspace:` specs can be aliased. Anything else would keep
693
+ // resolving the original name from the registry after the rename.
694
+ problems.push(
695
+ `"${depName}" in ${label} is required as "${spec}" rather than a workspace: dependency, so it cannot be pointed at ${target}.`,
696
+ );
697
+ continue;
698
+ }
699
+ deps[depName] = `workspace:${target}@${spec.slice('workspace:'.length)}`;
700
+ changed = true;
701
+ }
702
+ }
703
+
704
+ return { path: pkg.path, packageJson, changed, problems };
705
+ }),
706
+ );
707
+
708
+ const problems = rewritten.flatMap((entry) => entry.problems);
709
+ if (problems.length > 0) {
710
+ throw new Error(`Cannot rename ${fromScope} to ${toScope}:\n ${problems.join('\n ')}`);
711
+ }
712
+
713
+ await Promise.all(
714
+ rewritten
715
+ .filter((entry) => entry.changed)
716
+ .map((entry) => writePackageJson(entry.path, entry.packageJson)),
717
+ );
718
+
719
+ return renamed;
720
+ }
721
+
331
722
  /**
332
723
  * Resolve a package@version specifier to an exact version
333
724
  * @param {string} packageSpec - Package specifier in format "package@version"