From 3893c121785e4a11bd2577eed3bfb2b1c429ecc8 Mon Sep 17 00:00:00 2001 From: Claude Date: Mon, 16 Nov 2026 00:42:59 +0000 Subject: [PATCH 1/4] test: type-check the packed package from CJS and ESM consumers Adds tests/package-types.sh, which packs the package, installs it into a fresh consumer project and runs tsc under --module nodenext against a CommonJS (.cts) and an ES module (.mts) consumer. The CJS cases currently fail with TS7016 because the `require` export has no declarations (#1010). Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01XpTLXUxpfhtzV8YPuQiJAh --- .github/workflows/js.yml | 2 ++ .../package-types-test/cjs-default-import.cts | 12 +++++++++ tests/package-types-test/cjs-require.cts | 20 ++++++++++++++ tests/package-types-test/esm-import.mts | 14 ++++++++++ tests/package-types-test/tsconfig.json | 11 ++++++++ tests/package-types.sh | 27 +++++++++++++++++++ 6 files changed, 86 insertions(+) create mode 100644 tests/package-types-test/cjs-default-import.cts create mode 100644 tests/package-types-test/cjs-require.cts create mode 100644 tests/package-types-test/esm-import.mts create mode 100644 tests/package-types-test/tsconfig.json create mode 100755 tests/package-types.sh diff --git a/.github/workflows/js.yml b/.github/workflows/js.yml index 5ec824be..c46e2f07 100644 --- a/.github/workflows/js.yml +++ b/.github/workflows/js.yml @@ -41,5 +41,7 @@ jobs: run: npm run test-cjs - name: Package test run: npm run package-test + - name: Package types test + run: npm run package-types-test - name: Ws Live Tests run: npm run ws-live-tests diff --git a/tests/package-types-test/cjs-default-import.cts b/tests/package-types-test/cjs-default-import.cts new file mode 100644 index 00000000..43673461 --- /dev/null +++ b/tests/package-types-test/cjs-default-import.cts @@ -0,0 +1,12 @@ +// CommonJS consumer using a default import (esModuleInterop, on by default under nodenext). +import Binance from 'node-binance-api'; +import type { Interval } from 'node-binance-api'; + +const client = new Binance(); +const interval: Interval = '1h'; +client.prices('BTCUSDT'); + +// @ts-expect-error - method does not exist on Binance +client.thisMethodDoesNotExist(); + +export { interval }; diff --git a/tests/package-types-test/cjs-require.cts b/tests/package-types-test/cjs-require.cts new file mode 100644 index 00000000..92d6bb77 --- /dev/null +++ b/tests/package-types-test/cjs-require.cts @@ -0,0 +1,20 @@ +// CommonJS consumer using `import = require` (compiles to `require('node-binance-api')`). +import Binance = require('node-binance-api'); + +const client: Binance = new Binance({ APIKEY: 'key', APISECRET: 'secret' }); +const prices: Promise = client.prices('BTCUSDT'); +client.options({ test: true }); + +// Named types must be reachable through the `export =` namespace. +const interval: Binance.Interval = '1m'; +const side: Binance.OrderSide = 'BUY'; +const dict: Binance.Dictionary = { a: 1 }; +let order: Binance.Order | undefined; + +// Guards against the module silently resolving to `any`. +// @ts-expect-error - method does not exist on Binance +client.thisMethodDoesNotExist(); +// @ts-expect-error - invalid interval literal +const badInterval: Binance.Interval = 'not-an-interval'; + +export { prices, interval, side, dict, order, badInterval }; diff --git a/tests/package-types-test/esm-import.mts b/tests/package-types-test/esm-import.mts new file mode 100644 index 00000000..a6205f80 --- /dev/null +++ b/tests/package-types-test/esm-import.mts @@ -0,0 +1,14 @@ +// ES module consumer. +import Binance from 'node-binance-api'; +import type { Interval, Order, Dictionary } from 'node-binance-api'; + +const client = new Binance({ APIKEY: 'key', APISECRET: 'secret' }); +const interval: Interval = '1d'; +const dict: Dictionary = { a: 'b' }; +let order: Order | undefined; +client.prices('BTCUSDT'); + +// @ts-expect-error - method does not exist on Binance +client.thisMethodDoesNotExist(); + +export { interval, dict, order }; diff --git a/tests/package-types-test/tsconfig.json b/tests/package-types-test/tsconfig.json new file mode 100644 index 00000000..d6858d2d --- /dev/null +++ b/tests/package-types-test/tsconfig.json @@ -0,0 +1,11 @@ +{ + "compilerOptions": { + "module": "nodenext", + "moduleResolution": "nodenext", + "target": "ES2022", + "strict": true, + "noEmit": true, + "types": [] + }, + "files": ["cjs-require.cts", "cjs-default-import.cts", "esm-import.mts"] +} diff --git a/tests/package-types.sh b/tests/package-types.sh new file mode 100755 index 00000000..620af769 --- /dev/null +++ b/tests/package-types.sh @@ -0,0 +1,27 @@ +#!/bin/bash +# Type-checks the packed package from CommonJS and ESM consumers under +# `--module nodenext`, to make sure every `exports` entry ships declarations. +set -u + +ROOT_DIR="$(cd "$(dirname "$0")/.." && pwd)" +TSC="$ROOT_DIR/node_modules/.bin/tsc" +WORK_DIR="$(mktemp -d)" +trap 'rm -rf "$WORK_DIR"' EXIT + +cd "$ROOT_DIR" +TARBALL="$(npm pack . --silent --pack-destination "$WORK_DIR" | tail -n 1)" +cp ./tests/package-types-test/*.cts ./tests/package-types-test/*.mts ./tests/package-types-test/tsconfig.json "$WORK_DIR"/ + +cd "$WORK_DIR" +echo '{ "name": "package-types-test", "private": true }' > package.json +npm install --silent --no-audit --no-fund "./$TARBALL" > /dev/null + +"$TSC" -p tsconfig.json +return_code=$? + +if [ $return_code -eq 0 ]; then + echo "Package types test successful" +else + echo "Package types test failed" +fi +exit $return_code From 1b0e049789bef66de5d0eaa86faef1474acaccb8 Mon Sep 17 00:00:00 2001 From: Claude Date: Mon, 16 Nov 2026 00:42:59 +0000 Subject: [PATCH 2/4] fix: ship type declarations for the CommonJS `require` entry Under --module node16/nodenext TypeScript resolves types through `exports` and ignores the top-level `typings` field, so CommonJS consumers got TS7016 because `exports["."].require` had no declarations. - Add `types` conditions to both the `import` and `require` exports. - Generate dist/cjs/node-binance-api.d.cts at build time. The CJS bundle does `module.exports = Binance`, so the declaration uses `export =` and re-exposes the ESM type exports via a merged namespace (Binance.Order, or `import type { Order } from 'node-binance-api'`). The type list is read from the emitted ESM declarations so it stays in sync with src/. - Add `bundle-cjs-types` to the build and a `package-types-test` script. Fixes #1010 Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01XpTLXUxpfhtzV8YPuQiJAh --- package.json | 14 +++++-- scripts/generate-cjs-types.mjs | 70 ++++++++++++++++++++++++++++++++++ 2 files changed, 81 insertions(+), 3 deletions(-) create mode 100644 scripts/generate-cjs-types.mjs diff --git a/package.json b/package.json index 6ece2ee6..5ff3c974 100644 --- a/package.json +++ b/package.json @@ -6,8 +6,14 @@ "type": "module", "exports": { ".": { - "import": "./dist/node-binance-api.js", - "require": "./dist/cjs/node-binance-api.cjs" + "import": { + "types": "./dist/node-binance-api.d.ts", + "default": "./dist/node-binance-api.js" + }, + "require": { + "types": "./dist/cjs/node-binance-api.d.cts", + "default": "./dist/cjs/node-binance-api.cjs" + } } }, "dependencies": { @@ -22,7 +28,7 @@ "@types/ws": "^8.18.0" }, "scripts": { - "build": "tsc && npm run bundle-cjs", + "build": "tsc && npm run bundle-cjs && npm run bundle-cjs-types", "test": "mocha ./tests/live-tests.cjs", "static-test": "mocha ./tests/static-tests.mjs", "ts-test-live": "mocha ./tests/binance-class-live.test.ts", @@ -42,7 +48,9 @@ "codacy": "cat ./coverage/lcov.info | codacy-coverage -v", "codecov": "codecov", "bundle-cjs": "mkdir -p dist/cjs && rollup -c rollup.config.js", + "bundle-cjs-types": "node ./scripts/generate-cjs-types.mjs", "package-test": "./tests/package.sh", + "package-types-test": "./tests/package-types.sh", "publishPackage": "npm run build && sh publish.sh && git push && git push --tags && npm publish", "rollup-plugin-execute": "^1.1.1" }, diff --git a/scripts/generate-cjs-types.mjs b/scripts/generate-cjs-types.mjs new file mode 100644 index 00000000..f4f2cf76 --- /dev/null +++ b/scripts/generate-cjs-types.mjs @@ -0,0 +1,70 @@ +// Generates dist/cjs/node-binance-api.d.cts, the type declarations for the +// CommonJS (`require`) entry of the package. +// +// The CJS bundle produced by rollup does `module.exports = Binance`, so its +// declarations must use `export =` rather than `export default`. Every other +// (type-only) export of the ESM entry is re-exposed through a namespace merged +// with the class, so CJS consumers can write `Binance.Order`, and +// `import type { Order } from 'node-binance-api'` keeps working. +// +// The export list is read from the emitted ESM declarations with the +// TypeScript compiler API, so new types in src/ are picked up automatically. + +import fs from 'node:fs'; +import path from 'node:path'; +import { fileURLToPath } from 'node:url'; +import ts from 'typescript'; + +const rootDir = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..'); +const esmDeclarationFile = path.join(rootDir, 'dist', 'node-binance-api.d.ts'); +const cjsDeclarationFile = path.join(rootDir, 'dist', 'cjs', 'node-binance-api.d.cts'); + +if (!fs.existsSync(esmDeclarationFile)) { + throw new Error(`${path.relative(rootDir, esmDeclarationFile)} not found, run tsc first`); +} + +const program = ts.createProgram([esmDeclarationFile], { + module: ts.ModuleKind.NodeNext, + moduleResolution: ts.ModuleResolutionKind.NodeNext, + noEmit: true, + skipLibCheck: true, +}); +const checker = program.getTypeChecker(); +const moduleSymbol = checker.getSymbolAtLocation(program.getSourceFile(esmDeclarationFile)); + +const typeAliases = []; +for (const exported of checker.getExportsOfModule(moduleSymbol)) { + const name = exported.getName(); + if (name === 'default') { + continue; + } + const target = exported.flags & ts.SymbolFlags.Alias ? checker.getAliasedSymbol(exported) : exported; + if (target.flags & ts.SymbolFlags.Value) { + // A value export would also need to exist on the CJS `module.exports` + // object, which rollup's "default" export mode does not provide. + throw new Error(`Unsupported value export "${name}": only the default export may be a value`); + } + const declaration = target.declarations?.find((d) => d.typeParameters?.length); + const typeParameters = declaration?.typeParameters ?? []; + const params = typeParameters.length ? `<${typeParameters.map((p) => p.getText()).join(', ')}>` : ''; + const args = typeParameters.length ? `<${typeParameters.map((p) => p.name.getText()).join(', ')}>` : ''; + typeAliases.push(` export type ${name}${params} = ESM.${name}${args};`); +} +typeAliases.sort(); + +const output = `// This file is generated by scripts/generate-cjs-types.mjs. Do not edit. +import type * as ESM from '../node-binance-api.js'; + +declare const Binance: typeof ESM.default; +type Binance = ESM.default; + +declare namespace Binance { +${typeAliases.join('\n')} +} + +export = Binance; +`; + +fs.mkdirSync(path.dirname(cjsDeclarationFile), { recursive: true }); +fs.writeFileSync(cjsDeclarationFile, output); +console.log(`Generated ${path.relative(rootDir, cjsDeclarationFile)} (${typeAliases.length} types)`); From eb9eceecd49065ee608cfa6e396d4a70698f15ee Mon Sep 17 00:00:00 2001 From: Claude Date: Mon, 16 Nov 2026 13:11:54 +0000 Subject: [PATCH 3/4] test: also type-check CJS consumers under node16 and without esModuleInterop The package types test only ran under --module nodenext with the locked TypeScript 5.8, where a CommonJS declaration may import an ES module declaration. Run it under node16 as well, and add a pass with esModuleInterop disabled. Both currently fail (TS1541 and TS1259). Also make the script fail fast (set -euo pipefail) and stop hiding npm install errors. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01XpTLXUxpfhtzV8YPuQiJAh --- .../tsconfig.no-interop.json | 8 +++++++ tests/package-types.sh | 24 ++++++++++++------- 2 files changed, 23 insertions(+), 9 deletions(-) create mode 100644 tests/package-types-test/tsconfig.no-interop.json diff --git a/tests/package-types-test/tsconfig.no-interop.json b/tests/package-types-test/tsconfig.no-interop.json new file mode 100644 index 00000000..d121ac77 --- /dev/null +++ b/tests/package-types-test/tsconfig.no-interop.json @@ -0,0 +1,8 @@ +{ + "extends": "./tsconfig.json", + "compilerOptions": { + "esModuleInterop": false, + "allowSyntheticDefaultImports": false + }, + "files": ["cjs-require.cts", "esm-import.mts"] +} diff --git a/tests/package-types.sh b/tests/package-types.sh index 620af769..f9859e3c 100755 --- a/tests/package-types.sh +++ b/tests/package-types.sh @@ -1,7 +1,8 @@ #!/bin/bash -# Type-checks the packed package from CommonJS and ESM consumers under -# `--module nodenext`, to make sure every `exports` entry ships declarations. -set -u +# Type-checks the packed package from CommonJS and ESM consumers, to make sure +# every `exports` entry ships declarations that resolve and type-check +# (skipLibCheck is off) under each Node-style module mode. +set -euo pipefail ROOT_DIR="$(cd "$(dirname "$0")/.." && pwd)" TSC="$ROOT_DIR/node_modules/.bin/tsc" @@ -10,18 +11,23 @@ trap 'rm -rf "$WORK_DIR"' EXIT cd "$ROOT_DIR" TARBALL="$(npm pack . --silent --pack-destination "$WORK_DIR" | tail -n 1)" -cp ./tests/package-types-test/*.cts ./tests/package-types-test/*.mts ./tests/package-types-test/tsconfig.json "$WORK_DIR"/ +cp ./tests/package-types-test/*.cts ./tests/package-types-test/*.mts ./tests/package-types-test/*.json "$WORK_DIR"/ cd "$WORK_DIR" echo '{ "name": "package-types-test", "private": true }' > package.json -npm install --silent --no-audit --no-fund "./$TARBALL" > /dev/null +npm install --no-audit --no-fund --loglevel=error "./$TARBALL" -"$TSC" -p tsconfig.json -return_code=$? +status=0 +for mode in node16 nodenext; do + echo "tsc --module $mode" + "$TSC" -p tsconfig.json --module "$mode" --moduleResolution "$mode" || status=1 + echo "tsc --module $mode --esModuleInterop false" + "$TSC" -p tsconfig.no-interop.json --module "$mode" --moduleResolution "$mode" || status=1 +done -if [ $return_code -eq 0 ]; then +if [ $status -eq 0 ]; then echo "Package types test successful" else echo "Package types test failed" fi -exit $return_code +exit $status From 89984fa51c87f4fe5cac7eac22a2dbed60b97a9d Mon Sep 17 00:00:00 2001 From: Claude Date: Mon, 16 Nov 2026 13:11:54 +0000 Subject: [PATCH 4/4] fix: emit CommonJS copies of the declarations for the require entry The generated dist/cjs/node-binance-api.d.cts imported the ESM declarations, which TypeScript rejects from a CommonJS file under --module node16/node18, and under nodenext before 5.8 (TS1541/TS1479) when skipLibCheck is off. - Copy dist/*.d.ts to dist/cjs/types/*.d.cts, rewriting relative imports to the .cjs copies and package default imports (`import WebSocket from 'ws'`) to `import X = require(...)` so they also work with esModuleInterop disabled. - Type-check the generated declarations at the end of the generator (node16 and nodenext, esModuleInterop on and off, skipLibCheck off), so the build fails instead of shipping broken types. - Don't treat type-only re-exports of classes as value exports. - Run the package types test right after the build in CI. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01XpTLXUxpfhtzV8YPuQiJAh --- .github/workflows/js.yml | 4 +- scripts/generate-cjs-types.mjs | 85 +++++++++++++++++++++++++++------- 2 files changed, 71 insertions(+), 18 deletions(-) diff --git a/.github/workflows/js.yml b/.github/workflows/js.yml index c46e2f07..1208c8cf 100644 --- a/.github/workflows/js.yml +++ b/.github/workflows/js.yml @@ -27,6 +27,8 @@ jobs: run: npm run lint - name: Build run: npm run build + - name: Package types test + run: npm run package-types-test - name: Crypto Tests run: npm run crypto-tests - name: Static Tests (TS ESM) @@ -41,7 +43,5 @@ jobs: run: npm run test-cjs - name: Package test run: npm run package-test - - name: Package types test - run: npm run package-types-test - name: Ws Live Tests run: npm run ws-live-tests diff --git a/scripts/generate-cjs-types.mjs b/scripts/generate-cjs-types.mjs index f4f2cf76..78db6c02 100644 --- a/scripts/generate-cjs-types.mjs +++ b/scripts/generate-cjs-types.mjs @@ -1,5 +1,5 @@ -// Generates dist/cjs/node-binance-api.d.cts, the type declarations for the -// CommonJS (`require`) entry of the package. +// Generates the type declarations for the CommonJS (`require`) entry of the +// package, dist/cjs/node-binance-api.d.cts. // // The CJS bundle produced by rollup does `module.exports = Binance`, so its // declarations must use `export =` rather than `export default`. Every other @@ -7,8 +7,14 @@ // with the class, so CJS consumers can write `Binance.Order`, and // `import type { Order } from 'node-binance-api'` keeps working. // +// A CommonJS declaration file may not import an ES module declaration file +// under --module node16/node18 (or nodenext before TypeScript 5.8), so the +// emitted ESM declarations are first copied to dist/cjs/types/ as .d.cts files +// and the entry declaration imports those copies. +// // The export list is read from the emitted ESM declarations with the // TypeScript compiler API, so new types in src/ are picked up automatically. +// The result is type-checked (skipLibCheck off) before the script succeeds. import fs from 'node:fs'; import path from 'node:path'; @@ -16,21 +22,45 @@ import { fileURLToPath } from 'node:url'; import ts from 'typescript'; const rootDir = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..'); -const esmDeclarationFile = path.join(rootDir, 'dist', 'node-binance-api.d.ts'); -const cjsDeclarationFile = path.join(rootDir, 'dist', 'cjs', 'node-binance-api.d.cts'); +const distDir = path.join(rootDir, 'dist'); +const cjsDir = path.join(distDir, 'cjs'); +const cjsTypesDir = path.join(cjsDir, 'types'); +const entryName = 'node-binance-api'; +const esmEntryDeclaration = path.join(distDir, `${entryName}.d.ts`); +const cjsEntryDeclaration = path.join(cjsDir, `${entryName}.d.cts`); +const rel = (file) => path.relative(rootDir, file); + +if (!fs.existsSync(esmEntryDeclaration)) { + throw new Error(`${rel(esmEntryDeclaration)} not found, run tsc first`); +} -if (!fs.existsSync(esmDeclarationFile)) { - throw new Error(`${path.relative(rootDir, esmDeclarationFile)} not found, run tsc first`); +// 1. Copy dist/*.d.ts to dist/cjs/types/*.d.cts: +// - point relative imports at the .cjs copies (`./x.cjs` maps to `./x.d.cts`); +// - turn default imports of packages (e.g. `import WebSocket from 'ws'`) into +// `import X = require('pkg')`, which unlike a default import of an +// `export =` module also type-checks with esModuleInterop disabled. +fs.rmSync(cjsTypesDir, { recursive: true, force: true }); +fs.mkdirSync(cjsTypesDir, { recursive: true }); +for (const file of fs.readdirSync(distDir)) { + if (!file.endsWith('.d.ts')) { + continue; + } + const source = fs.readFileSync(path.join(distDir, file), 'utf8'); + const rewritten = source + .replace(/(['"])(\.{1,2}\/[^'"]+)\.js\1/g, '$1$2.cjs$1') + .replace(/^import (\w+) from (['"])([^.'"][^'"]*)\2;$/gm, 'import $1 = require($2$3$2);'); + fs.writeFileSync(path.join(cjsTypesDir, file.replace(/\.d\.ts$/, '.d.cts')), rewritten); } -const program = ts.createProgram([esmDeclarationFile], { +// 2. Collect the type exports of the ESM entry. +const program = ts.createProgram([esmEntryDeclaration], { module: ts.ModuleKind.NodeNext, moduleResolution: ts.ModuleResolutionKind.NodeNext, noEmit: true, skipLibCheck: true, }); const checker = program.getTypeChecker(); -const moduleSymbol = checker.getSymbolAtLocation(program.getSourceFile(esmDeclarationFile)); +const moduleSymbol = checker.getSymbolAtLocation(program.getSourceFile(esmEntryDeclaration)); const typeAliases = []; for (const exported of checker.getExportsOfModule(moduleSymbol)) { @@ -38,8 +68,10 @@ for (const exported of checker.getExportsOfModule(moduleSymbol)) { if (name === 'default') { continue; } - const target = exported.flags & ts.SymbolFlags.Alias ? checker.getAliasedSymbol(exported) : exported; - if (target.flags & ts.SymbolFlags.Value) { + const isAlias = (exported.flags & ts.SymbolFlags.Alias) !== 0; + const target = isAlias ? checker.getAliasedSymbol(exported) : exported; + const isTypeOnlyExport = isAlias && checker.getTypeOnlyAliasDeclaration(exported) !== undefined; + if ((target.flags & ts.SymbolFlags.Value) && !isTypeOnlyExport) { // A value export would also need to exist on the CJS `module.exports` // object, which rollup's "default" export mode does not provide. throw new Error(`Unsupported value export "${name}": only the default export may be a value`); @@ -52,8 +84,9 @@ for (const exported of checker.getExportsOfModule(moduleSymbol)) { } typeAliases.sort(); -const output = `// This file is generated by scripts/generate-cjs-types.mjs. Do not edit. -import type * as ESM from '../node-binance-api.js'; +// 3. Write the entry declaration. +fs.writeFileSync(cjsEntryDeclaration, `// This file is generated by scripts/generate-cjs-types.mjs. Do not edit. +import type * as ESM from './types/${entryName}.cjs'; declare const Binance: typeof ESM.default; type Binance = ESM.default; @@ -63,8 +96,28 @@ ${typeAliases.join('\n')} } export = Binance; -`; +`); + +// 4. Type-check the generated declarations the way consumers will see them. +for (const mode of [ts.ModuleKind.Node16, ts.ModuleKind.NodeNext]) { + for (const esModuleInterop of [true, false]) { + const check = ts.createProgram([cjsEntryDeclaration], { + module: mode, + moduleResolution: mode === ts.ModuleKind.Node16 ? ts.ModuleResolutionKind.Node16 : ts.ModuleResolutionKind.NodeNext, + esModuleInterop, + allowSyntheticDefaultImports: esModuleInterop, + strict: true, + noEmit: true, + skipLibCheck: false, + types: [], + }); + const diagnostics = ts.getPreEmitDiagnostics(check); + if (diagnostics.length) { + const host = { getCanonicalFileName: (f) => f, getCurrentDirectory: () => rootDir, getNewLine: () => '\n' }; + throw new Error(`Generated CJS declarations do not type-check (module ${ts.ModuleKind[mode]}, esModuleInterop ${esModuleInterop}):\n` + + ts.formatDiagnostics(diagnostics, host)); + } + } +} -fs.mkdirSync(path.dirname(cjsDeclarationFile), { recursive: true }); -fs.writeFileSync(cjsDeclarationFile, output); -console.log(`Generated ${path.relative(rootDir, cjsDeclarationFile)} (${typeAliases.length} types)`); +console.log(`Generated ${rel(cjsEntryDeclaration)} (${typeAliases.length} types)`);