@mui/internal-code-infra 0.0.4-canary.1 → 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 (146) hide show
  1. package/LICENSE +1 -1
  2. package/README.md +22 -8
  3. package/build/babel-config.d.mts +11 -3
  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 +16 -2
  15. package/build/cli/cmdNetlifyIgnore.d.mts +12 -2
  16. package/build/cli/cmdPublish.d.mts +24 -4
  17. package/build/cli/cmdPublishCanary.d.mts +21 -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 +200 -7
  45. package/build/utils/testUtils.d.mts +28 -0
  46. package/build/utils/typescript.d.mts +6 -16
  47. package/package.json +83 -56
  48. package/src/babel-config.mjs +9 -3
  49. package/src/brokenLinksChecker/crawlWorker.mjs +240 -0
  50. package/src/brokenLinksChecker/index.mjs +263 -188
  51. package/src/build-env.d.ts +13 -0
  52. package/src/changelog/fetchChangelogs.mjs +8 -2
  53. package/src/changelog/renderChangelog.mjs +1 -1
  54. package/src/changelog/types.ts +3 -1
  55. package/src/cli/cmdBuild.mjs +51 -85
  56. package/src/cli/cmdListWorkspaces.mjs +16 -3
  57. package/src/cli/cmdNetlifyIgnore.mjs +34 -93
  58. package/src/cli/cmdPublish.mjs +105 -36
  59. package/src/cli/cmdPublishCanary.mjs +145 -109
  60. package/src/cli/cmdPublishNewPackage.mjs +31 -8
  61. package/src/cli/cmdRenameScope.mjs +76 -0
  62. package/src/cli/cmdSetVersionOverrides.mjs +8 -9
  63. package/src/cli/cmdVale.mjs +513 -0
  64. package/src/cli/index.mjs +4 -0
  65. package/src/cli/packageJson.d.ts +2 -3
  66. package/src/eslint/baseConfig.mjs +51 -19
  67. package/src/eslint/docsConfig.mjs +2 -1
  68. package/src/eslint/mui/config.mjs +24 -4
  69. package/src/eslint/mui/index.mjs +6 -0
  70. package/src/eslint/mui/rules/no-floating-cleanup.mjs +187 -0
  71. package/src/eslint/mui/rules/no-guarded-throw.mjs +115 -0
  72. package/src/eslint/mui/rules/no-presentation-role.mjs +60 -0
  73. package/src/eslint/mui/rules/nodeEnvUtils.mjs +52 -0
  74. package/src/eslint/mui/rules/require-dev-wrapper.mjs +25 -40
  75. package/src/estree-typescript.d.ts +1 -1
  76. package/src/remark/config.mjs +157 -0
  77. package/src/remark/createLintTester.mjs +19 -0
  78. package/src/remark/firstBlockHeading.mjs +87 -0
  79. package/src/remark/gitDiff.mjs +43 -0
  80. package/src/remark/noSpaceInLinks.mjs +42 -0
  81. package/src/remark/straightQuotes.mjs +31 -0
  82. package/src/remark/tableAlignment.mjs +23 -0
  83. package/src/remark/terminalLanguage.mjs +19 -0
  84. package/src/stylelint/index.mjs +2 -2
  85. package/src/untyped-plugins.d.ts +14 -14
  86. package/src/utils/build.mjs +604 -270
  87. package/src/utils/git.mjs +27 -7
  88. package/src/utils/pnpm.mjs +549 -26
  89. package/src/utils/testUtils.mjs +53 -0
  90. package/src/utils/typescript.mjs +23 -42
  91. package/vale/.vale.ini +1 -0
  92. package/vale/styles/MUI/CorrectReferenceAllCases.yml +42 -0
  93. package/vale/styles/MUI/CorrectRererenceCased.yml +14 -0
  94. package/vale/styles/MUI/GoogleLatin.yml +11 -0
  95. package/vale/styles/MUI/MuiBrandName.yml +22 -0
  96. package/vale/styles/MUI/NoBritish.yml +112 -0
  97. package/vale/styles/MUI/NoCompanyName.yml +17 -0
  98. package/build/markdownlint/duplicate-h1.d.mts +0 -56
  99. package/build/markdownlint/git-diff.d.mts +0 -11
  100. package/build/markdownlint/index.d.mts +0 -52
  101. package/build/markdownlint/straight-quotes.d.mts +0 -11
  102. package/build/markdownlint/table-alignment.d.mts +0 -11
  103. package/build/markdownlint/terminal-language.d.mts +0 -11
  104. package/src/brokenLinksChecker/__fixtures__/static-site/broken-links.html +0 -20
  105. package/src/brokenLinksChecker/__fixtures__/static-site/broken-targets.html +0 -22
  106. package/src/brokenLinksChecker/__fixtures__/static-site/example.md +0 -20
  107. package/src/brokenLinksChecker/__fixtures__/static-site/external-links.html +0 -21
  108. package/src/brokenLinksChecker/__fixtures__/static-site/ignored-page.html +0 -17
  109. package/src/brokenLinksChecker/__fixtures__/static-site/index.html +0 -28
  110. package/src/brokenLinksChecker/__fixtures__/static-site/known-targets.json +0 -5
  111. package/src/brokenLinksChecker/__fixtures__/static-site/nested/page.html +0 -21
  112. package/src/brokenLinksChecker/__fixtures__/static-site/orphaned-page.html +0 -20
  113. package/src/brokenLinksChecker/__fixtures__/static-site/page-with-api-links.html +0 -20
  114. package/src/brokenLinksChecker/__fixtures__/static-site/page-with-custom-targets.html +0 -24
  115. package/src/brokenLinksChecker/__fixtures__/static-site/page-with-ignored-content.html +0 -28
  116. package/src/brokenLinksChecker/__fixtures__/static-site/page-with-known-target-links.html +0 -19
  117. package/src/brokenLinksChecker/__fixtures__/static-site/unclosed-tags.html +0 -1
  118. package/src/brokenLinksChecker/__fixtures__/static-site/valid.html +0 -20
  119. package/src/brokenLinksChecker/__fixtures__/static-site/with-anchors.html +0 -31
  120. package/src/brokenLinksChecker/index.test.ts +0 -261
  121. package/src/changelog/categorizeCommits.test.ts +0 -319
  122. package/src/changelog/filterCommits.test.ts +0 -363
  123. package/src/changelog/parseCommitLabels.test.ts +0 -509
  124. package/src/changelog/renderChangelog.test.ts +0 -378
  125. package/src/changelog/sortSections.test.ts +0 -199
  126. package/src/eslint/mui/rules/add-undef-to-optional.test.mjs +0 -361
  127. package/src/eslint/mui/rules/consistent-production-guard.test.mjs +0 -162
  128. package/src/eslint/mui/rules/disallow-active-elements-as-key-event-target.test.mjs +0 -66
  129. package/src/eslint/mui/rules/disallow-react-api-in-server-components.test.mjs +0 -305
  130. package/src/eslint/mui/rules/docgen-ignore-before-comment.test.mjs +0 -52
  131. package/src/eslint/mui/rules/flatten-parentheses.test.mjs +0 -245
  132. package/src/eslint/mui/rules/mui-name-matches-component-name.test.mjs +0 -247
  133. package/src/eslint/mui/rules/no-empty-box.test.mjs +0 -40
  134. package/src/eslint/mui/rules/no-styled-box.test.mjs +0 -73
  135. package/src/eslint/mui/rules/require-dev-wrapper.test.mjs +0 -265
  136. package/src/eslint/mui/rules/rules-of-use-theme-variants.test.mjs +0 -149
  137. package/src/eslint/mui/rules/straight-quotes.test.mjs +0 -67
  138. package/src/markdownlint/duplicate-h1.mjs +0 -69
  139. package/src/markdownlint/git-diff.mjs +0 -31
  140. package/src/markdownlint/index.mjs +0 -62
  141. package/src/markdownlint/straight-quotes.mjs +0 -26
  142. package/src/markdownlint/table-alignment.mjs +0 -42
  143. package/src/markdownlint/terminal-language.mjs +0 -19
  144. package/src/utils/build.test.mjs +0 -705
  145. package/src/utils/template.test.mjs +0 -133
  146. package/src/utils/typescript.test.mjs +0 -380
