Skip to content
Merged
Show file tree
Hide file tree
Changes from 2 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
11 changes: 8 additions & 3 deletions bulma-ui/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -133,9 +133,14 @@
},
"exports": {
".": {
"types": "./dist/types/index.d.ts",
"import": "./dist/index.esm.js",
"require": "./dist/index.cjs"
"import": {
"types": "./dist/types/index.d.ts",
"default": "./dist/index.esm.js"
},
"require": {
"types": "./dist/types-cjs/index.d.ts",
"default": "./dist/index.cjs"
}
},
"./constants": {
"import": {
Expand Down
105 changes: 104 additions & 1 deletion bulma-ui/rollup.config.js
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { readFile, readdir, writeFile } from 'node:fs/promises';
import { cp, readFile, readdir, writeFile } from 'node:fs/promises';
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved
import { existsSync } from 'node:fs';
import {
dirname,
Expand Down Expand Up @@ -724,6 +724,107 @@ export const hasModuleSpecifiers = text => {
* on its own reaches the check below, which is why the check is here rather
* than being left to the test.
*/
/**
* Mirror `dist/types` into `dist/types-cjs` and mark it CommonJS, so the
* `require` condition has declarations of the right flavour (#698).
*
* The package is `type: module`, so every emitted `.d.ts` reads as an ES module
* and a `moduleResolution: node16` consumer that REQUIRES the package meets
* TS1479 — "the referenced file is an ECMAScript module and cannot be imported
* with 'require'". One `types` target cannot describe both conditions.
*
* A nested `{"type":"commonjs"}` does the whole job, which is why this is a copy
* rather than a second declaration emit. Flavour comes from the nearest manifest,
* so the same bytes read as CommonJS from under `dist/types-cjs` — no `.d.cts`
* renaming, and no rewriting `./x.js` to `./x.cjs`, because inside that tree
* `./x.js` already resolves to a CommonJS `x.d.ts`. The specifiers the main pass
* wrote are correct here unchanged, which is the whole reason this is cheap.
*
* Measured before choosing it: all five consumer shapes — node16 and nodenext,
* CommonJS and ESM, plus bundler — typecheck clean against a package laid out
* this way, where node16 CommonJS is TS1479 without it. The cost is one extra
* copy of the declarations, about 6% of unpacked `dist`.
*
* Runs from `closeBundle` at config level, after `declarationExtensions` has
* given every specifier its extension — copying before that would mirror a tree
* whose specifiers do not resolve, and the post-pass there would never see the
* copy.
*/
const commonjsDeclarationTypes = (
from = 'dist/types',
to = 'dist/types-cjs'
) => {
let failed = false;
let started = 0;
let wrote = 0;
return {
name: 'bestax-commonjs-declaration-types',
buildStart() {
failed = false;
started = 0;
wrote = 0;
},
buildEnd(error) {
if (error) failed = true;
},
renderError() {
failed = true;
},
renderStart() {
started += 1;
},
writeBundle() {
wrote += 1;
},
async closeBundle(error) {
Comment thread
allxsmith marked this conversation as resolved.
Resolved
// The same latch `declarationExtensions` carries, for the same reason:
// `closeBundle` fires on every failure path too, and this hook's own
// error would replace the real one.
if (failed || error || started === 0 || wrote !== started) return;
let entries;
try {
entries = await readdir(from, { withFileTypes: true });
} catch (readError) {
if (readError.code === 'ENOENT') {
throw new Error(
`${from} is missing, so ${to} cannot be written. It comes from the ` +
'declaration pass, which has to run before this.'
);
}
throw readError;
}
if (!entries.length) {
throw new Error(
`${from} is empty, so ${to} would describe nothing. The declaration ` +
'pass has to run before this.'
);
}
// NO `rm` first, deliberately. `pnpm all` hands `build` and
// `bundle:stats` to one `turbo run` with no edge between them, and both
// are `rollup -c` over this same `dist` — so they run concurrently. Two
// processes writing identical bytes is harmless and is what happened
// before this plugin existed; one of them clearing the directory first is
// not. The loud outcome is a `cp` that fails mid-walk; the quiet one is an
// `rm` landing after the other process wrote the manifest, leaving a tree
// with no `package.json`, which falls back to the root `type: module` and
// puts TS1479 back with a green gate.
//
// `cp` overwrites, so a rebuild refreshes every file that still exists. A
// declaration deleted from `src` leaves a stale copy here — the same thing
// `dist` already does everywhere else, since nothing cleans it, and the
// extension pass holds the source tree to resolving rather than this one.
Comment thread
allxsmith marked this conversation as resolved.
Resolved
await cp(from, to, { recursive: true });
// The whole mechanism. Flavour is decided by the nearest manifest, so this
// one line is what makes the copied declarations CommonJS.
await writeFile(
join(to, 'package.json'),
`${JSON.stringify({ type: 'commonjs' }, null, 2)}\n`,
'utf8'
);
},
};
};

const constantsCjsTypes = () => ({
name: 'bestax-constants-cjs-types',
async writeBundle() {
Expand Down Expand Up @@ -807,6 +908,8 @@ export default commandLineArgs => {
// correct under `--watch`: that rebuilds only the config whose inputs
// changed, so a rewrite hung off any other entry never runs.
declarationExtensions(),
// After it: this mirrors what that pass has finished rewriting.
commonjsDeclarationTypes(),
resolve(),
commonjs(),
typescript({
Expand Down
69 changes: 53 additions & 16 deletions scripts/constants-subpath.test.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -364,15 +364,56 @@ describe('bulma-ui export map', () => {
);
});

it('pins the node16 boundary: ESM resolves, CommonJS is the known #698 gap', () => {
it('gives each root condition declarations of its own flavour', () => {
requireBuilt();
// #696 names `node16` as well as `nodenext`, and the two fixtures below
// cover only the latter. The pair is asserted together because the
// interesting fact is the BOUNDARY: under `node16` an ESM consumer is fine,
// and a CommonJS one meets TS1479 because a single ESM-flavoured `types`
// target serves both conditions. That failure is #698 and pre-existing —
// the same consumer got TS2305 before this change — and pinning it means
// fixing #698 fails this test, which is when it should be revisited.
// #698: the package is `type: module`, so every emitted `.d.ts` reads as an
// ES module, and one `types` target cannot describe both conditions — a
// `require` consumer on `node16` met TS1479. The consumer fixture below is
// what proves the fix; this case pins the SHAPE, so a change that keeps the
// types resolving but collapses the conditions is caught here rather than by
// a typecheck that happens to still pass.
const root = manifest.exports['.'];
assert.equal(
typeof root.import?.types,
'string',
'the import condition has no types target of its own'
);
assert.equal(
typeof root.require?.types,
'string',
'the require condition has no types target of its own'
);
assert.notEqual(
root.import.types,
root.require.types,
'both conditions point at the same declarations, which is the #698 bug'
);
// Both targets exist.
for (const spec of [root.import.types, root.require.types]) {
assert.ok(existsSync(target(spec)), `${spec} does not exist`);
}
// And the mechanism: flavour comes from the nearest manifest, so the CJS
// tree carries one saying so. Without this line the copied declarations
// read as ES modules again and the fix silently undoes itself.
const nested = JSON.parse(
readFileSync(join(PKG_DIR, 'dist', 'types-cjs', 'package.json'), 'utf8')
);
assert.equal(nested.type, 'commonjs');
Comment thread
allxsmith marked this conversation as resolved.
Resolved
});

it('typechecks a node16 consumer through BOTH conditions', () => {
requireBuilt();
// The ROOT entry under `node16`, both conditions. The `./constants` subpath
// has its own node16 pair; this is the root's, which is where #698 bit.
// Asserted together because it used to be a
// BOUNDARY: an ESM consumer was fine and a CommonJS one met TS1479, because
// one ESM-flavoured `types` target served both conditions.
//
// That was #698, and this case was written to fail when it was fixed — which
// it did, on the commit that gave the `require` condition its own
// CommonJS-flavoured declarations. Both sides pass now, and the pair stays
// because the interesting property is still the pair: giving `require` its
// own types must not cost the `import` side anything.
const build = type => {
const dir = mkdtempSync(join(tmpdir(), `bestax-node16-${type}-`));
mkdirSync(join(dir, 'src'), { recursive: true });
Expand Down Expand Up @@ -429,16 +470,12 @@ describe('bulma-ui export map', () => {
);

const cjs = build('cjs');
assert.notEqual(
assert.equal(
cjs.status,
0,
'a node16 CommonJS consumer now typechecks — #698 may be fixed, in ' +
'which case this expectation is what needs updating'
);
assert.match(
cjs.stdout,
/TS1479/,
`expected the known #698 failure, got:\n${cjs.stdout || cjs.stderr}`
`a node16 CommonJS consumer does not typecheck:\n${
cjs.stdout || cjs.stderr
}`
);
});

Expand Down
Loading