Skip to content

Instantly share code, notes, and snippets.

@janpapenbrock
Last active January 4, 2025 00:31
Show Gist options
  • Save janpapenbrock/66c1d1344910ba40b86bbe19b51f36af to your computer and use it in GitHub Desktop.
Save janpapenbrock/66c1d1344910ba40b86bbe19b51f36af to your computer and use it in GitHub Desktop.
patch-ngxs-noop

patch-ngxs-noop

To apply this automatically after npm install, add this to your main project's package.json:

{
  [...]
  "scripts": {
     [...]
     "postinstall" : "node patch-ngxs-noop/index.js"
  }
}
import {readFile, writeFile} from "node:fs/promises";
import {resolve} from "node:path";
// Specify the file path
const filePath = resolve('node_modules/@ngxs/store/fesm2022/ngxs-store.mjs');
// The text to be replaced
const oldText = `// This is used to replace \`setState\` and \`patchState\` once the action
// handler has been unsubscribed or completed, to prevent writing
// to the state context.
function noop() { }`;
const PATCH_MARKER = '// PATCHED NOOP'
// The new text to replace the old one
const newText = `${PATCH_MARKER}
// This is used to replace \`setState\` and \`patchState\` once the action
// handler has been unsubscribed or completed, to prevent writing
// to the state context.
import { captureException } from '@sentry/angular';
function noop(...args) {
const ex = new Error('State noop encountered; payload keys: ' + JSON.stringify(args.map(arg => Object.keys(arg))));
captureException(ex);
console.error(ex);
}
${PATCH_MARKER}`;
// Function to replace text in a file
const replaceTextInFile = async (filePath, oldText, newText) => {
try {
// Read the file
const data = await readFile(filePath, { encoding: 'utf8' });
/**
* We definitely want to error if we cannot find the noop to patch.
*/
if (!data.includes(oldText) && !data.includes(PATCH_MARKER)) {
console.error('File does not contain the noop() to replace.');
return;
}
const searchValue = data.includes(PATCH_MARKER) ? new RegExp(`${PATCH_MARKER}(.*)${PATCH_MARKER}`, 's') : oldText;
// Replace the old text with the new text
const updatedData = data.replace(searchValue, newText);
// Write the updated content back to the file
await writeFile(filePath, updatedData, { encoding: 'utf8' });
console.log('File updated successfully!');
} catch (err) {
console.error('Error occurred:', err);
}
};
// Call the function
replaceTextInFile(filePath, oldText, newText).then(() => {
console.log('Done');
});
{
"type": "module"
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment