@native-sdk/cli 0.4.1 → 0.4.3

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.
Files changed (48) hide show
  1. package/assets/native-sdk.manifest +17 -1
  2. package/build/app.zig +40 -1
  3. package/build.zig +49 -3
  4. package/package.json +10 -9
  5. package/src/platform/macos/appkit_host.m +21 -6
  6. package/src/platform/windows/webview2_host.cpp +377 -72
  7. package/src/primitives/canvas/chart.zig +8 -7
  8. package/src/primitives/canvas/chart_tests.zig +2 -2
  9. package/src/primitives/canvas/commands.zig +27 -0
  10. package/src/primitives/canvas/gpu.zig +8 -0
  11. package/src/primitives/canvas/markdown_tests.zig +1 -1
  12. package/src/primitives/canvas/reference.zig +215 -7
  13. package/src/primitives/canvas/reference_tests.zig +326 -7
  14. package/src/primitives/canvas/root.zig +3 -0
  15. package/src/primitives/canvas/serialization.zig +16 -3
  16. package/src/primitives/canvas/test_support.zig +3 -0
  17. package/src/primitives/canvas/themes/geist.zig +6 -0
  18. package/src/primitives/canvas/tokens.zig +7 -0
  19. package/src/primitives/canvas/widget_builtin_tests.zig +439 -3
  20. package/src/primitives/canvas/widget_render.zig +29 -41
  21. package/src/primitives/canvas/widget_render_controls.zig +73 -43
  22. package/src/primitives/canvas/widget_render_style.zig +53 -0
  23. package/src/primitives/canvas/widget_render_surfaces.zig +19 -18
  24. package/src/primitives/canvas/widget_runtime.zig +3 -0
  25. package/src/primitives/canvas/widget_runtime_tests.zig +20 -21
  26. package/src/primitives/canvas/widget_text_input.zig +104 -1
  27. package/src/runtime/canvas_frame_packet_tests.zig +9 -1
  28. package/src/runtime/canvas_frame_patch_tests.zig +39 -1
  29. package/src/runtime/canvas_widget_control_tests.zig +4 -4
  30. package/src/runtime/canvas_widget_runtime.zig +23 -3
  31. package/src/runtime/canvas_widget_text_tests.zig +101 -0
  32. package/src/runtime/ui_app.zig +78 -10
  33. package/src/runtime/ui_app_tests.zig +109 -0
  34. package/src/runtime/ui_app_window_tests.zig +93 -0
  35. package/src/runtime/view.zig +1 -1
  36. package/src/runtime/view_widget_scroll.zig +12 -1
  37. package/src/runtime/view_widget_text.zig +6 -2
  38. package/src/tooling/buildgraph.zig +112 -2
  39. package/src/tooling/junction.zig +247 -0
  40. package/src/tooling/package.zig +45 -0
  41. package/src/tooling/root.zig +1 -0
  42. package/src/tooling/templates.zig +102 -2
  43. package/third_party/webview2/LICENSE.txt +27 -0
  44. package/third_party/webview2/README.md +19 -0
  45. package/third_party/webview2/arm64/WebView2Loader.dll +0 -0
  46. package/third_party/webview2/include/EventToken.h +12 -0
  47. package/third_party/webview2/include/WebView2.h +60636 -0
  48. package/third_party/webview2/x64/WebView2Loader.dll +0 -0
