thoth-markup-lang 10.5.0 → 11.0.0

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 (4) hide show
  1. package/README.md +21 -20
  2. package/engine.php +80 -23
  3. package/package.json +7 -4
  4. package/thoth.js +128 -50
package/README.md CHANGED
@@ -1,42 +1,43 @@
1
- # THOTH: The Sovereign Intelligence Suite (v10.5.0)
1
+ # THOTH: The Sovereign Intelligence Suite (v11.0.0 Pulse Edition)
2
2
 
3
3
  <p align="center">
4
- <img src="https://img.shields.io/npm/v/thoth-markup-lang?style=for-the-badge&color=D4AF37&logo=npm" alt="NPM Version" />
5
- <img src="https://img.shields.io/badge/Version-10.5.0--Sovereign-D4AF37?style=for-the-badge" alt="Sovereign Version" />
6
- <img src="https://img.shields.io/badge/Built%20In-Egypt%20🇪🇬-orange?style=for-the-badge" alt="Egypt" />
4
+ <img src="https://img.shields.io/npm/v/thoth-markup-lang?style=for-the-badge&color=06b6d4&logo=npm" alt="NPM Version" />
5
+ <img src="https://img.shields.io/badge/Version-11.0.0--Pulse-f59e0b?style=for-the-badge" alt="Pulse Version" />
6
+ <img src="https://img.shields.io/badge/Engineered_In-Egypt_🇪🇬-020617?style=for-the-badge&logo=code" alt="Egypt" />
7
7
  </p>
8
8
 
9
- **The Binary Wisdom of Web Architecture.** THOTH is a high-performance, sovereign, indentation-based markup language and recursive runtime engine. It eliminates structural noise and redefines web development through pure, bracket-less logic.
9
+ **The Binary Wisdom of Web Architecture.** THOTH is a high-performance, sovereign, indentation-based markup language and recursive runtime engine. It eliminates structural noise, removes bracket chaos, and redefines web development through pure, architectural logic.
10
10
 
11
11
  ---
12
12
 
13
13
  ## 🏛️ Architectural Philosophy
14
14
 
15
- THOTH represents a shift from "tag-heavy" markup to **Recursive Indentation Logic**. In version 10.5.0, the engine introduces **Strict File Identification**, requiring all sovereign files to declare their identity with `TYPE THOTH`. This ensures architectural integrity and prevents non-sovereign code execution.
15
+ THOTH represents a monumental paradigm shift from "tag-heavy" legacy markup to **Recursive Indentation Logic**. With the release of **v11.0.0 (Pulse Edition)**, the engine introduces an ultra-fast parsing core and Python-style error handling, enforcing absolute structural purity. It requires all sovereign files to declare their identity with the `TYPE THOTH` protocol, ensuring architectural integrity and preventing unauthorized code execution.
16
16
 
