From 6a983c1c973eb51bf96ac7a5d372394de049f967 Mon Sep 17 00:00:00 2001 From: Oleg Date: Thu, 28 Nov 2024 10:54:53 +0000 Subject: [PATCH] syntax validation in build.js --- tasks/CLFScripts/build.ts | 23 +++++++++++++++++++++-- 1 file changed, 21 insertions(+), 2 deletions(-) diff --git a/tasks/CLFScripts/build.ts b/tasks/CLFScripts/build.ts index f6e399db..9fcae751 100644 --- a/tasks/CLFScripts/build.ts +++ b/tasks/CLFScripts/build.ts @@ -7,7 +7,7 @@ import {task, types} from 'hardhat/config'; import log, {err} from '../../utils/log'; import fs from 'fs'; import path from 'path'; - +import vm from 'vm'; export const pathToScript = [__dirname, '../', 'CLFScripts']; function checkFileAccessibility(filePath) { @@ -17,6 +17,22 @@ function checkFileAccessibility(filePath) { } } +/* Validates the JavaScript syntax of the file content */ +function validateSyntax(content, filePath) { + const ignoredErrors = [ + 'Cannot use import statement outside a module', + 'await is only valid in async functions and the top level bodies of modules', + ]; + try { + new vm.Script(content); + } catch (error) { + if (ignoredErrors.includes(error.message)) return; + + err(`Syntax error in file ${filePath}: ${error.message}`, 'validateSyntax'); + process.exit(1); + } +} + /* replaces any strings of the form ${VAR_NAME} with the value of the environment variable VAR_NAME */ function replaceEnvironmentVariables(content) { let missingVariable = false; @@ -76,6 +92,8 @@ function build(fileToBuild: string, quiet: boolean): void { try { let fileContent = fs.readFileSync(fileToBuild, 'utf8'); + validateSyntax(fileContent, fileToBuild); + fileContent = replaceEnvironmentVariables(fileContent); const cleanedUpFile = cleanupFile(fileContent); const minifiedFile = minifyFile(cleanedUpFile); @@ -85,9 +103,10 @@ function build(fileToBuild: string, quiet: boolean): void { scriptType = 'infra'; } - // Save the cleaned-up and minified versions saveProcessedFile(cleanedUpFile, fileToBuild, scriptType, quiet); saveProcessedFile(minifiedFile, fileToBuild.replace('.js', '.min.js'), scriptType, quiet); + validateSyntax(cleanedUpFile, fileToBuild); + validateSyntax(minifiedFile, fileToBuild); } catch (error) { err(`Error processing file ${fileToBuild}: ${error}`, 'buildScript'); process.exit(1);