@@ -0,0 +1,247 @@
1
+ //! Windows directory-junction shim for cross-volume SDK wiring.
2
+ //!
3
+ //! build.zig.zon path dependencies must be relative to the build root (Zig
4
+ //! rejects absolute paths), but on Windows a relative path only exists when
5
+ //! both ends share a volume: no chain of `..` segments leads from an app on
6
+ //! D:\ to an SDK under the npm global prefix on C:\, nor between two
7
+ //! different \\server\share UNC roots. `std.fs.path.relative` signals that
8
+ //! case by returning the canonicalized absolute target instead of a
9
+ //! relative path. The bridge is a directory junction inside the app's
10
+ //! `.native/` directory pointing at the framework root, so the zon
11
+ //! dependency can stay relative by routing through it. Junctions — mount
12
+ //! points, not file symlinks — resolve on the filesystem like plain
13
+ //! directories and, unlike symlinks, need neither Administrator rights nor
14
+ //! Developer Mode to create, which is why this shim sets a MOUNT_POINT
15
+ //! reparse point instead of calling the symlink API.
16
+
17
+ const std = @import("std");
18
+ const builtin = @import("builtin");
19
+
20
+ /// True when a path computed by `std.fs.path.relative` could not actually
21
+ /// be made relative — the Windows cross-volume case (two drive letters, or
22
+ /// two different UNC shares), where the function degrades to the absolute
23
+ /// target path. Checks both path flavors so the decision is testable with
24
+ /// fabricated `C:\`/`D:\` strings on every host.
25
+ pub fn crossesVolumes(dependency_path: []const u8) bool {
26
+ return std.fs.path.isAbsoluteWindows(dependency_path) or
27
+ std.fs.path.isAbsolutePosix(dependency_path);
28
+ }
29
+
30
+ /// The two user-level ways out when the cross-volume junction bridge is
31
+ /// unavailable or does not apply (appended to every cross-volume teaching
32
+ /// error, so no failure ever ends at "absolute paths are rejected" without
33
+ /// a way forward).
34
+ pub const cross_volume_ways_out =
35
+ \\Two ways out:
36
+ \\ - keep the app on the same volume as the Native SDK install, or
37
+ \\ - move the npm global prefix onto the app's volume
38
+ \\ (`npm config set prefix <dir on the app's volume>`, then
39
+ \\ reinstall @native-sdk/cli there).
40
+ \\
41
+ ;
42
+
43
+ pub const EnsureError = error{
44
+ /// Junctions are a Windows (NTFS reparse point) concept; on other
45
+ /// platforms a genuinely relative path always exists and this shim is
46
+ /// never needed.
47
+ UnsupportedPlatform,
48
+ /// The reparse point could not be created (exotic filesystem, policy).
49
+ /// Callers must turn this into a teaching error, never into an
50
+ /// absolute zon path.
51
+ JunctionFailed,
52
+ /// Something that is not a junction (a non-empty real directory)
53
+ /// occupies the junction path; refusing beats silently deleting a tree
54
+ /// the CLI does not own.
55
+ JunctionPathOccupied,
56
+ } || std.mem.Allocator.Error || std.Io.Cancelable;
57
+
58
+ /// Make `junction_path` a directory junction resolving to `target` (both
59
+ /// absolute, symlink-free paths — realpath output). Idempotent per
60
+ /// generation: a junction already resolving to `target` is left untouched
61
+ /// (so repeated `native dev|build|test` runs are no-ops), one resolving
62
+ /// elsewhere (the SDK moved or was upgraded in place) or dangling (its old
63
+ /// target was deleted) is removed and recreated.
64
+ pub fn ensure(allocator: std.mem.Allocator, io: std.Io, junction_path: []const u8, target: []const u8) EnsureError!void {
65
+ if (builtin.os.tag != .windows) return error.UnsupportedPlatform;
66
+
67
+ const cwd = std.Io.Dir.cwd();
68
+ if (cwd.realPathFileAlloc(io, junction_path, allocator)) |resolved| {
69
+ defer allocator.free(resolved);
70
+ // Windows paths are case-insensitive; compare that way so a mere
71
+ // case difference between two realpath spellings never causes a
72
+ // delete/recreate cycle on every generation.
73
+ if (std.ascii.eqlIgnoreCase(resolved, target)) return;
74
+ } else |err| switch (err) {
75
+ error.Canceled => |e| return e,
76
+ // Missing entirely, or a junction whose target no longer exists
77
+ // (realpath cannot resolve through it) — either way, fall through
78
+ // and clear the name so creation below starts fresh.
79
+ else => {},
80
+ }
81
+
82
+ remove(io, junction_path) catch |err| switch (err) {
83
+ error.JunctionNotFound => {},
84
+ else => |e| return e,
85
+ };
86
+
87
+ create(io, junction_path, target) catch |err| switch (err) {
88
+ error.Canceled => |e| return e,
89
+ else => {
90
+ // A half-made junction is a plain empty directory; clear it so
91
+ // the next attempt (or a user retry) starts from nothing.
92
+ cwd.deleteDir(io, junction_path) catch {};
93
+ return error.JunctionFailed;
94
+ },
95
+ };
96
+ }
97
+
98
+ /// Delete whatever occupies `junction_path` without ever touching a
99
+ /// junction's target: RemoveDirectory deletes the reparse point itself
100
+ /// (dangling or not) and also clears a plain empty directory, while a
101
+ /// non-empty real directory fails DirNotEmpty — surfaced as occupied
102
+ /// rather than destroying data the CLI does not own.
103
+ fn remove(io: std.Io, junction_path: []const u8) error{ JunctionNotFound, JunctionPathOccupied, Canceled }!void {
104
+ const cwd = std.Io.Dir.cwd();
105
+ cwd.deleteDir(io, junction_path) catch |err| switch (err) {
106
+ error.FileNotFound => return error.JunctionNotFound,
107
+ error.Canceled => |e| return e,
108
+ // A regular file squatting on the name: clear it the file way.
109
+ error.NotDir => cwd.deleteFile(io, junction_path) catch |file_err| switch (file_err) {
110
+ error.FileNotFound => return error.JunctionNotFound,
111
+ error.Canceled => |e| return e,
112
+ else => return error.JunctionPathOccupied,
113
+ },
114
+ else => return error.JunctionPathOccupied,
115
+ };
116
+ }
117
+
118
+ /// Create the junction: make the directory and set a MOUNT_POINT reparse
119
+ /// point on it in one NtCreateFile + FSCTL_SET_REPARSE_POINT pair, the same
120
+ /// operation `mklink /J` performs. The substitute name is the NT-namespaced
121
+ /// target (`\??\C:\...`), the print name its Win32 spelling for `dir`
122
+ /// output.
123
+ fn create(io: std.Io, junction_path: []const u8, target: []const u8) !void {
124
+ if (builtin.os.tag != .windows) return error.UnsupportedPlatform;
125
+ const w = std.os.windows;
126
+
127
+ const junction_nt = try std.Io.Threaded.sliceToPrefixedFileW(null, junction_path, .{ .allow_relative = false });
128
+ const target_nt = try std.Io.Threaded.sliceToPrefixedFileW(null, target, .{ .allow_relative = false });
129
+ const substitute = target_nt.span();
130
+
131
+ var print_buffer: [w.PATH_MAX_WIDE]u16 = undefined;
132
+ // An empty print name is valid reparse data; the junction still
133
+ // resolves, it just lists without a pretty target in Explorer/`dir`.
134
+ const print_name: []const u16 = w.ntToWin32Namespace(substitute, &print_buffer) catch &.{};
135
+
136
+ // REPARSE_DATA_BUFFER header for IO_REPARSE_TAG_MOUNT_POINT, followed
137
+ // by PathBuffer holding substitute + NUL + print + NUL (WTF-16).
138
+ const MountPointData = extern struct {
139
+ ReparseTag: w.IO_REPARSE_TAG,
140
+ ReparseDataLength: w.USHORT,
141
+ Reserved: w.USHORT,
142
+ SubstituteNameOffset: w.USHORT,
143
+ SubstituteNameLength: w.USHORT,
144
+ PrintNameOffset: w.USHORT,
145
+ PrintNameLength: w.USHORT,
146
+ };
147
+ var buffer: [w.MAXIMUM_REPARSE_DATA_BUFFER_SIZE]u8 = undefined;
148
+ const substitute_bytes = substitute.len * 2;
149
+ const print_bytes = print_name.len * 2;
150
+ const total_len = @sizeOf(MountPointData) + substitute_bytes + 2 + print_bytes + 2;
151
+ if (total_len > buffer.len) return error.NameTooLong;
152
+ const header: MountPointData = .{
153
+ .ReparseTag = .MOUNT_POINT,
154
+ // Everything after the 8-byte (tag + length + reserved) prefix.
155
+ .ReparseDataLength = @intCast(total_len - 8),
156
+ .Reserved = 0,
157
+ .SubstituteNameOffset = 0,
158
+ .SubstituteNameLength = @intCast(substitute_bytes),
159
+ .PrintNameOffset = @intCast(substitute_bytes + 2),
160
+ .PrintNameLength = @intCast(print_bytes),
161
+ };
162
+ @memcpy(buffer[0..@sizeOf(MountPointData)], std.mem.asBytes(&header));
163
+ var offset: usize = @sizeOf(MountPointData);
164
+ @memcpy(buffer[offset..][0..substitute_bytes], std.mem.sliceAsBytes(substitute));
165
+ offset += substitute_bytes;
166
+ buffer[offset] = 0;
167
+ buffer[offset + 1] = 0;
168
+ offset += 2;
169
+ @memcpy(buffer[offset..][0..print_bytes], std.mem.sliceAsBytes(print_name));
170
+ offset += print_bytes;
171
+ buffer[offset] = 0;
172
+ buffer[offset + 1] = 0;
173
+
174
+ // Create the directory and keep a synchronous write handle to it that
175
+ // does not follow reparse points — the handle FSCTL_SET_REPARSE_POINT
176
+ // stamps the mount point onto.
177
+ var handle: w.HANDLE = undefined;
178
+ const attr: w.OBJECT.ATTRIBUTES = .{
179
+ .RootDirectory = null,
180
+ .ObjectName = @constCast(&w.UNICODE_STRING.init(junction_nt.span())),
181
+ };
182
+ var iosb: w.IO_STATUS_BLOCK = undefined;
183
+ switch (w.ntdll.NtCreateFile(
184
+ &handle,
185
+ .{ .GENERIC = .{ .WRITE = true }, .STANDARD = .{ .SYNCHRONIZE = true } },
186
+ &attr,
187
+ &iosb,
188
+ null,
189
+ .{ .NORMAL = true },
190
+ .VALID_FLAGS,
191
+ .CREATE,
192
+ .{ .DIRECTORY_FILE = true, .IO = .SYNCHRONOUS_NONALERT, .OPEN_REPARSE_POINT = true },
193
+ null,
194
+ 0,
195
+ )) {
196
+ .SUCCESS => {},
197
+ .OBJECT_NAME_COLLISION => return error.PathAlreadyExists,
198
+ .ACCESS_DENIED => return error.AccessDenied,
199
+ else => return error.JunctionFailed,
200
+ }
201
+ defer w.CloseHandle(handle);
202
+
203
+ const result = try io.operate(.{ .device_io_control = .{
204
+ .file = .{ .handle = handle, .flags = .{ .nonblocking = false } },
205
+ .code = .SET_REPARSE_POINT,
206
+ .in = buffer[0..total_len],
207
+ } });
208
+ if (result.device_io_control.u.Status != .SUCCESS) return error.JunctionFailed;
209
+ }
210
+
211
+ test "cross-volume detection catches what std.fs.path.relative degrades to" {
212
+ // Same volume: a genuinely relative result, no junction needed.
213
+ try std.testing.expect(!crossesVolumes("../../.."));
214
+ try std.testing.expect(!crossesVolumes("..\\..\\sdk"));
215
+ try std.testing.expect(!crossesVolumes(""));
216
+ // Cross volume on Windows: relative() returns the absolute target.
217
+ try std.testing.expect(crossesVolumes("C:\\Users\\alpha\\AppData\\Roaming\\npm\\node_modules\\@native-sdk\\cli"));
218
+ try std.testing.expect(crossesVolumes("\\\\server\\share\\native-sdk"));
219
+ // POSIX absolute cannot happen from relative(), but stays covered.
220
+ try std.testing.expect(crossesVolumes("/opt/native-sdk"));
221
+ }
222
+
223
+ test "the reported cross-drive layout degrades to an absolute path and is detected" {
224
+ // The exact shape from the field report: app on D:\, npm-global SDK on
225
+ // C:\ — relativeWindows is pure, so this runs on every host.
226
+ const dependency_path = try std.fs.path.relativeWindows(
227
+ std.testing.allocator,
228
+ "D:\\Projects\\my_app",
229
+ null,
230
+ "D:\\Projects\\my_app\\.native\\build",
231
+ "C:\\Users\\alpha\\AppData\\Roaming\\npm\\node_modules\\@native-sdk\\cli",
232
+ );
233
+ defer std.testing.allocator.free(dependency_path);
234
+ try std.testing.expect(std.fs.path.isAbsoluteWindows(dependency_path));
235
+ try std.testing.expect(crossesVolumes(dependency_path));
236
+
237
+ // Control: same drive stays relative and is not routed.
238
+ const same_drive = try std.fs.path.relativeWindows(
239
+ std.testing.allocator,
240
+ "D:\\Projects\\my_app",
241
+ null,
242
+ "D:\\Projects\\my_app\\.native\\build",
243
+ "D:\\tools\\native-sdk",
244
+ );
245
+ defer std.testing.allocator.free(same_drive);
246
+ try std.testing.expect(!crossesVolumes(same_drive));
247
+ }
@@ -2,6 +2,7 @@ const std = @import("std");
2
2
  const android_tool = @import("android.zig");
