baraqex 1.0.63 → 1.0.65

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 (98) hide show
  1. package/bin/baraqex.js +1013 -1126
  2. package/dist/api/hello.d.ts +3 -0
  3. package/dist/api/hello.d.ts.map +1 -0
  4. package/dist/api/users/[id].d.ts +5 -0
  5. package/dist/api/users/[id].d.ts.map +1 -0
  6. package/dist/browser.d.ts +40 -0
  7. package/dist/browser.d.ts.map +1 -0
  8. package/dist/browser.js +407 -1
  9. package/dist/browser.js.map +4 -4
  10. package/dist/browser.package.json +4 -0
  11. package/dist/forms/index.d.ts +2 -0
  12. package/dist/forms/index.d.ts.map +1 -0
  13. package/dist/forms/types.d.ts +2 -0
  14. package/dist/forms/types.d.ts.map +1 -0
  15. package/dist/frontend/components/WasmLoader.d.ts +2 -0
  16. package/dist/frontend/components/WasmLoader.d.ts.map +1 -0
  17. package/dist/frontend/hooks/useWasm.d.ts +2 -0
  18. package/dist/frontend/hooks/useWasm.d.ts.map +1 -0
  19. package/dist/frontend/index.d.ts +2 -0
  20. package/dist/frontend/index.d.ts.map +1 -0
  21. package/dist/index.d.ts +38 -0
  22. package/dist/index.d.ts.map +1 -0
  23. package/dist/index.js +678 -317
  24. package/dist/index.js.map +4 -4
  25. package/dist/renderComponent.d.ts +9 -0
  26. package/dist/renderComponent.d.ts.map +1 -0
  27. package/dist/router/index.d.ts +2 -0
  28. package/dist/router/index.d.ts.map +1 -0
  29. package/dist/router/types.d.ts +2 -0
  30. package/dist/router/types.d.ts.map +1 -0
  31. package/dist/server/api-router.d.ts +16 -0
  32. package/dist/server/api-router.d.ts.map +1 -0
  33. package/dist/server/auth.d.ts +25 -0
  34. package/dist/server/auth.d.ts.map +1 -0
  35. package/dist/server/database.d.ts +22 -0
  36. package/dist/server/database.d.ts.map +1 -0
  37. package/dist/server/index.d.ts +116 -0
  38. package/dist/server/index.d.ts.map +1 -0
  39. package/dist/{server.js → server/index.js} +120 -23
  40. package/dist/server/index.js.map +7 -0
  41. package/dist/server/middleware.d.ts +11 -0
  42. package/dist/server/middleware.d.ts.map +1 -0
  43. package/dist/server/package.json +4 -0
  44. package/dist/server/templates.d.ts +31 -0
  45. package/dist/server/templates.d.ts.map +1 -0
  46. package/dist/server/types.d.ts +69 -0
  47. package/dist/server/types.d.ts.map +1 -0
  48. package/dist/server/utils.d.ts +70 -0
  49. package/dist/server/utils.d.ts.map +1 -0
  50. package/dist/server/wasm.d.ts +29 -0
  51. package/dist/server/wasm.d.ts.map +1 -0
  52. package/dist/server-renderer.d.ts +5 -0
  53. package/dist/server-renderer.d.ts.map +1 -0
  54. package/dist/store/index.d.ts +2 -0
  55. package/dist/store/index.d.ts.map +1 -0
  56. package/dist/store/types.d.ts +2 -0
  57. package/dist/store/types.d.ts.map +1 -0
  58. package/dist/wasm.d.ts +51 -0
  59. package/dist/wasm.d.ts.map +1 -0
  60. package/package.json +65 -56
  61. package/templates/basic-app/src/main.tsx +1 -0
  62. package/templates/fullstack-template/.env.example +42 -0
  63. package/templates/fullstack-template/README.md +38 -42
  64. package/templates/fullstack-template/package-lock.json +7932 -0
  65. package/templates/fullstack-template/package.json +58 -6
  66. package/templates/fullstack-template/server.js +28 -9
  67. package/templates/fullstack-template/src/App.tsx +94 -0
  68. package/templates/fullstack-template/src/api/auth/login.ts +75 -0
  69. package/templates/fullstack-template/src/api/auth/me.ts +66 -0
  70. package/templates/fullstack-template/src/api/auth/register.ts +59 -0
  71. package/templates/fullstack-template/src/api/todos/[id].ts +108 -0
  72. package/templates/fullstack-template/src/api/todos/index.ts +79 -0
  73. package/templates/fullstack-template/src/components/Dashboard.tsx +129 -0
  74. package/templates/fullstack-template/src/components/Header.tsx +76 -0
  75. package/templates/fullstack-template/src/contexts/ApiContext.tsx +69 -0
  76. package/templates/fullstack-template/src/contexts/AuthContext.tsx +155 -0
  77. package/templates/fullstack-template/src/server.ts +167 -0
  78. package/templates/fullstack-template/src/styles/App.css +446 -0
  79. package/templates/ssr-template/package-lock.json +38 -60
  80. package/templates/ssr-template/package.json +1 -1
  81. package/templates/ssr-template/src/App.tsx +4 -3
  82. package/templates/ssr-template/src/client.tsx +2 -1
  83. package/templates/wasm/App.tsx +564 -0
  84. package/templates/wasm/client.tsx +220 -0
  85. package/templates/wasm/index.tsx +21 -0
  86. package/templates/wasm/package-lock.json +5347 -5307
  87. package/templates/wasm/package.json +43 -25
  88. package/templates/wasm/public/example.wasm +0 -0
  89. package/templates/wasm/public/wasm_exec.js +1 -12
  90. package/templates/wasm/server.ts +145 -0
  91. package/templates/wasm/vite.config.ts +42 -24
  92. package/README_WASM.md +0 -472
  93. package/dist/server.js.map +0 -7
  94. package/templates/basic-app/src/App.jsx +0 -0
  95. package/templates/basic-app/src/App.tsx +0 -0
  96. package/templates/fullstack-template/src/api/hello.js +0 -17
  97. package/templates/fullstack-template/src/pages/index.js +0 -206
  98. /package/templates/{basic-app/server.js → wasm/go/wasm_exec.js} +0 -0
