@combeenation/vite-plugin-custom-code-sync
Version:
Vite plugin to sync between a Combeenation configurator and the local IDE running a custom code project
97 lines • 3.52 kB
JavaScript
import fs from 'fs';
import { WebSocketServer } from 'ws';
const configFile = 'cbn.config.json';
const cfgrDefsFilePath = 'src/typings/cfgr-defs.generated.ts';
const wsPort = 5174;
var WsMsgType;
(function (WsMsgType) {
WsMsgType["ideCbnConfig"] = "ide-cbn-config";
WsMsgType["updateCbnConfig"] = "update-cbn-config";
WsMsgType["syncCfgrDefs"] = "sync-cfgr-defs";
WsMsgType["syncAck"] = "sync-ack";
})(WsMsgType || (WsMsgType = {}));
function CbnCustomCodeSync() {
let wss;
return {
name: 'vite-plugin-cbn-custom-code-sync',
configureServer(server) {
wss = new WebSocketServer({ port: wsPort });
wss.on('connection', function connection(ws) {
_sendConfigToClient(ws);
ws.on('message', function incoming(message) {
const msg = JSON.parse(message);
switch (msg.type) {
case WsMsgType.syncCfgrDefs:
_updateCfgrDefs(msg.payload, ws);
break;
case WsMsgType.updateCbnConfig:
_updateCbnConfig(msg.payload, ws);
break;
default:
console.error('Unknown msg:', msg.type);
break;
}
});
ws.on('close', function close() {
//console.log('Cfgr disconnected.');
});
});
console.log('Cbn WebSocket server attached on port', wsPort);
const configFileWatcher = (path) => {
if (path.endsWith(configFile)) {
for (const ws of wss.clients) {
_sendConfigToClient(ws);
}
}
};
server.watcher.on('add', configFileWatcher);
server.watcher.on('change', configFileWatcher);
server.watcher.on('unlink', configFileWatcher);
},
buildEnd() {
// Close the WebSocket server when the build finishes
if (wss) {
wss.close(() => {
console.log('WebSocket server closed');
});
}
},
};
}
function _sendConfigToClient(ws) {
if (fs.existsSync(configFile)) {
const syncInfos = fs.readFileSync(configFile, 'utf-8');
_send(ws, WsMsgType.ideCbnConfig, syncInfos);
}
else {
_send(ws, WsMsgType.ideCbnConfig, '{}');
}
}
function _updateCfgrDefs(data, ws) {
try {
fs.writeFileSync(cfgrDefsFilePath, data);
console.log('[Cbn] Updated cfgr definitions successfully.');
}
catch (ex) {
_send(ws, WsMsgType.syncAck, { success: false });
console.error('[Cbn] Error when writing definitions file.', ex);
}
_send(ws, WsMsgType.syncAck, { success: true });
}
function _updateCbnConfig(data, ws) {
try {
fs.writeFileSync(configFile, data);
console.log('[Cbn] Updated cbn config successfully.');
_sendConfigToClient(ws);
}
catch (ex) {
_send(ws, WsMsgType.syncAck, { success: false });
console.error('[Cbn] Error when writing definitions file.', ex);
}
_send(ws, WsMsgType.syncAck, { success: true });
}
function _send(ws, type, payload) {
ws.send(JSON.stringify({ type: type, payload: payload }));
}
export default CbnCustomCodeSync;
//# sourceMappingURL=index.js.map