@@ -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,8 +51,8 @@ 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
55
+ * @property {string[]} [filter] - Same as filtering packages with --filter in pnpm. Only include packages matching the filter. See https://pnpm.io/filtering.
51
56
  */
52
57
 
53
58
  /**
@@ -58,10 +63,6 @@ import * as semver from 'semver';
58
63
  * @returns {Promise<PublicPackage[]>} Array of packages
59
64
  *
60
65
  * @overload
61
- * @param {{ nonPublishedOnly: true } & GetWorkspacePackagesOptions} [options={}] - Options for filtering packages
62
- * @returns {Promise<PublicPackage[]>} Array of packages
63
- *
64
- * @overload
65
66
  * @param {{ publicOnly?: false | undefined } & GetWorkspacePackagesOptions} [options={}] - Options for filtering packages
66
67
  * @returns {Promise<PrivatePackage[]>} Array of packages
67
68
  *
@@ -73,15 +74,38 @@ import * as semver from 'semver';
73
74
  * @returns {Promise<(PrivatePackage | PublicPackage)[]>} Array of packages
74
75
  */
75
76
  export async function getWorkspacePackages(options = {}) {
76
- const { sinceRef = null, publicOnly = false, nonPublishedOnly = false } = options;
77
+ const { sinceRef = null, publicOnly = false, filter = [] } = options;
78
+
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
+ };
77
88
 
