@mui/internal-code-infra 0.1.1-canary.4 → 0.1.1-canary.41

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 (102) hide show
  1. package/README.md +36 -4
  2. package/build/babel-config.d.mts +7 -1
  3. package/build/changelog/changelogChanges.d.mts +42 -0
  4. package/build/changelog/changelogGrouping.d.mts +52 -0
  5. package/build/changelog/changelogMarkdown.d.mts +69 -0
  6. package/build/changelog/changelogTags.d.mts +15 -0
  7. package/build/changelog/changelogTitle.d.mts +28 -0
  8. package/build/changelog/fetchChangelogData.d.mts +16 -0
  9. package/build/changelog/fetchChangelogs.d.mts +11 -12
  10. package/build/changelog/index.d.mts +25 -0
  11. package/build/changelog/octokit.d.mts +7 -0
  12. package/build/changelog/types.d.ts +174 -0
  13. package/build/eslint/baseConfig.d.mts +1 -1
  14. package/build/eslint/index.d.mts +1 -0
  15. package/build/eslint/mui/rules/no-constructor-assigned-field.d.mts +50 -0
  16. package/build/eslint/nodeSupportConfig.d.mts +11 -0
  17. package/build/eslint/packageJsonConfig.d.mts +7 -0
  18. package/build/remark/config.d.mts +5 -14
  19. package/build/utils/babelPlugin.d.mts +8 -0
  20. package/build/utils/build.d.mts +22 -0
  21. package/build/utils/cjsSourcesPlugin.d.mts +11 -0
  22. package/build/utils/credentials.d.mts +2 -2
  23. package/build/utils/dtsExportsPlugin.d.mts +8 -0
  24. package/build/utils/dtsNamespacesPlugin.d.mts +19 -0
  25. package/build/utils/fileUrlEntriesPlugin.d.mts +9 -0
  26. package/build/utils/getPublishedPkgJson.d.mts +20 -0
  27. package/build/utils/git.d.mts +30 -9
  28. package/build/utils/github.d.mts +8 -0
  29. package/build/utils/jsNamespacesPlugin.d.mts +13 -0
  30. package/build/utils/pnpm.d.mts +67 -3
  31. package/build/utils/publint.d.mts +6 -0
  32. package/build/utils/rolldownOutput.d.mts +38 -0
  33. package/build/utils/testUtils.d.mts +8 -0
  34. package/build/utils/typescript.d.mts +17 -0
  35. package/package.json +61 -49
  36. package/src/babel-config.mjs +35 -1
  37. package/src/brokenLinksChecker/index.mjs +8 -1
  38. package/src/changelog/changelogChanges.mjs +479 -0
  39. package/src/changelog/changelogGrouping.mjs +148 -0
  40. package/src/changelog/changelogMarkdown.mjs +110 -0
  41. package/src/changelog/changelogTags.mjs +34 -0
  42. package/src/changelog/changelogTitle.mjs +56 -0
  43. package/src/changelog/fetchChangelogData.mjs +172 -0
  44. package/src/changelog/fetchChangelogs.mjs +47 -34
  45. package/src/changelog/index.mjs +34 -0
  46. package/src/changelog/octokit.mjs +35 -0
  47. package/src/changelog/types.ts +187 -0
  48. package/src/cli/cmdBaseline.mjs +31 -0
  49. package/src/cli/cmdBuild.mjs +20 -89
  50. package/src/cli/cmdBuildNew.mjs +474 -0
  51. package/src/cli/cmdNetlifyIgnore.mjs +14 -7
  52. package/src/cli/cmdPublish.mjs +17 -3
  53. package/src/cli/cmdPublishNewPackage.mjs +11 -4
  54. package/src/cli/cmdValidateBuiltTypes.mjs +447 -32
  55. package/src/cli/index.mjs +4 -0
  56. package/src/eslint/baseConfig.mjs +10 -2
  57. package/src/eslint/docsConfig.mjs +28 -10
  58. package/src/eslint/index.mjs +1 -0
  59. package/src/eslint/jsonConfig.mjs +2 -1
  60. package/src/eslint/mui/config.mjs +16 -1
  61. package/src/eslint/mui/index.mjs +2 -0
  62. package/src/eslint/mui/rules/disallow-react-api-in-server-components.mjs +4 -1
  63. package/src/eslint/mui/rules/no-constructor-assigned-field.mjs +183 -0
  64. package/src/eslint/nodeSupportConfig.mjs +70 -0
  65. package/src/eslint/packageJsonConfig.mjs +50 -0
  66. package/src/eslint/testConfig.mjs +4 -2
  67. package/src/remark/config.mjs +60 -13
  68. package/src/utils/babelPlugin.mjs +52 -0
  69. package/src/utils/build.mjs +81 -0
  70. package/src/utils/cjsSourcesPlugin.mjs +92 -0
  71. package/src/utils/credentials.mjs +4 -3
  72. package/src/utils/dtsExportsPlugin.mjs +103 -0
  73. package/src/utils/dtsNamespacesPlugin.mjs +226 -0
  74. package/src/utils/extractErrorCodes.mjs +1 -3
  75. package/src/utils/fileUrlEntriesPlugin.mjs +84 -0
  76. package/src/utils/getPublishedPkgJson.mjs +86 -0
  77. package/src/utils/git.mjs +107 -46
  78. package/src/utils/github.mjs +27 -0
  79. package/src/utils/jsNamespacesPlugin.mjs +505 -0
  80. package/src/utils/pnpm.mjs +126 -25
  81. package/src/utils/publint.mjs +34 -0
  82. package/src/utils/rolldownOutput.mjs +70 -0
  83. package/src/utils/testUtils.mjs +26 -0
  84. package/src/utils/typescript.mjs +23 -13
  85. package/vale/styles/MUI/GoogleLatin.yml +5 -2
  86. package/build/cli/cmdArgosPush.d.mts +0 -18
  87. package/build/cli/cmdBuild.d.mts +0 -64
  88. package/build/cli/cmdCopyFiles.d.mts +0 -20
  89. package/build/cli/cmdExtractErrorCodes.d.mts +0 -6
  90. package/build/cli/cmdGenerateChangelog.d.mts +0 -32
  91. package/build/cli/cmdGithubAuth.d.mts +0 -11
  92. package/build/cli/cmdListWorkspaces.d.mts +0 -29
  93. package/build/cli/cmdNetlifyIgnore.d.mts +0 -17
  94. package/build/cli/cmdPublish.d.mts +0 -32
  95. package/build/cli/cmdPublishCanary.d.mts +0 -34
  96. package/build/cli/cmdPublishNewPackage.d.mts +0 -17
  97. package/build/cli/cmdRenameScope.d.mts +0 -18
  98. package/build/cli/cmdSetVersionOverrides.d.mts +0 -9
  99. package/build/cli/cmdVale.d.mts +0 -46
  100. package/build/cli/cmdValidateBuiltTypes.d.mts +0 -2
  101. package/build/cli/index.d.mts +0 -1
  102. package/vale/styles/MUI/CorrectRererenceCased.yml +0 -14
