baraqex 1.0.44 → 1.0.46

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 (60) hide show
  1. package/README_WASM.md +472 -0
  2. package/dist/browser.js +1 -422
  3. package/dist/browser.js.map +4 -4
  4. package/dist/index.js +31 -421
  5. package/dist/index.js.map +4 -4
  6. package/dist/{server/index.js → server.js} +21 -114
  7. package/dist/server.js.map +7 -0
  8. package/package.json +48 -57
  9. package/templates/ssr-template/package-lock.json +2 -2
  10. package/templates/ssr-template/src/App.tsx +1 -1
  11. package/templates/ssr-template/src/client.tsx +1 -1
  12. package/templates/ssr-template/src/server.ts +1 -1
  13. package/templates/wasm/package-lock.json +3169 -2710
  14. package/templates/wasm/package.json +10 -12
  15. package/templates/wasm/src/App.tsx +50 -19
  16. package/templates/wasm/vite.config.ts +24 -59
  17. package/dist/api/hello.d.ts +0 -3
  18. package/dist/api/hello.d.ts.map +0 -1
  19. package/dist/api/users/[id].d.ts +0 -5
  20. package/dist/api/users/[id].d.ts.map +0 -1
  21. package/dist/browser.d.ts +0 -29
  22. package/dist/browser.d.ts.map +0 -1
  23. package/dist/browser.package.json +0 -4
  24. package/dist/frontend/components/WasmLoader.d.ts +0 -2
  25. package/dist/frontend/components/WasmLoader.d.ts.map +0 -1
  26. package/dist/frontend/hooks/useWasm.d.ts +0 -2
  27. package/dist/frontend/hooks/useWasm.d.ts.map +0 -1
  28. package/dist/frontend/index.d.ts +0 -2
  29. package/dist/frontend/index.d.ts.map +0 -1
  30. package/dist/index.d.ts +0 -34
  31. package/dist/index.d.ts.map +0 -1
  32. package/dist/renderComponent.d.ts +0 -9
  33. package/dist/renderComponent.d.ts.map +0 -1
  34. package/dist/server/api-router.d.ts +0 -16
  35. package/dist/server/api-router.d.ts.map +0 -1
  36. package/dist/server/auth.d.ts +0 -25
  37. package/dist/server/auth.d.ts.map +0 -1
  38. package/dist/server/database.d.ts +0 -22
  39. package/dist/server/database.d.ts.map +0 -1
  40. package/dist/server/index.d.ts +0 -115
  41. package/dist/server/index.d.ts.map +0 -1
  42. package/dist/server/index.js.map +0 -7
  43. package/dist/server/middleware.d.ts +0 -11
  44. package/dist/server/middleware.d.ts.map +0 -1
  45. package/dist/server/package.json +0 -4
  46. package/dist/server/templates.d.ts +0 -31
  47. package/dist/server/templates.d.ts.map +0 -1
  48. package/dist/server/types.d.ts +0 -69
  49. package/dist/server/types.d.ts.map +0 -1
  50. package/dist/server/utils.d.ts +0 -70
  51. package/dist/server/utils.d.ts.map +0 -1
  52. package/dist/server/wasm.d.ts +0 -29
  53. package/dist/server/wasm.d.ts.map +0 -1
  54. package/dist/server-renderer.d.ts +0 -5
  55. package/dist/server-renderer.d.ts.map +0 -1
  56. package/dist/wasm.d.ts +0 -51
  57. package/dist/wasm.d.ts.map +0 -1
  58. package/templates/wasm/src/index.html +0 -14
  59. package/templates/wasm/src/main.tsx +0 -5
  60. package/templates/wasm/src/wasm-loader.ts +0 -119