package/README_WASM.md DELETED
@@ -1,472 +0,0 @@
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
@@ -1,7 +0,0 @@
1
- {
2
- "version": 3,
3
- "sources": ["../src/server/index.ts", "../src/server/database.ts", "../src/server/auth.ts", "../src/server/api-router.ts", "../src/server/middleware.ts", "../src/server/utils.ts", "../src/server/templates.ts", "../src/server/wasm.ts"],
4
- "sourcesContent": ["import path from 'path';\r\nimport http from 'http';\r\nimport fs from 'fs';\r\nimport { renderToString } from 'frontend-hamroun';\r\nimport { Database } from './database.js';\r\nimport { AuthService } from './auth.js';\r\nimport { ApiRouter } from './api-router.js';\r\nimport { requestLogger, errorHandler, notFoundHandler, rateLimit } from './middleware.js';\r\n\r\n// Import the utility functions\r\nimport * as utils from './utils.js';\r\nimport * as templates from './templates.js';\r\nimport { initNodeWasm, loadGoWasmFromFile } from './wasm.js';\r\n\r\n// Helper function to get the component name from the file path\r\nfunction getComponentName(filePath: string, pagesDir: string): string {\r\n try {\r\n // Get relative path from pages directory\r\n const relativePath = path.relative(pagesDir, filePath);\r\n // Remove extension\r\n const withoutExt = relativePath.replace(/\\.[^/.]+$/, '');\r\n // Replace index with empty for clean paths\r\n const cleanPath = withoutExt.replace(/\\/index$/, '');\r\n // Convert to module path format\r\n return `/pages/${cleanPath}`;\r\n } catch (e) {\r\n return '';\r\n }\r\n}\r\n\r\nexport interface ServerConfig {\r\n port?: number;\r\n apiDir?: string;\r\n pagesDir?: string;\r\n staticDir?: string;\r\n enableCors?: boolean;\r\n corsOptions?: any;\r\n db?: {\r\n url: string;\r\n type: 'mongodb' | 'mysql' | 'postgres';\r\n };\r\n auth?: {\r\n secret: string;\r\n expiresIn?: string | number;\r\n };\r\n}\r\n\r\nexport class Server {\r\n private app: any;\r\n private server: http.Server | null = null;\r\n private config: ServerConfig;\r\n private db: Database | null = null;\r\n private auth: AuthService | null = null;\r\n\r\n constructor(config: ServerConfig = {}) {\r\n this.config = {\r\n port: 3000,\r\n apiDir: './api',\r\n pagesDir: './pages',\r\n staticDir: './public',\r\n enableCors: true,\r\n ...config\r\n };\r\n\r\n this.initializeApp();\r\n }\r\n\r\n private async initializeApp() {\r\n try {\r\n // Dynamic import of express to handle missing dependency\r\n const express = await import('express');\r\n this.app = express.default();\r\n \r\n // Basic middleware\r\n this.app.use(express.default.json());\r\n this.app.use(express.default.urlencoded({ extended: true }));\r\n \r\n // CORS setup\r\n if (this.config.enableCors) {\r\n try {\r\n const cors = await import('cors');\r\n this.app.use(cors.default(this.config.corsOptions));\r\n } catch (error) {\r\n console.warn('CORS not available - install with: npm install cors @types/cors');\r\n }\r\n }\r\n \r\n // Setup database if configured\r\n if (this.config.db) {\r\n this.db = new Database(this.config.db);\r\n }\r\n \r\n // Setup auth if configured\r\n if (this.config.auth) {\r\n this.auth = new AuthService({\r\n secret: this.config.auth.secret,\r\n expiresIn: this.config.auth.expiresIn\r\n });\r\n this.app.use(this.auth.initialize());\r\n }\r\n \r\n // Static files - setup before other routes\r\n const staticPath = path.resolve(process.cwd(), this.config.staticDir!);\r\n if (fs.existsSync(staticPath)) {\r\n this.app.use(express.default.static(staticPath));\r\n }\r\n \r\n // Setup API routes\r\n this.setupApiRoutes();\r\n \r\n // Setup page routes (for SSR)\r\n this.setupPageRoutes();\r\n \r\n // Add error handlers at the end\r\n this.app.use(notFoundHandler);\r\n this.app.use(errorHandler);\r\n \r\n } catch (error: any) {\r\n if (error.code === 'MODULE_NOT_FOUND' && error.message.includes('express')) {\r\n throw new Error('Express not installed. Run: npm install express @types/express');\r\n }\r\n throw error;\r\n }\r\n }\r\n\r\n private setupApiRoutes() {\r\n const apiRouter = new ApiRouter(this.config.apiDir!, this.auth);\r\n this.app.use('/api', requestLogger, apiRouter.router);\r\n \r\n // Add API documentation route\r\n this.app.get('/api-docs', (req: any, res: any) => {\r\n const apiDocs = this.generateApiDocs();\r\n res.json(apiDocs);\r\n });\r\n }\r\n\r\n private generateApiDocs() {\r\n // Generate documentation based on API routes\r\n const apiDir = path.resolve(process.cwd(), this.config.apiDir!);\r\n const docs = { endpoints: [] as any[] };\r\n \r\n if (fs.existsSync(apiDir)) {\r\n this.scanApiDirectory(apiDir, '', docs.endpoints);\r\n }\r\n \r\n return docs;\r\n }\r\n \r\n private scanApiDirectory(dirPath: string, routePrefix: string, endpoints: any[]) {\r\n const entries = fs.readdirSync(dirPath, { withFileTypes: true });\r\n \r\n for (const entry of entries) {\r\n const fullPath = path.join(dirPath, entry.name);\r\n \r\n if (entry.isDirectory()) {\r\n this.scanApiDirectory(fullPath, `${routePrefix}/${entry.name}`, endpoints);\r\n } else if (entry.name.endsWith('.js') || entry.name.endsWith('.ts')) {\r\n const routePath = this.getRoutePath(entry.name, routePrefix);\r\n endpoints.push({\r\n path: routePath,\r\n file: path.relative(process.cwd(), fullPath),\r\n methods: this.detectApiMethods(fullPath)\r\n });\r\n }\r\n }\r\n }\r\n \r\n private getRoutePath(filename: string, routePrefix: string): string {\r\n const baseName = path.basename(filename, path.extname(filename));\r\n \r\n if (baseName === 'index') {\r\n return routePrefix || '/';\r\n }\r\n \r\n const paramMatch = baseName.match(/^\\[(.+)\\]$/);\r\n if (paramMatch) {\r\n return `${routePrefix}/:${paramMatch[1]}`;\r\n }\r\n \r\n return `${routePrefix}/${baseName}`;\r\n }\r\n \r\n private detectApiMethods(filePath: string): string[] {\r\n try {\r\n const content = fs.readFileSync(filePath, 'utf8');\r\n const methods = ['get', 'post', 'put', 'delete', 'patch', 'options'];\r\n return methods.filter(method => \r\n new RegExp(`export (async )?function ${method}\\\\s*\\\\(`).test(content) ||\r\n new RegExp(`export const ${method}\\\\s*=`).test(content)\r\n );\r\n } catch (error) {\r\n return [];\r\n }\r\n }\r\n\r\n private setupPageRoutes() {\r\n const pagesPath = path.resolve(process.cwd(), this.config.pagesDir!);\r\n if (!fs.existsSync(pagesPath)) {\r\n return;\r\n }\r\n\r\n // Setup catch-all route for SSR - but only if pages directory exists\r\n this.app.get('*', async (req: { path: string; }, res: { status: (arg0: number) => { (): any; new(): any; send: { (arg0: string): void; new(): any; }; }; }) => {\r\n try {\r\n const { html, statusCode } = await this.renderPage(req.path);\r\n res.status(statusCode || 200).send(html);\r\n } catch (error) {\r\n console.error('Error rendering page:', error);\r\n const errorHtml = templates.generateErrorPage(500, 'Server Error');\r\n res.status(500).send(errorHtml);\r\n }\r\n });\r\n }\r\n\r\n private async renderPage(routePath: string): Promise<{ html: string, statusCode?: number }> {\r\n try {\r\n // Try to find the page component\r\n const pagesDir = this.config.pagesDir ? path.resolve(process.cwd(), this.config.pagesDir) : '';\r\n if (!pagesDir || !fs.existsSync(pagesDir)) {\r\n return { \r\n html: templates.generateErrorPage(404, 'Pages directory not found'), \r\n statusCode: 404 \r\n };\r\n }\r\n \r\n // Normalize the path\r\n let normalizedPath = routePath;\r\n if (!normalizedPath.startsWith('/')) {\r\n normalizedPath = '/' + normalizedPath;\r\n }\r\n \r\n // Default to index for the root\r\n if (normalizedPath === '/') {\r\n normalizedPath = '/index';\r\n }\r\n \r\n // Try to find a matching page file\r\n let pagePath = '';\r\n const possiblePaths = [\r\n path.join(pagesDir, `${normalizedPath}.js`),\r\n path.join(pagesDir, `${normalizedPath}.ts`),\r\n path.join(pagesDir, `${normalizedPath}.jsx`),\r\n path.join(pagesDir, `${normalizedPath}.tsx`),\r\n path.join(pagesDir, `${normalizedPath}/index.js`),\r\n path.join(pagesDir, `${normalizedPath}/index.ts`),\r\n path.join(pagesDir, `${normalizedPath}/index.jsx`),\r\n path.join(pagesDir, `${normalizedPath}/index.tsx`)\r\n ];\r\n \r\n for (const p of possiblePaths) {\r\n if (fs.existsSync(p)) {\r\n pagePath = p;\r\n break;\r\n }\r\n }\r\n \r\n // Handle 404 if page not found\r\n if (!pagePath) {\r\n return { \r\n html: templates.generateErrorPage(404, `Page not found: ${normalizedPath}`), \r\n statusCode: 404 \r\n };\r\n }\r\n \r\n // Import and render the page component\r\n try {\r\n const pageModule = await import(pagePath);\r\n if (!pageModule || !pageModule.default) {\r\n throw new Error(`No default export found in ${pagePath}`);\r\n }\r\n \r\n const PageComponent = pageModule.default;\r\n const initialProps = {\r\n // Provide any initial props here\r\n path: normalizedPath,\r\n query: {}, // Could be parsed from URL\r\n api: { serverTime: new Date().toISOString() }\r\n };\r\n \r\n // Use the fixed renderComponent function\r\n const renderResult = await renderComponent(PageComponent, initialProps);\r\n \r\n if (!renderResult.success) {\r\n return { \r\n html: templates.generateErrorPage(500, 'Failed to render page', renderResult.error instanceof Error ? renderResult.error : new Error('Unknown error')), \r\n statusCode: 500 \r\n };\r\n }\r\n \r\n // Get the HTML string from the render result\r\n const htmlContent = renderResult.html;\r\n \r\n // Generate the full HTML document\r\n let pageTitle = 'My App';\r\n try {\r\n // Try to extract title from component if it has a getTitle method\r\n if (typeof PageComponent.getTitle === 'function') {\r\n pageTitle = PageComponent.getTitle(initialProps);\r\n } else if (PageComponent.title) {\r\n pageTitle = PageComponent.title;\r\n }\r\n } catch (e) {\r\n // Ignore title errors\r\n }\r\n \r\n // Parse the component name for hydration\r\n const componentName = getComponentName(pagePath, pagesDir);\r\n \r\n // Generate full HTML document with our template\r\n const fullHtml = templates.generateDocument(htmlContent, {\r\n title: pageTitle,\r\n // Get description from component if available\r\n description: typeof PageComponent.getDescription === 'function' \r\n ? PageComponent.getDescription(initialProps) \r\n : (PageComponent.description || ''),\r\n // Add scripts for client-side hydration\r\n scripts: ['/client.js'],\r\n // Add any custom meta tags\r\n meta: typeof PageComponent.getMeta === 'function'\r\n ? PageComponent.getMeta(initialProps)\r\n : {},\r\n // Add custom styles\r\n styles: ['/styles.css'],\r\n // Add initial data for client-side hydration\r\n initialData: initialProps,\r\n // Add component information for hydration\r\n componentName: componentName\r\n });\r\n \r\n return { html: fullHtml, statusCode: 200 };\r\n \r\n } catch (error) {\r\n console.error('Error rendering page:', error);\r\n return { \r\n html: templates.generateErrorPage(500, 'Error rendering page', error instanceof Error ? error : new Error('Unknown error')), \r\n statusCode: 500 \r\n };\r\n }\r\n } catch (error) {\r\n console.error('Error finding page:', error);\r\n return { \r\n html: templates.generateErrorPage(500, 'Server error', error instanceof Error ? error : new Error('Unknown error')), \r\n statusCode: 500 \r\n };\r\n }\r\n }\r\n\r\n public getExpressApp(): any {\r\n return this.app;\r\n }\r\n\r\n public getDatabase(): Database | null {\r\n return this.db;\r\n }\r\n\r\n public getAuth(): AuthService | null {\r\n return this.auth;\r\n }\r\n\r\n public start(): Promise<void> {\r\n return new Promise((resolve) => {\r\n this.server = this.app.listen(this.config.port, () => {\r\n console.log(`Server running at http://localhost:${this.config.port}`);\r\n resolve();\r\n });\r\n });\r\n }\r\n\r\n public stop(): Promise<void> {\r\n return new Promise((resolve, reject) => {\r\n if (!this.server) {\r\n return resolve();\r\n }\r\n \r\n this.server.close((err: any) => {\r\n if (err) return reject(err);\r\n this.server = null;\r\n resolve();\r\n });\r\n });\r\n }\r\n\r\n public restart(): Promise<void> {\r\n return this.stop().then(() => this.start());\r\n }\r\n \r\n public enableSSR(options: { hydratable?: boolean } = {}): void {\r\n if (!fs.existsSync(path.resolve(process.cwd(), this.config.pagesDir!))) {\r\n fs.mkdirSync(path.resolve(process.cwd(), this.config.pagesDir!), { recursive: true });\r\n }\r\n \r\n // Set up client-side JS for hydration if needed\r\n if (options.hydratable) {\r\n const staticDir = path.resolve(process.cwd(), this.config.staticDir!);\r\n if (!fs.existsSync(staticDir)) {\r\n fs.mkdirSync(staticDir, { recursive: true });\r\n }\r\n \r\n // Generate or copy client hydration script\r\n // This is a simplified example - would need more implementation\r\n const clientJsPath = path.join(staticDir, 'client.js');\r\n if (!fs.existsSync(clientJsPath)) {\r\n const clientJsContent = `\r\n // Auto-generated hydration script\r\n import { hydrate } from 'frontend-hamroun';\r\n \r\n // Find SSR content and hydrate it\r\n document.addEventListener('DOMContentLoaded', () => {\r\n const ssrRoots = document.querySelectorAll('[data-ssr-root]');\r\n ssrRoots.forEach(root => {\r\n const componentPath = root.getAttribute('data-component');\r\n if (componentPath) {\r\n import(componentPath).then(module => {\r\n hydrate(module.default, root);\r\n });\r\n }\r\n });\r\n });\r\n `;\r\n fs.writeFileSync(clientJsPath, clientJsContent);\r\n }\r\n }\r\n }\r\n\r\n public registerPlugin(plugin: (server: Server) => void): void {\r\n plugin(this);\r\n }\r\n \r\n public addShutdownHandler(): void {\r\n // Handle graceful shutdown\r\n const gracefulShutdown = async () => {\r\n console.log('Received shutdown signal, closing server...');\r\n try {\r\n await this.stop();\r\n if (this.db) {\r\n await this.db.disconnect();\r\n }\r\n console.log('Server shut down gracefully');\r\n process.exit(0);\r\n } catch (error) {\r\n console.error('Error during shutdown:', error);\r\n process.exit(1);\r\n }\r\n };\r\n \r\n // Listen for termination signals\r\n process.on('SIGTERM', gracefulShutdown);\r\n process.on('SIGINT', gracefulShutdown);\r\n }\r\n}\r\n\r\n// Add server utility functions\r\n\r\n/**\r\n * Creates and configures a new server instance\r\n */\r\nexport function createServer(config: ServerConfig = {}): Server {\r\n return new Server(config);\r\n}\r\n\r\n/**\r\n * Creates a new server with sensible defaults for development\r\n */\r\nexport function createDevServer(options: {\r\n port?: number;\r\n enableCors?: boolean;\r\n} = {}): Server {\r\n return new Server({\r\n port: options.port || 3000,\r\n enableCors: options.enableCors !== false,\r\n apiDir: './src/api',\r\n pagesDir: './src/pages',\r\n staticDir: './public'\r\n });\r\n}\r\n\r\n/**\r\n * Creates a production-ready server with optimized settings\r\n */\r\nexport function createProductionServer(config: ServerConfig): Server {\r\n const server = new Server({\r\n ...config,\r\n // Fix the PORT parsing\r\n port: config.port || (process.env.PORT ? parseInt(process.env.PORT) : 8080)\r\n });\r\n \r\n // Add shutdown handler for production environments\r\n server.addShutdownHandler();\r\n \r\n return server;\r\n}\r\n\r\n// Export additional utility functions\r\nexport function getRequestIp(req: any): string {\r\n return req.ip || \r\n (req.headers['x-forwarded-for'] as string)?.split(',')[0].trim() || \r\n req.socket.remoteAddress || \r\n '';\r\n}\r\n\r\nexport function parseCookies(req: any): Record<string, string> {\r\n const cookies: Record<string, string> = {};\r\n const cookieHeader = req.headers.cookie;\r\n \r\n if (cookieHeader) {\r\n cookieHeader.split(';').forEach((cookie: string) => {\r\n const [name, value] = cookie.split('=').map(c => c.trim());\r\n cookies[name] = value;\r\n });\r\n }\r\n \r\n return cookies;\r\n}\r\n\r\n// Fix the renderComponent function to use frontend-hamroun's renderToString properly\r\nexport const renderComponent = async (Component: any, props: any = {}) => {\r\n try {\r\n // Import frontend-hamroun modules\r\n const { jsx, renderToString } = await import('frontend-hamroun');\r\n \r\n // Create component element using jsx\r\n const element = jsx(Component, props);\r\n \r\n // Use frontend-hamroun's renderToString for proper SSR\r\n const html = renderToString(element);\r\n \r\n return {\r\n html: typeof html === 'string' ? html : String(html),\r\n success: true\r\n };\r\n } catch (error) {\r\n console.error('Error rendering component:', error);\r\n return {\r\n html: `<div class=\"error\">Error rendering component: ${error instanceof Error ? error.message : 'Unknown error'}</div>`,\r\n success: false,\r\n error\r\n };\r\n }\r\n};\r\n\r\n// Export WASM utilities for server-side usage\r\nexport { initNodeWasm, loadGoWasmFromFile } from './wasm.js';\r\n\r\n// Import and export server utilities\r\nexport * from './utils.js';\r\nexport * from './templates.js';\r\n\r\n// Export the Database and AuthService classes\r\nexport { Database } from './database.js';\r\nexport { AuthService } from './auth.js';\r\nexport { ApiRouter } from './api-router.js';\r\nexport { \r\n requestLogger, \r\n errorHandler, \r\n notFoundHandler, \r\n rateLimit \r\n} from './middleware.js';\r\n\r\n// Export renderToString for convenient SSR\r\nexport { renderToString };\r\n\r\n// Ensure the default export includes all required functions\r\nexport default {\r\n Server,\r\n createServer,\r\n createDevServer,\r\n createProductionServer,\r\n rateLimit,\r\n requestLogger,\r\n errorHandler,\r\n notFoundHandler,\r\n loadGoWasmFromFile,\r\n // Template utilities\r\n templates,\r\n // Server utilities\r\n utils,\r\n // Additional exports\r\n renderComponent,\r\n renderToString,\r\n getRequestIp,\r\n parseCookies,\r\n Database,\r\n AuthService,\r\n ApiRouter\r\n};\r\n\r\n", "export interface DbConfig {\r\n url: string;\r\n type: 'mongodb' | 'mysql' | 'postgres';\r\n}\r\n\r\nexport class Database {\r\n private config: DbConfig;\r\n private mongoClient: any = null;\r\n private mongoDb: any = null;\r\n private mysqlPool: any = null;\r\n private pgPool: any = null;\r\n\r\n constructor(config: DbConfig) {\r\n this.config = config;\r\n }\r\n\r\n async connect(): Promise<void> {\r\n switch (this.config.type) {\r\n case 'mongodb':\r\n await this.connectMongo();\r\n break;\r\n case 'mysql':\r\n await this.connectMysql();\r\n break;\r\n case 'postgres':\r\n await this.connectPostgres();\r\n break;\r\n default:\r\n throw new Error(`Unsupported database type: ${this.config.type}`);\r\n }\r\n }\r\n\r\n private async connectMongo(): Promise<void> {\r\n try {\r\n const { MongoClient } = await import('mongodb');\r\n this.mongoClient = new MongoClient(this.config.url);\r\n await this.mongoClient.connect();\r\n this.mongoDb = this.mongoClient.db();\r\n console.log('Connected to MongoDB');\r\n } catch (error: any) {\r\n if (error.code === 'MODULE_NOT_FOUND') {\r\n throw new Error('MongoDB driver not installed. Run: npm install mongodb');\r\n }\r\n console.error('MongoDB connection error:', error);\r\n throw error;\r\n }\r\n }\r\n\r\n private async connectMysql(): Promise<void> {\r\n try {\r\n const mysql = await import('mysql2/promise');\r\n this.mysqlPool = mysql.createPool(this.config.url);\r\n // Test connection\r\n await this.mysqlPool.getConnection();\r\n console.log('Connected to MySQL');\r\n } catch (error: any) {\r\n if (error.code === 'MODULE_NOT_FOUND') {\r\n throw new Error('MySQL driver not installed. Run: npm install mysql2');\r\n }\r\n console.error('MySQL connection error:', error);\r\n throw error;\r\n }\r\n }\r\n\r\n private async connectPostgres(): Promise<void> {\r\n try {\r\n const pg = await import('pg');\r\n this.pgPool = new pg.Pool({ connectionString: this.config.url });\r\n // Test connection\r\n const client = await this.pgPool.connect();\r\n client.release();\r\n console.log('Connected to PostgreSQL');\r\n } catch (error: any) {\r\n if (error.code === 'MODULE_NOT_FOUND') {\r\n throw new Error('PostgreSQL driver not installed. Run: npm install pg @types/pg');\r\n }\r\n console.error('PostgreSQL connection error:', error);\r\n throw error;\r\n }\r\n }\r\n\r\n async disconnect(): Promise<void> {\r\n if (this.mongoClient) {\r\n await this.mongoClient.close();\r\n this.mongoClient = null;\r\n this.mongoDb = null;\r\n }\r\n \r\n if (this.mysqlPool) {\r\n await this.mysqlPool.end();\r\n this.mysqlPool = null;\r\n }\r\n \r\n if (this.pgPool) {\r\n await this.pgPool.end();\r\n this.pgPool = null;\r\n }\r\n }\r\n\r\n // Database-specific methods\r\n getMongoDb(): any {\r\n return this.mongoDb;\r\n }\r\n\r\n getMysqlPool(): any {\r\n return this.mysqlPool;\r\n }\r\n\r\n getPgPool(): any {\r\n return this.pgPool;\r\n }\r\n\r\n // Generic query method\r\n async query(sql: string, values?: any[]): Promise<any> {\r\n switch (this.config.type) {\r\n case 'mongodb':\r\n throw new Error('For MongoDB, use getMongoDb() instead of query()');\r\n case 'mysql':\r\n if (!this.mysqlPool) throw new Error('MySQL not connected');\r\n const [rows] = await this.mysqlPool.execute(sql, values || []);\r\n return rows;\r\n case 'postgres':\r\n if (!this.pgPool) throw new Error('PostgreSQL not connected');\r\n const result = await this.pgPool.query(sql, values || []);\r\n return result.rows;\r\n default:\r\n throw new Error(`Unsupported database type: ${this.config.type}`);\r\n }\r\n }\r\n}\r\n", "\r\n\r\nexport interface AuthConfig {\r\n secret: string;\r\n expiresIn?: string | number;\r\n}\r\n\r\nexport interface User {\r\n id: string | number;\r\n username: string;\r\n password?: string;\r\n email?: string;\r\n roles?: string[];\r\n [key: string]: any;\r\n}\r\n\r\nexport class AuthService {\r\n private config: AuthConfig;\r\n\r\n constructor(config: AuthConfig) {\r\n this.config = {\r\n expiresIn: '24h',\r\n ...config\r\n };\r\n }\r\n\r\n async hashPassword(password: string): Promise<string> {\r\n try {\r\n const bcrypt = await import('bcryptjs');\r\n return bcrypt.hash(password, 10);\r\n } catch (error: any) {\r\n if (error.code === 'MODULE_NOT_FOUND') {\r\n throw new Error('bcryptjs not installed. Run: npm install bcryptjs @types/bcryptjs');\r\n }\r\n throw error;\r\n }\r\n }\r\n\r\n async comparePasswords(password: string, hashedPassword: string): Promise<boolean> {\r\n try {\r\n const bcrypt = await import('bcryptjs');\r\n return bcrypt.compare(password, hashedPassword);\r\n } catch (error: any) {\r\n if (error.code === 'MODULE_NOT_FOUND') {\r\n throw new Error('bcryptjs not installed. Run: npm install bcryptjs @types/bcryptjs');\r\n }\r\n throw error;\r\n }\r\n }\r\n\r\n generateToken(user: Omit<User, 'password'>): string {\r\n try {\r\n const jwt = require('jsonwebtoken');\r\n const options: any = {};\r\n \r\n if (this.config.expiresIn) {\r\n options.expiresIn = this.config.expiresIn;\r\n }\r\n \r\n return jwt.sign(\r\n { id: user.id, username: user.username, roles: user.roles || [] },\r\n this.config.secret,\r\n options\r\n );\r\n } catch (error: any) {\r\n if (error.code === 'MODULE_NOT_FOUND') {\r\n throw new Error('jsonwebtoken not installed. Run: npm install jsonwebtoken @types/jsonwebtoken');\r\n }\r\n throw error;\r\n }\r\n }\r\n\r\n verifyToken(token: string): any {\r\n try {\r\n const jwt = require('jsonwebtoken');\r\n return jwt.verify(token, this.config.secret);\r\n } catch (error: any) {\r\n if (error.code === 'MODULE_NOT_FOUND') {\r\n throw new Error('jsonwebtoken not installed. Run: npm install jsonwebtoken @types/jsonwebtoken');\r\n }\r\n return null;\r\n }\r\n }\r\n\r\n // Express middleware for authentication\r\n initialize() {\r\n return (req: any, res: any, next: any) => {\r\n const token = this.extractToken(req);\r\n if (token) {\r\n const decoded = this.verifyToken(token);\r\n if (decoded) {\r\n req.user = decoded;\r\n }\r\n }\r\n next();\r\n };\r\n }\r\n\r\n // Express middleware for requiring authentication\r\n requireAuth() {\r\n return (req: any, res: any, next: any) => {\r\n if (!req.user) {\r\n return res.status(401).json({ message: 'Unauthorized' });\r\n }\r\n return next();\r\n };\r\n }\r\n\r\n // Express middleware for requiring specific roles\r\n requireRoles(roles: string[]) {\r\n return (req: any, res: any, next: any) => {\r\n if (!req.user) {\r\n return res.status(401).json({ message: 'Unauthorized' });\r\n }\r\n \r\n const userRoles = req.user.roles || [];\r\n const hasRequiredRole = roles.some(role => userRoles.includes(role));\r\n \r\n if (!hasRequiredRole) {\r\n return res.status(403).json({ message: 'Forbidden' });\r\n }\r\n \r\n return next();\r\n };\r\n }\r\n\r\n private extractToken(req: any): string | null {\r\n if (req.headers.authorization && req.headers.authorization.startsWith('Bearer ')) {\r\n return req.headers.authorization.substring(7);\r\n }\r\n return null;\r\n }\r\n}\r\n", "import path from 'path';\r\nimport fs from 'fs';\r\nimport { AuthService } from './auth.js';\r\nimport { pathToFileURL } from 'url';\r\n\r\ninterface RouteHandler {\r\n (req: any, res: any, next?: any): void | Promise<void>;\r\n}\r\n\r\ninterface RouteModule {\r\n get?: RouteHandler;\r\n post?: RouteHandler;\r\n put?: RouteHandler;\r\n delete?: RouteHandler;\r\n patch?: RouteHandler;\r\n options?: RouteHandler;\r\n middleware?: ((req: any, res: any, next: any) => void)[];\r\n // Add index signature to allow string indexing\r\n [key: string]: RouteHandler | ((req: any, res: any, next: any) => void)[] | undefined;\r\n}\r\n\r\nexport class ApiRouter {\r\n public router: any;\r\n private apiDir: string;\r\n private auth: AuthService | null;\r\n\r\n constructor(apiDir: string, auth: AuthService | null = null) {\r\n this.router = null;\r\n this.apiDir = path.resolve(process.cwd(), apiDir);\r\n this.auth = auth;\r\n \r\n this.initializeRouter();\r\n }\r\n\r\n private async initializeRouter() {\r\n try {\r\n const express = await import('express');\r\n this.router = express.default.Router();\r\n this.setupRoutes();\r\n } catch (error: any) {\r\n if (error.code === 'MODULE_NOT_FOUND') {\r\n throw new Error('Express not installed. Run: npm install express @types/express');\r\n }\r\n throw error;\r\n }\r\n }\r\n\r\n private setupRoutes() {\r\n if (!fs.existsSync(this.apiDir)) {\r\n console.log(`API directory not found: ${this.apiDir}`);\r\n return;\r\n }\r\n\r\n this.scanDirectory(this.apiDir, '');\r\n }\r\n\r\n private scanDirectory(dirPath: string, routePrefix: string) {\r\n const entries = fs.readdirSync(dirPath, { withFileTypes: true });\r\n\r\n for (const entry of entries) {\r\n const fullPath = path.join(dirPath, entry.name);\r\n \r\n if (entry.isDirectory()) {\r\n // Recursively scan subdirectories\r\n this.scanDirectory(fullPath, `${routePrefix}/${entry.name}`);\r\n } else if (this.isRouteFile(entry.name)) {\r\n // Process route file\r\n const routePath = this.getRoutePath(entry.name, routePrefix);\r\n this.registerRoute(fullPath, routePath);\r\n }\r\n }\r\n }\r\n\r\n private isRouteFile(filename: string): boolean {\r\n return filename.endsWith('.js') || \r\n filename.endsWith('.ts') || \r\n filename.endsWith('.mjs');\r\n }\r\n\r\n private getRoutePath(filename: string, routePrefix: string): string {\r\n // Remove extension and handle special names\r\n const baseName = path.basename(filename, path.extname(filename));\r\n \r\n if (baseName === 'index') {\r\n return routePrefix || '/';\r\n }\r\n \r\n // Handle dynamic routes [param]\r\n const paramMatch = baseName.match(/^\\[(.+)\\]$/);\r\n if (paramMatch) {\r\n return `${routePrefix}/:${paramMatch[1]}`;\r\n }\r\n \r\n return `${routePrefix}/${baseName}`;\r\n }\r\n\r\n private async registerRoute(filePath: string, routePath: string) {\r\n try {\r\n // Ensure we have an absolute path and normalize it\r\n const absolutePath = path.isAbsolute(filePath) ? filePath : path.resolve(filePath);\r\n \r\n // Convert to proper file:// URL for Windows\r\n const fileUrl = pathToFileURL(absolutePath).href;\r\n \r\n if (process.platform === 'win32') {\r\n // Add timestamp to force reload on Windows\r\n const urlWithTimestamp = `${fileUrl}?t=${Date.now()}`;\r\n \r\n // Dynamic import the route file\r\n const routeModule = await import(urlWithTimestamp);\r\n \r\n if (!this.isValidRouteModule(routeModule)) {\r\n console.warn(`Invalid route module: ${filePath}`);\r\n return;\r\n }\r\n \r\n console.log(`Registering API route: ${routePath}`);\r\n \r\n // Register middleware if any\r\n const middleware = routeModule.middleware || [];\r\n \r\n // Register HTTP methods\r\n for (const method of ['get', 'post', 'put', 'delete', 'patch', 'options']) {\r\n const handler = routeModule[method];\r\n if (typeof handler === 'function') {\r\n const routerMethod = this.router[method];\r\n routerMethod.call(\r\n this.router,\r\n routePath, \r\n ...middleware,\r\n this.wrapHandler(handler)\r\n );\r\n }\r\n }\r\n } else {\r\n // Non-Windows platforms\r\n const routeModule = await import(fileUrl);\r\n \r\n if (!this.isValidRouteModule(routeModule)) {\r\n console.warn(`Invalid route module: ${filePath}`);\r\n return;\r\n }\r\n \r\n console.log(`Registering API route: ${routePath}`);\r\n \r\n // Register middleware if any\r\n const middleware = routeModule.middleware || [];\r\n \r\n // Register HTTP methods\r\n for (const method of ['get', 'post', 'put', 'delete', 'patch', 'options']) {\r\n const handler = routeModule[method];\r\n if (typeof handler === 'function') {\r\n const routerMethod = this.router[method];\r\n routerMethod.call(\r\n this.router,\r\n routePath, \r\n ...middleware,\r\n this.wrapHandler(handler)\r\n );\r\n }\r\n }\r\n }\r\n } catch (error) {\r\n console.error(`Error registering route (${filePath}):`, error);\r\n }\r\n }\r\n\r\n private isValidRouteModule(module: any): module is RouteModule {\r\n if (!module) return false;\r\n \r\n // Check if at least one HTTP method handler is defined\r\n return ['get', 'post', 'put', 'delete', 'patch', 'options']\r\n .some(method => typeof module[method] === 'function');\r\n }\r\n\r\n private wrapHandler(handler: RouteHandler) {\r\n return async (req: any, res: any, next: any) => {\r\n try {\r\n await handler(req, res, next);\r\n } catch (error) {\r\n next(error);\r\n }\r\n };\r\n }\r\n}\r\n", "import { Request, Response, NextFunction } from 'express';\r\n\r\nexport interface MiddlewareFunction {\r\n (req: any, res: any, next: any): void | Promise<void>;\r\n}\r\n\r\n// Common middleware functions\r\nexport const requestLogger: MiddlewareFunction = (req, res, next) => {\r\n console.log(`${new Date().toISOString()} - ${req.method} ${req.url}`);\r\n next();\r\n};\r\n\r\nexport const errorHandler = (\r\n err: Error, \r\n req: any, \r\n res: any, \r\n next: any\r\n) => {\r\n console.error(err.stack);\r\n res.status(500).json({\r\n error: {\r\n message: 'Internal Server Error',\r\n ...(process.env.NODE_ENV !== 'production' ? { details: err.message, stack: err.stack } : {})\r\n }\r\n });\r\n};\r\n\r\nexport const notFoundHandler = (req: any, res: any) => {\r\n res.status(404).json({\r\n error: {\r\n message: `Not Found - ${req.method} ${req.url}`\r\n }\r\n });\r\n};\r\n\r\n// Middleware for rate limiting\r\nexport function rateLimit(options: { windowMs: number; max: number }) {\r\n const requests = new Map<string, number[]>();\r\n \r\n return (req: any, res: any, next: any) => {\r\n const ip = req.ip || req.socket.remoteAddress || 'unknown';\r\n const now = Date.now();\r\n \r\n // Get existing requests and filter out old ones\r\n const reqTimes = (requests.get(ip) || [])\r\n .filter(time => now - time < options.windowMs);\r\n \r\n // Add current request\r\n reqTimes.push(now);\r\n requests.set(ip, reqTimes);\r\n \r\n // Check if too many requests\r\n if (reqTimes.length > options.max) {\r\n return res.status(429).json({\r\n error: {\r\n message: 'Too Many Requests',\r\n retryAfter: Math.ceil(options.windowMs / 1000)\r\n }\r\n });\r\n }\r\n \r\n return next();\r\n };\r\n}\r\n", "import crypto from 'crypto';\r\nimport fs from 'fs/promises';\r\nimport path from 'path';\r\n\r\n/**\r\n * Utility functions for server-side operations\r\n */\r\n\r\n/**\r\n * Safely parse JSON with error handling\r\n */\r\nexport function safeJsonParse<T>(json: string, fallback: T): T {\r\n try {\r\n return JSON.parse(json) as T;\r\n } catch (error) {\r\n return fallback;\r\n }\r\n}\r\n\r\n/**\r\n * Generate a secure random token\r\n */\r\nexport function generateToken(length: number = 32): string {\r\n return crypto.randomBytes(length).toString('hex');\r\n}\r\n\r\n/**\r\n * Hash a string using SHA-256\r\n */\r\nexport function hashString(input: string, salt: string = ''): string {\r\n return crypto.createHash('sha256').update(input + salt).digest('hex');\r\n}\r\n\r\n/**\r\n * Get pagination parameters from request\r\n */\r\nexport function getPagination(req: any): { page: number; limit: number; skip: number } {\r\n const page = Math.max(1, parseInt(req.query.page as string) || 1);\r\n const rawLimit = parseInt(req.query.limit as string);\r\n \r\n // If no limit is provided or limit is 0/invalid, use default of 20\r\n // If limit is provided and valid, enforce min of 1 and max of 100\r\n let limit: number;\r\n if (isNaN(rawLimit) || rawLimit <= 0) {\r\n limit = 20; // Default limit\r\n } else {\r\n limit = Math.max(1, Math.min(100, rawLimit));\r\n }\r\n \r\n const skip = (page - 1) * limit;\r\n \r\n return { page, limit, skip };\r\n}\r\n\r\n/**\r\n * Standard success response format\r\n */\r\nexport function sendSuccess<T>(res: any, data: T, message: string = 'Success'): any {\r\n return res.json({\r\n success: true,\r\n message,\r\n data\r\n });\r\n}\r\n\r\n/**\r\n * Standard error response format\r\n */\r\nexport function sendError(\r\n res: any, \r\n message: string = 'An error occurred', \r\n statusCode: number = 400,\r\n errors?: any\r\n): any {\r\n return res.status(statusCode).json({\r\n success: false,\r\n message,\r\n errors: errors || undefined\r\n });\r\n}\r\n\r\n/**\r\n * Validate required fields in request body\r\n */\r\nexport function validateFields(\r\n req: any, \r\n requiredFields: string[]\r\n): { valid: boolean; missing: string[] } {\r\n const missing = requiredFields.filter(field => {\r\n const value = req.body[field];\r\n return value === undefined || value === null || value === '';\r\n });\r\n \r\n return {\r\n valid: missing.length === 0,\r\n missing\r\n };\r\n}\r\n\r\n/**\r\n * Handle file upload validation\r\n */\r\nexport function validateFileUpload(\r\n file: any, // Using 'any' to avoid the Express.Multer dependency\r\n options: {\r\n maxSize?: number;\r\n allowedTypes?: string[];\r\n } = {}\r\n): { valid: boolean; error?: string } {\r\n if (!file) {\r\n return { valid: false, error: 'No file provided' };\r\n }\r\n \r\n // Check file size\r\n if (options.maxSize && file.size > options.maxSize) {\r\n return { \r\n valid: false, \r\n error: `File too large. Maximum size allowed is ${options.maxSize / 1024 / 1024}MB` \r\n };\r\n }\r\n \r\n // Check file type\r\n if (options.allowedTypes && options.allowedTypes.length > 0) {\r\n const fileType = file.mimetype;\r\n if (!options.allowedTypes.includes(fileType)) {\r\n return { \r\n valid: false, \r\n error: `Invalid file type. Allowed types: ${options.allowedTypes.join(', ')}` \r\n };\r\n }\r\n }\r\n \r\n return { valid: true };\r\n}\r\n\r\n/**\r\n * Get server environment information\r\n */\r\nexport function getEnvironmentInfo(): Record<string, any> {\r\n return {\r\n nodeVersion: process.version,\r\n platform: process.platform,\r\n arch: process.arch,\r\n memory: process.memoryUsage(),\r\n uptime: process.uptime(),\r\n env: process.env.NODE_ENV || 'development'\r\n };\r\n}\r\n\r\n/**\r\n * Check if a directory is empty\r\n */\r\nexport async function isDirectoryEmpty(dirPath: string): Promise<boolean> {\r\n try {\r\n const files = await fs.readdir(dirPath);\r\n return files.length === 0;\r\n } catch (error) {\r\n // Directory doesn't exist or can't be read\r\n return true;\r\n }\r\n}\r\n\r\n/**\r\n * Create directory if it doesn't exist\r\n */\r\nexport async function ensureDirectory(dirPath: string): Promise<void> {\r\n try {\r\n await fs.access(dirPath);\r\n } catch (error) {\r\n // Directory doesn't exist, create it\r\n await fs.mkdir(dirPath, { recursive: true });\r\n }\r\n}\r\n\r\n/**\r\n * Write JSON to file\r\n */\r\nexport async function writeJsonFile(filePath: string, data: any): Promise<void> {\r\n await ensureDirectory(path.dirname(filePath));\r\n await fs.writeFile(filePath, JSON.stringify(data, null, 2), 'utf8');\r\n}\r\n\r\n/**\r\n * Read JSON from file\r\n */\r\nexport async function readJsonFile<T>(filePath: string, defaultValue: T): Promise<T> {\r\n try {\r\n const data = await fs.readFile(filePath, 'utf8');\r\n return safeJsonParse<T>(data, defaultValue);\r\n } catch (error) {\r\n return defaultValue;\r\n }\r\n}\r\n", "/**\r\n * HTML template generators for server-side rendering\r\n */\r\n\r\nexport interface DocumentOptions {\r\n title?: string;\r\n description?: string;\r\n lang?: string;\r\n charset?: string;\r\n viewport?: string;\r\n scripts?: string[];\r\n styles?: string[];\r\n meta?: Record<string, string>;\r\n bodyClasses?: string;\r\n htmlAttrs?: Record<string, string>;\r\n bodyAttrs?: Record<string, string>;\r\n initialData?: any;\r\n componentName?: string;\r\n}\r\n\r\n/**\r\n * Generate a complete HTML document\r\n */\r\nexport function generateDocument(\r\n content: string, \r\n options: DocumentOptions = {}\r\n): string {\r\n const {\r\n title = 'Frontend Hamroun App',\r\n description = '',\r\n lang = 'en',\r\n charset = 'UTF-8',\r\n viewport = 'width=device-width, initial-scale=1.0',\r\n scripts = [],\r\n styles = [],\r\n meta = {},\r\n bodyClasses = '',\r\n htmlAttrs = {},\r\n bodyAttrs = {},\r\n initialData = {},\r\n componentName = ''\r\n } = options;\r\n \r\n // Generate HTML attributes\r\n const htmlAttributes = Object.entries(htmlAttrs)\r\n .map(([key, value]) => `${key}=\"${escapeHtml(value)}\"`)\r\n .join(' ');\r\n \r\n // Generate body attributes\r\n const bodyAttributes = Object.entries(bodyAttrs)\r\n .map(([key, value]) => `${key}=\"${escapeHtml(value)}\"`)\r\n .join(' ');\r\n \r\n // Generate meta tags\r\n const metaTags = [\r\n `<meta charset=\"${charset}\">`,\r\n `<meta name=\"viewport\" content=\"${viewport}\">`,\r\n description ? `<meta name=\"description\" content=\"${escapeHtml(description)}\">` : ''\r\n ];\r\n \r\n // Add custom meta tags\r\n Object.entries(meta).forEach(([name, content]) => {\r\n metaTags.push(`<meta name=\"${escapeHtml(name)}\" content=\"${escapeHtml(content)}\">`);\r\n });\r\n \r\n // Generate script tags\r\n const scriptTags = scripts.map(src => {\r\n if (src.startsWith('<script')) {\r\n return src; // Allow inline scripts\r\n }\r\n return `<script src=\"${escapeHtml(src)}\" ${src.endsWith('.js') ? 'type=\"module\"' : ''} defer></script>`;\r\n });\r\n \r\n // Generate style tags\r\n const styleTags = styles.map(href => {\r\n if (href.startsWith('<style')) {\r\n return href; // Allow inline styles\r\n }\r\n return `<link rel=\"stylesheet\" href=\"${escapeHtml(href)}\">`;\r\n });\r\n \r\n // Create initial data script\r\n const initialDataScript = Object.keys(initialData).length > 0 ? \r\n `<script id=\"__APP_DATA__\" type=\"application/json\">${escapeHtml(JSON.stringify(initialData))}</script>` : '';\r\n \r\n // Create the complete HTML document\r\n return `<!DOCTYPE html>\r\n<html lang=\"${lang}\" ${htmlAttributes}>\r\n<head>\r\n ${metaTags.filter(Boolean).join('\\n ')}\r\n <title>${escapeHtml(title)}</title>\r\n ${styleTags.join('\\n ')}\r\n</head>\r\n<body class=\"${bodyClasses}\" ${bodyAttributes}>\r\n <div id=\"app-root\" data-ssr-root${componentName ? ` data-component=\"${escapeHtml(componentName)}\"` : ''}>${content}</div>\r\n ${initialDataScript}\r\n ${scriptTags.join('\\n ')}\r\n</body>\r\n</html>`;\r\n}\r\n\r\n/**\r\n * Generate an error page\r\n */\r\nexport function generateErrorPage(\r\n statusCode: number, \r\n message: string, \r\n error?: Error\r\n): string {\r\n const errorMessages: Record<number, string> = {\r\n 400: 'Bad Request',\r\n 401: 'Unauthorized',\r\n 403: 'Forbidden',\r\n 404: 'Not Found',\r\n 500: 'Internal Server Error'\r\n };\r\n \r\n const title = `${statusCode} - ${errorMessages[statusCode] || 'Error'}`;\r\n \r\n // Generate error details (only in development)\r\n const isDev = process.env.NODE_ENV !== 'production';\r\n const errorDetails = isDev && error ? `\r\n <div class=\"error-details\">\r\n <pre>${escapeHtml(error.stack || error.message)}</pre>\r\n </div>\r\n ` : '';\r\n \r\n // Create error content\r\n const content = `\r\n <div class=\"error-container\">\r\n <h1>${statusCode}</h1>\r\n <h2>${escapeHtml(errorMessages[statusCode] || 'Error')}</h2>\r\n <p>${escapeHtml(message)}</p>\r\n ${errorDetails}\r\n <a href=\"/\" class=\"home-link\">Back to Home</a>\r\n </div>\r\n `;\r\n \r\n // Add error page styling\r\n const styles = [`<style>\r\n body {\r\n font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, Oxygen, Ubuntu, Cantarell, 'Open Sans', 'Helvetica Neue', sans-serif;\r\n display: flex;\r\n justify-content: center;\r\n align-items: center;\r\n min-height: 100vh;\r\n margin: 0;\r\n background-color: #f7f7f7;\r\n color: #333;\r\n }\r\n .error-container {\r\n text-align: center;\r\n padding: 2rem;\r\n border-radius: 8px;\r\n background-color: white;\r\n box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1);\r\n max-width: 600px;\r\n width: 100%;\r\n }\r\n h1 {\r\n font-size: 6rem;\r\n margin: 0;\r\n color: #e74c3c;\r\n }\r\n h2 {\r\n margin-top: 0;\r\n margin-bottom: 1rem;\r\n color: #333;\r\n }\r\n .error-details {\r\n text-align: left;\r\n margin: 2rem 0;\r\n padding: 1rem;\r\n background-color: #f8f8f8;\r\n border-radius: 4px;\r\n overflow: auto;\r\n }\r\n pre {\r\n margin: 0;\r\n font-family: monospace;\r\n font-size: 0.85rem;\r\n white-space: pre-wrap;\r\n }\r\n .home-link {\r\n display: inline-block;\r\n margin-top: 1.5rem;\r\n padding: 0.75rem 1.5rem;\r\n background-color: #3498db;\r\n color: white;\r\n text-decoration: none;\r\n border-radius: 4px;\r\n transition: background-color 0.2s;\r\n }\r\n .home-link:hover {\r\n background-color: #2980b9;\r\n }\r\n </style>`];\r\n \r\n return generateDocument(content, {\r\n title,\r\n description: `Error ${statusCode}: ${errorMessages[statusCode] || 'Error'}`,\r\n bodyClasses: 'error-page',\r\n styles\r\n });\r\n}\r\n\r\n/**\r\n * Generate a loading page\r\n */\r\nexport function generateLoadingPage(message: string = 'Loading...'): string {\r\n const content = `\r\n <div class=\"loading-container\">\r\n <div class=\"spinner\"></div>\r\n <p>${escapeHtml(message)}</p>\r\n </div>\r\n `;\r\n \r\n const styles = [`<style>\r\n body {\r\n font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, Oxygen, Ubuntu, Cantarell, 'Open Sans', 'Helvetica Neue', sans-serif;\r\n display: flex;\r\n justify-content: center;\r\n align-items: center;\r\n min-height: 100vh;\r\n margin: 0;\r\n background-color: #f7f7f7;\r\n color: #333;\r\n }\r\n .loading-container {\r\n text-align: center;\r\n }\r\n .spinner {\r\n width: 50px;\r\n height: 50px;\r\n border: 5px solid rgba(0, 0, 0, 0.1);\r\n border-radius: 50%;\r\n border-top-color: #3498db;\r\n animation: spin 1s ease-in-out infinite;\r\n margin: 0 auto 20px;\r\n }\r\n @keyframes spin {\r\n to { transform: rotate(360deg); }\r\n }\r\n </style>`];\r\n \r\n return generateDocument(content, {\r\n title: 'Loading',\r\n bodyClasses: 'loading-page',\r\n styles\r\n });\r\n}\r\n\r\n/**\r\n * Escape HTML special characters\r\n */\r\nfunction escapeHtml(text: string): string {\r\n return String(text)\r\n .replace(/&/g, '&amp;')\r\n .replace(/</g, '&lt;')\r\n .replace(/>/g, '&gt;')\r\n .replace(/\"/g, '&quot;')\r\n .replace(/'/g, '&#039;');\r\n}\r\n", "/**\r\n * Server-side Go WASM integration for Node.js\r\n * Uses the standard Go WASM runtime (wasm_exec.js)\r\n */\r\nimport fs from 'fs/promises';\r\nimport path from 'path';\r\nimport { pathToFileURL } from 'url';\r\nimport { GoWasmInstance, GoWasmOptions } from '../server/types.js';\r\n\r\n// Global flag to ensure we only initialize WASM once\r\nlet initialized = false;\r\n\r\n/**\r\n * Initialize the Node.js environment for running Go WASM modules\r\n */\r\nexport async function initNodeWasm(): Promise<void> {\r\n if (initialized) return;\r\n \r\n try {\r\n // Global WASM environment setup for Node.js\r\n globalThis.TextEncoder = globalThis.TextEncoder || TextEncoder;\r\n globalThis.TextDecoder = globalThis.TextDecoder || TextDecoder;\r\n \r\n // Mark as initialized\r\n initialized = true;\r\n } catch (error) {\r\n console.error('[WASM] Failed to initialize Node.js WASM environment:', error);\r\n throw error;\r\n }\r\n}\r\n\r\n/**\r\n * Load Go WASM runtime from wasm_exec.js file\r\n */\r\nasync function loadGoRuntime(goWasmPath?: string): Promise<any> {\r\n if (typeof global.Go === 'function') {\r\n return global.Go;\r\n }\r\n\r\n // Try to find wasm_exec.js or wasm_exec.cjs\r\n const possiblePaths = [\r\n goWasmPath,\r\n './wasm_exec.cjs',\r\n './wasm_exec.js',\r\n './public/wasm_exec.cjs',\r\n './public/wasm_exec.js',\r\n './src/wasm_exec.cjs',\r\n './src/wasm_exec.js',\r\n path.join(process.cwd(), 'wasm_exec.cjs'),\r\n path.join(process.cwd(), 'wasm_exec.js'),\r\n path.join(process.cwd(), 'public', 'wasm_exec.cjs'),\r\n path.join(process.cwd(), 'public', 'wasm_exec.js'),\r\n path.join(process.cwd(), 'src', 'wasm_exec.cjs'),\r\n path.join(process.cwd(), 'src', 'wasm_exec.js')\r\n ].filter(Boolean);\r\n\r\n for (const wasmExecPath of possiblePaths) {\r\n try {\r\n const resolvedPath = path.resolve(wasmExecPath!);\r\n \r\n // Check if file exists using fs.stat instead of fs.access\r\n try {\r\n const stats = await fs.stat(resolvedPath);\r\n if (!stats.isFile()) {\r\n continue;\r\n }\r\n } catch (statError) {\r\n continue; // File doesn't exist, try next path\r\n }\r\n \r\n // Load the Go runtime using dynamic import with file:// URL\r\n const wasmExecUrl = pathToFileURL(resolvedPath).href;\r\n \r\n // Clear global.Go to ensure fresh import\r\n if (global.Go) {\r\n delete (global as any).Go;\r\n }\r\n \r\n // Import the module\r\n await import(wasmExecUrl);\r\n \r\n if (typeof global.Go === 'function') {\r\n console.log(`[WASM] Loaded Go runtime from: ${resolvedPath}`);\r\n return global.Go;\r\n } else {\r\n console.warn(`[WASM] File found but Go class not exported: ${resolvedPath}`);\r\n }\r\n } catch (error: any) {\r\n console.warn(`[WASM] Error loading from ${wasmExecPath}:`, error.message);\r\n continue;\r\n }\r\n }\r\n\r\n throw new Error(\r\n '[WASM] Could not find wasm_exec.js. Please ensure you have the Go WASM runtime file available.\\n' +\r\n 'You can get it from: https://github.com/golang/go/blob/master/misc/wasm/wasm_exec.js\\n' +\r\n `Searched paths: ${possiblePaths.join(', ')}`\r\n );\r\n}\r\n\r\n/**\r\n * Load a Go WASM module from a file path for server-side usage\r\n */\r\nexport async function loadGoWasmFromFile(\r\n wasmFilePath: string,\r\n options: GoWasmOptions = {}\r\n): Promise<GoWasmInstance> {\r\n try {\r\n // Initialize Node.js WASM environment\r\n await initNodeWasm();\r\n \r\n if (options.debug) {\r\n console.log('[WASM] Loading WASM from file:', wasmFilePath);\r\n }\r\n\r\n // Load the standard Go runtime\r\n const GoRuntime = await loadGoRuntime(options.goWasmPath);\r\n const go = new GoRuntime();\r\n \r\n // Load WASM binary\r\n const wasmBuffer = await fs.readFile(wasmFilePath);\r\n const wasmModule = await WebAssembly.compile(wasmBuffer);\r\n \r\n // The updated wasm_exec.js provides imports under 'gojs' instead of 'go'\r\n // Create imports object with the correct structure\r\n const baseImports = go.importObject;\r\n const finalImportObject = {\r\n ...baseImports,\r\n ...options.importObject\r\n };\r\n \r\n if (options.debug) {\r\n console.log('[WASM] Available import modules:', Object.keys(finalImportObject));\r\n \r\n // Debug each module's functions\r\n for (const [moduleName, moduleExports] of Object.entries(finalImportObject)) {\r\n if (typeof moduleExports === 'object' && moduleExports !== null) {\r\n const exportNames = Object.keys(moduleExports);\r\n console.log(`[WASM] ${moduleName} import functions:`, exportNames);\r\n }\r\n }\r\n }\r\n \r\n // Instantiate the WASM module\r\n const instance = await WebAssembly.instantiate(wasmModule, finalImportObject);\r\n \r\n if (options.debug) {\r\n console.log('[WASM] WASM instance created, starting Go runtime...');\r\n }\r\n \r\n // Initialize Go runtime - this will run the main function\r\n // The go.run() method returns a promise that resolves when the program exits\r\n const runPromise = go.run(instance);\r\n \r\n if (options.debug) {\r\n console.log('[WASM] Go runtime started, waiting for initialization...');\r\n }\r\n \r\n // Give Go runtime time to initialize and register functions\r\n // Don't wait for the program to finish, just wait for functions to be registered\r\n await new Promise(resolve => setTimeout(resolve, 2000));\r\n \r\n if (options.debug) {\r\n console.log('[WASM] Scanning global object for Go functions...');\r\n }\r\n \r\n // Extract exported functions from global scope\r\n const functions: Record<string, Function> = {};\r\n const globalObj = global as any;\r\n \r\n // Scan for Go functions\r\n const allKeys = Object.getOwnPropertyNames(globalObj);\r\n const goKeys = allKeys.filter(key => key.startsWith('go'));\r\n \r\n if (options.debug) {\r\n console.log('[WASM] All keys starting with \"go\":', goKeys);\r\n }\r\n \r\n for (const key of goKeys) {\r\n if (typeof globalObj[key] === 'function') {\r\n functions[key] = globalObj[key];\r\n if (options.debug) {\r\n console.log(`[WASM] Found function: ${key}`);\r\n }\r\n }\r\n }\r\n\r\n const wasmInstance: GoWasmInstance = {\r\n instance,\r\n module: wasmModule,\r\n exports: instance.exports,\r\n functions\r\n };\r\n \r\n // Run onLoad callback if provided\r\n if (options.onLoad) {\r\n options.onLoad(wasmInstance);\r\n }\r\n \r\n if (options.debug) {\r\n console.log(`[WASM] Module loaded successfully with ${Object.keys(functions).length} functions`);\r\n console.log('[WASM] Final function list:', Object.keys(functions));\r\n }\r\n \r\n // Don't await the runPromise - let the Go program finish in the background\r\n // The functions are already registered and available\r\n runPromise.catch((error:any)=> {\r\n if (options.debug) {\r\n console.log('[WASM] Go program finished with error:', error);\r\n }\r\n });\r\n \r\n return wasmInstance;\r\n } catch (error) {\r\n console.error('[WASM] Failed to load Go WASM module:', error);\r\n throw error;\r\n }\r\n}\r\n\r\n/**\r\n * Call a Go WASM function in Node.js environment\r\n */\r\nexport function callWasmFunction(funcName: string, ...args: any[]): any {\r\n const func = (global as any)[funcName];\r\n if (typeof func !== 'function') {\r\n throw new Error(`Function ${funcName} not found. Make sure the WASM module is loaded.`);\r\n }\r\n \r\n return func(...args);\r\n}\r\n\r\n/**\r\n * Check if Go WASM is ready in Node.js\r\n */\r\nexport function isWasmReady(): boolean {\r\n const globalObj = global as any;\r\n return Object.keys(globalObj).some(key => \r\n key.startsWith('go') && typeof globalObj[key] === 'function'\r\n );\r\n}\r\n\r\n/**\r\n * Get all available Go WASM functions in Node.js\r\n */\r\nexport function getWasmFunctions(): string[] {\r\n const globalObj = global as any;\r\n return Object.keys(globalObj).filter(key => \r\n key.startsWith('go') && typeof globalObj[key] === 'function'\r\n );\r\n}\r\n\r\n// Extend global for Go runtime\r\ndeclare global {\r\n var Go: new () => {\r\n importObject: any;\r\n run: (instance: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AAiB,QAAQ,MAAM,UAAU,eAAe;AAAA,MAC/G,SAAS;AAAA,MACT;AAAA,IACF;AAAA,EACF;AACF;AAwBA,IAAO,iBAAQ;AAAA,EACb;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA;AAAA,EAEA;AAAA;AAAA,EAEA;AAAA;AAAA,EAEA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AACF;",
6
- "names": ["path", "fs", "fs", "path", "content", "fs", "path", "pathToFileURL", "path", "fs", "renderToString"]
7
- }
File without changes