@@ -14,10 +14,21 @@ import pluginTransformInlineEnvVars from './babelPluginInlineEnvironmentVariable
14
14
  // Plain TypeScript, ie. files that can't contain JSX.
15
15
  const TS_WITHOUT_JSX = /\.[cm]?ts$/;
16
16
 
17
+ // Work `code-infra build-new` leaves to Oxc and Rolldown.
18
+ const OXC_HANDLED_PLUGINS = new Set([
19
+ 'babel-plugin-transform-inline-environment-variables',
20
+ 'babel-plugin-transform-import-meta',
21
+ '@mui/internal-babel-plugin-resolve-imports',
22
+ ]);
23
+
17
24
  /**
18
25
  * @typedef {'annotation' | 'syntax' | 'infer' | 'all'} ReactCompilationMode
19
26
  */
20
27
 
28
+ /**
29
+ * @typedef {'babel' | 'oxc'} Compiler
30
+ */
31
+
21
32
  /**
22
33
  * @param {Object} param0
23
34
  * @param {boolean} [param0.debug]
@@ -30,6 +41,7 @@ const TS_WITHOUT_JSX = /\.[cm]?ts$/;
30
41
  * @param {string} [param0.reactCompilerReactVersion]
31
42
  * @param {ReactCompilationMode} [param0.reactCompilerMode]
32
43
  * @param {{ allowedCallees?: Record<string, string[]> }} [param0.displayName] - Options for the display name plugin.
44
+ * @param {Compiler} [param0.compiler] - `oxc` keeps only the plugins Oxc has no equivalent for.
33
45
  * @returns {import('@babel/core').InputOptions} The base Babel configuration.
34
46
  */