package/README_WASM.md ADDED
@@ -0,0 +1,472 @@
1
+ # WebAssembly (WASM) Integration Guide
2
+
3
+ Baraqex provides seamless integration with Go-compiled WebAssembly modules, allowing you to run high-performance Go code both on the server (Node.js) and in the browser.
4
+
5
+ ## Table of Contents
6
+
7
+ - [Overview](#overview)
8
+ - [Server-side WASM Usage](#server-side-wasm-usage)
9
+ - [Client-side WASM Usage](#client-side-wasm-usage)
10
+ - [Creating Go WASM Modules](#creating-go-wasm-modules)
11
+ - [API Reference](#api-reference)
12
+ - [Best Practices](#best-practices)
13
+ - [Troubleshooting](#troubleshooting)
14
+
15
+ ## Overview
16
+
17
+ The WASM integration in Baraqex supports:
18
+ - Loading and executing Go WASM modules
19
+ - Automatic JavaScript-Go interop
20
+ - Memory management and error handling
21
+ - Both server-side (Node.js) and client-side (browser) execution
22
+ - Debug mode for development
23
+
24
+ ## Server-side WASM Usage
25
+
26
+ ### Basic Setup
27
+
28
+ ```typescript
29
+ import { loadGoWasmFromFile, initNodeWasm } from 'baraqex/server';
30
+
31
+ // Initialize the Node.js WASM environment (optional, called automatically)
32
+ await initNodeWasm();
33
+
34
+ // Load a Go WASM module
35
+ const wasmInstance = await loadGoWasmFromFile('./path/to/your/module.wasm');
36
+
37
+ // Call exported Go functions
38
+ const result = wasmInstance.functions.myGoFunction('hello', 42);
39
+ console.log('Result from Go:', result);
40
+ ```
41
+
42
+ ### Advanced Configuration
43
+
44
+ ```typescript
45
+ import { loadGoWasmFromFile } from 'baraqex/server';
46
+
47
+ const wasmInstance = await loadGoWasmFromFile('./module.wasm', {
48
+ // Enable debug logging
49
+ debug: true,
50
+
51
+ // Provide custom import objects
52
+ importObject: {
53
+ env: {
54
+ customFunction: (value: number) => {
55
+ console.log('Called from Go with:', value);
56
+ return value * 2;
57
+ }
58
+ }
59
+ },
60
+
61
+ // Callback when module is loaded
62
+ onLoad: (instance) => {
63
+ console.log('WASM module loaded successfully');
64
+ console.log('Available functions:', Object.keys(instance.functions));
65
+ }
66
+ });
67
+ ```
68
+
69
+ ### Using in Express Routes
70
+
71
+ ```typescript
72
+ import { createServer } from 'baraqex/server';
73
+ import { loadGoWasmFromFile } from 'baraqex/server';
74
+
75
+ const server = createServer();
76
+ let wasmModule: any;
77
+
78
+ // Load WASM module during server startup
79
+ server.start().then(async () => {
80
+ wasmModule = await loadGoWasmFromFile('./crypto.wasm');
81
+ });
82
+
83
+ // Use WASM in API routes
84
+ server.getExpressApp().post('/api/hash', (req, res) => {
85
+ try {
86
+ const { data } = req.body;
87
+ const hash = wasmModule.functions.hashData(data);
88
+ res.json({ hash });
89
+ } catch (error) {
90
+ res.status(500).json({ error: 'WASM execution failed' });
91
+ }
92
+ });
93
+ ```
94
+
95
+ ## Client-side WASM Usage
96
+
97
+ ### Basic Browser Usage
98
+
99
+ ```typescript
100
+ import { loadGoWasm } from 'baraqex';
101
+
102
+ // Load WASM module in the browser
103
+ const wasmInstance = await loadGoWasm('./module.wasm');
104
+
105
+ // Call Go functions
106
+ const result = wasmInstance.functions.processData(inputData);
107
+ ```
108
+
109
+ ### React Component Example
110
+
111
+ ```tsx
112
+ import React, { useEffect, useState } from 'react';
113
+ import { loadGoWasm } from 'baraqex';
114
+
115
+ export function WasmComponent() {
116
+ const [wasmModule, setWasmModule] = useState<any>(null);
117
+ const [result, setResult] = useState<string>('');
118
+
119
+ useEffect(() => {
120
+ loadGoWasm('./math.wasm', { debug: true })
121
+ .then(setWasmModule)
122
+ .catch(console.error);
123
+ }, []);
124
+
125
+ const handleCalculate = () => {
126
+ if (wasmModule) {
127
+ const output = wasmModule.functions.fibonacci(10);
128
+ setResult(`Fibonacci(10) = ${output}`);
129
+ }
130
+ };
131
+
132
+ return (
133
+ <div>
134
+ <button onClick={handleCalculate} disabled={!wasmModule}>
135
+ Calculate Fibonacci
136
+ </button>
137
+ <p>{result}</p>
138
+ </div>
139
+ );
140
+ }
141
+ ```
142
+
143
+ ## Creating Go WASM Modules
144
+
145
+ ### Basic Go Module Structure
146
+
147
+ ```go
148
+ // main.go
149
+ package main
150
+
151
+ import (
152
+ "syscall/js"
153
+ "strconv"
154
+ )
155
+
156
+ // Export a function to JavaScript
157
+ func fibonacci(this js.Value, args []js.Value) interface{} {
158
+ n := args[0].Int()
159
+ return fibonacciCalc(n)
160
+ }
161
+
162
+ func fibonacciCalc(n int) int {
163
+ if n <= 1 {
164
+ return n
165
+ }
166
+ return fibonacciCalc(n-1) + fibonacciCalc(n-2)
167
+ }
168
+
169
+ // Export a string processing function
170
+ func processString(this js.Value, args []js.Value) interface{} {
171
+ input := args[0].String()
172
+ return "Processed: " + input
173
+ }
174
+
175
+ func main() {
176
+ // Keep the program running
177
+ c := make(chan struct{}, 0)
178
+
179
+ // Register functions
180
+ js.Global().Set("fibonacci", js.FuncOf(fibonacci))
181
+ js.Global().Set("processString", js.FuncOf(processString))
182
+
183
+ println("Go WASM module initialized")
184
+ <-c
185
+ }
186
+ ```
187
+
188
+ ### Compiling to WASM
189
+
190
+ ```bash
191
+ # Set environment for WASM compilation
192
+ export GOOS=js
193
+ export GOARCH=wasm
194
+
195
+ # Compile to WASM
196
+ go build -o module.wasm main.go
197
+
198
+ # Copy the WASM support file (if needed for browser)
199
+ cp "$(go env GOROOT)/misc/wasm/wasm_exec.js" .
200
+ ```
201
+
202
+ ### Advanced Go Example with Error Handling
203
+
204
+ ```go
205
+ package main
206
+
207
+ import (
208
+ "encoding/json"
209
+ "syscall/js"
210
+ )
211
+
212
+ type ProcessRequest struct {
213
+ Data string `json:"data"`
214
+ Method string `json:"method"`
215
+ }
216
+
217
+ type ProcessResponse struct {
218
+ Result string `json:"result"`
219
+ Error string `json:"error,omitempty"`
220
+ }
221
+
222
+ func processJSON(this js.Value, args []js.Value) interface{} {
223
+ defer func() {
224
+ if r := recover(); r != nil {
225
+ // Return error object
226
+ errorResponse := ProcessResponse{
227
+ Error: "Internal error occurred",
228
+ }
229
+ jsonBytes, _ := json.Marshal(errorResponse)
230
+ return string(jsonBytes)
231
+ }
232
+ }()
233
+
234
+ inputJSON := args[0].String()
235
+
236
+ var request ProcessRequest
237
+ if err := json.Unmarshal([]byte(inputJSON), &request); err != nil {
238
+ response := ProcessResponse{
239
+ Error: "Invalid JSON input",
240
+ }
241
+ jsonBytes, _ := json.Marshal(response)
242
+ return string(jsonBytes)
243
+ }
244
+
245
+ // Process the data based on method
246
+ var result string
247
+ switch request.Method {
248
+ case "uppercase":
249
+ result = strings.ToUpper(request.Data)
250
+ case "lowercase":
251
+ result = strings.ToLower(request.Data)
252
+ default:
253
+ response := ProcessResponse{
254
+ Error: "Unknown method: " + request.Method,
255
+ }
256
+ jsonBytes, _ := json.Marshal(response)
257
+ return string(jsonBytes)
258
+ }
259
+
260
+ response := ProcessResponse{
261
+ Result: result,
262
+ }
263
+ jsonBytes, _ := json.Marshal(response)
264
+ return string(jsonBytes)
265
+ }
266
+
267
+ func main() {
268
+ c := make(chan struct{}, 0)
269
+ js.Global().Set("processJSON", js.FuncOf(processJSON))
270
+ <-c
271
+ }
272
+ ```
273
+
274
+ ## API Reference
275
+
276
+ ### Server-side Functions
277
+
278
+ #### `initNodeWasm(): Promise<void>`
279
+ Initializes the Node.js environment for WASM execution. Called automatically by `loadGoWasmFromFile`.
280
+
281
+ #### `loadGoWasmFromFile(path: string, options?: GoWasmOptions): Promise<GoWasmInstance>`
282
+ Loads a WASM module from a file path.
283
+
284
+ **Parameters:**
285
+ - `path`: File path to the WASM module
286
+ - `options`: Configuration options
287
+
288
+ **Options:**
289
+ ```typescript
290
+ interface GoWasmOptions {
291
+ debug?: boolean; // Enable debug logging
292
+ importObject?: any; // Custom import objects
293
+ onLoad?: (instance: GoWasmInstance) => void; // Load callback
294
+ }
295
+ ```
296
+
297
+ **Returns:**
298
+ ```typescript
299
+ interface GoWasmInstance {
300
+ instance: WebAssembly.Instance; // Raw WASM instance
301
+ module: WebAssembly.Module; // Compiled WASM module
302
+ exports: any; // Direct exports
303
+ functions: Record<string, Function>; // Wrapped Go functions
304
+ }
305
+ ```
306
+
307
+ ### Client-side Functions
308
+
309
+ #### `loadGoWasm(url: string, options?: GoWasmOptions): Promise<GoWasmInstance>`
310
+ Loads a WASM module from a URL in the browser.
311
+
312
+ ### Error Handling
313
+
314
+ ```typescript
315
+ try {
316
+ const wasmInstance = await loadGoWasmFromFile('./module.wasm');
317
+ const result = wasmInstance.functions.myFunction(data);
318
+ } catch (error) {
319
+ if (error.message.includes('WASM')) {
320
+ console.error('WASM-specific error:', error);
321
+ } else {
322
+ console.error('General error:', error);
323
+ }
324
+ }
325
+ ```
326
+
327
+ ## Best Practices
328
+
329
+ ### 1. Error Handling in Go
330
+ Always handle panics and return meaningful error messages:
331
+
332
+ ```go
333
+ func safeFunction(this js.Value, args []js.Value) interface{} {
334
+ defer func() {
335
+ if r := recover(); r != nil {
336
+ return map[string]interface{}{
337
+ "error": "Function panicked",
338
+ "details": fmt.Sprintf("%v", r),
339
+ }
340
+ }
341
+ }()
342
+
343
+ // Your function logic here
344
+ return map[string]interface{}{
345
+ "success": true,
346
+ "result": "your result",
347
+ }
348
+ }
349
+ ```
350
+
351
+ ### 2. Memory Management
352
+ Be mindful of memory usage in long-running WASM modules:
353
+
354
+ ```go
355
+ // Release references when done
356
+ func cleanup() {
357
+ // Clear large data structures
358
+ largeSlice = nil
359
+ // Force garbage collection if needed
360
+ runtime.GC()
361
+ }
362
+ ```
363
+
364
+ ### 3. Async Operations
365
+ Use proper async patterns in JavaScript:
366
+
367
+ ```typescript
368
+ // Good: Use async/await
369
+ const result = await wasmInstance.functions.asyncOperation(data);
370
+
371
+ // Or: Use Promises
372
+ wasmInstance.functions.asyncOperation(data)
373
+ .then(result => {
374
+ console.log('Success:', result);
375
+ })
376
+ .catch(error => {
377
+ console.error('Error:', error);
378
+ });
379
+ ```
380
+
381
+ ### 4. Development vs Production
382
+ Use debug mode during development:
383
+
384
+ ```typescript
385
+ const debugMode = process.env.NODE_ENV !== 'production';
386
+ const wasmInstance = await loadGoWasmFromFile('./module.wasm', {
387
+ debug: debugMode
388
+ });
389
+ ```
390
+
391
+ ## Troubleshooting
392
+
393
+ ### Common Issues
394
+
395
+ 1. **Module not found**
396
+ ```
397
+ Error: ENOENT: no such file or directory
398
+ ```
399
+ - Ensure the WASM file path is correct
400
+ - Check file permissions
401
+
402
+ 2. **WASM compilation failed**
403
+ ```
404
+ Error: WebAssembly.compile failed
405
+ ```
406
+ - Verify the WASM file is valid
407
+ - Check Go compilation errors
408
+
409
+ 3. **Function not found**
410
+ ```
411
+ TypeError: wasmInstance.functions.myFunction is not a function
412
+ ```
413
+ - Ensure the function is exported in Go using `js.Global().Set()`
414
+ - Check function name spelling
415
+
416
+ 4. **Memory errors**
417
+ ```
418
+ Error: invalid array length
419
+ ```
420
+ - Check bounds in Go code
421
+ - Ensure proper memory allocation
422
+
423
+ ### Debug Tips
424
+
425
+ 1. **Enable debug mode:**
426
+ ```typescript
427
+ const wasmInstance = await loadGoWasmFromFile('./module.wasm', {
428
+ debug: true
429
+ });
430
+ ```
431
+
432
+ 2. **Check available functions:**
433
+ ```typescript
434
+ console.log('Available functions:', Object.keys(wasmInstance.functions));
435
+ ```
436
+
437
+ 3. **Monitor memory usage:**
438
+ ```typescript
439
+ // Server-side
440
+ console.log('Memory usage:', process.memoryUsage());
441
+
442
+ // Browser
443
+ console.log('Memory info:', performance.memory);
444
+ ```
445
+
446
+ ### Node.js Version Compatibility
447
+
448
+ - **Node.js >= 16**: Full support
449
+ - **Node.js 14-15**: May require `--experimental-wasm-bigint` flag
450
+ - **Node.js < 14**: Not supported
451
+
452
+ ### Browser Compatibility
453
+
454
+ - **Chrome/Edge >= 69**: Full support
455
+ - **Firefox >= 63**: Full support
456
+ - **Safari >= 14**: Full support
457
+ - **IE**: Not supported
458
+
459
+ ## Examples
460
+
461
+ Check the `examples/` directory for complete working examples:
462
+
463
+ - `examples/wasm-server/` - Server-side WASM usage
464
+ - `examples/wasm-browser/` - Browser WASM integration
465
+ - `examples/go-modules/` - Sample Go WASM modules
466
+
467
+ ## Support
468
+
469
+ For issues and questions:
470
+ - Check the troubleshooting section above
471
+ - Review the test files in `tests/server/wasm.test.ts`
472
+ - Open an issue on the GitHub repository