@collectapp/checkout-sdk
Version:
Collect Africa Checkout library
114 lines (93 loc) • 2.63 kB
JavaScript
const { spawn, exec } = require('child_process');
const fs = require('fs');
const path = require('path');
// Configuration
const watchDir = './src';
const buildCommand = 'npm run build';
let serverProcess = null;
let debounceTimer = null;
let isBuilding = false;
const DEBOUNCE_TIME = 1000; // ms
// Start the server
function startServer() {
if (serverProcess) {
serverProcess.kill();
}
console.log('Starting server...');
serverProcess = spawn('node', ['server.js'], { stdio: 'inherit' });
serverProcess.on('close', code => {
if (code !== 0 && code !== null) {
console.error(`Server process exited with code ${code}`);
}
});
}
// Run build
function runBuild() {
if (isBuilding) {
console.log('Build already in progress, skipping...');
return;
}
isBuilding = true;
console.log('Building...');
exec(buildCommand, (error, stdout, stderr) => {
isBuilding = false;
if (error) {
console.error(`Build error: ${error.message}`);
return;
}
if (stderr && stderr.trim()) {
console.error(`Build stderr: ${stderr}`);
}
if (stdout && stdout.trim()) {
console.log(`Build stdout: ${stdout}`);
}
console.log('Build completed successfully');
});
}
// Watch for changes in the src directory
function watchForChanges() {
console.log(`Watching for changes in ${watchDir}...`);
fs.watch(watchDir, { recursive: true }, (eventType, filename) => {
if (filename && filename.endsWith('.ts')) {
// Debounce to avoid multiple builds for the same change
clearTimeout(debounceTimer);
debounceTimer = setTimeout(() => {
console.log(`Change detected in ${filename}, rebuilding...`);
runBuild();
}, DEBOUNCE_TIME);
}
});
}
// Start TypeScript compiler in watch mode
function startTypeScriptWatch() {
console.log('Starting TypeScript compiler in watch mode...');
const tscProcess = spawn('npx', ['tsc', '--watch', '--incremental'], {
stdio: 'inherit',
});
tscProcess.on('close', code => {
if (code !== 0 && code !== null) {
console.error(`TypeScript compiler exited with code ${code}`);
}
});
}
// Main function
function main() {
console.log('Starting development environment...');
// Initial build
runBuild();
// Start TypeScript watch
startTypeScriptWatch();
// Start watching for changes
watchForChanges();
// Start server
startServer();
// Handle process termination
process.on('SIGINT', () => {
console.log('Shutting down...');
if (serverProcess) {
serverProcess.kill();
}
process.exit(0);
});
}
main();