Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 3 additions & 0 deletions packages/code-infra/src/cli/cmdBuildNew.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@ import { getVersionEnvVariables } from '../utils/babel.mjs';
import { babelPlugin } from '../utils/babelPlugin.mjs';
import { cjsSourcesPlugin } from '../utils/cjsSourcesPlugin.mjs';
import { dtsExportsPlugin } from '../utils/dtsExportsPlugin.mjs';
import { dtsLibReferencesPlugin } from '../utils/dtsLibReferencesPlugin.mjs';
import { dtsNamespacesPlugin } from '../utils/dtsNamespacesPlugin.mjs';
import { jsNamespacesPlugin } from '../utils/jsNamespacesPlugin.mjs';
import { fileUrlEntriesPlugin } from '../utils/fileUrlEntriesPlugin.mjs';
Expand Down Expand Up @@ -419,6 +420,8 @@ export default /** @type {import('yargs').CommandModule<{}, Args>} */ ({
dtsExportsPlugin(),
// https://github.com/sxzz/rolldown-plugin-dts/issues/300
dtsNamespacesPlugin(),
// https://github.com/sxzz/rolldown-plugin-dts/issues/395
dtsLibReferencesPlugin(),
options.plugins,
],
external: [PACKAGE_IMPORTS, OXC_SHARED_HELPERS],
Expand Down
59 changes: 59 additions & 0 deletions packages/code-infra/src/utils/dtsLibReferencesPlugin.mjs
Original file line number Diff line number Diff line change
@@ -0,0 +1,59 @@
import { RolldownMagicString } from 'rolldown';
import { parse } from 'rolldown/utils';

import { DTS_FILES } from './rolldownOutput.mjs';

// A `/// <reference lib="…" />` comment, without its leading `//`.
const LIB_REFERENCE = /^\/\s*<reference\s+lib\s*=/;

/**
* rolldown-plugin-dts drops `/// <reference lib="…" />` directives above imports and re-exports.
* This moves each to the top of its module's declarations, as tsc emits it. Remove this plugin
* once rolldown-plugin-dts keeps them: https://github.com/sxzz/rolldown-plugin-dts/issues/395
* @returns {import('tsdown').Rolldown.Plugin}
*/
export function dtsLibReferencesPlugin() {
/** @type {Map<string, string[]>} */
const references = new Map();

return {
name: 'code-infra:dts-lib-references',
transform: {
// Runs before rolldown-plugin-dts turns the declarations into JavaScript.
order: 'pre',
filter: { id: DTS_FILES, code: '<reference' },
async handler(code, id) {
const { comments } = await parse(id, code, { lang: 'dts' });
const directives = comments.filter(
(comment) => comment.type === 'Line' && LIB_REFERENCE.test(comment.value),
);
if (directives.length === 0) {
return null;
}

references.set(
id,
directives.map((comment) => `//${comment.value}`),
);
// rolldown-plugin-dts keeps a directive above a declaration, which would then appear twice.
const result = new RolldownMagicString(code);
for (const comment of directives) {
result.remove(comment.start, comment.end);
}
return result.toString();
},
},
generateBundle(_options, bundle) {
for (const chunk of Object.values(bundle)) {
if (chunk.type !== 'chunk' || !DTS_FILES.test(chunk.fileName)) {
continue;
}

const directives = new Set(chunk.moduleIds.flatMap((id) => references.get(id) ?? []));
if (directives.size > 0) {
chunk.code = `${[...directives].join('\n')}\n${chunk.code}`;
}
}
},
};
}
104 changes: 104 additions & 0 deletions packages/code-infra/src/utils/dtsLibReferencesPlugin.test.mjs
Original file line number Diff line number Diff line change
@@ -0,0 +1,104 @@
import { execFile } from 'node:child_process';
import * as fs from 'node:fs/promises';
import * as path from 'node:path';
import { promisify } from 'node:util';
import { build } from 'tsdown';
import { expect, it } from 'vitest';

import { dtsLibReferencesPlugin } from './dtsLibReferencesPlugin.mjs';
import { getTsgo, makeTempFiles } from './testUtils.mjs';

const DIRECTIVE = '/// <reference lib="es2020.intl" preserve="true" />';

/**
* The lines of `code` with a reference directive, by line number.
* @param {string} code
*/
function getReferences(code) {
return Object.fromEntries(
code
.split('\n')
.flatMap((line, index) => (line.includes('<reference') ? [[index + 1, line]] : [])),
);
}

it.each(/** @type {const} */ (['cjs', 'es']))(
'keeps reference lib directives in %s declarations',
async (format) => {
const packageType = format === 'es' ? 'module' : 'commonjs';
const extension = format === 'es' ? '.d.mts' : '.d.ts';

// tsgo reports real paths; macOS temp directories sit behind a symlink.
const cwd = await fs.realpath(
await makeTempFiles({
'package.json': JSON.stringify({ type: packageType }),
'tsconfig.json': JSON.stringify({
compilerOptions: {
declaration: true,
emitDeclarationOnly: true,
module: 'nodenext',
moduleResolution: 'nodenext',
rootDir: 'src',
types: [],
},
include: ['src'],
}),
// As in `@mui/material/Unstable_Menu2`.
'src/index.ts': [DIRECTIVE, "export * from './locales.js';"].join('\n'),
'src/locales.ts': 'export type Locales = Intl.LocalesArgument;',
// rolldown-plugin-dts keeps a directive above a declaration.
'src/format.ts': [
DIRECTIVE,
'export declare function format(locales: Intl.LocalesArgument): string;',
].join('\n'),
'consumer.ts': "import type { Locales } from 'pkg'; const locales: Locales = 'en';",
}),
);

const tsc = await getTsgo();

await build({
cwd,
config: false,
entry: ['src/index.ts', 'src/format.ts'],
unbundle: true,
root: 'src',
outDir: 'node_modules/pkg',
format,
tsconfig: 'tsconfig.json',
dts: { generator: 'tsgo', tsgo: { path: tsc } },
outExtensions: () => ({ js: format === 'es' ? '.mjs' : '.js' }),
cjsDefault: false,
deps: { neverBundle: true },
inputOptions: { plugins: [dtsLibReferencesPlugin()] },
report: false,
logLevel: 'silent',
});
await fs.writeFile(
path.join(cwd, 'node_modules/pkg/package.json'),
JSON.stringify({
name: 'pkg',
type: packageType,
exports: { '.': { types: `./index${extension}` } },
}),
);

const [index, locales, formatDts] = await Promise.all(
['index', 'locales', 'format'].map((name) =>
fs.readFile(path.join(cwd, 'node_modules/pkg', `${name}${extension}`), 'utf8'),
),
);
expect(getReferences(index)).toEqual({ 1: DIRECTIVE });
expect(getReferences(locales)).toEqual({});
expect(getReferences(formatDts)).toEqual({ 1: DIRECTIVE });

// Material UI documents `"lib": ["es6", "dom"]` as its minimum, which has no `Intl.LocalesArgument`.
const { stdout } = await promisify(execFile)(
tsc,
['--ignoreConfig', '--noEmit', '--module', 'nodenext', '--lib', 'es2015', 'consumer.ts'],
{ cwd },
).catch((/** @type {{ stdout: string }} */ error) => error);

expect(stdout).toBe('');
},
);
Loading