gowm 1.0.8 โ†’ 1.1.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -14,16 +14,58 @@
14
14
 
15
15
  ## โœจ Features
16
16
 
17
- - ๐Ÿš€ **Unified Interface** - Load Go WASM modules from local files or GitHub repositories
17
+ - ๐Ÿš€ **Loader System** - Intelligent loader for all source types (files, URLs, GitHub)
18
18
  - ๐Ÿ”ง **Cross-Platform** - Full support for Node.js and browser environments
19
- - โš›๏ธ **React Integration** - Built-in hooks (`useWasm`, `useWasmFromGitHub`)
20
- - ๐Ÿ–– **Vue 3 Support** - Reactive composables with automatic cleanup
19
+ - ๐ŸŽฏ **Auto-Detection** - Automatically detects source type and optimal loading strategy
21
20
  - ๐Ÿ“ฆ **GitHub Direct Loading** - Load WASM modules directly from GitHub repositories
22
21
  - ๐Ÿท๏ธ **Version Control** - Support for branches, tags, and specific commits
23
- - ๐Ÿ›ก๏ธ **Error Handling** - Robust error handling and automatic retries
24
- - ๐Ÿงน **Memory Management** - Automatic resource cleanup and memory management
25
- - ๐Ÿ“Š **Module Statistics** - Built-in monitoring and performance metrics
26
- - ๐Ÿ”„ **Flexible Calls** - Both synchronous and asynchronous function calls
22
+ - ๐Ÿ›ก๏ธ **Enhanced Error Handling** - Robust error handling with fallback strategies
23
+ - ๐Ÿงน **Smart Memory Management** - Safe memory allocation and resource cleanup
24
+ - ๐Ÿ“Š **Comprehensive Statistics** - Built-in monitoring, testing, and performance metrics
25
+ - ๐Ÿ”„ **Flexible API** - Both synchronous and asynchronous function calls
26
+ - ๐Ÿ“ **TypeScript Support** - Full TypeScript definitions included
27
+ - โš›๏ธ **React Hooks** - `useWasm()` and `useWasmFromGitHub()` hooks
28
+ - ๐Ÿ’š **Vue Composables** - `useWasm()` and `useWasmFromGitHub()` composables
29
+ - ๐Ÿ”ง **CLI** - `npx gowm list|info|types|verify|install`
30
+ - ๐Ÿ“ก **Event System** - `on()` / `off()` / `once()` for module lifecycle events
31
+ - ๐Ÿ—๏ธ **Type Generator** - Generate TypeScript interfaces from `module.json`
32
+
33
+ ### ๐Ÿ†• New in v1.1.1
34
+
35
+ - ๐Ÿ“ก **Event System** - `on('module:loaded')`, `on('module:error')`, `on('memory:warning')` with chaining
36
+ - โš›๏ธ **React Hooks** - `import { useWasm } from 'gowm/react'` with auto-cleanup and reload
37
+ - ๐Ÿ’š **Vue 3 Composables** - `import { useWasm } from 'gowm/vue'` with reactive refs and watch
38
+ - ๐Ÿ”ง **CLI** - `npx gowm list|info|types|verify|install` for module discovery and management
39
+ - ๐Ÿ—๏ธ **Type Generator** - `generateTypes()` creates TypeScript interfaces from `module.json`
40
+ - ๐Ÿ“ฆ **ESM Exports Map** - Sub-path exports `gowm/react`, `gowm/vue`, `gowm/tools/type-generator`
41
+ - ๐Ÿ“‹ **TypeScript Definitions** - Dedicated `types/react.d.ts` and `types/vue.d.ts`
42
+ - ๐Ÿงช **274 Unit Tests** - Extended coverage for all Phase 4 features
43
+
44
+ ### Previous (v1.4.0)
45
+
46
+ - ๐Ÿ“‹ **Module Metadata** - Automatic `module.json` fetching from GitHub repositories
47
+ - ๐Ÿ”’ **SHA256 Integrity** - WASM file integrity verification via `.wasm.integrity` files (SRI format)
48
+ - ๐ŸŽฏ **readySignal Auto-Discovery** - Uses `gowmConfig.readySignal` from metadata instead of generic polling
49
+ - โœ… **Function Call Validation** - Parameter count validation, type warnings in debug mode
50
+ - ๐Ÿ“– **`describe()` Documentation** - Inline documentation for functions (`bridge.describe('add')`)
51
+ - ๐Ÿ“Š **`getDetailedFunctions()`** - Rich function listing with parameters, types, examples
52
+ - ๐Ÿ—‚๏ธ **`getFunctionCategories()`** - Organized function categories from metadata
53
+
54
+ ### Previous (v1.3.0)
55
+
56
+ - ๐Ÿ’พ **Multi-Level Cache** - Memory (L1) + disk/IndexedDB (L2) caching with configurable TTL
57
+ - ๐Ÿ” **Retry with Backoff** - Automatic retry with exponential backoff on network failures
58
+ - โšก **Streaming Instantiation** - `WebAssembly.instantiateStreaming()` for HTTP loads (compile during download)
59
+ - ๐ŸŽฏ **Promise-Based Readiness** - Callback-first signals with adaptive polling fallback
60
+ - ๐Ÿ“ฆ **Compressed WASM** - Auto-detect and decompress `.wasm.gz` and `.wasm.br` files
61
+
62
+ ### Previous (v1.2.0)
63
+
64
+ - ๐Ÿ”’ **Module Namespace Isolation** - Each module gets its own namespace via `globalThis.__gowm_modules_`
65
+ - ๐ŸŒฟ **Auto Branch Detection** - GitHub default branch auto-detected via API
66
+ - ๐Ÿ” **Improved Source Detection** - Strict local path and GitHub URL detection
67
+ - ๐Ÿ“ **Configurable Logging** - Log levels with custom logger support
68
+ - ๐Ÿ›ก๏ธ **Safe Memory Allocation** - Removed unsafe offset-based fallback
27
69
 
