Skip to content

Commit

Permalink
Merge pull request #16 from wpdas/feature/core-improvement-beta-24
Browse files Browse the repository at this point in the history
Feature: Code Improvement for version Beta 24
  • Loading branch information
wpdas authored Apr 22, 2024
2 parents 26332ff + 9cf7e9f commit d1ff2a2
Show file tree
Hide file tree
Showing 9 changed files with 132 additions and 2 deletions.
24 changes: 24 additions & 0 deletions lib/actions/injectFoundRegExps.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
const regexObjects = require("../parsers/regex-parser/regexObjects");

/**
* Troca as referencias de expressoes regulares com elas sendo devidamente escapadas. Isso é necessário
* pois todas as expressoes encontradas sao extraídas para depois serem realocadas de forma formatada/escapada
* corretamente no código final.
*
* @param {*} bundleContent
* @returns
*/
const injectFoundRegExps = (bundleContent) => {
const expressions = regexObjects.getExpressions();
const exps = Object.keys(expressions);
exps.forEach((expressionKey) => {
bundleContent = bundleContent.replaceAll(
`"${expressionKey}"`,
expressions[expressionKey],
);
});

return bundleContent;
};

module.exports = injectFoundRegExps;
11 changes: 10 additions & 1 deletion lib/actions/loadFilesInfo.js
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,8 @@ const transformComponentReferenceToJSX = require("../parsers/transformComponentR
const hasWidgetPropsCheck = require("./hasWidgetPropsCheck");
const { removeImports } = require("../parse");
const filesContentCache = require("../config/filesContentCache");

const replaceRegexWithReferences = require("../parsers/regex-parser/convertRegexToStringLiteral");
const regexObjects = require("../parsers/regex-parser/regexObjects");
/**
* Transform statefull components references to JSX (this applies for stateful and stateless components)
* Troca referencias de stateful components para JSX. Accesse o arquivo "transformComponentReferenceToJSX" para saber mais.
Expand Down Expand Up @@ -105,6 +106,14 @@ const processFileSchema = (filePath, processOnlyThisFile) => {

let fileContent = filesContentCache.getFileContent(filePath);

// Captura as expressoes regulares, salvam ela em um objeto para ser usado
// posteriormente no compiler.js através do "injectFoundRegExps.js"
const replaceRegexResult = replaceRegexWithReferences(fileContent);
if (replaceRegexResult.hasExpressions) {
fileContent = replaceRegexResult.code;
regexObjects.addExpressions(replaceRegexResult.expressions);
}

// Remove comments from file
// INFO: Esta sendo usado para remover comentários de arquivos jsx também
const removeCommentsResult = removeCommentsFromTSX(fileContent, filePath);
Expand Down
5 changes: 5 additions & 0 deletions lib/alem-vm/alem-vm.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -261,6 +261,11 @@ export declare const promisify: (
*/
export declare const isDevelopment: boolean;

/**
* Get the current environment. This can be set using NODE_ENV env var.
*/
export declare const getAlemEnvironment: () => string;

/**
* Create a debounced method to obtain the data after the desired interval.
* @param cb Callback
Expand Down
5 changes: 5 additions & 0 deletions lib/alem-vm/state.ts
Original file line number Diff line number Diff line change
Expand Up @@ -200,6 +200,11 @@ export const props = {
*/
isDevelopment: alemState().alemEnvironment === "development",

/**
* Get the Environment
*/
getAlemEnvironment: () => alemState().alemEnvironment,

// ==================================== Components|Widgets Code ====================================
componentsCode: {
COMPONENTS_CODE: {},
Expand Down
6 changes: 6 additions & 0 deletions lib/compiler.js
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@ const saveFileSchemas = require("./actions/saveFileSchemas");
const renderErrorDisplay = require("./actions/renderErrorDisplay");
const injectModules = require("./actions/injectModules");
const applyOptions = require("./actions/applyOptions");
const injectFoundRegExps = require("./actions/injectFoundRegExps");

const distFolder = process.env.DIST_FOLDER || "build";

Expand Down Expand Up @@ -100,6 +101,11 @@ function run_final_process(filesInfo) {
// Add sinatures
bundleContent = addSignatures(bundleContent);

// Troca as referencias de expressoes regulares com elas sendo devidamente escapadas. Isso é necessário
// pois todas as expressoes encontradas sao extraídas para depois serem realocadas de forma formatada/escapada
// corretamente no código final
bundleContent = injectFoundRegExps(bundleContent);

// Save final bundle file
saveFinalBundleFile(bundleContent);

Expand Down
1 change: 1 addition & 0 deletions lib/config/parseAlemFeatures.js
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ const parseAlemFeatures = (bundleContent) => {
.replaceAll("useParams(", "props.alem.useParams(")
.replaceAll("createRoute(", "props.alem.createRoute(")
.replaceAll("promisify(", "props.alem.promisify(")
.replaceAll("getAlemEnvironment(", "props.alem.getAlemEnvironment(")
.replaceAll(
/(?<!\.)\bisDevelopment\b(?![:.])/g,
"props.alem.isDevelopment",
Expand Down
51 changes: 51 additions & 0 deletions lib/parsers/regex-parser/convertRegexToStringLiteral.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,51 @@
const { parse } = require("@babel/parser");
const generate = require("@babel/generator").default;
const { default: traverse } = require("@babel/traverse");
const { create_new_name } = require("../../utils");

function escapeRegexContent(regex) {
// Escapa todos os backslashes primeiro para evitar duplicação
let escapedRegex = regex.replace(/\\/g, "\\\\");

// Agora escapa todos os backticks
escapedRegex = escapedRegex.replace(/`/g, "\\`");

return escapedRegex;
}

function replaceRegexWithReferences(code) {
const regexExpressions = {};
let ast = parse(code, {
sourceType: "module",
plugins: ["jsx", "typescript"],
});

traverse(ast, {
RegExpLiteral(path) {
const { pattern, flags } = path.node;
const regex = new RegExp(pattern, flags);
const referenceId = `:::${create_new_name()}:::`;
regexExpressions[referenceId] = escapeRegexContent(regex.toString());

// Replace the RegExpLiteral with the reference ID
path.replaceWith({
type: "StringLiteral",
value: referenceId,
});
},
});

const output = generate(ast, {
retainLines: true,
concise: false,
comments: true,
});

return {
code: output.code,
expressions: regexExpressions,
hasExpressions: Object.keys(regexExpressions).length > 0,
};
}

module.exports = replaceRegexWithReferences;
29 changes: 29 additions & 0 deletions lib/parsers/regex-parser/regexObjects.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
let _regexObjects = {};

/**
* INFO: Houve a tentativa de guardar as referencias das expressoes no estado global, porém a VM não suporta
* passar expressoes regulares como parametros para os Widgets abaixo
*/
// function convertRegexStringsToLiterals(obj) {
// const entries = Object.keys(obj);
// let finalObjects = "";

// entries.forEach((key) => {
// const currentEntrieValue = obj[key];
// let currentRegexString = `${key}: ${currentEntrieValue}`;
// finalObjects += `${currentRegexString},\n`;
// });

// return finalObjects;
// }

const addExpressions = (expressions) =>
(_regexObjects = { ..._regexObjects, ...expressions });
const getExpressions = () => _regexObjects;
// const getStringExpressions = () => convertRegexStringsToLiterals(_regexObjects);

module.exports = {
addExpressions,
getExpressions,
// getStringExpressions,
};
2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
{
"name": "alem",
"description": "Create web3 applications for NEAR BOS with a focus on performance and friendly development.",
"version": "1.0.0-beta.23",
"version": "1.0.0-beta.24",
"main": "main.js",
"types": "index.d.ts",
"author": "Wenderson Pires - wendersonpires.near",
Expand Down

0 comments on commit d1ff2a2

Please sign in to comment.