### Install zig-napi Package with Zig Package Manager Source: https://github.com/jiacai2050/zig-napi/blob/main/README.org Shows the command-line steps to install the zig-napi package using Zig's built-in package manager. Requires fetching the package from GitHub with a specific tag or commit ID, then updating build.zig configuration. ```bash zig fetch --save git+https://github.com/jiacai2050/zig-napi#{TAG_OR_COMMIT_ID} ``` -------------------------------- ### Configure Zig N-API Addon in build.zig Source: https://github.com/jiacai2050/zig-napi/blob/main/README.org Demonstrates the build configuration needed to compile a Zig N-API addon. Sets up a dynamic library linking with the napi package as an import, configures the output as a .node file, and installs it for use in Node.js. Requires specifying the root source file, optimization level, and target. ```zig const name = "napi-demo"; const addon = b.addLibrary(.{ .name = name, .root_module = b.createModule(.{ .root_source_file = b.path("src/root.zig"), .optimize = optimize, .target = target, }), .linkage = .dynamic, }); const dep_napi = b.dependency("napi", .{}); addon.root_module.addImport("napi", dep_napi.module("napi")); addon.linker_allow_shlib_undefined = true; const install_lib = b.addInstallArtifact(addon, .{ .dest_sub_path = name ++ ".node", }); b.getInstallStep().dependOn(&install_lib.step); ``` -------------------------------- ### JavaScript Usage of String Creation Functions (JavaScript) Source: https://context7.com/jiacai2050/zig-napi/llms.txt This JavaScript code shows how to call Zig functions that create and process JavaScript strings. It demonstrates calling `createGreeting` to get a simple string and `processName` to process an input string. ```javascript const addon = require('./addon.node'); console.log(addon.createGreeting()); // "Hello from Zig!" console.log(addon.processName("Alice")); // "Processed: Alice" ``` -------------------------------- ### Export Zig Functions to JavaScript with N-API Source: https://context7.com/jiacai2050/zig-napi/llms.txt Expose Zig functions to JavaScript. This example shows how to define an 'add' function and a 'greeting' function in Zig that can be called directly from Node.js. It handles type conversions (e.g., f64, string) and error propagation. ```zig const napi = @import("napi"); const std = @import("std"); pub fn add(env: napi.Env, n1: napi.Value, n2: napi.Value) !napi.Value { const d1 = try n1.getValue(f64); const d2 = try n2.getValue(f64); return try env.create(f64, d1 + d2); } pub fn greeting(env: napi.Env, who: napi.Value) !napi.Value { var buf: [64]u8 = undefined; const len = try who.getValueString(.utf8, &buf); const allocator = std.heap.page_allocator; const message = try std.fmt.allocPrint(allocator, "Hello {s}", .{buf[0..len]}); defer allocator.free(message); return try env.createString(.utf8, message); } fn init(env: napi.Env, exports: napi.Value) !napi.Value { try exports.setNamedProperty("add", try env.createFunction(add, null)); try exports.setNamedProperty("greeting", try env.createFunction(greeting, null)); return exports; } comptime { napi.registerModule(init); } ``` ```javascript const addon = require('./addon.node'); console.log(addon.add(10, 20)); // 30 console.log(addon.greeting("Tom")); // "Hello Tom" ``` -------------------------------- ### Call JavaScript Functions from Zig using N-API Source: https://context7.com/jiacai2050/zig-napi/llms.txt Invoke JavaScript functions from Zig code. This example demonstrates how to get a global JavaScript function ('AddTwo') and call it with arguments passed from Zig. It includes type checking for the retrieved function. ```zig const napi = @import("napi"); pub fn callAddTwoNumbers(env: napi.Env, num: napi.Value) !napi.Value { const global = try env.getGlobal(); const add_two = try global.getNamedProperty("AddTwo"); if ((try add_two.typeOf()) != .Function) { return error.TypeError; } const args = [_]napi.Value{num}; return add_two.callFunction(args.len, global, args); } comptime { napi.registerModule(init); } fn init(env: napi.Env, exports: napi.Value) !napi.Value { try exports.setNamedProperty( "callAddTwoNumbers", try env.createFunction(callAddTwoNumbers, null), ); return exports; } ``` ```javascript function AddTwo(num) { return num + 2; } global.AddTwo = AddTwo; const addon = require('./addon.node'); console.log(addon.callAddTwoNumbers(1)); // 3 console.log(addon.callAddTwoNumbers(101)); // 103 ``` -------------------------------- ### Property Access and Manipulation in Zig Source: https://context7.com/jiacai2050/zig-napi/llms.txt Provides Zig functions to manipulate JavaScript objects, including checking for named properties, getting property values, setting new properties, checking own properties, and deleting properties. ```zig const napi = @import("napi"); pub fn manipulateObject(env: napi.Env, obj: napi.Value) !napi.Value { // Check if property exists const has_name = try obj.hasNamedProperty("name"); if (has_name) { // Get property value const name = try obj.getNamedProperty("name"); _ = name; } // Set new property try obj.setNamedProperty("modified", try env.create(bool, true)); // Check own property (not inherited) const has_own = try obj.hasOwnProperty("modified"); // Delete property const deleted = try obj.deleteNamedProperty("temporary"); return try env.create(bool, has_own and deleted); } ``` -------------------------------- ### Register Zig Module with Node.js Runtime (Zig) Source: https://context7.com/jiacai2050/zig-napi/llms.txt This Zig code demonstrates how to register a module with the Node.js runtime using compile-time initialization. It defines an `init` function that sets up properties for the module, including a 'hello' function. The `registerModule` function is used for this purpose. ```zig const std = @import("std"); const napi = @import("napi"); comptime { napi.registerModule(init); } fn init(env: napi.Env, exports: napi.Value) !napi.Value { try exports.setNamedProperty( "hello", try env.createFunction(hello, null), ); return exports; } fn hello(env: napi.Env, who: napi.Value) !napi.Value { var buf: [64]u8 = undefined; const len = try who.getValueString(.utf8, &buf); const allocator = std.heap.page_allocator; const message = try std.fmt.allocPrint(allocator, "Hello {s}", .{buf[0..len]}); defer allocator.free(message); return try env.createString(.utf8, message); } ``` -------------------------------- ### Create Hello World N-API Module in Zig Source: https://github.com/jiacai2050/zig-napi/blob/main/README.org Demonstrates creating a basic Node.js native addon in Zig that exports a hello function. The function takes a string parameter, formats a greeting message, and returns it as an N-API string value. Requires registering the module with registerModule and implementing init and handler functions. ```zig const std = @import("std"); const napi = @import("napi"); // Every napi module needs to call `registerModule` to register it with the N-API runtime. comptime { napi.registerModule(init); } fn hello(env: napi.Env, who: napi.Value) !napi.Value { var buf: [64]u8 = undefined; const len = try who.getValueString(.utf8, &buf); const allocator = std.heap.page_allocator; const message = try std.fmt.allocPrint(allocator, "Hello {s}", .{buf[0..len]}); defer allocator.free(message); return try env.createString(.utf8, message); } fn init(env: napi.Env, exports: napi.Value) !napi.Value { try exports.setNamedProperty( "hello", try env.createFunction(hello, null), ); return exports; } ``` -------------------------------- ### JavaScript Usage of Object Creation Function (JavaScript) Source: https://context7.com/jiacai2050/zig-napi/llms.txt This JavaScript code demonstrates how to call a Zig function `makeObject` that returns a JavaScript object. It then logs the created object to the console, showing the properties set from Zig. ```javascript const addon = require('./addon.node'); const obj = addon.makeObject(); console.log(obj); // { // 'str-key': 'string prop', // 'i64-key': 100, // 'i32-key': 200, // 'u32-key': 201, // 'f64-key': 300, // 'null-key': null, // 'true-key': true, // 'false-key': false // } ``` -------------------------------- ### Node.js Addon Usage (JavaScript) Source: https://context7.com/jiacai2050/zig-napi/llms.txt This JavaScript code demonstrates how to require and use a Node.js native addon compiled from Zig using zig-napi. It shows calling the 'hello' function exported by the Zig module with a string argument. ```javascript const addon = require('./zig-out/lib/hello.node'); console.log(addon.hello('World')); // Output: "Hello World" ``` -------------------------------- ### Create JavaScript Strings from Zig (Zig) Source: https://context7.com/jiacai2050/zig-napi/llms.txt This Zig code illustrates creating JavaScript string values from Zig using different encodings. It includes a function `createGreeting` for a simple string and `processName` which formats a string received from JavaScript before returning it. ```zig const napi = @import("napi"); pub fn createGreeting(env: napi.Env) !napi.Value { // Create UTF-8 string const greeting = try env.createString(.utf8, "Hello from Zig!"); return greeting; } pub fn processName(env: napi.Env, name: napi.Value) !napi.Value { var buffer: [64]u8 = undefined; const len = try name.getValueString(.utf8, &buffer); const name_slice = buffer[0..len]; // Create formatted string const allocator = std.heap.page_allocator; const result = try std.fmt.allocPrint(allocator, "Processed: {s}", .{name_slice}); defer allocator.free(result); return try env.createString(.utf8, result); } ``` -------------------------------- ### Handle Scopes for Memory Management in JavaScript Source: https://context7.com/jiacai2050/zig-napi/llms.txt Demonstrates how to call Zig N-API functions that manage memory using scopes from JavaScript. It shows the expected output for functions using regular and escapable scopes. ```javascript const addon = require('./addon.node'); console.log(addon.processWithScope()); // "done" console.log(addon.processWithEscapeScope()); // "escaped value" ``` -------------------------------- ### Error Handling and Throwing in JavaScript Source: https://context7.com/jiacai2050/zig-napi/llms.txt Shows how to catch errors thrown from Zig N-API functions in JavaScript. It demonstrates using a try-catch block to handle expected errors during validation. ```javascript const addon = require('./addon.node'); try { addon.validateAndProcess("not a number"); } catch (err) { console.error(err.message); // "Expected a number" } ``` -------------------------------- ### Error Handling and Throwing in Zig Source: https://context7.com/jiacai2050/zig-napi/llms.txt Illustrates how to create and throw JavaScript errors from Zig with custom messages. It includes a function to validate input types and throw an error if validation fails, and another to directly throw an error. ```zig const napi = @import("napi"); pub fn validateAndProcess(env: napi.Env, value: napi.Value) !napi.Value { const value_type = try value.typeOf(); if (value_type != .Number) { // Create and throw an error const error_msg = try env.createString(.utf8, "Expected a number"); const error_obj = try env.createError(null, error_msg); try env.throw(error_obj); return error_obj; } const num = try value.getValue(f64); return try env.create(f64, num * 2); } pub fn throwDirectError(env: napi.Env) !void { try env.throwError(null, "Something went wrong!"); } ``` -------------------------------- ### Property Access and Manipulation in JavaScript Source: https://context7.com/jiacai2050/zig-napi/llms.txt Demonstrates interacting with Zig N-API functions that manipulate JavaScript objects. It shows how to pass an object to a Zig function and observe the modifications made to it. ```javascript const addon = require('./addon.node'); const obj = { name: "test", temporary: "value" }; addon.manipulateObject(obj); console.log(obj); // { name: "test", modified: true } ``` -------------------------------- ### Handle Scopes for Memory Management in Zig Source: https://context7.com/jiacai2050/zig-napi/llms.txt Manages JavaScript value lifetimes using handle scopes for efficient memory usage in Zig. It shows how to open regular and escapable scopes, create values within them, and ensure cleanup. ```zig const napi = @import("napi"); pub fn processWithScope(env: napi.Env) !napi.Value { // Open a regular scope const scope = try env.openScope(); defer scope.deinit() catch {}; // Create values within scope - they'll be cleaned up on deinit const temp_value = try env.createString(.utf8, "temporary"); _ = temp_value; // Result value return try env.createString(.utf8, "done"); } pub fn processWithEscapeScope(env: napi.Env) !napi.Value { // Open an escapable scope const scope = try env.openEscapeScope(); defer scope.deinit() catch {}; // Create a value to escape const result = try env.createString(.utf8, "escaped value"); // Promote this value to outer scope return try scope.escapeHandle(result); } ``` -------------------------------- ### Consume Zig N-API Addon in Node.js Source: https://github.com/jiacai2050/zig-napi/blob/main/README.org Shows how to require and use a compiled Zig N-API addon from JavaScript. The addon is loaded as a .node file and its exported functions are called with JavaScript values. Includes assertions to verify function behavior. ```javascript const addon = require('../zig-out/lib/hello.node'); const assert = require('node:assert/strict'); assert.strictEqual('Hello Tom', addon.hello('Tom')); assert.strictEqual('Hello Jack', addon.hello('Jack')); ``` -------------------------------- ### Create and Set Properties on JavaScript Objects (Zig) Source: https://context7.com/jiacai2050/zig-napi/llms.txt This Zig code defines a function `makeObject` that creates a new JavaScript object and sets various properties with different Zig types, including strings, numbers, null, and booleans. It uses type-safe Zig values to populate the object. ```zig const napi = @import("napi"); pub fn makeObject(env: napi.Env) !napi.Value { const object = try env.createObject(); // Set various types of properties try object.setNamedProperty("str-key", try env.create([]const u8, "string prop")); try object.setNamedProperty("i64-key", try env.create(i64, 100)); try object.setNamedProperty("i32-key", try env.create(i32, 200)); try object.setNamedProperty("u32-key", try env.create(u32, 201)); try object.setNamedProperty("f64-key", try env.create(f64, 300.0)); try object.setNamedProperty("null-key", try env.create(void, {})); try object.setNamedProperty("true-key", try env.create(bool, true)); try object.setNamedProperty("false-key", try env.create(bool, false)); return object; } ``` -------------------------------- ### Creating JavaScript ArrayBuffer from Zig with N-API Source: https://context7.com/jiacai2050/zig-napi/llms.txt Generate JavaScript ArrayBuffer objects directly from Zig memory. This function takes a string, copies its content into a newly created ArrayBuffer, and returns the buffer to JavaScript for direct memory access. ```zig const std = @import("std"); const napi = @import("napi"); pub fn makeArrayBuffer(env: napi.Env, str: napi.Value) !napi.Value { var buffer: [64]u8 = undefined; const len = try str.getValueString(.utf8, &buffer); var data: [*]u8 = undefined; const array_buffer = try napi.Value.createArrayBuffer(env, len, @ptrCast(&data)); // Fill the array buffer with the string data const slice = data[0..len]; std.mem.copyForwards(u8, slice, buffer[0..len]); return array_buffer; } ``` ```javascript const addon = require('./addon.node'); const buffer = addon.makeArrayBuffer("Hello"); console.log(new Uint8Array(buffer)); // Uint8Array [72, 101, 108, 108, 111] ``` -------------------------------- ### Value Type Checking in JavaScript Source: https://context7.com/jiacai2050/zig-napi/llms.txt Shows how to call a Zig N-API function designed for JavaScript value type checking from Node.js. It demonstrates passing an array and logging the structured result indicating its type and properties. ```javascript const addon = require('./addon.node'); console.log(addon.inspectValue([1, 2, 3])); // { type: 6, isArray: true, isBuffer: false, isDate: false, isError: false } ``` -------------------------------- ### Type Coercion between JavaScript Types using N-API in Zig Source: https://context7.com/jiacai2050/zig-napi/llms.txt Perform type conversions between JavaScript values (like string to number, number to string) using Node-API's coercion capabilities within Zig. This ensures interoperability by converting types as needed before further processing. ```zig const napi = @import("napi"); pub fn coerceStrToNumber(env: napi.Env, str: napi.Value) !napi.Value { _ = env; const coerced_num = try str.coerceTo(.Number); if (try coerced_num.typeOf() != .Number) { return error.InvalidType; } return coerced_num; } pub fn coerceNumberToStr(env: napi.Env, num: napi.Value) !napi.Value { _ = env; const coerced_str = try num.coerceTo(.String); if (try coerced_str.typeOf() != .String) { return error.InvalidType; } return coerced_str; } ``` ```javascript const addon = require('./addon.node'); console.log(addon.coerceStrToNumber("123")); // 123 console.log(addon.coerceNumberToStr(456)); // "456" ``` -------------------------------- ### Working with JavaScript Arrays in Zig using N-API Source: https://context7.com/jiacai2050/zig-napi/llms.txt Access and process JavaScript arrays from Zig. This function iterates over an array passed from JavaScript, sums its elements (assuming they are u32), and returns the total. It properly manages scopes for each element access. ```zig const std = @import("std"); const napi = @import("napi"); pub fn visitArrayInScope(env: napi.Env, arr: napi.Value) !napi.Value { const len = try arr.getArrayLength(); var sum: u32 = 0; for (0..len) |i| { const scope = try env.openScope(); defer scope.deinit() catch |err| { std.log.err("Deinit scope failed, err:{any}", .{err}); }; const item = try arr.getElement(@intCast(i)); sum += try item.getValue(u32); } return env.create(u32, sum); } ``` ```javascript const addon = require('./addon.node'); const result = addon.visitArrayInScope([1, 2, 3, 4, 5]); console.log(result); // 15 ``` -------------------------------- ### Value Type Checking in Zig Source: https://context7.com/jiacai2050/zig-napi/llms.txt Implements Zig functions to check various JavaScript value types, including arrays, buffers, dates, and errors. It returns an object detailing the type and specific checks performed on the input value. ```zig const napi = @import("napi"); pub fn inspectValue(env: napi.Env, value: napi.Value) !napi.Value { const value_type = try value.typeOf(); const is_array = try value.isArray(); const is_buffer = try value.isBuffer(); const is_date = try value.isDate(); const is_error = try value.isError(); const result = try env.createObject(); try result.setNamedProperty("type", try env.create(i32, @intFromEnum(value_type))); try result.setNamedProperty("isArray", try env.create(bool, is_array)); try result.setNamedProperty("isBuffer", try env.create(bool, is_buffer)); try result.setNamedProperty("isDate", try env.create(bool, is_date)); try result.setNamedProperty("isError", try env.create(bool, is_error)); return result; } ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.