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

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 +471 -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
@@ -0,0 +1,505 @@
1
+ import * as path from 'node:path';
2
+ import { parse, Visitor } from 'rolldown/utils';
3
+
4
+ import {
5
+ applyEdits,
6
+ countReferences,
7
+ DTS_FILES,
8
+ GENERATED_NAMESPACE,
9
+ getBinding,
10
+ getName,
11
+ slice,
12
+ } from './rolldownOutput.mjs';
13
+
14
+ const RUNTIME_MODULE = '\0rolldown/runtime.js';
15
+
16
+ /**
17
+ * @typedef {import('./rolldownOutput.mjs').Edit} Edit
18
+ * @typedef {import('./rolldownOutput.mjs').Node} Node
19
+ */
20
+
21
+ /** @param {import('tsdown').Rolldown.OutputChunk} chunk */
22
+ async function parseProgram(chunk) {
23
+ const { program } = await parse(chunk.fileName, chunk.code, { lang: 'js' });
24
+
25
+ return program;
26
+ }
27
+
28
+ /** @param {import('tsdown').Rolldown.OutputChunk} chunk */
29
+ async function parseChunk(chunk) {
30
+ return (await parseProgram(chunk)).body;
31
+ }
32
+
33
+ /**
34
+ * The chunk `node` loads when it is `require('./file')`.
35
+ * @param {import('tsdown').Rolldown.OutputChunk} chunk
36
+ * @param {Node | null | undefined} node
37
+ */
38
+ function getRequired(chunk, node) {
39
+ const source = node?.type === 'CallExpression' ? node.arguments[0] : null;
40
+
41
+ if (
42
+ node?.type !== 'CallExpression' ||
43
+ node.callee.type !== 'Identifier' ||
44
+ node.callee.name !== 'require' ||
45
+ source?.type !== 'Literal' ||
46
+ typeof source.value !== 'string' ||
47
+ !source.value.startsWith('.')
48
+ ) {
49
+ return undefined;
50
+ }
51
+
52
+ return path.posix.join(path.posix.dirname(chunk.fileName), source.value);
53
+ }
54
+
55
+ /**
56
+ * The CommonJS reads of other chunks' exports, ie, `require_parts.name` and
57
+ * `require('./parts.js').name`.
58
+ * @param {import('tsdown').Rolldown.OutputChunk} chunk
59
+ */
60
+ async function getRequiredReads(chunk) {
61
+ const program = await parseProgram(chunk);
62
+ /** @type {Map<string, string>} */
63
+ const bindings = new Map();
64
+
65
+ for (const node of program.body) {
66
+ for (const declarator of node.type === 'VariableDeclaration' ? node.declarations : []) {
67
+ const target = getRequired(chunk, declarator.init);
68
+
69
+ if (target && declarator.id.type === 'Identifier') {
70
+ bindings.set(declarator.id.name, target);
71
+ }
72
+ }
73
+ }
74
+
75
+ /** @type {Set<string>} */
76
+ const required = new Set();
77
+ /** @type {{ node: import('rolldown/utils').ESTree.MemberExpression; target: string; name: string }[]} */
78
+ const reads = [];
79
+ new Visitor({
80
+ CallExpression(node) {
81
+ const target = getRequired(chunk, node);
82
+
83
+ if (target) {
84
+ required.add(target);
85
+ }
86
+ },
87
+ MemberExpression(node) {
88
+ const { object, property } = node;
89
+
90
+ const target =
91
+ object.type === 'Identifier' ? bindings.get(object.name) : getRequired(chunk, object);
92
+
93
+ if (target && !node.computed && property.type === 'Identifier') {
94
+ reads.push({ node, target, name: property.name });
95
+ }
96
+ },
97
+ }).visit(program);
98
+
99
+ return { required, reads };
100
+ }
101
+
102
+ /**
103
+ * Whether `node` calls Rolldown's runtime `helper`, imported (ESM) or read off its `require()` (CJS).
104
+ * @param {Node | null | undefined} node
105
+ * @param {string} helper
106
+ */
107
+ function callsHelper(node, helper) {
108
+ if (node?.type !== 'CallExpression') {
109
+ return false;
110
+ }
111
+
112
+ const { callee } = node;
113
+
114
+ if (callee.type === 'Identifier') {
115
+ return callee.name === helper;
116
+ }
117
+
118
+ return (
119
+ callee.type === 'MemberExpression' &&
120
+ !callee.computed &&
121
+ callee.property.type === 'Identifier' &&
122
+ callee.property.name === helper
123
+ );
124
+ }
125
+
126
+ /**
127
+ * The name `statement` exports as CommonJS through a getter returning `local`, ie,
128
+ * `Object.defineProperty(exports, "name", { get() { return local; } })`.
129
+ * @param {Node} statement
130
+ * @param {string} local
131
+ */
132
+ function getCjsExport(statement, local) {
133
+ const call = statement.type === 'ExpressionStatement' ? statement.expression : null;
134
+
135
+ if (
136
+ call?.type !== 'CallExpression' ||
137
+ call.callee.type !== 'MemberExpression' ||
138
+ call.callee.object.type !== 'Identifier' ||
139
+ call.callee.object.name !== 'Object' ||
140
+ call.callee.property.type !== 'Identifier' ||
141
+ call.callee.property.name !== 'defineProperty' ||
142
+ call.arguments[0]?.type !== 'Identifier' ||
143
+ call.arguments[0].name !== 'exports' ||
144
+ call.arguments[1]?.type !== 'Literal' ||
145
+ call.arguments[2]?.type !== 'ObjectExpression'
146
+ ) {
147
+ return undefined;
148
+ }
149
+
150
+ const getter = call.arguments[2].properties.find(
151
+ (property) =>
152
+ property.type === 'Property' &&
153
+ property.key.type === 'Identifier' &&
154
+ property.key.name === 'get',
155
+ );
156
+
157
+ const body =
158
+ getter?.type === 'Property' && getter.value.type === 'FunctionExpression'
159
+ ? getter.value.body?.body
160
+ : null;
161
+
162
+ const returned =
163
+ body?.length === 1 && body[0].type === 'ReturnStatement' ? body[0].argument : null;
164
+
165
+ return returned?.type === 'Identifier' && returned.name === local
166
+ ? String(call.arguments[1].value)
167
+ : undefined;
168
+ }
169
+
170
+ /**
171
+ * The `__reExport()` calls filling namespace `name`, and whether the module reads it beyond
172
+ * those, its declaration and its exports.
173
+ * @param {import('tsdown').Rolldown.OutputChunk} chunk
174
+ * @param {Node[]} body
175
+ * @param {string} name
176
+ */
177
+ function getOwnStatements(chunk, body, name) {
178
+ const reExports = body.filter(
179
+ (statement) =>
180
+ statement.type === 'ExpressionStatement' &&
181
+ callsHelper(statement.expression, '__reExport') &&
182
+ statement.expression.type === 'CallExpression' &&
183
+ statement.expression.arguments[0]?.type === 'Identifier' &&
184
+ statement.expression.arguments[0].name === name,
185
+ );
186
+ const exports = body.flatMap((statement) =>
187
+ statement.type === 'ExportNamedDeclaration' && !statement.source
188
+ ? statement.specifiers.filter(
189
+ (specifier) => specifier.type === 'ExportSpecifier' && getName(specifier.local) === name,
190
+ )
191
+ : [],
192
+ );
193
+
194
+ const cjsExports = body.filter((statement) => getCjsExport(statement, name) !== undefined);
195
+
196
+ const cjsReferences = cjsExports.reduce(
197
+ (count, statement) => count + countReferences(slice(chunk.code, statement), name),
198
+ 0,
199
+ );
200
+
201
+ const usedLocally =
202
+ countReferences(chunk.code, name) !== 1 + reExports.length + exports.length + cjsReferences;
203
+
204
+ return { reExports, cjsExports, usedLocally };
205
+ }
206
+
207
+ /**
208
+ * The `__exportAll()` namespaces of `chunk` whose members it all exports by name and that it
209
+ * doesn't read itself, so `import * as` can stand in for them. Rolldown can inline constants into the object instead.
210
+ * @param {import('tsdown').Rolldown.OutputChunk} chunk
211
+ */
212
+ async function getNamespaces(chunk) {
213
+ const exported = new Set(chunk.exports);
214
+ /** @type {Set<string>} */
215
+ const namespaces = new Set();
216
+ const body = await parseChunk(chunk);
217
+ for (const node of body) {
218
+ const declarator = node.type === 'VariableDeclaration' ? node.declarations[0] : null;
219
+ const init = declarator?.init;
220
+ if (
221
+ declarator?.id.type !== 'Identifier' ||
222
+ !GENERATED_NAMESPACE.test(declarator.id.name) ||
223
+ !callsHelper(init, '__exportAll') ||
224
+ init?.type !== 'CallExpression' ||
225
+ init.arguments[0]?.type !== 'ObjectExpression'
226
+ ) {
227
+ continue;
228
+ }
229
+ const complete = init.arguments[0].properties.every(
230
+ (property) =>
231
+ property.type === 'Property' &&
232
+ !property.computed &&
233
+ property.key.type === 'Identifier' &&
234
+ exported.has(property.key.name),
235
+ );
236
+ // Rewriting would leave the module's own references on a second, different object.
237
+ if (complete && !getOwnStatements(chunk, body, declarator.id.name).usedLocally) {
238
+ namespaces.add(declarator.id.name);
239
+ }
240
+ }
241
+ return namespaces;
242
+ }
243
+
244
+ /**
245
+ * @param {Node} node
246
+ * @param {string} text
247
+ * @returns {Edit}
248
+ */
249
+ function replace(node, text) {
250
+ return { start: node.start, end: node.end, text };
251
+ }
252
+
253
+ /**
254
+ * The names each chunk is imported by, keyed by its file name.
255
+ * @param {import('tsdown').Rolldown.OutputChunk[]} chunks
256
+ */
257
+ async function getImportedNames(chunks) {
258
+ const bodies = await Promise.all(chunks.map(parseChunk));
259
+ const requiredReads = await Promise.all(chunks.map(getRequiredReads));
260
+ /** @type {Map<string, Set<string>>} */
261
+ const imported = new Map();
262
+ for (const [index, chunk] of chunks.entries()) {
263
+ for (const node of bodies[index]) {
264
+ if (
265
+ (node.type !== 'ImportDeclaration' && node.type !== 'ExportNamedDeclaration') ||
266
+ !node.source?.value.startsWith('.')
267
+ ) {
268
+ continue;
269
+ }
270
+ const target = path.posix.join(path.posix.dirname(chunk.fileName), node.source.value);
271
+ const names = imported.get(target) ?? new Set();
272
+ imported.set(target, names);
273
+ for (const specifier of node.specifiers) {
274
+ if (specifier.type === 'ImportSpecifier') {
275
+ names.add(getName(specifier.imported));
276
+ } else if (specifier.type === 'ExportSpecifier') {
277
+ names.add(getName(specifier.local));
278
+ }
279
+ }
280
+ }
281
+
282
+ const { required, reads } = requiredReads[index];
283
+
284
+ for (const target of required) {
285
+ imported.set(target, imported.get(target) ?? new Set());
286
+ }
287
+
288
+ for (const { target, name } of reads) {
289
+ imported.get(target)?.add(name);
290
+ }
291
+ }
292
+ return imported;
293
+ }
294
+
295
+ /**
296
+ * Removes `__exportAll()` namespace objects nothing references any more, and their exports.
297
+ * @param {import('tsdown').Rolldown.OutputChunk} chunk
298
+ * @param {Set<string>} imported Names other chunks import from `chunk`.
299
+ */
300
+ async function dropUnusedNamespaces(chunk, imported) {
301
+ const body = await parseChunk(chunk);
302
+ /** @type {Edit[]} */
303
+ const edits = [];
304
+ /** @type {Set<string>} */
305
+ const dropped = new Set();
306
+ for (const node of body) {
307
+ const declarator = node.type === 'VariableDeclaration' ? node.declarations[0] : null;
308
+ if (
309
+ declarator?.id.type !== 'Identifier' ||
310
+ !GENERATED_NAMESPACE.test(declarator.id.name) ||
311
+ !callsHelper(declarator.init, '__exportAll') ||
312
+ imported.has(declarator.id.name)
313
+ ) {
314
+ continue;
315
+ }
316
+ const name = declarator.id.name;
317
+ const { reExports, cjsExports, usedLocally } = getOwnStatements(chunk, body, name);
318
+ if (usedLocally) {
319
+ continue;
320
+ }
321
+ dropped.add(name);
322
+ edits.push(
323
+ replace(node, ''),
324
+ ...[...reExports, ...cjsExports].map((statement) => replace(statement, '')),
325
+ );
326
+ }
327
+ if (dropped.size === 0) {
328
+ return;
329
+ }
330
+ for (const node of body) {
331
+ if (node.type !== 'ExportNamedDeclaration' || node.source || node.declaration) {
332
+ continue;
333
+ }
334
+ const kept = node.specifiers.filter(
335
+ (specifier) => specifier.type !== 'ExportSpecifier' || !dropped.has(getName(specifier.local)),
336
+ );
337
+ if (kept.length === node.specifiers.length) {
338
+ continue;
339
+ }
340
+ edits.push(
341
+ replace(
342
+ node,
343
+ `export { ${kept.map((specifier) => slice(chunk.code, specifier)).join(', ')} };`,
344
+ ),
345
+ );
346
+ }
347
+ chunk.code = applyEdits(chunk.code, edits);
348
+ await dropUnusedImports(chunk);
349
+ }
350
+
351
+ /**
352
+ * Removes the imports the dropped namespaces used: runtime helpers and namespaces they re-exported.
353
+ * @param {import('tsdown').Rolldown.OutputChunk} chunk
354
+ */
355
+ async function dropUnusedImports(chunk) {
356
+ /** @type {Edit[]} */
357
+ const edits = [];
358
+ for (const node of await parseChunk(chunk)) {
359
+ const declarator = node.type === 'VariableDeclaration' ? node.declarations[0] : null;
360
+
361
+ if (
362
+ declarator?.id.type === 'Identifier' &&
363
+ getRequired(chunk, declarator.init) &&
364
+ countReferences(chunk.code, declarator.id.name) === 1
365
+ ) {
366
+ edits.push(replace(node, ''));
367
+ continue;
368
+ }
369
+
370
+ // `import 'x'` has no specifiers to drop and keeps its side effects.
371
+ if (node.type !== 'ImportDeclaration' || node.specifiers.length === 0) {
372
+ continue;
373
+ }
374
+
375
+ const kept = node.specifiers.filter(
376
+ (specifier) =>
377
+ !(
378
+ specifier.type === 'ImportNamespaceSpecifier' ||
379
+ (specifier.type === 'ImportSpecifier' &&
380
+ ['__exportAll', '__reExport'].includes(getName(specifier.imported)))
381
+ ) || countReferences(chunk.code, specifier.local.name) > 1,
382
+ );
383
+ if (kept.length === 0) {
384
+ edits.push(replace(node, ''));
385
+ }
386
+ }
387
+ chunk.code = applyEdits(chunk.code, edits);
388
+ }
389
+
390
+ /**
391
+ * @param {import('tsdown').Rolldown.OutputChunk} chunk
392
+ * @param {Map<string, Set<string>>} rewritable The rewritable namespaces, keyed by file name.
393
+ */
394
+ async function rewriteImports(chunk, rewritable) {
395
+ /** @type {Edit[]} */
396
+ const edits = [];
397
+
398
+ for (const { node, target, name } of (await getRequiredReads(chunk)).reads) {
399
+ if (rewritable.get(target)?.has(name)) {
400
+ edits.push(replace(node, slice(chunk.code, node.object)));
401
+ }
402
+ }
403
+
404
+ for (const node of await parseChunk(chunk)) {
405
+ if (
406
+ (node.type !== 'ImportDeclaration' && node.type !== 'ExportNamedDeclaration') ||
407
+ !node.source?.value.startsWith('.')
408
+ ) {
409
+ continue;
410
+ }
411
+ const target = rewritable.get(
412
+ path.posix.join(path.posix.dirname(chunk.fileName), node.source.value),
413
+ );
414
+
415
+ const bindings = node.specifiers.map((specifier) => getBinding(specifier));
416
+
417
+ // A default import or a quoted name keeps the statement, and with it the object.
418
+ if (!target || bindings.some(([, alias]) => alias?.type !== 'Identifier')) {
419
+ continue;
420
+ }
421
+
422
+ const source = JSON.stringify(node.source.value);
423
+ const keyword = node.type === 'ImportDeclaration' ? 'import' : 'export';
424
+ /** @type {string[]} */
425
+ const rest = [];
426
+ /** @type {string[]} */
427
+ const namespaces = [];
428
+
429
+ for (const [index, [imported, alias]] of bindings.entries()) {
430
+ if (!imported || !alias || !target.has(getName(imported))) {
431
+ rest.push(slice(chunk.code, node.specifiers[index]));
432
+ continue;
433
+ }
434
+
435
+ namespaces.push(`${keyword} * as ${getName(alias)} from ${source};`);
436
+ }
437
+
438
+ if (namespaces.length === 0) {
439
+ continue;
440
+ }
441
+
442
+ if (rest.length > 0) {
443
+ namespaces.unshift(`${keyword} { ${rest.join(', ')} } from ${source};`);
444
+ }
445
+
446
+ edits.push(replace(node, namespaces.join('\n')));
447
+ }
448
+ chunk.code = applyEdits(chunk.code, edits);
449
+ }
450
+
451
+ /**
452
+ * Deletes Rolldown's runtime helpers once the dropped namespaces were their last users.
453
+ * @param {import('tsdown').Rolldown.OutputBundle} bundle
454
+ * @param {import('tsdown').Rolldown.OutputChunk[]} chunks
455
+ */
456
+ async function dropUnusedRuntime(bundle, chunks) {
457
+ const runtime = chunks.find((chunk) => chunk.moduleIds.includes(RUNTIME_MODULE));
458
+ if (!runtime) {
459
+ return;
460
+ }
461
+ const imported = await getImportedNames(chunks);
462
+ if (!imported.has(runtime.fileName)) {
463
+ delete bundle[runtime.fileName];
464
+ }
465
+ }
466
+
467
+ /**
468
+ * Rolldown turns `export * as X from './parts'` into an `__exportAll()` object holding every
469
+ * export, which bundlers can't tree-shake. Rolldown also reads names an external `export *` provides
470
+ * through that object. ESM chunks import such namespaces with `import * as` instead, and CommonJS
471
+ * chunks read the module's `exports`. Objects nothing references any more are removed with their
472
+ * `<name>_exports` export.
473
+ * Remove this plugin once Rolldown keeps namespace re-exports in unbundled builds:
474
+ * https://github.com/rolldown/rolldown/issues/6669
475
+ * @returns {import('tsdown').Rolldown.Plugin}
476
+ */
477
+ export function jsNamespacesPlugin() {
478
+ return {
479
+ name: 'code-infra:js-namespaces',
480
+ async generateBundle(options, bundle) {
481
+ if (options.format !== 'es' && options.format !== 'cjs') {
482
+ return;
483
+ }
484
+ const chunks = Object.values(bundle).filter(
485
+ /** @returns {output is import('tsdown').Rolldown.OutputChunk} */
486
+ (output) => output.type === 'chunk' && !DTS_FILES.test(output.fileName),
487
+ );
488
+ const namespaces = new Map(
489
+ await Promise.all(
490
+ chunks.map(
491
+ async (chunk) => /** @type {const} */ ([chunk.fileName, await getNamespaces(chunk)]),
492
+ ),
493
+ ),
494
+ );
495
+ await Promise.all(chunks.map((chunk) => rewriteImports(chunk, namespaces)));
496
+ const imported = await getImportedNames(chunks);
497
+ await Promise.all(
498
+ chunks.map((chunk) =>
499
+ dropUnusedNamespaces(chunk, imported.get(chunk.fileName) ?? new Set()),
500
+ ),
501
+ );
502
+ await dropUnusedRuntime(bundle, chunks);
503
+ },
504
+ };
505
+ }
@@ -12,6 +12,9 @@ import { parseDocument, isMap } from 'yaml';
12
12
  /** Canonical npm registry URL, in the form `getPublishRegistry` returns. */
