baraqex 1.0.20 → 1.0.21

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.
package/README.md CHANGED
@@ -0,0 +1,595 @@
1
+ # Baraqex 🚀
2
+
3
+ A powerful, modern JavaScript/TypeScript framework for building universal web applications with seamless WebAssembly integration, server-side rendering, and full-stack capabilities.
4
+
5
+ ## ✨ Features
6
+
7
+ ### 🎯 Core Features
8
+ - **Universal JSX Support** - Modern React-like components without dependencies
9
+ - **WebAssembly Integration** - Seamless Go WASM support for both browser and Node.js
10
+ - **Server-Side Rendering** - Built-in SSR with hydration support
11
+ - **Full-Stack Framework** - Complete backend server with API routes
12
+ - **TypeScript First** - Full TypeScript support with excellent IntelliSense
13
+ - **Zero Dependencies** - Lightweight core with optional features
14
+
15
+ ### 🌐 WebAssembly Features
16
+ - **Browser WASM** - Load and execute Go WASM modules in the browser
17
+ - **Server WASM** - Run Go WASM functions in Node.js environment
18
+ - **Unified API** - Identical interface for browser and server environments
19
+ - **Hot Reloading** - Development support with fast refresh
20
+
21
+ ### 🔧 Backend Features
22
+ - **Express Integration** - Built on Express.js for reliability
23
+ - **API Routes** - File-based API routing system
24
+ - **Authentication** - JWT-based auth with middleware support
25
+ - **Database Support** - MongoDB, MySQL, PostgreSQL adapters
26
+ - **Static Serving** - Efficient static file serving
27
+
28
+ ## 📦 Installation
29
+
30
+ ```bash
31
+ npm install baraqex
32
+ ```
33
+
34
+ ## 🚀 Quick Start
35
+
36
+ ### Frontend Usage
37
+
38
+ ```javascript
39
+ import { jsx, useState } from 'baraqex';
40
+ import { loadGoWasm, callWasmFunction } from 'baraqex';
41
+
42
+ function App() {
43
+ const [count, setCount] = useState(0);
44
+ const [wasmReady, setWasmReady] = useState(false);
45
+
46
+ // Load WebAssembly module
47
+ useEffect(() => {
48
+ async function initWasm() {
49
+ await loadGoWasm('/app.wasm');
50
+ setWasmReady(true);
51
+ }
52
+ initWasm();
53
+ }, []);
54
+
55
+ const handleCalculate = () => {
56
+ if (wasmReady) {
57
+ // Call Go WASM function
58
+ const result = callWasmFunction('calculate', count);
59
+ console.log('WASM result:', result);
60
+ }
61
+ };
62
+
63
+ return (
64
+ <div>
65
+ <h1>Baraqex App</h1>
66
+ <p>Count: {count}</p>
67
+ <button onClick={() => setCount(count + 1)}>
68
+ Increment
69
+ </button>
70
+ <button onClick={handleCalculate} disabled={!wasmReady}>
71
+ Calculate with WASM
72
+ </button>
73
+ </div>
74
+ );
75
+ }
76
+
77
+ export default App;
78
+ ```
79
+
80
+ ### Server Usage
81
+
82
+ ```javascript
83
+ import { createServer } from 'baraqex/server';
84
+ import { loadGoWasmFromFile, callWasmFunction } from 'baraqex/server';
85
+
86
+ // Create server
87
+ const server = createServer({
88
+ port: 3000,
89
+ apiDir: './api',
90
+ pagesDir: './pages',
91
+ staticDir: './public'
92
+ });
93
+
94
+ // Load WASM for server-side processing
95
+ async function initServerWasm() {
96
+ await loadGoWasmFromFile('./compute.wasm');
97
+ console.log('Server WASM ready!');
98
+ }
99
+
100
+ // Start server
101
+ server.start().then(() => {
102
+ console.log('Server running on http://localhost:3000');
103
+ initServerWasm();
104
+ });
105
+ ```
106
+
107
+ ## 📖 Documentation
108
+
109
+ ### WebAssembly Integration
110
+
111
+ #### Browser WASM
112
+
113
+ ```javascript
114
+ import { loadGoWasm, callWasmFunction, isWasmReady, getWasmFunctions } from 'baraqex';
115
+
116
+ // Load WASM module
117
+ await loadGoWasm('/example.wasm', {
118
+ debug: true,
119
+ onLoad: (instance) => {
120
+ console.log('WASM loaded!', instance);
121
+ }
122
+ });
123
+
124
+ // Check if ready
125
+ if (isWasmReady()) {
126
+ // Get available functions
127
+ const functions = getWasmFunctions();
128
+ console.log('Available functions:', functions);
129
+
130
+ // Call functions
131
+ const greeting = callWasmFunction('goHello', 'World');
132
+ const sum = callWasmFunction('goAdd', 10, 20);
133
+ const fibonacci = callWasmFunction('goFibonacci', 10);
134
+ }
135
+ ```
136
+
137
+ #### Server WASM
138
+
139
+ ```javascript
140
+ import { loadGoWasmFromFile, callWasmFunction } from 'baraqex/server';
141
+
142
+ // Load WASM from file
143
+ await loadGoWasmFromFile('./example.wasm', {
144
+ debug: true,
145
+ goWasmPath: './wasm_exec.cjs'
146
+ });
147
+
148
+ // Use identical API as browser
149
+ const result = callWasmFunction('goCalculate', 42);
150
+ ```
151
+
152
+ #### Go WASM Example
153
+
154
+ ```go
155
+ // main.go
156
+ package main
157
+
158
+ import (
159
+ "fmt"
160
+ "syscall/js"
161
+ )
162
+
163
+ func goHello(this js.Value, args []js.Value) interface{} {
164
+ name := args[0].String()
165
+ return fmt.Sprintf("Hello, %s from Go WASM!", name)
166
+ }
167
+
168
+ func goAdd(this js.Value, args []js.Value) interface{} {
169
+ a := args[0].Float()
170
+ b := args[1].Float()
171
+ return a + b
172
+ }
173
+
174
+ func main() {
175
+ // Register functions
176
+ js.Global().Set("goHello", js.FuncOf(goHello))
177
+ js.Global().Set("goAdd", js.FuncOf(goAdd))
178
+
179
+ fmt.Println("Go WASM ready!")
180
+
181
+ // Keep running
182
+ select {}
183
+ }
184
+ ```
185
+
186
+ Build with:
187
+ ```bash
188
+ GOOS=js GOARCH=wasm go build -o example.wasm main.go
189
+ ```
190
+
191
+ ### Server-Side Rendering
192
+
193
+ #### Page Components
194
+
195
+ ```javascript
196
+ // pages/index.js
197
+ import { jsx } from 'baraqex';
198
+
199
+ export default function HomePage(props) {
200
+ return (
201
+ <html>
202
+ <head>
203
+ <title>My App</title>
204
+ </head>
205
+ <body>
206
+ <h1>Welcome to Baraqex!</h1>
207
+ <p>Server time: {props.api.serverTime}</p>
208
+ </body>
209
+ </html>
210
+ );
211
+ }
212
+
213
+ // Optional: Add metadata
214
+ HomePage.getTitle = (props) => 'Home - My App';
215
+ HomePage.getDescription = (props) => 'Welcome to my application';
216
+ ```
217
+
218
+ #### API Routes
219
+
220
+ ```javascript
221
+ // api/users.js
222
+ export async function get(req, res) {
223
+ // GET /api/users
224
+ const users = await getUsersFromDatabase();
225
+ res.json({ users });
226
+ }
227
+
228
+ export async function post(req, res) {
229
+ // POST /api/users
230
+ const newUser = await createUser(req.body);
231
+ res.json({ user: newUser });
232
+ }
233
+
234
+ // api/users/[id].js
235
+ export async function get(req, res) {
236
+ // GET /api/users/:id
237
+ const user = await getUserById(req.params.id);
238
+ res.json({ user });
239
+ }
240
+ ```
241
+
242
+ ### Database Integration
243
+
244
+ ```javascript
245
+ import { Database } from 'baraqex/server';
246
+
247
+ // MongoDB
248
+ const db = new Database({
249
+ type: 'mongodb',
250
+ url: 'mongodb://localhost:27017/myapp'
251
+ });
252
+
253
+ await db.connect();
254
+ const collection = db.getMongoDb().collection('users');
255
+
256
+ // MySQL
257
+ const db = new Database({
258
+ type: 'mysql',
259
+ url: 'mysql://user:pass@localhost:3306/myapp'
260
+ });
261
+
262
+ await db.connect();
263
+ const users = await db.query('SELECT * FROM users WHERE active = ?', [true]);
264
+
265
+ // PostgreSQL
266
+ const db = new Database({
267
+ type: 'postgres',
268
+ url: 'postgresql://user:pass@localhost:5432/myapp'
269
+ });
270
+
271
+ await db.connect();
272
+ const result = await db.query('SELECT * FROM users WHERE id = $1', [userId]);
273
+ ```
274
+
275
+ ### Authentication
276
+
277
+ ```javascript
278
+ import { AuthService } from 'baraqex/server';
279
+
280
+ const auth = new AuthService({
281
+ secret: 'your-secret-key',
282
+ expiresIn: '24h'
283
+ });
284
+
285
+ // In your API routes
286
+ export async function post(req, res) {
287
+ const { username, password } = req.body;
288
+
289
+ // Validate user
290
+ const user = await validateUser(username, password);
291
+ if (!user) {
292
+ return res.status(401).json({ error: 'Invalid credentials' });
293
+ }
294
+
295
+ // Generate token
296
+ const token = auth.generateToken(user);
297
+ res.json({ token, user });
298
+ }
299
+
300
+ // Protected route
301
+ export const middleware = [auth.requireAuth()];
302
+
303
+ export async function get(req, res) {
304
+ // req.user is available
305
+ res.json({ user: req.user });
306
+ }
307
+ ```
308
+
309
+ ## 🛠️ Development
310
+
311
+ ### Project Structure
312
+
313
+ ```
314
+ my-app/
315
+ ├── src/
316
+ │ ├── pages/ # SSR pages
317
+ │ │ ├── index.js # Home page
318
+ │ │ └── about.js # About page
319
+ │ ├── api/ # API routes
320
+ │ │ ├── users.js # /api/users
321
+ │ │ └── auth/ # /api/auth/*
322
+ │ └── components/ # Reusable components
323
+ ├── public/ # Static files
324
+ │ ├── app.wasm # WebAssembly modules
325
+ │ └── styles.css # Stylesheets
326
+ ├── wasm/ # Go WASM source
327
+ │ └── main.go # Go functions
328
+ └── package.json
329
+ ```
330
+
331
+ ### Build Scripts
332
+
333
+ ```json
334
+ {
335
+ "scripts": {
336
+ "dev": "baraqex dev",
337
+ "build": "baraqex build",
338
+ "start": "baraqex start",
339
+ "build:wasm": "GOOS=js GOARCH=wasm go build -o public/app.wasm wasm/main.go"
340
+ }
341
+ }
342
+ ```
343
+
344
+ ### Development Server
345
+
346
+ ```javascript
347
+ import { createDevServer } from 'baraqex/server';
348
+
349
+ const server = createDevServer({
350
+ port: 3000,
351
+ enableCors: true
352
+ });
353
+
354
+ // Enable SSR with hot reloading
355
+ server.enableSSR({ hydratable: true });
356
+
357
+ await server.start();
358
+ ```
359
+
360
+ ## 🔧 Configuration
361
+
362
+ ### Server Configuration
363
+
364
+ ```javascript
365
+ import { createServer } from 'baraqex/server';
366
+
367
+ const server = createServer({
368
+ port: process.env.PORT || 3000,
369
+ apiDir: './src/api',
370
+ pagesDir: './src/pages',
371
+ staticDir: './public',
372
+ enableCors: true,
373
+ corsOptions: {
374
+ origin: ['http://localhost:3000'],
375
+ credentials: true
376
+ },
377
+ db: {
378
+ type: 'mongodb',
379
+ url: process.env.DATABASE_URL
380
+ },
381
+ auth: {
382
+ secret: process.env.JWT_SECRET,
383
+ expiresIn: '7d'
384
+ }
385
+ });
386
+ ```
387
+
388
+ ### WASM Configuration
389
+
390
+ ```javascript
391
+ // Browser
392
+ await loadGoWasm('/app.wasm', {
393
+ debug: process.env.NODE_ENV === 'development',
394
+ importObject: {
395
+ // Custom WASM imports
396
+ },
397
+ onLoad: (instance) => {
398
+ console.log('WASM loaded with exports:', instance.exports);
399
+ }
400
+ });
401
+
402
+ // Server
403
+ await loadGoWasmFromFile('./app.wasm', {
404
+ debug: true,
405
+ goWasmPath: './wasm_exec.cjs'
406
+ });
407
+ ```
408
+
409
+ ## 📊 Performance
410
+
411
+ ### WebAssembly Benefits
412
+ - **Near-native performance** for compute-intensive tasks
413
+ - **Memory efficiency** with direct memory access
414
+ - **Parallel processing** capabilities
415
+ - **Type safety** with compiled languages
416
+
417
+ ### Server Optimizations
418
+ - **Built-in caching** for static assets
419
+ - **Compression** support (gzip, brotli)
420
+ - **HTTP/2** ready
421
+ - **Cluster mode** for production
422
+
423
+ ## 🧪 Testing
424
+
425
+ ### Complete Test Suite
426
+
427
+ ```bash
428
+ # Run all tests (builds project first)
429
+ npm test
430
+
431
+ # Run server function tests only
432
+ npm run test:server
433
+
434
+ # Run WASM integration tests only
435
+ npm run test:wasm
436
+ ```
437
+
438
+ ### WASM Testing
439
+
440
+ ```javascript
441
+ // test-wasm.js
442
+ import { loadGoWasmFromFile, callWasmFunction } from 'baraqex/server';
443
+
444
+ async function testWasm() {
445
+ await loadGoWasmFromFile('./example.wasm');
446
+
447
+ // Test functions
448
+ const greeting = callWasmFunction('goHello', 'Test');
449
+ console.assert(greeting.includes('Test'), 'Hello function works');
450
+
451
+ const sum = callWasmFunction('goAdd', 5, 3);
452
+ console.assert(sum === 8, 'Add function works');
453
+
454
+ console.log('All WASM tests passed!');
455
+ }
456
+
457
+ testWasm();
458
+ ```
459
+
460
+ ### Server Testing
461
+
462
+ ```javascript
463
+ import request from 'supertest';
464
+ import { createServer } from 'baraqex/server';
465
+
466
+ const server = createServer();
467
+ const app = server.getExpressApp();
468
+
469
+ describe('API Routes', () => {
470
+ test('GET /api/users', async () => {
471
+ const response = await request(app)
472
+ .get('/api/users')
473
+ .expect(200);
474
+
475
+ expect(response.body).toHaveProperty('users');
476
+ });
477
+ });
478
+ ```
479
+
480
+ ### Test Results
481
+
482
+ The test suite covers:
483
+ - ✅ **Server Creation** - Basic server setup and configuration
484
+ - ✅ **Database Connections** - MongoDB, MySQL, PostgreSQL adapters
485
+ - ✅ **Authentication** - JWT token generation and validation
486
+ - ✅ **WebAssembly Integration** - Go WASM loading and function calls
487
+ - ✅ **API Routes** - Dynamic route registration and handling
488
+ - ✅ **Server Utilities** - Helper functions and middleware
489
+ - ✅ **Template Generation** - HTML document and error page creation
490
+
491
+ ## 🚀 Deployment
492
+
493
+ ### Production Build
494
+
495
+ ```bash
496
+ # Build WASM modules
497
+ npm run build:wasm
498
+
499
+ # Build application
500
+ npm run build
501
+
502
+ # Start production server
503
+ npm start
504
+ ```
505
+
506
+ ### Docker Deployment
507
+
508
+ ```dockerfile
509
+ FROM node:18-alpine
510
+
511
+ WORKDIR /app
512
+
513
+ # Install Go for WASM building
514
+ RUN apk add --no-cache go
515
+
516
+ # Copy package files
517
+ COPY package*.json ./
518
+ RUN npm ci --only=production
519
+
520
+ # Copy source
521
+ COPY . .
522
+
523
+ # Build WASM
524
+ RUN npm run build:wasm
525
+
526
+ # Build app
527
+ RUN npm run build
528
+
529
+ EXPOSE 3000
530
+
531
+ CMD ["npm", "start"]
532
+ ```
533
+
534
+ ### Environment Variables
535
+
536
+ ```bash
537
+ # Server
538
+ PORT=3000
539
+ NODE_ENV=production
540
+
541
+ # Database
542
+ DATABASE_URL=mongodb://localhost:27017/myapp
543
+
544
+ # Authentication
545
+ JWT_SECRET=your-super-secret-key
546
+
547
+ # WASM
548
+ WASM_DEBUG=false
549
+ ```
550
+
551
+ ## 🤝 Contributing
552
+
553
+ 1. Fork the repository
554
+ 2. Create a feature branch: `git checkout -b feature/amazing-feature`
555
+ 3. Make changes and add tests
556
+ 4. Commit: `git commit -m 'Add amazing feature'`
557
+ 5. Push: `git push origin feature/amazing-feature`
558
+ 6. Submit a Pull Request
559
+
560
+ ## 📄 License
561
+
562
+ MIT License - see the [LICENSE](LICENSE) file for details.
563
+
564
+ ## 🆘 Support
565
+
566
+ - **Documentation**: [www.baraqex.tech](https://www.baraqex.tech)
567
+ - **Website**: [www.baraqex.tech](https://www.baraqex.tech)
568
+ - **Issues**: [GitHub Issues](https://github.com/hamroun/baraqex/issues)
569
+ - **Discussions**: [GitHub Discussions](https://github.com/hamroun/baraqex/discussions)
570
+ - **Discord**: [Join our community](https://discord.gg/baraqex)
571
+
572
+ ## 🎯 Examples
573
+
574
+ Check out the [examples directory](./examples) for complete sample applications:
575
+
576
+ - **Basic WASM App** - Simple calculator with Go WASM
577
+ - **Full-Stack Todo** - Complete CRUD app with auth
578
+ - **Real-time Chat** - WebSocket integration
579
+ - **E-commerce Site** - Complex SSR application
580
+ - **Data Visualization** - WASM-powered charts
581
+
582
+ ## 🔗 Related Projects
583
+
584
+ - **Go WASM Runtime**: Standard Go WebAssembly support
585
+ - **Express.js**: The underlying server framework
586
+ - **TypeScript**: Type safety and developer experience
587
+ - **Official Website**: [www.baraqex.tech](https://www.baraqex.tech)
588
+
589
+ ---
590
+
591
+ **Made with ❤️ by the Baraqex team**
592
+
593
+ *Build universal, high-performance web applications with the power of WebAssembly and modern JavaScript.*
594
+
595
+ **Learn more at [www.baraqex.tech](https://www.baraqex.tech)**