add WASM browser module and browser demo
This commit is contained in:
66
browser/host/platform-env.js
Normal file
66
browser/host/platform-env.js
Normal file
@@ -0,0 +1,66 @@
|
||||
/**
|
||||
* Platform environment — provides extern "env" functions for the WASM module.
|
||||
*
|
||||
* These map directly to the `extern "env" fn js_*` declarations in the Zig
|
||||
* platform abstraction layer (src/platform/time.zig, random.zig, etc.).
|
||||
*/
|
||||
|
||||
/**
|
||||
* Create the env import object for WASM instantiation.
|
||||
* @param {() => WebAssembly.Memory} getMemory - Returns the WASM memory instance
|
||||
* @returns {Record<string, Function>} env imports
|
||||
*/
|
||||
export function createPlatformEnv(getMemory) {
|
||||
return {
|
||||
// -- Time (src/platform/time.zig) --
|
||||
|
||||
/** @returns {bigint} milliseconds since epoch */
|
||||
js_timestamp_ms() {
|
||||
return BigInt(Date.now());
|
||||
},
|
||||
|
||||
/** @returns {bigint} nanoseconds since epoch (ms precision in browser) */
|
||||
js_timestamp_ns() {
|
||||
return BigInt(Date.now()) * 1_000_000n;
|
||||
},
|
||||
|
||||
// -- Random (src/platform/random.zig) --
|
||||
|
||||
/** Fill buffer with cryptographically secure random bytes */
|
||||
js_random_bytes(ptr, len) {
|
||||
const bytes = new Uint8Array(getMemory().buffer, ptr, len);
|
||||
crypto.getRandomValues(bytes);
|
||||
},
|
||||
|
||||
// -- Logging (src/wasm/main.zig) --
|
||||
|
||||
/** Log a message from WASM to the browser console */
|
||||
js_log(ptr, len) {
|
||||
const bytes = new Uint8Array(getMemory().buffer, ptr, len);
|
||||
const msg = new TextDecoder().decode(bytes);
|
||||
console.log('[zig-p2p]', msg);
|
||||
},
|
||||
|
||||
// -- WebRTC DataChannel (src/platform/webrtc_wasm.zig) --
|
||||
// These are called by the WASM transport when sending data.
|
||||
// They are wired to the WebRTCHost by zig-p2p.js during initialization.
|
||||
|
||||
/** Send data on a DataChannel. Returns 0 on success, -1 on error. */
|
||||
js_datachannel_send(channelId, dataPtr, dataLen) {
|
||||
// Overridden by zig-p2p.js to route to WebRTCHost
|
||||
console.warn('[zig-p2p] js_datachannel_send called before WebRTCHost wired');
|
||||
return -1;
|
||||
},
|
||||
|
||||
/** Close a DataChannel */
|
||||
js_datachannel_close(channelId) {
|
||||
// Overridden by zig-p2p.js to route to WebRTCHost
|
||||
},
|
||||
|
||||
/** Get buffered amount for a DataChannel */
|
||||
js_datachannel_buffered_amount(channelId) {
|
||||
// Overridden by zig-p2p.js to route to WebRTCHost
|
||||
return 0;
|
||||
},
|
||||
};
|
||||
}
|
||||
Reference in New Issue
Block a user