13
13
  const NPMJS_REGISTRY = 'https://registry.npmjs.org/';
14
14
 
15
+ /** Version that `publish-new-package` publishes to reserve the name of a new package. */
16
+ export const PLACEHOLDER_VERSION = '0.0.1';
17
+
15
18
  /**
16
19
  * @typedef {Object} PrivatePackage
17
20
  * @property {string} [name] - Package name
@@ -189,49 +192,147 @@ function requiresTrustedPublisherBootstrap(registry) {
189
192
  }
190
193
 
191
194
  /**
192
- * Filter to the packages that must be published by hand before CI can take over.
193
- *
194
- * A brand new package has to be pushed once manually (see
195
- * `code-infra publish-new-package`) before the OIDC-based workflow can publish
196
- * it, so the release fails with a clear message instead of a confusing 404
197
- * midway through. See {@link getPackageVersionInfo} for the version-level check.
195
+ * @typedef {Object} RegistryPackage
196
+ * @property {string} registry - Registry that the package publishes to
197
+ * @property {boolean} exists - Whether the package is on the registry
198
+ * @property {Record<string, string>} distTags - Dist-tags of the package
199
+ * @property {string[]} versions - Published versions of the package
200
+ */
201
+
202
+ /**
203
+ * Read each package from its publish registry with `pnpm view`, so the lookup uses the
204
+ * same registry configuration and credentials as `pnpm publish`.
198
205
  *
199
- * @param {PublicPackage[]} packages - Packages to check
200
- * @returns {Promise<PublicPackage[]>} The subset needing a manual first publish
206
+ * @param {PublicPackage[]} packages - Packages to read
207
+ * @param {{ npmOnly?: boolean }} [options] - `npmOnly` reads only the packages that publish to npm.
208
+ * Checks that only concern npm use it, so a missing credential for another registry does not block them.
209
+ * @returns {Promise<Map<string, RegistryPackage>>} By package name
201
210
  */