78
- // Build command with conditional filter
79
- const filterArg = sinceRef ? ['--filter', `...[${sinceRef}]`] : [];
80
- const result = options.cwd
81
- ? await $({ cwd: options.cwd })`pnpm ls -r --json --depth -1 ${filterArg}`
82
- : await $`pnpm ls -r --json --depth -1 ${filterArg}`;
83
- /** @type {PnpmListResultItem[]} */
84
- const packageData = JSON.parse(result.stdout);
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));
108
+ }
85
109
 
86
110
  // Filter packages based on options
87
111
  const filteredPackages = packageData.flatMap((pkg) => {
@@ -99,24 +123,115 @@ export async function getWorkspacePackages(options = {}) {
99
123
  ];
100
124
  });
101
125
 
102
- if (nonPublishedOnly) {
103
- // Check if any of the packages are new/need manual publishing first.
104
- const filteredPublicPackages = filteredPackages.filter((pkg) => !pkg.isPrivate);
126
+ return filteredPackages;
127
+ }
105
128
 
106
- const results = await Promise.all(
107
- filteredPublicPackages.map(async (pkg) => {
108
- const url = `${process.env.npm_config_registry || 'https://registry.npmjs.org'}/${pkg.name}`;
109
- return fetch(url).then((res) => res.status === 404);
110
- }),
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 },
111
157
  );
112
- return filteredPublicPackages.filter((_pkg, index) => !!results[index]);
113
158
  }
159
+ registryUrl.pathname = `${registryUrl.pathname.replace(/\/+$/, '')}/`;
160
+ return registryUrl.href;
161
+ }
114
162
 
