### Install Panic Capture Handler
Source: https://zero-native.dev/debugging
Installs the panic capture handler during application startup. Requires an IO object and the paths to log setup.
```zig
zero_native.debug.installPanicCapture(io, log_setup.paths);
```
--------------------------------
### Install and Run CEF
Source: https://zero-native.dev/web-engines
Use the zero-native CLI to install the CEF runtime and then build and run the application.
```bash
zero-native cef install
zig build run
```
--------------------------------
### CLI Setup for CEF
Source: https://zero-native.dev/web-engines
Install the CEF runtime using the CLI and then run a doctor check on the application manifest.
```bash
zero-native cef install
zero-native doctor --manifest app.zon
```
--------------------------------
### EmbeddedApp Initialization Example
Source: https://zero-native.dev/embed
Example demonstrating how to initialize and use the EmbeddedApp for testing purposes.
```APIDOC
## Testing with EmbeddedApp
```
var null_platform = zero_native.NullPlatform.init(.{});
var state: u8 = 0;
var embedded = zero_native.embed.EmbeddedApp.init(.{
.context = &state,
.name = "embedded",
.source = zero_native.WebViewSource.html("
Embedded
"),
}, null_platform.platform());
try embedded.start();
// null_platform.loaded_source now contains the loaded HTML
```
```
--------------------------------
### Testing EmbeddedApp with NullPlatform
Source: https://zero-native.dev/embed
This example demonstrates testing the EmbeddedApp with a NullPlatform, useful for isolated testing scenarios. It initializes the app with a simple HTML source and starts it, allowing verification of the loaded content via null_platform.loaded_source.
```zig
var null_platform = zero_native.NullPlatform.init(.{});
var state: u8 = 0;
var embedded = zero_native.embed.EmbeddedApp.init(.{
.context = &state,
.name = "embedded",
.source = zero_native.WebViewSource.html("Embedded
"),
}, null_platform.platform());
try embedded.start();
// null_platform.loaded_source now contains the loaded HTML
```
--------------------------------
### Hello World App in Zero-Native
Source: https://zero-native.dev/quick-start
A minimal Zero-Native application example that displays a simple 'Hello from zero-native' message using inline HTML.
```zig
const HelloApp = struct {
fn app(self: *@This()) zero_native.App {
return .{
.context = self,
.name = "hello",
.source = zero_native.WebViewSource.html(
\
\
\
\ Hello from zero-native
\
\
),
};
}
};
```
--------------------------------
### Initialize and Run a zero-native App
Source: https://zero-native.dev/
Use this command sequence to initialize a new zero-native project with a Next.js frontend, install its dependencies, and run the application for the first time.
```bash
zero-native init my_app --frontend next
cd my_app
zig build run
```
--------------------------------
### Handling tray actions
Source: https://zero-native.dev/tray
Example of how to handle user interactions with the system tray menu items.
```APIDOC
## Handling tray actions
When a user clicks a tray menu item, the runtime dispatches a `CommandEvent` with the name `"tray.action"`. Use your `event_fn` to handle it:
```zig
fn event(context: *anyopaque, runtime: *Runtime, ev: Event) anyerror!void {
switch (ev) {
.command => |cmd| {
if (std.mem.eql(u8, cmd.name, "tray.action")) {
// Handle tray menu click
}
},
else => {},
}
}
```
```
--------------------------------
### Install zero-native CLI
Source: https://zero-native.dev/packages
Install the zero-native CLI globally using npm. This command installs the zero-native package, which includes prebuilt binaries for macOS, Linux, and Windows.
```bash
npm install -g zero-native
```
--------------------------------
### Run Zero-Native Application
Source: https://zero-native.dev/quick-start
Builds and runs the Zero-Native application. The first run automatically installs frontend dependencies.
```bash
zig build run
```
--------------------------------
### Run Zero-Native Dev Server
Source: https://zero-native.dev/cli/dev
Execute the dev server with your native binary. You can override the frontend URL and the command used to start the dev server, or set a custom readiness timeout.
```bash
zero-native dev --binary zig-out/bin/MyApp
```
```bash
zero-native dev --binary zig-out/bin/MyApp --url http://127.0.0.1:3000/ --command "npm run dev"
```
```bash
zero-native dev --binary zig-out/bin/MyApp --timeout-ms 60000
```
--------------------------------
### Initialize Runtime with Options
Source: https://zero-native.dev/app-model
Initialize the Zero Native runtime with various options, including platform, trace sink, security policies, and window state persistence. The runtime is then started with the application.
```zig
var runtime = zero_native.Runtime.init(.{
.platform = my_platform,
.trace_sink = fanout.sink(),
.bridge = my_app.bridge(),
.builtin_bridge = .{ .enabled = true, .commands = &builtin_policies },
.security = .{
.permissions = &app_permissions,
.navigation = .{ .allowed_origins = &.{ "zero://app" } },
},
.js_window_api = true,
.window_state_store = state_store,
.automation = if (build_options.automation) automation_server else null,
});
try runtime.run(my_app.app());
```
--------------------------------
### Typical CEF Workflow
Source: https://zero-native.dev/packaging
This sequence outlines the typical workflow for developing with the Chromium engine, including installing CEF, building the app, and packaging.
```bash
zero-native cef install --version
zig build
zero-native package --target macos
```
--------------------------------
### app.zon Manifest Example
Source: https://zero-native.dev/app-zon
This is a complete example of an app.zon manifest file. It declares essential app metadata, permissions, bridge policies, security rules, and window layout.
```json
.{
.id = "dev.zero_native",
.name = "zero-native",
.display_name = "zero-native",
.version = "0.1.0",
.icons = .{ "assets/icon.icns", "assets/icon.ico" },
.platforms = .{ "macos" },
.permissions = .{ "window" },
.capabilities = .{ "webview", "js_bridge" },
.bridge = .{
.commands = .{
.{ .name = "native.ping", .origins = .{ "zero://app" } },
.{ .name = "zero-native.window.create", .permissions = .{ "window" }, .origins = .{ "zero://app" } },
},
},
.security = .{
.navigation = .{
.allowed_origins = .{ "zero://app", "http://127.0.0.1:5173" },
.external_links = .{ .action = "deny" },
},
},
.web_engine = "system",
.cef = .{ .dir = "third_party/cef/macos", .auto_install = false },
.windows = .{
.{ .label = "main", .title = "zero-native", .width = 720, .height = 480, .restore_state = true },
},
}
```
--------------------------------
### Define a Zero-Native Module with Lifecycle Hooks
Source: https://zero-native.dev/extensions
Defines a module structure with data and implements start and command lifecycle hooks. The start hook initializes module data, and the command hook handles specific commands like 'reset'.
```zig
const MyModule = struct {
data: u32 = 0,
fn start(context: *anyopaque, runtime: zero_native.extensions.RuntimeContext) anyerror!void {
_ = runtime;
const self: *@This() = @ptrCast(@alignCast(context));
self.data = 42;
}
fn command(context: *anyopaque, runtime: zero_native.extensions.RuntimeContext, cmd: zero_native.extensions.Command) anyerror!void {
_ = runtime;
const self: *@This() = @ptrCast(@alignCast(context));
if (std.mem.eql(u8, cmd.name, "reset")) self.data = 0;
}
};
```
--------------------------------
### Package Application for Linux
Source: https://zero-native.dev/packaging
Shortcut command to package your application for Linux, including desktop entry and icon installation. Optional arguments for output directory and binary path are available.
```bash
zero-native package-linux [--output path] [--binary path]
```
--------------------------------
### Automatic CEF Installation during Build
Source: https://zero-native.dev/web-engines
Enable automatic installation of the CEF runtime during the build process by setting '.auto_install' to true in the app.zon manifest.
```zig
.cef = .{ .dir = "third_party/cef/", .auto_install = true }
```
--------------------------------
### Manage Frontend Dev Server Lifecycle
Source: https://zero-native.dev/frontend
Use the `zero-native dev` command to manage the frontend server. It starts the process, waits for connections, launches the native shell, and terminates the frontend when the shell exits.
```bash
zero-native dev --binary zig-out/bin/MyApp
```
```bash
zero-native dev --binary zig-out/bin/MyApp --url http://127.0.0.1:3000/ --command "npm run dev"
```
--------------------------------
### Check CEF setup with zero-native doctor
Source: https://zero-native.dev/debugging/doctor
This command checks the CEF setup and validates the app.zon manifest file.
```bash
zero-native doctor --manifest app.zon
```
--------------------------------
### Configure Runtime Trace Sink
Source: https://zero-native.dev/debugging
Wires a trace sink into the zero-native runtime using RuntimeOptions.trace_sink. This example uses a fanout sink.
```zig
var runtime = zero_native.Runtime.init(.{
.platform = my_platform,
.trace_sink = fanout.sink(),
});
```
--------------------------------
### macOS Beta Path for Zero-Native
Source: https://zero-native.dev/quick-start
Steps for validating an app on macOS using the beta path, including CEF installation and packaging. Ensure app.zon is configured for Chromium.
```bash
zero-native init my_app --frontend next
cd my_app
zig build run
zero-native cef install
zig build run
zero-native package --target macos --signing identity --identity "Developer ID Application: Your Name"
zero-native doctor --manifest app.zon --strict
```
--------------------------------
### Configure Frontend Settings in app.zon
Source: https://zero-native.dev/frontend
Configure frontend build paths, entry points, and development server settings within your app.zon file. This setup is crucial for managing how your frontend assets are handled.
```json
.frontend = .{
.dist = "dist",
.entry = "index.html",
.spa_fallback = true,
.dev = .{
.url = "http://127.0.0.1:5173/",
.command = .{"npm", "run", "dev", "--", "--host", "127.0.0.1"},
.ready_path = "/",
.timeout_ms = 30000,
},
}
```
--------------------------------
### JavaScript Usage of Builtin Commands
Source: https://zero-native.dev/bridge/builtin-commands
Examples of how to use built-in Zero-Native commands from JavaScript, including creating a window, opening a file dialog, and showing a message dialog. Ensure the `builtin_bridge` policy is correctly configured in your runtime options.
```javascript
const win = await window.zero.windows.create({
label: "tools",
title: "Tools",
width: 420,
height: 320,
});
```
```javascript
const files = await window.zero.invoke("zero-native.dialog.openFile", {
title: "Select a file",
allowMultiple: true,
});
```
```javascript
const result = await window.zero.invoke("zero-native.dialog.showMessage", {
style: "warning",
title: "Confirm",
message: "Are you sure?",
primaryButton: "Yes",
secondaryButton: "No",
});
```
--------------------------------
### Define File Filters for Dialogs
Source: https://zero-native.dev/dialogs
Example of how to define file filters for use with dialogs. This structure specifies display names and associated file extensions.
```zig
const filters = [_]zero_native.FileFilter{
.{ .name = "Images", .extensions = &.{ "png", "jpg", "gif" } },
.{ .name = "All Files", .extensions = &.{ "*" } },
};
```
--------------------------------
### Sign and Package CEF Apps for macOS
Source: https://zero-native.dev/packaging/signing
This sequence installs a specific CEF version, builds the project, signs the macOS package, and creates a DMG. This is for Chromium-based applications where CEF needs to be bundled and signed correctly.
```bash
zero-native cef install --version
```
```bash
zig build
```
```bash
zero-native package --target macos --signing identity --identity "Developer ID Application: Your Name"
```
```bash
hdiutil create -volname "Your App" -srcfolder zig-out/package/your-app.app -ov -format UDZO zig-out/package/your-app.dmg
```
--------------------------------
### Verify CEF Package Layout on macOS
Source: https://zero-native.dev/packaging
Use this command to verify that the packaged macOS application correctly includes the CEF framework and resource files. It requires a local CEF layout or automatic installation.
```bash
zig build test-package-cef-layout -Dplatform=macos
```
--------------------------------
### Create a Zero-Native Project
Source: https://zero-native.dev/quick-start
Initializes a new Zero-Native project with a specified frontend framework. Navigate into the project directory after creation.
```bash
zero-native init my_app --frontend next
cd my_app
```
--------------------------------
### Initialize NullPlatform and Runtime
Source: https://zero-native.dev/testing
Initializes NullPlatform for headless testing and sets up a Runtime with it. NullPlatform records loaded sources and dispatched events without creating real windows.
```zig
var null_platform = zero_native.NullPlatform.init(.{});
var runtime = zero_native.Runtime.init(.{
.platform = null_platform.platform(),
});
```
--------------------------------
### Initialize Automation Server with Custom Directory
Source: https://zero-native.dev/automation
Initialize the automation server with a custom directory path instead of the default.
```zig
const server = zero_native.automation.Server.init(io, "/tmp/my-app-automation", "My App");
```
--------------------------------
### Build and Package Application
Source: https://zero-native.dev/packaging
Use these commands to build and package your application. The first command performs a standard build and package, while the second offers more control via the CLI.
```bash
zig build package
```
```bash
zero-native package --target macos --manifest app.zon --binary zig-out/bin/MyApp
```
--------------------------------
### Create and Focus Window from Zig
Source: https://zero-native.dev/windows
Use `runtime.createWindow` to create a new window with specified options and `runtime.focusWindow` to bring it to the foreground. Requires the `runtime` and `zero_native` modules.
```zig
const info = try runtime.createWindow(.{
.label = "tools",
.title = "Tools",
.default_frame = zero_native.geometry.RectF.init(80, 80, 420, 320),
});
try runtime.focusWindow(info.id);
```
--------------------------------
### Configure WebView Assets
Source: https://zero-native.dev/app-model
Use the `assets` constructor for WebViewSource to serve local files. Specify the root path, entry point, origin, and SPA fallback behavior.
```zig
.source = zero_native.WebViewSource.assets(.{
.root_path = "dist",
.entry = "index.html", // default
.origin = "zero://app", // default
.spa_fallback = true, // default
}),
```
--------------------------------
### CLI: Dump Snapshot
Source: https://zero-native.dev/automation
Retrieve and display the current runtime state, including app name, window metadata, and readiness status.
```bash
# Dump the current snapshot
zero-native automate snapshot
```
--------------------------------
### Bundle Frontend Assets
Source: https://zero-native.dev/packaging
Use this command to bundle your frontend assets. This copies the configured `dist` directory into the build output, making assets accessible via `zero://app/`.
```bash
zig build bundle-assets
```
--------------------------------
### Configure System WebView
Source: https://zero-native.dev/web-engines
Set the web engine to 'system' to use the OS's default WebView. This option has no bundled browser dependency.
```zig
.web_engine = "system",
```
--------------------------------
### Register and Initialize a Zero-Native Module
Source: https://zero-native.dev/extensions
Registers a defined module with the ModuleRegistry and initializes the Zero-Native runtime with the registry. Ensure capabilities are correctly defined for the module.
```zig
var my_module = MyModule{};
const caps = [_]zero_native.extensions.Capability{.{ .kind = .native_module }};
const modules = [_]zero_native.extensions.Module{.{
.info = .{ .id = 1, .name = "my-module", .capabilities = &caps },
.context = &my_module,
.hooks = .{ .start_fn = MyModule.start, .command_fn = MyModule.command },
}};
const registry = zero_native.extensions.ModuleRegistry{ .modules = &modules };
var runtime = zero_native.Runtime.init(.{
.platform = my_platform,
.extensions = registry,
});
```
--------------------------------
### Configure External Link Handling
Source: https://zero-native.dev/security
Opt into opening external links in the system browser by specifying an action and a list of allowed URL prefixes.
```zig
.security = .{
.navigation = .{
.external_links = .{
.action = "open_system_browser",
.allowed_urls = .{ "https://example.com/docs/*" },
},
},
},
```
--------------------------------
### Initialize and Control Embedded App Runtime
Source: https://zero-native.dev/embed
Use this snippet to initialize an EmbeddedApp and control its lifecycle within your application's event loop. Ensure proper error handling for start, frame, resize, and stop operations.
```javascript
var embedded = zero_native.embed.EmbeddedApp.init(my_app.app(), my_platform);
try embedded.start();
// In your render loop:
try embedded.frame();
// On resize:
try embedded.resize(new_surface);
// On shutdown:
try embedded.stop();
```
--------------------------------
### Create, List, Focus, and Close Windows from JavaScript
Source: https://zero-native.dev/windows
Utilize the `window.zero.windows` API in JavaScript to create new windows, list all open windows, focus a specific window by its ID, and close a window. Ensure the JavaScript is executed from an allowed origin.
```javascript
const win = await window.zero.windows.create({
label: "tools",
title: "Tools",
width: 420,
height: 320,
});
const all = await window.zero.windows.list();
await window.zero.windows.focus(win.id);
await window.zero.windows.close(win.id);
```
--------------------------------
### Zero-Native Configuration in app.zon
Source: https://zero-native.dev/cli/dev
Configure frontend development server settings within the `app.zon` manifest file. This includes the distribution directory, entry point, SPA fallback behavior, and specific development server configurations like URL, command, ready path, and timeout.
```zig
.frontend = .{\n .dist = "dist",\n .entry = "index.html",\n .spa_fallback = true,\n .dev = .{\n .url = "http://127.0.0.1:5173/",\n .command = .{ "npm", "run", "dev", "--", "--host", "127.0.0.1" },\n .ready_path = "/",\n .timeout_ms = 30000,\n },\n}
```
--------------------------------
### Package Application for iOS
Source: https://zero-native.dev/packaging
Shortcut command for experimental packaging of your application for iOS. Optional arguments for output directory and binary path are available.
```bash
zero-native package-ios [--output path] [--binary path]
```
--------------------------------
### Package Application for Android
Source: https://zero-native.dev/packaging
Shortcut command for experimental packaging of your application for Android. Optional arguments for output directory and binary path are available.
```bash
zero-native package-android [--output path] [--binary path]
```
--------------------------------
### Define Permissions and Capabilities
Source: https://zero-native.dev/security
Declare broad app features with capabilities and runtime grants with permissions. Use the smallest set required for your app.
```zig
.permissions = .{ "window", "filesystem" },
.capabilities = .{ "webview", "js_bridge" },
```
--------------------------------
### Package Application for Windows
Source: https://zero-native.dev/packaging
Shortcut command to package your application specifically for Windows. Optional arguments for output directory and binary path are available.
```bash
zero-native package-windows [--output path] [--binary path]
```
--------------------------------
### Initialize Automation Server in Runner
Source: https://zero-native.dev/automation
Pass an initialized `zero_native.automation.Server` to `RuntimeOptions` in your runner code. The default directory is `.zig-cache/zero-native-automation`.
```zig
const server = zero_native.automation.Server.init(io, ".zig-cache/zero-native-automation", "My App");
var runtime = zero_native.Runtime.init(.{
.platform = my_platform,
.automation = server,
});
```
--------------------------------
### CLI: Reload WebView
Source: https://zero-native.dev/automation
Instruct the runtime to reload the WebView source code.
```bash
# Reload the WebView
zero-native automate reload
```
--------------------------------
### Declare Main Window in app.zon
Source: https://zero-native.dev/windows
Define the main window configuration within the `app.zon` file, specifying its label, title, dimensions, and whether to restore its state on startup. This is crucial for application initialization.
```json
.windows = .{
.{ .label = "main", .title = "zero-native", .width = 720, .height = 480, .restore_state = true },
},
```
--------------------------------
### RuntimeOptions Fields
Source: https://zero-native.dev/app-model
Configuration options for initializing the Runtime.
```APIDOC
## RuntimeOptions
Field| Type| Default| Description
---|---|---|---
`platform`| `Platform`| required| Platform abstraction (macOS, Linux, or NullPlatform)
`trace_sink`| `?trace.Sink`| `null`| Destination for structured trace records
`log_path`| `?[]const u8`| `null`| Path for persistent log file
`extensions`| `?ModuleRegistry`| `null`| Extension modules with lifecycle hooks
`bridge`| `?BridgeDispatcher`| `null`| App-defined bridge commands and handlers
`builtin_bridge`| `BridgePolicy`| `.`| Policy for built-in commands (dialogs, windows)
`security`| `SecurityPolicy`| `.`| Navigation allowlist, external links, permissions
`automation`| `?automation.Server`| `null`| File-based automation server for testing
`window_state_store`| `?window_state.Store`| `null`| Persistent window geometry and state
`js_window_api`| `bool`| `false`| Expose `window.zero.windows.*`; origin and `window` permission checks still apply
```
--------------------------------
### Initialize FileTraceSink
Source: https://zero-native.dev/debugging
Initializes a FileTraceSink to append trace records to a file on disk. Requires an IO object, log directory, log file name, and format.
```zig
var file_sink = zero_native.debug.FileTraceSink.init(io, log_dir, log_file, .json_lines);
```
--------------------------------
### Configure app.zon for Packaging
Source: https://zero-native.dev/packaging
The `app.zon` manifest file drives packaging metadata. Ensure fields like `id`, `name`, `version`, `icons`, and `platforms` are correctly set for your application.
```zig
.{
.id = "com.example.myapp",
.name = "myapp",
.display_name = "My App",
.version = "1.0.0",
.icons = .{ "assets/icon.icns", "assets/icon.ico" },
.platforms = .{ "macos", "linux" },
.web_engine = "system",
.cef = .{ .dir = "third_party/cef/macos", .auto_install = false },
}
```
--------------------------------
### CLI: Wait for App Ready
Source: https://zero-native.dev/automation
Use the `zero-native automate wait` command to block execution until the application's snapshot indicates `ready=true`.
```bash
# Wait for the app to be ready (polls snapshot.txt for ready=true)
zero-native automate wait
```
--------------------------------
### TrayOptions
Source: https://zero-native.dev/tray
Configuration options for creating or updating a system tray icon.
```APIDOC
## TrayOptions
Field| Type| Default
---|---|---
`icon_path`| `[]const u8`| `""`
`tooltip`| `[]const u8`| `""`
`items`| `[]const TrayMenuItem`| `&.`
```
--------------------------------
### PlatformServices methods
Source: https://zero-native.dev/tray
Methods available for managing the system tray icon and its menu.
```APIDOC
## PlatformServices methods
* `createTray(options)` -- create or replace the tray icon
* `updateTrayMenu(items)` -- update menu items without recreating the tray
* `removeTray()` -- remove the tray icon
```
--------------------------------
### Configure Permissions for JavaScript Window API
Source: https://zero-native.dev/windows
Before using JavaScript to create windows, configure application permissions to include `zero_native.security.permission_window` and specify allowed origins. This snippet shows the security configuration object.
```zig
const app_permissions = [_][]const u8{zero_native.security.permission_window};
.security = .{
.permissions = &app_permissions,
.navigation = .{ .allowed_origins = &.{ "zero://app" } },
},
.js_window_api = true,
```
--------------------------------
### CLI: Capture Screenshot
Source: https://zero-native.dev/automation
Capture a screenshot of the running application. The output is currently a 2x2 placeholder in PPM format.
```bash
# Capture a screenshot
zero-native automate screenshot
```
--------------------------------
### Build with Debug Overlay
Source: https://zero-native.dev/debugging
Builds and runs the webview application with the debug overlay enabled using the -Ddebug-overlay=true flag. This provides a visual debugging interface.
```bash
zig build run-webview -Ddebug-overlay=true
```
--------------------------------
### WebViewSource Constructors
Source: https://zero-native.dev/app-model
Methods for specifying the initial content of a WebView.
```APIDOC
## WebViewSource
Three constructors for specifying what the WebView loads:
* **`.html(content)`**
Inline HTML string, served as `zero://inline`.
* **`.url(address)`**
Load a remote or local URL.
* **`.assets(options)`**
Serve a local file tree through a custom origin.
The assets constructor takes a `WebViewAssetSource`:
```
.source = zero_native.WebViewSource.assets(.{
.root_path = "dist",
.entry = "index.html", // default
.origin = "zero://app", // default
.spa_fallback = true, // default
}),
```
Field| Default| Description
---|---|---
`root_path`| required| Path to the directory containing frontend assets
`entry`| `"index.html"`| HTML entry point within the root path
`origin`| `"zero://app"`| Origin used for asset URLs
`spa_fallback`| `true`| Serve entry for unknown routes (SPA mode)
```
--------------------------------
### Package for Windows
Source: https://zero-native.dev/packaging
Command to package the application for the Windows target. Note that Windows packaging is in early development.
```bash
zero-native package --target windows --manifest app.zon --binary zig-out/bin/MyApp.exe
```
--------------------------------
### Dynamic Frontend Source Function
Source: https://zero-native.dev/frontend
Use this function on your App to dynamically switch between a development server and bundled production assets based on environment variables.
```zig
fn source(context: *anyopaque) anyerror!zero_native.WebViewSource {
const self: *App = @ptrCast(@alignCast(context));
return zero_native.frontend.sourceFromEnv(self.env_map, .{
.dist = "dist",
.entry = "index.html",
});
}
```
--------------------------------
### Package for Linux
Source: https://zero-native.dev/packaging
Command to package the application specifically for the Linux target. Ensure the manifest and binary path are correct.
```bash
zero-native package --target linux --manifest app.zon --binary zig-out/bin/MyApp
```
--------------------------------
### Configure Chromium (CEF) Engine
Source: https://zero-native.dev/web-engines
Set the web engine to 'chromium' and specify the CEF directory. Ensure 'auto_install' is set to false if managing CEF manually.
```zig
.web_engine = "chromium",
```
```zig
.cef = .{ .dir = "third_party/cef/", .auto_install = false },
```
--------------------------------
### Frontend Dev Server Configuration
Source: https://zero-native.dev/app-zon
Configures the managed dev server for `zero-native dev` and `zig build dev`. Specify the distribution directory, entry point, SPA fallback behavior, and dev server details.
```json
.frontend = .{
.dist = "frontend/dist",
.entry = "index.html",
.spa_fallback = true,
.dev = .{
.url = "http://127.0.0.1:5173/",
.command = .{ "npm", "--prefix", "frontend", "run", "dev" },
.ready_path = "/",
.timeout_ms = 30000,
},
},
```
--------------------------------
### CLI: List Automation Apps
Source: https://zero-native.dev/automation
List all running applications that have been enabled for automation.
```bash
# List running automation-enabled apps
zero-native automate list
```
--------------------------------
### Build Test WebView Smoke
Source: https://zero-native.dev/automation
Build the `test-webview-smoke` step, typically used for end-to-end testing of the WebView integration.
```zig
zig build test-webview-smoke -Dplatform=macos
```
--------------------------------
### Configure Frontend Assets in app.zon
Source: https://zero-native.dev/packaging
Configure frontend asset bundling within the `app.zon` manifest. Specify the distribution directory, entry point, and SPA fallback behavior.
```zig
.frontend = .{ .dist = "dist", .entry = "index.html", .spa_fallback = true }
```
--------------------------------
### Enable Automation Build Flag
Source: https://zero-native.dev/automation
Build your Zig project with the automation flag enabled to activate the automation server.
```zig
zig build run-webview -Dautomation=true
```
--------------------------------
### Create Distributable Disk Image
Source: https://zero-native.dev/packaging/signing
Use this command to build a distributable disk image (.dmg) for your macOS application. This is typically done after the application has been packaged and signed.
```bash
zig build dmg
```
--------------------------------
### Create FanoutTraceSink
Source: https://zero-native.dev/debugging
Creates a FanoutTraceSink to broadcast trace records to multiple child sinks, such as stdout and a file sink. Requires an array of sinks.
```zig
var sinks = [_]trace.Sink{ stdout_sink.sink(), file_sink.sink() };
var fanout = zero_native.debug.FanoutTraceSink{ .sinks = &sinks };
```
--------------------------------
### Enable Builtin Commands with Runtime Options
Source: https://zero-native.dev/bridge/builtin-commands
Configure the `builtin_bridge` policy in `RuntimeOptions` to enable specific built-in commands and define allowed origins and permissions. This is necessary for dialog commands which are default-deny.
```zig
const app_permissions = [_][]const u8{zero_native.security.permission_window};
.security = .{
.permissions = &app_permissions,
.navigation = .{ .allowed_origins = &.{ "zero://app" } },
},
.builtin_bridge = .{
.enabled = true,
.commands = &.{
.{ .name = "zero-native.window.list", .permissions = .{ "window" }, .origins = .{ "zero://app" } },
.{ .name = "zero-native.window.create", .permissions = .{ "window" }, .origins = .{ "zero://app" } },
.{ .name = "zero-native.dialog.openFile", .origins = .{ "zero://app" } },
.{ .name = "zero-native.dialog.showMessage", .origins = .{ "zero://app" } },
},
},
```
--------------------------------
### Local Release Testing with Zig Build Notarize
Source: https://zero-native.dev/packaging/signing
This command is a helper for local release testing of the notarization process. It does not invoke `xcrun notarytool` directly. After running, manually submit the signed package for notarization.
```bash
zig build notarize
```
--------------------------------
### Production Frontend Source
Source: https://zero-native.dev/frontend
Return a production source configuration that always uses local assets. This is suitable for packaged builds where a development server is not needed.
```zig
return zero_native.frontend.productionSource(.{ .dist = "dist", .entry = "index.html" });
```
--------------------------------
### Submit Signed Package for Notarization
Source: https://zero-native.dev/packaging/signing
Manually submit your signed application package for notarization using `xcrun notarytool`. This command requires your Apple ID, Team ID, and a keychain-stored password. The `--wait` flag ensures the command blocks until notarization is complete.
```bash
xcrun notarytool submit zig-out/package/your-app.zip --apple-id "you@example.com" --team-id "TEAMID" --password "@keychain:AC_PASSWORD" --wait
```
--------------------------------
### Handle System Tray Actions
Source: https://zero-native.dev/tray
Use your `event_fn` to handle `"tray.action"` commands dispatched when a user clicks a system tray menu item. This snippet shows how to check the event type and command name.
```zig
fn event(context: *anyopaque, runtime: *Runtime, ev: Event) anyerror!void {
switch (ev) {
.command => |cmd| {
if (std.mem.eql(u8, cmd.name, "tray.action")) {
// Handle tray menu click
}
},
else => {},
}
}
```
--------------------------------
### Run WebView Smoke Tests
Source: https://zero-native.dev/testing
Executes WebView smoke tests on macOS, including options for CEF integration. These tests require a GUI-capable macOS session.
```bash
zig build test-webview-smoke -Dplatform=macos
```
```bash
zig build test-webview-cef-smoke -Dplatform=macos -Dweb-engine=chromium
```
--------------------------------
### Run Headless Tests
Source: https://zero-native.dev/testing
Executes the default test suite which does not require a window server. Bridge and IPC coverage are handled by these headless desktop tests.
```bash
zig build test
```
```bash
zig build test-desktop
```
```bash
zig build test-platform-info
```
--------------------------------
### Validate Application Manifest and Environment
Source: https://zero-native.dev/packaging
Use `zero-native doctor` to check your host environment, WebView, manifest, and log paths. Add `--strict` to fail on warnings. `zero-native validate` checks the manifest.
```bash
zero-native doctor --manifest app.zon --strict
zero-native validate app.zon
```
--------------------------------
### Open File Dialog from JavaScript
Source: https://zero-native.dev/dialogs
Invokes the open file dialog from JavaScript. Requires the 'zero-native.dialog.openFile' function to be available via the zero bridge. Options like 'allowMultiple' and 'allowDirectories' can be configured.
```javascript
const files = await window.zero.invoke("zero-native.dialog.openFile", {
title: "Select a file",
defaultPath: "/home",
allowMultiple: true,
allowDirectories: false,
});
```
--------------------------------
### Configure Update Settings in app.zon
Source: https://zero-native.dev/updates
Define the update feed URL, public key for signature verification, and startup check behavior. Ensure the `feed_url` points to a valid JSON feed and `public_key` is a base64-encoded ed25519 public key.
```zon
.updates = .{
.feed_url = "https://example.com/releases/zero-native-feed.json",
.public_key = "base64-ed25519-public-key",
.check_on_start = true,
},
```
--------------------------------
### Validate app.zon Manifest
Source: https://zero-native.dev/app-zon
Commands to validate the app.zon manifest file using the zero-native CLI.
```bash
zero-native validate app.zon
```
```bash
zero-native doctor --manifest app.zon --strict
```
--------------------------------
### Configure Built-in Bridge Policy
Source: https://zero-native.dev/security
Explicitly configure built-in bridge policies for window and dialog commands, specifying required permissions and allowed origins.
```zig
.builtin_bridge = .{
.enabled = true,
.commands = &+{
.{ .name = "zero-native.window.create", .permissions = .{ "window" }, .origins = .{ "zero://app" } },
.{ .name = "zero-native.dialog.openFile", .origins = .{ "zero://app" } },
.{ .name = "zero-native.dialog.showMessage", .origins = .{ "zero://app" } },
},
},
```
--------------------------------
### Open File Dialog
Source: https://zero-native.dev/dialogs
Opens a native file dialog to allow users to select one or more files or directories. Returns a result object containing the count and paths of selected items.
```APIDOC
## Open File Dialog
### Description
Opens a native file dialog for selecting files or directories.
### Parameters
#### Request Body
- **title** (string) - Optional - The title of the dialog window.
- **default_path** (string) - Optional - The initial directory to open.
- **filters** (array of FileFilter) - Optional - Filters for file types.
- **allow_directories** (boolean) - Optional - Whether to allow selecting directories.
- **allow_multiple** (boolean) - Optional - Whether to allow selecting multiple items.
### Response
#### Success Response (200)
- **count** (integer) - The number of selected items.
- **paths** (array of string) - An array of paths to the selected items.
### Request Example
```json
{
"title": "Select files",
"defaultPath": "/home/user",
"allowMultiple": true,
"filters": [
{ "name": "Images", "extensions": ["png", "jpg"] },
{ "name": "All Files", "extensions": ["*"] }
]
}
```
### Response Example
```json
{
"count": 2,
"paths": ["/home/user/image1.png", "/home/user/image2.jpg"]
}
```
```
--------------------------------
### Generate Platform-Specific Icons
Source: https://zero-native.dev/packaging
Command to generate platform-specific icon files (`.icns` for macOS, `.ico` for Windows) from a source PNG image.
```bash
zig build generate-icon
```
--------------------------------
### Initialize TestHarness
Source: https://zero-native.dev/testing
Initializes the TestHarness with default settings for headless testing. Use this to test bridge handlers, lifecycle events, and command dispatch.
```zig
var harness: zero_native.TestHarness = undefined;
harness.init(.{});
```
--------------------------------
### Bundle CEF Runtime
Source: https://zero-native.dev/packaging
Command to bundle the Chromium Embedded Framework (CEF) runtime. This is necessary when using the Chromium web engine. Ensure the CEF distribution matches the target platform and architecture.
```bash
zig build cef-bundle -Dcef-dir=/path/to/cef
```
--------------------------------
### App Struct Fields
Source: https://zero-native.dev/app-model
Defines the structure of a Zero-Native application.
```APIDOC
## The App struct
Field| Type| Description
---|---|---
`context`| `*anyopaque`| Pointer to your app state (required)
`name`| `[]const u8`| App name used in traces and automation snapshots (required)
`source`| `WebViewSource`| Initial WebView content (required)
`source_fn`| `?fn(*anyopaque) !WebViewSource`| Dynamic source resolver (overrides `source` when set)
`start_fn`| `?fn(*anyopaque, *Runtime) !void`| Called after the runtime starts and the first window is loaded
`event_fn`| `?fn(*anyopaque, *Runtime, Event) !void`| Called on every runtime event (lifecycle + commands)
`stop_fn`| `?fn(*anyopaque, *Runtime) !void`| Called before the runtime shuts down
All callback fields are optional. A minimal app only needs `context`, `name`, and `source`.
```
--------------------------------
### Register Native Bridge Commands
Source: https://zero-native.dev/security
Register native bridge commands with their names, required permissions, and allowed origins. Prefer exact origins over wildcards.
```zig
.bridge = .{
.commands = .{
,{
.name = "native.ping",
.origins = .{ "zero://app" },
},
,{
.name = "zero-native.window.create",
.permissions = .{ "window" },
.origins = .{ "zero://app" },
},
},
},
```
--------------------------------
### Runtime Methods
Source: https://zero-native.dev/app-model
The Runtime object provides methods to manage application windows and lifecycle.
```APIDOC
## Runtime Methods
### `init(options) Runtime`
Create a runtime instance with specified options.
### `run(app) !void`
Enter the platform event loop and start the application.
### `createWindow(options) !WindowInfo`
Open a new application window.
### `listWindows() []WindowInfo`
Retrieve a list of all currently open windows.
### `focusWindow(id) !void`
Bring a specific window to the foreground.
### `closeWindow(id) !void`
Close a specific application window.
### `invalidate()`
Request a redraw of the application.
### `invalidateFor(reason, dirty_region)`
Request a redraw for a specific reason and an optional dirty region.
### `frameDiagnostics() FrameDiagnostics`
Return statistics from the last rendered frame.
### `dispatchEvent(event)`
Inject a synthetic event into the application.
### `dispatchPlatformEvent(app, event)`
Forward a platform-specific event to the application.
### `automationSnapshot()`
Write the current application state to the automation directory.
```
--------------------------------
### Run CEF Smoke Tests
Source: https://zero-native.dev/web-engines
Execute smoke tests for the webview and CEF layout on macOS. The CEF smoke test requires a local CEF layout or auto-installation enabled.
```bash
zig build test-webview-cef-smoke -Dplatform=macos -Dweb-engine=chromium
```
```bash
zig build test-package-cef-layout -Dplatform=macos
```
--------------------------------
### Configure Web Engine in app.zon
Source: https://zero-native.dev/web-engines
Specify the web engine to use in your application's configuration. Options include 'system' for the default or 'chromium' for a Chromium-based engine. CEF can also be configured with its directory and auto-installation.
```zon
.web_engine = "system",
// or, on supported platforms:
.web_engine = "chromium",
.cef = .{
.dir = "third_party/cef/",
.auto_install = true,
},
```
--------------------------------
### Wire the Bridge Dispatcher in Zig
Source: https://zero-native.dev/bridge
Configure the bridge dispatcher by defining handlers and optionally setting up policies. This involves creating a registry of command names mapped to handler functions and their contexts.
```zig
fn bridge(self: *App) zero_native.BridgeDispatcher {
self.handlers = .{.{ .name = "native.ping", .context = self, .invoke_fn = ping }};
return .{
.policy = .{ .enabled = true, .commands = &policies },
.registry = .{ .handlers = &self.handlers },
};
}
```
--------------------------------
### Run zero-native doctor
Source: https://zero-native.dev/debugging/doctor
Use this command to check your development environment for issues. It always exits with a status code of 0.
```bash
zero-native doctor
```