35
47
  export function getBaseConfig({
@@ -43,6 +55,7 @@ export function getBaseConfig({
43
55
  reactCompilerReactVersion,
44
56
  reactCompilerMode,
45
57
  displayName,
58
+ compiler = 'babel',
46
59
  }) {
47
60
  /**
48
61
  * @type {import('@babel/preset-env').Options}
@@ -124,7 +137,8 @@ export function getBaseConfig({
124
137
  ]);
125
138
  }
126
139
 
127
- return {
140
+ /** @type {import('@babel/core').InputOptions} */
141
+ const config = {
128
142
  assumptions: {
129
143
  noDocumentAll: true,
130
144
  // With our case these assumptions are safe, and the
@@ -170,6 +184,21 @@ export function getBaseConfig({
170
184
  },
171
185
  ],
172
186
  };
187
+ if (compiler === 'babel') {
188
+ return config;
189
+ }
190
+
191
+ return {
192
+ assumptions: config.assumptions,
193
+ ignore: config.ignore,
194
+ plugins: [
195
+ ...plugins.filter(
196
+ (plugin) => !OXC_HANDLED_PLUGINS.has(/** @type {[unknown, unknown, string]} */ (plugin)[2]),
197
+ ),
198
+ // Oxc only marks JSX as pure, not React calls such as `createContext()`.
199
+ [pluginReactPureAnnotations, {}, '@babel/plugin-transform-react-pure-annotations'],
200
+ ],
201
+ };
173
202
  }
174
203
 
175
204
  /**
@@ -188,12 +217,16 @@ export default function getBabelConfig(api) {
188
217
  let bundle;
189
218
  /** @type {boolean} */
190
219
  let noResolveImports;
220
+ /** @type {Compiler} */
221
+ let compiler = 'babel';
191
222
 
192
223
  if (api.env) {
193
224
  // legacy
194
225
  bundle = api.env(['regressions', 'stable']) ? 'esm' : 'cjs';
195
226
  // eslint-disable-next-line mui/consistent-production-guard
196
227
  noResolveImports = api.env('test') || process.env.NODE_ENV === 'test';
228
+ compiler =
229
+ api.caller((caller) => /** @type {{ compiler?: Compiler }} */ (caller)?.compiler) ?? compiler;
197
230
  } else {
198
231
  bundle = api.bundle || 'esm';
199
232
  noResolveImports = api.noResolveImports || false;
@@ -211,5 +244,6 @@ export default function getBabelConfig(api) {
211
244
  noResolveImports,
212
245
  reactCompilerReactVersion: process.env.MUI_REACT_COMPILER_REACT_VERSION,
213
246
  reactCompilerMode: /** @type {ReactCompilationMode} */ (process.env.MUI_REACT_COMPILER_MODE),
247
+ compiler,
214
248
  });
215
249
  }
@@ -621,6 +621,8 @@ export async function crawl(rawOptions) {
621
621
 
622
622
  /** @type {AbortController | null} */
623
623
  let controller = null;
624
+ /** @type {Promise<unknown> | null} */
625
+ let serverExited = null;
624
626
 
625
627
  try {
626
628
  if (options.startCommand) {
@@ -630,6 +632,7 @@ export async function crawl(rawOptions) {
630
632
  stdout: 'pipe',
631
633
  stderr: 'pipe',
632
634
  cancelSignal: controller.signal,
635
+ killDescendants: true,
633
636
  env: {
634
637
  FORCE_COLOR: '1',
635
638
  ...process.env,
@@ -640,7 +643,10 @@ export async function crawl(rawOptions) {
640
643
  const serverPrefix = chalk.gray('server: ');
641
644
  appProcess.stdout.pipe(prefixLines(serverPrefix)).pipe(process.stdout);
642
645
  appProcess.stderr.pipe(prefixLines(serverPrefix)).pipe(process.stderr);
643
- appProcess.catch(() => {});
646
+ // Settles once the whole process tree has exited: descendants inherit the
647
+ // stdout/stderr pipes, so execa waits for them too, and escalates to SIGKILL
648
+ // after `forceKillAfterDelay` when a server is slow to shut down.
649
+ serverExited = appProcess.catch(() => {});
644
650
 
645
651
  // Poll the first page we are about to crawl (resolved against host) so we
646
652
  // wait for the actual entry point to be serveable rather than the
@@ -660,6 +666,7 @@ export async function crawl(rawOptions) {
660
666
  if (controller) {
661
667
  console.log(chalk.blue('Stopping server...'));
662
668
  controller.abort();
669
+ await serverExited;
663
670
  }
664
671
  }
665
672
  }
@@ -0,0 +1,479 @@
1
+ import { mapAsync } from 'es-toolkit/array';
2
+
3
+ import { getRateLimitRetryTime } from '../utils/github.mjs';
4
+
5
+ /**
6
+ * @typedef {import('@octokit/rest').Octokit} Octokit
7
+ * @typedef {import('./types.ts').GitHubRepository} GitHubRepository
8
+ * @typedef {import('./types.ts').ChangelogAuthor} ChangelogAuthor
9
+ * @typedef {import('./types.ts').ChangelogChange} ChangelogChange
10
+ * @typedef {Awaited<ReturnType<Octokit['repos']['compareCommitsWithBasehead']>>['data']['commits'][number]} Commit
11
+ */
12
+
13
+ /**
14
+ * What is needed from a pull request. Listing and getting one return different supersets of this.
15
+ *
16
+ * @typedef {Object} PullRequest
17
+ * @property {number} number
18
+ * @property {string} title
19
+ * @property {string | null} body
20
+ * @property {{ login: string, type: string } | null} user
21
+ * @property {{ login: string, type: string }[] | null} [assignees]
22
+ * @property {string} author_association
23
+ * @property {{ name?: string }[]} labels
24
+ */
25
+
26
+ /** @type {Record<string, ChangelogAuthor['association']>} */
27
+ const ASSOCIATIONS = {
28
+ OWNER: 'team',
29
+ MEMBER: 'team',
30
+ COLLABORATOR: 'community',
31
+ CONTRIBUTOR: 'community',
32
+ FIRST_TIMER: 'first-timer',
33
+ FIRST_TIME_CONTRIBUTOR: 'first-timer',
34
+ MANNEQUIN: 'first-timer',
35
+ NONE: 'first-timer',
36
+ };
37
+
38
+ const BREAKING_CHANGE_LABELS = ['breaking', 'breaking change'];
39
+ const CHERRY_PICK_LABEL = 'cherry-pick';
40
+ const COPILOT = 'Copilot';
41
+ const PULL_REFERENCE =
42
+ /(?:https:\/\/github\.com\/(?<urlOwner>[\w.-]+)\/(?<urlRepo>[\w.-]+)\/pull\/|(?:(?<owner>[\w.-]+)\/(?<repo>[\w.-]+))?#)(?<number>\d+)/;
43
+ // Unnamed, so that the pattern can be repeated.
44
+ const ANY_PULL_REFERENCE = PULL_REFERENCE.source.replaceAll(/\(\?<\w+>/g, '(?:');
45
+ // Anchored to the start of a line: changelogs quoted in dependency bumps mention cherry-picks too.
46
+ const CHERRY_PICK_LINE = new RegExp(
47
+ `^cherry[- ]pick(?:ed|s)?(?: of| from)?:? (${ANY_PULL_REFERENCE}(?:(?:,? and |, ?| )${ANY_PULL_REFERENCE})*)`,
48
+ 'gim',
49
+ );
50
+
51
+ /**
52
+ * @param {PullRequest} pull
53
+ * @param {GitHubRepository} repository - Where the pull request is
54
+ * @returns {(GitHubRepository & { number: number, text: string })[]}
55
+ */
56
+ function getCherryPickReferences(pull, repository) {
57
+ return [...(pull.body ?? '').matchAll(CHERRY_PICK_LINE)].flatMap(([, references]) =>
58
+ [...references.matchAll(new RegExp(PULL_REFERENCE, 'g'))].map(({ groups = {} }) => {
59
+ const owner = groups.urlOwner ?? groups.owner ?? repository.owner;
60
+ const repo = groups.urlRepo ?? groups.repo ?? repository.repo;
61
+ const isSameRepository = owner === repository.owner && repo === repository.repo;
62
+ return {
63
+ owner,
64
+ repo,
65
+ number: Number(groups.number),
66
+ // As written in a title, also when the body has a link.
67
+ text: isSameRepository ? `#${groups.number}` : `${owner}/${repo}#${groups.number}`,
68
+ };
69
+ }),
70
+ );
71
+ }
72
+
73
+ /**
74
+ * Copilot works for a person, so what it does isn't the routine work of other bots.
75
+ *
76
+ * @param {{ login?: string, type?: string } | null} [account]
77
+ */
78
+ function isBotAccount(account) {
79
+ return account?.type === 'Bot' && account.login !== COPILOT;
80
+ }
81
+
82
+ /**
83
+ * @param {any} error
84
+ */
85
+ function isForbidden(error) {
86
+ return error.status === 403 && getRateLimitRetryTime(error) === null;
87
+ }
88
+
89
+ /**
90
+ * @template {string} Key
91
+ * @template Value
92
+ * @param {(key: Key) => Promise<Value>} load
93
+ * @returns {(key: Key) => Promise<Value>}
94
+ */
95
+ function memoize(load) {
96
+ /** @type {Map<Key, Promise<Value>>} */
97
+ const cache = new Map();
98
+ return (key) => {
99
+ const cached = cache.get(key) ?? load(key);
100
+ cache.set(key, cached);
101
+ return cached;
102
+ };
103
+ }
104
+
105
+ /**
106
+ * @param {Object} options
107
+ * @param {Octokit} options.octokit
108
+ * @param {GitHubRepository} options.repository
109
+ * @param {AbortSignal} options.signal
110
+ */
111
+ function createAuthorResolver({ octokit, repository, signal }) {
112
+ let hasWarnedAboutMembership = false;
113
+ /**
114
+ * @param {string} login
115
+ */
116
+ function creditUnchecked(login) {
117
+ if (!hasWarnedAboutMembership) {
118
+ hasWarnedAboutMembership = true;
119
+ console.warn(
120
+ `The token can't read the private members of ${repository.owner}. ` +
121
+ `Authors that can't be checked, such as ${login}, are credited as community.`,
122
+ );
123
+ }
124
+ return /** @type {const} */ ('community');
125
+ }
126
+
127
+ const getMembership = memoize(
128
+ /**
129
+ * @param {string} login
130
+ * @returns {Promise<ChangelogAuthor['association']>}
131
+ */
132
+ async (login) => {
133
+ try {
134
+ await octokit.orgs.checkMembershipForUser({
135
+ org: repository.owner,
136
+ username: login,
137
+ request: { signal },
138
+ });
139
+ return 'team';
140
+ } catch (/** @type {any} */ error) {
141
+ if (isForbidden(error)) {
142
+ return creditUnchecked(login);
143
+ }
144
+ if (error.status === 404) {
145
+ // GitHub redirects outsiders to the public members, which don't tell about private ones.
146
+ return error.response?.url.includes('/public_members/')
147
+ ? creditUnchecked(login)
148
+ : 'community';
149
+ }
150
+ throw error;
151
+ }
152
+ },
153
+ );
154
+
155
+ const getOriginal = memoize(async (/** @type {string} */ key) => {
156
+ const [owner, repo, number] = key.split('/');
157
+ try {
158
+ const { data } = await octokit.pulls.get({
159
+ owner,
160
+ repo,
161
+ pull_number: Number(number),
162
+ request: { signal },
163
+ });
164
+ return /** @type {PullRequest} */ (data);
165
+ } catch (/** @type {any} */ error) {
166
+ if (error.status === 404 || isForbidden(error)) {
167
+ return null;
168
+ }
169
+ throw error;
170
+ }
171
+ });
172
+
173
+ /**
174
+ * @param {PullRequest} pull
175
+ * @param {GitHubRepository} pullRepository
176
+ * @returns {Promise<ChangelogAuthor | null>}
177
+ */
178
+ async function getOpener(pull, pullRepository) {
179
+ if (!pull.user) {
180
+ return null;
181
+ }
182
+ const { login, type } = pull.user;
183
+ const isSameRepository =
184
+ pullRepository.owner === repository.owner && pullRepository.repo === repository.repo;
185
+ /** @type {ChangelogAuthor['association']} */
186
+ let association = 'community';
187
+ if (type !== 'Bot') {
188
+ association = isSameRepository
189
+ ? (ASSOCIATIONS[pull.author_association] ?? 'community')
190
+ : // The association with another repository says nothing about this one.
191
+ await getMembership(login);
192
+ }
193
+ return { login, name: null, association, isBot: isBotAccount(pull.user) };
194
+ }
195
+
196
+ /**
197
+ * The opener, or the person who asked Copilot for the pull request.
198
+ *
199
+ * @param {PullRequest} pull
200
+ * @param {GitHubRepository} pullRepository
201
+ * @returns {Promise<ChangelogAuthor | null>}
202
+ */
203
+ async function getCredit(pull, pullRepository) {
204
+ if (pull.user?.login === COPILOT) {
205
+ // It assigns itself and whoever asked for the pull request.
206
+ const people = (pull.assignees ?? []).filter((assignee) => assignee.type !== 'Bot');
207
+ if (people.length === 1) {
208
+ const { login } = people[0];
209
+ // The association of the pull request is the one of Copilot.
210
+ return { login, name: null, association: await getMembership(login), isBot: false };
211
+ }
212
+ }
213
+ return getOpener(pull, pullRepository);
214
+ }
215
+
216
+ /**
217
+ * @param {PullRequest} pull
218
+ * @param {GitHubRepository} pullRepository
219
+ * @param {string[]} chain - Cherry-picks that led to this pull request
220
+ * @returns {Promise<{ author: ChangelogAuthor | null, isBot: boolean, references: string[] } | null>}
221
+ * `null` when the pull request is a cherry-pick by a bot of which the original author is unknown
222
+ */
223
+ async function resolve(pull, pullRepository, chain = []) {
224
+ const isBot = isBotAccount(pull.user);
225
+ const opener = async () => ({
226
+ author: await getCredit(pull, pullRepository),
227
+ isBot,
228
+ references: [],
229
+ });
230
+ const references = getCherryPickReferences(pull, pullRepository);
231
+ if (references.length === 0) {
232
+ const isLabeled = pull.labels.some((label) => label.name === CHERRY_PICK_LABEL);
233
+ return isBot && isLabeled ? null : opener();
234
+ }
235
+
236
+ const originals = await Promise.all(
237
+ references.map(async (reference) => {
238
+ const key = `${reference.owner}/${reference.repo}/${reference.number}`;
239
+ const original = chain.includes(key) ? null : await getOriginal(key);
240
+ return original && resolve(original, reference, [...chain, key]);
241
+ }),
242
+ );
243
+ const author = originals[0]?.author;
244
+ if (author && originals.every((original) => original?.author?.login === author.login)) {
245
+ // A person who cherry-picks the work of a bot is the better credit.
246
+ const isBotAuthor = originals.some((original) => original?.isBot);
247
+ if (isBot || !isBotAuthor) {
248
+ return {
249
+ author,
250
+ isBot: isBotAuthor,
251
+ references: references.map((reference) => reference.text),
252
+ };
253
+ }
254
+ }
255
+ return isBot ? null : opener();
256
+ }
257
+
258
+ return {
259
+ /**
260
+ * @param {PullRequest} pull
261
+ * @returns {Promise<{ author: ChangelogAuthor | null, openedBy: ChangelogAuthor | null, references: string[] }>}
262
+ */
263
+ async fromPullRequest(pull) {
264
+ const openedBy = await getOpener(pull, repository);
265
+ const resolved = await resolve(pull, repository);
266
+ if (!resolved) {
267
+ console.warn(
268
+ `#${pull.number} is a cherry-pick, but its original author can't be determined. ` +
269
+ `${openedBy?.login} is credited instead.`,
270
+ );
271
+ return { author: openedBy, openedBy, references: [] };
272
+ }
273
+ const { author, references } = resolved;
274
+ if (author?.login === COPILOT) {
275
+ console.warn(
276
+ `#${pull.number} is by ${COPILOT}, but who it worked for can't be determined. ` +
277
+ `${COPILOT} is credited instead.`,
278
+ );
279
+ }
280
+ return { author, openedBy, references };
281
+ },
282
+ /**
283
+ * @param {Commit} commit
284
+ * @returns {Promise<ChangelogAuthor>}
285
+ */
286
+ async fromCommit(commit) {
287
+ const login = commit.author?.login ?? null;
288
+ return {
289
+ login,
290
+ name: commit.commit.author?.name ?? null,
291
+ association:
292
+ login === null || commit.author?.type === 'Bot'
293
+ ? 'community'
294
+ : await getMembership(login),
295
+ isBot: isBotAccount(commit.author),
296
+ };
297
+ },
298
+ };
299
+ }
300
+
301
+ /**
302
+ * Strips trailing `(#1)` references, and `(@login)` credits when asked to.
303
+ *
304
+ * @param {string} title
305
+ * @param {string[]} references
306
+ * @param {boolean} stripCredits
307
+ * @returns {string}
308
+ */
309
+ function stripTrailingReferences(title, references, stripCredits) {
310
+ const [, rest, reference] = /^(.*?)\s*\(([^()]+)\)$/.exec(title) ?? [];
311
+ // The credit can name a login that has since been renamed.
312
+ return references.includes(reference) || (stripCredits && /^@[\w-]+$/.test(reference))
313
+ ? stripTrailingReferences(rest, references, stripCredits)
314
+ : title;
315
+ }
316
+
317
+ /**
318
+ * @param {Object} options
319
+ * @param {Octokit} options.octokit
320
+ * @param {GitHubRepository} options.repository
321
+ * @param {string} options.previousSha
322
+ * @param {string} options.releaseSha
323
+ * @param {boolean} options.includeDirectCommits
324
+ * @param {string[]} [options.excludeBots] - Bots whose changes are left out, as `app/<slug>` or login
325
+ * @param {AbortController} options.controller - Aborted when a request fails
326
+ * @returns {Promise<ChangelogChange[]>}
327
+ */
328
+ export async function fetchChangelogChanges({
329
+ octokit,
330
+ repository,
331
+ previousSha,
332
+ releaseSha,
333
+ includeDirectCommits,
334
+ excludeBots = ['app/renovate', 'app/code-infra-renovate'],
335
+ controller,
336
+ }) {
337
+ const { signal } = controller;
338
+ const excluded = new Set(
339
+ excludeBots.map((bot) => (bot.startsWith('app/') ? `${bot.slice('app/'.length)}[bot]` : bot)),
340
+ );
341
+ const isExcludedAccount = (
342
+ /** @type {{ login?: string, type?: string } | null | undefined} */ account,
343
+ ) => account?.type === 'Bot' && excluded.has(account.login ?? '');
344
+ const location = { ...repository, request: { signal } };
345
+ const authors = createAuthorResolver({ octokit, repository, signal });
346
+
347
+ async function listCommits() {
348
+ /** @type {Commit[]} */
349
+ const commits = [];
350
+ let total = 0;
351
+ const pages = octokit.paginate.iterator(
352
+ octokit.repos.compareCommitsWithBasehead.endpoint.merge({
353
+ ...location,
354
+ basehead: `${previousSha}...${releaseSha}`,
355
+ per_page: 100,
356
+ }),
357
+ );
358
+ for await (const { data } of /** @type {AsyncIterable<any>} */ (pages)) {
359
+ commits.push(...data.commits);
360
+ total = data.total_commits;
361
+ }
362
+ if (commits.length !== total) {
363
+ throw new Error(`GitHub listed ${commits.length} of the ${total} commits in the release.`);
364
+ }
365
+ return commits;
366
+ }
367
+
368
+ /**
369
+ * Asks GitHub rather than trusting the message, where a reference to an issue or to another pull
370
+ * request looks the same as the pull request the commit was merged from.
371
+ *
372
+ * @param {string} sha
373
+ * @param {string} subject
374
+ */
375
+ async function findPullRequest(sha, subject) {
376
+ const isMergedAsCommit = (
377
+ /** @type {{ merged_at: string | null, merge_commit_sha: string | null }} */ pull,
378
+ ) => pull.merged_at !== null && pull.merge_commit_sha === sha;
379
+
380
+ const pulls = await octokit.paginate(octokit.repos.listPullRequestsAssociatedWithCommit, {
381
+ ...location,
382
+ commit_sha: sha,
383
+ per_page: 100,
384
+ });
385
+ // On maintenance branches, GitHub also lists pull requests that merely contain the commit.
386
+ const listed = pulls.find(isMergedAsCommit);
387
+ if (listed) {
388
+ return listed;
389
+ }
390
+
391
+ // GitHub lists nothing for some commits, such as mui/mui-x@227a2fee.
392
+ const reference = /\(#(\d+)\)$/.exec(subject);
393
+ if (!reference) {
394
+ return null;
395
+ }
396
+ try {
397
+ const { data } = await octokit.pulls.get({ ...location, pull_number: Number(reference[1]) });
398
+ return isMergedAsCommit(data) ? data : null;
399
+ } catch (/** @type {any} */ error) {
400
+ if (error.status === 404) {
401
+ return null;
402
+ }
403
+ throw error;
404
+ }
405
+ }
406
+
407
+ /**
408
+ * @param {Commit} commit
409
+ * @returns {Promise<ChangelogChange | null>}
410
+ */
411
+ async function toChange(commit) {
412
+ const { sha } = commit;
413
+ const { message } = commit.commit;
414
+ const subject = message.split('\n', 1)[0].trim();
415
+
416
+ const pull = await findPullRequest(sha, subject);
417
+ if (pull) {
418
+ if (isExcludedAccount(pull.user)) {
419
+ return null;
420
+ }
421
+ const { author, openedBy, references } = await authors.fromPullRequest(pull);
422
+ if (author?.isBot && excluded.has(author.login ?? '')) {
423
+ return null;
424
+ }
425
+ const ownReference = `#${pull.number}`;
426
+ const title = subject.endsWith(`(${ownReference})`) ? subject : pull.title;
427
+ const isCreditedCherryPick = references.length > 0;
428
+ return {
429
+ title: stripTrailingReferences(title, [ownReference, ...references], isCreditedCherryPick),
430
+ message,
431
+ sha,
432
+ url: pull.html_url,
433
+ labels: pull.labels.map((label) => label.name),
434
+ isBreakingChange: pull.labels.some((label) => BREAKING_CHANGE_LABELS.includes(label.name)),
435
+ pullRequest: {
436
+ number: pull.number,
437
+ title: pull.title,
438
+ body: pull.body ?? '',
439
+ openedBy,
440
+ },
441
+ author,
442
+ createdAt: pull.created_at,
443
+ mergedAt: pull.merged_at,
444
+ };
445
+ }
446
+
447
+ if (!includeDirectCommits || isExcludedAccount(commit.author)) {
448
+ return null;
449
+ }
450
+ return {
451
+ title: subject,
452
+ message,
453
+ sha,
454
+ url: commit.html_url,
455
+ labels: [],
456
+ isBreakingChange: false,
457
+ pullRequest: null,
458
+ author: await authors.fromCommit(commit),
459
+ createdAt: commit.commit.author?.date ?? null,
460
+ mergedAt: commit.commit.committer?.date ?? null,
461
+ };
462
+ }
463
+
464
+ const changes = await mapAsync(
465
+ await listCommits(),
466
+ async (commit) => {
467
+ signal.throwIfAborted();
468
+ try {
469
+ return await toChange(commit);
470
+ } catch (error) {
471
+ // Immediately, or the next queued commit still gets to make its request.
472
+ controller.abort(error);
473
+ throw error;
474
+ }
475
+ },
476
+ { concurrency: 10 },
477
+ );
478
+ return changes.filter((change) => change !== null);
479
+ }