baraqex 1.0.31 → 1.0.33

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 (36) hide show
  1. package/bin/baraqex.js +1253 -196
  2. package/dist/server/index.d.ts +3 -6
  3. package/dist/server/index.d.ts.map +1 -1
  4. package/dist/server/index.js +8 -125
  5. package/dist/server/index.js.map +1 -1
  6. package/package.json +1 -1
  7. package/templates/fullstack-template/src/pages/index.js +193 -48
  8. package/templates/ssr-template/package-lock.json +5080 -0
  9. package/templates/ssr-template/package.json +8 -14
  10. package/templates/ssr-template/src/App.tsx +7 -19
  11. package/templates/ssr-template/src/client.tsx +1 -21
  12. package/templates/ssr-template/src/server.ts +14 -183
  13. package/templates/ssr-template/tsconfig.json +6 -15
  14. package/templates/ssr-template/tsconfig.server.json +5 -18
  15. package/templates/wasm/build-wasm.js +228 -0
  16. package/templates/wasm/esbuild.config.js +63 -0
  17. package/templates/wasm/go/main.go +256 -0
  18. package/templates/wasm/go/wasm_exec.js +0 -0
  19. package/templates/wasm/index.html +97 -0
  20. package/templates/wasm/jsx-shim.js +9 -0
  21. package/templates/wasm/package-lock.json +4848 -0
  22. package/templates/wasm/package.json +27 -0
  23. package/templates/wasm/public/example.wasm +0 -0
  24. package/templates/wasm/public/wasm_exec.js +572 -0
  25. package/templates/wasm/src/App.tsx +519 -0
  26. package/templates/wasm/src/client.tsx +220 -0
  27. package/templates/wasm/src/index.html +14 -0
  28. package/templates/wasm/src/index.tsx +21 -0
  29. package/templates/wasm/src/main.tsx +5 -0
  30. package/templates/wasm/src/server.ts +145 -0
  31. package/templates/wasm/src/wasm-loader.ts +119 -0
  32. package/templates/wasm/tsconfig.json +21 -0
  33. package/templates/wasm/tsconfig.node.json +13 -0
  34. package/templates/wasm/tsconfig.server.json +23 -0
  35. package/templates/wasm/vite.config.ts +73 -0
  36. package/templates/wasm/wasm-loader.js +103 -0
