tsds-build
Version:
Development stack for TypeScript libraries
68 lines (67 loc) • 3.26 kB
JavaScript
var _ref;
var _os_cpus;
import fs from 'fs';
import { copyFile } from 'fs-copy-compat';
import Iterator from 'fs-iterator';
import mkdirp from 'mkdirp-classic';
import os from 'os';
import path from 'path';
import Queue from 'queue-cb';
import { transformDirectory, transformTypes } from 'ts-swc-transform';
import { loadConfig } from 'tsds-lib';
const MAX_FILES = 10;
const concurrency = Math.min(64, Math.max(8, ((_ref = (_os_cpus = os.cpus()) === null || _os_cpus === void 0 ? void 0 : _os_cpus.length) !== null && _ref !== void 0 ? _ref : 4) * 8));
const reportFn = (dest, type, cb)=>(err, results)=>{
var _ref;
if (err) console.log(`${type} failed: ${err.message}`);
else console.log(`Created ${((_ref = results === null || results === void 0 ? void 0 : results.length) !== null && _ref !== void 0 ? _ref : 0) < MAX_FILES ? results === null || results === void 0 ? void 0 : results.map((x)=>`dist/${type}/${path.relative(dest, x)}`).join(',') : `${results === null || results === void 0 ? void 0 : results.length} files in dist/${type}`}`);
cb(err);
};
export default function files(_args, type, options, callback) {
const config = loadConfig(options);
if (!config) {
console.log('tsds: no config. Skipping');
return callback();
}
if (!config.source) {
console.log(`tsds: config missing source. Skipping code: ${type}`);
return callback();
}
const cwd = options.cwd || process.cwd();
const src = path.dirname(path.join(cwd, config.source));
const dest = path.join(cwd, 'dist', type);
mkdirp(dest, (err)=>{
if (err) return callback(err);
const queue = new Queue();
queue.defer((cb)=>fs.writeFile(path.join(dest, 'package.json'), `{ "type": "${type === 'cjs' ? 'commonjs' : 'module'}" }`, 'utf8', (err)=>cb(err)));
queue.defer((cb)=>transformDirectory(src, dest, type, {
...options,
sourceMaps: true
}, reportFn(dest, type, cb)));
queue.defer((cb)=>transformTypes(src, dest, reportFn(dest, type, cb)));
queue.await((err)=>{
if (err) return callback(err);
if (type !== 'cjs') return callback();
// move the types into the folder with the correct extension
const iterator = new Iterator(dest);
iterator.forEach((entry, cb)=>{
const ext = path.extname(entry.basename);
const stats = entry.stats;
if (!stats || !stats.isFile() || [
'.js',
'.mjs'
].indexOf(ext) < 0) {
cb();
return;
}
const relative = path.relative(dest, path.dirname(entry.fullPath));
const sourcePath = path.join(dest, relative, `${entry.basename.slice(0, -ext.length)}.d.ts`);
const destPath = path.join(dest, relative, `${entry.basename.slice(0, -ext.length)}.d.${ext === '.js' ? 'cts' : 'mts'}`);
copyFile(sourcePath, destPath, (err)=>err && err.code !== 'ENOENT' ? cb(err) : cb());
}, {
callbacks: true,
concurrency
}, callback);
});
});
}