115
- 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;
176
+ }
177
+
178
+ /**
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;
116
187
  }
117
188
 
118
189
  /**
119
- * Get package version info from registry
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
+ *
120
235
  * @param {string} packageName - Name of the package
121
236
  * @param {string} baseVersion - Base version to check
122
237
  * @returns {Promise<VersionInfo>} Version information
@@ -148,11 +263,17 @@ export async function getPackageVersionInfo(packageName, baseVersion) {
148
263
  }
149
264
  }
150
265
 
266
+ /**
267
+ * @typedef {Object} PublishSummaryEntry
268
+ * @property {string} name
269
+ * @property {string} version
270
+ */
271
+
151
272
  /**
152
273
  * Publish packages with the given options
153
274
  * @param {PublicPackage[]} packages - Packages to publish
154
275
  * @param {PublishOptions} [options={}] - Publishing options
155
- * @returns {Promise<void>}
276
+ * @returns {Promise<PublishSummaryEntry[]>}
156
277
  */
157
278
  export async function publishPackages(packages, options = {}) {
158
279
  const args = [];
@@ -172,7 +293,202 @@ export async function publishPackages(packages, options = {}) {
172
293
  args.push('--no-git-checks');
173
294
  }
174
295
 
175
- 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);
313
+ }
314
+
315
+ /**
316
+ * @typedef {Object} GetTransitiveDependenciesOptions
317
+ * @property {Map<string, string>} [workspacePathByName] - Map of workspace package name to directory path
318
+ * @property {boolean} [includeDev=true] - Whether to include devDependencies in the traversal
319
+ */
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
+
337
+ /**
338
+ * Get all transitive workspace dependencies for a set of packages.
339
+ *
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.
348
+ *
349
+ * @param {string[]} packageNames - Package names to start the traversal from
350
+ * @param {GetTransitiveDependenciesOptions} [options]
351
+ * @returns {Promise<Set<string>>} All reachable workspace package names, including the input packages themselves
352
+ */
353
+ export async function getTransitiveDependencies(packageNames, options = {}) {
354
+ const { includeDev = true, workspacePathByName = new Map() } = options;
355
+
356
+ /** @type {Map<string, Promise<Set<string>>>} */
357
+ const cache = new Map();
358
+
359
+ /**
360
+ * @param {string} packageName
361
+ * @returns {Promise<Set<string>>}
362
+ */
363
+ function collectDeps(packageName) {
364
+ const cached = cache.get(packageName);
365
+ if (cached) {
366
+ return cached;
367
+ }
368
+
369
+ const promise = (async () => {
370
+ const packagePath = workspacePathByName.get(packageName);
371
+ if (!packagePath) {
372
+ throw new Error(`Workspace "${packageName}" not found`);
373
+ }
374
+
375
+ const pkgJson = await readPackageJson(packagePath);
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
+ });
389
+
390
+ const recursiveResults = await Promise.all(workspaceDeps.map(collectDeps));
391
+ return new Set([...workspaceDeps, ...recursiveResults.flatMap((s) => [...s])]);
392
+ })();
393
+
394
+ cache.set(packageName, promise);
395
+ return promise;
396
+ }
397
+
398
+ for (const name of packageNames) {
399
+ if (!workspacePathByName.has(name)) {
400
+ throw new Error(`Workspace "${name}" not found`);
401
+ }
402
+ }
403
+
404
+ const results = await Promise.all(packageNames.map(collectDeps));
405
+ return new Set([...packageNames, ...results.flatMap((s) => [...s])]);
406
+ }
407
+
408
+ /**
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.
418
+ *
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
422
+ * @returns {Promise<{issues: string[]}>}
423
+ * List of human-readable issue strings. Empty when the dependency set is valid.
424
+ * @internal
425
+ */
426
+ export async function checkPublishDependencies(
427
+ packages,
428
+ workspacePackageByName,
429
+ workspacePathByName,
430
+ ) {
431
+ const publishedNames = new Set(packages.map((pkg) => pkg.name));
432
+
433
+ const transitiveDeps = await getTransitiveDependencies(
434
+ packages.map((pkg) => pkg.name),
435
+ { includeDev: false, workspacePathByName },
436
+ );
437
+
438
+ /** @type {Set<string>} */
439
+ const privateButRequired = new Set();
440
+ /** @type {Set<string>} */
441
+ const missingFromPublish = new Set();
442
+
443
+ for (const depName of transitiveDeps) {
444
+ if (publishedNames.has(depName)) {
445
+ continue;
446
+ }
447
+ const workspacePkg = workspacePackageByName.get(depName);
448
+ if (workspacePkg?.isPrivate) {
449
+ privateButRequired.add(depName);
450
+ } else {
451
+ missingFromPublish.add(depName);
452
+ }
453
+ }
454
+
455
+ /** @type {string[]} */
456
+ const issues = [];
457
+
458
+ if (privateButRequired.size > 0) {
459
+ issues.push(
460
+ `The following private workspace packages are required as dependencies but cannot be published: ${[...privateButRequired].join(', ')}`,
461
+ );
462
+ }
463
+
464
+ if (missingFromPublish.size > 0) {
465
+ issues.push(
466
+ `The following workspace packages are required as dependencies but are not included in the publish set: ${[...missingFromPublish].join(', ')}. Add them to the --filter list.`,
467
+ );
468
+ }
469
+
470
+ return { issues };
471
+ }
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);
176
492
  }
