fleetbo-cockpit-cli 1.0.73 → 1.0.74

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (2) hide show
  1. package/cli.js +112 -916
  2. package/package.json +1 -1
package/cli.js CHANGED
@@ -31,238 +31,64 @@ process.env.DOTENV_SILENT = 'true';
31
31
  const envPath = path.join(process.cwd(), '.env');
32
32
 
33
33
  if (!fs.existsSync(envPath)) {
34
- console.error('\x1b[31m%s\x1b[0m', '\n❌ Error: Configuration file (.env) not found.');
35
- console.error('\x1b[90m%s\x1b[0m', 'Make sure you are in a Fleetbo project directory.\n');
34
+ console.error('\x1b[31m[Fleetbo] ❌ Error: .env file not found in current directory.\x1b[0m');
36
35
  process.exit(1);
37
36
  }
38
37
 
39
- dotenv.config({ path: envPath, quiet: true });
38
+ dotenv.config({ path: envPath });
40
39
 
41
- const projectId = process.env.REACT_APP_ENTERPRISE_ID;
42
- const keyApp = process.env.REACT_KEY_APP;
43
- const testerEmail = process.env.REACT_APP_TESTER_EMAIL;
40
+ const projectId = process.env.FLEETBO_PROJECT_ID;
41
+ const developerToken = process.env.FLEETBO_DEVELOPER_TOKEN;
44
42
 
