diff --git a/.github/workflows/js.yml b/.github/workflows/js.yml index 5ec824be..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) 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..78db6c02 --- /dev/null +++ b/scripts/generate-cjs-types.mjs @@ -0,0 +1,123 @@ +// 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 +// (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. +// +// 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'; +import { fileURLToPath } from 'node:url'; +import ts from 'typescript'; + +const rootDir = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..'); +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`); +} + +// 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); +} + +// 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(esmEntryDeclaration)); + +const typeAliases = []; +for (const exported of checker.getExportsOfModule(moduleSymbol)) { + const name = exported.getName(); + if (name === 'default') { + continue; + } + 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`); + } + 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(); + +// 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; + +declare namespace Binance { +${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)); + } + } +} + +console.log(`Generated ${rel(cjsEntryDeclaration)} (${typeAliases.length} types)`); 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-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 new file mode 100755 index 00000000..f9859e3c --- /dev/null +++ b/tests/package-types.sh @@ -0,0 +1,33 @@ +#!/bin/bash +# 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" +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/*.json "$WORK_DIR"/ + +cd "$WORK_DIR" +echo '{ "name": "package-types-test", "private": true }' > package.json +npm install --no-audit --no-fund --loglevel=error "./$TARBALL" + +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 [ $status -eq 0 ]; then + echo "Package types test successful" +else + echo "Package types test failed" +fi +exit $status