177
493
 
178
494
  /**
@@ -196,6 +512,213 @@ export async function writePackageJson(packagePath, packageJson) {
196
512
  await fs.writeFile(path.join(packagePath, 'package.json'), content);
197
513
  }
198
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
+
199
722
  /**
200
723
  * Resolve a package@version specifier to an exact version
201
724
  * @param {string} packageSpec - Package specifier in format "package@version"
@@ -0,0 +1,53 @@
1
+ import * as fs from 'node:fs/promises';
2
+ import * as os from 'node:os';
3
+ import * as path from 'node:path';
4
+ import { onTestFinished } from 'vitest';
5
+
6
+ import { writePackageJson } from './pnpm.mjs';
7
+
8
+ /**
9
+ * Creates a temporary directory and registers an `onTestFinished` hook to
10
+ * remove it automatically when the current test ends — even if the test throws.
11
+ *
12
+ * @returns {Promise<string>} The path of the created temporary directory.
13
+ */
14
+ export async function makeTempDir() {
15
+ const tmpDir = await fs.mkdtemp(path.join(os.tmpdir(), 'code-infra-test-'));
16
+ onTestFinished(async () => {
17
+ await fs.rm(tmpDir, { recursive: true, force: true });
18
+ });
19
+ return tmpDir;
20
+ }
21
+
22
+ /**
23
+ * Write a package.json into a subdirectory of a temp workspace.
24
+ *
25
+ * @param {string} root - Workspace root
26
+ * @param {string} dir - Subdirectory to create
27
+ * @param {object} pkgJson - Manifest contents
28
+ * @returns {Promise<string>} The package directory
29
+ */
30
+ export async function writePackage(root, dir, pkgJson) {
31
+ const pkgDir = path.join(root, dir);
32
+ await fs.mkdir(pkgDir, { recursive: true });
33
+ await writePackageJson(pkgDir, pkgJson);
34
+ return pkgDir;
35
+ }
36
+
37
+ /**
38
+ * @param {string} name
39
+ * @param {string} pkgPath
40
+ * @returns {import('./pnpm.mjs').PublicPackage}
41
+ */
42
+ export function publicPkg(name, pkgPath) {
43
+ return { name, version: '1.0.0', path: pkgPath, isPrivate: false };
44
+ }
45
+
46
+ /**
47
+ * @param {string} name
48
+ * @param {string} pkgPath
49
+ * @returns {import('./pnpm.mjs').PrivatePackage}
50
+ */
51
+ export function privatePkg(name, pkgPath) {
52
+ return { name, version: '1.0.0', path: pkgPath, isPrivate: true };
53
+ }