import util from 'util';
import fs from 'fs';
import copyNodeModules from 'copy-node-modules';
import { exec } from 'child_process';
const distModules = './dist/node_modules';
const modules = './node_modules';
const exists = util.promisify(fs.exists);
console.log('Running TS Watcher');
const watcher = exec('npm run watch', async () => {
await compile();
});
(async function start() {
// in order to start the watcher before the serverless itself
await delay(2000);
})();
function delay(t) {
return new Promise((resolve) => {
setTimeout(async () => {
await compile();
resolve();
}, t);
});
}
async function compile() {
try {
if (await exists(distModules)) {
console.log('node_modules found');
process.exit(0);
} else if (await exists(modules)) {
console.log('Copying node_modules to dist.');
copyNodeModules('', './dist', { devDependencies: false }, (err, results) => {
if (err) {
console.error(err);
process.exit(1);
}
Object.keys(results).forEach((name) => {
const version = results[name];
console.log(`Package name: ${name}, version: ${version}`);
});
process.exit(0);
});
} else {
console.error('run "npm install" before "run localhost"');
process.exit(1);
}
} catch (e) {
console.error(e);
watcher.kill('SIGINT');
}
}
process.on('SIGINT', () => {
watcher.kill('SIGINT');
});