diff --git a/.changeset/cjs-require-entry-points.md b/.changeset/cjs-require-entry-points.md new file mode 100644 index 0000000..cd60f4a --- /dev/null +++ b/.changeset/cjs-require-entry-points.md @@ -0,0 +1,9 @@ +--- +"react-datocms": patch +--- + +`require("react-datocms")` and every `require` of a subpath (`react-datocms/seo`, +`react-datocms/image`, …) threw `ReferenceError: exports is not defined in ES +module scope` on Node. The CommonJS build in `dist/cjs` now carries its own +`package.json` with `"type": "commonjs"`, so Node loads it as CommonJS. `import` +and bundled apps are unaffected. diff --git a/.github/workflows/node.js.yml b/.github/workflows/node.js.yml index 2b3b0df..683dbba 100644 --- a/.github/workflows/node.js.yml +++ b/.github/workflows/node.js.yml @@ -19,3 +19,17 @@ jobs: cache: "npm" - run: npm ci - run: npm test + + package: + # Loads every entry point of the packed tarball with `require` and `import`, + # which `npm test` (source only) can't catch. + runs-on: ubuntu-latest + + steps: + - uses: actions/checkout@v4 + - uses: actions/setup-node@v4 + with: + node-version-file: ".nvmrc" + cache: "npm" + - run: npm ci + - run: npm run test:package diff --git a/package.json b/package.json index 2757103..45a18ab 100644 --- a/package.json +++ b/package.json @@ -160,9 +160,10 @@ "watch": "rimraf dist && tsc --project ./tsconfig.commonjs.json --watch", "prepare": "npm run test && npm run build", "test": "jest --coverage", + "test:package": "npm run build && node scripts/test-package.mjs", "toc": "doctoc --github docs", "tsc:types": "tsc", - "tsc:cjs": "tsc --project ./tsconfig.commonjs.json", + "tsc:cjs": "tsc --project ./tsconfig.commonjs.json && node scripts/copy-cjs-package-json.mjs", "tsc:esm": "tsc --project ./tsconfig.esnext.json", "changeset": "changeset", "release": "release-toolchain", diff --git a/scripts/cjs-package.json b/scripts/cjs-package.json new file mode 100644 index 0000000..5bbefff --- /dev/null +++ b/scripts/cjs-package.json @@ -0,0 +1,3 @@ +{ + "type": "commonjs" +} diff --git a/scripts/copy-cjs-package-json.mjs b/scripts/copy-cjs-package-json.mjs new file mode 100644 index 0000000..e6f178c --- /dev/null +++ b/scripts/copy-cjs-package-json.mjs @@ -0,0 +1,8 @@ +// Marks dist/cjs as CommonJS, overriding the root "type": "module". + +import { copyFileSync } from 'node:fs'; + +copyFileSync( + new URL('./cjs-package.json', import.meta.url), + new URL('../dist/cjs/package.json', import.meta.url), +); diff --git a/scripts/test-package.mjs b/scripts/test-package.mjs new file mode 100644 index 0000000..aa53854 --- /dev/null +++ b/scripts/test-package.mjs @@ -0,0 +1,66 @@ +// Packs the built library, installs the tarball into a throwaway consumer, and +// loads every `exports` entry point with both `require` and `import`. +// Expects `dist/` to be built already: `npm run test:package` does both. + +import { execFileSync, spawnSync } from 'node:child_process'; +import { mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs'; +import { tmpdir } from 'node:os'; +import { join } from 'node:path'; + +const pkg = JSON.parse(readFileSync(new URL('../package.json', import.meta.url))); + +const specifiers = Object.keys(pkg.exports).map((key) => + key === '.' ? pkg.name : `${pkg.name}${key.slice(1)}`, +); + +// The optional Mux peer is installed because the root and `/video-player` +// entry points load it unconditionally. +const peers = ['react', 'react-dom', '@mux/mux-player-react'].map( + (name) => `${name}@${pkg.devDependencies[name]}`, +); + +/** + * Runs a command and returns its trimmed stdout, throwing if it exits non-zero. + */ +const run = (command, args, cwd) => + execFileSync(command, args, { cwd, encoding: 'utf8', shell: process.platform === 'win32' }).trim(); + +/** + * Loads `specifier` in a fresh Node process from `cwd`, returning the error's + * first line, or `null` when it loads. + */ +const load = (cwd, specifier, mode) => { + const file = join(cwd, mode === 'require' ? 'load.cjs' : 'load.mjs'); + writeFileSync( + file, + mode === 'require' ? `require(${JSON.stringify(specifier)});\n` : `await import(${JSON.stringify(specifier)});\n`, + ); + const result = spawnSync(process.execPath, [file], { cwd, encoding: 'utf8' }); + return result.status === 0 ? null : (result.stderr.match(/^\w*Error.*$/m)?.[0] ?? result.stderr.trim()); +}; + +const workDir = mkdtempSync(join(tmpdir(), 'react-datocms-package-')); + +try { + const tarball = join(workDir, run('npm', ['pack', '--ignore-scripts', '--silent', '--pack-destination', workDir])); + + const consumerDir = join(workDir, 'consumer'); + mkdirSync(consumerDir); + writeFileSync(join(consumerDir, 'package.json'), JSON.stringify({ name: 'consumer', private: true })); + run('npm', ['install', '--silent', '--no-audit', '--no-fund', tarball, ...peers], consumerDir); + + const failures = specifiers.flatMap((specifier) => + ['require', 'import'].flatMap((mode) => { + const error = load(consumerDir, specifier, mode); + console.log(`${error ? 'FAIL' : 'ok '} ${mode} ${specifier}${error ? `: ${error}` : ''}`); + return error ? [specifier] : []; + }), + ); + + console.log( + `\nNode ${process.version}: ${specifiers.length * 2 - failures.length}/${specifiers.length * 2} entry point loads succeeded`, + ); + process.exitCode = failures.length ? 1 : 0; +} finally { + rmSync(workDir, { recursive: true, force: true }); +}