diff options
Diffstat (limited to 'scripts/frontend/preinstall.mjs')
-rw-r--r-- | scripts/frontend/preinstall.mjs | 59 |
1 files changed, 59 insertions, 0 deletions
diff --git a/scripts/frontend/preinstall.mjs b/scripts/frontend/preinstall.mjs new file mode 100644 index 00000000000..09d980344ea --- /dev/null +++ b/scripts/frontend/preinstall.mjs @@ -0,0 +1,59 @@ +import { dirname, join } from 'node:path'; +import { fileURLToPath } from 'node:url'; +import { readFile, rm } from 'node:fs/promises'; + +const ROOT_PATH = join(dirname(fileURLToPath(import.meta.url)), '..', '..'); +const NODE_MODULES = join(ROOT_PATH, 'node_modules'); +const INTEGRITY_FILE = join(NODE_MODULES, '.yarn-integrity'); +const PACKAGE_JSON = join(ROOT_PATH, 'package.json'); + +function isAliasedDependency(x) { + return x.includes('@npm:'); +} +function serializeAliasedDependencyPatterns(obj) { + return Object.entries(obj).map(([key, version]) => `${key}@${version}`); +} + +async function readJSON(file) { + return JSON.parse(await readFile(file, { encoding: 'utf-8' })); +} + +async function getPrevTopLevelPatterns() { + try { + return (await readJSON(INTEGRITY_FILE))?.topLevelPatterns?.filter(isAliasedDependency); + } catch { + return []; + } +} +async function getCurrentTopLevelPatterns() { + try { + const { dependencies, devDependencies } = await readJSON(PACKAGE_JSON); + + return serializeAliasedDependencyPatterns(dependencies) + .concat(serializeAliasedDependencyPatterns(devDependencies)) + .filter(isAliasedDependency); + } catch { + return []; + } +} + +function arraysHaveSameItems(a1, a2) { + return JSON.stringify(a1.sort()) === JSON.stringify(a2.sort()); +} + +const [prevTopLevelPatterns, currentTopLevelPatterns] = await Promise.all([ + getPrevTopLevelPatterns(), + getCurrentTopLevelPatterns(), +]); + +/** + * Yarn seems to have problems at times, if one uses an <alias>@npm:<name> + * and those packages are being updated. In case one switches branches the + * node_modules folder seems to end up being a corrupted somehow + */ +if (!arraysHaveSameItems(prevTopLevelPatterns, currentTopLevelPatterns)) { + console.error( + '[WARNING] package.json changed significantly. Removing node_modules to be sure there are no problems.', + ); + await rm(NODE_MODULES, { recursive: true, force: true }); +} |