17
- - **Official Website:** [thoth-lang.com](https://honeydew-pigeon-679592.hostingersite.com/)
18
- - **Architected by:** [Engineer Abdelfatah Abdelhamed](mailto:abdelfatahabdelhamed.kfs@gmail.com)
17
+ - **Official Website:** [THOTH Language Portal](https://honeydew-pigeon-679592.hostingersite.com/)
18
+ - **Lead Architect:** Engineer Abdelfatah Abdelhamed
19
19
 
20
20
  ---
21
21
 
22
- ## 💎 Intelligence Suite Features (v10.5.0)
22
+ ## 💎 Intelligence Suite Features (v11.0.0 Pulse)
23
23
 
24
- * **🛡️ Strict Identification:** Mandatory `TYPE THOTH` header to ensure file sovereignty.
25
- * **💎 Zero-Bracket Architecture:** Eliminates opening/closing tags, reducing syntax noise by 70%.
26
- * **🔗 Recursive Data Binding:** Native integration with JSON flat-file databases using `@{{key}}`.
27
- * **🔐 Procedural Middleware (Auth Guard):** Secure structural nodes using `Auth="role"` attributes.
28
- * **🚀 Dev Server & Live Reload:** Integrated HTTP server with automated browser synchronization.
29
- * **🔍 Advanced Meta SEO Engine:** Automated generation of Meta Tags directly from your data context.
30
- * **⚠️ Intelligent Error Overlay:** Real-time fault tracking identifying errors by line number.
31
- * **📦 Scoped Components:** Modular file management through the `Import:` directive.
32
- * **💉 Hybrid Injection:** Native support for scoped `StyleSheet` (CSS) and `Scripting` (JS).
24
+ * **⚡ Ultra-Fast Parser Core [NEW]:** Upgraded O(n) string manipulation algorithms for blazing-fast indentation computation and rendering.
25
+ * **🐞 Python-Style Tracebacks [NEW]:** Intelligent error handling that pinpoints exact file, line number, and syntax faults in both Terminal and a Browser Overlay.
26
+ * **🛡️ Strict Identification:** Mandatory `TYPE THOTH` protocol header to ensure uncompromised file sovereignty.
27
+ * **💎 Zero-Bracket Architecture:** Eliminates opening/closing DOM tags, reducing syntax noise by up to 70%.
28
+ * **🔗 Recursive Data Binding:** Native integration with JSON flat-file databases using `@{{key}}` syntax.
29
+ * **🔐 Procedural Middleware (Auth Guard):** Secure structural DOM nodes natively using `Auth="role"` attributes.
30
+ * **🚀 Pulse Dev Server & Live Reload:** Integrated HTTP server with automated browser synchronization and state tracking.
31
+ * **🔍 Advanced Meta SEO Engine:** Automated generation of HTML5 Meta Tags directly from your JSON data context.
32
+ * **📦 Scoped Components:** Modular file architecture and management through the `Import:` directive.
33
+ * **💉 Hybrid Injection:** Native support for scoped `StyleSheet` (Raw CSS) and `Scripting` (Raw JS) inside the `.thoth` environment.
33
34
 
34
35
  ---
35
36
 
36
37
  ## 🚀 Technical Implementation
37
38
 
38
- ### Global Installation
39
- Install the THOTH CLI via NPM:
39
+ ### 1. Global Installation
40
+ Install the THOTH Engine globally via NPM to access the sovereign CLI:
40
41
 
41
42
  ```bash
42
43
  npm install -g thoth-markup-lang
package/engine.php CHANGED
@@ -1,18 +1,30 @@
1
1
  <?php
2
2
  /**
3
- * THOTH Sovereign Runtime Engine v10.5 - Final Master Suite
3
+ * THOTH Sovereign Runtime Engine v11.0 - Pulse Edition
4
4
  * Architect: Engineer Abdelfatah Abdelhamed 🇪🇬
5
5
  * --------------------------------------------------
6
- * الميزات المدمجة:
6
+ * الميزات المدمجة (النسخة المطورة):
7
7
  * 1. التوثيق المعماري: إلزامية وجود TYPE THOTH في السطر الأول.
8
8
  * 2. نظام Middleware (Auth Guard): التحكم الكامل في صلاحيات الوصول.
9
9
  * 3. نظام البيانات الديناميكي: JSON Binding & Recursive Loops.
10
10
  * 4. نظام Meta SEO الذكي: توليد عناصر Meta بناءً على البيانات.
11
- * 5. Dev Mode & Error Overlay: تتبع أخطاء الهندسة البرمجية لحظياً.
11
+ * 5. Python-Style Traceback: متتبع أخطاء ذكي يحدد السطر ونوع الخطأ بدقة.
12
+ * 6. High-Performance Core: تسريع التحليل باستخدام دوال PHP الحديثة.
12
13
  */
13
14
 
14
15
  session_start();
15
16
 
17
+ /**
18
+ * كلاس استثناءات مخصص للغة تحوت لتتبع الأخطاء بذكاء
19
+ */
20
+ class ThothSyntaxError extends Exception {
21
+ public $lineContent;
22
+ public function __construct($message, $code = 0, $lineContent = "", Throwable $previous = null) {
23
+ $this->lineContent = $lineContent;
24
+ parent::__construct($message, $code, $previous);
25
+ }
26
+ }
27
+
16
28
  class ThothEngine {
17
29
  private $tagMap = [
18
30
  'Title' => 'h1', 'Sub' => 'h2', 'Heading' => 'h3', 'Text' => 'p',
@@ -28,12 +40,15 @@ class ThothEngine {
28
40
  private $dataContext = [];
29
41
  private $devMode = true;
30
42
  private $currentLine = 0;
43
+ private $currentFile = "";
31
44
 
32
45
  /**
33
46
  * المدخل الرئيسي للمحرك
34
47
  */
35
48
  public function render($filePath, $isSubCall = false) {
36
49
  $safePath = basename($filePath);
50
+ $this->currentFile = $safePath;
51
+
37
52
  if (!file_exists($safePath)) {
38
53
  return $this->errorPage("404 | THOTH Missing", "الملف غير موجود في النطاق السيادي.");
39
54
  }
@@ -43,7 +58,7 @@ class ThothEngine {
43
58
  // --- شرط السيادة: التحقق من نوع الملف ---
44
59
  $firstLine = trim($lines[0]);
45
60
  if ($firstLine !== "TYPE THOTH") {
46
- return $this->devErrorOverlay("خطأ في الهوية البرمجية: يجب أن يبدأ الملف بـ TYPE THOTH لضمان السيادة.", 1);
61
+ return $this->devErrorOverlay("SyntaxError: Missing Identity Protocol. File must begin with TYPE THOTH.", 1, $lines[0]);
47
62
  }
48
63
  unset($lines[0]); // إزالة سطر التعريف من المعالجة
49
64
 
@@ -62,7 +77,10 @@ class ThothEngine {
62
77
  foreach ($lines as $index => $line) {
63
78
  $this->currentLine = $index + 1;
64
79
  $trimmed = trim($line);
65
- if ($trimmed === "" || strpos($trimmed, '#') === 0) continue;
80
+
81
+ // تسريع معالجة الأسطر الفارغة والتعليقات باستخدام str_starts_with
82
+ if ($trimmed === "" || str_starts_with($trimmed, '#')) continue;
83
+
66
84
  $indent = strlen($line) - strlen(ltrim($line));
67
85
 
68
86
  // Middleware Guard
@@ -84,16 +102,21 @@ class ThothEngine {
84
102
  else { $htmlBody .= $this->processRepeat($repeatKey, $repeatBuffer); $isRepeatMode = false; $repeatBuffer = []; }
85
103
  }
86
104
 
87
- if (strpos($trimmed, 'Repeat Over="') === 0) {
105
+ if (str_starts_with($trimmed, 'Repeat Over="')) {
88
106
  preg_match('/Over="([^"]+)"/', $trimmed, $matches);
107
+ if(empty($matches[1])) throw new ThothSyntaxError("LoopError: Missing valid array key in Over statement.", $this->currentLine, $line);
89
108
  $repeatKey = $matches[1] ?? '';
90
109
  $repeatIndent = $indent; $isRepeatMode = true; continue;
91
110
  }
92
111
 
93
112
  // Components & Data
94
- if (strpos($trimmed, 'DataSource:') === 0) { $this->loadData(trim(substr($trimmed, 11))); continue; }
95
- if (strpos($trimmed, 'Var ') === 0) { $this->parseVariable($trimmed); continue; }
96
- if (strpos($trimmed, 'Import:') === 0) { $htmlBody .= $this->render(trim(substr($trimmed, 7)), true); continue; }
113
+ if (str_starts_with($trimmed, 'DataSource:')) { $this->loadData(trim(substr($trimmed, 11))); continue; }
114
+ if (str_starts_with($trimmed, 'Var ')) { $this->parseVariable($trimmed); continue; }
115
+ if (str_starts_with($trimmed, 'Import:')) {
116
+ $importFile = trim(substr($trimmed, 7));
117
+ if(!file_exists($importFile)) throw new ThothSyntaxError("ImportError: Module '$importFile' not found.", $this->currentLine, $line);
118
+ $htmlBody .= $this->render($importFile, true); continue;
119
+ }
97
120
 
98
121
  $line = $this->resolveDynamicData($line);
99
122
  $trimmed = trim($line);
@@ -105,6 +128,11 @@ class ThothEngine {
105
128
  }
106
129
 
107
130
  $sep = $this->findSeparator($trimmed);
131
+ if($sep === -1 && !empty($trimmed) && !isset($this->tagMap[explode(' ', $trimmed)[0]]) && !in_array(strtolower(explode(' ', $trimmed)[0]), $this->voidTags) && $cmd !== "StyleSheet" && $cmd !== "Scripting"){
132
+ // الذكاء الاصطناعي لاكتشاف الأخطاء المطبعية
133
+ throw new ThothSyntaxError("ParseError: Invalid syntax or missing separator ':'.", $this->currentLine, $line);
134
+ }
135
+
108
136
  $cmdPart = ($sep !== -1) ? trim(substr($trimmed, 0, $sep)) : $trimmed;
109
137
  $val = ($sep !== -1) ? trim(substr($trimmed, $sep + 1)) : "";
110
138
 
@@ -142,8 +170,10 @@ class ThothEngine {
142
170
 
143
171
  return ($isSubCall) ? $htmlBody : $this->generateFullHTML($htmlBody);
144
172
 
173
+ } catch (ThothSyntaxError $e) {
174
+ return $this->devErrorOverlay($e->getMessage(), $this->currentLine, $e->lineContent);
145
175
  } catch (Exception $e) {
146
- return $this->devErrorOverlay($e->getMessage(), $this->currentLine);
176
+ return $this->devErrorOverlay("RuntimeError: " . $e->getMessage(), $this->currentLine, "System Execution Error");
147
177
  }
148
178
  }
149
179
 
@@ -173,7 +203,8 @@ class ThothEngine {
173
203
 
174
204
  private function findSeparator($text) {
175
205
  $inQuotes = false;
176
- for ($i = 0; $i < strlen($text); $i++) {
206
+ $len = strlen($text);
207
+ for ($i = 0; $i < $len; $i++) {
177
208
  if ($text[$i] === '"') $inQuotes = !$inQuotes;
178
209
  if ($text[$i] === ':' && !$inQuotes) return $i;
179
210
  }
@@ -193,15 +224,39 @@ class ThothEngine {
193
224
  }
194
225
 
195
226
  private function errorPage($title, $msg) {
196
- return "<div style='font-family:sans-serif; background:#000; color:#fff; height:100vh; display:flex; flex-direction:column; align-items:center; justify-content:center;'><h1>$title</h1><p>$msg</p></div>";
227
+ return "<div style='font-family:sans-serif; background:#020617; color:#fff; height:100vh; display:flex; flex-direction:column; align-items:center; justify-content:center;'><h1>$title</h1><p style='color:#06b6d4'>$msg</p></div>";
197
228
  }
198
229
 
199
- private function devErrorOverlay($msg, $line) {
200
- return "<div style='position:fixed; top:0; left:0; width:100%; height:100%; background:rgba(0,0,0,0.9); z-index:9999; display:flex; align-items:center; justify-content:center; font-family:monospace;'>
201
- <div style='background:#111; border:2px solid #D4AF37; padding:40px; border-radius:20px; color:#fff;'>
202
- <h2 style='color:#D4AF37;'>⚠️ THOTH ARCHITECTURAL ERROR</h2>
203
- <p>$msg</p><div style='color:red;'>Line: $line</div>
204
- <button onclick='location.reload()' style='margin-top:20px; background:#D4AF37; padding:10px 20px; border:none; cursor:pointer;'>RE-SYNC ENGINE</button></div></div>";
230
+ /**
231
+ * Python-Style Traceback Overlay
232
+ * تصميم هندسي ذكي يحدد الخطأ والمكان والملف بالتفصيل
233
+ */
234
+ private function devErrorOverlay($msg, $line, $lineContent = "") {
235
+ $escapedContent = htmlspecialchars($lineContent);
236
+ return "
237
+ <div style='position:fixed; top:0; left:0; width:100%; height:100%; background:rgba(2,6,23,0.95); z-index:99999; display:flex; align-items:center; justify-content:center; font-family:\"Fira Code\", monospace;'>
238
+ <div style='background:#0f172a; border:1px solid #ef4444; width:80%; max-width:800px; padding:30px; border-radius:12px; box-shadow:0 0 30px rgba(239, 68, 68, 0.2); color:#e2e8f0;'>
239
+
240
+ <div style='border-bottom: 1px solid #334155; padding-bottom:15px; mb-4;'>
241
+ <h2 style='color:#ef4444; margin:0; font-size:1.5rem;'>⚠️ THOTH Traceback (most recent call last):</h2>
242
+ </div>
243
+
244
+ <div style='padding: 20px 0;'>
245
+ <p style='margin:0 0 10px 0; color:#94a3b8;'>File <span style='color:#06b6d4;'>\"{$this->currentFile}\"</span>, line <span style='color:#f59e0b; font-weight:bold;'>$line</span>, in &lt;module&gt;</p>
246
+
247
+ <div style='background:#000; padding:15px; border-radius:8px; border-left:4px solid #ef4444; overflow-x:auto;'>
248
+ <div style='color:#f87171;'>$line | <span style='color:#e2e8f0;'>$escapedContent</span></div>
249
+ <div style='color:#ef4444; margin-top:5px;'>&nbsp;&nbsp;&nbsp;&nbsp;^</div>
250
+ </div>
251
+
252
+ <p style='margin:20px 0 0 0; color:#ef4444; font-weight:bold; font-size:1.1rem;'>$msg</p>
253
+ </div>
254
+
255
+ <div style='border-top: 1px solid #334155; padding-top:15px; text-align:right;'>
256
+ <button onclick='location.reload()' style='background:#ef4444; color:#fff; padding:8px 24px; border:none; border-radius:6px; cursor:pointer; font-weight:bold; font-family:inherit;'>RESTART ENGINE</button>
257
+ </div>
258
+ </div>
259
+ </div>";
205
260
  }
206
261
 
207
262
  private function generateFullHTML($body) {
@@ -211,10 +266,12 @@ class ThothEngine {
211
266
  $liveReload = $this->devMode ? "<script>
212
267
  let lastMod = null;
213
268
  setInterval(async () => {
214
- const res = await fetch(window.location.href, { method: 'HEAD' });
215
- const etag = res.headers.get('etag');
216
- if (lastMod && etag !== lastMod) location.reload();
217
- lastMod = etag;
269
+ try {
270
+ const res = await fetch(window.location.href, { method: 'HEAD' });
271
+ const etag = res.headers.get('etag');
272
+ if (lastMod && etag !== lastMod) location.reload();
273
+ lastMod = etag;
274
+ } catch(e) {}
218
275
  }, 2000);
219
276
  </script>" : "";
220
277
 
@@ -222,7 +279,7 @@ class ThothEngine {
222
279
  " <meta charset='UTF-8'>\n" .
223
280
  " <meta name='viewport' content='width=device-width, initial-scale=1.0'>\n" .
224
281
  " <meta name='description' content='$desc'>\n" .
225
- " <meta name='generator' content='THOTH Sovereign Engine 10.5'>\n" .
282
+ " <meta name='generator' content='THOTH Sovereign Engine 11.0'>\n" .
226
283
  " <title>$title</title>\n" .
227
284
  "</head>\n<body>\n$body\n$liveReload</body>\n</html>";
228
285
  }
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "thoth-markup-lang",
3
- "version": "10.5.0",
4
- "description": "THOTH Sovereign Suite: A revolutionary indentation-based markup ecosystem featuring Strict File Identification (TYPE THOTH), recursive JSON data-binding, procedural middleware auth guards, and an ultra-high-performance runtime. Engineered by Architect Abdelfatah Abdelhamed.",
3
+ "version": "11.0.0",
4
+ "description": "THOTH Sovereign Suite (Pulse Edition): A revolutionary indentation-based markup ecosystem featuring Strict File Identification (TYPE THOTH), Python-style tracebacks, recursive JSON data-binding, procedural middleware auth guards, and an ultra-high-performance runtime. Engineered by Engineer Abdelfatah Abdelhamed.",
5
5
  "main": "thoth.js",
6
6
  "bin": {
7
7
  "thoth": "./thoth.js"
@@ -14,13 +14,16 @@
14
14
  "serve": "node thoth.js serve --port 3000 --strict",
15
15
  "validate": "node thoth.js validate --all",
16
16
  "auth-setup": "node thoth.js auth --init",
17
- "version": "echo THOTH v10.5.0 Sovereign Intelligence Suite"
17
+ "version": "echo THOTH v11.0.0 Pulse Edition Sovereign Intelligence Suite"
18
18
  },
19
19
  "keywords": [
20
20
  "thoth",
21
21
  "thoth-lang",
22
22
  "markup-language",
23
23
  "sovereign-engine",
24
+ "pulse-edition",
25
+ "python-style-traceback",
26
+ "smart-error-handling",
24
27
  "type-thoth-identification",
25
28
  "strict-markup",
26
29
  "indentation-logic",
@@ -36,7 +39,7 @@
36
39
  "performance-runtime",
37
40
  "high-speed-compiler"
38
41
  ],
39
- "author": "Abdelfatah Abdelhamed <abdelfatahabdelhamed.kfs@gmail.com>",
42
+ "author": "Engineer Abdelfatah Abdelhamed <abdelfatahabdelhamed.kfs@gmail.com>",
40
43
  "license": "MIT",
41
44
  "engines": {
42
45
  "node": ">=14.0.0"
package/thoth.js CHANGED
@@ -1,8 +1,8 @@
1
1
  #!/usr/bin/env node
2
2
 
3
3
  /**
4
- * THOTH Engine v10.5.0 - The Sovereign Architect (Intelligence Suite)
5
- * Lead Developer: Engineer Abdelfatah Abdelhamed
4
+ * THOTH Engine v11.0.0 - Pulse Edition (Sovereign Intelligence Suite)
5
+ * Lead Developer & Architect: Engineer Abdelfatah Abdelhamed 🇪🇬
6
6
  * ------------------------------------------------------------------
7
7
  * الميزات المدمجة:
8
8
  * 1. Strict Identification: إلزامية وجود TYPE THOTH في السطر الأول.
@@ -10,12 +10,25 @@
10
10
  * 3. Dynamic Meta Engine: توليد وسوم الميتا تلقائياً من سياق البيانات.
11
11
  * 4. Dev Server & Live Reload: خادم محلي لمراقبة التغييرات لحظياً.
12
12
  * 5. Recursive Data Engine: نظام الـ Loops والـ JSON والـ Variables.
13
+ * 6. Python-Style Traceback: متتبع أخطاء ذكي ودقيق جداً.
14
+ * 7. Ultra-Fast Parser: تسريع خوارزميات الـ Indentation والـ String manipulation.
13
15
  */
14
16
 
15
17
  const fs = require('fs');
16
18
  const path = require('path');
17
19
  const http = require('http');
18
20
 
21
+ // --- كلاس تتبع الأخطاء الذكي (Python-Style Error Traceback) ---
22
+ class ThothSyntaxError extends Error {
23
+ constructor(message, lineNum, lineContent, filePath) {
24
+ super(message);
25
+ this.name = 'ThothSyntaxError';
26
+ this.lineNum = lineNum;
27
+ this.lineContent = lineContent;
28
+ this.filePath = filePath;
29
+ }
30
+ }
31
+
19
32
  // --- القاموس المعماري الشامل ---
20
33
  const TAG_MAP = {
21
34
  'Title': 'h1', 'Sub': 'h2', 'Heading': 'h3', 'Text': 'p', 'Bold': 'strong',
@@ -51,44 +64,46 @@ if (!command || (!target && command !== 'serve')) {
51
64
  */
52
65
  function displayUsage() {
53
66
  const yellow = '\x1b[33m';
67
+ const cyan = '\x1b[36m';
54
68
  const reset = '\x1b[0m';
55
69
  console.log(yellow + '━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━' + reset);
56
- console.log('\x1b[1m\x1b[32m THOTH INTELLIGENCE SUITE v10.5.0 \x1b[0m');
57
- console.log(yellow + ' Lead Architect: Abdelfatah Abdelhamed' + reset);
70
+ console.log('\x1b[1m\x1b[32m THOTH INTELLIGENCE SUITE v11.0.0 (Pulse) \x1b[0m');
71
+ console.log(cyan + ' Lead Architect: Engineer Abdelfatah Abdelhamed' + reset);
58
72
  console.log(yellow + '━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━' + reset);
59
73
  console.log(' Usage:');
60
74
  console.log(' thoth build [file].thoth (Production Compilation)');
61
- console.log(' thoth serve [file].thoth (Live Dev Server + Reload)');
75
+ console.log(' thoth serve [file].thoth (Live Dev Server + Traceback)');
62
76
  }
63
77
 
64
78
  /**
65
- * معالجة البيانات الديناميكية @{{key}} و @Variable
79
+ * معالجة البيانات الديناميكية @{{key}} و @Variable (Fast Regex)
66
80
  */
81
+ const DATA_REGEX = /@\{\{([^}]+)\}\}/g;
67
82
  function resolveData(text, context, variables = {}) {
68
- // 1. استبدال المتغيرات @Var
69
83
  let resolved = text;
70
84
  for (const [key, val] of Object.entries(variables)) {
71
85
  resolved = resolved.replace(new RegExp(key, 'g'), val);
72
86
  }
73
- // 2. استبدال بيانات JSON @{{key}}
74
- return resolved.replace(/@\{\{([^}]+)\}\}/g, (match, key) => {
87
+ return resolved.replace(DATA_REGEX, (match, key) => {
75
88
  const val = context[key.trim()];
76
89
  return val !== undefined ? val : match;
77
90
  });
78
91
  }
79
92
 
80
93
  /**
81
- * محرك التجميع المعماري
94
+ * محرك التجميع المعماري (المسرع)
82
95
  */
83
96
  function compileThoth(inputPath, isDev = false) {
84
- if (!fs.existsSync(inputPath)) throw new Error(`Source Integrity Error: "${inputPath}" not found.`);
97
+ if (!fs.existsSync(inputPath)) {
98
+ throw new ThothSyntaxError(`Source Integrity Error: File not found.`, 0, "", inputPath);
99
+ }
85
100
 
86
101
  const source = fs.readFileSync(inputPath, 'utf8');
87
102
  const lines = source.split(/\r?\n/);
88
103
 
89
104
  // --- التحقق من شرط السيادة الأول ---
90
105
  if (lines[0].trim() !== "TYPE THOTH") {
91
- throw new Error("Architectural Identity Error: File must start with 'TYPE THOTH' to ensure sovereignty.");
106
+ throw new ThothSyntaxError("Architectural Identity Error: Missing 'TYPE THOTH' protocol to ensure sovereignty.", 1, lines[0], inputPath);
92
107
  }
93
108
 
94
109
  let htmlContent = "";
@@ -98,12 +113,15 @@ function compileThoth(inputPath, isDev = false) {
98
113
  let skipIndent = -1;
99
114
  let repeatScope = { active: false, key: '', indent: 0, buffer: [] };
100
115
 
101
- for (let i = 1; i < lines.length; i++) { // نبدأ من 1 لتجاوز سطر النوع
116
+ for (let i = 1; i < lines.length; i++) {
117
+ const lineNum = i + 1;
102
118
  let line = lines[i];
103
- const trimmed = line.trim();
104
- const indent = line.search(/\S/);
105
-
119
+
120
+ // تسريع اكتشاف المسافات (أسرع من Regex search)
121
+ const trimmed = line.trimStart();
106
122
  if (!trimmed || trimmed.startsWith('#')) continue;
123
+ const indent = line.length - trimmed.length;
124
+ const fullyTrimmed = trimmed.trimEnd();
107
125
 
108
126
  // --- 1. Middleware / Auth Guard ---
109
127
  if (skipIndent !== -1) {
@@ -111,7 +129,7 @@ function compileThoth(inputPath, isDev = false) {
111
129
  else skipIndent = -1;
112
130
  }
113
131
 
114
- const authMatch = trimmed.match(/Auth="([^"]+)"/);
132
+ const authMatch = fullyTrimmed.match(/Auth="([^"]+)"/);
115
133
  if (authMatch) {
116
134
  if (authMatch[1] !== config.currentUserRole && authMatch[1] !== 'guest') {
117
135
  skipIndent = indent;
@@ -126,31 +144,45 @@ function compileThoth(inputPath, isDev = false) {
126
144
  continue;
127
145
  } else {
128
146
  const list = dataContext[repeatScope.key] || [];
147
+ if(!Array.isArray(list)) {
148
+ throw new ThothSyntaxError(`DataMappingError: '${repeatScope.key}' is not a valid Array in Context.`, lineNum, line, inputPath);
149
+ }
129
150
  list.forEach(item => {
130
- htmlContent += processBuffer(repeatScope.buffer, item, variables);
151
+ htmlContent += processBuffer(repeatScope.buffer, item, variables, inputPath, lineNum);
131
152
  });
132
153
  repeatScope.active = false;
133
154
  repeatScope.buffer = [];
134
155
  }
135
156
  }
136
157
 
137
- if (trimmed.startsWith('Repeat Over="')) {
138
- repeatScope.key = trimmed.match(/Over="([^"]+)"/)[1];
158
+ if (fullyTrimmed.startsWith('Repeat Over="')) {
159
+ const match = fullyTrimmed.match(/Over="([^"]+)"/);
160
+ if (!match) throw new ThothSyntaxError("LoopError: Invalid Repeat syntax.", lineNum, line, inputPath);
161
+ repeatScope.key = match[1];
139
162
  repeatScope.active = true;
140
163
  repeatScope.indent = indent;
141
164
  continue;
142
165
  }
143
166
 
144
167
  // --- 3. Data Ingestion & Variables ---
145
- if (trimmed.startsWith('DataSource:')) {
146
- const dPath = path.resolve(path.dirname(inputPath), trimmed.split(':')[1].trim());
147
- if (fs.existsSync(dPath)) dataContext = JSON.parse(fs.readFileSync(dPath, 'utf8'));
168
+ if (fullyTrimmed.startsWith('DataSource:')) {
169
+ const jsonFileName = fullyTrimmed.split(':')[1].trim();
170
+ const dPath = path.resolve(path.dirname(inputPath), jsonFileName);
171
+ if (!fs.existsSync(dPath)) {
172
+ throw new ThothSyntaxError(`MissingDataError: DataSource '${jsonFileName}' not found.`, lineNum, line, inputPath);
173
+ }
174
+ try {
175
+ dataContext = JSON.parse(fs.readFileSync(dPath, 'utf8'));
176
+ } catch(e) {
177
+ throw new ThothSyntaxError(`JSONParseError: Invalid JSON format in '${jsonFileName}'.`, lineNum, line, inputPath);
178
+ }
148
179
  continue;
149
180
  }
150
181
 
151
- if (trimmed.startsWith('Var ')) {
152
- const vParts = trimmed.substring(4).split(':');
182
+ if (fullyTrimmed.startsWith('Var ')) {
183
+ const vParts = fullyTrimmed.substring(4).split(':');
153
184
  if (vParts.length === 2) variables['@' + vParts[0].trim()] = vParts[1].trim();
185
+ else throw new ThothSyntaxError(`VariableError: Invalid Var syntax. Expected 'Var name: value'.`, lineNum, line, inputPath);
154
186
  continue;
155
187
  }
156
188
 
@@ -168,7 +200,7 @@ function compileThoth(inputPath, isDev = false) {
168
200
  }
169
201
  }
170
202
 
171
- // --- خوارزمية تحليل الفصل الذكي ---
203
+ // --- خوارزمية تحليل الفصل الذكي (Strict Parser) ---
172
204
  let colonIdx = -1;
173
205
  let inQuotes = false;
174
206
  for (let j = 0; j < processedTrimmed.length; j++) {
@@ -201,11 +233,11 @@ function compileThoth(inputPath, isDev = false) {
201
233
  const open = `<${tag}${cleanAttrs ? ' ' + cleanAttrs : ''}>`;
202
234
 
203
235
  if (VOID_ELEMENTS.includes(tag)) {
204
- htmlContent += open + '\n';
236
+ htmlContent += ' '.repeat(indent) + open + '\n';
205
237
  } else if (val) {
206
- htmlContent += `${open}${val}</${tag}>\n`;
238
+ htmlContent += ' '.repeat(indent) + `${open}${val}</${tag}>\n`;
207
239
  } else {
208
- htmlContent += open + '\n';
240
+ htmlContent += ' '.repeat(indent) + open + '\n';
209
241
  stack.push({ name: tag, indent: indent });
210
242
  }
211
243
  }
@@ -213,7 +245,7 @@ function compileThoth(inputPath, isDev = false) {
213
245
  // إغلاق أي تكرار متبقي
214
246
  if (repeatScope.active) {
215
247
  const list = dataContext[repeatScope.key] || [];
216
- list.forEach(item => { htmlContent += processBuffer(repeatScope.buffer, item, variables); });
248
+ list.forEach(item => { htmlContent += processBuffer(repeatScope.buffer, item, variables, inputPath, lines.length); });
217
249
  }
218
250
 
219
251
  while (stack.length > 0) htmlContent += `</${stack.pop().name}>\n`;
@@ -224,14 +256,14 @@ function compileThoth(inputPath, isDev = false) {
224
256
  /**
225
257
  * معالجة الـ Buffer داخل الـ Loop
226
258
  */
227
- function processBuffer(buffer, item, variables) {
259
+ function processBuffer(buffer, item, variables, filePath, baseLineNum) {
228
260
  let res = "";
229
261
  let bStack = [];
230
- buffer.forEach(l => {
231
- const ind = l.search(/\S/);
262
+ buffer.forEach((l, idx) => {
263
+ const ind = l.length - l.trimStart().length;
232
264
  let pLine = resolveData(l, item, variables);
233
265
  const t = pLine.trim();
234
- let cIdx = t.indexOf(':');
266
+ let cIdx = t.indexOf(':'); // Fast path for loops
235
267
  let cmdStr = cIdx !== -1 ? t.substring(0, cIdx).trim() : t;
236
268
  let valStr = cIdx !== -1 ? t.substring(cIdx + 1).trim() : "";
237
269
 
@@ -241,9 +273,9 @@ function processBuffer(buffer, item, variables) {
241
273
  while (bStack.length > 0 && bStack[bStack.length - 1].indent >= ind) res += `</${bStack.pop().name}>\n`;
242
274
 
243
275
  const op = `<${tag}${space !== -1 ? ' ' + cmdStr.substring(space).trim() : ''}>`;
244
- if (VOID_ELEMENTS.includes(tag)) res += op + '\n';
245
- else if (valStr) res += `${op}${valStr}</${tag}>\n`;
246
- else { res += op + '\n'; bStack.push({ name: tag, indent: ind }); }
276
+ if (VOID_ELEMENTS.includes(tag)) res += ' '.repeat(ind) + op + '\n';
277
+ else if (valStr) res += ' '.repeat(ind) + `${op}${valStr}</${tag}>\n`;
278
+ else { res += ' '.repeat(ind) + op + '\n'; bStack.push({ name: tag, indent: ind }); }
247
279
  });
248
280
  while (bStack.length > 0) res += `</${bStack.pop().name}>\n`;
249
281
  return res;
@@ -258,7 +290,7 @@ function generateBoilerplate(content, isDev) {
258
290
 
259
291
  const liveReload = isDev ? `
260
292
  <script>
261
- console.log('%c THOTH DEV MODE: ACTIVE ', 'background:#D4AF37;color:#000;font-weight:bold;');
293
+ console.log('%c THOTH PULSE DEV MODE: ACTIVE ', 'background:#06b6d4;color:#000;font-weight:bold;');
262
294
  let lastMod = null;
263
295
  setInterval(async () => {
264
296
  try {
@@ -276,17 +308,66 @@ function generateBoilerplate(content, isDev) {
276
308
  <meta charset="UTF-8">
277
309
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
278
310
  <meta name="description" content="${desc}">
279
- <meta name="generator" content="THOTH Sovereign Engine v10.5.0">
280
- <meta name="author" content="Abdelfatah Abdelhamed">
311
+ <meta name="generator" content="THOTH Sovereign Engine v11.0.0">
312
+ <meta name="author" content="Engineer Abdelfatah Abdelhamed">
281
313
  <title>${title}</title>
282
314
  </head>
283
- <body style="margin:0; background:#050505; color:#fff;">
315
+ <body style="margin:0; background:#020617; color:#f8fafc;">
284
316
  ${content}
285
317
  ${liveReload}
286
318
  </body>
287
319
  </html>`;
288
320
  }
289
321
 
322
+ /**
323
+ * دالة توليد واجهة تتبع الأخطاء (Browser Overlay)
324
+ */
325
+ function getBrowserTracebackHTML(e) {
326
+ if (e.name === 'ThothSyntaxError') {
327
+ const escapedContent = e.lineContent.replace(/</g, '&lt;').replace(/>/g, '&gt;');
328
+ return `
329
+ <!DOCTYPE html><html lang="en"><head><meta charset="UTF-8"><title>THOTH Engine Error</title></head>
330
+ <body style="margin:0; background:#020617; font-family:'Fira Code', monospace; display:flex; align-items:center; justify-content:center; height:100vh;">
331
+ <div style="background:#0f172a; border:1px solid #ef4444; width:90%; max-width:800px; padding:30px; border-radius:12px; box-shadow:0 0 30px rgba(239, 68, 68, 0.2); color:#e2e8f0;">
332
+ <div style="border-bottom: 1px solid #334155; padding-bottom:15px; margin-bottom:20px;">
333
+ <h2 style="color:#ef4444; margin:0; font-size:1.5rem;">⚠️ THOTH Traceback (most recent call last):</h2>
334
+ </div>
335
+ <div style="padding: 10px 0;">
336
+ <p style="margin:0 0 10px 0; color:#94a3b8;">File <span style="color:#06b6d4;">"${e.filePath}"</span>, line <span style="color:#f59e0b; font-weight:bold;">${e.lineNum}</span>, in &lt;module&gt;</p>
337
+ <div style="background:#000; padding:15px; border-radius:8px; border-left:4px solid #ef4444; overflow-x:auto;">
338
+ <div style="color:#f87171;">${e.lineNum} | <span style="color:#e2e8f0;">${escapedContent}</span></div>
339
+ <div style="color:#ef4444; margin-top:5px;">&nbsp;&nbsp;&nbsp;&nbsp;^</div>
340
+ </div>
341
+ <p style="margin:20px 0 0 0; color:#ef4444; font-weight:bold; font-size:1.1rem;">${e.message}</p>
342
+ </div>
343
+ <div style="border-top: 1px solid #334155; padding-top:15px; margin-top:20px; text-align:right;">
344
+ <button onclick="location.reload()" style="background:#ef4444; color:#fff; padding:8px 24px; border:none; border-radius:6px; cursor:pointer; font-weight:bold; font-family:inherit;">RESTART ENGINE</button>
345
+ </div>
346
+ </div>
347
+ </body></html>`;
348
+ }
349
+ return `<body style="background:#000;color:#ff5555;padding:50px;font-family:monospace">
350
+ <h2 style="border-bottom:2px solid #ff5555;padding-bottom:10px">SOVEREIGN RUNTIME ERROR</h2>
351
+ <p style="font-size:18px">${e.message}</p>
352
+ <button onclick="location.reload()" style="background:#ff5555;color:#fff;border:none;padding:10px 20px;cursor:pointer">RETRY</button>
353
+ </body>`;
354
+ }
355
+
356
+ /**
357
+ * طباعة الأخطاء في التيرمينال
358
+ */
359
+ function printTerminalError(e) {
360
+ if (e.name === 'ThothSyntaxError') {
361
+ console.error('\x1b[31m%s\x1b[0m', `\n⚠️ THOTH Traceback (most recent call last):`);
362
+ console.error('\x1b[90m%s\x1b[0m', ` File "${e.filePath}", line ${e.lineNum}, in <module>`);
363
+ console.error(` ${e.lineContent}`);
364
+ console.error('\x1b[31m%s\x1b[0m', ` ^`);
365
+ console.error('\x1b[1m\x1b[31m%s\x1b[0m', `${e.message}\n`);
366
+ } else {
367
+ console.error(`\x1b[31m [ERROR] ${e.message}\x1b[0m`);
368
+ }
369
+ }
370
+
290
371
  // --- طبقة التنفيذ ---
291
372
  if (command === 'serve') {
292
373
  const server = http.createServer((req, res) => {
@@ -299,21 +380,18 @@ if (command === 'serve') {
299
380
  });
300
381
  res.end(html);
301
382
  } catch (e) {
383
+ printTerminalError(e);
302
384
  res.writeHead(500, { 'Content-Type': 'text/html' });
303
- res.end(`<body style="background:#000;color:#ff5555;padding:50px;font-family:monospace">
304
- <h2 style="border-bottom:2px solid #ff5555;padding-bottom:10px">SOVEREIGN COMPILATION ERROR</h2>
305
- <p style="font-size:18px">${e.message}</p>
306
- <button onclick="location.reload()" style="background:#ff5555;color:#fff;border:none;padding:10px 20px;cursor:pointer">RETRY</button>
307
- </body>`);
385
+ res.end(getBrowserTracebackHTML(e));
308
386
  }
309
387
  });
310
388
 
311
389
  server.listen(config.port, () => {
312
- console.log('\x1b[32m%s\x1b[0m', `──────────────────────────────────────────`);
390
+ console.log('\x1b[36m%s\x1b[0m', `──────────────────────────────────────────`);
313
391
  console.log(` ✔ SERVER ACTIVE: http://localhost:${config.port}`);
314
392
  console.log(` ✔ ARCHITECTURE: ${target}`);
315
- console.log(` ✔ MODE: Intelligence Suite v10.5.0`);
316
- console.log('\x1b[32m%s\x1b[0m', `──────────────────────────────────────────`);
393
+ console.log(` ✔ MODE: Pulse Edition v11.0.0`);
394
+ console.log('\x1b[36m%s\x1b[0m', `──────────────────────────────────────────`);
317
395
  });
318
396
  } else {
319
397
  try {
@@ -321,7 +399,7 @@ if (command === 'serve') {
321
399
  fs.writeFileSync(target.replace('.thoth', '.html'), out);
322
400
  console.log(`\x1b[32m [SUCCESS] Architecture materialized: ${target.replace('.thoth', '.html')}\x1b[0m`);
323
401
  } catch (e) {
324
- console.error(`\x1b[31m [ERROR] ${e.message}\x1b[0m`);
402
+ printTerminalError(e);
325
403
  process.exit(1);
326
404
  }
327
405
  }