UNPKG

can-algorithm

Version:

Cortex Algorithm Numeral - Intelligent development automation tool

379 lines (311 loc) 9.7 kB
const express = require('express'); const bodyParser = require('body-parser'); const fs = require('fs').promises; const path = require('path'); const crypto = require('crypto'); const app = express(); app.use(bodyParser.json({ limit: '50mb' })); const PORT = process.env.CORTEX_PORT || 3001; const tasks = new Map(); const processRequest = async (request, context) => { const keywords = request.toLowerCase().split(' '); if (keywords.includes('create') && keywords.includes('file')) { const fileName = keywords[keywords.indexOf('file') + 1] || 'newfile.js'; return { action: { type: 'create_file', path: fileName, content: generateFileContent(fileName, context) }, message: `Creating file: ${fileName}` }; } if (keywords.includes('fix') && keywords.includes('error')) { return { action: { type: 'fix_errors', files: context.file_details.filter(f => f.type === '.js') }, message: 'Analyzing and fixing errors in JavaScript files' }; } if (keywords.includes('rename')) { const fileIndex = keywords.indexOf('file'); const oldName = keywords[fileIndex + 1]; const newName = keywords[keywords.indexOf('to') + 1]; return { action: { type: 'rename_file', oldPath: oldName, newPath: newName }, message: `Renaming ${oldName} to ${newName}` }; } return { action: null, message: 'Request understood. No action required.' }; }; const generateFileContent = (fileName, context) => { const ext = path.extname(fileName); const templates = { '.js': `const ${path.basename(fileName, ext)} = { init: function() { console.log('Initialized'); }, execute: function() { return true; } }; module.exports = ${path.basename(fileName, ext)};`, '.html': `<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>${path.basename(fileName, ext)}</title> </head> <body> <h1>${path.basename(fileName, ext)}</h1> </body> </html>`, '.css': `* { margin: 0; padding: 0; box-sizing: border-box; } body { font-family: Arial, sans-serif; line-height: 1.6; }`, '.php': `<?php class ${path.basename(fileName, ext)} { public function __construct() { } public function execute() { return true; } }` }; return templates[ext] || ''; }; const generateProjectStructure = (request) => { const actions = []; if (request.includes('e-commerce')) { actions.push( { type: 'create_file', path: 'index.html', content: generateEcommerceHTML() }, { type: 'create_file', path: 'styles.css', content: generateEcommerceCSS() }, { type: 'create_file', path: 'app.js', content: generateEcommerceJS() }, { type: 'create_file', path: 'products.json', content: '[]' }, { type: 'create_file', path: 'cart.js', content: generateCartJS() } ); } if (request.includes('api')) { actions.push( { type: 'create_file', path: 'server.js', content: generateAPIServer() }, { type: 'create_file', path: 'routes/index.js', content: generateRoutes() }, { type: 'create_file', path: 'middleware/auth.js', content: generateAuthMiddleware() } ); } return actions; }; const generateEcommerceHTML = () => `<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>E-Commerce Store</title> <link rel="stylesheet" href="styles.css"> </head> <body> <header> <nav> <div class="logo">Store</div> <div class="cart">Cart (<span id="cart-count">0</span>)</div> </nav> </header> <main> <div id="products" class="products-grid"></div> </main> <script src="app.js"></script> <script src="cart.js"></script> </body> </html>`; const generateEcommerceCSS = () => `* { margin: 0; padding: 0; box-sizing: border-box; } body { font-family: Arial, sans-serif; background: #f4f4f4; } header { background: #333; color: white; padding: 1rem; } nav { display: flex; justify-content: space-between; align-items: center; max-width: 1200px; margin: 0 auto; } .products-grid { display: grid; grid-template-columns: repeat(auto-fill, minmax(250px, 1fr)); gap: 2rem; padding: 2rem; max-width: 1200px; margin: 0 auto; } .product-card { background: white; border-radius: 8px; padding: 1rem; box-shadow: 0 2px 5px rgba(0,0,0,0.1); }`; const generateEcommerceJS = () => `const products = []; const cart = []; async function loadProducts() { try { const response = await fetch('products.json'); const data = await response.json(); products.push(...data); displayProducts(); } catch (error) { console.error('Error loading products:', error); } } function displayProducts() { const container = document.getElementById('products'); container.innerHTML = products.map(product => \` <div class="product-card"> <h3>\${product.name}</h3> <p>\${product.price}</p> <button onclick="addToCart(\${product.id})">Add to Cart</button> </div> \`).join(''); } function addToCart(productId) { const product = products.find(p => p.id === productId); cart.push(product); updateCartDisplay(); } function updateCartDisplay() { document.getElementById('cart-count').textContent = cart.length; } loadProducts();`; const generateCartJS = () => `class ShoppingCart { constructor() { this.items = []; } add(product) { this.items.push(product); this.save(); } remove(productId) { this.items = this.items.filter(item => item.id !== productId); this.save(); } save() { localStorage.setItem('cart', JSON.stringify(this.items)); } load() { const saved = localStorage.getItem('cart'); if (saved) { this.items = JSON.parse(saved); } } }`; const generateAPIServer = () => `const express = require('express'); const bodyParser = require('body-parser'); const cors = require('cors'); const app = express(); const PORT = process.env.PORT || 3000; app.use(cors()); app.use(bodyParser.json()); app.use('/api', require('./routes')); app.listen(PORT, () => { console.log(\`Server running on port \${PORT}\`); });`; const generateRoutes = () => `const router = require('express').Router(); router.get('/health', (req, res) => { res.json({ status: 'OK' }); }); router.get('/products', (req, res) => { res.json([]); }); router.post('/products', (req, res) => { res.json({ success: true }); }); module.exports = router;`; const generateAuthMiddleware = () => `module.exports = (req, res, next) => { const token = req.headers.authorization; if (!token) { return res.status(401).json({ error: 'No token provided' }); } next(); };`; app.post('/cortex/ask', async (req, res) => { try { const { request, context, license_key } = req.body; const result = await processRequest(request, context); res.json(result); } catch (error) { res.status(500).json({ success: false, error: error.message }); } }); app.post('/cortex/project', async (req, res) => { try { const { request, context, license_key, task_id } = req.body; const task = { id: task_id, status: 'processing', request: request, started: new Date(), estimated_time: '2-6 hours' }; tasks.set(task_id, task); setTimeout(async () => { const actions = generateProjectStructure(request); task.status = 'completed'; task.actions = actions; task.completed = new Date(); tasks.set(task_id, task); }, 5000); res.json({ success: true, task_id: task_id, estimated_time: task.estimated_time }); } catch (error) { res.status(500).json({ success: false, error: error.message }); } }); app.get('/cortex/task/:id', (req, res) => { const task = tasks.get(req.params.id); if (!task) { return res.status(404).json({ error: 'Task not found' }); } res.json(task); }); app.get('/cortex/health', (req, res) => { res.json({ status: 'healthy', version: '1.0.0', uptime: process.uptime(), active_tasks: tasks.size }); }); app.listen(PORT, () => { console.log(`Cortex Service running on port ${PORT}`); });