Skip to content

Commit

Permalink
Merge pull request #1 from wpdas/feature/new-compiler
Browse files Browse the repository at this point in the history
feature/new-compiler
  • Loading branch information
wpdas authored Mar 11, 2024
2 parents a3f9e44 + b1c5862 commit 6d64405
Show file tree
Hide file tree
Showing 17 changed files with 532 additions and 357 deletions.
4 changes: 3 additions & 1 deletion docs/router/use-location.md
Original file line number Diff line number Diff line change
Expand Up @@ -2,13 +2,15 @@

This hook returns the current location object. It can be useful if you'd like to perform some side effect whenever the current location changes.

Use `useLocation().isRoutesReady` to get to know when the routes are ready to be accessed.

```ts
// http://127.0.0.1:8080/alem-lib.near/widget/Index?path=profile
import { useLocation } from "alem/hooks";

export const SomeComponent = () => {
const location = useLocation();
console.log(location); // { pathname: "profile", routes: ["home", "profile"] }
console.log(location); // { isRoutesReady: true, pathname: "profile", routes: ["home", "profile"] }

return "";
};
Expand Down
24 changes: 24 additions & 0 deletions lib/actions/addSignatures.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
const path = require("path");
const fs = require("fs");
const alemPkg = require("../../package.json");

const addSignatures = (bundleContent) => {
const projectPkg = JSON.parse(
fs.readFileSync(path.join("package.json"), "utf-8"),
);

const projectRepositoryLink =
projectPkg?.repository && typeof projectPkg?.repository === "string"
? projectPkg?.repository
: projectPkg.repository?.url || "";

bundleContent = `
/** Bundle generated by Além Library v${alemPkg.version} - See more here: https://github.com/wpdas/alem */
${projectRepositoryLink ? `/** Project repository: ${projectRepositoryLink.replaceAll("git+", "").replaceAll(".git", "")} */` : ""}
${bundleContent}
`;

return bundleContent;
};

module.exports = addSignatures;
80 changes: 80 additions & 0 deletions lib/actions/loadFilesContent.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,80 @@
const { process_file } = require("../parse");

// Load App Files Content based on files schema
// const loadFilesContent = (orderedFilesToImport) => {
// let bundleFile = "";
// orderedFilesToImport.forEach((filePath) => {
// bundleFile += process_file(filePath);
// });

// return bundleFile;
// };

/**
* (Recommended)
* Load files based on the filePath sequence
*/
const loadFilesContent = (filesToLoad) => {
let bundleFile = "";
filesToLoad.forEach((filePath) => {
bundleFile += process_file(filePath);
});

return bundleFile;
};

/**
* NOTE: Esse modelo joga as dependencias pra cima
*/
// const loadFilesContentSendingImportsToTheTop = (filesSchema) => {
// let bundleFile = "";

// // 1 - carrega o "filePath"
// // 2 - carrega os arquivos "toImport" acima do "filePath"
// // 3 - verificar se o conteúdo já nao existe antes de adicionar
// // se existir, ignora a adicao
// // 4 - Se conteudo já existir e estiver abaixo do "filePath", remove ele
// // e tras pra cima

// const addContent = (content) => {
// if (!bundleFile.includes(content)) {
// bundleFile = `
// ${content}

// ${bundleFile}
// `;
// }
// };

// filesSchema.forEach((fileSchema) => {
// const filePathContent = process_file(fileSchema.filePath);
// addContent(filePathContent);

// // Adiciona os "toImport" deste File Schema
// fileSchema.toImport.forEach((dependencyFilePath) => {
// const dependentFileContent = process_file(dependencyFilePath);

// // Checa se o conteudo dependente já existe e se esta acima do elemento
// // pai (filePath), se estiver embaixo, manda pra cima
// const filePathPosition = bundleFile.indexOf(filePathContent);
// const dependentPosition = bundleFile.indexOf(dependentFileContent);

// // Se existir tanto um quanto outro...
// if (filePathPosition > 0 && dependentPosition > 0) {
// // Se o dependent estiver abaixo do filePathContent
// if (dependentPosition > filePathPosition) {
// // Remove o dependente do conteudo do bundle
// // Ele vai ser adicionado dnv no "addContent" abaixo, só que
// // acima do arquivo "filePath"
// bundleFile.replace(dependentFileContent, "");
// }
// }

// addContent(dependentFileContent);
// });
// });

// return bundleFile;
// };

module.exports = loadFilesContent;
125 changes: 125 additions & 0 deletions lib/actions/loadFilesInfo.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,125 @@
const path = require("path");
const fs = require("fs");
const helpers = require("../helpers");
const { removeComments } = require("../parse");