@@ -0,0 +1,220 @@
1
+ import { jsx, render } from 'frontend-hamroun';
2
+ import { loadGoWasm } from '../wasm-loader.js';
3
+
4
+ // WASM Demo Component
5
+ function WasmDemo() {
6
+ const [wasmReady, setWasmReady] = useState(false);
7
+ const [result, setResult] = useState('');
8
+ const [input1, setInput1] = useState('5');
9
+ const [input2, setInput2] = useState('3');
10
+ const [fibInput, setFibInput] = useState('10');
11
+
12
+ useEffect(() => {
13
+ loadWasm();
14
+ }, []);
15
+
16
+ const loadWasm = async () => {
17
+ try {
18
+ await loadGoWasm('/example.wasm');
19
+ setWasmReady(true);
20
+ setResult('✅ Go WASM module loaded successfully!');
21
+ } catch (error) {
22
+ setResult(`❌ Failed to load WASM: ${error.message}`);
23
+ }
24
+ };
25
+
26
+ const testAdd = () => {
27
+ if (!wasmReady) return;
28
+ try {
29
+ const num1 = parseFloat(input1);
30
+ const num2 = parseFloat(input2);
31
+ const result = (window as any).add(num1, num2);
32
+ setResult(`Add result: ${num1} + ${num2} = ${result}`);
33
+ } catch (error) {
34
+ setResult(`Error: ${error.message}`);
35
+ }
36
+ };
37
+
38
+ const testFibonacci = () => {
39
+ if (!wasmReady) return;
40
+ try {
41
+ const n = parseInt(fibInput);
42
+ const result = (window as any).fibonacci(n);
43
+ setResult(`Fibonacci(${n}) = ${result}`);
44
+ } catch (error) {
45
+ setResult(`Error: ${error.message}`);
46
+ }
47
+ };
48
+
49
+ const testProcessArray = () => {
50
+ if (!wasmReady) return;
51
+ try {
52
+ const testArray = [1, 2, 3, 4, 5];
53
+ const result = (window as any).processArray(testArray);
54
+ const resultArray = Array.from(result);
55
+ setResult(`Process array [${testArray.join(', ')}] = [${resultArray.join(', ')}]`);
56
+ } catch (error) {
57
+ setResult(`Error: ${error.message}`);
58
+ }
59
+ };
60
+
61
+ const testFormatMessage = () => {
62
+ if (!wasmReady) return;
63
+ try {
64
+ const message = 'Hello from JavaScript!';
65
+ const result = (window as any).formatMessage(message);
66
+ setResult(`Formatted: ${result}`);
67
+ } catch (error) {
68
+ setResult(`Error: ${error.message}`);
69
+ }
70
+ };
71
+
72
+ const testPerformance = () => {
73
+ if (!wasmReady) return;
74
+ try {
75
+ const iterations = 100000;
76
+ const startTime = performance.now();
77
+ const result = (window as any).performanceBenchmark(iterations);
78
+ const endTime = performance.now();
79
+
80
+ setResult(
81
+ `Performance test: ${result.message}\n` +
82
+ `Result: ${result.result}\n` +
83
+ `Time: ${(endTime - startTime).toFixed(2)}ms`
84
+ );
85
+ } catch (error) {
86
+ setResult(`Error: ${error.message}`);
87
+ }
88
+ };
89
+
90
+ const testTypeDemo = () => {
91
+ if (!wasmReady) return;
92
+ try {
93
+ const result = (window as any).typeDemo();
94
+ setResult(
95
+ `Type demo results:\n` +
96
+ `String: ${result.string}\n` +
97
+ `Number: ${result.number}\n` +
98
+ `Boolean: ${result.boolean}\n` +
99
+ `Array: [${Array.from(result.array).join(', ')}]`
100
+ );
101
+ } catch (error) {
102
+ setResult(`Error: ${error.message}`);
103
+ }
104
+ };
105
+
106
+ return jsx('div', {
107
+ className: 'wasm-demo',
108
+ children: [
109
+ jsx('h1', { children: '🚀 Frontend Hamroun + Go WASM Demo' }),
110
+
111
+ jsx('div', {
112
+ className: 'status',
113
+ children: jsx('p', {
114
+ className: wasmReady ? 'ready' : 'loading',
115
+ children: wasmReady ? '✅ WASM Ready' : '⏳ Loading WASM...'
116
+ })
117
+ }),
118
+
119
+ jsx('div', {
120
+ className: 'controls',
121
+ children: [
122
+ jsx('h2', { children: '🧮 Arithmetic Operations' }),
123
+ jsx('div', {
124
+ className: 'input-group',
125
+ children: [
126
+ jsx('input', {
127
+ type: 'number',
128
+ value: input1,
129
+ onChange: (e: any) => setInput1(e.target.value),
130
+ placeholder: 'First number'
131
+ }),
132
+ jsx('span', { children: ' + ' }),
133
+ jsx('input', {
134
+ type: 'number',
135
+ value: input2,
136
+ onChange: (e: any) => setInput2(e.target.value),
137
+ placeholder: 'Second number'
138
+ }),
139
+ jsx('button', {
140
+ onClick: testAdd,
141
+ disabled: !wasmReady,
142
+ children: 'Calculate'
143
+ })
144
+ ]
145
+ }),
146
+
147
+ jsx('h2', { children: '🔢 Fibonacci Sequence' }),
148
+ jsx('div', {
149
+ className: 'input-group',
150
+ children: [
151
+ jsx('input', {
152
+ type: 'number',
153
+ value: fibInput,
154
+ onChange: (e: any) => setFibInput(e.target.value),
155
+ placeholder: 'Fibonacci number'
156
+ }),
157
+ jsx('button', {
158
+ onClick: testFibonacci,
159
+ disabled: !wasmReady,
160
+ children: 'Calculate Fibonacci'
161
+ })
162
+ ]
163
+ }),
164
+
165
+ jsx('h2', { children: '🔧 Advanced Functions' }),
166
+ jsx('div', {
167
+ className: 'button-group',
168
+ children: [
169
+ jsx('button', {
170
+ onClick: testProcessArray,
171
+ disabled: !wasmReady,
172
+ children: 'Process Array'
173
+ }),
174
+ jsx('button', {
175
+ onClick: testFormatMessage,
176
+ disabled: !wasmReady,
177
+ children: 'Format Message'
178
+ }),
179
+ jsx('button', {
180
+ onClick: testPerformance,
181
+ disabled: !wasmReady,
182
+ children: 'Performance Test'
183
+ }),
184
+ jsx('button', {
185
+ onClick: testTypeDemo,
186
+ disabled: !wasmReady,
187
+ children: 'Type Demo'
188
+ })
189
+ ]
190
+ })
191
+ ]
192
+ }),
193
+
194
+ jsx('div', {
195
+ className: 'result',
196
+ children: [
197
+ jsx('h3', { children: '📋 Result:' }),
198
+ jsx('pre', { children: result })
199
+ ]
200
+ })
201
+ ]
202
+ });
203
+ }
204
+
205
+ // App Component
206
+ function App() {
207
+ return jsx('div', {
208
+ className: 'app',
209
+ children: jsx(WasmDemo, {})
210
+ });
211
+ }
212
+
213
+ // Render the app
214
+ const appElement = document.getElementById('app');
215
+ if (appElement) {
216
+ render(jsx(App, {}), appElement);
217
+ }
218
+
219
+ // Import statements for hooks
220
+ import { useState, useEffect } from 'frontend-hamroun';
@@ -0,0 +1,14 @@
1
+ <!DOCTYPE html>
2
+ <html lang="en">
3
+ <head>
4
+ <meta charset="UTF-8" />
5
+ <link rel="icon" type="image/svg+xml" href="/favicon.ico" />
6
+ <meta name="viewport" content="width=device-width, initial-scale=1.0" />
7
+ <title>Baraqex WASM Template</title>
8
+ <script src="/wasm_exec.js"></script>
9
+ </head>
10
+ <body>
11
+ <div id="root"></div>
12
+ <script type="module" src="/main.tsx"></script>
13
+ </body>
14
+ </html>
@@ -0,0 +1,21 @@
1
+ import { jsx, render } from 'frontend-hamroun';
2
+ import App from './App.tsx';
3
+
4
+ // Simple render without infinite loops
5
+ function startApp() {
6
+ const appElement = jsx(App, {});
7
+ const rootElement = document.getElementById('app');
8
+
9
+ if (rootElement) {
10
+ render(appElement, rootElement);
11
+ } else {
12
+ console.error('Root element not found');
13
+ }
14
+ }
15
+
16
+ // Start when DOM is ready
17
+ if (document.readyState === 'loading') {
18
+ document.addEventListener('DOMContentLoaded', startApp);
19
+ } else {
20
+ startApp();
21
+ }
@@ -0,0 +1,5 @@
1
+ import { jsx, render } from 'frontend-hamroun';
2
+ import App from './App';
3
+
4
+ // Render the app
5
+ render(jsx(App, {}), document.getElementById('root')!);
@@ -0,0 +1,145 @@
1
+ import { createServer } from 'frontend-hamroun';
2
+ import { loadGoWasmFromFile } from 'frontend-hamroun';
3
+ import path from 'path';
4
+ import { fileURLToPath } from 'url';
5
+
6
+ const __filename = fileURLToPath(import.meta.url);
7
+ const __dirname = path.dirname(__filename);
8
+
9
+ // Create server instance
10
+ const server = createServer({
11
+ port: 3000,
12
+ staticDir: './public',
13
+ pagesDir: './src/pages',
14
+ apiDir: './src/api'
15
+ });
16
+
17
+ // Server-side WASM integration example
18
+ async function initServerWasm() {
19
+ try {
20
+ console.log('🔄 Initializing server-side Go WASM...');
21
+
22
+ const wasmPath = path.join(__dirname, '..', 'public', 'example.wasm');
23
+ const wasmInstance = await loadGoWasmFromFile(wasmPath, {
24
+ debug: true,
25
+ onLoad: (instance) => {
26
+ console.log('✅ Go WASM loaded on server side');
27
+
28
+ // Test server-side WASM functions
29
+ try {
30
+ if (instance.functions.add) {
31
+ const result = instance.functions.add(5, 3);
32
+ console.log('Server WASM test - add(5, 3):', result);
33
+ }
34
+
35
+ if (instance.functions.fibonacci) {
36
+ const fibResult = instance.functions.fibonacci(10);
37
+ console.log('Server WASM test - fibonacci(10):', fibResult);
38
+ }
39
+ } catch (error) {
40
+ console.log('Server WASM test functions not available:', error.message);
41
+ }
42
+ }
43
+ });
44
+
45
+ // Make WASM instance available to API routes
46
+ server.getExpressApp().locals.wasm = wasmInstance;
47
+
48
+ } catch (error) {
49
+ console.error('❌ Failed to initialize server-side WASM:', error);
50
+ }
51
+ }
52
+
53
+ // API route example using server-side WASM
54
+ server.getExpressApp().get('/api/wasm/compute', async (req, res) => {
55
+ try {
56
+ const { operation, a, b } = req.query;
57
+ const wasmInstance = req.app.locals.wasm;
58
+
59
+ if (!wasmInstance) {
60
+ return res.status(500).json({ error: 'WASM not initialized' });
61
+ }
62
+
63
+ let result;
64
+ switch (operation) {
65
+ case 'add':
66
+ if (wasmInstance.functions.add) {
67
+ result = wasmInstance.functions.add(Number(a), Number(b));
68
+ } else {
69
+ throw new Error('Add function not available');
70
+ }
71
+ break;
72
+ case 'fibonacci':
73
+ if (wasmInstance.functions.fibonacci) {
74
+ result = wasmInstance.functions.fibonacci(Number(a));
75
+ } else {
76
+ throw new Error('Fibonacci function not available');
77
+ }
78
+ break;
79
+ default:
80
+ throw new Error('Unknown operation');
81
+ }
82
+
83
+ res.json({
84
+ success: true,
85
+ operation,
86
+ result,
87
+ serverTime: new Date().toISOString()
88
+ });
89
+ } catch (error) {
90
+ res.status(400).json({
91
+ success: false,
92
+ error: error.message
93
+ });
94
+ }
95
+ });
96
+
97
+ // Health check endpoint
98
+ server.getExpressApp().get('/api/health', (req, res) => {
99
+ res.json({
100
+ status: 'healthy',
101
+ wasm: !!req.app.locals.wasm,
102
+ timestamp: new Date().toISOString()
103
+ });
104
+ });
105
+
106
+ // Start server
107
+ async function startServer() {
108
+ try {
109
+ // Initialize WASM first
110
+ await initServerWasm();
111
+
112
+ // Start the server
113
+ await server.start();
114
+
115
+ console.log('🚀 Server started successfully!');
116
+ console.log('📋 Available endpoints:');
117
+ console.log(' • http://localhost:3000 - Main app');
118
+ console.log(' • http://localhost:3000/api/health - Health check');
119
+ console.log(' • http://localhost:3000/api/wasm/compute - WASM compute API');
120
+ console.log('');
121
+ console.log('💡 Example API calls:');
122
+ console.log(' • /api/wasm/compute?operation=add&a=5&b=3');
123
+ console.log(' • /api/wasm/compute?operation=fibonacci&a=10');
124
+
125
+ } catch (error) {
126
+ console.error('❌ Failed to start server:', error);
127
+ process.exit(1);
128
+ }
129
+ }
130
+
131
+ // Graceful shutdown
132
+ process.on('SIGTERM', async () => {
133
+ console.log('🛑 Received SIGTERM, shutting down gracefully...');
134
+ await server.stop();
135
+ process.exit(0);
136
+ });
137
+
138
+ process.on('SIGINT', async () => {
139
+ console.log('🛑 Received SIGINT, shutting down gracefully...');
140
+ await server.stop();
141
+ process.exit(0);
142
+ });
143
+
144
+ // Start the server
145
+ startServer();
@@ -0,0 +1,119 @@
1
+ /**
2
+ * Browser-only WASM loader for the WASM template
3
+ * This is a simplified version that works in the browser without server dependencies
4
+ */
5
+
6
+ export interface WasmOptions {
7
+ debug?: boolean;
8
+ onLoad?: () => void;
9
+ }
10
+
11
+ let wasmReady = false;
12
+ let wasmError: string | null = null;
13
+
14
+ /**
15
+ * Load Go WASM module in the browser
16
+ */
17
+ export async function loadGoWasm(wasmPath: string, options: WasmOptions = {}): Promise<void> {
18
+ if (wasmReady) return;
19
+
20
+ try {
21
+ if (options.debug) {
22
+ console.log('[WASM] Loading WASM from:', wasmPath);
23
+ }
24
+
25
+ // Check if Go runtime is available
26
+ if (typeof (window as any).Go !== 'function') {
27
+ throw new Error('Go WASM runtime not found. Make sure wasm_exec.js is loaded.');
28
+ }
29
+
30
+ // Create Go instance
31
+ const go = new (window as any).Go();
32
+
33
+ if (options.debug) {
34
+ console.log('[WASM] Go runtime created, loading WASM binary...');
35
+ }
36
+
37
+ // Load WASM binary
38
+ const response = await fetch(wasmPath);
39
+ if (!response.ok) {
40
+ throw new Error(`Failed to fetch WASM file: ${response.status} ${response.statusText}`);
41
+ }
42
+
43
+ const wasmBytes = await response.arrayBuffer();
44
+ const wasmModule = await WebAssembly.instantiate(wasmBytes, go.importObject);
45
+
46
+ if (options.debug) {
47
+ console.log('[WASM] WASM module instantiated, starting Go runtime...');
48
+ }
49
+
50
+ // Start Go runtime (this runs main() function)
51
+ go.run(wasmModule.instance);
52
+
53
+ // Give Go time to initialize and register functions
54
+ await new Promise(resolve => setTimeout(resolve, 1000));
55
+
56
+ if (options.debug) {
57
+ console.log('[WASM] Scanning for Go functions...');
58
+ const goFunctions = Object.keys(window as any).filter(key =>
59
+ key.startsWith('go') && typeof (window as any)[key] === 'function'
60
+ );
61
+ console.log('[WASM] Available functions:', goFunctions);
62
+ }
63
+
64
+ wasmReady = true;
65
+ wasmError = null;
66
+
67
+ if (options.onLoad) {
68
+ options.onLoad();
69
+ }
70
+
71
+ if (options.debug) {
72
+ console.log('[WASM] Go WASM loaded successfully!');
73
+ }
74
+
75
+ } catch (error) {
76
+ wasmError = error instanceof Error ? error.message : 'Unknown WASM loading error';
77
+ console.error('[WASM] Failed to load:', error);
78
+ throw error;
79
+ }
80
+ }
81
+
82
+ /**
83
+ * Call a Go WASM function in the browser
84
+ */
85
+ export function callWasmFunction(funcName: string, ...args: any[]): any {
86
+ if (!wasmReady) {
87
+ throw new Error('WASM not ready. Call loadGoWasm() first.');
88
+ }
89
+
90
+ const func = (window as any)[funcName];
91
+ if (typeof func !== 'function') {
92
+ throw new Error(`Function ${funcName} not found. Available functions: ${getWasmFunctions().join(', ')}`);
93
+ }
94
+
95
+ return func(...args);
96
+ }
97
+
98
+ /**
99
+ * Check if WASM is ready
100
+ */
101
+ export function isWasmReady(): boolean {
102
+ return wasmReady;
103
+ }
104
+
105
+ /**
106
+ * Get all available Go WASM functions
107
+ */
108
+ export function getWasmFunctions(): string[] {
109
+ return Object.keys(window as any).filter(key =>
110
+ key.startsWith('go') && typeof (window as any)[key] === 'function'
111
+ );
112
+ }
113
+
114
+ /**
115
+ * Get WASM loading error if any
116
+ */
117
+ export function getWasmError(): string | null {
118
+ return wasmError;
119
+ }
@@ -0,0 +1,21 @@
1
+ {
2
+ "compilerOptions": {
3
+ "target": "ES2020",
4
+ "lib": ["ES2020", "DOM", "DOM.Iterable"],
5
+ "module": "ESNext",
6
+ "skipLibCheck": true,
7
+ "moduleResolution": "bundler",
8
+ "allowImportingTsExtensions": true,
9
+ "resolveJsonModule": true,
10
+ "isolatedModules": true,
11
+ "noEmit": true,
12
+ "jsx": "preserve",
13
+ "jsxImportSource": "frontend-hamroun",
14
+ "strict": true,
15
+ "noUnusedLocals": true,
16
+ "noUnusedParameters": true,
17
+ "noFallthroughCasesInSwitch": true
18
+ },
19
+ "include": ["src"],
20
+ "references": [{ "path": "./tsconfig.node.json" }]
21
+ }
@@ -0,0 +1,13 @@
1
+ {
2
+ "compilerOptions": {
3
+ "composite": true,
4
+ "skipLibCheck": true,
5
+ "module": "ESNext",
6
+ "moduleResolution": "bundler",
7
+ "allowSyntheticDefaultImports": true,
8
+ "strict": true,
9
+ "noEmit": true,
10
+ "types": ["node"]
11
+ },
12
+ "include": ["vite.config.*", "vitest.config.*", "build-wasm.js", "esbuild.config.js"]
13
+ }
@@ -0,0 +1,23 @@
1
+ {
2
+ "extends": "./tsconfig.json",
3
+ "compilerOptions": {
4
+ "module": "ESNext",
5
+ "outDir": "dist",
6
+ "noEmit": false,
7
+ "jsx": "preserve",
8
+ "moduleResolution": "bundler",
9
+ "composite": true,
10
+ "skipLibCheck": true,
11
+ "allowSyntheticDefaultImports": true,
12
+ "strict": true,
13
+ "target": "ES2020",
14
+ "lib": ["ES2020"],
15
+ "types": ["node"],
16
+ "esModuleInterop": true,
17
+ "allowImportingTsExtensions": true,
18
+ "resolveJsonModule": true,
19
+ "isolatedModules": true
20
+ },
21
+ "include": ["src/server.ts", "**/*.ts", "**/*.js"],
22
+ "exclude": ["node_modules", "dist"]
23
+ }
@@ -0,0 +1,73 @@
1
+ import { defineConfig } from 'vite';
2
+ import path from 'path';
3
+
4
+ export default defineConfig({
5
+ root: 'src',
6
+ publicDir: '../public',
7
+ build: {
8
+ outDir: '../dist',
9
+ emptyOutDir: true,
10
+ rollupOptions: {
11
+ input: {
12
+ main: path.resolve(__dirname, 'src/index.html')
13
+ }
14
+ }
15
+ },
16
+ server: {
17
+ port: 3000,
18
+ open: true
19
+ },
20
+ optimizeDeps: {
21
+ exclude: [
22
+ // Exclude Node.js-only packages from browser bundling
23
+ 'crypto',
24
+ 'mongodb',
25
+ 'mysql2',
26
+ 'pg',
27
+ 'bcryptjs',
28
+ 'jsonwebtoken',
29
+ 'cors',
30
+ 'express',
31
+ 'fs',
32
+ 'path',
33
+ 'url',
34
+ 'http',
35
+ 'https',
36
+ 'stream',
37
+ 'util',
38
+ 'events',
39
+ 'buffer',
40
+ 'assert',
41
+ 'child_process',
42
+ 'cluster',
43
+ 'dgram',
44
+ 'dns',
45
+ 'domain',
46
+ 'net',
47
+ 'os',
48
+ 'punycode',
49
+ 'querystring',
50
+ 'readline',
51
+ 'repl',
52
+ 'string_decoder',
53
+ 'sys',
54
+ 'timers',
55
+ 'tls',
56
+ 'tty',
57
+ 'vm',
58
+ 'worker_threads',
59
+ 'zlib'
60
+ ]
61
+ },
62
+ define: {
63
+ global: 'globalThis',
64
+ 'process.env': {}
65
+ },
66
+ resolve: {
67
+ alias: {
68
+ // Provide browser-compatible alternatives
69
+ buffer: 'buffer',
70
+ process: 'process/browser'
71
+ }
72
+ }
73
+ });