28
70
  ## ๐Ÿ“ฅ Installation
29
71
 
@@ -40,162 +82,146 @@ pnpm add gowm
40
82
  ### Node.js Example
41
83
 
42
84
  ```javascript
43
- const { load, loadFromGitHub } = require('gowm');
85
+ const { GoWM } = require("gowm");
44
86
 
45
87
  async function example() {
46
88
  try {
47
- // Load from GitHub repository (recommended)
48
- const math = await loadFromGitHub('benoitpetit/wasm-modules-repository', {
49
- name: 'math',
50
- path: 'math-wasm',
51
- branch: 'master'
52
- });
53
-
89
+ // Create a GoWM instance with configurable logging
90
+ const gowm = new GoWM({ logLevel: "info" });
91
+
92
+ // Load from GitHub repository (branch auto-detected)
93
+ // v1.4.0: module.json metadata fetched, SHA256 integrity verified
94
+ const math = await gowm.loadFromGitHub(
95
+ "benoitpetit/wasm-modules-repository",
96
+ {
97
+ name: "math",
98
+ path: "math-wasm",
99
+ retries: 3, // retry on network failure
100
+ cache: { ttl: 3600000 }, // cache for 1 hour
101
+ // metadata: true, // auto-fetch module.json (default)
102
+ // integrity: true, // verify SHA256 hash (default)
103
+ // validateCalls: true, // validate parameters (default)
104
+ },
105
+ );
106
+
107
+ // Call functions (v1.4.0: parameters validated against metadata)
108
+ const result = math.call("add", 5, 3);
109
+ console.log("5 + 3 =", result); // 8
110
+
111
+ // v1.4.0: Describe a function from module.json metadata
112
+ const desc = gowm.describeFunction("math", "add");
113
+ console.log(desc);
114
+ // { name: 'add', description: '...', parameters: [...], returnType: '...' }
115
+
116
+ // v1.4.0: Get detailed function list with metadata
117
+ const functions = math.getDetailedFunctions();
118
+ console.log("Functions:", functions.length);
119
+
120
+ // v1.4.0: Get function categories
121
+ const categories = math.getFunctionCategories();
122
+ console.log("Categories:", Object.keys(categories));
123
+
124
+ // v1.4.0: Module metadata
125
+ const metadata = gowm.getModuleMetadata("math");
126
+ console.log(`${metadata.name} v${metadata.version}`);
127
+
128
+ // Load from HTTP URL (uses streaming instantiation when possible)
129
+ const remoteWasm = await gowm.loadFromUrl(
130
+ "https://example.com/module.wasm",
131
+ );
132
+
54
133
  // Load from local file
55
- const localWasm = await load('./math.wasm', { name: 'local-math' });
56
-
57
- // Call functions
58
- const result = math.call('add', 5, 3);
59
- console.log('5 + 3 =', result); // 8
60
-
134
+ const localWasm = await gowm.load("./math.wasm", { name: "local-math" });
135
+
136
+ // Disable cache for a specific load
137
+ const freshLoad = await gowm.load("./module.wasm", { cache: false });
138
+
61
139
  // Async calls
62
- const asyncResult = await math.callAsync('multiply', 4, 7);
63
- console.log('4 * 7 =', asyncResult); // 28
64
-
140
+ const asyncResult = await math.callAsync("multiply", 4, 7);
141
+ console.log("4 * 7 =", asyncResult); // 28
142
+
65
143
  // Check available functions
66
- if (math.hasFunction('divide')) {
67
- console.log('divide function is available');
144
+ if (math.hasFunction("divide")) {
145
+ console.log("divide function is available");
68
146
  }
69
-
70
- // Get module statistics
147
+
148
+ // Get comprehensive statistics
71
149
  const stats = math.getStats();
72
- console.log('Available functions:', stats.functions);
73
-
150
+ console.log("Available functions:", stats.functions);
151
+ console.log("Memory usage:", stats.memoryUsage);
152
+
153
+ // Clear the cache
154
+ await gowm.clearCache();
74
155
  } catch (error) {
75
- console.error('Error:', error);
156
+ console.error("Error:", error);
76
157
  }
77
158
  }
78
159
 
79
160
  example();
80
161
  ```
