treste 2.0.0 → 2.1.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.
@@ -0,0 +1,705 @@
1
+ "use strict";
2
+ /**
3
+ * Native Standard Library Implementations
4
+ * Bibliotecas nativas em TypeScript para o Trest Language
5
+ */
6
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
7
+ if (k2 === undefined) k2 = k;
8
+ var desc = Object.getOwnPropertyDescriptor(m, k);
9
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
10
+ desc = { enumerable: true, get: function() { return m[k]; } };
11
+ }
12
+ Object.defineProperty(o, k2, desc);
13
+ }) : (function(o, m, k, k2) {
14
+ if (k2 === undefined) k2 = k;
15
+ o[k2] = m[k];
16
+ }));
17
+ var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
18
+ Object.defineProperty(o, "default", { enumerable: true, value: v });
19
+ }) : function(o, v) {
20
+ o["default"] = v;
21
+ });
22
+ var __importStar = (this && this.__importStar) || (function () {
23
+ var ownKeys = function(o) {
24
+ ownKeys = Object.getOwnPropertyNames || function (o) {
25
+ var ar = [];
26
+ for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
27
+ return ar;
28
+ };
29
+ return ownKeys(o);
30
+ };
31
+ return function (mod) {
32
+ if (mod && mod.__esModule) return mod;
33
+ var result = {};
34
+ if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
35
+ __setModuleDefault(result, mod);
36
+ return result;
37
+ };
38
+ })();
39
+ Object.defineProperty(exports, "__esModule", { value: true });
40
+ exports.StdModules = exports.StdCrypto = exports.StdDate = exports.StdJSON = exports.StdFileSystem = exports.StdDatabase = exports.StdGUI = exports.StdAsync = exports.StdHTTP = void 0;
41
+ const http = __importStar(require("http"));
42
+ const https = __importStar(require("https"));
43
+ const fs = __importStar(require("fs"));
44
+ const url_1 = require("url");
45
+ /**
46
+ * ========================================
47
+ * HTTP Module - Cliente e Servidor HTTP
48
+ * ========================================
49
+ */
50
+ class StdHTTP {
51
+ /**
52
+ * GET Request
53
+ */
54
+ static async GET(url, options = {}) {
55
+ return this.request(url, 'GET', null, options);
56
+ }
57
+ /**
58
+ * POST Request
59
+ */
60
+ static async POST(url, data, options = {}) {
61
+ return this.request(url, 'POST', data, options);
62
+ }
63
+ /**
64
+ * PUT Request
65
+ */
66
+ static async PUT(url, data, options = {}) {
67
+ return this.request(url, 'PUT', data, options);
68
+ }
69
+ /**
70
+ * DELETE Request
71
+ */
72
+ static async DELETE(url, options = {}) {
73
+ return this.request(url, 'DELETE', null, options);
74
+ }
75
+ /**
76
+ * Generic HTTP Request
77
+ */
78
+ static request(urlStr, method, data = null, options = {}) {
79
+ return new Promise((resolve, reject) => {
80
+ try {
81
+ const url = new url_1.URL(urlStr);
82
+ const isHttps = url.protocol === 'https:';
83
+ const requestOptions = {
84
+ hostname: url.hostname,
85
+ port: url.port || (isHttps ? 443 : 80),
86
+ path: url.pathname + url.search,
87
+ method: method,
88
+ headers: options.headers || {
89
+ 'Content-Type': 'application/json',
90
+ },
91
+ };
92
+ const client = isHttps ? https : http;
93
+ const req = client.request(requestOptions, (res) => {
94
+ let body = '';
95
+ res.on('data', (chunk) => {
96
+ body += chunk;
97
+ });
98
+ res.on('end', () => {
99
+ try {
100
+ const parsed = JSON.parse(body);
101
+ resolve({
102
+ status: res.statusCode,
103
+ data: parsed,
104
+ headers: res.headers,
105
+ });
106
+ }
107
+ catch {
108
+ resolve({
109
+ status: res.statusCode,
110
+ data: body,
111
+ headers: res.headers,
112
+ });
113
+ }
114
+ });
115
+ });
116
+ req.on('error', (error) => {
117
+ reject({ status: 0, error: error.message });
118
+ });
119
+ if (data) {
120
+ const dataStr = typeof data === 'string' ? data : JSON.stringify(data);
121
+ req.write(dataStr);
122
+ }
123
+ req.end();
124
+ }
125
+ catch (error) {
126
+ reject({ status: 0, error: error.message });
127
+ }
128
+ });
129
+ }
130
+ /**
131
+ * Create HTTP Server
132
+ */
133
+ static createServer() {
134
+ const routes = new Map();
135
+ const addRoute = (method, path, handler) => {
136
+ if (!routes.has(path)) {
137
+ routes.set(path, new Map());
138
+ }
139
+ routes.get(path).set(method, handler);
140
+ };
141
+ const server = http.createServer((req, res) => {
142
+ const handlers = routes.get(req.url || '/');
143
+ const handler = handlers?.get(req.method || 'GET');
144
+ if (handler) {
145
+ const requestObj = {
146
+ url: req.url,
147
+ method: req.method,
148
+ headers: req.headers,
149
+ body: '',
150
+ };
151
+ let body = '';
152
+ req.on('data', (chunk) => {
153
+ body += chunk;
154
+ });
155
+ req.on('end', () => {
156
+ try {
157
+ requestObj.body = JSON.parse(body);
158
+ }
159
+ catch {
160
+ requestObj.body = body;
161
+ }
162
+ const responseObj = {
163
+ status: (code) => {
164
+ res.statusCode = code;
165
+ return responseObj;
166
+ },
167
+ send: (data) => {
168
+ const dataStr = typeof data === 'string' ? data : JSON.stringify(data);
169
+ res.end(dataStr);
170
+ return responseObj;
171
+ },
172
+ json: (data) => {
173
+ res.setHeader('Content-Type', 'application/json');
174
+ res.end(JSON.stringify(data));
175
+ return responseObj;
176
+ },
177
+ };
178
+ handler(requestObj, responseObj);
179
+ });
180
+ }
181
+ else {
182
+ res.statusCode = 404;
183
+ res.end('Not Found');
184
+ }
185
+ });
186
+ return {
187
+ listen: (port, callback) => {
188
+ server.listen(port, () => {
189
+ if (callback)
190
+ callback();
191
+ });
192
+ },
193
+ get: (path, handler) => addRoute('GET', path, handler),
194
+ post: (path, handler) => addRoute('POST', path, handler),
195
+ put: (path, handler) => addRoute('PUT', path, handler),
196
+ delete: (path, handler) => addRoute('DELETE', path, handler),
197
+ };
198
+ }
199
+ /**
200
+ * Fetch API
201
+ */
202
+ static async fetch(url, options = {}) {
203
+ return this.request(url, options.method || 'GET', options.body, options);
204
+ }
205
+ }
206
+ exports.StdHTTP = StdHTTP;
207
+ /**
208
+ * ========================================
209
+ * Async Module - Promises, Delay
210
+ * ========================================
211
+ */
212
+ class StdAsync {
213
+ /**
214
+ * Create Promise
215
+ */
216
+ static createPromise(executor) {
217
+ return new Promise((resolve, reject) => {
218
+ executor(resolve, reject);
219
+ });
220
+ }
221
+ /**
222
+ * Promise.all
223
+ */
224
+ static allPromises(promises) {
225
+ return Promise.all(promises);
226
+ }
227
+ /**
228
+ * Promise.race
229
+ */
230
+ static anyPromise(promises) {
231
+ return Promise.race(promises);
232
+ }
233
+ /**
234
+ * Delay/Sleep
235
+ */
236
+ static delay(ms) {
237
+ return new Promise((resolve) => setTimeout(resolve, ms));
238
+ }
239
+ /**
240
+ * setInterval
241
+ */
242
+ static repeatInterval(fn, ms) {
243
+ return setInterval(() => fn(), ms);
244
+ }
245
+ /**
246
+ * clearInterval
247
+ */
248
+ static clearRepeat(id) {
249
+ clearInterval(id);
250
+ }
251
+ /**
252
+ * setTimeout
253
+ */
254
+ static setTimer(fn, ms) {
255
+ return setTimeout(() => fn(), ms);
256
+ }
257
+ /**
258
+ * clearTimeout
259
+ */
260
+ static clearTimer(id) {
261
+ clearTimeout(id);
262
+ }
263
+ }
264
+ exports.StdAsync = StdAsync;
265
+ /**
266
+ * ========================================
267
+ * GUI Module - Interface Gráfica
268
+ * ========================================
269
+ */
270
+ class StdGUI {
271
+ /**
272
+ * Create Terminal
273
+ */
274
+ static createTerminal() {
275
+ return {
276
+ clear: () => {
277
+ console.clear();
278
+ },
279
+ printAt: (x, y, text) => {
280
+ // Basic terminal positioning
281
+ process.stdout.write(`\x1b[${y};${x}H${text}`);
282
+ },
283
+ getHeight: () => process.stdout.rows || 24,
284
+ getWidth: () => process.stdout.columns || 80,
285
+ };
286
+ }
287
+ /**
288
+ * Create Window (placeholder)
289
+ */
290
+ static createWindow(options) {
291
+ console.log(`Creating window: ${options.title || 'Untitled'}`);
292
+ return {
293
+ show: () => console.log('Window shown'),
294
+ hide: () => console.log('Window hidden'),
295
+ close: () => console.log('Window closed'),
296
+ addComponent: (component) => {
297
+ console.log('Component added', component);
298
+ },
299
+ };
300
+ }
301
+ /**
302
+ * Create Button
303
+ */
304
+ static createButton(text, onClick) {
305
+ return {
306
+ text,
307
+ click: onClick,
308
+ disable: () => console.log(`Button "${text}" disabled`),
309
+ enable: () => console.log(`Button "${text}" enabled`),
310
+ };
311
+ }
312
+ /**
313
+ * Create Text Input
314
+ */
315
+ static createText(placeholder, onChange) {
316
+ return {
317
+ value: '',
318
+ change: onChange,
319
+ focus: () => console.log('Text focused'),
320
+ blur: () => console.log('Text blurred'),
321
+ };
322
+ }
323
+ /**
324
+ * Create List
325
+ */
326
+ static createList(data, onSelect) {
327
+ return {
328
+ data,
329
+ select: onSelect,
330
+ update: (newData) => {
331
+ data = newData;
332
+ console.log('List updated');
333
+ },
334
+ };
335
+ }
336
+ /**
337
+ * Component Container
338
+ */
339
+ static componentContainer(children) {
340
+ return {
341
+ children,
342
+ add: (component) => {
343
+ children.push(component);
344
+ },
345
+ remove: (component) => {
346
+ const index = children.indexOf(component);
347
+ if (index > -1)
348
+ children.splice(index, 1);
349
+ },
350
+ };
351
+ }
352
+ /**
353
+ * Component Label
354
+ */
355
+ static componentLabel(text) {
356
+ return { text };
357
+ }
358
+ /**
359
+ * Component Image
360
+ */
361
+ static componentImage(src) {
362
+ return {
363
+ src,
364
+ show: () => console.log(`Image shown: ${src}`),
365
+ hide: () => console.log(`Image hidden: ${src}`),
366
+ };
367
+ }
368
+ }
369
+ exports.StdGUI = StdGUI;
370
+ /**
371
+ * ========================================
372
+ * Database Module - SQLite
373
+ * ========================================
374
+ */
375
+ class StdDatabase {
376
+ /**
377
+ * Open Database
378
+ */
379
+ static openDB(dbPath) {
380
+ if (this.dbConnections.has(dbPath)) {
381
+ return this.dbConnections.get(dbPath);
382
+ }
383
+ // For now, use file-based mock database
384
+ const db = {
385
+ path: dbPath,
386
+ execute: (query, params = []) => {
387
+ console.log(`[DB] Executing: ${query}`, params);
388
+ return { success: true };
389
+ },
390
+ query: (query, params = []) => {
391
+ console.log(`[DB] Querying: ${query}`, params);
392
+ return [];
393
+ },
394
+ transaction: (fn) => {
395
+ console.log('[DB] Transaction started');
396
+ fn();
397
+ console.log('[DB] Transaction committed');
398
+ },
399
+ close: () => {
400
+ console.log(`[DB] Closed: ${dbPath}`);
401
+ this.dbConnections.delete(dbPath);
402
+ },
403
+ };
404
+ this.dbConnections.set(dbPath, db);
405
+ return db;
406
+ }
407
+ /**
408
+ * Query Builder
409
+ */
410
+ static createQueryBuilder(table) {
411
+ const builder = {
412
+ table,
413
+ selectFields: '*',
414
+ whereClause: '',
415
+ orderClause: '',
416
+ limitValue: '',
417
+ conditions: [],
418
+ select: function (fields) {
419
+ this.selectFields = fields;
420
+ return this;
421
+ },
422
+ where: function (condition) {
423
+ this.whereClause = `WHERE ${condition}`;
424
+ return this;
425
+ },
426
+ order: function (field) {
427
+ this.orderClause = `ORDER BY ${field}`;
428
+ return this;
429
+ },
430
+ limit: function (n) {
431
+ this.limitValue = `LIMIT ${n}`;
432
+ return this;
433
+ },
434
+ execute: function () {
435
+ const sql = `SELECT ${this.selectFields} FROM ${this.table} ${this.whereClause} ${this.orderClause} ${this.limitValue}`;
436
+ console.log(`[Query Builder] ${sql}`);
437
+ return [];
438
+ },
439
+ };
440
+ return builder;
441
+ }
442
+ /**
443
+ * Basic Model
444
+ */
445
+ static Model(table) {
446
+ return {
447
+ table,
448
+ find: (id) => {
449
+ console.log(`[Model] Finding ${table} with id: ${id}`);
450
+ return null;
451
+ },
452
+ all: () => {
453
+ console.log(`[Model] Getting all ${table}`);
454
+ return [];
455
+ },
456
+ create: (data) => {
457
+ console.log(`[Model] Creating ${table}:`, data);
458
+ return { id: 1, ...data };
459
+ },
460
+ update: (id, data) => {
461
+ console.log(`[Model] Updating ${table} ${id}:`, data);
462
+ return { success: true };
463
+ },
464
+ delete: (id) => {
465
+ console.log(`[Model] Deleting ${table} ${id}`);
466
+ return { success: true };
467
+ },
468
+ };
469
+ }
470
+ }
471
+ exports.StdDatabase = StdDatabase;
472
+ StdDatabase.dbConnections = new Map();
473
+ /**
474
+ * ========================================
475
+ * Enhanced File System Module
476
+ * ========================================
477
+ */
478
+ class StdFileSystem {
479
+ /**
480
+ * Read File
481
+ */
482
+ static readFile(filePath) {
483
+ try {
484
+ return fs.readFileSync(filePath, 'utf-8');
485
+ }
486
+ catch (error) {
487
+ throw new Error(`Cannot read file: ${error.message}`);
488
+ }
489
+ }
490
+ /**
491
+ * Write File
492
+ */
493
+ static writeFile(filePath, content) {
494
+ try {
495
+ fs.writeFileSync(filePath, content, 'utf-8');
496
+ }
497
+ catch (error) {
498
+ throw new Error(`Cannot write file: ${error.message}`);
499
+ }
500
+ }
501
+ /**
502
+ * File Exists
503
+ */
504
+ static exists(filePath) {
505
+ return fs.existsSync(filePath);
506
+ }
507
+ /**
508
+ * Delete File
509
+ */
510
+ static deleteFile(filePath) {
511
+ try {
512
+ fs.unlinkSync(filePath);
513
+ }
514
+ catch (error) {
515
+ throw new Error(`Cannot delete file: ${error.message}`);
516
+ }
517
+ }
518
+ /**
519
+ * List Directory
520
+ */
521
+ static listDir(dirPath) {
522
+ try {
523
+ return fs.readdirSync(dirPath);
524
+ }
525
+ catch (error) {
526
+ throw new Error(`Cannot list directory: ${error.message}`);
527
+ }
528
+ }
529
+ /**
530
+ * Create Directory
531
+ */
532
+ static createDir(dirPath) {
533
+ try {
534
+ fs.mkdirSync(dirPath, { recursive: true });
535
+ }
536
+ catch (error) {
537
+ throw new Error(`Cannot create directory: ${error.message}`);
538
+ }
539
+ }
540
+ /**
541
+ * Delete Directory
542
+ */
543
+ static deleteDir(dirPath) {
544
+ try {
545
+ fs.rmSync(dirPath, { recursive: true, force: true });
546
+ }
547
+ catch (error) {
548
+ throw new Error(`Cannot delete directory: ${error.message}`);
549
+ }
550
+ }
551
+ /**
552
+ * Get File Stats
553
+ */
554
+ static getStats(filePath) {
555
+ try {
556
+ const stats = fs.statSync(filePath);
557
+ return {
558
+ size: stats.size,
559
+ isFile: stats.isFile(),
560
+ isDirectory: stats.isDirectory(),
561
+ createdAt: stats.birthtime,
562
+ modifiedAt: stats.mtime,
563
+ };
564
+ }
565
+ catch (error) {
566
+ throw new Error(`Cannot get stats: ${error.message}`);
567
+ }
568
+ }
569
+ }
570
+ exports.StdFileSystem = StdFileSystem;
571
+ /**
572
+ * ========================================
573
+ * JSON Module
574
+ * ========================================
575
+ */
576
+ class StdJSON {
577
+ /**
578
+ * Parse JSON
579
+ */
580
+ static parse(jsonStr) {
581
+ try {
582
+ return JSON.parse(jsonStr);
583
+ }
584
+ catch (error) {
585
+ throw new Error(`Invalid JSON: ${error.message}`);
586
+ }
587
+ }
588
+ /**
589
+ * Stringify JSON
590
+ */
591
+ static stringify(obj, indent = 0) {
592
+ return JSON.stringify(obj, null, indent);
593
+ }
594
+ }
595
+ exports.StdJSON = StdJSON;
596
+ /**
597
+ * ========================================
598
+ * Date Module
599
+ * ========================================
600
+ */
601
+ class StdDate {
602
+ /**
603
+ * Current Date
604
+ */
605
+ static now() {
606
+ return new Date();
607
+ }
608
+ /**
609
+ * Format Date
610
+ */
611
+ static format(date, formatStr = 'YYYY-MM-DD HH:mm:ss') {
612
+ const d = new Date(date);
613
+ const year = d.getFullYear();
614
+ const month = String(d.getMonth() + 1).padStart(2, '0');
615
+ const day = String(d.getDate()).padStart(2, '0');
616
+ const hours = String(d.getHours()).padStart(2, '0');
617
+ const minutes = String(d.getMinutes()).padStart(2, '0');
618
+ const seconds = String(d.getSeconds()).padStart(2, '0');
619
+ return formatStr
620
+ .replace('YYYY', String(year))
621
+ .replace('MM', month)
622
+ .replace('DD', day)
623
+ .replace('HH', hours)
624
+ .replace('mm', minutes)
625
+ .replace('ss', seconds);
626
+ }
627
+ /**
628
+ * Get Timezone
629
+ */
630
+ static timezone() {
631
+ return Intl.DateTimeFormat().resolvedOptions().timeZone;
632
+ }
633
+ }
634
+ exports.StdDate = StdDate;
635
+ /**
636
+ * ========================================
637
+ * Crypto Module
638
+ * ========================================
639
+ */
640
+ const crypto = __importStar(require("crypto"));
641
+ class StdCrypto {
642
+ /**
643
+ * Hash MD5
644
+ */
645
+ static md5(text) {
646
+ return crypto.createHash('md5').update(text).digest('hex');
647
+ }
648
+ /**
649
+ * Hash SHA256
650
+ */
651
+ static sha256(text) {
652
+ return crypto.createHash('sha256').update(text).digest('hex');
653
+ }
654
+ /**
655
+ * Hash SHA512
656
+ */
657
+ static sha512(text) {
658
+ return crypto.createHash('sha512').update(text).digest('hex');
659
+ }
660
+ /**
661
+ * Random Bytes
662
+ */
663
+ static randomBytes(length) {
664
+ return crypto.randomBytes(length).toString('hex');
665
+ }
666
+ /**
667
+ * Encrypt AES
668
+ */
669
+ static encrypt(text, key) {
670
+ const algorithm = 'aes-256-cbc';
671
+ const iv = crypto.randomBytes(16);
672
+ const cipher = crypto.createCipheriv(algorithm, Buffer.from(key.slice(0, 32).padEnd(32, '0')), iv);
673
+ let encrypted = cipher.update(text, 'utf8', 'hex');
674
+ encrypted += cipher.final('hex');
675
+ return iv.toString('hex') + ':' + encrypted;
676
+ }
677
+ /**
678
+ * Decrypt AES
679
+ */
680
+ static decrypt(encrypted, key) {
681
+ const algorithm = 'aes-256-cbc';
682
+ const parts = encrypted.split(':');
683
+ const iv = Buffer.from(parts[0], 'hex');
684
+ const encryptedText = parts[1];
685
+ const decipher = crypto.createDecipheriv(algorithm, Buffer.from(key.slice(0, 32).padEnd(32, '0')), iv);
686
+ let decrypted = decipher.update(encryptedText, 'hex', 'utf8');
687
+ decrypted += decipher.final('utf8');
688
+ return decrypted;
689
+ }
690
+ }
691
+ exports.StdCrypto = StdCrypto;
692
+ /**
693
+ * Export all modules
694
+ */
695
+ exports.StdModules = {
696
+ HTTP: StdHTTP,
697
+ Async: StdAsync,
698
+ GUI: StdGUI,
699
+ Database: StdDatabase,
700
+ FileSystem: StdFileSystem,
701
+ JSON: StdJSON,
702
+ Date: StdDate,
703
+ Crypto: StdCrypto,
704
+ };
705
+ //# sourceMappingURL=std-native.js.map