3
3
  const app_icon_tool = @import("app_icon");
4
4
  const assets_tool = @import("assets.zig");
5
+ const buildgraph = @import("buildgraph.zig");
5
6
  const cef = @import("cef.zig");
6
7
  const codesign = @import("codesign.zig");
7
8
  const diagnostics = @import("diagnostics");
@@ -212,6 +213,11 @@ fn createDesktopArtifact(allocator: std.mem.Allocator, io: std.Io, options: Pack
212
213
  const binary_subpath = try std.fmt.allocPrint(allocator, "bin/{s}", .{executable_name});
213
214
  defer allocator.free(binary_subpath);
214
215
  try copyFileToDir(allocator, io, dir, binary_path, binary_subpath);
216
+ if (options.target == .windows and options.web_engine == .system) {
217
+ try copyWindowsWebView2Loader(allocator, io, dir, options, binary_path);
218
+ }
219
+ } else if (options.target == .windows and options.web_engine == .system) {
220
+ try writeFile(dir, io, "bin/README.txt", "Build the app binary separately and place it here for this target, together with the WebView2Loader.dll for its architecture (vendored in the SDK under third_party/webview2/).\n");
215
221
  } else {
216
222
  try writeFile(dir, io, "bin/README.txt", "Build the app binary separately and place it here for this target.\n");
217
223
  }
