jz 0.0.0 → 0.1.0

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/wasi.js ADDED
@@ -0,0 +1,74 @@
1
+ /**
2
+ * WASI Preview 1 polyfill for jz modules.
3
+ *
4
+ * Provides wasi_snapshot_preview1 imports for environments without native WASI.
5
+ * The compiled .wasm uses standard WASI — runs natively on wasmtime/wasmer/deno.
6
+ * This polyfill is only needed for browsers and plain Node.
7
+ *
8
+ * @example
9
+ * import { instantiate } from 'jz/wasi'
10
+ * const inst = instantiate(wasm)
11
+ * inst.exports.f()
12
+ *
13
+ * @module wasi
14
+ */
15
+
16
+ /**
17
+ * Create WASI import object for WebAssembly instantiation.
18
+ * @param {object} [opts]
19
+ * @param {function} [opts.write] - Custom write: (fd, text) => void
20
+ */
21
+ export function wasi(opts = {}) {
22
+ let mem = null
23
+ const write = opts.write || ((fd, text) => {
24
+ if (fd === 1) typeof process !== 'undefined' && process.stdout ? process.stdout.write(text) : console.log(text.replace(/\n$/, ''))
25
+ else typeof process !== 'undefined' && process.stderr ? process.stderr.write(text) : console.warn(text.replace(/\n$/, ''))
26
+ })
27
+
28
+ return {
29
+ wasi_snapshot_preview1: {
30
+ fd_write(fd, iovs, iovs_len, nwritten) {
31
+ const dv = new DataView(mem.buffer)
32
+ let written = 0
33
+ for (let i = 0; i < iovs_len; i++) {
34
+ const ptr = dv.getUint32(iovs + i * 8, true)
35
+ const len = dv.getUint32(iovs + i * 8 + 4, true)
36
+ write(fd, new TextDecoder().decode(new Uint8Array(mem.buffer, ptr, len)))
37
+ written += len
38
+ }
39
+ dv.setUint32(nwritten, written, true)
40
+ return 0
41
+ },
42
+ clock_time_get(clock_id, precision, result_ptr) {
43
+ const dv = new DataView(mem.buffer)
44
+ const now = clock_id === 0
45
+ ? BigInt(Math.round(Date.now() * 1e6)) // realtime: ms → ns
46
+ : BigInt(Math.round(performance.now() * 1e6)) // monotonic: ms → ns
47
+ dv.setBigInt64(result_ptr, now, true)
48
+ return 0
49
+ },
50
+ proc_exit() {},
51
+ environ_sizes_get(count_ptr, size_ptr) {
52
+ const dv = new DataView(mem.buffer)
53
+ dv.setUint32(count_ptr, 0, true)
54
+ dv.setUint32(size_ptr, 0, true)
55
+ return 0
56
+ },
57
+ environ_get() { return 0 },
58
+ },
59
+ _setMemory(m) { mem = m },
60
+ }
61
+ }
62
+
63
+ /**
64
+ * Compile and instantiate a jz WASI module.
65
+ * @param {BufferSource} wasm
66
+ * @param {object} [opts] - Options passed to wasi()
67
+ * @returns {WebAssembly.Instance}
68
+ */
69
+ export function instantiate(wasm, opts = {}) {
70
+ const imports = wasi(opts)
71
+ const inst = new WebAssembly.Instance(new WebAssembly.Module(wasm), imports)
72
+ imports._setMemory(inst.exports.memory)
73
+ return inst
74
+ }