202
- export async function getPackagesNeedingManualPublish(packages) {
203
- const results = await Promise.all(
211
+ export async function getRegistryPackages(packages, { npmOnly = false } = {}) {
212
+ const entries = await Promise.all(
204
213
  packages.map(async (pkg) => {
205
214
  const registry = await getPublishRegistry(pkg.path);
206
- if (!requiresTrustedPublisherBootstrap(registry)) {
207
- return false;
215
+ if (npmOnly && registry !== NPMJS_REGISTRY) {
216
+ return null;
208
217
  }
209
-
210
- // HEAD, because only the status matters — a packument runs to megabytes.
211
- const res = await fetch(new URL(pkg.name, registry), { method: 'HEAD' });
212
- if (res.status === 404) {
213
- return true;
218
+ const { exitCode, stdout, stderr } = await $({
219
+ cwd: pkg.path,
220
+ reject: false,
221
+ // pnpm resolves its own `packageManager` version from `--registry`, which may not serve it.
222
+ env: { PNPM_CONFIG_PM_ON_FAIL: 'ignore' },
223
+ })`pnpm view ${pkg.name} dist-tags versions --json --registry ${registry}`;
224
+ let info;
225
+ try {
226
+ info = JSON.parse(stdout || '{}');
227
+ } catch {
228
+ info = {};
214
229
  }
215
- if (!res.ok) {
216
- // Anything else (401, 5xx, a proxy hiccup) tells us nothing about
217
- // whether the package exists. Treating it as "already published" would
218
- // silently disable the check, so fail loudly instead.
230
+ // Anything but a 404 tells nothing about whether the package exists. Treating it as
231
+ // "not published" would silently disable the checks, so fail loudly instead.
232
+ if (exitCode !== 0 && info.error?.code !== 'ERR_PNPM_FETCH_404') {
219
233
  throw new Error(
220
- `Failed to check whether ${pkg.name} exists on ${registry}: HTTP ${res.status}`,
234
+ `Failed to read ${pkg.name} from ${registry}: ${info.error?.message ?? stderr}`,
221
235
  );
222
236
  }
223
- return false;
237
+ /** @type {RegistryPackage} */
238
+ const registryPackage = {
239
+ registry,
240
+ exists: exitCode === 0,
241
+ distTags: info['dist-tags'] ?? {},
242
+ versions: [info.versions ?? []].flat(),
243
+ };
244
+ return /** @type {const} */ ([pkg.name, registryPackage]);
224
245
  }),
225
246
  );
247
+ return new Map(entries.filter((entry) => entry !== null));
248
+ }
226
249
 
227
- return packages.filter((_pkg, index) => results[index]);
250
+ /**
251
+ * Filter to the packages that must be published by hand before CI can take over.
252
+ *
253
+ * A brand new package has to be pushed once manually (see
254
+ * `code-infra publish-new-package`) before the OIDC-based workflow can publish
255
+ * it, so the release fails with a clear message instead of a confusing 404
256
+ * midway through. See {@link getPackageVersionInfo} for the version-level check.
257
+ *
258
+ * @param {PublicPackage[]} packages - Packages to check
259
+ * @param {Map<string, RegistryPackage>} registryPackages - Registry data from {@link getRegistryPackages}
260
+ * @returns {PublicPackage[]} The subset needing a manual first publish
261
+ */
262
+ export function getPackagesNeedingManualPublish(packages, registryPackages) {
263
+ return packages.filter((pkg) => {
264
+ const registryPackage = registryPackages.get(pkg.name);
265
+ return (
266
+ registryPackage !== undefined &&
267
+ !registryPackage.exists &&
268
+ requiresTrustedPublisherBootstrap(registryPackage.registry)
269
+ );
270
+ });
271
+ }
272
+
273
+ /**
274
+ * Why publishing `version` with `tag` would move the dist-tag to the wrong release line.
275
+ *
276
+ * @param {string} tag - Dist-tag to publish with
277
+ * @param {string} version - Version to publish
278
+ * @param {string} current - Version that the dist-tag points to on the registry
279
+ * @returns {string | null} The reason, or null when the publish is safe
280
+ */
281
+ function getDistTagConflict(tag, version, current) {
282
+ if (semver.lt(version, current)) {
283
+ return `"${tag}" can only move to a newer version, but ${version} is lower than the current ${current}`;
284
+ }
285
+ // A tag that already points to a prerelease can move to the next one, for packages still in beta.
286
+ if (
287
+ (tag === 'latest' || tag.startsWith('latest-')) &&
288
+ semver.prerelease(version) &&
289
+ !semver.prerelease(current)
290
+ ) {
291
+ return `"${tag}" cannot point to a prerelease (${version})`;
292
+ }
293
+ if (tag.startsWith('latest-') && semver.major(version) !== semver.major(current)) {
294
+ return `"${tag}" cannot cross a major (${current} to ${version})`;
295
+ }
296
+ return null;
297
+ }
298
+
299
+ /**
300
+ * @typedef {Object} DistTagConflict
301
+ * @property {PublicPackage} pkg - Package to publish
302
+ * @property {string} reason - Why the dist-tag would move to the wrong release line
303
+ */
304
+
305
+ /**
306
+ * Find the packages whose publish with `tag` would move the dist-tag to the wrong release line.
307
+ *
308
+ * @param {PublicPackage[]} packages - Packages to publish
309
+ * @param {string} tag - Dist-tag to publish with
310
+ * @param {Map<string, RegistryPackage>} registryPackages - Registry data from {@link getRegistryPackages}
311
+ * @returns {DistTagConflict[]}
312
+ */
313
+ export function getDistTagConflicts(packages, tag, registryPackages) {
314
+ return packages.flatMap((pkg) => {
315
+ const registryPackage = registryPackages.get(pkg.name);
316
+ // pnpm skips versions that are already published, such as unchanged packages on a legacy branch.
317
+ if (!registryPackage || registryPackage.versions.includes(pkg.version)) {
318
+ return [];
319
+ }
320
+ // A package that is not on the registry yet has no dist-tags to protect, and npm points
321
+ // `latest` at the first version, which is the placeholder for a new package.
322
+ const current = semver.valid(registryPackage.distTags[tag]);
323
+ if (!current || current === PLACEHOLDER_VERSION) {
324
+ return [];
325
+ }
326
+ const reason = getDistTagConflict(tag, pkg.version, current);
327
+ return reason ? [{ pkg, reason }] : [];
328
+ });
228
329
  }
229
330
 
230
331
  /**
231
332
  * Get package version info from registry.
232
333
  *
233
334
  * Resolves through `pnpm view`, which reports a lookup failure the same way it
234
- * reports a missing version. Use {@link getPackagesNeedingManualPublish} where
335
+ * reports a missing version. Use {@link getRegistryPackages} where
235
336
  * absence has to be told apart from an error.
236
337
  *
237
338
  * @param {string} packageName - Name of the package