const fs = require('fs');
let code = fs.readFileSync('background.js', 'utf8');
let lines = code.split('\n');

// Revert any previous broken injections first
lines[127] = lines[127].replace(
  /chrome\.runtime\.onMessage\.addListener\(\(s => \(s && \["localProcess","openLocalSetup","validateKey","nativeSync","recordDb","checkBatchDb"\]\.includes\(s\.cmd\)\) \? false : e\(void 0, void 0, void 0, \(function\* \(\) \{/g,
  'chrome.runtime.onMessage.addListener((s => e(void 0, void 0, void 0, (function* () {'
);

// 1. Fix the syntax error at the end of the listener
lines[127] = lines[127].replace(/\} \}\)\)\)\) \}; const s =/g, '} })))) ; const s =');

// 2. Inject the ternary operator to bypass the original listener
lines[127] = lines[127].replace(
  'chrome.runtime.onMessage.addListener((s => e(void 0, void 0, void 0, (function* () {',
  'chrome.runtime.onMessage.addListener((s => (s && ["localProcess","openLocalSetup","validateKey","nativeSync","recordDb","checkBatchDb"].includes(s.cmd)) ? false : e(void 0, void 0, void 0, (function* () {'
);

fs.writeFileSync('background.js', lines.join('\n'));
console.log('Fixed syntax and injected ternary operator.');