45
- if (!projectId) {
46
- console.error('\n\x1b[31m❌ Error: Project ID missing in .env.\x1b[0m\n');
43
+ if (!projectId || !developerToken) {
44
+ console.error('\x1b[31m[Fleetbo] ❌ Error: FLEETBO_PROJECT_ID or FLEETBO_DEVELOPER_TOKEN missing in .env\x1b[0m');
47
45
  process.exit(1);
48
46
  }
49
47
 
50
48
  // ============================================
51
- // HELPERS
49
+ // CORE LOGIC: ALEX ENGINE (Generation)
52
50
  // ============================================
53
- const wrapText = (text, maxWidth) => {
54
- if (!text) return "";
55
- const rawLines = text.split('\n');
56
- let formattedLines = [];
57
- rawLines.forEach(line => {
58
- if (line.trim().length === 0) {
59
- formattedLines.push("");
60
- return;
61
- }
62
- const isSpecialFormat = /^[\s]*[-*•\d]/.test(line) || line.startsWith(" ");
63
- if (isSpecialFormat) {
64
- formattedLines.push(line);
65
- } else {
66
- const words = line.split(" ");
67
- let currentLine = words[0];
68
- for (let i = 1; i < words.length; i++) {
69
- if (currentLine.length + 1 + words[i].length <= maxWidth) {
70
- currentLine += " " + words[i];
71
- } else {
72
- formattedLines.push(currentLine);
73
- currentLine = words[i];
74
- }
75
- }
76
- formattedLines.push(currentLine);
77
- }
78
- });
79
- return formattedLines.join('\n ');
80
- };
81
-
82
- const checkGitSecurity = () => {
83
- const gitDir = path.join(process.cwd(), '.git');
84
- const gitignorePath = path.join(process.cwd(), '.gitignore');
85
- if (fs.existsSync(gitDir)) {
86
- if (!fs.existsSync(gitignorePath)) {
87
- console.error('\n\x1b[31m🚨 SECURITY ALERT:\x1b[0m .git detected but no .gitignore found.');
88
- process.exit(1);
89
- }
90
- const gitignoreContent = fs.readFileSync(gitignorePath, 'utf8');
91
- if (!gitignoreContent.includes('.env')) {
92
- console.error('\n\x1b[31m🚨 CRITICAL RISK:\x1b[0m .env is NOT ignored by Git.');
93
- process.exit(1);
94
- }
95
- }
96
- };
97
-
98
- const injectRouteIntoAppJs = (moduleName, subPath = '') => {
99
- const appJsPath = path.join(process.cwd(), 'src', 'App.js');
100
- if (!fs.existsSync(appJsPath)) {
101
- console.error(` \x1b[31m[Safety Stop]\x1b[0m App.js missing.`);
102
- return false;
103
- }
104
-
105
- let content = fs.readFileSync(appJsPath, 'utf8');
106
- const importAnchor = '// FLEETBO_MORE_IMPORTS';
107
- const routeAnchor = '{/* FLEETBO_DYNAMIC ROUTES */}';
108
-
109
- if (!content.includes(importAnchor) || !content.includes(routeAnchor)) {
110
- console.log(` \x1b[33m[Skipped]\x1b[0m Anchors missing in App.js. Manual injection required.`);
111
- return false;
112
- }
113
-
114
- const cleanSubPath = subPath ? `${subPath}/` : '';
115
- const importLine = `import ${moduleName} from './app/${cleanSubPath}${moduleName}';`;
116
- const routeLine = `<Route path="/${cleanSubPath}${moduleName.toLowerCase()}" element={<${moduleName} />} />`;
117
-
118
- let modified = false;
119
-
120
- if (!content.includes(importLine)) {
121
- content = content.replace(importAnchor, `${importLine}\n${importAnchor}`);
122
- modified = true;
123
- }
124
- if (!content.includes(routeLine)) {
125
- content = content.replace(routeAnchor, `${routeLine}\n ${routeAnchor}`);
126
- modified = true;
127
- }
128
- if (modified) {
129
- fs.writeFileSync(appJsPath, content);
130
- console.log(` \x1b[32m[Routed]\x1b[0m ${moduleName} injected into App.js safely.`);
131
- }
132
-
133
- return modified;
134
- };
135
51
 
136
- const showEnergyTransfer = async () => {
137
- const width = 30;
138
- for (let i = 0; i <= width; i++) {
139
- const dots = "█".repeat(i);
140
- const empty = "░".repeat(width - i);
141
- process.stdout.write(`\r \x1b[32m⚡ Propulsion Sync:\x1b[0m [${dots}${empty}] ${Math.round((i / width) * 100)}%`);
142
- await new Promise(r => setTimeout(r, 45));
52
+ const runAlexEngine = async () => {
53
+ const prompt = args.slice(1).join(' ');
54
+ if (!prompt) {
55
+ console.log('\n\x1b[36mAlex ❯\x1b[0m I am ready. Describe your feature, and I will architect the solution.\n');
56
+ process.exit(0);
143
57
  }
144
- process.stdout.write('\n');
145
- };
146
-
147
- // Détecte TOUS les mots en PascalCase (ex: GuestCreator, CameraModule, Tab2)
148
- const extractPotentialModules = (text) => {
149
- // Regex stricte : Majuscule + minuscules + Majuscule (ex: ProfileCreator, UserConfig)
150
- const regex = /\b[A-Z][a-z]+[A-Z][a-zA-Z0-9_]*\b/g;
151
- const matches = text.match(regex) || [];
152
- return [...new Set(matches)];
153
- };
154
-
155
58
 
156
- // Sert uniquement à définir le TON du contexte envoyé à Alex
157
- const getContextIntent = (text) => {
158
- const modifierKeywords = [
159
- 'modifier', 'corrige', 'ajoute', 'erreur', 'plante', 'problème', 'bug', 'change',
160
- 'update', 'fix', 'edit', 'error', 'fail', 'crash', 'issue', 'add'
161
- ];
162
- const inspireKeywords = [
163
- 'inspire', 'base', 'comme', 'modèle', 'reference', 'reprends', 'copie',
164
- 'inspire', 'based on', 'model', 'reference', 'like', 'copy', 'similar'
165
- ];
166
-
167
- const lower = text.toLowerCase();
168
- if (modifierKeywords.some(k => lower.includes(k))) return "MODIFICATION";
169
- if (inspireKeywords.some(k => lower.includes(k))) return "INSPIRATION";
170
- return "REFERENCE";
171
- };
59
+ console.log(`\n\x1b[90m🧠 Alex is thinking...\x1b[0m`);
60
+ process.stdout.write(`\x1b[90m \x1b[0m`);
172
61
 
173
- const getModuleCache = async ({ projectId, moduleName }) => {
174
62
  try {
175
- const res = await axios.post(CACHE_URL, { projectId, moduleName });
176
- if (res.data && res.data.found) {
177
- // On renvoie à la fois "module" (pour un seul) et "modules" (pour la liste)
178
- return { found: true, module: res.data.module, modules: res.data.modules };
179
- }
180
- return { found: false };
181
- } catch (e) {
182
- return { found: false };
183
- }
184
- };
185
-
186
- const removeRouteFromAppJs = (moduleName) => {
187
- const appJsPath = path.join(process.cwd(), 'src', 'App.js');
188
- if (!fs.existsSync(appJsPath)) return false;
189
-
190
- let content = fs.readFileSync(appJsPath, 'utf8');
191
-
192
- // Pattern exact pour l'import et la route (gestion du sous-dossier mocks/)
193
- const importLine = `import ${moduleName} from './app/mocks/${moduleName}';`;
194
- const routeLine = `<Route path="/mocks/${moduleName.toLowerCase()}" element={<${moduleName} />} />`;
195
-
196
- const originalContent = content;
197
-
198
- // On retire les lignes si elles existent (avec le retour à la ligne)
199
- content = content.replace(new RegExp(`${importLine.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')}\\n?`, 'g'), '');
200
- content = content.replace(new RegExp(`\\s*${routeLine.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')}\\n?`, 'g'), '');
201
-
202
- if (content !== originalContent) {
203
- fs.writeFileSync(appJsPath, content);
204
- console.log(` \x1b[32m[Unrouted]\x1b[0m ${moduleName} removed from App.js.`);
205
- return true;
206
- }
207
- return false;
208
- };
63
+ // --- MEMORY SYSTEM (SMART CACHE SCANNER V3 - SOUVERAINETÉ DU MÉTAL) ---
64
+ // On cherche les noms de modules (PascalCase) dans le prompt
65
+ const moduleMatches = prompt.match(/\b[A-Z][a-z]+[A-Z][a-zA-Z0-9_]*\b/g) || [];
66
+ const uniqueModules = [...new Set(moduleMatches)];
67
+
68
+ let targetModuleContext = "";
69
+ let referenceContexts = "";
209
70
 
210
- // ============================================
211
- // COMMAND: alex
212
- // ============================================
213
- if (command === 'alex') {
214
- checkGitSecurity();
215
- const initialPrompt = args.slice(1).join(' ');
216
-
217
- const processAlexRequest = async (prompt) => {
218
- if (prompt.length > 1000) {
219
- console.log('\n\x1b[31m⛔ [Alex Safety] Request too long (' + prompt.length + '/1000 chars).\x1b[0m');
220
- return;
221
- }
71
+ if (uniqueModules.length > 0) {
72
+ const cachePromises = uniqueModules.map(async (modName) => {
73
+ const isReferenceOnly = modName.endsWith('Ref');
74
+ const cleanModName = isReferenceOnly ? modName.replace('Ref', '') : modName;
222
75
 
223
- // 📋 INTERCEPTION: LIST MODULES
224
- const isListingRequest = /^(liste|list|quels modules|montre les modules|show modules)/i.test(prompt);
225
- if (isListingRequest) {
226
- process.stdout.write(` \x1b[90m🔍 Scanning OS Cache...\x1b[0m\n`);
227
- const cacheRes = await getModuleCache({ projectId, moduleName: null });
228
-
229
- if (cacheRes.found !== false && cacheRes.modules && cacheRes.modules.length > 0) {
230
- console.log(`\n\x1b[36m⚡ FLEETBO OS MODULES (${cacheRes.modules.length}):\x1b[0m`);
231
- cacheRes.modules.forEach(m => {
232
- const metalColor = m.platform === 'android' ? '\x1b[32m' : '\x1b[34m';
233
- console.log(` ${metalColor}■\x1b[0m \x1b[1m${m.moduleName}\x1b[0m \x1b[90m(${m.platform})\x1b[0m`);
234
- });
235
- } else {
236
- console.log(`\n \x1b[90mNo modules found in the infrastructure of this project.\x1b[0m`);
237
- }
238
- return;
239
- }
76
+ try {
77
+ const cacheRes = await axios.post(CACHE_URL, {
78
+ projectId,
79
+ developerToken,
80
+ moduleName: cleanModName
81
+ });
240
82
 
241
- console.log('\x1b[33m🧠 Alex is thinking...\x1b[0m');
242
-
243
- try {
244
- // --- MEMORY SYSTEM (SMART CACHE SCANNER V3 - SOUVERAINETÉ DU MÉTAL) ---
245
- let contextInjection = "";
246
- const potentialModules = extractPotentialModules(prompt);
247
-
248
- let targetModuleContext = "";
249
- let referenceContexts = "";
250
-
251
- for (let modName of potentialModules) {
252
- let isReferenceOnly = false;
253
-
254
- // 🟢 LE DÉTECTEUR D'INSPIRATION
255
- if (modName.endsWith('Ref')) {
256
- isReferenceOnly = true;
257
- modName = modName.replace('Ref', '');
258
- } else if (modName.endsWith('Schema')) {
259
- isReferenceOnly = true;
260
- modName = modName.replace('Schema', '');
83
+ return { name: cleanModName, isRef: isReferenceOnly, found: cacheRes.data.found, module: cacheRes.data.module };
84
+ } catch (e) {
85
+ return { name: cleanModName, isRef: isReferenceOnly, found: false };
261
86
  }
87
+ });
88
+
89
+ const results = await Promise.all(cachePromises);
262
90
 
263
- process.stdout.write(` \x1b[90m🔍 Checking OS cache for ${modName}...\x1b[0m`);
264
- const cache = await getModuleCache({ projectId, moduleName: modName });
265
-
91
+ results.forEach(cache => {
266
92
  if (cache.found) {
267
93
  process.stdout.write(` \x1b[32mFOUND METAL\x1b[0m\n`);
268
94
 
@@ -271,737 +97,107 @@ if (command === 'alex') {
271
97
  if (cache.module.dataSchema) memoryScript += `\n[SCRIPT MÉMOIRE DONNÉES]\n${cache.module.dataSchema}\n`;
272
98
  if (cache.module.uiSchema) memoryScript += `\n[SCRIPT MÉMOIRE UI NATIF]\n${cache.module.uiSchema}\n`;
273
99
 
274
- if (!memoryScript) memoryScript = `\n[SCRIPT MÉMOIRE DU MODULE ${modName}]\nAucun schéma enregistré pour ce module.\n`;
100
+ if (!memoryScript) memoryScript = `\n[SCRIPT MÉMOIRE DU MODULE ${cache.name}]\nAucun schéma enregistré pour ce module.\n`;
275
101
 
276
- if (isReferenceOnly) {
102
+ if (cache.isRef) {
277
103
  // 🚨 CAS A : INSPIRATION (Lecture seule)
278
- referenceContexts += `\n--- CONTEXTE : MODULE DE RÉFÉRENCE (${modName}) ---\nDOGME : Ne modifie pas ce module (Lecture seule). Tu dois l'utiliser comme modèle. Aligne-toi sur ses Scripts Mémoires (Données et/ou UI) et sur son Code Natif en fonction de ce que le Pilote te demande d'imiter.\n${memoryScript}\n[CODE NATIF DE RÉFÉRENCE]\n${cache.module.code}\n`;
279
- } else if (!targetModuleContext) {
280
- // 🚨 CAS B : CIBLE PRINCIPALE (Modification)
281
- // LE MOCK EST BANI ! Le Métal est la seule source de vérité.
282
- const intent = getContextIntent(prompt);
283
- if (intent === "MODIFICATION") {
284
- targetModuleContext = `\n--- CONTEXTE : MÉTAL EXISTANT À MODIFIER (${modName}) ---\nDOGME: Tu dois modifier ce code Natif. Ensuite, tu forgeras un Mock JSX entièrement neuf basé UNIQUEMENT sur ton nouveau code Natif.\n${memoryScript}\n[CODE NATIF EXISTANT]\n${cache.module.code}\n--- FIN DU CONTEXTE ---\n`;
285
- } else {
286
- targetModuleContext = `\n--- CONTEXTE : BASE DE TRAVAIL (${modName}) ---\n${memoryScript}\n`;
287
- }
104
+ referenceContexts += `\n--- CONTEXTE : MODULE DE RÉFÉRENCE (${cache.name}) ---\nDOGME : Ne modifie pas ce module (Lecture seule). Tu dois l'utiliser comme modèle. Aligne-toi sur ses Scripts Mémoires (Données et/ou UI) et sur son Code Natif en fonction de ce que le Pilote te demande d'imiter.\n${memoryScript}\n[CODE NATIF DE RÉFÉRENCE]\n${cache.module.code}\n`;
105
+ } else {
106
+ // 🚨 CAS B : MODIFICATION (Souveraineté du Métal - Amnésie du Mock)
107
+ targetModuleContext += `\n--- CONTEXTE : MÉTAL EXISTANT À MODIFIER (${cache.name}) ---\nDOGME : Tu dois modifier ce code Natif. Ensuite, tu forgeras un Mock JSX entièrement neuf basé UNIQUEMENT sur ton nouveau code Natif.\n${memoryScript}\n[CODE NATIF EXISTANT]\n${cache.module.code}\n`;
288
108
  }
289
- } else {
290
- process.stdout.write(` \x1b[31mNOT FOUND\x1b[0m\n`);
291
109
  }
292
- }
293
-
294
- contextInjection = referenceContexts + targetModuleContext;
295
- if (contextInjection) {
296
- prompt = contextInjection + "\n\n[INSTRUCTION DU PILOTE]\n" + prompt;
297
- }
298
- // --- END MEMORY MODIFICATION ---
299
-
300
- // 🟢 NEW: Real-time timestamp injection
301
- const now = new Date();
302
- // Clean format: YYYY-MM-DD at HH:MM:SS
303
- const exactTime = now.toISOString().split('T')[0] + ' at ' + now.toTimeString().split(' ')[0];
304
-
305
- const promptWithTime = prompt + `\n\n[SYSTEM INFO: The exact current timestamp is ${exactTime}. Use it STRICTLY for your signature '// ⚡ Forged by Alex on...' at the bottom of your files.]`;
306
-
307
- const result = await axios.post(ALEX_ENGINE_URL, { prompt: promptWithTime, projectType: 'android' }, {
308
- headers: { 'x-project-id': projectId }
309
110
  });
111
+ }
310
112
 
311
- let aiData = result.data;
312
-
313
- if (typeof aiData === 'string') {
314
- try { aiData = JSON.parse(aiData); } catch (_) {}
315
- }
316
-
317
- // 🟢 DISPLAY REASONING IN TERMINAL
318
- if (aiData.thinking_process) {
319
- // Show start of reasoning in gray for info
320
- console.log(` \x1b[90m🧠 Alex Analysis: ${aiData.thinking_process.substring(0, 150)}...\x1b[0m`);
321
- }
322
-
323
- process.stdout.write('\x1b[A\r' + ' '.repeat(50) + '\r');
324
-
325
- if (aiData.status === 'quota_exceeded') {
326
- console.log(`\n\x1b[31m⛔ ARCHITECT QUOTA REACHED:\x1b[0m ${aiData.message}`);
327
- return;
328
- }
329
-
330
- if (aiData.status === 'success' || aiData.status === 'message' || aiData.status === 'complex_refusal') {
331
- console.log('');
332
- let rawMsg = aiData.message || "I'm ready.";
333
-
334
- if (typeof rawMsg === 'string' && rawMsg.trimStart().startsWith('{')) {
335
- try {
336
- const nested = JSON.parse(rawMsg);
337
- if (nested && nested.message) {
338
- rawMsg = nested.message;
339
- if (!aiData.moduleData && nested.moduleData) {
340
- aiData.moduleData = nested.moduleData;
341
- }
342
- }
343
- } catch (_) {}
344
- }
345
-
346
- if (typeof rawMsg === 'object') {
347
- rawMsg = rawMsg.message || rawMsg.text || "Module generated.";
348
- }
349
- try {
350
- const testParse = JSON.parse(rawMsg);
351
- if (testParse && typeof testParse === 'object' && testParse.status) {
352
- rawMsg = testParse.message || "Module generated.";
353
- }
354
- } catch (_) { }
355
-
356
- const formattedMsg = wrapText(rawMsg, 85);
357
- console.log('\x1b[32mAlex ❯\x1b[0m ' + formattedMsg);
113
+ const fullPrompt = `${referenceContexts}\n${targetModuleContext}\n--- FIN DU CONTEXTE ---\n\n[INSTRUCTION DU PILOTE]\n${prompt}`;
358
114
 
359
- }
360
-
361
- // --- FILE CREATION LOGIC ---
362
- if (aiData.status === 'success' && aiData.moduleData) {
363
- let { fileName, code, mockFileName, mockCode, moduleName, instructions, config_offload, dataSchema, uiSchema } = aiData.moduleData;
364
-
365
- // 🛡️ ANTI-DUMP SHIELD (Prevents terminal flooding)
366
- if (moduleName) {
367
- // Cleanup module name
368
- moduleName = moduleName.split('\n')[0].replace(/["'{}]/g, '').trim();
369
- if (moduleName.length > 40) moduleName = moduleName.substring(0, 40) + "...";
370
- }
371
-
372
- console.log(` \x1b[90m Architecting: ${moduleName}\x1b[0m`);
373
-
374
- const writeFile = (dir, name, content) => {
375
- const fullPath = path.join(process.cwd(), dir);
376
- const filePath = path.join(fullPath, name);
377
- if (!fs.existsSync(fullPath)) fs.mkdirSync(fullPath, { recursive: true });
378
- fs.writeFileSync(filePath, content);
379
- console.log(` \x1b[32m[Written]\x1b[0m ${dir}${name}`);
380
- };
381
-
382
- if (instructions && Array.isArray(instructions) && instructions.length > 0) {
383
- console.log('\n\x1b[33m--- GUIDE (MCI) ---\x1b[0m');
384
- instructions.forEach(line => {
385
- if (typeof line === 'string') {
386
- const formattedLine = line.replace(/ACTION|CAPTURE|PERSPECTIVE/g, '\x1b[1m$&\x1b[0m');
387
- console.log(` ${formattedLine}`);
388
- }
389
- });
390
- }
391
-
392
- if (code && fileName) {
393
- const folder = fileName.endsWith('.kt') ? 'public/native/android/' : 'src/app/';
394
- writeFile(folder, fileName, code);
395
- if (fileName.endsWith('.jsx')) injectRouteIntoAppJs(fileName.replace('.jsx', ''));
396
- }
397
-
398
- if (mockCode && mockFileName) {
399
- const pageName = mockFileName.replace('.jsx', '');
400
- writeFile('src/app/mocks/', mockFileName, mockCode);
401
- const injected = injectRouteIntoAppJs(pageName, 'mocks');
402
- if (injected) {
403
- console.log(` \x1b[32m[Routed]\x1b[0m App.js -> /mocks/${pageName.toLowerCase()}`);
404
- }
405
- }
406
-
407
- // --- KERNEL SYNCHRONIZATION ---
408
- const depsCount = config_offload?.dependencies?.length || 0;
409
- process.stdout.write(` \x1b[33m[Cloud Inject]\x1b[0m Archiving ${moduleName} to OS (${depsCount} libs)...`);
410
-
411
- try {
412
- await axios.post(INJECT_DEPS_URL, {
413
- projectId: projectId,
414
- fileData: {
415
- path: fileName,
416
- moduleName: moduleName,
417
- fileName: fileName,
418
- code: code,
419
- mockFileName: mockFileName,
420
- mockCode: mockCode,
421
- config_offload: config_offload || { dependencies: [], permissions: [] },
422
- dataSchema: dataSchema || null, // 👈 LA LIGNE MAGIQUE
423
- uiSchema: uiSchema || null
424
- }
425
- });
426
- process.stdout.write(` \x1b[32mOK\x1b[0m\n`);
427
- } catch (err) {
428
- process.stdout.write(` \x1b[31mFAILED\x1b[0m\n`);
429
- console.error(` ⚠️ OS sync failed: ${err.message}`);
430
- }
431
- // 🟢 LE FUEL EST DÉPLACÉ ICI (TOUTE FIN DU TRY)
432
- if (aiData.remainingConsultations !== undefined) {
433
- const remaining = aiData.remainingConsultations;
434
- const limit = aiData.consultationLimit || 7;
435
- const tierLabel = aiData.tier.toUpperCase();
436
- const percent = Math.round((remaining / limit) * 100);
437
- const energyColor = percent > 20 ? '\x1b[32m' : '\x1b[31m';
438
- console.log(`\n\x1b[36m⚡ Architect Fuel:\x1b[0m ${energyColor}${percent}%\x1b[0m (${remaining}/${limit} instructions left) [${tierLabel}]\n`);
439
- }
440
- } else if (aiData.status === 'success' && !aiData.moduleData) {
441
- // SAFETY: If formatting is broken
442
- console.log(`\n\x1b[31m⚠️ Error: Alex replied, but source code could not be extracted. Try the command again.\x1b[0m\n`);
443
- }
444
- } catch (error) {
445
- process.stdout.write('\r' + ' '.repeat(50) + '\r');
446
- console.error('\n\x1b[31m Alex Error:\x1b[0m ' + (error.response?.data?.message || error.message));
447
- }
448
- };
449
-
450
- const startAlexSession = async () => {
451
- process.stdout.write('\x1b[33m🛡️ Alex is checking runtime state...\x1b[0m\r');
452
- let attempts = 0;
453
- const maxAttempts = 5;
454
- let isReady = false;
455
- let dynamicUsername = 'Pilot';
456
-
457
- while (attempts < maxAttempts && !isReady) {
458
- try {
459
- const validation = await axios.post(ALEX_ENGINE_URL, {
460
- prompt: "ping", validateProject: true, checkNetwork: true, projectKey: keyApp
461
- }, { headers: { 'x-project-id': projectId }, timeout: 5000 });
462
-
463
- if (validation.data?.isRunning) {
464
- isReady = true;
465
- dynamicUsername = validation.data.username || 'Pilot';
466
- break;
467
- }
468
- attempts++;
469
- if (attempts < maxAttempts) await new Promise(r => setTimeout(r, 2000));
470
- } catch (error) {
471
- attempts++;
472
- await new Promise(r => setTimeout(r, 2000));
473
- }
474
- }
475
-
476
- if (!isReady) {
477
- console.error('\n\x1b[31m⚠️ ENGINE OFFLINE:\x1b[0m Start Fleetbo runtime first: "npm run fleetbo" ');
478
- console.error(`\x1b[90m(Ensure you are running the runtime for project: ${keyApp})\x1b[0m`);
479
- process.exit(1);
480
- }
481
-
482
- process.stdout.write(' '.repeat(60) + '\r');
483
-
484
- // 1. IDENTITY
485
- console.log('\n\x1b[32m🤖 Alex is online.\x1b[0m');
486
- console.log('\x1b[90m Your JS stays the brain. I forge the native muscle.\x1b[0m');
487
-
488
- // 2. FORGE CAPABILITIES
489
- console.log('\n\x1b[36m⚡ WHAT I CAN FORGE:\x1b[0m');
490
- console.log('');
491
- console.log(' \x1b[1m📷 Hardware\x1b[0m\x1b[90m Camera, Scanner, GPS, Biometrics, Sensors\x1b[0m');
492
- console.log(' \x1b[1m🎬 High-Perf\x1b[0m\x1b[90m Infinite Feeds, Video Players, Swipe Decks\x1b[0m');
493
- console.log(' \x1b[1m🏗️ Sovereign\x1b[0m\x1b[90m Full screens: form + photo + save-to-cloud\x1b[0m');
494
-
495
- // 3. COLLABORATION
496
- console.log('\n\x1b[36m💡 TELL ME "WHAT + WHY":\x1b[0m');
497
- console.log('\x1b[90m I will analyze your need and recommend the perfect module to forge.\x1b[0m');
498
- console.log('');
499
- console.log(' \x1b[33m"I need a camera [WHAT] to scan receipts for my expense tracker [WHY]"\x1b[0m');
500
- console.log(' \x1b[33m"I need a form [WHAT] to add products with photos to my catalog [WHY]"\x1b[0m');
501
-
502
- // 4. READINESS
503
- console.log('\n\x1b[32mAlex ❯\x1b[0m I am ready. Describe your feature, and I will architect the solution.');
504
- console.log('');
505
-
506
- const rl = readline.createInterface({
507
- input: process.stdin,
508
- output: process.stdout,
509
- prompt: `\x1b[34m${dynamicUsername} ❯ \x1b[0m`
115
+ // Requête à l'IA
116
+ const exactTime = new Date().toLocaleTimeString('fr-FR', { hour: '2-digit', minute: '2-digit' });
117
+ const res = await axios.post(ALEX_ENGINE_URL, {
118
+ prompt: fullPrompt,
119
+ projectId,
120
+ developerToken,
121
+ systemInfo: `[SYSTEM INFO: The exact current timestamp is ${exactTime}. Use it STRICTLY for your signature '// Forged by Alex on...' at the end of 'code' and 'mockCode'.]`
510
122
  });
511
-
512
- process.stdout.write('\n\x1b[F');
513
- rl.prompt();
514
123
 
515
- let inputBuffer = "";
516
- let isProcessing = false;
124
+ const aiData = res.data;
517
125
 
518
- rl.on('line', async (line) => {
519
- if (isProcessing) return;
126
+ if (aiData.message) {
127
+ readline.clearLine(process.stdout, 0);
128
+ readline.cursorTo(process.stdout, 0);
129
+ console.log(`\x1b[36mAlex ❯\x1b[0m ${aiData.message}\n`);
130
+ }
520
131
 
521
- const trimmedLine = line.trim();
132
+ // --- FILE CREATION LOGIC ---
133
+ if (aiData.status === 'success' && aiData.moduleData) {
134
+ let { fileName, code, mockFileName, mockCode, moduleName, instructions, config_offload, dataSchema, uiSchema } = aiData.moduleData;
522
135
 
523
- if (['exit', 'quit'].includes(trimmedLine.toLowerCase())) {
524
- console.log('\n\x1b[90m Alex session closed.\x1b[0m');
525
- rl.close();
526
- return;
136
+ if (!fileName || !code) {
137
+ console.error('\x1b[31m[Fleetbo] ❌ Critical: Alex provided incomplete source code.\x1b[0m');
138
+ process.exit(1);
527
139
  }
528
140
 
529
- if (trimmedLine !== "") {
530
- inputBuffer += (inputBuffer ? "\n" : "") + line;
531
- rl.setPrompt("");
532
- }
533
- else {
534
- if (inputBuffer.trim() !== "") {
535
- const finalPrompt = inputBuffer.trim();
536
- inputBuffer = "";
537
-
538
- if (finalPrompt.length > 1000) {
539
- console.log(`\n\x1b[31m⛔ [Alex Safety] Mission rejected: Excessive size (${finalPrompt.length}/1000 characters).\x1b[0m`);
540
- rl.setPrompt(`\x1b[34m${dynamicUsername} ❯ \x1b[0m`);
541
- rl.prompt();
542
- return;
543
- }
141
+ // Correction automatique du format de fichier
142
+ if (!fileName.includes('.')) fileName += '.kt';
143
+ if (mockFileName && !mockFileName.includes('.')) mockFileName += '.jsx';
544
144
 
545
- isProcessing = true;
546
- rl.setPrompt("");
547
- await processAlexRequest(finalPrompt);
548
- isProcessing = false;
549
-
550
- console.log('');
551
- rl.setPrompt(`\x1b[34m${dynamicUsername} ❯ \x1b[0m`);
552
- rl.prompt();
553
- } else {
554
- rl.setPrompt(`\x1b[34m${dynamicUsername} ❯ \x1b[0m`);
555
- rl.prompt();
556
- }
145
+ // Sauvegarde locale (optionnelle pour debug, mais prioritairement injection Cloud)
146
+ const buildPath = path.join(process.cwd(), 'fleetbo_build');
147
+ if (!fs.existsSync(buildPath)) fs.mkdirSync(buildPath);
148
+ fs.writeFileSync(path.join(buildPath, fileName), code);
149
+ if (mockCode && mockFileName) {
150
+ fs.writeFileSync(path.join(buildPath, mockFileName), mockCode);
557
151
  }
558
- });
559
- };
560
-
561
- if (!initialPrompt || initialPrompt === '?') startAlexSession();
562
- else processAlexRequest(initialPrompt);
563
-
564
- }
565
152
 
566
- // ============================================
567
- // COMMAND: rm (MODULE ANNIHILATION)
568
- // ============================================
569
- else if (command === 'rm') {
570
- const moduleName = args[1];
571
- if (!moduleName) {
572
- console.error('\n\x1b[31m❌ Error: Module name required.\x1b[0m');
573
- console.log('\x1b[90mUsage: npm run fleetbo rm [ModuleName]\x1b[0m\n');
574
- process.exit(1);
575
- }
576
-
577
- console.log(`\n\x1b[33m🗑️ Annihilating module: ${moduleName}...\x1b[0m`);
578
-
579
- // 1. Define physical paths
580
- const ktPath = path.join(process.cwd(), 'public', 'native', 'android', `${moduleName}.kt`);
581
- const jsxPath = path.join(process.cwd(), 'src', 'app', 'mocks', `${moduleName}.jsx`);
582
-
583
- let actionsDone = 0;
584
-
585
- // 2. Eradicate Metal Engine (Kotlin)
586
- if (fs.existsSync(ktPath)) {
587
- fs.unlinkSync(ktPath);
588
- console.log(` \x1b[32m[Deleted]\x1b[0m Metal file (.kt) eradicated.`);
589
- actionsDone++;
590
- }
591
-
592
- // 3. Eradicate Virtual Twin (Mock JSX)
593
- if (fs.existsSync(jsxPath)) {
594
- fs.unlinkSync(jsxPath);
595
- console.log(` \x1b[32m[Deleted]\x1b[0m Virtual Twin (.jsx) eradicated.`);
596
- actionsDone++;
597
- }
598
-
599
- // 4. Disinfect System Core (App.js)
600
- const unrouted = removeRouteFromAppJs(moduleName);
601
- if (unrouted) actionsDone++;
602
-
603
- if (actionsDone === 0) {
604
- console.log(`\n\x1b[31m⚠️ No trace of module "${moduleName}" found in the OS.\x1b[0m\n`);
605
- } else {
606
- console.log(`\n\x1b[32m Module ${moduleName} successfully eradicated from the OS.\x1b[0m\n`);
607
- }
608
- }
609
-
610
- // ============================================
611
- // COMMAND: android / ios (PROPULSION BUILD)
612
- // ============================================
613
- else if (command === 'android' || command === 'ios') {
614
-
615
- // 🟢 DÉBUT DE LA PROTECTION (Fonction Async Immédiate)
616
- // Cela garantit que le code fonctionne partout, même via 'require()'
617
- (async () => {
618
-
619
- // 🛑 INTERCEPTION IOS : BLOQUAGE NET (MAINTENANCE/BETA)
620
- if (command === 'ios') {
621
- console.log(`\n\x1b[36m⚡ FLEETBO IOS PROPULSION\x1b[0m`);
622
- console.log(`\x1b[33m[0/3] Initializing Neural Uplink...\x1b[0m`);
623
-
624
- // ✅ Ce 'await' est maintenant sécurisé
625
- await new Promise(r => setTimeout(r, 800));
626
-
627
- console.log(`\n\x1b[31m⛔ PROPULSION ABORTED: iOS Frequency Restricted.\x1b[0m`);
628
- console.log(`\x1b[90m This module is currently reserved for Vanguard Pilots (Closed Beta).\x1b[0m`);
629
- console.log(`\x1b[90m Please engage propulsion on Android frequency for now.\x1b[0m\n`);
630
-
631
- process.exit(1);
632
- }
633
-
634
- checkGitSecurity();
635
- const platform = command;
636
- const nativeDir = platform === 'android' ? 'public/native/android/' : 'public/native/ios/';
637
- const extension = platform === 'android' ? '.kt' : '.swift';
638
- const nativePath = path.join(process.cwd(), nativeDir);
639
-
640
- // Vérification des modules natifs
641
- let hasNativeFiles = false;
642
- let nativeFileCount = 0;
643
- if (fs.existsSync(nativePath)) {
644
- const files = fs.readdirSync(nativePath);
645
- const nativeFiles = files.filter(file => file.endsWith(extension));
646
- hasNativeFiles = nativeFiles.length > 0;
647
- nativeFileCount = nativeFiles.length;
648
- }
649
-
650
- if (!hasNativeFiles) {
651
- console.log(`\n\x1b[31m⚠️ ENGINE INCOMPLETE:\x1b[0m No native blueprints detected for \x1b[1m${platform.toUpperCase()}\x1b[0m.`);
652
- console.log(`\x1b[90mAlex must architect at least one ${extension} module before deployment.\x1b[0m`);
653
- console.log(`\x1b[90mRun: npm run fleetbo alex\x1b[0m\n`);
654
- process.exit(1);
655
- }
656
-
657
- const targetUrl = platform === 'android' ? ANDROID_BUILD_URL : IOS_BUILD_URL;
658
-
659
- console.log(`\n\x1b[36m⚡ FLEETBO ${platform.toUpperCase()} PROPULSION\x1b[0m`);
660
- console.log(`\x1b[90m ${nativeFileCount} native module(s) detected\x1b[0m\n`);
661
-
662
- try {
663
- // ==========================================================
664
- // PRE-FLIGHT CHECK QUOTAS & TIER
665
- // ==========================================================
666
- process.stdout.write(`\x1b[33m[0/3]\x1b[0m Checking Propulsion Access... `);
153
+ // INJECTION CLOUD (Indispensable pour le build et la mémoire d'Alex)
667
154
  try {
668
- // On envoie le signal 'x-preflight' pour tester les droits sans builder
669
- await axios.post(targetUrl, {}, {
670
- headers: {
671
- 'x-project-id': projectId,
672
- 'x-preflight': 'true'
155
+ await axios.post(INJECT_DEPS_URL, {
156
+ projectId,
157
+ developerToken,
158
+ fileData: {
159
+ path: fileName,
160
+ moduleName: moduleName || fileName.split('.')[0],
161
+ fileName: fileName,
162
+ code: code,
163
+ mockFileName: mockFileName,
164
+ mockCode: mockCode,
165
+ config_offload: config_offload || { dependencies: [], permissions: [] },
166
+ dataSchema: dataSchema || null,
167
+ uiSchema: uiSchema || null
673
168
  }
674
169
  });
675
- // Si ça passe (200 OK), c'est un Senior ou un Junior autorisé (si vous changez d'avis)
676
- process.stdout.write(`\x1b[32mOK (Senior Pilot)\x1b[0m\n\n`);
677
-
678
- } catch (preflightError) {
679
- process.stdout.write(`\x1b[31mDENIED\x1b[0m\n`);
680
-
681
- const errData = preflightError.response?.data;
682
-
683
- // 🛑 1. INTERCEPTION SPÉCIFIQUE JUNIOR
684
- // C'est ici qu'on lit le code renvoyé par index.js
685
- if (errData?.code === 'junior_restriction') {
686
- console.log(`\n\x1b[31m━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\x1b[0m`);
687
- console.log(`\x1b[31m⛔ ACCESS DENIED: JUNIOR PILOT DETECTED\x1b[0m`);
688
- console.log(`\x1b[31m━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\x1b[0m`);
689
- console.log(``);
690
- console.log(` \x1b[33m This feature is locked for Junior Pilots.\x1b[0m`);
691
- console.log(` \x1b[32m Upgrade to Senior on fleetbo.io to unlock Propulsion.\x1b[0m`);
692
- console.log(``);
693
- process.exit(1); // Arrêt immédiat et propre du script
694
- }
695
-
696
- // 2. Gestion des autres erreurs (Quota Senior dépassé, Serveur HS, etc.)
697
- if (errData && errData.error) {
698
- throw new Error(errData.error);
699
- }
700
- throw preflightError;
701
- }
702
-
703
- // Étape 1: Build React
704
- console.log(`\x1b[33m[1/3]\x1b[0m Synthesizing Fleetbo Core Logic...`);
705
- execSync('npm run build', { stdio: 'inherit' });
706
-
707
- let buildDir = fs.existsSync(path.join(process.cwd(), 'dist')) ? 'dist' : 'build';
708
- const buildPath = path.join(process.cwd(), buildDir);
709
-
710
- if (!fs.existsSync(buildPath)) {
711
- throw new Error(`Build directory not found: ${buildDir}`);
712
- }
713
-
714
- // Étape 2: Créer le ZIP
715
- console.log(`\n\x1b[33m[2/3]\x1b[0m Packaging bundle + native modules...`);
716
-
717
- const zipBuffer = await new Promise((resolve, reject) => {
718
- const chunks = [];
719
- const archive = archiver('zip', { zlib: { level: 9 } });
720
-
721
- archive.on('data', chunk => chunks.push(chunk));
722
- archive.on('end', () => resolve(Buffer.concat(chunks)));
723
- archive.on('error', reject);
724
- archive.on('warning', (err) => {
725
- if (err.code !== 'ENOENT') reject(err);
726
- });
727
-
728
- archive.directory(buildPath, 'build');
729
- if (fs.existsSync(nativePath)) {
730
- archive.directory(nativePath, `build/native/${platform}`);
731
- }
732
- archive.finalize();
733
- });
734
-
735
- const sizeMB = (zipBuffer.length / 1024 / 1024).toFixed(2);
736
- console.log(` \x1b[32m✓\x1b[0m Bundle ready: ${sizeMB} MB`);
737
-
738
- // Étape 3: Upload
739
- console.log(`\n\x1b[33m[3/3]\x1b[0m Uploading to Fleetbo OS...`);
740
- await showEnergyTransfer();
741
-
742
- let uploadResponse;
743
- try {
744
- uploadResponse = await axios.post(targetUrl, zipBuffer, {
745
- headers: {
746
- 'Content-Type': 'application/zip',
747
- 'x-project-id': projectId
748
- },
749
- maxContentLength: Infinity,
750
- maxBodyLength: Infinity,
751
- timeout: 120000
752
- });
753
- } catch (axiosError) {
754
- if (axiosError.response && axiosError.response.data && axiosError.response.data.error) {
755
- throw new Error(axiosError.response.data.error);
756
- } else {
757
- throw new Error(`Connection to OS failed: ${axiosError.message}`);
758
- }
759
- }
760
-
761
- if (uploadResponse.data && uploadResponse.data.success) {
762
- console.log(`\n\x1b[32m━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\x1b[0m`);
763
- console.log(`\x1b[32m✓ ${platform.toUpperCase()} PROPULSION SUCCESSFUL\x1b[0m`);
764
- console.log(`\x1b[32m━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\x1b[0m`);
765
- console.log(`\x1b[90m Deployment ID: ${uploadResponse.data.deploymentId || 'N/A'}\x1b[0m`);
766
- console.log(`\x1b[90m ${uploadResponse.data.message || 'Complete.'}\x1b[0m\n`);
767
- } else {
768
- throw new Error(uploadResponse.data?.error || 'Unknown logical error from Factory');
769
- }
770
-
771
- } catch (error) {
772
- console.log(`\n\x1b[31m━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\x1b[0m`);
773
- console.log(`\x1b[31m✗ PROPULSION FAILED\x1b[0m`);
774
- console.log(`\x1b[31m━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\x1b[0m`);
775
-
776
- console.error(`\x1b[31m Error:\x1b[0m ${error.message}`);
777
-
778
- if (error.message.includes('Limit') || error.message.includes('Quota')) {
779
- console.log(`\n\x1b[33m 💡 Tip:\x1b[0m Upgrade to Senior Pilot for more builds.`);
780
- } else if (error.message.includes('No native module')) {
781
- console.log(`\n\x1b[33m 💡 Tip:\x1b[0m Run "npm run fleetbo alex" to create native modules first.`);
782
- } else if (error.message.includes('Trial Period Ended')) {
783
- console.log(`\n\x1b[33m 💡 Tip:\x1b[0m Your free sprint is over. Upgrade to Senior Pilot on fleetbo.io.`);
170
+ console.log(`\x1b[32m[Fleetbo] ${fileName} has been forged and fused with the Core.\x1b[0m`);
171
+ } catch (injectErr) {
172
+ console.error(`\x1b[31m[Fleetbo] ❌ Forge failed: Core rejection.\x1b[0m`, injectErr.response?.data || injectErr.message);
784
173
  }
785
- console.log('');
786
- process.exit(1);
174
+ } else if (aiData.status === 'success') {
175
+ console.error('\x1b[33m⚠️ Error: Alex replied, but source code could not be extracted. Try the command again.\x1b[0m');
787
176
  }
788
177
 
789
- })(); // 🟢 FIN DE LA PROTECTION
790
- }
791
- // ============================================
792
- // COMMAND: page / g / generate
793
- // ============================================
794
- else if (['page', 'g', 'generate'].includes(command)) {
795
- const pageGeneratorPath = path.join(__dirname, 'page.js');
796
- try {
797
- require(pageGeneratorPath);
798
- } catch (e) {
799
- console.error('\x1b[31m Page Generator Error:\x1b[0m', e.message);
800
- process.exit(1);
178
+ } catch (error) {
179
+ readline.clearLine(process.stdout, 0);
180
+ readline.cursorTo(process.stdout, 0);
181
+ console.error(`\x1b[31m[Fleetbo] Alex Engine Error:\x1b[0m`, error.response?.data || error.message);
801
182
  }
802
- }
183
+ };
184
+
803
185
  // ============================================
804
- // COMMAND: (default) - Start Dev Environment
186
+ // COMMAND ROUTER
805
187
  // ============================================
806
- else {
807
- const NULL_DEV = process.platform === 'win32' ? '>nul 2>&1' : '2>/dev/null';
808
-
809
- function killProcessOnPort(port) {
810
- try {
811
- if (process.platform !== 'win32') {
812
- const pid = execSync(`lsof -ti:${port} ${NULL_DEV}`).toString().trim();
813
- if (pid) execSync(`kill -9 ${pid.split('\n').join(' ')} ${NULL_DEV}`);
814
- }
815
- } catch (e) {}
816
- }
817
-
818
- const killNetworkService = () => {
819
- if (uplinkProcess) {
820
- try {
821
- uplinkProcess.kill('SIGINT');
822
- console.log('[Fleetbo] Engine closed.');
823
- } catch (e) {
824
- console.error('[Fleetbo] Error closing tunnel:', e.message);
825
- }
826
- }
827
- };
828
-
829
- let isExiting = false;
830
-
831
- async function cleanupAndExit(code = 0) {
832
- if (isExiting) return;
833
- isExiting = true;
834
- console.log('\n\x1b[33m[Fleetbo] 🛑 Stopping environment & Cleaning Uplink...\x1b[0m');
835
- try {
836
- await axios.post(UPDATE_NETWORK_URL, { keyApp, networkUrl: '', tester: testerEmail });
837
- console.log('\x1b[32m[Fleetbo] ✓ Network status reset to offline.\x1b[0m');
838
- } catch (e) {
839
- console.error('[Fleetbo] Network cleanup warning:', e.message);
840
- }
841
- killNetworkService();
842
- killProcessOnPort(PORT);
843
- console.log('[Fleetbo] Bye.');
844
- process.exit(code);
845
- }
846
-
847
- process.on('SIGINT', () => cleanupAndExit(0));
848
- process.on('SIGTERM', () => cleanupAndExit(0));
849
-
850
- async function syncFirebase(keyApp, networkUrl, testerEmail) {
851
- try {
852
- await axios.post(UPDATE_NETWORK_URL, { keyApp, networkUrl, tester: testerEmail });
853
- console.log('\n\x1b[32mEngine started successfully\x1b[0m');
854
- console.log(`\x1b[32mFleetbo OS ❯\x1b[0m -------------------------------------------------------------`);
855
- console.log('\x1b[32mFleetbo OS ❯\x1b[0m \x1b[1mGO GO GO ! OS IS READY\x1b[0m');
856
- console.log('\x1b[32mFleetbo OS ❯\x1b[0m You can now start coding and previewing. 🚀');
857
- console.log(`\x1b[32mFleetbo OS ❯\x1b[0m -------------------------------------------------------------`);
858
- console.log(`\x1b[34mPilot Instruction ❯\x1b[0m Return to the Workspace. The Engine is ready for your orders.\n`);
859
- } catch (err) {
860
- console.error(`\x1b[31mFleetbo OS ❯\x1b[0m Sync Error: ${err.message}`);
861
- }
862
- }
863
-
864
- async function runDevEnvironment() {
865
- console.log(`[Fleetbo] 🛡️ Initializing Dev Environment...`);
866
-
867
- // Mise à jour silencieuse de browserslist
868
- try {
869
- const npxExec = process.platform === 'win32' ? 'npx.cmd' : 'npx';
870
- execSync(`${npxExec} -y update-browserslist-db@latest`, { stdio: 'ignore' });
871
- } catch (e) {}
872
-
873
- killNetworkService();
874
- killProcessOnPort(PORT);
875
-
876
- if (!testerEmail) {
877
- console.error('\x1b[31mError: REACT_APP_TESTER_EMAIL missing in .env\x1b[0m');
878
- process.exit(1);
879
- }
880
-
881
- const npmCmd = process.platform === 'win32' ? 'npm.cmd' : 'npm';
882
- const devServer = spawn(npmCmd, ['start'], {
883
- stdio: ['ignore', 'pipe', 'pipe'],
884
- shell: true,
885
- env: {
886
- ...process.env,
887
- NODE_OPTIONS: '--no-deprecation',
888
- BROWSER: 'none',
889
- PORT: PORT.toString(),
890
- DANGEROUSLY_DISABLE_HOST_CHECK: 'true',
891
- HOST: '0.0.0.0',
892
- WDS_SOCKET_HOST: 'localhost',
893
- WDS_SOCKET_PORT: PORT.toString()
894
- }
895
- });
896
188
 
897
- //devServer.stdout.pipe(process.stdout);
898
- devServer.stderr.pipe(process.stderr);
189
+ switch (command) {
190
+ case 'alex':
191
+ runAlexEngine();
192
+ break;
899
193
 
900
- let connectionStarted = false;
901
-
902
- devServer.stdout.on('data', (data) => {
903
- const output = data.toString();
904
-
905
- // 🛡️ FILTRE ANTI-PLOMBERIE FLEETBO
906
- const lines = output.split('\n');
907
- const forbiddenTerms = [
908
- 'Attempting to bind to HOST',
909
- 'If this was unintentional',
910
- 'Learn more here:',
911
- 'Starting the development server',
912
- 'You can now view',
913
- 'Local:',
914
- 'On Your Network:',
915
- 'Note that the development build',
916
- 'To create a production build',
917
- 'webpack compiled successfully'
918
- ];
919
-
920
- // On filtre les lignes pour ne garder que le vrai code/debug
921
- const filteredOutput = lines.filter(line => {
922
- return !forbiddenTerms.some(term => line.includes(term));
923
- }).join('\n');
924
-
925
- // S'il reste quelque chose d'utile (un console.log du dev, un warning, une vraie erreur), on l'affiche
926
- if (filteredOutput.trim() !== '') {
927
- process.stdout.write(filteredOutput + '\n');
928
- }
929
-
930
- // 🚀 DÉTECTION DU DÉMARRAGE ET LANCEMENT DE L'UPLINK
931
- if (!connectionStarted && (output.includes('Local:') || output.includes('Compiled successfully'))) {
932
- connectionStarted = true;
933
-
934
- console.log('\x1b[33mFleetbo OS ❯\x1b[0m ---------------------------------------------------');
935
- console.log(`\x1b[33mFleetbo OS ❯\x1b[0m 🔗 Establishing Secure Uplink...`);
936
- console.log(`\x1b[33mFleetbo OS ❯\x1b[0m ⏳ Please wait for the green message...`);
937
- console.log('\x1b[33mFleetbo OS ❯\x1b[0m ---------------------------------------------------');
938
-
939
- // ============================================
940
- // UPLINK avec auto-retry (Fleetbo OS Resilience)
941
- // ============================================
942
- const MAX_UPLINK_RETRIES = 5;
943
- const RETRY_DELAYS = [0, 10, 20, 30, 45];
944
- let uplinkFound = false;
945
-
946
- const startUplink = (attempt) => {
947
- if (uplinkFound) return;
948
-
949
- const npxCmd = process.platform === 'win32' ? 'npx.cmd' : 'npx';
950
-
951
- if (attempt > 0) {
952
- console.log(`\x1b[33m[Fleetbo] 🔄 Uplink reconnection ${attempt}/${MAX_UPLINK_RETRIES - 1}...\x1b[0m`);
953
- }
954
-
955
- uplinkProcess = spawn(npxCmd, [
956
- '-y',
957
- 'cloudflared',
958
- 'tunnel',
959
- '--url', `http://127.0.0.1:${PORT}`,
960
- '--http-host-header', `127.0.0.1:${PORT}`
961
- ], { shell: true });
962
-
963
- const handleUplinkOutput = (chunk) => {
964
- const text = chunk.toString();
965
- if (uplinkFound) return;
966
- const match = text.match(/https:\/\/[a-zA-Z0-9-]+\.trycloudflare\.com/);
967
- if (match) {
968
- uplinkFound = true;
969
- // ⚡ Stabilisation du noyau : on attend 1.5s
970
- setTimeout(() => {
971
- syncFirebase(process.env.REACT_KEY_APP, match[0], process.env.REACT_APP_TESTER_EMAIL);
972
- }, 1500);
973
- }
974
- };
975
-
976
- uplinkProcess.stdout.on('data', handleUplinkOutput);
977
- uplinkProcess.stderr.on('data', handleUplinkOutput);
978
-
979
- uplinkProcess.on('error', (err) => {
980
- if (uplinkFound) return;
981
- console.error(`\x1b[31m[Fleetbo] ⚠️ Uplink Connection failed to establish.\x1b[0m`);
982
- });
194
+ default:
195
+ console.log(`
196
+ \x1b[36mFleetbo OS CLI\x1b[0m
197
+ Usage: npm run fleetbo [command]
983
198
 
984
- uplinkProcess.on('close', (code) => {
985
- if (uplinkFound) return;
986
-
987
- const nextAttempt = attempt + 1;
988
- if (nextAttempt < MAX_UPLINK_RETRIES) {
989
- const delay = RETRY_DELAYS[nextAttempt] || 30;
990
- console.log(`\x1b[33m[Fleetbo] ⚠️ Uplink interrupted. Fleetbo OS retrying in ${delay}s... (${nextAttempt}/${MAX_UPLINK_RETRIES - 1})\x1b[0m`);
991
- setTimeout(() => startUplink(nextAttempt), delay * 1000);
992
- } else {
993
- console.error(`\x1b[31m[Fleetbo] ❌ Secure Uplink could not be established.\x1b[0m`);
994
- console.error(`\x1b[90m[Fleetbo] Fleetbo OS network is temporarily unavailable.\x1b[0m`);
995
- console.error(`\x1b[90m[Fleetbo] Your dev server is still running on http://localhost:${PORT}\x1b[0m`);
996
- console.error(`\x1b[90m[Fleetbo] Restart with "npm run fleetbo" when the network is back.\x1b[0m`);
997
- }
998
- });
999
- };
1000
-
1001
- startUplink(0);
1002
- }
1003
- });
1004
- }
1005
-
1006
- runDevEnvironment();
199
+ Commands:
200
+ alex [prompt] Talk to the Architect to forge or modify modules.
201
+ `);
202
+ break;
1007
203
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "fleetbo-cockpit-cli",
3
- "version": "1.0.73",
3
+ "version": "1.0.74",
4
4
  "description": "Fleetbo CLI - Build native mobile apps with React",
5
5
  "author": "Fleetbo",
6
6
  "license": "MIT",