/**
* To be like:
*
* ```ts
* [
* {
* filePath: "file/path/ModuleFile.tsx",
* toImport: ["path/moduleFile1.tsx", "path/moduleFile2.tsx"]
* nextFilesToLoad: [
* "path/to/import/ModuleFile1.tsx",
* "path/to/import/ModuleFile2.tsx",
* ]
* },
* {...}
* {...}
* ]
* ```
*
* Then, load files in a unique bundle, filtering to not add duplicated content
*/
let contentOrderer = [];
// Arquivos já processados (evita duplicidade)
let processedFiles = [];
// Lista em ordem de arquivos para carregar / importar
let orderedFilesToImport = [];
const processFileSchema = (filePath) => {
// Se estiver vazio no primeiro processo, adiciona o arquivo de entrada 1
// (entry point File)
if (orderedFilesToImport.length === 0) {
orderedFilesToImport.push(filePath);
}
// console.log("\n\n");
// console.log("Processando:", filePath, "||");
let parentFolder = ".";
if (filePath) {
const parentPathParts = filePath.split("/");
parentPathParts.pop();
parentFolder = parentPathParts.join("/");
}

let fileContent = fs.readFileSync(filePath, "utf8");

// Remove comments from file
fileContent = removeComments(fileContent);

const fileImportsPath = helpers.getImportsPath(fileContent);
const currentFileSchema = {
filePath: filePath,
// usado para guiar as proximas cargas
// pode ser deletado no final do processo
nextFilesToLoad: [],
toImport: [],
};
fileImportsPath.forEach((importPath) => {
// Usa src para inicio ou o caminho do pai do arquivo sendo processado atualmente
let importedFileContentPath = path.join(parentFolder, importPath);

importedFileContentPath = helpers.getFilePathWithType(
importedFileContentPath,
);

// Registra todos os arquivos que o arquivo atual pede para importar
if (importedFileContentPath) {
currentFileSchema.toImport.push(importedFileContentPath);
}

// Registra os arquivos necessarios para o arquivo atual (imports)
// Esse dado da seguimento na busca de dados dos arquivos dos imports
if (!processedFiles.includes(importedFileContentPath)) {
if (importedFileContentPath) {
currentFileSchema.nextFilesToLoad.push(importedFileContentPath);
orderedFilesToImport.push(importedFileContentPath);
} else {
console.log(
`${filePath} -> Arquivo dependente nao encontrado: ${importPath}`,
);
}

processedFiles.push(importedFileContentPath);
}
});

// Push current schema result
contentOrderer.push(currentFileSchema);

// Recursividade
// console.log("RECURSIVIDADE:");
currentFileSchema.nextFilesToLoad.forEach((fileToImport) => {
processFileSchema(fileToImport);
});
};

const loadFilesInfo = (entryFile) => {
// Reset state
contentOrderer = [];
processedFiles = [];
// NOTE: Nao esta sendo usado no momento porque esta usando o contentOrderer.filePath
// NOTE: contentOrderer.filePath funcionou melhor do que a sequencia do orderedFilesToImport
orderedFilesToImport = [];

// Start loading process
processFileSchema(entryFile);

// Finaliza o processo do contentOrderer deletando o campo "filesToImport"
// de todos os filhos, já que agora náo são mais necessarios
contentOrderer.map((item) => {
delete item.filesToImport;
return item;
});

return {
filesSchema: contentOrderer,
// orderedFilesToImport: orderedFilesToImport.reverse(),
orderedFilesToImport: contentOrderer
.map((schema) => schema.filePath)
.reverse(),
};
};

module.exports = loadFilesInfo;
19 changes: 19 additions & 0 deletions lib/actions/saveFinalBundleFile.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
const path = require("path");
const fs = require("fs");
const { read_bos_config } = require("../config");

// Save final bundle file
// Note: must save inside a ./src folder. This is the only folder bos-clir-rs recognizes
const saveFinalBundleFile = (bundleContent) => {
const config = read_bos_config();
const finalFileName = config.isIndex
? "Index"
: config.name.replaceAll(" ", "-").toLowerCase();

fs.writeFileSync(
path.join(`./build/src/${finalFileName}.jsx`),
bundleContent,
);
};

module.exports = saveFinalBundleFile;
68 changes: 68 additions & 0 deletions lib/actions/toolsFiles.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,68 @@
const path = require("path");
const { process_file } = require("../parse");
const { read_bos_config } = require("../config");
const { for_rfile } = require("../utils");

const TOOLS_FOLDER = "../tools";

const loadHeaderFilesContent = () => {
const config = read_bos_config();

// Utils
let bundleFileBody = process_file(
path.join(__dirname, TOOLS_FOLDER, "utils.js"),
);

// Components
bundleFileBody += process_file(
path.join(__dirname, TOOLS_FOLDER, "components.jsx"),
);

// State manager
bundleFileBody += process_file(
path.join(__dirname, TOOLS_FOLDER, "stateManager.jsx"),
);

// Routes manager
bundleFileBody += process_file(
path.join(__dirname, TOOLS_FOLDER, "routes.jsx"),
);

// Hooks
bundleFileBody += process_file(
path.join(__dirname, TOOLS_FOLDER, "hooks.js"),
);

// Check if AlemSpinner should be used
if (!config?.options?.showFallbackSpinner) {
bundleFileBody = bundleFileBody.replace(
"return <AlemSpinner />;",
'return "";',
);
}

// Load .CSS files
// Loop through all .css files inside the './src' and get their content
bundleFileBody += "const alemCssBody = `";
for_rfile(path.join(".", "src"), ["css", "sass"], (file) => {
const fileBody = process_file(file);
bundleFileBody += fileBody;
});
bundleFileBody += "`;";

// Theme
bundleFileBody += process_file(
path.join(__dirname, TOOLS_FOLDER, "theme.jsx"),
);

return bundleFileBody;
};

const loadIndexerContent = () => {
return process_file(path.join(__dirname, TOOLS_FOLDER, "appIndexer.jsx"));
};

module.exports = {
loadHeaderFilesContent,
loadIndexerContent,
};
Loading

0 comments on commit 6d64405

Please sign in to comment.