81
162
 
82
- ### React Integration
163
+ ## ๐Ÿ”„ Loader System
83
164
 
84
- ```jsx
85
- import React, { useState } from 'react';
86
- import { useWasmFromGitHub } from 'gowm/hooks/useWasm';
165
+ GoWM v1.1.0 features a loader system that handles all source types with a single API:
87
166
 
88
- function Calculator() {
89
- const { wasm, loading, error } = useWasmFromGitHub('benoitpetit/wasm-modules-repository', {
90
- path: 'math-wasm',
91
- branch: 'master',
92
- name: 'calculator'
93
- });
94
-
95
- const [result, setResult] = useState(null);
96
-
97
- const calculate = async () => {
98
- if (wasm) {
99
- try {
100
- const sum = await wasm.callAsync('add', 10, 20);
101
- setResult(sum);
102
- } catch (err) {
103
- console.error('Calculation failed:', err);
104
- }
105
- }
106
- };
167
+ ### Auto-Detection
107
168
 
108
- if (loading) return <div>Loading WASM module...</div>;
109
- if (error) return <div>Error: {error.message}</div>;
169
+ ```javascript
170
+ const { load } = require("gowm");
110
171
 
111
- return (
112
- <div>
113
- <button onClick={calculate}>Calculate 10 + 20</button>
114
- {result !== null && <p>Result: {result}</p>}
115
- </div>
116
- );
117
- }
172
+ // Automatically detects source type
173
+ await load("owner/repo"); // โ†’ GitHub repository
174
+ await load("https://example.com/module.wasm"); // โ†’ HTTP URL
175
+ await load("./local/module.wasm"); // โ†’ Local file
176
+ await load("/absolute/path/module.wasm"); // โ†’ Absolute path
118
177
  ```
119
178
 
120
- ### Vue 3 Integration
121
-
122
- ```vue
123
- <template>
124
- <div class="calculator">
125
- <div v-if="loading">Loading WASM module...</div>
126
- <div v-else-if="error" class="error">Error: {{ error.message }}</div>
127
- <div v-else>
128
- <input v-model.number="num1" type="number" placeholder="First number" />
129
- <input v-model.number="num2" type="number" placeholder="Second number" />
130
- <button @click="calculate">Calculate {{ num1 }} + {{ num2 }}</button>
131
- <div v-if="result !== null" class="result">Result: {{ result }}</div>
132
- </div>
133
- </div>
134
- </template>
179
+ ### Specific Loading Methods
135
180
 
