/
aat
/
sreda.v2
Обзор
Документация
Войти
/
aat
/
sreda.v2
Код
Запросы
0
Пакеты
0
Релизы
0
Аналитика
Безопасность
master
back/scripts/builder.cjs
157 строк
6 KB
Alex
upd
15 апр 2026, 22:13
15 апр 2026, 22:13
2da2bd8
Код
Авторство
О чём код?
const path = require('path'); const fs = require('fs'); const dotenv = require('dotenv'); const babel = require('@babel/core'); const root = path.join(__dirname, '../'); const packageJson = require(root+"/package.json"); const env = dotenv.config( { path: root+'.env' }); const getExportDefault = (sourceCode) => { // Чтение исходного файла // const sourceCode = fs.readFileSync('./your_module.ts', 'utf8'); let ExportDefaultDeclaration = ''; // Парсим файл и получаем AST const ast = babel.parse(sourceCode, { plugins: ['@babel/plugin-transform-typescript'], // Поддержка TypeScript babel-plugin-typescript }); const body = ast?.program?.body ?? []; for (const node of body) { if (node.type === "ExportDefaultDeclaration") { ExportDefaultDeclaration = node.declaration.name; } } return ExportDefaultDeclaration; } const scanDirectory = (baseDir, dirPath, depth = 0) => { const allowedExtensions = ['.js', '.ts', '.cjs', '.mjs', '.cts', '.mts']; let tree = {}; let foundFiles = {}; // Сюда будут собираться пути к файлам // Ограничимся первыми двумя уровнями if (depth > 1) { return { tree, foundFiles }; } // Читаем содержимое текущего каталога const entries = fs.readdirSync(dirPath, { withFileTypes: true }); for (let entry of entries) { if (entry.isDirectory()) { // Если это папка, создаем её узел в дереве if (depth === 1) { // На втором уровне делаем запись null // tree[entry.name] = null; } else { // Иначе рекурсивно спускаемся в неё const childTreeAndFiles = scanDirectory( baseDir, path.join(dirPath, entry.name), depth + 1 ); tree[entry.name] = childTreeAndFiles.tree; foundFiles = {...foundFiles, ...childTreeAndFiles.foundFiles}; // собираем найденные файлы } } else { // Если это файл и его расширение подходит, добавляем его в дерево и список if (depth === 1) { const ext = path.extname(entry.name); if (allowedExtensions.includes(ext)) { const filenameWithoutExt = path.basename(entry.name, ext); if (filenameWithoutExt === "index") { const fullPath = path.join(dirPath, entry.name); const relativePath = './'+path.relative(baseDir, fullPath); const moduleName = dirPath.split('/').pop(); const packageJson = require(path.join(dirPath, 'package.json')) tree[entry.name] = { moduleName, name: entry.name, package: packageJson, relativePath }; foundFiles[moduleName] = relativePath; // сохраняем полный путь к файлу } } } } } return { tree, foundFiles }; // возвращаем оба результата } const generate = (modelesPath, { tree, foundFiles }) => { const ExportDefaults = []; const importModules = {}; const importsLines = Object.keys(foundFiles).map(name=>{ const pathFile = foundFiles[name]; let templateImport = ''; try { const sourceCode = fs.readFileSync( path.join(modelesPath, pathFile ), 'utf8'); const ExportDefaultDeclaration = getExportDefault(sourceCode); if (!ExportDefaults.includes(ExportDefaultDeclaration)) { templateImport = `import ${ExportDefaultDeclaration} from '${pathFile}'`; ExportDefaults.push(ExportDefaultDeclaration); importModules[ExportDefaultDeclaration] = pathFile; } else { templateImport = `// import ${ExportDefaultDeclaration} from '${pathFile}' - Error a module with the same export name was announced earlier`; } } catch (e) { templateImport = `// import ??? from '${pathFile}' - Error file syntax!`; } return templateImport; }) const txt = importsLines.join('\n'); return { txt, importModules}; } const main = async () => { console.log('--------=========== BUILDER START =========------------'); const {tree, foundFiles} = scanDirectory(root+'src/modules', root+'src/modules'); let { txt, importModules} = generate(root+'src/modules', {tree, foundFiles}); txt += `\nimport DI from './index'\n\n`; //build container const addDI = [ 'function Initialize() {' ]; Object.keys(importModules).map(key => { addDI.push(` DI.service('${key}', ${key});`); }) addDI.push('\n'); Object.keys(importModules).map(key => { addDI.push(` DI.container.${key}?.Init?.(DI);`); }) addDI.push('\n'); Object.keys(importModules).map(key => { addDI.push(` DI.container.${key}?.Routes?.(DI);`); }) addDI.push('}') txt += addDI.join('\n'); txt += `\n\nexport default Initialize;` // const Modules = Object.keys(importModules).join(', '); //{ ${Modules} } fs.writeFileSync(root+'src/modules/modules.js', txt); console.log('--------=========== BUILDER END =========------------'); //console.log(root, env, packageJson, tree, foundFiles, txt); } main();