@hunghg255/napi-zig-cli 1.5.0 → 1.7.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/README.md CHANGED
@@ -27,4 +27,37 @@ Project configuration lives in `package.json`:
27
27
  }
28
28
  ```
29
29
 
30
+ `artifacts` writes one package per target under `npm/<target>/`, listed as
31
+ `optionalDependencies` of the main package, and the generated `index.js`
32
+ loads the one that fits the machine. The WebAssembly targets are packaged
33
+ too: `npm/wasm32-wasi/` holds `<name>.wasm32-wasi.wasm` and the loader
34
+ `<name>.wasm32-wasi.cjs` (its `main`), depends on `@emnapi/core` and
35
+ `@emnapi/runtime`, and installs on every platform; `wasm32-wasi-threads`
36
+ adds a worker script and `@emnapi/wasi-threads`. `index.js` tries the native
37
+ binary for the platform first, then `wasm32-wasi-threads`, then
38
+ `wasm32-wasi`. The threaded loader reads the shared memory's bounds
39
+ (`wasm_initial_memory` / `wasm_max_memory` in `build.zig`) from the module
40
+ itself; `"napi": { "wasm": { "initialMemory": ..., "maxMemory": ... } }`
41
+ (bytes) still overrides them, but is no longer needed (1.7).
42
+
43
+ Browsers and bundlers (1.7, experimental): each wasm package also carries
44
+ `<name>.<target>.browser.mjs`, an ES module that fetches the `.wasm` with
45
+ `new URL('./<file>.wasm', import.meta.url)` (which webpack, Vite, Rollup and
46
+ Parcel turn into an asset), instantiates it on import and exports
47
+ `load(options)` for more instances (`wasm`, `wasi`, `context`; threaded also
48
+ `memory`, `reuseWorker`, `onCreateWorker`). The package's `exports` map
49
+ sends Node.js, Bun and Deno (condition `node`) to the CommonJS loader and
50
+ browsers and bundlers (`browser`, `import`) to the ES module. A minimal
51
+ WASI (console, clocks, random bytes, no files) is built in; pass a full one
52
+ as `wasi` if the addon needs it. The threaded flavour starts each thread as
53
+ a module worker (`<name>.<target>.browser-worker.mjs`), needs
54
+ `SharedArrayBuffer` - serve the page with `Cross-Origin-Opener-Policy:
55
+ same-origin` and `Cross-Origin-Embedder-Policy: require-corp` - and should
56
+ be imported in a worker, as the page's main thread may not block. New
57
+ projects get a `browser.mjs` that re-exports the `wasm32-wasi` package and
58
+ an `exports` map that keeps Node.js on `index.js`. Tested in Chromium
59
+ without a bundler; no bundler is tested yet (esbuild does not handle
60
+ `new Worker(new URL(...))`, so the threaded flavour needs a bundler that
61
+ does, or `load({ onCreateWorker })`).
62
+
30
63
  The `zig` executable is taken from `PATH` (override with `NAPI_ZIG_ZIG`).
package/bin/napi-zig.mjs CHANGED
@@ -25,11 +25,14 @@ Usage:
25
25
  --glibc <ver> minimum glibc for *-gnu targets (default 2.28)
26
26
  --dynamic-host resolve Node-API at load time (Electron, renamed hosts)
27
27
  The target darwin-universal merges darwin-x64 and darwin-arm64 into one
28
- file; wasm32-wasi is experimental.
28
+ file. wasm32-wasi and wasm32-wasi-threads write <name>.<target>.wasm
29
+ plus the <name>.<target>.cjs that loads it through emnapi.
29
30
 
30
31
  napi-zig artifacts [--target <id>]...
31
32
  Create npm/<target>/ packages for the built binaries and list them as
32
- optionalDependencies in package.json.
33
+ optionalDependencies in package.json. A wasm target's package carries
34
+ the .wasm and its loader and depends on emnapi; the generated index.js
35
+ falls back to it where no native binary fits.
33
36
 
34
37
  napi-zig publish [--dry-run] [--tag <tag>] [--otp <code>] [--provenance] [--access <a>]
35
38
  Verify the npm/<target>/ packages, then "npm publish" each of them and
@@ -112,8 +115,8 @@ function main() {
112
115
  case 'targets':
113
116
  for (const target of TARGETS) {
114
117
  const how = target.merge ? `(${target.merge.join(' + ')})` : target.zig
115
- const notes = [target.id === hostTargetId() && 'host', target.experimental && 'experimental'].filter(Boolean)
116
- console.log(`${target.id.padEnd(18)} ${how}${notes.length ? ` [${notes.join(', ')}]` : ''}`)
118
+ const notes = [target.id === hostTargetId() && 'host', target.wasm && 'any platform, through emnapi'].filter(Boolean)
119
+ console.log(`${target.id.padEnd(20)} ${how}${notes.length ? ` [${notes.join(', ')}]` : ''}`)
117
120
  }
118
121
  break
119
122
  default:
package/lib/artifacts.mjs CHANGED
@@ -2,12 +2,19 @@ import { copyFileSync, existsSync, mkdirSync, writeFileSync } from 'node:fs'
2
2
  import { join, resolve } from 'node:path'
3
3
  import { loadProject } from './project.mjs'
4
4
  import { binaryName, findTarget } from './targets.mjs'
5
+ import { EMNAPI_DEPENDENCIES, EMNAPI_THREADS_DEPENDENCIES, wasmLoaderFiles, wasmPackageEntries } from './wasm.mjs'
5
6
 
6
7
  /** The npm package that carries the binary of one target. */
7
8
  export function platformPackageName(pkg, id) {
8
9
  return `${pkg.name}-${id}`
9
10
  }
10
11
 
12
+ /** The files of a target's package: the binary, then a wasm loader. */
13
+ export function packageFiles(project, target) {
14
+ const binary = binaryName(project.addonName, target)
15
+ return target.wasm ? [binary, ...Object.keys(wasmLoaderFiles(project, target))] : [binary]
16
+ }
17
+
11
18
  /**
12
19
  * Lays out one npm package per platform under `npm/<target>/`, the way
13
20
  * prebuilt native addons are usually published:
@@ -17,6 +24,19 @@ export function platformPackageName(pkg, id) {
17
24
  *
18
25
  * and lists them as optionalDependencies of the main package, so that
19
26
  * `npm install` downloads only the binary matching the user's machine.
27
+ *
28
+ * A WebAssembly target's package fits every machine (no `os` or `cpu`):
29
+ * it holds the `.wasm`, the Node.js loader that is its `main` and its
30
+ * "node" export, the browser loader (an ES module) that is its "browser"
31
+ * export (and, threaded, the worker script of each), and depends on
32
+ * emnapi. The generated index.js falls back to it where no native package
33
+ * fits; the generated browser.mjs imports it.
34
+ *
35
+ * npm/wasm32-wasi/package.json { main: "<name>.wasm32-wasi.cjs", exports: { node, browser, ... },
36
+ * dependencies: { "@emnapi/core", ... } }
37
+ * npm/wasm32-wasi/<name>.wasm32-wasi.wasm
38
+ * npm/wasm32-wasi/<name>.wasm32-wasi.cjs
39
+ * npm/wasm32-wasi/<name>.wasm32-wasi.browser.mjs
20
40
  */
21
41
  export function artifacts(options) {
22
42
  const project = loadProject(resolve(options.cwd ?? '.'))
@@ -35,12 +55,13 @@ export function artifacts(options) {
35
55
  const platformPackage = {
36
56
  name: platformPackageName(pkg, id),
37
57
  version: pkg.version,
38
- description: `${pkg.name} prebuilt binary for ${id}`,
58
+ description: `${pkg.name} prebuilt ${target.wasm ? 'WebAssembly build' : 'binary'} for ${id}`,
39
59
  ...(target.os ? { os: [target.os] } : {}),
40
60
  ...(target.cpu ? { cpu: target.cpu } : {}),
41
61
  ...(target.libc ? { libc: [target.libc] } : {}),
42
- main: binary,
43
- files: [binary],
62
+ ...(target.wasm ? wasmPackageEntries(addonName, target) : { main: binary }),
63
+ files: packageFiles(project, target),
64
+ ...(target.wasm ? { dependencies: target.threads ? EMNAPI_THREADS_DEPENDENCIES : EMNAPI_DEPENDENCIES } : {}),
44
65
  license: pkg.license,
45
66
  repository: pkg.repository,
46
67
  ...(pkg.publishConfig ? { publishConfig: pkg.publishConfig } : {}),
@@ -50,6 +71,10 @@ export function artifacts(options) {
50
71
  const source = join(project.dir, binary)
51
72
  if (existsSync(source)) copyFileSync(source, join(dir, binary))
52
73
  else missing.push(binary)
74
+ // (Generated afresh: they only depend on the project.)
75
+ if (target.wasm) {
76
+ for (const [name, text] of Object.entries(wasmLoaderFiles(project, target))) writeFileSync(join(dir, name), text)
77
+ }
53
78
  created.push(dir)
54
79
  }
55
80
 
@@ -0,0 +1,100 @@
1
+ // A minimal WASI (preview 1) for browsers, used by the browser loaders that
2
+ // `napi-zig build` writes for WebAssembly targets.
3
+ //
4
+ // napi-zig modules import nothing from WASI unless the addon itself does
5
+ // I/O through the standard library (printing, randomness, clocks); this
6
+ // gives such an addon a console for stdout/stderr, the clocks, random
7
+ // bytes, empty argv/environ, and ENOSYS for everything else - enough for
8
+ // `std.debug.print`, `std.crypto.random` and timers, not for files. Pass a
9
+ // full implementation (e.g. `new WASI(...)` from @tybys/wasm-util) as the
10
+ // loader's `wasi` option for more.
11
+ //
12
+ // `createBrowserWasi` is embedded verbatim (through Function.prototype
13
+ // .toString) in the generated loaders, so it must stay self-contained.
14
+
15
+ /**
16
+ * `{ wasiImport, initialize(instance) }`, the shape emnapi expects.
17
+ * `options.memory`: the module's memory, if it imports it (threads);
18
+ * otherwise `initialize` picks up the exported one. `options.child`: a
19
+ * wasm thread's instance, which must not run the module's initializer.
20
+ */
21
+ export function createBrowserWasi(options = {}) {
22
+ let memory = options.memory ?? null
23
+ const SUCCESS = 0
24
+ const EBADF = 8
25
+ const ENOSYS = 52
26
+ const view = () => new DataView(memory.buffer)
27
+ const pending = { 1: '', 2: '' }
28
+ const decoders = { 1: new TextDecoder(), 2: new TextDecoder() }
29
+ const flush = (fd, all) => {
30
+ const text = pending[fd]
31
+ const cut = all ? text.length : text.lastIndexOf('\n') + 1
32
+ if (cut === 0) return
33
+ for (const line of text.slice(0, cut).replace(/\n$/, '').split('\n')) (fd === 1 ? console.log : console.error)(line)
34
+ pending[fd] = text.slice(cut)
35
+ }
36
+ const nanoseconds = (id) =>
37
+ id === 0 ? BigInt(Date.now()) * 1000000n : BigInt(Math.round((performance.timeOrigin + performance.now()) * 1e6))
38
+ const sizes = (count, size) => {
39
+ const v = view()
40
+ v.setUint32(count, 0, true)
41
+ v.setUint32(size, 0, true)
42
+ return SUCCESS
43
+ }
44
+ const wasiImport = {
45
+ args_sizes_get: sizes,
46
+ args_get: () => SUCCESS,
47
+ environ_sizes_get: sizes,
48
+ environ_get: () => SUCCESS,
49
+ clock_res_get(id, out) {
50
+ view().setBigUint64(out, 1000n, true)
51
+ return SUCCESS
52
+ },
53
+ clock_time_get(id, precision, out) {
54
+ view().setBigUint64(out, nanoseconds(id), true)
55
+ return SUCCESS
56
+ },
57
+ random_get(buffer, length) {
58
+ // (getRandomValues takes at most 64 KiB, and no shared memory.)
59
+ for (let done = 0; done < length; done += 65536) {
60
+ const chunk = new Uint8Array(Math.min(65536, length - done))
61
+ crypto.getRandomValues(chunk)
62
+ new Uint8Array(memory.buffer, buffer + done, chunk.length).set(chunk)
63
+ }
64
+ return SUCCESS
65
+ },
66
+ fd_write(fd, iovs, count, written) {
67
+ if (fd !== 1 && fd !== 2) return EBADF
68
+ const v = view()
69
+ let total = 0
70
+ for (let i = 0; i < count; i++) {
71
+ const pointer = v.getUint32(iovs + i * 8, true)
72
+ const length = v.getUint32(iovs + i * 8 + 4, true)
73
+ // (A copy: TextDecoder does not read shared memory.)
74
+ pending[fd] += decoders[fd].decode(new Uint8Array(memory.buffer, pointer, length).slice(), { stream: true })
75
+ total += length
76
+ }
77
+ flush(fd, false)
78
+ v.setUint32(written, total, true)
79
+ return SUCCESS
80
+ },
81
+ fd_close: (fd) => (fd <= 2 ? SUCCESS : EBADF),
82
+ fd_fdstat_get: (fd) => (fd <= 2 ? ENOSYS : EBADF),
83
+ sched_yield: () => SUCCESS,
84
+ proc_exit(code) {
85
+ flush(1, true)
86
+ flush(2, true)
87
+ throw new Error(`the WebAssembly module exited with code ${code}`)
88
+ },
89
+ }
90
+ return {
91
+ // Anything else a module may import answers ENOSYS.
92
+ wasiImport: new Proxy(wasiImport, {
93
+ get: (target, name) => (name in target ? target[name] : () => ENOSYS),
94
+ }),
95
+ initialize(instance) {
96
+ memory = memory ?? instance.exports.memory
97
+ if (!options.child && typeof instance.exports._initialize === 'function') instance.exports._initialize()
98
+ },
99
+ }
100
+ }
package/lib/build.mjs CHANGED
@@ -4,6 +4,7 @@ import { loadProject } from './project.mjs'
4
4
  import { DEFAULT_GLIBC, binaryName, findTarget, hostTargetId, zigTriple } from './targets.mjs'
5
5
  import { createUniversal } from './macho.mjs'
6
6
  import { run, zigExe } from './exec.mjs'
7
+ import { wasmLoaderFiles } from './wasm.mjs'
7
8
 
8
9
  const OPTIMIZE_MODES = { debug: 'debug', safe: 'safe', fast: 'fast', small: 'small' }
9
10
  // Spellings used by Zig before 0.17.
@@ -77,6 +78,13 @@ export function build(options) {
77
78
  }
78
79
  copyFileSync(source, dest)
79
80
  built.push(dest)
81
+ // A wasm build comes with the JavaScript that loads it.
82
+ if (target.wasm) {
83
+ for (const [name, text] of Object.entries(wasmLoaderFiles(project, target))) {
84
+ writeFileSync(join(outDir, name), text)
85
+ built.push(join(outDir, name))
86
+ }
87
+ }
80
88
 
81
89
  const dts = join(prefix, project.dts)
82
90
  if (existsSync(dts)) copyFileSync(dts, join(outDir, project.dts))
package/lib/project.mjs CHANGED
@@ -23,5 +23,8 @@ export function loadProject(dir) {
23
23
  addonName,
24
24
  targets: config.targets ?? [],
25
25
  dts: config.dts ?? 'index.d.ts',
26
+ // Memory bounds of the threaded wasm build, if build.zig changes them:
27
+ // { initialMemory, maxMemory } in bytes.
28
+ wasm: config.wasm ?? {},
26
29
  }
27
30
  }
package/lib/publish.mjs CHANGED
@@ -2,7 +2,7 @@ import { existsSync, readFileSync, readdirSync } from 'node:fs'
2
2
  import { dirname, join, resolve } from 'node:path'
3
3
  import { loadProject } from './project.mjs'
4
4
  import { binaryName, findTarget } from './targets.mjs'
5
- import { platformPackageName } from './artifacts.mjs'
5
+ import { packageFiles, platformPackageName } from './artifacts.mjs'
6
6
  import { run } from './exec.mjs'
7
7
 
8
8
  /**
@@ -46,13 +46,18 @@ export function publishPlan(project) {
46
46
  const manifestPath = join(dir, 'package.json')
47
47
  if (!existsSync(manifestPath)) continue
48
48
  const manifest = JSON.parse(readFileSync(manifestPath, 'utf8'))
49
- const binary = binaryName(addonName, findTarget(id))
49
+ const target = findTarget(id)
50
+ const binary = binaryName(addonName, target)
50
51
  const expectedName = platformPackageName(pkg, id)
51
52
  if (manifest.name !== expectedName) problems.push(`npm/${id}: name is ${manifest.name}, expected ${expectedName}`)
52
53
  if (manifest.version !== pkg.version) {
53
54
  problems.push(`npm/${id}: version ${manifest.version} does not match ${pkg.version} (re-run "napi-zig artifacts")`)
54
55
  }
55
- if (!existsSync(join(dir, binary))) problems.push(`npm/${id}: ${binary} is missing (build it, then re-run "napi-zig artifacts")`)
56
+ for (const file of packageFiles(project, target)) {
57
+ if (!existsSync(join(dir, file))) {
58
+ problems.push(`npm/${id}: ${file} is missing (${file === binary ? 'build it, then ' : ''}re-run "napi-zig artifacts")`)
59
+ }
60
+ }
56
61
  if (pkg.optionalDependencies?.[expectedName] !== pkg.version) {
57
62
  problems.push(`package.json: optionalDependencies["${expectedName}"] should be "${pkg.version}"`)
58
63
  }
package/lib/targets.mjs CHANGED
@@ -16,16 +16,18 @@ export const TARGETS = [
16
16
  { id: 'darwin-universal', os: 'darwin', cpu: ['x64', 'arm64'], merge: ['darwin-x64', 'darwin-arm64'] },
17
17
  { id: 'win32-x64', os: 'win32', cpu: ['x64'], zig: 'x86_64-windows-gnu' },
18
18
  { id: 'win32-arm64', os: 'win32', cpu: ['arm64'], zig: 'aarch64-windows-gnu' },
19
- // Experimental: runs anywhere through emnapi; single-threaded.
20
- { id: 'wasm32-wasi', zig: 'wasm32-wasi', ext: 'wasm', experimental: true },
21
- // The same with threads (shared memory + wasi-threads): Async and
22
- // ThreadsafeFunction work.
19
+ // WebAssembly, loaded through emnapi on any platform: the fallback of the
20
+ // generated index.js where no native binary fits. Single-threaded...
21
+ { id: 'wasm32-wasi', zig: 'wasm32-wasi', ext: 'wasm', wasm: true },
22
+ // ...and with threads (shared memory + wasi-threads): Async,
23
+ // ThreadsafeFunction and streams work.
23
24
  {
24
25
  id: 'wasm32-wasi-threads',
25
26
  zig: 'wasm32-wasi',
26
27
  zigArgs: ['-Dcpu=baseline+atomics+bulk_memory'],
27
28
  ext: 'wasm',
28
- experimental: true,
29
+ wasm: true,
30
+ threads: true,
29
31
  },
30
32
  ]
31
33
 
@@ -0,0 +1,131 @@
1
+ // Reads the bounds of the memory a WebAssembly module imports, from the
2
+ // module itself.
3
+ //
4
+ // A threaded wasm32-wasi build imports its (shared) memory as `env.memory`,
5
+ // so whoever instantiates it has to create a `WebAssembly.Memory` whose
6
+ // bounds fit what the module was linked with (addAddon's
7
+ // wasm_initial_memory / wasm_max_memory). `WebAssembly.Module.imports()`
8
+ // names the import but not its limits, so the loaders read them from the
9
+ // binary's import section instead.
10
+ //
11
+ // `wasmMemoryImport` is embedded verbatim (through Function.prototype
12
+ // .toString) in the loaders that `napi-zig build` writes, so it must stay
13
+ // self-contained: no imports, no references outside its own body. The
14
+ // reference loader of the repository (examples/wasm-threads/load.cjs)
15
+ // carries a copy, which the CLI tests compare with this one.
16
+
17
+ /**
18
+ * The limits of the memory that a WebAssembly module imports as
19
+ * `env.memory`, in pages of `pageSize` bytes (64 KiB unless the module
20
+ * says otherwise): `{ initial, maximum, shared, memory64, pageSize }`,
21
+ * `maximum` being undefined when the module sets none. Null if the module
22
+ * imports no `env.memory` (it defines its own, or has none). Throws on
23
+ * anything that is not a well-formed core module up to the import section.
24
+ *
25
+ * @param {ArrayBuffer | ArrayBufferView} source the module's bytes
26
+ */
27
+ export function wasmMemoryImport(source) {
28
+ const bytes = ArrayBuffer.isView(source)
29
+ ? new Uint8Array(source.buffer, source.byteOffset, source.byteLength)
30
+ : new Uint8Array(source)
31
+ let at = 0
32
+ let end = bytes.length
33
+ const fail = (what) => {
34
+ throw new Error(`not a valid WebAssembly module: ${what} (at byte ${at})`)
35
+ }
36
+ const byte = () => {
37
+ if (at >= end) fail('unexpected end')
38
+ return bytes[at++]
39
+ }
40
+ // Unsigned LEB128 of at most `bits` bits, as a Number (exact up to 2^53).
41
+ const unsigned = (bits) => {
42
+ let value = 0
43
+ let scale = 1
44
+ for (let shift = 0; ; shift += 7) {
45
+ const b = byte()
46
+ // The last byte may only use the bits that are left.
47
+ if (shift + 7 > bits && b >> (bits - shift) !== 0) fail('integer too large')
48
+ value += (b & 0x7f) * scale
49
+ scale *= 128
50
+ if ((b & 0x80) === 0) break
51
+ }
52
+ if (value > Number.MAX_SAFE_INTEGER) fail('integer too large')
53
+ return value
54
+ }
55
+ // Signed LEB128 of at most 33 bits (a heap type); only skipped.
56
+ const skipSigned33 = () => {
57
+ for (let shift = 0; ; shift += 7) {
58
+ if (shift >= 35) fail('integer too long')
59
+ if ((byte() & 0x80) === 0) return
60
+ }
61
+ }
62
+ const name = () => {
63
+ const length = unsigned(32)
64
+ if (length > end - at) fail('name runs past its section')
65
+ let text = ''
66
+ for (let i = 0; i < length; i++) text += String.fromCharCode(bytes[at + i])
67
+ at += length
68
+ return text
69
+ }
70
+ // A value or reference type: one byte, or (ref null? <heap type>).
71
+ const skipType = () => {
72
+ const b = byte()
73
+ if (b === 0x63 || b === 0x64) skipSigned33()
74
+ }
75
+ const limits = () => {
76
+ const flags = byte()
77
+ if (flags & ~0x0f) fail(`unknown limits flags 0x${flags.toString(16)}`)
78
+ const memory64 = (flags & 0x04) !== 0
79
+ const bits = memory64 ? 64 : 32
80
+ const initial = unsigned(bits)
81
+ const maximum = flags & 0x01 ? unsigned(bits) : undefined
82
+ // (Custom page sizes: the page size's log2 follows.)
83
+ const pageSize = flags & 0x08 ? 2 ** unsigned(32) : 65536
84
+ return { initial, maximum, shared: (flags & 0x02) !== 0, memory64, pageSize }
85
+ }
86
+
87
+ if (bytes.length < 8) fail('too short')
88
+ if (bytes[0] !== 0x00 || bytes[1] !== 0x61 || bytes[2] !== 0x73 || bytes[3] !== 0x6d) fail('no \\0asm magic')
89
+ if (bytes[4] !== 0x01 || bytes[5] !== 0x00 || bytes[6] !== 0x00 || bytes[7] !== 0x00) fail('not a version 1 core module')
90
+ at = 8
91
+ while (at < bytes.length) {
92
+ end = bytes.length
93
+ const id = byte()
94
+ const size = unsigned(32)
95
+ if (size > bytes.length - at) fail('section runs past the end')
96
+ const sectionEnd = at + size
97
+ // Custom sections (0) may come anywhere and the type section (1)
98
+ // before the imports; any other section comes after them.
99
+ if (id === 2) {
100
+ end = sectionEnd
101
+ const count = unsigned(32)
102
+ for (let i = 0; i < count; i++) {
103
+ const module = name()
104
+ const field = name()
105
+ const kind = byte()
106
+ if (kind === 0x00) {
107
+ unsigned(32) // a function: its type index
108
+ } else if (kind === 0x01) {
109
+ skipType() // a table
110
+ limits()
111
+ } else if (kind === 0x02) {
112
+ const memory = limits()
113
+ if (module === 'env' && field === 'memory') return memory
114
+ } else if (kind === 0x03) {
115
+ skipType() // a global
116
+ if (byte() > 1) fail('bad global mutability')
117
+ } else if (kind === 0x04) {
118
+ byte() // a tag: its attribute, then its type index
119
+ unsigned(32)
120
+ } else {
121
+ fail(`unknown import kind 0x${kind.toString(16)}`)
122
+ }
123
+ }
124
+ if (at !== sectionEnd) fail('import section size mismatch')
125
+ return null
126
+ }
127
+ if (id !== 0 && id !== 1) return null
128
+ at = sectionEnd
129
+ }
130
+ return null
131
+ }
package/lib/wasm.mjs ADDED
@@ -0,0 +1,336 @@
1
+ // The JavaScript that loads a WebAssembly build of an addon through emnapi
2
+ // (the Node-API implementation for WebAssembly): written next to the .wasm
3
+ // by `napi-zig build` and shipped in its npm package by `napi-zig
4
+ // artifacts`. Generated from the reference loaders of napi-zig's wasm
5
+ // examples (examples/wasm/load.cjs, examples/wasm-threads/load.cjs).
6
+
7
+ import { binaryName } from './targets.mjs'
8
+ import { wasmMemoryImport } from './wasm-memory.mjs'
9
+ import { createBrowserWasi } from './browser-wasi.mjs'
10
+
11
+ /** The emnapi packages a loader needs, as npm dependency ranges. */
12
+ export const EMNAPI_DEPENDENCIES = {
13
+ '@emnapi/core': '^1.4.0',
14
+ '@emnapi/runtime': '^1.4.0',
15
+ }
16
+ export const EMNAPI_THREADS_DEPENDENCIES = {
17
+ ...EMNAPI_DEPENDENCIES,
18
+ '@emnapi/wasi-threads': '^1.0.0',
19
+ }
20
+
21
+ // The linker's defaults in addAddon (wasm_initial_memory / wasm_max_memory):
22
+ // only used if a threaded module does not import its memory as `env.memory`
23
+ // (which napi-zig's builds always do; the loaders read the bounds from there).
24
+ export const DEFAULT_INITIAL_MEMORY = 32 << 20
25
+ export const DEFAULT_MAX_MEMORY = 2 ** 30
26
+
27
+ /** `<name>.<target>.cjs`: the module that loads `<name>.<target>.wasm` in Node.js (and Bun, Deno). */
28
+ export function loaderName(addonName, target) {
29
+ return `${addonName}.${target.id}.cjs`
30
+ }
31
+
32
+ /** `<name>.<target>.worker.cjs`: what each wasm thread runs in Node.js. */
33
+ export function workerName(addonName, target) {
34
+ return `${addonName}.${target.id}.worker.cjs`
35
+ }
36
+
37
+ /** `<name>.<target>.browser.mjs`: the ES module that loads the .wasm in browsers and bundlers. */
38
+ export function browserLoaderName(addonName, target) {
39
+ return `${addonName}.${target.id}.browser.mjs`
40
+ }
41
+
42
+ /** `<name>.<target>.browser-worker.mjs`: what each wasm thread runs in a browser (a module worker). */
43
+ export function browserWorkerName(addonName, target) {
44
+ return `${addonName}.${target.id}.browser-worker.mjs`
45
+ }
46
+
47
+ /** The files that load a wasm target's binary: `{ name: contents }`. */
48
+ export function wasmLoaderFiles(project, target) {
49
+ const threaded = Boolean(target.threads)
50
+ const { addonName } = project
51
+ const binary = binaryName(addonName, target)
52
+ const memory = project.wasm ?? {}
53
+ const files = {
54
+ [loaderName(addonName, target)]: threaded ? threadedLoader(binary, workerName(addonName, target), memory) : loader(binary),
55
+ }
56
+ if (threaded) files[workerName(addonName, target)] = worker()
57
+ files[browserLoaderName(addonName, target)] = threaded
58
+ ? threadedBrowserLoader(binary, browserWorkerName(addonName, target), memory)
59
+ : browserLoader(binary)
60
+ if (threaded) files[browserWorkerName(addonName, target)] = browserWorker()
61
+ return files
62
+ }
63
+
64
+ /** The `package.json` fields that point at a wasm target's loaders. */
65
+ export function wasmPackageEntries(addonName, target) {
66
+ const node = `./${loaderName(addonName, target)}`
67
+ const browser = `./${browserLoaderName(addonName, target)}`
68
+ return {
69
+ main: loaderName(addonName, target),
70
+ browser: browserLoaderName(addonName, target),
71
+ // Node.js, Bun and Deno match "node": the CommonJS loader (node:wasi,
72
+ // worker_threads). Browsers and bundlers for the web match "browser"
73
+ // (or "import"): the ES module that fetches the .wasm.
74
+ exports: {
75
+ '.': { node, browser, import: browser, default: node },
76
+ './package.json': './package.json',
77
+ './*': './*',
78
+ },
79
+ }
80
+ }
81
+
82
+ const header = (what) => `// Generated by napi-zig: ${what}
83
+ // through emnapi (@emnapi/core, @emnapi/runtime).
84
+ 'use strict'
85
+ `
86
+
87
+ const esmHeader = (what) => `// Generated by napi-zig: ${what}
88
+ // through emnapi (@emnapi/core, @emnapi/runtime).
89
+ `
90
+
91
+ /** Explicit bounds ("napi.wasm" in package.json, in bytes) as pages, or the module's own. */
92
+ function memoryBounds(options) {
93
+ const pages = (bytes) => String(Math.ceil(bytes / 65536))
94
+ return {
95
+ initial: options.initialMemory != null ? pages(options.initialMemory) : 'imported.initial',
96
+ maximum: options.maxMemory != null ? pages(options.maxMemory) : 'imported.maximum',
97
+ }
98
+ }
99
+
100
+ /** Declares `memory`, the shared memory of a threaded module (`found`: what wasmMemoryImport returned). */
101
+ function memorySource(options, found, indent = '') {
102
+ const { initial, maximum } = memoryBounds(options)
103
+ const overridden = options.initialMemory != null || options.maxMemory != null
104
+ return [
105
+ '// One memory shared by every thread, with the bounds the module imports',
106
+ `// it with (as linked by build.zig: wasm_initial_memory, wasm_max_memory)${overridden ? ',' : '.'}`,
107
+ ...(overridden ? ['// overridden by "napi.wasm" in package.json.'] : []),
108
+ `const imported = ${found} ?? { initial: ${DEFAULT_INITIAL_MEMORY / 65536}, maximum: ${DEFAULT_MAX_MEMORY / 65536} }`,
109
+ `const memory = new WebAssembly.Memory({ initial: ${initial}, maximum: ${maximum}, shared: true })`,
110
+ ].join(`\n${indent}`)
111
+ }
112
+
113
+ const shared = `
114
+ // Bun's node:wasi has no \`initialize\` (the entry point of reactor modules
115
+ // such as this one); do what it does there.
116
+ function newWasi() {
117
+ const wasi = new WASI({ version: 'preview1' })
118
+ if (typeof wasi.initialize !== 'function') {
119
+ wasi.initialize = (instance) => {
120
+ wasi.setMemory(instance.exports.memory)
121
+ instance.exports._initialize?.()
122
+ }
123
+ }
124
+ return wasi
125
+ }
126
+ `
127
+
128
+ const context = `
129
+ // emnapi keeps the event loop alive while work is pending by holding a
130
+ // referenced MessagePort, which Deno does not count: there a referenced
131
+ // timer does the job instead.
132
+ function context() {
133
+ const ctx = getDefaultContext()
134
+ if (globalThis.Deno && ctx.refCounter && !ctx.refCounter.napiZigTimer) {
135
+ let count = 0
136
+ let timer = null
137
+ ctx.refCounter = {
138
+ napiZigTimer: true,
139
+ increase() {
140
+ if (count++ === 0) timer = setInterval(() => {}, 1 << 30)
141
+ },
142
+ decrease() {
143
+ if (count === 0) return
144
+ if (--count === 0) clearInterval(timer)
145
+ },
146
+ }
147
+ }
148
+ return ctx
149
+ }
150
+ `
151
+
152
+ function loader(binary) {
153
+ return `${header('loads the wasm32-wasi build of this addon')}
154
+ const { readFileSync } = require('node:fs')
155
+ const { join } = require('node:path')
156
+ const { WASI } = require('node:wasi')
157
+ const { instantiateNapiModuleSync } = require('@emnapi/core')
158
+ const { getDefaultContext } = require('@emnapi/runtime')
159
+ ${shared}${context}
160
+ const { napiModule } = instantiateNapiModuleSync(readFileSync(join(__dirname, ${JSON.stringify(binary)})), {
161
+ context: context(),
162
+ wasi: newWasi(),
163
+ })
164
+ module.exports = napiModule.exports
165
+ `
166
+ }
167
+
168
+ function threadedLoader(binary, workerFile, options) {
169
+ return `${header('loads the threaded wasm32-wasi build of this addon')}
170
+ const { readFileSync } = require('node:fs')
171
+ const { join } = require('node:path')
172
+ const { WASI } = require('node:wasi')
173
+ const { Worker } = require('node:worker_threads')
174
+ const { instantiateNapiModuleSync } = require('@emnapi/core')
175
+ const { getDefaultContext } = require('@emnapi/runtime')
176
+ ${shared}${context}
177
+ // The limits of the memory a module imports as env.memory, read from its
178
+ // import section (WebAssembly.Module.imports() does not report them).
179
+ ${wasmMemoryImport}
180
+
181
+ const bytes = readFileSync(join(__dirname, ${JSON.stringify(binary)}))
182
+ ${memorySource(options, 'wasmMemoryImport(bytes)')}
183
+ const { napiModule } = instantiateNapiModuleSync(bytes, {
184
+ context: context(),
185
+ wasi: newWasi(),
186
+ // Each thread the addon spawns is a worker running ${workerFile}.
187
+ onCreateWorker: () => new Worker(join(__dirname, ${JSON.stringify(workerFile)}), { env: process.env }),
188
+ waitThreadStart: 5000,
189
+ overwriteImports(imports) {
190
+ imports.env.memory = memory
191
+ },
192
+ })
193
+ module.exports = napiModule.exports
194
+ `
195
+ }
196
+
197
+ function worker() {
198
+ return `${header('runs one thread of the threaded wasm32-wasi build of this addon')}
199
+ const { parentPort } = require('node:worker_threads')
200
+ const { WASI } = require('node:wasi')
201
+ const { instantiateNapiModuleSync, MessageHandler } = require('@emnapi/core')
202
+ ${shared}
203
+ const postMessage = (message) => parentPort.postMessage(message)
204
+ // emnapi's thread-side code talks to the main thread through the web
205
+ // worker globals; give it those names on Node.js.
206
+ Object.assign(globalThis, { self: globalThis, postMessage })
207
+
208
+ const handler = new MessageHandler({
209
+ postMessage,
210
+ onLoad({ wasmModule, wasmMemory }) {
211
+ return instantiateNapiModuleSync(wasmModule, {
212
+ childThread: true,
213
+ wasi: newWasi(),
214
+ postMessage,
215
+ overwriteImports(imports) {
216
+ imports.env.memory = wasmMemory
217
+ },
218
+ })
219
+ },
220
+ })
221
+
222
+ parentPort.on('message', (data) => handler.handle({ data }))
223
+ `
224
+ }
225
+
226
+ // --- browsers and bundlers ----------------------------------------------------
227
+
228
+ const fetchBytes = `
229
+ // The .wasm's bytes: \`source\` is a URL (or string), a Response, bytes, or
230
+ // a compiled WebAssembly.Module (passed through).
231
+ async function bytesOf(source) {
232
+ if (source instanceof WebAssembly.Module || source instanceof ArrayBuffer || ArrayBuffer.isView(source)) return source
233
+ const response = typeof Response !== 'undefined' && source instanceof Response ? source : await fetch(source)
234
+ if (!response.ok) throw new Error(\`could not fetch \${response.url || source}: HTTP \${response.status}\`)
235
+ return new Uint8Array(await response.arrayBuffer())
236
+ }
237
+ `
238
+
239
+ function browserLoader(binary) {
240
+ return `${esmHeader('loads the wasm32-wasi build of this addon in browsers and bundlers')}//
241
+ // import addon from '<package>' // instantiated once, on import
242
+ // import { load } from '<package>' // load({ wasm, wasi, context }): another instance
243
+ import { instantiateNapiModule } from '@emnapi/core'
244
+ import { getDefaultContext } from '@emnapi/runtime'
245
+
246
+ // A console for stdout/stderr, clocks and random bytes: enough WASI for a
247
+ // module that does not touch files (pass \`wasi\` for more).
248
+ ${createBrowserWasi}
249
+
250
+ // (The pattern bundlers know: they copy the .wasm and rewrite the URL.)
251
+ const wasmUrl = new URL(${JSON.stringify(`./${binary}`)}, import.meta.url)
252
+ ${fetchBytes}
253
+ export async function load(options = {}) {
254
+ const { napiModule } = await instantiateNapiModule(await bytesOf(options.wasm ?? wasmUrl), {
255
+ context: options.context ?? getDefaultContext(),
256
+ wasi: options.wasi ?? createBrowserWasi(),
257
+ })
258
+ return napiModule.exports
259
+ }
260
+
261
+ export default await load()
262
+ `
263
+ }
264
+
265
+ function threadedBrowserLoader(binary, workerFile, options) {
266
+ return `${esmHeader('loads the threaded wasm32-wasi build of this addon in browsers and bundlers')}//
267
+ // Threads are Web Workers sharing one WebAssembly.Memory, which takes a
268
+ // SharedArrayBuffer: the page must be cross-origin isolated (served with
269
+ // Cross-Origin-Opener-Policy: same-origin and Cross-Origin-Embedder-Policy:
270
+ // require-corp). Load it in a worker rather than on the page's main thread,
271
+ // which may not block.
272
+ //
273
+ // import addon from '<package>' // instantiated once, on import
274
+ // import { load } from '<package>' // load({ wasm, wasi, context, memory, reuseWorker, onCreateWorker })
275
+ import { instantiateNapiModule } from '@emnapi/core'
276
+ import { getDefaultContext } from '@emnapi/runtime'
277
+
278
+ // The limits of the memory a module imports as env.memory, read from its
279
+ // import section (WebAssembly.Module.imports() does not report them).
280
+ ${wasmMemoryImport}
281
+
282
+ // A console for stdout/stderr, clocks and random bytes: enough WASI for a
283
+ // module that does not touch files (pass \`wasi\` for more).
284
+ ${createBrowserWasi}
285
+
286
+ // (The pattern bundlers know: they copy the .wasm and rewrite the URL.)
287
+ const wasmUrl = new URL(${JSON.stringify(`./${binary}`)}, import.meta.url)
288
+ ${fetchBytes}
289
+ export async function load(options = {}) {
290
+ const bytes = await bytesOf(options.wasm ?? wasmUrl)
291
+ const memory = options.memory ?? createMemory(bytes instanceof WebAssembly.Module ? null : bytes)
292
+ const { napiModule } = await instantiateNapiModule(bytes, {
293
+ context: options.context ?? getDefaultContext(),
294
+ wasi: options.wasi ?? createBrowserWasi({ memory }),
295
+ // A worker cannot start while the thread that asked for it is busy, so
296
+ // a few are kept ready (as many as napi-zig's Async pool has threads by
297
+ // default); more are started when needed.
298
+ reuseWorker: options.reuseWorker ?? { size: 4, strict: false },
299
+ // Each thread the addon spawns is a module worker running ${workerFile}.
300
+ onCreateWorker: options.onCreateWorker ?? (() => new Worker(new URL(${JSON.stringify(`./${workerFile}`)}, import.meta.url), { type: 'module' })),
301
+ overwriteImports(imports) {
302
+ imports.env.memory = memory
303
+ },
304
+ })
305
+ return napiModule.exports
306
+ }
307
+
308
+ function createMemory(bytes) {
309
+ ${memorySource(options, '(bytes && wasmMemoryImport(bytes))', ' ')}
310
+ return memory
311
+ }
312
+
313
+ export default await load()
314
+ `
315
+ }
316
+
317
+ function browserWorker() {
318
+ return `${esmHeader('runs one thread of the threaded wasm32-wasi build of this addon in a browser')}import { instantiateNapiModuleSync, MessageHandler } from '@emnapi/core'
319
+
320
+ ${createBrowserWasi}
321
+
322
+ const handler = new MessageHandler({
323
+ onLoad({ wasmModule, wasmMemory }) {
324
+ return instantiateNapiModuleSync(wasmModule, {
325
+ childThread: true,
326
+ wasi: createBrowserWasi({ memory: wasmMemory, child: true }),
327
+ overwriteImports(imports) {
328
+ imports.env.memory = wasmMemory
329
+ },
330
+ })
331
+ },
332
+ })
333
+
334
+ globalThis.onmessage = (event) => handler.handle(event)
335
+ `
336
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@hunghg255/napi-zig-cli",
3
- "version": "1.5.0",
3
+ "version": "1.7.0",
4
4
  "description": "Command line tool for napi-zig: scaffold, build, cross-compile and publish Node.js native addons written in Zig",
5
5
  "keywords": [
6
6
  "napi",
@@ -29,8 +29,12 @@ jobs:
29
29
  - uses: actions/upload-artifact@v4
30
30
  with:
31
31
  name: binaries
32
+ # (*.wasm and their loaders: the wasm32-wasi targets, if listed
33
+ # in "napi.targets".)
32
34
  path: |
33
35
  *.node
36
+ *.wasm
37
+ *.wasm32-wasi*.cjs
34
38
  index.d.ts
35
39
  if-no-files-found: error
36
40
 
@@ -5,3 +5,5 @@ node_modules/
5
5
  *.node
6
6
  index.d.ts
7
7
  npm/
8
+ *.wasm
9
+ *.wasm32-wasi*.cjs
@@ -0,0 +1,12 @@
1
+ // Browsers and bundlers (the "browser" export of package.json): the
2
+ // WebAssembly build of the addon, instantiated on import. Node.js, Bun and
3
+ // Deno load index.js instead (native binary first, WebAssembly as the
4
+ // fallback).
5
+ //
6
+ // import addon from '{{PACKAGE_NAME}}'
7
+ //
8
+ // This needs "wasm32-wasi" in "napi.targets" (built and published with the
9
+ // rest). The threaded build, "wasm32-wasi-threads", needs a cross-origin
10
+ // isolated page and is best loaded in a worker: import
11
+ // '{{PACKAGE_NAME}}-wasm32-wasi-threads' there (or point this file at it).
12
+ export { default, load } from '{{PACKAGE_NAME}}-wasm32-wasi'
@@ -1,5 +1,7 @@
1
1
  // Loads the binary for the current platform: a local build if there is one
2
- // (`napi-zig build`), otherwise the prebuilt optional dependency.
2
+ // (`napi-zig build`), otherwise the prebuilt optional dependency - and where
3
+ // no native binary fits, the WebAssembly build (through emnapi), local or
4
+ // prebuilt.
3
5
  'use strict'
4
6
 
5
7
  const { existsSync } = require('node:fs')
@@ -8,6 +10,9 @@ const { join } = require('node:path')
8
10
  const ADDON = '{{ADDON_NAME}}'
9
11
  const PACKAGE = '{{PACKAGE_NAME}}'
10
12
 
13
+ // Threaded first: it can do everything the single-threaded build can.
14
+ const WASM_IDS = ['wasm32-wasi-threads', 'wasm32-wasi']
15
+
11
16
  function targetIds() {
12
17
  const { platform, arch } = process
13
18
  if (platform === 'darwin') return [`darwin-${arch}`, 'darwin-universal']
@@ -20,18 +25,29 @@ function targetIds() {
20
25
  function load() {
21
26
  const ids = targetIds()
22
27
  const errors = []
23
- for (const id of ids) {
24
- const local = join(__dirname, `${ADDON}.${id}.node`)
25
- if (existsSync(local)) return require(local)
28
+ const attempt = (local, id) => {
29
+ if (existsSync(local)) return { found: true, exports: require(local) }
26
30
  try {
27
- return require(`${PACKAGE}-${id}`)
31
+ return { found: true, exports: require(`${PACKAGE}-${id}`) }
28
32
  } catch (err) {
29
33
  errors.push(err)
34
+ return { found: false }
30
35
  }
31
36
  }
37
+ for (const id of ids) {
38
+ const result = attempt(join(__dirname, `${ADDON}.${id}.node`), id)
39
+ if (result.found) return result.exports
40
+ }
41
+ // A wasm build's loader sits next to its .wasm (it is the main module of
42
+ // the wasm package).
43
+ for (const id of WASM_IDS) {
44
+ const result = attempt(join(__dirname, `${ADDON}.${id}.cjs`), id)
45
+ if (result.found) return result.exports
46
+ }
32
47
  throw new Error(
33
- `${PACKAGE}: no native binary found for ${ids.join(' / ')}. ` +
34
- `Run "napi-zig build", or check that the optional dependency ${PACKAGE}-${ids[0]} is installed.`,
48
+ `${PACKAGE}: no binary found for ${ids.join(' / ')}, nor a WebAssembly build. ` +
49
+ `Run "napi-zig build", or check that the optional dependency ${PACKAGE}-${ids[0]} ` +
50
+ `(or ${PACKAGE}-${WASM_IDS[1]}) is installed.`,
35
51
  { cause: errors[0] },
36
52
  )
37
53
  }
@@ -4,9 +4,20 @@
4
4
  "description": "A Node.js addon written in Zig",
5
5
  "main": "index.js",
6
6
  "types": "index.d.ts",
7
+ "browser": "browser.mjs",
8
+ "exports": {
9
+ ".": {
10
+ "types": "./index.d.ts",
11
+ "node": "./index.js",
12
+ "browser": "./browser.mjs",
13
+ "default": "./index.js"
14
+ },
15
+ "./package.json": "./package.json"
16
+ },
7
17
  "files": [
8
18
  "index.js",
9
- "index.d.ts"
19
+ "index.d.ts",
20
+ "browser.mjs"
10
21
  ],
11
22
  "napi": {
12
23
  "name": "{{ADDON_NAME}}",
@@ -21,7 +32,7 @@
21
32
  "test": "node --test"
22
33
  },
23
34
  "devDependencies": {
24
- "@hunghg255/napi-zig-cli": "^1.5.0"
35
+ "@hunghg255/napi-zig-cli": "^1.7.0"
25
36
  },
26
37
  "license": "MIT"
27
38
  }