136
- <script>
137
- import { ref } from 'vue';
138
- import { useWasmFromGitHub } from 'gowm/composables/useWasm';
139
-
140
- export default {
141
- name: 'Calculator',
142
- setup() {
143
- const { wasm, loading, error } = useWasmFromGitHub('benoitpetit/wasm-modules-repository', {
144
- path: 'math-wasm',
145
- branch: 'master',
146
- name: 'math'
147
- });
148
-
149
- const num1 = ref(10);
150
- const num2 = ref(20);
151
- const result = ref(null);
152
-
153
- const calculate = async () => {
154
- if (wasm.value) {
155
- try {
156
- result.value = await wasm.value.callAsync('add', num1.value, num2.value);
157
- } catch (err) {
158
- console.error('Calculation error:', err);
159
- }
160
- }
161
- };
181
+ ```javascript
182
+ const { loadFromFile, loadFromUrl, loadFromGitHub } = require("gowm");
162
183
 
163
- return { wasm, loading, error, num1, num2, result, calculate };
164
- }
165
- };
166
- </script>
184
+ // Explicit methods for specific sources
185
+ await loadFromFile("./module.wasm"); // Node.js only
186
+ await loadFromUrl("https://example.com/mod.wasm"); // HTTP/HTTPS
187
+ await loadFromGitHub("owner/repo", options); // GitHub repository
167
188
  ```
168
189
 
169
190
  ## ๐Ÿ™ GitHub Repository Loading
170
191
 
171
- GoWM excels at loading WASM modules directly from GitHub repositories with intelligent file discovery:
192
+ GoWM excels at loading WASM modules directly from GitHub repositories with intelligent file discovery and automatic default branch detection:
172
193
 
173
194
  ```javascript
174
- const { loadFromGitHub } = require('gowm');
195
+ const { GoWM } = require("gowm");
196
+ const gowm = new GoWM();
175
197
 
176
198
  async function examples() {
177
- // Basic loading with automatic file discovery
178
- const math = await loadFromGitHub('benoitpetit/wasm-modules-repository', {
179
- path: 'math-wasm',
180
- branch: 'master'
181
- });
182
-
199
+ // Basic loading โ€” branch auto-detected via GitHub API
200
+ const math = await gowm.loadFromGitHub(
201
+ "benoitpetit/wasm-modules-repository",
202
+ {
203
+ path: "math-wasm",
204
+ },
205
+ );
206
+
183
207
  // Advanced loading with specific options
184
- const crypto = await loadFromGitHub('benoitpetit/wasm-modules-repository', {
185
- path: 'crypto-wasm',
186
- filename: 'main.wasm',
187
- branch: 'master',
188
- name: 'crypto-processor'
189
- });
190
-
208
+ const crypto = await gowm.loadFromGitHub(
209
+ "benoitpetit/wasm-modules-repository",
210
+ {
211
+ path: "crypto-wasm",
212
+ filename: "main.wasm",
213
+ name: "crypto-processor",
214
+ timeout: 30000, // Custom timeout
215
+ },
216
+ );
217
+
191
218
  // Load from full GitHub URL
192
- const image = await loadFromGitHub(
193
- 'https://github.com/benoitpetit/wasm-modules-repository',
194
- {
195
- path: 'image-wasm',
196
- filename: 'main.wasm',
197
- branch: 'master'
198
- }
219
+ const image = await gowm.loadFromGitHub(
220
+ "https://github.com/benoitpetit/wasm-modules-repository",
221
+ {
222
+ path: "image-wasm",
223
+ filename: "main.wasm",
224
+ },
199
225
  );
200
226
  }
201
227
  ```
@@ -213,33 +239,62 @@ GoWM automatically searches for WASM files in these locations:
213
239
 
214
240
  ### Core Functions
215
241
 
242
+ #### `load(source, options)`
243
+
244
+ Universal loading function that auto-detects source type.
245
+
246
+ **Parameters:**
247
+
248
+ - `source` (string): Can be file path, HTTP URL, or GitHub repo
249
+ - `options` (object, optional):
250
+ - `name` (string): Module identifier
251
+ - `timeout` (number): Initialization timeout (default: 15000ms)
252
+ - `preInit` (boolean): Pre-initialize module (default: true)
253
+ - `goRuntimePath` (string): Custom path to wasm_exec.js
254
+
255
+ **Returns:** Promise<WasmBridge>
256
+
216
257
  #### `loadFromGitHub(githubRepo, options)`
217
258
 
218
259
  Loads a WASM module from a GitHub repository with automatic file resolution.
219
260
 
220
261
  **Parameters:**
262
+
221
263
  - `githubRepo` (string): GitHub repository ("owner/repo" or full GitHub URL)
222
264
  - `options` (object, optional):
223
265
  - `name` (string): Module identifier (default: repository name)
224
- - `branch` (string): Git branch (default: 'master')
266
+ - `branch` (string): Git branch (default: auto-detected via GitHub API)
225
267
  - `tag` (string): Git tag (takes precedence over branch)
226
268
  - `path` (string): Path within repository (default: '')
227
269
  - `filename` (string): Specific filename (default: auto-detect)
270
+ - `timeout` (number): Initialization timeout (default: 15000ms)
228
271
  - `goRuntimePath` (string): Custom path to wasm_exec.js
229
272
  - `preInit` (boolean): Pre-initialize the module (default: true)
273
+ - `metadata` (boolean): Fetch module.json metadata (default: true) _(v1.4.0)_
274
+ - `integrity` (boolean): Verify SHA256 integrity (default: true) _(v1.4.0)_
275
+ - `validateCalls` (boolean): Validate function parameters (default: true) _(v1.4.0)_
230
276
 
231
277
  **Returns:** Promise<WasmBridge>
232
278
 
233
- #### `load(wasmPath, options)`
279
+ #### `loadFromUrl(url, options)`
234
280
 
235
- Loads a WASM module from a local file or URL.
281
+ Loads a WASM module from HTTP/HTTPS URL.
236
282
 
237
283
  **Parameters:**
238
- - `wasmPath` (string): Path to the .wasm file or URL
239
- - `options` (object, optional):
240
- - `name` (string): Module identifier (default: 'default')
241
- - `goRuntimePath` (string): Custom path to wasm_exec.js
242
- - `preInit` (boolean): Pre-initialize the module (default: true)
284
+
285
+ - `url` (string): HTTP/HTTPS URL to WASM file
286
+ - `options` (object, optional): Same as `load()` options
287
+
288
+ **Returns:** Promise<WasmBridge>
289
+
290
+ #### `loadFromFile(filePath, options)`
291
+
292
+ Loads a WASM module from local file (Node.js only).
293
+
294
+ **Parameters:**
295
+
296
+ - `filePath` (string): Path to the .wasm file
297
+ - `options` (object, optional): Same as `load()` options
243
298
 
244
299
  **Returns:** Promise<WasmBridge>
245
300
 
@@ -248,58 +303,97 @@ Loads a WASM module from a local file or URL.
248
303
  Retrieves an already loaded module by name.
249
304
 
250
305
  **Parameters:**
251
- - `name` (string, optional): Module name (default: 'default')
252
306
 
253
- **Returns:** WasmBridge | null
307
+ - `name` (string, optional): Module name (default: 'default')
254
308
 
255
- ### WasmBridge Methods
309
+ **Returns:** UnifiedWasmBridge | null
256
310
 
257
- #### `call(funcName, ...args)`
311
+ ### Enhanced Bridge Methods
258
312
 
259
- Calls a WASM function synchronously.
313
+ The bridge provides comprehensive functionality:
260
314
 
261
- **Parameters:**
262
- - `funcName` (string): Name of the function to call
263
- - `...args`: Function arguments
315
+ #### `call(funcName, ...args)`
264
316
 
265
- **Returns:** Function result
317
+ Calls a WASM function synchronously. In v1.4.0, validates parameter count and types (debug mode) against module.json metadata.
266
318
 
267
319
  #### `callAsync(funcName, ...args)`
268
320
 
269
321
  Calls a WASM function asynchronously.
270
322
 
271
- **Parameters:**
272
- - `funcName` (string): Name of the function to call
273
- - `...args`: Function arguments
323
+ #### `describe(funcName)` _(v1.4.0)_
274
324
 
275
- **Returns:** Promise<Function result>
325
+ Returns inline documentation for a function from module.json metadata.
276
326
 
277
- #### `hasFunction(funcName)`
327
+ **Returns:** `{ name, description, category, parameters, returnType, example, errorPattern }` or `null`
278
328
 
279
- Checks if a function exists in the WASM module.
329
+ #### `getDetailedFunctions()` _(v1.4.0)_
280
330
 
281
- **Parameters:**
282
- - `funcName` (string): Function name to check
331
+ Returns all functions with their full metadata (parameters, types, descriptions).
283
332
 
284
- **Returns:** boolean
333
+ **Returns:** `Array<{ name, description, category, parameters, returnType, example }>`
285
334
 
286
- #### `getAvailableFunctions()`
335
+ #### `getMetadata()` _(v1.4.0)_
287
336
 
288
- Gets a list of all available functions in the module.
337
+ Returns the raw module.json metadata object.
289
338
 
290
- **Returns:** string[]
339
+ #### `getFunctionCategories()` _(v1.4.0)_
291
340
 
292
- #### `getStats()`
341
+ Returns function categories from metadata.
342
+
343
+ **Returns:** `{ [category: string]: string[] }` or `null`
344
+
345
+ #### `createBuffer(data)`
346
+
347
+ Creates a buffer for data transfer with enhanced type support.
293
348
 
294
- Gets module statistics and information.
349
+ **Supported Types:**
295
350
 
296
- **Returns:** Object with module statistics
351
+ - `Float64Array`, `Float32Array`
352
+ - `Uint8Array`, `Uint16Array`, `Uint32Array`
353
+ - `Int8Array`, `Int16Array`, `Int32Array`
354
+ - `Array`, `string`
297
355
 
298
- #### `cleanup()`
356
+ #### `test()`
299
357
 
300
- Manually clean up module resources.
358
+ Runs comprehensive tests on the module.
301
359
 
302
- **Returns:** void
360
+ **Returns:** Object with test results:
361
+
362
+ ```javascript
363
+ {
364
+ functionCalls: boolean,
365
+ memoryAllocation: boolean,
366
+ callbacks: boolean,
367
+ asyncCalls: boolean,
368
+ errors: string[]
369
+ }
370
+ ```
371
+
372
+ #### `getStats()`
373
+
374
+ Gets comprehensive module statistics.
375
+
376
+ **Returns:** Object with detailed statistics:
377
+
378
+ ```javascript
379
+ {
380
+ name: string,
381
+ ready: boolean,
382
+ environment: 'Node.js' | 'Browser',
383
+ functions: string[],
384
+ callbacks: string[],
385
+ allocatedBuffers: number,
386
+ memoryUsage: {
387
+ total: number,
388
+ wasm: number,
389
+ go: number,
390
+ buffers: number,
391
+ buffersCount: number
392
+ },
393
+ supportedDataTypes: string[],
394
+ loadedAt: string
395
+ }
396
+ ```
303
397
 
304
398
  ### Utility Functions
305
399
 
@@ -309,153 +403,287 @@ Manually clean up module resources.
309
403
  - `unloadAll()`: Unload all modules
310
404
  - `isLoaded(name)`: Check if a module is loaded
311
405
  - `getTotalMemoryUsage()`: Get total memory usage
406
+ - `testAll()`: Test all loaded modules
407
+ - `getHelp()`: Get comprehensive help information
408
+ - `getVersion()`: Get GoWM version string
409
+ - `clearCache()`: Clear all cached WASM bytes _(v1.3.0)_
410
+ - `getModuleMetadata(name)`: Get module.json metadata _(v1.4.0)_
411
+ - `describeFunction(moduleName, funcName)`: Describe a function from metadata _(v1.4.0)_
412
+ - `on(event, callback)`: Register event listener _(v1.1.1)_
413
+ - `off(event, callback)`: Remove event listener _(v1.1.1)_
414
+ - `once(event, callback)`: One-time event listener _(v1.1.1)_
415
+ - `generateTypes(metadata, options)`: Generate TypeScript types _(v1.1.1)_
416
+ - `generateTypesFromGitHub(repo, options)`: Generate types from GitHub _(v1.1.1)_
312
417
 
313
- ## โš›๏ธ React Hooks
418
+ ## ๐ŸŒ Browser Usage
314
419
 
315
- ### `useWasm(wasmPath, options)`
420
+ For browser environments, GoWM automatically optimizes for the browser:
316
421
 
317
- Hook for loading local WASM modules.
422
+ ```html
423
+ <!DOCTYPE html>
424
+ <html>
425
+ <head>
426
+ <script type="module">
427
+ import { loadFromGitHub } from "./node_modules/gowm/src/browser.js";
428
+
429
+ async function init() {
430
+ const wasm = await loadFromGitHub(
431
+ "benoitpetit/wasm-modules-repository",
432
+ {
433
+ path: "math-wasm",
434
+ },
435
+ );
436
+ const result = wasm.call("add", 21, 21);
437
+ console.log("21 + 21 =", result); // 42
438
+ }
318
439
 
319
- ```jsx
320
- import { useWasm } from 'gowm/hooks/useWasm';
440
+ init();
441
+ </script>
442
+ </head>
443
+ <body>
444
+ <h1>GoWM Browser Example</h1>
445
+ </body>
446
+ </html>
447
+ ```
321
448
 
322
- function MyComponent() {
323
- const { wasm, loading, error } = useWasm('./my-module.wasm', {
324
- name: 'myModule'
325
- });
449
+ ### Global Usage
326
450
 
327
- // Use wasm when loaded
328
- }
451
+ ```html
452
+ <script src="path/to/gowm/src/browser.js"></script>
453
+ <script>
454
+ GoWM.loadFromUrl("https://example.com/module.wasm");
455
+ </script>
329
456
  ```
330
457
 
331
- ### `useWasmFromGitHub(githubRepo, options)`
458
+ ## ๐Ÿ“ก Event System _(v1.1.1)_
332
459
 
333
- Hook for loading WASM modules from GitHub repositories.
460
+ Monitor module lifecycle with event listeners:
334
461
 
335
- ```jsx
336
- import { useWasmFromGitHub } from 'gowm/hooks/useWasm';
462
+ ```javascript
463
+ const gowm = new GoWM({ memoryWarningThreshold: 50 * 1024 * 1024 });
464
+
465
+ gowm
466
+ .on("module:loading", ({ name, source }) => console.log(`Loading ${name}...`))
467
+ .on("module:loaded", ({ name, loadTime }) =>
468
+ console.log(`Loaded in ${loadTime}ms`),
469
+ )
470
+ .on("module:error", ({ name, error }) =>
471
+ console.error(`Failed: ${error.message}`),
472
+ )
473
+ .on("module:unloaded", ({ name }) => console.log(`Unloaded ${name}`))
474
+ .on("memory:warning", ({ totalMemory, threshold }) =>
475
+ console.warn("Memory warning!"),
476
+ );
337
477
 
338
- function MyComponent() {
339
- const { wasm, loading, error } = useWasmFromGitHub('benoitpetit/wasm-modules-repository', {
340
- path: 'math-wasm',
341
- branch: 'master',
342
- name: 'myModule'
343
- });
344
- }
478
+ // One-time listener
479
+ gowm.once("module:loaded", ({ name }) =>
480
+ console.log(`First module loaded: ${name}`),
481
+ );
482
+
483
+ // Remove listener
484
+ const handler = (data) => console.log(data);
485
+ gowm.on("module:loaded", handler);
486
+ gowm.off("module:loaded", handler);
345
487
  ```
346
488
 
347
- ### `useMultipleWasmFromGitHub(githubRepos, options)`
489
+ ## โš›๏ธ React Hooks _(v1.1.1)_
348
490
 
349
- Hook for loading multiple WASM modules from GitHub repositories.
491
+ ```bash
492
+ npm install gowm react
493
+ ```
350
494
 
351
- ```jsx
352
- import { useMultipleWasmFromGitHub } from 'gowm/hooks/useWasm';
495
+ ```tsx
496
+ import { useWasm, useWasmFromGitHub } from "gowm/react";
353
497
 
354
- function MyComponent() {
355
- const { modules, loading, errors, reload } = useMultipleWasmFromGitHub([
356
- { name: 'math', repo: 'benoitpetit/wasm-modules-repository', path: 'math-wasm' },
357
- { name: 'crypto', repo: 'benoitpetit/wasm-modules-repository', path: 'crypto-wasm', branch: 'master' }
358
- ]);
498
+ function Calculator() {
499
+ const { bridge, loading, error, reload } = useWasmFromGitHub(
500
+ "benoitpetit/wasm-modules-repository",
501
+ { path: "math-wasm" },
502
+ );
503
+
504
+ if (loading) return <p>Loading...</p>;
505
+ if (error) return <p>Error: {error.message}</p>;
506
+
507
+ return (
508
+ <div>
509
+ <p>5 + 3 = {bridge.call("add", 5, 3)}</p>
510
+ <button onClick={reload}>Reload</button>
511
+ </div>
512
+ );
359
513
  }
360
514
  ```
361
515
 
362
- ## ๐Ÿ–– Vue 3 Composables
516
+ ## ๐Ÿ’š Vue 3 Composables _(v1.1.1)_
363
517
 
364
- ### `useWasm(wasmPath, options)`
365
-
366
- Composable for loading local WASM modules.
518
+ ```bash
519
+ npm install gowm vue
520
+ ```
367
521
 
368
522
  ```vue
369
- <script>
370
- import { useWasm } from 'gowm/composables/useWasm';
523
+ <script setup>
524
+ import { useWasmFromGitHub } from "gowm/vue";
371
525
 
372
- export default {
373
- setup() {
374
- const { wasm, loading, error, reload } = useWasm('./my-module.wasm');
375
- return { wasm, loading, error, reload };
376
- }
377
- }
526
+ const { bridge, loading, error, metadata, reload } = useWasmFromGitHub(
527
+ "benoitpetit/wasm-modules-repository",
528
+ { path: "math-wasm" },
529
+ );
378
530
  </script>
531
+
532
+ <template>
533
+ <p v-if="loading">Loading...</p>
534
+ <p v-else-if="error">Error: {{ error.message }}</p>
535
+ <div v-else>
536
+ <p>{{ metadata?.name }} v{{ metadata?.version }}</p>
537
+ <p>5 + 3 = {{ bridge.call("add", 5, 3) }}</p>
538
+ <button @click="reload">Reload</button>
539
+ </div>
540
+ </template>
379
541
  ```
380
542
 
381
- ### `useWasmFromGitHub(githubRepo, options)`
543
+ ## ๐Ÿ”ง CLI _(v1.1.1)_
382
544
 
383
- Composable for loading WASM modules from GitHub repositories.
545
+ ```bash
546
+ # List available modules in a repository
547
+ npx gowm list benoitpetit/wasm-modules-repository
384
548
 
385
- ```vue
386
- <script>
387
- import { useWasmFromGitHub } from 'gowm/composables/useWasm';
388
-
389
- export default {
390
- setup() {
391
- const { wasm, loading, error } = useWasmFromGitHub('benoitpetit/wasm-modules-repository', {
392
- path: 'math-wasm',
393
- branch: 'master'
394
- });
395
- return { wasm, loading, error };
396
- }
397
- }
398
- </script>
549
+ # Get module info from module.json
550
+ npx gowm info benoitpetit/wasm-modules-repository math-wasm
551
+
552
+ # Generate TypeScript types from module.json
553
+ npx gowm types benoitpetit/wasm-modules-repository math-wasm --out math-wasm.d.ts
554
+
555
+ # Verify WASM file integrity
556
+ npx gowm verify ./main.wasm --integrity sha256-xxxxxxxxx
557
+
558
+ # Download a module (wasm + module.json + integrity)
559
+ npx gowm install benoitpetit/wasm-modules-repository math-wasm --dir ./wasm
399
560
  ```
400
561
 
401
- ### `useMultipleWasm(modules)`
562
+ ## ๐Ÿ—๏ธ Type Generator _(v1.1.1)_
402
563
 
403
- Composable for loading multiple WASM modules.
564
+ Generate TypeScript interfaces from `module.json`:
404
565
 
405
- ```vue
406
- <script>
407
- import { useMultipleWasm } from 'gowm/composables/useWasm';
408
-
409
- export default {
410
- setup() {
411
- const { modules, loading, errors } = useMultipleWasm([
412
- { name: 'local', path: './local.wasm' },
413
- { name: 'github', github: 'benoitpetit/wasm-modules-repository', path: 'math-wasm' }
414
- ]);
415
- return { modules, loading, errors };
416
- }
566
+ ```javascript
567
+ const { generateTypes, generateTypesFromGitHub } = require("gowm");
568
+
569
+ // From a metadata object
570
+ const ts = generateTypes(metadata, { includeJSDoc: true });
571
+
572
+ // From GitHub
573
+ const ts = await generateTypesFromGitHub(
574
+ "benoitpetit/wasm-modules-repository/math-wasm",
575
+ { branch: "master" },
576
+ );
577
+ ```
578
+
579
+ Generated output:
580
+
581
+ ```typescript
582
+ import { WasmBridge } from "gowm";
583
+
584
+ /** math-wasm v0.2.0 - Mathematical functions */
585
+ export interface MathWasmBridge extends WasmBridge {
586
+ /** Add two numbers */
587
+ call(func: "add", a: number, b: number): number;
588
+ /** Calculate factorial */
589
+ call(func: "factorial", n: number): number;
590
+ // ...
417
591
  }
418
- </script>
419
592
  ```
420
593
 
421
- ## ๐ŸŒ Browser Usage
594
+ ## ๐Ÿ—๏ธ Architecture
422
595
 
423
- For browser environments, use the ES6 module version:
596
+ GoWM v1.1.1 features a clean architecture:
424
597
 
425
- ```html
426
- <!DOCTYPE html>
427
- <html>
428
- <head>
429
- <script type="module">
430
- import { loadFromGitHub } from './node_modules/gowm/src/browser.js';
431
-
432
- async function init() {
433
- const wasm = await loadFromGitHub('benoitpetit/wasm-modules-repository', {
434
- path: 'math-wasm',
435
- branch: 'master'
436
- });
437
- const result = wasm.call('add', 21, 21);
438
- console.log('21 + 21 =', result); // 42
439
- }
440
-
441
- init();
442
- </script>
443
- </head>
444
- <body>
445
- <h1>GoWM Browser Example</h1>
446
- </body>
447
- </html>
598
+ ```
599
+ src/
600
+ โ”œโ”€โ”€ core/gowm.js # Main GoWM class (events, logging)
601
+ โ”œโ”€โ”€ loaders/unified-loader.js # Universal loading system with metadata & integrity
602
+ โ”œโ”€โ”€ bridges/unified-bridge.js # Namespace-aware bridge with validation & describe()
603
+ โ”œโ”€โ”€ react/index.js # React hooks (useWasm, useWasmFromGitHub)
604
+ โ”œโ”€โ”€ vue/index.js # Vue 3 composables (useWasm, useWasmFromGitHub)
605
+ โ”œโ”€โ”€ cli/gowm-cli.js # CLI (list, info, types, verify, install)
606
+ โ”œโ”€โ”€ tools/type-generator.js # TypeScript type generation from module.json
607
+ โ”œโ”€โ”€ index.js # Main entry point
608
+ โ””โ”€โ”€ browser.js # Browser-optimized entry
609
+ types/
610
+ โ”œโ”€โ”€ index.d.ts # Core TypeScript definitions
611
+ โ”œโ”€โ”€ react.d.ts # React hooks types
612
+ โ””โ”€โ”€ vue.d.ts # Vue composables types
448
613
  ```
449
614
 
615
+ ### Key Improvements in v1.1.1
616
+
617
+ - **Event System**: `on()` / `off()` / `once()` for module lifecycle events with memory warnings
618
+ - **React Hooks**: `useWasm()` and `useWasmFromGitHub()` with auto-cleanup
619
+ - **Vue 3 Composables**: Reactive refs with `watch()` support and auto-cleanup
620
+ - **CLI**: 5 commands for module discovery, inspection, type generation, integrity, and installation
621
+ - **Type Generator**: Generate TypeScript interfaces from `module.json` metadata
622
+ - **ESM Exports Map**: Sub-path exports for `gowm/react`, `gowm/vue`, `gowm/tools/type-generator`
623
+ - **274 Unit Tests**: Extended test coverage for all features
624
+
450
625
  ## ๐Ÿ“Š Examples
451
626
 
452
627
  Check out the `/examples` directory for comprehensive examples:
453
628
 
454
- - **Node.js examples**: Basic and advanced usage patterns
455
- - **React examples**: Complete React applications with hooks
456
- - **Vue examples**: Vue 3 application templates with composables
629
+ - **Node.js examples**: Basic, crypto, text, and JSON/XML usage patterns
457
630
  - **Browser examples**: Vanilla JavaScript implementations
458
631
 
632
+ ### Running Examples
633
+
634
+ ```bash
635
+ # Run basic Node.js example
636
+ npm run test:basic
637
+
638
+ # Run crypto example
639
+ npm run test:crypto
640
+
641
+ # Serve browser examples
642
+ npm run demo:serve
643
+ ```
644
+
645
+ ## ๐Ÿ”ง Development
646
+
647
+ ### Running Tests
648
+
649
+ ```bash
650
+ # Run all unit tests
651
+ npm test
652
+
653
+ # Run tests with coverage report
654
+ npm run test:coverage
655
+
656
+ # Run all tests (unit + integration + examples)
657
+ npm run test:all
658
+ ```
659
+
660
+ ### Testing Your Modules
661
+
662
+ ```javascript
663
+ const { GoWM } = require("gowm");
664
+ const gowm = new GoWM({ logLevel: "debug" });
665
+
666
+ // Load and test a module
667
+ const module = await gowm.load("your-module.wasm");
668
+ const testResults = module.test();
669
+ console.log("Test results:", testResults);
670
+
671
+ // Get comprehensive statistics
672
+ const stats = gowm.getStats();
673
+ console.log("System stats:", stats);
674
+ ```
675
+
676
+ ### Custom Loading
677
+
678
+ ```javascript
679
+ const { WasmLoader, WasmBridge } = require("gowm");
680
+
681
+ // Use components directly for advanced scenarios
682
+ const loader = new WasmLoader();
683
+ const module = await loader.loadModule("source");
684
+ const bridge = new WasmBridge(module, { moduleId: "my-module" });
685
+ ```
686
+
459
687
  ## ๐Ÿ“„ License
460
688
 
461
689
  MIT License - see the [LICENSE](LICENSE) file for details.