@hunghg255/napi-zig-cli 0.0.0-stage → 1.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/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 napi-zig contributors
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,30 @@
1
- # Temporary Holding Version
1
+ # @hunghg255/napi-zig-cli
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ Command line companion for [napi-zig](..): scaffold, build and package
4
+ Node.js addons written in Zig. No dependencies; it drives `zig build`.
5
+
6
+ ```
7
+ napi-zig new <name> [--napi-path <dir>] scaffold a project (with a CI workflow)
8
+ napi-zig build [--target <id>]... [--all] build <name>.<target>.node + index.d.ts
9
+ napi-zig artifacts create npm/<target>/ packages
10
+ napi-zig publish [--dry-run] npm publish the platform packages, then the main one
11
+ napi-zig targets list supported targets
12
+ ```
13
+
14
+ `build` cross-compiles out of the box - Zig ships the libc headers and
15
+ linkers for every target, so `napi-zig build --all` on one machine produces
16
+ the binaries for Linux (glibc and musl), macOS (also as one universal file)
17
+ and Windows, plus WebAssembly (`wasm32-wasi`, `wasm32-wasi-threads`).
18
+
19
+ Project configuration lives in `package.json`:
20
+
21
+ ```json
22
+ {
23
+ "napi": {
24
+ "name": "my-addon",
25
+ "targets": ["linux-x64-gnu", "linux-arm64-gnu", "darwin-arm64", "win32-x64"]
26
+ }
27
+ }
28
+ ```
29
+
30
+ The `zig` executable is taken from `PATH` (override with `NAPI_ZIG_ZIG`).
@@ -0,0 +1,129 @@
1
+ #!/usr/bin/env node
2
+ import { parseArgs } from 'node:util'
3
+ import { readFileSync } from 'node:fs'
4
+ import { build } from '../lib/build.mjs'
5
+ import { artifacts } from '../lib/artifacts.mjs'
6
+ import { newProject } from '../lib/new.mjs'
7
+ import { publish } from '../lib/publish.mjs'
8
+ import { TARGETS, hostTargetId } from '../lib/targets.mjs'
9
+
10
+ const HELP = `napi-zig - build Node.js addons written in Zig
11
+
12
+ Usage:
13
+ napi-zig new <name> [--napi-path <dir>] [--napi-url <url>]
14
+ Scaffold a new addon project in ./<name> (source, build files, loader,
15
+ tests and GitHub Actions workflow).
16
+
17
+ napi-zig build [--target <id>]... [--all] [--debug] [--out-dir <dir>] [-- <zig build args>]
18
+ Run zig build and write <name>.<target>.node (+ index.d.ts) next to
19
+ package.json. Defaults to the host platform, optimized.
20
+ --target <id> build for a platform (repeatable); see "targets"
21
+ --all build every target listed in package.json "napi.targets"
22
+ --debug same as --optimize debug
23
+ --optimize <m> debug | safe | fast (default) | small
24
+ --portable pass an explicit target even for the host platform
25
+ --glibc <ver> minimum glibc for *-gnu targets (default 2.28)
26
+ --dynamic-host resolve Node-API at load time (Electron, renamed hosts)
27
+ The target darwin-universal merges darwin-x64 and darwin-arm64 into one
28
+ file; wasm32-wasi is experimental.
29
+
30
+ napi-zig artifacts [--target <id>]...
31
+ Create npm/<target>/ packages for the built binaries and list them as
32
+ optionalDependencies in package.json.
33
+
34
+ napi-zig publish [--dry-run] [--tag <tag>] [--otp <code>] [--provenance] [--access <a>]
35
+ Verify the npm/<target>/ packages, then "npm publish" each of them and
36
+ finally the main package. --dry-run uploads nothing.
37
+
38
+ napi-zig targets
39
+ List the supported targets.
40
+ `
41
+
42
+ function main() {
43
+ const argv = process.argv.slice(2)
44
+ const separator = argv.indexOf('--')
45
+ const zigArgs = separator === -1 ? [] : argv.slice(separator + 1)
46
+ const { values, positionals } = parseArgs({
47
+ args: separator === -1 ? argv : argv.slice(0, separator),
48
+ allowPositionals: true,
49
+ options: {
50
+ target: { type: 'string', multiple: true, short: 't' },
51
+ all: { type: 'boolean' },
52
+ debug: { type: 'boolean' },
53
+ optimize: { type: 'string' },
54
+ portable: { type: 'boolean' },
55
+ glibc: { type: 'string' },
56
+ 'dynamic-host': { type: 'boolean' },
57
+ 'dry-run': { type: 'boolean' },
58
+ tag: { type: 'string' },
59
+ otp: { type: 'string' },
60
+ access: { type: 'string' },
61
+ provenance: { type: 'boolean' },
62
+ 'out-dir': { type: 'string' },
63
+ cwd: { type: 'string' },
64
+ 'napi-path': { type: 'string' },
65
+ 'napi-url': { type: 'string' },
66
+ help: { type: 'boolean', short: 'h' },
67
+ version: { type: 'boolean', short: 'v' },
68
+ },
69
+ })
70
+
71
+ const [command, ...rest] = positionals
72
+ if (values.version) {
73
+ const pkg = JSON.parse(readFileSync(new URL('../package.json', import.meta.url), 'utf8'))
74
+ console.log(pkg.version)
75
+ return
76
+ }
77
+ if (values.help || !command || command === 'help') {
78
+ console.log(HELP)
79
+ return
80
+ }
81
+
82
+ switch (command) {
83
+ case 'new':
84
+ newProject({ name: rest[0], cwd: values.cwd, napiPath: values['napi-path'], napiUrl: values['napi-url'] })
85
+ break
86
+ case 'build':
87
+ build({
88
+ cwd: values.cwd,
89
+ targets: values.target,
90
+ all: values.all,
91
+ optimize: values.optimize ?? (values.debug ? 'debug' : 'fast'),
92
+ portable: values.portable,
93
+ glibc: values.glibc,
94
+ dynamicHost: values['dynamic-host'],
95
+ outDir: values['out-dir'],
96
+ zigArgs,
97
+ })
98
+ break
99
+ case 'artifacts':
100
+ artifacts({ cwd: values.cwd, targets: values.target })
101
+ break
102
+ case 'publish':
103
+ publish({
104
+ cwd: values.cwd,
105
+ dryRun: values['dry-run'],
106
+ tag: values.tag,
107
+ otp: values.otp,
108
+ access: values.access,
109
+ provenance: values.provenance,
110
+ })
111
+ break
112
+ case 'targets':
113
+ for (const target of TARGETS) {
114
+ 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(', ')}]` : ''}`)
117
+ }
118
+ break
119
+ default:
120
+ throw new Error(`unknown command '${command}'. Run 'napi-zig help'.`)
121
+ }
122
+ }
123
+
124
+ try {
125
+ main()
126
+ } catch (err) {
127
+ console.error(`napi-zig: error: ${err.message}`)
128
+ process.exitCode = 1
129
+ }
@@ -0,0 +1,65 @@
1
+ import { copyFileSync, existsSync, mkdirSync, writeFileSync } from 'node:fs'
2
+ import { join, resolve } from 'node:path'
3
+ import { loadProject } from './project.mjs'
4
+ import { binaryName, findTarget } from './targets.mjs'
5
+
6
+ /** The npm package that carries the binary of one target. */
7
+ export function platformPackageName(pkg, id) {
8
+ return `${pkg.name}-${id}`
9
+ }
10
+
11
+ /**
12
+ * Lays out one npm package per platform under `npm/<target>/`, the way
13
+ * prebuilt native addons are usually published:
14
+ *
15
+ * npm/linux-x64-gnu/package.json { os: ["linux"], cpu: ["x64"], libc: ["glibc"] }
16
+ * npm/linux-x64-gnu/<name>.linux-x64-gnu.node
17
+ *
18
+ * and lists them as optionalDependencies of the main package, so that
19
+ * `npm install` downloads only the binary matching the user's machine.
20
+ */
21
+ export function artifacts(options) {
22
+ const project = loadProject(resolve(options.cwd ?? '.'))
23
+ const { pkg, addonName } = project
24
+ const targets = options.targets?.length ? options.targets : project.targets
25
+ if (!targets.length) throw new Error('no targets: pass --target or set "napi.targets" in package.json')
26
+
27
+ const created = []
28
+ const missing = []
29
+ for (const id of targets) {
30
+ const target = findTarget(id)
31
+ const binary = binaryName(addonName, target)
32
+ const dir = join(project.dir, 'npm', id)
33
+ mkdirSync(dir, { recursive: true })
34
+
35
+ const platformPackage = {
36
+ name: platformPackageName(pkg, id),
37
+ version: pkg.version,
38
+ description: `${pkg.name} prebuilt binary for ${id}`,
39
+ ...(target.os ? { os: [target.os] } : {}),
40
+ ...(target.cpu ? { cpu: target.cpu } : {}),
41
+ ...(target.libc ? { libc: [target.libc] } : {}),
42
+ main: binary,
43
+ files: [binary],
44
+ license: pkg.license,
45
+ repository: pkg.repository,
46
+ ...(pkg.publishConfig ? { publishConfig: pkg.publishConfig } : {}),
47
+ }
48
+ writeFileSync(join(dir, 'package.json'), JSON.stringify(platformPackage, null, 2) + '\n')
49
+
50
+ const source = join(project.dir, binary)
51
+ if (existsSync(source)) copyFileSync(source, join(dir, binary))
52
+ else missing.push(binary)
53
+ created.push(dir)
54
+ }
55
+
56
+ pkg.optionalDependencies = {
57
+ ...pkg.optionalDependencies,
58
+ ...Object.fromEntries(targets.map((id) => [platformPackageName(pkg, id), pkg.version])),
59
+ }
60
+ writeFileSync(project.packagePath, JSON.stringify(pkg, null, 2) + '\n')
61
+
62
+ for (const dir of created) console.log(`napi-zig: prepared ${dir}`)
63
+ for (const binary of missing) console.warn(`napi-zig: warning: ${binary} has not been built yet`)
64
+ return { created, missing }
65
+ }
package/lib/build.mjs ADDED
@@ -0,0 +1,89 @@
1
+ import { copyFileSync, existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs'
2
+ import { join, resolve } from 'node:path'
3
+ import { loadProject } from './project.mjs'
4
+ import { DEFAULT_GLIBC, binaryName, findTarget, hostTargetId, zigTriple } from './targets.mjs'
5
+ import { createUniversal } from './macho.mjs'
6
+ import { run, zigExe } from './exec.mjs'
7
+
8
+ const OPTIMIZE_MODES = { debug: 'debug', safe: 'safe', fast: 'fast', small: 'small' }
9
+ // Spellings used by Zig before 0.17.
10
+ const LEGACY_MODES = { Debug: 'debug', ReleaseSafe: 'safe', ReleaseFast: 'fast', ReleaseSmall: 'small' }
11
+
12
+ export function optimizeMode(name = 'fast') {
13
+ const mode = OPTIMIZE_MODES[name] ?? LEGACY_MODES[name]
14
+ if (!mode) throw new Error(`unknown optimize mode '${name}' (expected debug, safe, fast or small)`)
15
+ return mode
16
+ }
17
+
18
+ /**
19
+ * Runs `zig build` once per target and collects the results next to
20
+ * package.json as `<name>.<target>.node` (plus `index.d.ts`).
21
+ */
22
+ export function build(options) {
23
+ const project = loadProject(resolve(options.cwd ?? '.'))
24
+ const outDir = resolve(project.dir, options.outDir ?? '.')
25
+ mkdirSync(outDir, { recursive: true })
26
+
27
+ let targetIds = options.targets?.length ? options.targets : [hostTargetId()]
28
+ if (options.all) {
29
+ if (!project.targets.length) throw new Error('--all needs a "napi.targets" list in package.json')
30
+ targetIds = project.targets
31
+ }
32
+ const targets = targetIds.map(findTarget)
33
+
34
+ // Merged targets need their parts; build those first (once).
35
+ const order = []
36
+ for (const target of targets) {
37
+ for (const part of target.merge ?? []) {
38
+ if (!order.some((t) => t.id === part)) order.push(findTarget(part))
39
+ }
40
+ if (!order.some((t) => t.id === target.id)) order.push(target)
41
+ }
42
+
43
+ const optimize = optimizeMode(options.optimize)
44
+ const built = []
45
+ for (const target of order) {
46
+ const dest = join(outDir, binaryName(project.addonName, target))
47
+ if (target.merge) {
48
+ const parts = target.merge.map((id) => readFileSync(join(outDir, binaryName(project.addonName, findTarget(id)))))
49
+ console.log(`napi-zig: merging ${target.merge.join(' + ')} into ${target.id}`)
50
+ writeFileSync(dest, createUniversal(parts), { mode: 0o755 })
51
+ built.push(dest)
52
+ continue
53
+ }
54
+
55
+ // Each target gets its own prefix so parallel or repeated builds never
56
+ // pick up another target's output.
57
+ const prefix = mkdtempSync(join(project.dir, '.zig-cache-napi-'))
58
+ try {
59
+ const args = ['build', '--prefix', prefix, `-Doptimize=${optimize}`]
60
+ // A native build lets zig use the host CPU/libc defaults.
61
+ if (target.id !== hostTargetId() || options.portable) {
62
+ args.push(`-Dtarget=${zigTriple(target, options.glibc ?? DEFAULT_GLIBC)}`)
63
+ }
64
+ args.push(...(target.zigArgs ?? []))
65
+ if (options.dynamicHost) args.push('-Ddynamic-host=true')
66
+ args.push(...(options.zigArgs ?? []))
67
+ console.log(`napi-zig: building ${project.addonName} for ${target.id}`)
68
+ run(zigExe(), args, { cwd: project.dir })
69
+
70
+ const produced = `${project.addonName}.${target.ext ?? 'node'}`
71
+ const source = join(prefix, produced)
72
+ if (!existsSync(source)) {
73
+ throw new Error(
74
+ `zig build did not produce ${produced}. ` +
75
+ `Does build.zig call addAddon with .name = "${project.addonName}" and addon.install(b)?`,
76
+ )
77
+ }
78
+ copyFileSync(source, dest)
79
+ built.push(dest)
80
+
81
+ const dts = join(prefix, project.dts)
82
+ if (existsSync(dts)) copyFileSync(dts, join(outDir, project.dts))
83
+ } finally {
84
+ rmSync(prefix, { recursive: true, force: true })
85
+ }
86
+ }
87
+ for (const file of built) console.log(`napi-zig: wrote ${file}`)
88
+ return built
89
+ }
package/lib/exec.mjs ADDED
@@ -0,0 +1,15 @@
1
+ import { spawnSync } from 'node:child_process'
2
+
3
+ /** Runs a command, streaming its output; throws if it fails. */
4
+ export function run(command, args, options = {}) {
5
+ const result = spawnSync(command, args, { stdio: 'inherit', ...options })
6
+ if (result.error) {
7
+ if (result.error.code === 'ENOENT') throw new Error(`'${command}' was not found in PATH`)
8
+ throw result.error
9
+ }
10
+ if (result.status !== 0) throw new Error(`${command} ${args.join(' ')} exited with code ${result.status}`)
11
+ }
12
+
13
+ export function zigExe() {
14
+ return process.env.NAPI_ZIG_ZIG ?? 'zig'
15
+ }
package/lib/index.mjs ADDED
@@ -0,0 +1,8 @@
1
+ // Programmatic API of @hunghg255/napi-zig-cli: the functions behind each command.
2
+ export { build, optimizeMode } from './build.mjs'
3
+ export { artifacts, platformPackageName } from './artifacts.mjs'
4
+ export { publish, publishPlan } from './publish.mjs'
5
+ export { newProject, NAPI_ZIG_URL } from './new.mjs'
6
+ export { TARGETS, DEFAULT_GLIBC, findTarget, hostTargetId, zigTriple, binaryName } from './targets.mjs'
7
+ export { createUniversal, readUniversal, machoArch } from './macho.mjs'
8
+ export { loadProject } from './project.mjs'
package/lib/macho.mjs ADDED
@@ -0,0 +1,74 @@
1
+ // Universal (fat) Mach-O files: what `lipo -create` produces, written
2
+ // directly so that universal binaries can be made on any host OS.
3
+ //
4
+ // Layout (all header fields big-endian):
5
+ // fat_header { magic = 0xcafebabe, nfat_arch }
6
+ // fat_arch[] { cputype, cpusubtype, offset, size, align }
7
+ // ...each thin image at its page-aligned offset
8
+
9
+ const FAT_MAGIC = 0xcafebabe
10
+ const MH_MAGIC_64 = 0xfeedfacf
11
+ // 16 KiB: the page size of arm64 macOS, and a valid alignment for x86_64 too.
12
+ const ALIGN_LOG2 = 14
13
+
14
+ const CPU_NAMES = new Map([
15
+ [0x01000007, 'x86_64'],
16
+ [0x0100000c, 'arm64'],
17
+ ])
18
+
19
+ /** Reads the architecture of a thin 64-bit Mach-O image. */
20
+ export function machoArch(image) {
21
+ if (image.length < 32 || image.readUInt32LE(0) !== MH_MAGIC_64) {
22
+ throw new Error('not a thin 64-bit Mach-O file')
23
+ }
24
+ const cputype = image.readUInt32LE(4)
25
+ const cpusubtype = image.readUInt32LE(8)
26
+ return { cputype, cpusubtype, name: CPU_NAMES.get(cputype) ?? `cpu 0x${cputype.toString(16)}` }
27
+ }
28
+
29
+ /** Merges thin Mach-O images (one per architecture) into a universal file. */
30
+ export function createUniversal(images) {
31
+ if (images.length < 2) throw new Error('a universal binary needs at least two architectures')
32
+ const archs = images.map(machoArch)
33
+ const names = archs.map((a) => a.name)
34
+ if (new Set(names).size !== names.length) throw new Error(`duplicate architecture in universal binary: ${names.join(', ')}`)
35
+
36
+ const align = 1 << ALIGN_LOG2
37
+ const headerSize = 8 + 20 * images.length
38
+ let offset = Math.ceil(headerSize / align) * align
39
+ const offsets = images.map((image) => {
40
+ const start = offset
41
+ offset = Math.ceil((offset + image.length) / align) * align
42
+ return start
43
+ })
44
+ const last = images.length - 1
45
+ const out = Buffer.alloc(offsets[last] + images[last].length)
46
+
47
+ out.writeUInt32BE(FAT_MAGIC, 0)
48
+ out.writeUInt32BE(images.length, 4)
49
+ images.forEach((image, i) => {
50
+ const entry = 8 + 20 * i
51
+ out.writeUInt32BE(archs[i].cputype, entry)
52
+ out.writeUInt32BE(archs[i].cpusubtype, entry + 4)
53
+ out.writeUInt32BE(offsets[i], entry + 8)
54
+ out.writeUInt32BE(image.length, entry + 12)
55
+ out.writeUInt32BE(ALIGN_LOG2, entry + 16)
56
+ image.copy(out, offsets[i])
57
+ })
58
+ return out
59
+ }
60
+
61
+ /** Lists the slices of a universal file: [{ name, offset, size }]. */
62
+ export function readUniversal(file) {
63
+ if (file.readUInt32BE(0) !== FAT_MAGIC) throw new Error('not a universal Mach-O file')
64
+ const count = file.readUInt32BE(4)
65
+ return Array.from({ length: count }, (_, i) => {
66
+ const entry = 8 + 20 * i
67
+ const cputype = file.readUInt32BE(entry)
68
+ return {
69
+ name: CPU_NAMES.get(cputype) ?? `cpu 0x${cputype.toString(16)}`,
70
+ offset: file.readUInt32BE(entry + 8),
71
+ size: file.readUInt32BE(entry + 12),
72
+ }
73
+ })
74
+ }
package/lib/new.mjs ADDED
@@ -0,0 +1,97 @@
1
+ import { existsSync, mkdirSync, readdirSync, readFileSync, writeFileSync } from 'node:fs'
2
+ import { randomInt } from 'node:crypto'
3
+ import { crc32 } from 'node:zlib'
4
+ import { dirname, isAbsolute, join, relative, resolve } from 'node:path'
5
+ import { fileURLToPath } from 'node:url'
6
+
7
+ const templateDir = join(dirname(fileURLToPath(import.meta.url)), '..', 'template')
8
+
9
+ const { version } = JSON.parse(readFileSync(new URL('../package.json', import.meta.url), 'utf8'))
10
+
11
+ /** The napi-zig Zig package matching this CLI release. */
12
+ export const NAPI_ZIG_URL = `git+https://github.com/hunghg255/napi-zig#v${version}`
13
+
14
+ const DEFAULT_TARGETS = [
15
+ 'linux-x64-gnu',
16
+ 'linux-arm64-gnu',
17
+ 'linux-x64-musl',
18
+ 'linux-arm64-musl',
19
+ 'darwin-x64',
20
+ 'darwin-arm64',
21
+ 'win32-x64',
22
+ 'win32-arm64',
23
+ ]
24
+
25
+ /** A valid Zig identifier derived from the package name. */
26
+ export function zigName(name) {
27
+ const ident = name.replace(/^@[^/]+\//, '').replace(/[^A-Za-z0-9_]/g, '_')
28
+ return /^[0-9]/.test(ident) ? `_${ident}` : ident
29
+ }
30
+
31
+ /**
32
+ * build.zig.zon fingerprints pair a random id (low 32 bits) with the CRC-32
33
+ * of the package name (high 32 bits).
34
+ */
35
+ export function fingerprint(name) {
36
+ const id = BigInt(randomInt(1, 0xffffffff))
37
+ return '0x' + ((BigInt(crc32(name)) << 32n) | id).toString(16)
38
+ }
39
+
40
+ function walk(dir) {
41
+ return readdirSync(dir, { withFileTypes: true }).flatMap((entry) =>
42
+ entry.isDirectory() ? walk(join(dir, entry.name)) : [join(dir, entry.name)],
43
+ )
44
+ }
45
+
46
+ /** Scaffolds a new addon project in `<cwd>/<name>`. */
47
+ export function newProject(options) {
48
+ const name = options.name
49
+ if (!name) throw new Error('usage: napi-zig new <name> [--napi-path <dir> | --napi-url <url>]')
50
+ if (!/^(@[a-z0-9-~][a-z0-9-._~]*\/)?[a-z0-9-~][a-z0-9-._~]*$/.test(name)) {
51
+ throw new Error(`'${name}' is not a valid npm package name`)
52
+ }
53
+ const addonName = name.replace(/^@[^/]+\//, '')
54
+ const dir = resolve(options.cwd ?? '.', addonName)
55
+ if (existsSync(dir) && readdirSync(dir).length > 0) throw new Error(`${dir} already exists and is not empty`)
56
+
57
+ const napiUrl = options.napiUrl ?? NAPI_ZIG_URL
58
+ let dependency = ` // Added by: zig fetch --save=napi ${napiUrl}`
59
+ if (options.napiPath) {
60
+ const target = resolve(options.cwd ?? '.', options.napiPath)
61
+ const relPath = relative(dir, target)
62
+ // build.zig.zon only accepts paths relative to the project. On Windows
63
+ // there is none between two drives.
64
+ if (isAbsolute(relPath)) {
65
+ throw new Error(`--napi-path ${target} must be on the same drive as the project (${dir}); use --napi-url instead`)
66
+ }
67
+ const rel = relPath.split('\\').join('/')
68
+ dependency = ` .napi = .{ .path = "${rel}" },`
69
+ }
70
+
71
+ const zig = zigName(name)
72
+ const values = {
73
+ PACKAGE_NAME: name,
74
+ ADDON_NAME: addonName,
75
+ ZIG_NAME: zig,
76
+ FINGERPRINT: fingerprint(zig),
77
+ NAPI_DEPENDENCY: dependency,
78
+ TARGETS: JSON.stringify(DEFAULT_TARGETS),
79
+ }
80
+
81
+ for (const file of walk(templateDir)) {
82
+ // Dotfiles are stored without the dot so npm does not drop them.
83
+ const rel = relative(templateDir, file).replace(/\.tmpl$/, '').replace(/(^|[\\/])_dot_/, '$1.')
84
+ const dest = join(dir, rel)
85
+ mkdirSync(dirname(dest), { recursive: true })
86
+ const text = readFileSync(file, 'utf8').replace(/\{\{([A-Z_]+)\}\}/g, (match, key) => values[key] ?? match)
87
+ writeFileSync(dest, text)
88
+ }
89
+
90
+ console.log(`napi-zig: created ${dir}`)
91
+ const steps = [`cd ${addonName}`]
92
+ // The dependency hash is only known to zig, so it writes that entry.
93
+ if (!options.napiPath) steps.push(`zig fetch --save=napi ${napiUrl}`)
94
+ steps.push('npm install', 'npm run build', 'npm test')
95
+ console.log(`\nNext steps:\n ${steps.join('\n ')}`)
96
+ return dir
97
+ }
@@ -0,0 +1,27 @@
1
+ import { readFileSync, existsSync } from 'node:fs'
2
+ import { join } from 'node:path'
3
+
4
+ /**
5
+ * Reads the addon configuration from package.json:
6
+ *
7
+ * "napi": { "name": "my-addon", "targets": ["linux-x64-gnu", ...] }
8
+ *
9
+ * `name` is the addon name given to `addAddon` in build.zig (the build
10
+ * produces `<name>.node`); it defaults to the unscoped package name.
11
+ */
12
+ export function loadProject(dir) {
13
+ const packagePath = join(dir, 'package.json')
14
+ if (!existsSync(packagePath)) throw new Error(`no package.json in ${dir}`)
15
+ const pkg = JSON.parse(readFileSync(packagePath, 'utf8'))
16
+ const config = pkg.napi ?? {}
17
+ const addonName = config.name ?? String(pkg.name ?? '').replace(/^@[^/]+\//, '')
18
+ if (!addonName) throw new Error('package.json needs a "name" or a "napi.name"')
19
+ return {
20
+ dir,
21
+ packagePath,
22
+ pkg,
23
+ addonName,
24
+ targets: config.targets ?? [],
25
+ dts: config.dts ?? 'index.d.ts',
26
+ }
27
+ }
@@ -0,0 +1,94 @@
1
+ import { existsSync, readFileSync, readdirSync } from 'node:fs'
2
+ import { dirname, join, resolve } from 'node:path'
3
+ import { loadProject } from './project.mjs'
4
+ import { binaryName, findTarget } from './targets.mjs'
5
+ import { platformPackageName } from './artifacts.mjs'
6
+ import { run } from './exec.mjs'
7
+
8
+ /**
9
+ * How to start npm with `args`, as `[command, argv, spawnOptions]`.
10
+ *
11
+ * Node cannot spawn `npm.cmd` (or a script file) directly on Windows, so a
12
+ * JavaScript entry point (`NAPI_ZIG_NPM=path/to/npm-cli.js`, or the npm that
13
+ * ships next to the running node) is started with this node; only as a last
14
+ * resort does Windows go through the shell, with every argument quoted.
15
+ */
16
+ export function npmCommand(args) {
17
+ const isScript = (file) => /\.[cm]?js$/i.test(file)
18
+ const override = process.env.NAPI_ZIG_NPM
19
+ if (override) {
20
+ return isScript(override) ? [process.execPath, [override, ...args], {}] : [override, args, {}]
21
+ }
22
+ if (process.platform !== 'win32') return ['npm', args, {}]
23
+ const bundled = join(dirname(process.execPath), 'node_modules', 'npm', 'bin', 'npm-cli.js')
24
+ if (existsSync(bundled)) return [process.execPath, [bundled, ...args], {}]
25
+ for (const arg of args) {
26
+ if (/["%^&|<>!\r\n]/.test(arg)) throw new Error(`cannot pass ${JSON.stringify(arg)} to npm.cmd safely`)
27
+ }
28
+ return ['npm.cmd', args.map((arg) => `"${arg}"`), { shell: true }]
29
+ }
30
+
31
+ /**
32
+ * Checks that everything `publish` would upload is in place and consistent.
33
+ * Returns the directories to publish, platform packages first: the main
34
+ * package must not become installable before its binaries are.
35
+ */
36
+ export function publishPlan(project) {
37
+ const { pkg, addonName } = project
38
+ if (pkg.private) throw new Error('package.json has "private": true')
39
+ const npmDir = join(project.dir, 'npm')
40
+ if (!existsSync(npmDir)) throw new Error('no npm/ directory: run "napi-zig artifacts" first')
41
+
42
+ const problems = []
43
+ const dirs = []
44
+ for (const id of readdirSync(npmDir).sort()) {
45
+ const dir = join(npmDir, id)
46
+ const manifestPath = join(dir, 'package.json')
47
+ if (!existsSync(manifestPath)) continue
48
+ const manifest = JSON.parse(readFileSync(manifestPath, 'utf8'))
49
+ const binary = binaryName(addonName, findTarget(id))
50
+ const expectedName = platformPackageName(pkg, id)
51
+ if (manifest.name !== expectedName) problems.push(`npm/${id}: name is ${manifest.name}, expected ${expectedName}`)
52
+ if (manifest.version !== pkg.version) {
53
+ problems.push(`npm/${id}: version ${manifest.version} does not match ${pkg.version} (re-run "napi-zig artifacts")`)
54
+ }
55
+ if (!existsSync(join(dir, binary))) problems.push(`npm/${id}: ${binary} is missing (build it, then re-run "napi-zig artifacts")`)
56
+ if (pkg.optionalDependencies?.[expectedName] !== pkg.version) {
57
+ problems.push(`package.json: optionalDependencies["${expectedName}"] should be "${pkg.version}"`)
58
+ }
59
+ dirs.push(dir)
60
+ }
61
+ if (!dirs.length) problems.push('npm/ contains no platform packages')
62
+ for (const file of [pkg.main, pkg.types].filter(Boolean)) {
63
+ if (!existsSync(join(project.dir, file))) problems.push(`${file} (referenced by package.json) does not exist`)
64
+ }
65
+ if (problems.length) throw new Error(`not ready to publish:\n - ${problems.join('\n - ')}`)
66
+ return [...dirs, project.dir]
67
+ }
68
+
69
+ /**
70
+ * Publishes the platform packages and then the main package with
71
+ * `npm publish`. With `dryRun`, npm packs and reports but uploads nothing.
72
+ */
73
+ export function publish(options) {
74
+ const project = loadProject(resolve(options.cwd ?? '.'))
75
+ const dirs = publishPlan(project)
76
+
77
+ const args = ['publish', '--access', options.access ?? 'public']
78
+ if (options.tag) args.push('--tag', options.tag)
79
+ if (options.otp) args.push('--otp', options.otp)
80
+ if (options.provenance) args.push('--provenance')
81
+ if (options.dryRun) args.push('--dry-run')
82
+
83
+ for (const dir of dirs) {
84
+ console.log(`napi-zig: ${options.dryRun ? '[dry run] ' : ''}npm ${args.join(' ')} (in ${dir})`)
85
+ const [command, argv, spawnOptions] = npmCommand(args)
86
+ run(command, argv, { ...spawnOptions, cwd: dir })
87
+ }
88
+ console.log(
89
+ options.dryRun
90
+ ? `napi-zig: dry run complete, ${dirs.length} packages checked, nothing was uploaded`
91
+ : `napi-zig: published ${dirs.length} packages`,
92
+ )
93
+ return dirs
94
+ }
@@ -0,0 +1,61 @@
1
+ // The platforms an addon can be built for. `id` is the suffix used in file
2
+ // and package names (`<name>.<id>.node`, `<package>-<id>`); `zig` is the
3
+ // target triple handed to `zig build -Dtarget=`.
4
+
5
+ // Node.js 18+ requires glibc 2.28, so there is no point in targeting less.
6
+ export const DEFAULT_GLIBC = '2.28'
7
+
8
+ export const TARGETS = [
9
+ { id: 'linux-x64-gnu', os: 'linux', cpu: ['x64'], libc: 'glibc', zig: 'x86_64-linux-gnu' },
10
+ { id: 'linux-arm64-gnu', os: 'linux', cpu: ['arm64'], libc: 'glibc', zig: 'aarch64-linux-gnu' },
11
+ { id: 'linux-x64-musl', os: 'linux', cpu: ['x64'], libc: 'musl', zig: 'x86_64-linux-musl' },
12
+ { id: 'linux-arm64-musl', os: 'linux', cpu: ['arm64'], libc: 'musl', zig: 'aarch64-linux-musl' },
13
+ { id: 'darwin-x64', os: 'darwin', cpu: ['x64'], zig: 'x86_64-macos' },
14
+ { id: 'darwin-arm64', os: 'darwin', cpu: ['arm64'], zig: 'aarch64-macos' },
15
+ // One file for both Mac architectures, made by merging the two above.
16
+ { id: 'darwin-universal', os: 'darwin', cpu: ['x64', 'arm64'], merge: ['darwin-x64', 'darwin-arm64'] },
17
+ { id: 'win32-x64', os: 'win32', cpu: ['x64'], zig: 'x86_64-windows-gnu' },
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.
23
+ {
24
+ id: 'wasm32-wasi-threads',
25
+ zig: 'wasm32-wasi',
26
+ zigArgs: ['-Dcpu=baseline+atomics+bulk_memory'],
27
+ ext: 'wasm',
28
+ experimental: true,
29
+ },
30
+ ]
31
+
32
+ export function findTarget(id) {
33
+ const target = TARGETS.find((t) => t.id === id)
34
+ if (!target) {
35
+ throw new Error(`unknown target '${id}'. Known targets: ${TARGETS.map((t) => t.id).join(', ')}`)
36
+ }
37
+ return target
38
+ }
39
+
40
+ /** `<name>.<target>.node` (or `.wasm`). */
41
+ export function binaryName(addonName, target) {
42
+ return `${addonName}.${target.id}.${target.ext ?? 'node'}`
43
+ }
44
+
45
+ /** The zig triple, with the glibc version pinned for gnu targets. */
46
+ export function zigTriple(target, glibc = DEFAULT_GLIBC) {
47
+ return target.libc === 'glibc' ? `${target.zig}.${glibc}` : target.zig
48
+ }
49
+
50
+ function isMusl() {
51
+ if (process.platform !== 'linux') return false
52
+ const report = process.report?.getReport?.()
53
+ return !report?.header?.glibcVersionRuntime
54
+ }
55
+
56
+ /** The target id of the running Node.js process. */
57
+ export function hostTargetId() {
58
+ const { platform, arch } = process
59
+ if (platform === 'linux') return `linux-${arch}-${isMusl() ? 'musl' : 'gnu'}`
60
+ return `${platform}-${arch}`
61
+ }
package/package.json CHANGED
@@ -1,6 +1,51 @@
1
1
  {
2
2
  "name": "@hunghg255/napi-zig-cli",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "1.1.0",
4
+ "description": "Command line tool for napi-zig: scaffold, build, cross-compile and publish Node.js native addons written in Zig",
5
+ "keywords": [
6
+ "napi",
7
+ "node-api",
8
+ "n-api",
9
+ "zig",
10
+ "native",
11
+ "addon",
12
+ "node-addon",
13
+ "cross-compile",
14
+ "cli"
15
+ ],
16
+ "homepage": "https://github.com/hunghg255/napi-zig#readme",
17
+ "bugs": {
18
+ "url": "https://github.com/hunghg255/napi-zig/issues"
19
+ },
20
+ "repository": {
21
+ "type": "git",
22
+ "url": "git+https://github.com/hunghg255/napi-zig.git",
23
+ "directory": "cli"
24
+ },
25
+ "license": "MIT",
26
+ "type": "module",
27
+ "bin": {
28
+ "napi-zig": "bin/napi-zig.mjs"
29
+ },
30
+ "main": "./lib/index.mjs",
31
+ "exports": {
32
+ ".": "./lib/index.mjs",
33
+ "./package.json": "./package.json"
34
+ },
35
+ "files": [
36
+ "bin",
37
+ "lib",
38
+ "template",
39
+ "README.md",
40
+ "LICENSE"
41
+ ],
42
+ "scripts": {
43
+ "test": "node --test test/*.test.mjs"
44
+ },
45
+ "engines": {
46
+ "node": ">=18.17"
47
+ },
48
+ "publishConfig": {
49
+ "access": "public"
50
+ }
51
+ }
@@ -0,0 +1,75 @@
1
+ # Build every target on one Linux runner (Zig cross-compiles), test the
2
+ # binaries on each OS, and publish to npm when a v* tag is pushed.
3
+ #
4
+ # Publishing needs an npm automation token in the NPM_TOKEN repository secret.
5
+ name: CI
6
+
7
+ on:
8
+ push:
9
+ branches: [main]
10
+ tags: ['v*']
11
+ pull_request:
12
+
13
+ env:
14
+ ZIG_VERSION: 0.17.1
15
+
16
+ jobs:
17
+ build:
18
+ runs-on: ubuntu-latest
19
+ steps:
20
+ - uses: actions/checkout@v4
21
+ - uses: mlugg/setup-zig@v2
22
+ with:
23
+ version: ${{ env.ZIG_VERSION }}
24
+ - uses: actions/setup-node@v4
25
+ with:
26
+ node-version: 22
27
+ - run: npm install
28
+ - run: npx napi-zig build --all
29
+ - uses: actions/upload-artifact@v4
30
+ with:
31
+ name: binaries
32
+ path: |
33
+ *.node
34
+ index.d.ts
35
+ if-no-files-found: error
36
+
37
+ test:
38
+ needs: build
39
+ strategy:
40
+ fail-fast: false
41
+ matrix:
42
+ os: [ubuntu-latest, ubuntu-24.04-arm, macos-latest, macos-13, windows-latest]
43
+ node: [20, 22]
44
+ runs-on: ${{ matrix.os }}
45
+ steps:
46
+ - uses: actions/checkout@v4
47
+ - uses: actions/setup-node@v4
48
+ with:
49
+ node-version: ${{ matrix.node }}
50
+ - uses: actions/download-artifact@v4
51
+ with:
52
+ name: binaries
53
+ - run: npm test
54
+
55
+ publish:
56
+ needs: test
57
+ if: startsWith(github.ref, 'refs/tags/v')
58
+ runs-on: ubuntu-latest
59
+ permissions:
60
+ contents: read
61
+ id-token: write
62
+ steps:
63
+ - uses: actions/checkout@v4
64
+ - uses: actions/setup-node@v4
65
+ with:
66
+ node-version: 22
67
+ registry-url: https://registry.npmjs.org
68
+ - run: npm install
69
+ - uses: actions/download-artifact@v4
70
+ with:
71
+ name: binaries
72
+ - run: npx napi-zig artifacts
73
+ - run: npx napi-zig publish --provenance
74
+ env:
75
+ NODE_AUTH_TOKEN: ${{ secrets.NPM_TOKEN }}
@@ -0,0 +1,7 @@
1
+ .zig-cache/
2
+ .zig-cache-napi-*/
3
+ zig-out/
4
+ node_modules/
5
+ *.node
6
+ index.d.ts
7
+ npm/
@@ -0,0 +1,19 @@
1
+ const std = @import("std");
2
+ const napi = @import("napi");
3
+
4
+ pub fn build(b: *std.Build) void {
5
+ // -Ddynamic-host: resolve Node-API in the host process at load time
6
+ // instead of importing it from `node.exe` (needed for Electron on Windows).
7
+ const dynamic_host = b.option(bool, "dynamic-host", "Bind Node-API at load time (Electron, renamed hosts)") orelse false;
8
+
9
+ const addon = napi.addAddon(b, .{
10
+ .name = "{{ADDON_NAME}}",
11
+ .root_source_file = b.path("src/lib.zig"),
12
+ .target = b.standardTargetOptions(.{}),
13
+ .optimize = b.standardOptimizeOption(.{}),
14
+ .napi = b.dependency("napi", .{}),
15
+ .host_binding = if (dynamic_host) .dynamic else .import,
16
+ });
17
+ // Installs {{ADDON_NAME}}.node and index.d.ts into the prefix (zig-out/).
18
+ addon.install(b);
19
+ }
@@ -0,0 +1,10 @@
1
+ .{
2
+ .name = .{{ZIG_NAME}},
3
+ .version = "0.1.0",
4
+ .fingerprint = {{FINGERPRINT}},
5
+ .minimum_zig_version = "0.17.0",
6
+ .dependencies = .{
7
+ {{NAPI_DEPENDENCY}}
8
+ },
9
+ .paths = .{ "build.zig", "build.zig.zon", "src" },
10
+ }
@@ -0,0 +1,39 @@
1
+ // Loads the binary for the current platform: a local build if there is one
2
+ // (`napi-zig build`), otherwise the prebuilt optional dependency.
3
+ 'use strict'
4
+
5
+ const { existsSync } = require('node:fs')
6
+ const { join } = require('node:path')
7
+
8
+ const ADDON = '{{ADDON_NAME}}'
9
+ const PACKAGE = '{{PACKAGE_NAME}}'
10
+
11
+ function targetIds() {
12
+ const { platform, arch } = process
13
+ if (platform === 'darwin') return [`darwin-${arch}`, 'darwin-universal']
14
+ if (platform !== 'linux') return [`${platform}-${arch}`]
15
+ const report = process.report && process.report.getReport()
16
+ const glibc = report && report.header && report.header.glibcVersionRuntime
17
+ return [`linux-${arch}-${glibc ? 'gnu' : 'musl'}`]
18
+ }
19
+
20
+ function load() {
21
+ const ids = targetIds()
22
+ const errors = []
23
+ for (const id of ids) {
24
+ const local = join(__dirname, `${ADDON}.${id}.node`)
25
+ if (existsSync(local)) return require(local)
26
+ try {
27
+ return require(`${PACKAGE}-${id}`)
28
+ } catch (err) {
29
+ errors.push(err)
30
+ }
31
+ }
32
+ 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.`,
35
+ { cause: errors[0] },
36
+ )
37
+ }
38
+
39
+ module.exports = load()
@@ -0,0 +1,27 @@
1
+ {
2
+ "name": "{{PACKAGE_NAME}}",
3
+ "version": "0.1.0",
4
+ "description": "A Node.js addon written in Zig",
5
+ "main": "index.js",
6
+ "types": "index.d.ts",
7
+ "files": [
8
+ "index.js",
9
+ "index.d.ts"
10
+ ],
11
+ "napi": {
12
+ "name": "{{ADDON_NAME}}",
13
+ "targets": {{TARGETS}}
14
+ },
15
+ "scripts": {
16
+ "build": "napi-zig build",
17
+ "build:debug": "napi-zig build --debug",
18
+ "build:all": "napi-zig build --all",
19
+ "artifacts": "napi-zig artifacts",
20
+ "release": "napi-zig build --all && napi-zig artifacts && napi-zig publish",
21
+ "test": "node --test"
22
+ },
23
+ "devDependencies": {
24
+ "@hunghg255/napi-zig-cli": "^1.1.0"
25
+ },
26
+ "license": "MIT"
27
+ }
@@ -0,0 +1,39 @@
1
+ const std = @import("std");
2
+ const napi = @import("napi");
3
+
4
+ /// Adds two numbers.
5
+ pub fn sum(a: i32, b: i32) i32 {
6
+ return a + b;
7
+ }
8
+
9
+ /// Returns a greeting. `alloc` is a per-call arena managed by napi-zig.
10
+ pub fn greet(alloc: std.mem.Allocator, name: []const u8) ![]u8 {
11
+ return std.fmt.allocPrint(alloc, "Hello, {s}!", .{name});
12
+ }
13
+
14
+ /// Structs with pub fns become JS classes.
15
+ pub const Counter = struct {
16
+ value: i64,
17
+
18
+ pub fn init(start: ?i64) Counter {
19
+ return .{ .value = start orelse 0 };
20
+ }
21
+
22
+ pub fn inc(self: *Counter) i64 {
23
+ self.value += 1;
24
+ return self.value;
25
+ }
26
+ };
27
+
28
+ fn fibWork(n: u32) u64 {
29
+ return if (n < 2) n else fibWork(n - 1) + fibWork(n - 2);
30
+ }
31
+
32
+ /// Runs on a worker thread and resolves a Promise.
33
+ pub fn fib(n: u32) napi.Async(u64) {
34
+ return .spawn(fibWork, .{n});
35
+ }
36
+
37
+ comptime {
38
+ napi.module(@This());
39
+ }
@@ -0,0 +1,23 @@
1
+ 'use strict'
2
+
3
+ const { test } = require('node:test')
4
+ const assert = require('node:assert/strict')
5
+ const addon = require('..')
6
+
7
+ test('sum', () => {
8
+ assert.equal(addon.sum(2, 3), 5)
9
+ })
10
+
11
+ test('greet', () => {
12
+ assert.equal(addon.greet('Zig'), 'Hello, Zig!')
13
+ })
14
+
15
+ test('Counter', () => {
16
+ const counter = new addon.Counter(41)
17
+ assert.equal(counter.inc(), 42)
18
+ assert.equal(counter.value, 42)
19
+ })
20
+
21
+ test('fib', async () => {
22
+ assert.equal(await addon.fib(20), 6765)
23
+ })