@mui/internal-code-infra 0.1.1-canary.35 → 0.1.1-canary.37
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.
- package/README.md +29 -0
- package/build/babel-config.d.mts +7 -1
- package/build/utils/babelPlugin.d.mts +8 -0
- package/build/utils/build.d.mts +8 -0
- package/build/utils/cjsSourcesPlugin.d.mts +11 -0
- package/build/utils/dtsExportsPlugin.d.mts +8 -0
- package/build/utils/dtsNamespacesPlugin.d.mts +19 -0
- package/build/utils/fileUrlEntriesPlugin.d.mts +9 -0
- package/build/utils/getPublishedPkgJson.d.mts +20 -0
- package/build/utils/jsNamespacesPlugin.d.mts +13 -0
- package/build/utils/publint.d.mts +6 -0
- package/build/utils/rolldownOutput.d.mts +38 -0
- package/build/utils/testUtils.d.mts +8 -0
- package/build/utils/typescript.d.mts +5 -0
- package/package.json +4 -2
- package/src/babel-config.mjs +35 -1
- package/src/cli/cmdBuild.mjs +9 -125
- package/src/cli/cmdBuildNew.mjs +471 -0
- package/src/cli/index.mjs +2 -0
- package/src/utils/babelPlugin.mjs +52 -0
- package/src/utils/build.mjs +47 -0
- package/src/utils/cjsSourcesPlugin.mjs +92 -0
- package/src/utils/dtsExportsPlugin.mjs +103 -0
- package/src/utils/dtsNamespacesPlugin.mjs +226 -0
- package/src/utils/fileUrlEntriesPlugin.mjs +84 -0
- package/src/utils/getPublishedPkgJson.mjs +86 -0
- package/src/utils/jsNamespacesPlugin.mjs +505 -0
- package/src/utils/publint.mjs +34 -0
- package/src/utils/rolldownOutput.mjs +70 -0
- package/src/utils/testUtils.mjs +26 -0
- package/src/utils/typescript.mjs +22 -12
|
@@ -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
|
+
}
|
|
@@ -0,0 +1,34 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Lints the output directory with publint. Errors fail the build, warnings are only reported.
|
|
3
|
+
* @param {string} buildDir - The build directory to validate.
|
|
4
|
+
* @returns {Promise<void>}
|
|
5
|
+
*/
|
|
6
|
+
export async function validateWithPublint(buildDir) {
|
|
7
|
+
const [{ publint }, { formatMessage }] = await Promise.all([
|
|
8
|
+
import('publint'),
|
|
9
|
+
import('publint/utils'),
|
|
10
|
+
]);
|
|
11
|
+
// Everything in the output directory is published, so there is nothing to pack.
|
|
12
|
+
const result = await publint({ pkgDir: buildDir, pack: false, level: 'warning' });
|
|
13
|
+
const { pkg } = result;
|
|
14
|
+
// TODO: remove this filter and bump publint to >=0.3.25, which ships the fix from
|
|
15
|
+
// https://github.com/publint/publint/pull/265 (publint checks `browser` values
|
|
16
|
+
// that point at another package as local files).
|
|
17
|
+
const messages = result.messages.filter((message) => {
|
|
18
|
+
if (message.code !== 'FILE_DOES_NOT_EXIST' || message.path[0] !== 'browser') {
|
|
19
|
+
return true;
|
|
20
|
+
}
|
|
21
|
+
const value = message.path.length === 2 ? pkg.browser?.[message.path[1]] : undefined;
|
|
22
|
+
return typeof value !== 'string' || value.startsWith('.');
|
|
23
|
+
});
|
|
24
|
+
|
|
25
|
+
for (const message of messages) {
|
|
26
|
+
const log = message.type === 'error' ? console.error : console.warn;
|
|
27
|
+
log(`publint ${message.type}: ${formatMessage(message, pkg)}`);
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
const errorCount = messages.filter((message) => message.type === 'error').length;
|
|
31
|
+
if (errorCount > 0) {
|
|
32
|
+
throw new Error(`publint found ${errorCount} error(s) in "${buildDir}".`);
|
|
33
|
+
}
|
|
34
|
+
}
|
|
@@ -0,0 +1,70 @@
|
|
|
1
|
+
import { RolldownMagicString } from 'rolldown';
|
|
2
|
+
|
|
3
|
+
export const DTS_FILES = /\.d\.[cm]?ts$/;
|
|
4
|
+
|
|
5
|
+
export const GENERATED_NAMESPACE = /_exports$/;
|
|
6
|
+
|
|
7
|
+
/**
|
|
8
|
+
* @typedef {{ start: number; end: number; text: string }} Edit
|
|
9
|
+
* @typedef {import('rolldown/utils').ESTree.Node} Node
|
|
10
|
+
* @typedef {import('rolldown/utils').ESTree.ModuleExportName | import('rolldown/utils').ESTree.BindingIdentifier} Name
|
|
11
|
+
*/
|
|
12
|
+
|
|
13
|
+
/**
|
|
14
|
+
* @param {string} code
|
|
15
|
+
* @param {Edit[]} edits
|
|
16
|
+
*/
|
|
17
|
+
export function applyEdits(code, edits) {
|
|
18
|
+
const result = new RolldownMagicString(code);
|
|
19
|
+
|
|
20
|
+
for (const { start, end, text } of edits) {
|
|
21
|
+
if (text) {
|
|
22
|
+
result.update(start, end, text);
|
|
23
|
+
} else {
|
|
24
|
+
result.remove(start, end);
|
|
25
|
+
}
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
return result.toString();
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
/**
|
|
32
|
+
* @param {string} code
|
|
33
|
+
* @param {string} name
|
|
34
|
+
*/
|
|
35
|
+
export function countReferences(code, name) {
|
|
36
|
+
const escaped = name.replace(/[$]/g, '\\$&');
|
|
37
|
+
|
|
38
|
+
return code.match(new RegExp(`(?<![\\w$])${escaped}(?![\\w$])`, 'g'))?.length ?? 0;
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
/** @param {Name} node */
|
|
42
|
+
export function getName(node) {
|
|
43
|
+
return node.type === 'Identifier' ? node.name : String(node.value);
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
/**
|
|
47
|
+
* The imported and local names of an import specifier, or the local and exported names of an
|
|
48
|
+
* export specifier.
|
|
49
|
+
* @param {Node} specifier
|
|
50
|
+
* @returns {[Name, Name] | []}
|
|
51
|
+
*/
|
|
52
|
+
export function getBinding(specifier) {
|
|
53
|
+
if (specifier.type === 'ImportSpecifier') {
|
|
54
|
+
return [specifier.imported, specifier.local];
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
if (specifier.type === 'ExportSpecifier') {
|
|
58
|
+
return [specifier.local, specifier.exported];
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
return [];
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
/**
|
|
65
|
+
* @param {string} code
|
|
66
|
+
* @param {Node} node
|
|
67
|
+
*/
|
|
68
|
+
export function slice(code, node) {
|
|
69
|
+
return code.slice(node.start, node.end);
|
|
70
|
+
}
|
package/src/utils/testUtils.mjs
CHANGED
|
@@ -19,6 +19,24 @@ export async function makeTempDir() {
|
|
|
19
19
|
return tmpDir;
|
|
20
20
|
}
|
|
21
21
|
|
|
22
|
+
/**
|
|
23
|
+
* Creates a temporary directory (see {@link makeTempDir}) containing `files`.
|
|
24
|
+
*
|
|
25
|
+
* @param {Record<string, string>} files - File contents keyed by path relative to the directory.
|
|
26
|
+
* @returns {Promise<string>} The path of the created temporary directory.
|
|
27
|
+
*/
|
|
28
|
+
export async function makeTempFiles(files) {
|
|
29
|
+
const tmpDir = await makeTempDir();
|
|
30
|
+
await Promise.all(
|
|
31
|
+
Object.entries(files).map(async ([name, contents]) => {
|
|
32
|
+
const file = path.join(tmpDir, name);
|
|
33
|
+
await fs.mkdir(path.dirname(file), { recursive: true });
|
|
34
|
+
await fs.writeFile(file, contents);
|
|
35
|
+
}),
|
|
36
|
+
);
|
|
37
|
+
return tmpDir;
|
|
38
|
+
}
|
|
39
|
+
|
|
22
40
|
/**
|
|
23
41
|
* Write a package.json into a subdirectory of a temp workspace.
|
|
24
42
|
*
|
|
@@ -51,3 +69,11 @@ export function publicPkg(name, pkgPath) {
|
|
|
51
69
|
export function privatePkg(name, pkgPath) {
|
|
52
70
|
return { name, version: '1.0.0', path: pkgPath, isPrivate: true };
|
|
53
71
|
}
|
|
72
|
+
|
|
73
|
+
export async function getTsgo() {
|
|
74
|
+
const { default: getExePath } = await import(
|
|
75
|
+
new URL('../../../../node_modules/@typescript/native/lib/getExePath.js', import.meta.url).href
|
|
76
|
+
);
|
|
77
|
+
|
|
78
|
+
return getExePath();
|
|
79
|
+
}
|
package/src/utils/typescript.mjs
CHANGED
|
@@ -54,6 +54,27 @@ export async function findTscPair(cwd) {
|
|
|
54
54
|
return { native: tsc, js: tsc6 ?? 'tsc' };
|
|
55
55
|
}
|
|
56
56
|
|
|
57
|
+
/**
|
|
58
|
+
* @param {string} cwd
|
|
59
|
+
* @returns {Promise<string>} The `tsconfig.build.json` to emit declarations with.
|
|
60
|
+
*/
|
|
61
|
+
export async function getTsconfig(cwd) {
|
|
62
|
+
const tsconfig = path.join(cwd, 'tsconfig.build.json');
|
|
63
|
+
|
|
64
|
+
const exists = await fs.stat(tsconfig).then(
|
|
65
|
+
(file) => file.isFile(),
|
|
66
|
+
() => false,
|
|
67
|
+
);
|
|
68
|
+
|
|
69
|
+
if (!exists) {
|
|
70
|
+
throw new Error(
|
|
71
|
+
`Unable to find a tsconfig to build types. Add 'tsconfig.build.json' to '${cwd}'.`,
|
|
72
|
+
);
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
return tsconfig;
|
|
76
|
+
}
|
|
77
|
+
|
|
57
78
|
/**
|
|
58
79
|
* Emits TypeScript declaration files.
|
|
59
80
|
* @param {string} tsconfig - The path to the tsconfig.json file.
|
|
@@ -233,19 +254,8 @@ export async function createTypes({
|
|
|
233
254
|
|
|
234
255
|
try {
|
|
235
256
|
await copyDeclarations(srcDir, tmpDir, { verbose });
|
|
236
|
-
const tsconfigPath = path.join(cwd, 'tsconfig.build.json');
|
|
237
|
-
const tsconfigExists = await fs.stat(tsconfigPath).then(
|
|
238
|
-
(file) => file.isFile(),
|
|
239
|
-
() => false,
|
|
240
|
-
);
|
|
241
257
|
if (!skipTsc) {
|
|
242
|
-
|
|
243
|
-
throw new Error(
|
|
244
|
-
'Unable to find a tsconfig to build this project. ' +
|
|
245
|
-
`The package root needs to contain a 'tsconfig.build.json'. ` +
|
|
246
|
-
`The package root is '${cwd}'`,
|
|
247
|
-
);
|
|
248
|
-
}
|
|
258
|
+
const tsconfigPath = await getTsconfig(cwd);
|
|
249
259
|
console.log(`Building types for ${tsconfigPath} in ${tmpDir}`);
|
|
250
260
|
await emitDeclarations(tsconfigPath, tmpDir, { useTsgo });
|
|
251
261
|
}
|