@@ -934,6 +940,45 @@ fn zonStringAlloc(allocator: std.mem.Allocator, value: []const u8) ![]const u8 {
934
940
  return out.toOwnedSlice(allocator);
935
941
  }
936
942
 
943
+ /// The Windows system engine discovers the machine's WebView2 runtime
944
+ /// through WebView2Loader.dll, which the host loads from the executable's
945
+ /// directory — the vendored copy ships inside every packaged app. The
946
+ /// architecture comes from the packaged binary's PE header so an arm64
947
+ /// build gets the arm64 loader.
948
+ fn copyWindowsWebView2Loader(allocator: std.mem.Allocator, io: std.Io, dir: std.Io.Dir, options: PackageOptions, binary_path: []const u8) !void {
949
+ const framework_root = blk: {
950
+ if (options.env_map) |env_map| {
951
+ if (try buildgraph.resolveFrameworkRoot(allocator, io, env_map)) |root| break :blk root;
952
+ } else if (try buildgraph.frameworkRootFromExecutable(allocator, io)) |root| {
953
+ break :blk root;
954
+ }
955
+ return error.MissingFramework;
956
+ };
957
+ defer allocator.free(framework_root);
958
+ const arch_dir: []const u8 = if (try peExecutableIsArm64(io, binary_path)) "arm64" else "x64";
959
+ const loader_path = try std.fs.path.join(allocator, &.{ framework_root, "third_party", "webview2", arch_dir, "WebView2Loader.dll" });
960
+ defer allocator.free(loader_path);
961
+ try copyFileToDir(allocator, io, dir, loader_path, "bin/WebView2Loader.dll");
962
+ }
963
+
964
+ /// Whether a PE executable targets arm64, read from the COFF machine
965
+ /// field. Anything unrecognized falls back to x64, the default Windows
966
+ /// build target.
967
+ fn peExecutableIsArm64(io: std.Io, path: []const u8) !bool {
968
+ var file = try std.Io.Dir.cwd().openFile(io, path, .{});
969
+ defer file.close(io);
970
+ var read_buffer: [4096]u8 = undefined;
971
+ var reader = file.reader(io, &read_buffer);
972
+ var header: [4096]u8 = undefined;
973
+ const len = try reader.interface.readSliceShort(&header);
974
+ if (len < 0x40 or header[0] != 'M' or header[1] != 'Z') return false;
975
+ const pe_offset: usize = std.mem.readInt(u32, header[0x3c..0x40], .little);
976
+ if (pe_offset + 6 > len) return false;
977
+ if (!std.mem.eql(u8, header[pe_offset..][0..4], "PE\x00\x00")) return false;
978
+ const machine = std.mem.readInt(u16, header[pe_offset + 4 ..][0..2], .little);
979
+ return machine == 0xaa64;
980
+ }
981
+
937
982
  fn copyFileToDir(allocator: std.mem.Allocator, io: std.Io, dir: std.Io.Dir, source_path: []const u8, dest_subpath: []const u8) !void {
938
983
  _ = allocator;
939
984
  try std.Io.Dir.copyFile(std.Io.Dir.cwd(), source_path, dir, dest_subpath, io, .{ .make_path = true, .replace = true });
@@ -9,6 +9,7 @@ pub const dev = @import("dev.zig");
9
9
  pub const cef = @import("cef.zig");
10
10
  pub const web_engine = @import("web_engine.zig");
11
11
  pub const buildgraph = @import("buildgraph.zig");
12
+ pub const junction = @import("junction.zig");
12
13
  pub const embedlib = @import("embedlib.zig");
13
14
  pub const eject_components = @import("eject_components.zig");
14
15
  pub const toolchain = @import("toolchain.zig");
@@ -1,4 +1,5 @@
1
1
  const std = @import("std");
2
+ const junction = @import("junction.zig");
2
3
 
3
4
  /// The SDK's default app icon, rendered from vector source by
4
5
  /// `zig build generate-icon` (tools/generate_app_icon.zig). Embedded so
@@ -944,11 +945,13 @@ fn buildZig(allocator: std.mem.Allocator, names: TemplateNames, framework_path:
944
945
  \\ const run = b.addRunArtifact(exe);
945
946
  \\ run.step.dependOn(&frontend_build.step);
946
947
  \\ addCefRuntimeRunFiles(b, target, run, exe, web_engine, cef_dir);
948
+ \\ addWebView2RuntimeRunFiles(b, target, run, web_engine, native_sdk_path);
947
949
  \\ const run_step = b.step("run", "Run the app");
948
950
  \\ run_step.dependOn(&run.step);
949
951
  \\
950
952
  \\ const dev = b.addSystemCommand(&.{ "native", "dev", "--manifest", "app.zon", "--binary" });
951
953
  \\ dev.addFileArg(exe.getEmittedBin());
954
+ \\ addWebView2RuntimeRunFiles(b, target, dev, web_engine, native_sdk_path);
952
955
  \\ dev.step.dependOn(&exe.step);
953
956
  \\ dev.step.dependOn(&frontend_install.step);
954
957
  \\ const dev_step = b.step("dev", "Run the frontend dev server and native shell");
@@ -972,6 +975,11 @@ fn buildZig(allocator: std.mem.Allocator, names: TemplateNames, framework_path:
972
975
  \\ b.fmt("zig-out/package/{s}-0.1.0-{s}-{s}{s}", .{ app_exe_name, @tagName(package_target), optimize_name, packageSuffix(package_target) }),
973
976
  \\ "--binary",
974
977
  \\ });
978
+ \\ // The CLI resolves SDK-owned package inputs (the vendored WebView2
979
+ \\ // loader) from the framework root; a PATH-resolved `native` could
980
+ \\ // belong to a different checkout than the one this build compiled
981
+ \\ // against, so hand the same root over explicitly.
982
+ \\ package.setEnvironmentVariable("NATIVE_SDK_PATH", b.pathFromRoot(native_sdk_path));
975
983
  \\ package.addFileArg(exe.getEmittedBin());
976
984
  \\ package.addArgs(&.{ "--web-engine", @tagName(web_engine), "--cef-dir", cef_dir });
977
985
  \\ if (cef_auto_install) package.addArg("--cef-auto-install");
@@ -1139,7 +1147,19 @@ fn buildZig(allocator: std.mem.Allocator, names: TemplateNames, framework_path:
1139
1147
  \\ if (web_engine == .chromium) app_mod.linkSystemLibrary("stdc++", .{});
1140
1148
  \\ } else if (platform == .windows) {
1141
1149
  \\ switch (web_engine) {
1142
- \\ .system => app_mod.addCSourceFile(.{ .file = nativeSdkPath(b, native_sdk_path, "src/platform/windows/webview2_host.cpp"), .flags = &.{ "-std=c++17" } }),
1150
+ \\ .system => {
1151
+ \\ // The vendored WebView2 SDK header (third_party/webview2)
1152
+ \\ // turns on the host's embedded-WebView layer; the host
1153
+ \\ // fails the compile by design if it cannot be found.
1154
+ \\ app_mod.addIncludePath(nativeSdkPath(b, native_sdk_path, "third_party/webview2/include"));
1155
+ \\ app_mod.addCSourceFile(.{ .file = nativeSdkPath(b, native_sdk_path, "src/platform/windows/webview2_host.cpp"), .flags = &.{ "-std=c++17" } });
1156
+ \\ // WebView2Loader.dll rides next to the installed app
1157
+ \\ // executable: the host loads it at runtime to discover
1158
+ \\ // the machine's WebView2 runtime. Canvas apps never
1159
+ \\ // touch it.
1160
+ \\ const loader = b.addInstallBinFile(nativeSdkPath(b, native_sdk_path, webView2LoaderSubPath(target)), "WebView2Loader.dll");
1161
+ \\ b.getInstallStep().dependOn(&loader.step);
1162
+ \\ },
1143
1163
  \\ .chromium => {
1144
1164
  \\ const cef_check = addCefCheck(b, target, cef_dir);
1145
1165
  \\ if (cef_auto_install) {
@@ -1172,6 +1192,26 @@ fn buildZig(allocator: std.mem.Allocator, names: TemplateNames, framework_path:
1172
1192
  \\ }
1173
1193
  \\}
1174
1194
  \\
1195
+ \\/// The vendored WebView2Loader.dll for the target architecture, relative
1196
+ \\/// to the framework root.
1197
+ \\fn webView2LoaderSubPath(target: std.Build.ResolvedTarget) []const u8 {
1198
+ \\ return if (target.result.cpu.arch == .aarch64)
1199
+ \\ "third_party/webview2/arm64/WebView2Loader.dll"
1200
+ \\ else
1201
+ \\ "third_party/webview2/x64/WebView2Loader.dll";
1202
+ \\}
1203
+ \\
1204
+ \\/// `zig build run` and `zig build dev` execute the cached artifact, which
1205
+ \\/// has no installed WebView2Loader.dll beside it; the vendored loader's
1206
+ \\/// directory goes on the step's PATH so the host's LoadLibrary resolves it
1207
+ \\/// (`native dev` passes its environment on to the app it spawns).
1208
+ \\fn addWebView2RuntimeRunFiles(b: *std.Build, target: std.Build.ResolvedTarget, run: *std.Build.Step.Run, web_engine: WebEngineOption, native_sdk_path: []const u8) void {
1209
+ \\ if (web_engine != .system) return;
1210
+ \\ if (target.result.os.tag != .windows) return;
1211
+ \\ const loader_dir = std.fs.path.dirname(webView2LoaderSubPath(target)).?;
1212
+ \\ run.addPathDir(b.pathFromRoot(b.pathJoin(&.{ native_sdk_path, loader_dir })));
1213
+ \\}
1214
+ \\
1175
1215
  \\fn addCefRuntimeRunFiles(b: *std.Build, target: std.Build.ResolvedTarget, run: *std.Build.Step.Run, exe: *std.Build.Step.Compile, web_engine: WebEngineOption, cef_dir: []const u8) void {
1176
1216
  \\ if (web_engine != .chromium) return;
1177
1217
  \\ if (target.result.os.tag != .macos) return;
@@ -2835,6 +2875,8 @@ test "writeDefaultApp emits Vite project files" {
2835
2875
  try std.testing.expect(std.mem.indexOf(u8, build_zig_text, "frontend_build.step.dependOn(&frontend_install.step)") != null);
2836
2876
  try std.testing.expect(std.mem.indexOf(u8, build_zig_text, "\"native\", \"dev\"") != null);
2837
2877
  try std.testing.expect(std.mem.indexOf(u8, build_zig_text, "dev.step.dependOn(&frontend_install.step)") != null);
2878
+ try std.testing.expect(std.mem.indexOf(u8, build_zig_text, "addWebView2RuntimeRunFiles(b, target, dev, web_engine, native_sdk_path)") != null);
2879
+ try std.testing.expect(std.mem.indexOf(u8, build_zig_text, "package.setEnvironmentVariable(\"NATIVE_SDK_PATH\", b.pathFromRoot(native_sdk_path))") != null);
2838
2880
  try std.testing.expect(std.mem.indexOf(u8, build_zig_text, "chromium") != null);
2839
2881
  try std.testing.expect(std.mem.indexOf(u8, build_zig_text, "cef-dir") != null);
2840
2882
  try std.testing.expect(std.mem.indexOf(u8, build_zig_text, "src/platform/macos/cef_host.mm") != null);
@@ -3142,13 +3184,71 @@ fn nativeDependencyPath(allocator: std.mem.Allocator, io: std.Io, destination: [
3142
3184
  defer allocator.free(framework_real);
3143
3185
 
3144
3186
  const relative = try std.fs.path.relative(allocator, cwd, null, destination_real, framework_real);
3187
+ errdefer allocator.free(relative);
3188
+ // On Windows, two different volumes (drive letters or UNC shares) have
3189
+ // no relative path between them, and std.fs.path.relative degrades to
3190
+ // the absolute target — which build.zig.zon rejects. The full scaffold's
3191
+ // build files are user-owned from day one, so the CLI cannot bridge with
3192
+ // a junction it would never refresh; teach the constraint instead.
3193
+ if (junction.crossesVolumes(relative)) {
3194
+ std.debug.print(
3195
+ \\cannot scaffold a full-shape app at {s}:
3196
+ \\the Native SDK ({s})
3197
+ \\sits on a different Windows volume, and the scaffolded
3198
+ \\build.zig.zon needs a relative SDK path — no relative path
3199
+ \\crosses volumes.
3200
+ \\
3201
+ , .{ destination_real, framework_real });
3202
+ std.debug.print(junction.cross_volume_ways_out, .{});
3203
+ return error.CrossVolumeFramework;
3204
+ }
3145
3205
  if (relative.len == 0) {
3206
+ // Dupe before freeing `relative`: if the dupe fails, the errdefer
3207
+ // above still owns `relative` and must free it exactly once.
3208
+ const dot = try allocator.dupe(u8, ".");
3146
3209
  allocator.free(relative);
3147
- return allocator.dupe(u8, ".");
3210
+ return dot;
3148
3211
  }
3149
3212
  return relative;
3150
3213
  }
3151
3214
 
3215
+ test "nativeDependencyPath falls back to `.` for a same-directory scaffold" {
3216
+ const io = std.testing.io;
3217
+ const destination = ".zig-cache/test-native-dependency-same-dir";
3218
+ try std.Io.Dir.cwd().createDirPath(io, destination);
3219
+ const destination_real = try std.Io.Dir.cwd().realPathFileAlloc(io, destination, std.testing.allocator);
3220
+ defer std.testing.allocator.free(destination_real);
3221
+
3222
+ const dependency = try nativeDependencyPath(std.testing.allocator, io, destination, destination_real);
3223
+ defer std.testing.allocator.free(dependency);
3224
+ try std.testing.expectEqualStrings(".", dependency);
3225
+ }
3226
+
3227
+ fn expectSameDirDependencyDot(allocator: std.mem.Allocator, io: std.Io, destination: []const u8, framework_path: []const u8) !void {
3228
+ const dependency = try nativeDependencyPath(allocator, io, destination, framework_path);
3229
+ defer allocator.free(dependency);
3230
+ try std.testing.expectEqualStrings(".", dependency);
3231
+ }
3232
+
3233
+ test "nativeDependencyPath survives every allocation-failure point of the `.` fallback" {
3234
+ // Walks every allocation-failure point of the `.` fallback and asserts
3235
+ // no leak and no swallowed OutOfMemory at each index. The fallback's
3236
+ // ownership rule — the errdefer releases the relative path exactly
3237
+ // once, so the fallible dupe must run before the manual free — keeps
3238
+ // this loop clean at the index where the dupe itself fails. (The slice
3239
+ // in this branch is empty, and freeing an empty slice is a no-op, so a
3240
+ // free-then-dupe ordering would not crash here today; the test pins
3241
+ // the ordering so the branch stays safe if it ever handles a non-empty
3242
+ // allocation.)
3243
+ const io = std.testing.io;
3244
+ const destination = ".zig-cache/test-native-dependency-oom";
3245
+ try std.Io.Dir.cwd().createDirPath(io, destination);
3246
+ const destination_real = try std.Io.Dir.cwd().realPathFileAlloc(io, destination, std.testing.allocator);
3247
+ defer std.testing.allocator.free(destination_real);
3248
+
3249
+ try std.testing.checkAllAllocationFailures(std.testing.allocator, expectSameDirDependencyDot, .{ io, destination, destination_real });
3250
+ }
3251
+
3152
3252
  fn appendZigString(out: *std.ArrayList(u8), allocator: std.mem.Allocator, value: []const u8) !void {
3153
3253
  try appendEscapedString(out, allocator, value);
3154
3254
  }
@@ -0,0 +1,27 @@
1
+ Copyright (C) Microsoft Corporation. All rights reserved.
2
+
3
+ Redistribution and use in source and binary forms, with or without
4
+ modification, are permitted provided that the following conditions are
5
+ met:
6
+
7
+ * Redistributions of source code must retain the above copyright
8
+ notice, this list of conditions and the following disclaimer.
9
+ * Redistributions in binary form must reproduce the above
10
+ copyright notice, this list of conditions and the following disclaimer
11
+ in the documentation and/or other materials provided with the
12
+ distribution.
13
+ * The name of Microsoft Corporation, or the names of its contributors
14
+ may not be used to endorse or promote products derived from this
15
+ software without specific prior written permission.
16
+
17
+ THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
18
+ "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
19
+ LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
20
+ A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
21
+ OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
22
+ SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
23
+ LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
24
+ DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
25
+ THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
26
+ (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
27
+ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
@@ -0,0 +1,19 @@
1
+ # WebView2 SDK Vendor Layout
2
+
3
+ The Windows system web engine embeds the OS WebView2 runtime. The interface header and the loader library that discovers the installed runtime come from the WebView2 SDK NuGet package and are vendored here so a repo checkout builds the real embedded-WebView Windows host with no extra fetch step.
4
+
5
+ Vendored from the `Microsoft.Web.WebView2` NuGet package, version `1.0.2903.40` (package sha256 `ef128016dd1e51c59178c827ed5b8aa3322c57afa8675d930f8109505542ad74`), under the package's BSD-style license (`LICENSE.txt`, kept verbatim alongside the files it covers):
6
+
7
+ ```text
8
+ third_party/webview2/
9
+ LICENSE.txt package LICENSE.txt, verbatim
10
+ include/WebView2.h build/native/include/WebView2.h, verbatim
11
+ x64/WebView2Loader.dll build/native/x64/WebView2Loader.dll, verbatim
12
+ arm64/WebView2Loader.dll build/native/arm64/WebView2Loader.dll, verbatim
13
+ ```
14
+
15
+ `include/EventToken.h` is a first-party compatibility shim (see its header comment), not a package file.
16
+
17
+ The build adds `include/` to the include path of the Windows host and stages the architecture's `WebView2Loader.dll` next to the app executable; the host loads it at runtime to locate the installed WebView2 runtime (preinstalled on stock Windows 11; on older machines the Evergreen runtime installer provides it). Apps that never load a WebView run fine without either piece.
18
+
19
+ To update: download a newer `Microsoft.Web.WebView2` package from NuGet, replace the files listed above verbatim, and record the new version and package sha256 here.
@@ -0,0 +1,12 @@
1
+ /* First-party compatibility shim, not part of the WebView2 SDK package:
2
+ * WebView2.h includes "EventToken.h" for this one struct, and the
3
+ * mingw-w64 headers zig ships do not carry that file. The layout is the
4
+ * OS ABI's event-registration cookie — a single 64-bit value. */
5
+ #ifndef __EVENTTOKEN_H__
6
+ #define __EVENTTOKEN_H__
7
+
8
+ typedef struct EventRegistrationToken {
9
+ __int64 value;
10
+ } EventRegistrationToken;
11
+
12
+ #endif