@native-sdk/cli 0.4.3 → 0.5.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (100) hide show
  1. package/build/app.zig +308 -72
  2. package/build/ts_run.mjs +63 -0
  3. package/build.zig +336 -7
  4. package/build.zig.zon +1 -0
  5. package/package.json +15 -10
  6. package/packages/core/package-lock.json +43 -0
  7. package/packages/core/package.json +37 -0
  8. package/packages/core/rt/rt.zig +1579 -0
  9. package/packages/core/sdk/bytes_text_methods.d.ts +88 -0
  10. package/packages/core/sdk/core.ts +694 -0
  11. package/packages/core/sdk/events.ts +137 -0
  12. package/packages/core/sdk/text.ts +519 -0
  13. package/packages/core/src/checker.ts +1869 -0
  14. package/packages/core/src/cli.ts +68 -0
  15. package/packages/core/src/devhost.ts +291 -0
  16. package/packages/core/src/devhost_resolver.mjs +22 -0
  17. package/packages/core/src/diagnostics.ts +417 -0
  18. package/packages/core/src/emitter.ts +8815 -0
  19. package/packages/core/src/infer.ts +1515 -0
  20. package/packages/core/src/modules.ts +173 -0
  21. package/packages/core/src/ownership.ts +740 -0
  22. package/packages/core/src/text_polyfill.ts +337 -0
  23. package/packages/core/src/text_tables.ts +408 -0
  24. package/packages/core/src/transpile.ts +146 -0
  25. package/packages/core/src/typed_ast.ts +536 -0
  26. package/packages/core/src/types.ts +815 -0
  27. package/skill-data/core/SKILL.md +3 -0
  28. package/skill-data/native-ui/SKILL.md +30 -0
  29. package/skill-data/ts-core/SKILL.md +493 -0
  30. package/skill-data/zig/SKILL.md +208 -0
  31. package/skills/native-sdk/SKILL.md +1 -1
  32. package/src/app_runner/root.zig +75 -9
  33. package/src/app_runner/ts_core_main.zig +231 -0
  34. package/src/platform/linux/gtk_host.c +226 -21
  35. package/src/platform/windows/webview2_host.cpp +16 -10
  36. package/src/primitives/app_manifest/comptime_scene.zig +341 -0
  37. package/src/primitives/app_manifest/root.zig +13 -0
  38. package/src/primitives/app_manifest/types.zig +14 -0
  39. package/src/primitives/app_manifest/validation.zig +18 -0
  40. package/src/primitives/app_manifest/web_layer.zig +366 -0
  41. package/src/primitives/canvas/commands.zig +14 -7
  42. package/src/primitives/canvas/lazy_tls.zig +73 -0
  43. package/src/primitives/canvas/render_generic_resources.zig +22 -15
  44. package/src/primitives/canvas/root.zig +6 -0
  45. package/src/primitives/canvas/tests.zig +1 -0
  46. package/src/primitives/canvas/text_atlas.zig +40 -32
  47. package/src/primitives/canvas/text_layout_cache.zig +29 -22
  48. package/src/primitives/canvas/text_measure_cache.zig +56 -41
  49. package/src/primitives/canvas/text_spans.zig +39 -26
  50. package/src/primitives/canvas/tokens.zig +54 -0
  51. package/src/primitives/canvas/ui.zig +125 -0
  52. package/src/primitives/canvas/ui_markup.zig +22 -3
  53. package/src/primitives/canvas/ui_markup_compiled.zig +97 -7
  54. package/src/primitives/canvas/ui_markup_compiled_tests.zig +275 -0
  55. package/src/primitives/canvas/ui_markup_contract.zig +68 -14
  56. package/src/primitives/canvas/ui_markup_contract_tests.zig +257 -2
  57. package/src/primitives/canvas/ui_markup_reflect.zig +214 -0
  58. package/src/primitives/canvas/ui_markup_view.zig +105 -1
  59. package/src/primitives/canvas/ui_markup_view_tests.zig +336 -0
  60. package/src/primitives/canvas/ui_schema.zig +8 -0
  61. package/src/primitives/canvas/ui_schema_tests.zig +5 -4
  62. package/src/primitives/canvas/widget_invalidation.zig +14 -7
  63. package/src/primitives/canvas/widget_render.zig +25 -15
  64. package/src/primitives/canvas/widget_render_controls.zig +15 -9
  65. package/src/primitives/canvas/widget_runtime_tests.zig +44 -0
  66. package/src/root.zig +7 -0
  67. package/src/runtime/api.zig +7 -0
  68. package/src/runtime/bridge_responses.zig +2 -0
  69. package/src/runtime/builtin_bridge.zig +6 -0
  70. package/src/runtime/canvas_frame.zig +57 -36
  71. package/src/runtime/canvas_images.zig +9 -3
  72. package/src/runtime/canvas_widget_control_tests.zig +5 -6
  73. package/src/runtime/canvas_widget_runtime.zig +7 -4
  74. package/src/runtime/effects.zig +490 -2
  75. package/src/runtime/effects_host_tests.zig +594 -0
  76. package/src/runtime/flow.zig +8 -0
  77. package/src/runtime/platform_bridge_tests.zig +1 -0
  78. package/src/runtime/root.zig +18 -0
  79. package/src/runtime/session_replay.zig +7 -1
  80. package/src/runtime/session_tests.zig +35 -8
  81. package/src/runtime/tests.zig +2 -0
  82. package/src/runtime/ts_core_host.zig +1505 -0
  83. package/src/runtime/ts_core_host_tests.zig +1408 -0
  84. package/src/runtime/ts_ui_app.zig +469 -0
  85. package/src/runtime/ui_app.zig +58 -0
  86. package/src/runtime/view_canvas.zig +24 -17
  87. package/src/runtime/view_widget_tree.zig +2 -2
  88. package/src/runtime/web_layer_gate_tests.zig +242 -0
  89. package/src/runtime/window_storage.zig +5 -0
  90. package/src/runtime/window_view_runtime.zig +1 -0
  91. package/src/tooling/buildgraph.zig +7 -1
  92. package/src/tooling/codesign.zig +212 -105
  93. package/src/tooling/doctor.zig +78 -0
  94. package/src/tooling/manifest.zig +314 -1
  95. package/src/tooling/package.zig +722 -18
  96. package/src/tooling/raw_manifest.zig +16 -0
  97. package/src/tooling/root.zig +1 -0
  98. package/src/tooling/templates.zig +911 -88
  99. package/src/tooling/ts_core.zig +486 -0
  100. package/src/tooling/verbs.zig +22 -0
package/build/app.zig CHANGED
@@ -5,6 +5,12 @@
5
5
 
6
6
  const std = @import("std");
7
7
 
8
+ /// The shared web-layer inference contract: this build graph is one thin
9
+ /// adapter over it (the CLI's manifest tooling and the app runner are the
10
+ /// others), feeding it the inputs only this boundary sees — the
11
+ /// `-Dweb-engine` and `-Dweb-layer` flags resolved against app.zon.
12
+ const web_layer_contract = @import("../src/primitives/app_manifest/web_layer.zig");
13
+
8
14
  const PlatformOption = enum {
9
15
  auto,
10
16
  null,
@@ -20,10 +26,9 @@ const TraceOption = enum {
20
26
  all,
21
27
  };
22
28
 
23
- const WebEngineOption = enum {
24
- system,
25
- chromium,
26
- };
29
+ const WebEngineOption = web_layer_contract.WebEngine;
30
+
31
+ const WebLayerOption = web_layer_contract.WebViewLayer;
27
32
 
28
33
  pub const AppOptions = struct {
29
34
  name: []const u8,
@@ -37,6 +42,121 @@ pub const AppOptions = struct {
37
42
  app_root: []const u8 = ".",
38
43
  };
39
44
 
45
+ /// Which core the app tree carries. No flag and no config anywhere: the
46
+ /// tree IS the truth — `src/core.ts` is a TypeScript core (transpiled at
47
+ /// build time, run through generated wiring), `src/main.zig` a Zig one,
48
+ /// and both at once is a teaching error naming the two files.
49
+ const CoreTree = enum { zig, ts, both, neither };
50
+
51
+ fn detectCoreTree(b: *std.Build, app_root: []const u8) CoreTree {
52
+ const has_ts = appFileExists(b, app_root, "src/core.ts");
53
+ const has_zig = appFileExists(b, app_root, "src/main.zig");
54
+ if (has_ts and has_zig) return .both;
55
+ if (has_ts) return .ts;
56
+ if (has_zig) return .zig;
57
+ return .neither;
58
+ }
59
+
60
+ fn appFileExists(b: *std.Build, app_root: []const u8, sub_path: []const u8) bool {
61
+ b.build_root.handle.access(b.graph.io, appPath(b, app_root, sub_path), .{}) catch return false;
62
+ return true;
63
+ }
64
+
65
+ /// The staged TypeScript-core wiring: one generated directory holding the
66
+ /// transpiled core (core.zig), its rt kernel, the app's markup, and the
67
+ /// SDK's generated-wiring entry (ts_core_main.zig as main.zig). Built once
68
+ /// per app build and shared by the exe and test modules.
69
+ const TsCoreStage = struct {
70
+ main_root: std.Build.LazyPath,
71
+ };
72
+
73
+ fn tsCoreStage(b: *std.Build, dep: *std.Build.Dependency, app_root: []const u8) TsCoreStage {
74
+ if (!appFileExists(b, app_root, "src/app.native")) {
75
+ @panic("\nthis app has a TypeScript core (src/core.ts) but no view: TS apps render markup," ++
76
+ " so add src/app.native (the whole view tier binds the core's emitted model)\n");
77
+ }
78
+ const node = b.findProgram(&.{"node"}, &.{}) catch {
79
+ @panic("\nbuilding a TypeScript app core needs node on PATH (the @native-sdk/core transpiler runs at" ++
80
+ " build time; the binary it emits ships no JS runtime).\nInstall Node.js 22+ — https://nodejs.org" ++
81
+ " or `brew install node` — and re-run.\n");
82
+ };
83
+ dep.builder.build_root.handle.access(
84
+ dep.builder.graph.io,
85
+ "packages/core/node_modules/@typescript/typescript6",
86
+ .{},
87
+ ) catch {
88
+ // Name the SDK dependency's real location (a checkout or the
89
+ // npm-installed @native-sdk/cli package — both carry
90
+ // packages/core with its lockfile, so `npm ci` works in place).
91
+ std.debug.panic("\nthe SDK's @native-sdk/core transpiler is missing its installed dependency.\nFix with:" ++
92
+ " cd {s}/packages/core && npm ci\n", .{dep.builder.build_root.path orelse "<sdk>"});
93
+ };
94
+
95
+ // The transpiler runs through build/ts_run.mjs, not as `node cli.ts`:
96
+ // on the npm-installed layout the transpiler's .ts sources live inside
97
+ // node_modules, where node refuses its builtin type stripping — the
98
+ // runner strips those modules with the transpiler's own installed
99
+ // TypeScript and is a pass-through on a repo checkout.
100
+ const transpile = b.addSystemCommand(&.{node});
101
+ transpile.addFileArg(dep.path("build/ts_run.mjs"));
102
+ transpile.addFileArg(dep.path("packages/core/src/cli.ts"));
103
+ transpile.addFileArg(b.path(appPath(b, app_root, "src/core.ts")));
104
+ transpile.addArg("-o");
105
+ const emitted_core = transpile.addOutputFileArg("core.zig");
106
+ // The transpiler reads its own sources, the SDK modules, and the core's
107
+ // WHOLE import graph at run time; declare them so a transpiler upgrade
108
+ // or an edit to ANY module of a multi-file core re-emits it. The graph
109
+ // is declared as every .ts under the app's src/ (a superset of the
110
+ // reachable imports: over-approximation only re-runs the transpile,
111
+ // never misses a stale input). Failure mode: the checker's NS
112
+ // diagnostics stream to stderr verbatim — they are the teaching layer,
113
+ // nothing wraps them.
114
+ addTsDirInputs(b, dep.builder, transpile, "packages/core/sdk");
115
+ addAppTsDirInputs(b, transpile, appPath(b, app_root, "src"));
116
+ const transpiler_sources = [_][]const u8{
117
+ "checker.ts", "cli.ts", "diagnostics.ts", "emitter.ts", "infer.ts", "modules.ts", "transpile.ts", "typed_ast.ts", "types.ts",
118
+ };
119
+ for (transpiler_sources) |source| {
120
+ transpile.addFileInput(dep.path(b.fmt("packages/core/src/{s}", .{source})));
121
+ }
122
+
123
+ // The wiring imports core.zig and app.native relatively; the emitted
124
+ // core imports rt.zig relatively: stage all four into one directory.
125
+ const staged = b.addWriteFiles();
126
+ _ = staged.addCopyFile(emitted_core, "core.zig");
127
+ _ = staged.addCopyFile(dep.path("packages/core/rt/rt.zig"), "rt.zig");
128
+ _ = staged.addCopyFile(b.path(appPath(b, app_root, "src/app.native")), "app.native");
129
+ const main_root = staged.addCopyFile(dep.path("src/app_runner/ts_core_main.zig"), "main.zig");
130
+ return .{ .main_root = main_root };
131
+ }
132
+
133
+ /// Declare every .ts file in an SDK-relative directory as a file input of
134
+ /// the transpile step (the SDK library modules an app may import).
135
+ fn addTsDirInputs(b: *std.Build, sdk_builder: *std.Build, transpile: *std.Build.Step.Run, dir_path: []const u8) void {
136
+ var dir = sdk_builder.build_root.handle.openDir(b.graph.io, dir_path, .{ .iterate = true }) catch return;
137
+ defer dir.close(b.graph.io);
138
+ var it = dir.iterate();
139
+ while (it.next(b.graph.io) catch null) |entry| {
140
+ if (entry.kind != .file) continue;
141
+ if (!std.mem.endsWith(u8, entry.name, ".ts")) continue;
142
+ transpile.addFileInput(sdk_builder.path(b.fmt("{s}/{s}", .{ dir_path, entry.name })));
143
+ }
144
+ }
145
+
146
+ /// Declare every .ts file under the app's src/ (recursively — a core may
147
+ /// split into subdirectories) as a file input of the transpile step.
148
+ fn addAppTsDirInputs(b: *std.Build, transpile: *std.Build.Step.Run, src_path: []const u8) void {
149
+ var dir = b.build_root.handle.openDir(b.graph.io, src_path, .{ .iterate = true }) catch return;
150
+ defer dir.close(b.graph.io);
151
+ var walker = dir.walk(b.allocator) catch return;
152
+ defer walker.deinit();
153
+ while (walker.next(b.graph.io) catch null) |entry| {
154
+ if (entry.kind != .file) continue;
155
+ if (!std.mem.endsWith(u8, entry.basename, ".ts")) continue;
156
+ transpile.addFileInput(b.path(b.fmt("{s}/{s}", .{ src_path, entry.path })));
157
+ }
158
+ }
159
+
40
160
  /// The `native_sdk_app_*` C ABI every embed static library exports.
41
161
  pub const mobile_export_symbol_names = [_][]const u8{
42
162
  "native_sdk_app_create",
@@ -185,11 +305,31 @@ pub fn addAppArtifacts(b: *std.Build, dep: *std.Build.Dependency, app_options: A
185
305
  const optimize = exampleOptimizeMode(b, optimize_request, .Debug);
186
306
  const app_optimize = exampleOptimizeMode(b, optimize_request, .ReleaseFast);
187
307
 
308
+ // The core role is detected from the tree (never a flag or config):
309
+ // builds with a custom `main` entry declared their core explicitly and
310
+ // skip detection.
311
+ const core_tree: CoreTree = if (std.mem.eql(u8, app_options.main, "src/main.zig"))
312
+ detectCoreTree(b, app_options.app_root)
313
+ else
314
+ .zig;
315
+ if (core_tree == .both) {
316
+ @panic("\nthis app declares two cores: src/core.ts (TypeScript) and src/main.zig (Zig)." ++
317
+ "\nAn app has exactly one core - the tree is the truth. Keep src/core.ts and delete" ++
318
+ " src/main.zig,\nor keep src/main.zig and delete src/core.ts. (Other Zig files under" ++
319
+ " src/ are fine either way.)\n");
320
+ }
321
+ const ts_stage: ?TsCoreStage = if (core_tree == .ts) tsCoreStage(b, dep, app_options.app_root) else null;
322
+
188
323
  // Mobile targets get the embed static library as a `lib` step: the
189
324
  // artifact the toolkit-owned iOS host (and any hand-written shim)
190
325
  // links, so `native dev|package --target ios` works against every
191
326
  // standard app build — generated graph or ejected — with nothing but
192
327
  // `-Dtarget`. Desktop targets keep the step absent.
328
+ if (ts_stage != null and (target.result.os.tag == .ios or target.result.abi.isAndroid())) {
329
+ @panic("\nTypeScript app cores build desktop apps today; the mobile embed library for TS" ++
330
+ " cores lands with the mobile host tier.\nBuild for a desktop target, or port the core" ++
331
+ " to a Zig `mobileOptions` app for mobile.\n");
332
+ }
193
333
  if (target.result.os.tag == .ios or target.result.abi.isAndroid()) {
194
334
  addMobileLibWithTarget(b, dep, target, optimize, .{
195
335
  .name = app_options.name,
@@ -202,6 +342,7 @@ pub fn addAppArtifacts(b: *std.Build, dep: *std.Build.Dependency, app_options: A
202
342
  const automation_enabled = b.option(bool, "automation", "Enable Native SDK automation artifacts") orelse false;
203
343
  const js_bridge_enabled = b.option(bool, "js-bridge", "Enable optional JavaScript bridge stubs") orelse false;
204
344
  const web_engine_override = b.option(WebEngineOption, "web-engine", "Override app.zon web engine: system, chromium");
345
+ const web_layer_override = b.option(WebLayerOption, "web-layer", "Override app.zon webview_layer: auto, include, exclude");
205
346
  const cef_dir_override = b.option([]const u8, "cef-dir", "Override CEF root directory for Chromium builds");
206
347
  const cef_auto_install_override = b.option(bool, "cef-auto-install", "Override app.zon CEF auto-install setting");
207
348
  const selected_platform: PlatformOption = switch (platform_option) {
@@ -217,13 +358,14 @@ pub fn addAppArtifacts(b: *std.Build, dep: *std.Build.Dependency, app_options: A
217
358
  if (selected_platform == .windows and target.result.os.tag != .windows) {
218
359
  @panic("-Dplatform=windows requires a Windows target");
219
360
  }
220
- const app_web_engine = appWebEngineConfig(b, app_options.app_root);
221
- const web_engine = web_engine_override orelse app_web_engine.web_engine;
222
- const cef_dir = cef_dir_override orelse defaultCefDir(selected_platform, app_web_engine.cef_dir);
223
- const cef_auto_install = cef_auto_install_override orelse app_web_engine.cef_auto_install;
361
+ const app_config = appManifestBuildConfig(b, app_options.app_root);
362
+ const web_engine = web_engine_override orelse app_config.web_engine;
363
+ const cef_dir = cef_dir_override orelse defaultCefDir(selected_platform, app_config.cef_dir);
364
+ const cef_auto_install = cef_auto_install_override orelse app_config.cef_auto_install;
224
365
  if (web_engine == .chromium and selected_platform != .macos) {
225
366
  @panic("-Dweb-engine=chromium currently requires -Dplatform=macos");
226
367
  }
368
+ const web_layer = resolveWebLayer(app_config, web_engine, web_layer_override);
227
369
 
228
370
  const options = b.addOptions();
229
371
  options.addOption([]const u8, "platform", switch (selected_platform) {
@@ -238,28 +380,60 @@ pub fn addAppArtifacts(b: *std.Build, dep: *std.Build.Dependency, app_options: A
238
380
  options.addOption(bool, "debug_overlay", debug_overlay);
239
381
  options.addOption(bool, "automation", automation_enabled);
240
382
  options.addOption(bool, "js_bridge", js_bridge_enabled);
383
+ options.addOption(bool, "web_layer", web_layer);
241
384
  const options_mod = options.createModule();
242
385
 
243
- const app_mod = appModule(b, dep, target, app_optimize, app_options, options_mod);
386
+ const app_mod = appModule(b, dep, target, app_optimize, app_options, options_mod, ts_stage);
244
387
  const exe = b.addExecutable(.{
245
388
  .name = app_options.name,
246
389
  .root_module = app_mod,
247
390
  });
248
- linkPlatform(b, dep, target, app_mod, exe, selected_platform, web_engine, cef_dir, cef_auto_install);
391
+ linkPlatform(b, dep, target, app_mod, exe, selected_platform, web_engine, web_layer, cef_dir, cef_auto_install);
249
392
  const install = b.addInstallArtifact(exe, .{});
250
393
  b.getInstallStep().dependOn(&install.step);
251
394
 
252
395
  const run = b.addRunArtifact(exe);
253
396
  addCefRuntimeRunFiles(b, target, run, exe, web_engine, cef_dir);
254
- addWebView2RuntimeRunFiles(dep, target, run, web_engine);
397
+ addWebView2RuntimeRunFiles(dep, target, run, web_engine, web_layer);
255
398
  const run_step = b.step("run", "Run the app");
256
399
  run_step.dependOn(&run.step);
257
400
 
258
- const test_app_mod = if (app_optimize == optimize) app_mod else appModule(b, dep, target, optimize, app_options, options_mod);
401
+ const test_app_mod = if (app_optimize == optimize) app_mod else appModule(b, dep, target, optimize, app_options, options_mod, ts_stage);
259
402
  const tests = b.addTest(.{ .root_module = test_app_mod, .use_llvm = useLlvmWorkaround(target) });
260
403
  const test_step = b.step("test", "Run tests");
261
404
  test_step.dependOn(&b.addRunArtifact(tests).step);
262
405
 
406
+ // `native test` must surface the app's compile-time teaching errors,
407
+ // not just its test failures. Test builds never analyze `main` (the
408
+ // test runner replaces the entry point), so rules that fire inside it
409
+ // — UiApp.create's Model-defaults rule above all — used to ambush at
410
+ // `native build`, the LAST step in the loop. Compiling this object
411
+ // forces full semantic analysis of the app module, entry point
412
+ // included; nothing links or runs.
413
+ const analysis_root = b.addWriteFiles().add("app_analysis.zig",
414
+ \\//! Generated by the app build: force semantic analysis of the
415
+ \\//! app's entry point at test time. Exactly `main`, transitively —
416
+ \\//! the same surface `native build` analyzes — so test-time can
417
+ \\//! never be stricter than the build it fronts.
418
+ \\comptime {
419
+ \\ const app = @import("app");
420
+ \\ if (@hasDecl(app, "main")) _ = &app.main;
421
+ \\}
422
+ \\
423
+ );
424
+ const analysis_mod = b.createModule(.{
425
+ .root_source_file = analysis_root,
426
+ .target = target,
427
+ .optimize = optimize,
428
+ });
429
+ analysis_mod.addImport("app", test_app_mod);
430
+ const analysis_obj = b.addObject(.{
431
+ .name = b.fmt("{s}-analysis", .{app_options.name}),
432
+ .root_module = analysis_mod,
433
+ .use_llvm = useLlvmWorkaround(target),
434
+ });
435
+ test_step.dependOn(&analysis_obj.step);
436
+
263
437
  // `zig build model-contract`: reflect the app's Model/Msg into
264
438
  // zig-out/model-contract.zon so `native check` can verify markup
265
439
  // bindings against the app's real surface without compiling the app.
@@ -331,6 +505,19 @@ pub fn addAppArtifacts(b: *std.Build, dep: *std.Build.Dependency, app_options: A
331
505
  // build graph knows the packaged binary's REAL mode, so forward
332
506
  // it instead of letting the CLI assume one.
333
507
  package_run.addArgs(&.{ "--optimize", @tagName(app_optimize) });
508
+ // Forward the RESOLVED web-layer decision, never the raw inputs:
509
+ // this graph already decided web vs native-only for the exe it is
510
+ // packaging (app.zon declarations plus -Dweb-layer/-Dweb-engine),
511
+ // and the CLI re-inferring from app.zon alone would miss a
512
+ // flag-driven override — a WebView2-referencing exe packaged
513
+ // without its loader. Handing over the decision itself makes
514
+ // exe/package agreement structural.
515
+ package_run.addArgs(&.{ "--web-layer", if (web_layer) "include" else "exclude" });
516
+ // Same reasoning for the web engine: the CLI defaults to system, so
517
+ // a Chromium exe packaged without these flags would ship no CEF
518
+ // runtime (the generated build graph already forwards them).
519
+ package_run.addArgs(&.{ "--web-engine", @tagName(web_engine), "--cef-dir", cef_dir });
520
+ if (cef_auto_install) package_run.addArg("--cef-auto-install");
334
521
  package_run.has_side_effects = true;
335
522
  const package_step = b.step("package", "Create a distributable package via the native CLI");
336
523
  package_step.dependOn(&package_run.step);
@@ -367,20 +554,35 @@ fn exampleOptimizeMode(b: *std.Build, requested: ?std.builtin.OptimizeMode, defa
367
554
  };
368
555
  }
369
556
 
370
- fn appModule(b: *std.Build, dep: *std.Build.Dependency, target: std.Build.ResolvedTarget, optimize: std.builtin.OptimizeMode, app_options: AppOptions, options_mod: *std.Build.Module) *std.Build.Module {
557
+ fn appModule(b: *std.Build, dep: *std.Build.Dependency, target: std.Build.ResolvedTarget, optimize: std.builtin.OptimizeMode, app_options: AppOptions, options_mod: *std.Build.Module, ts_stage: ?TsCoreStage) *std.Build.Module {
371
558
  const native_sdk_mod = nativeSdkModule(b, dep, target, optimize);
372
559
  const runner_mod = b.createModule(.{
373
560
  .root_source_file = dep.path("src/app_runner/root.zig"),
374
561
  .target = target,
375
562
  .optimize = optimize,
376
563
  });
564
+ const manifest_mod = b.createModule(.{ .root_source_file = b.path(appPath(b, app_options.app_root, "app.zon")) });
377
565
  runner_mod.addImport("native_sdk", native_sdk_mod);
378
566
  runner_mod.addImport("build_options", options_mod);
379
- runner_mod.addImport("app_manifest_zon", b.createModule(.{ .root_source_file = b.path(appPath(b, app_options.app_root, "app.zon")) }));
380
-
381
- const app_mod = localModule(b, target, optimize, appPath(b, app_options.app_root, app_options.main));
567
+ runner_mod.addImport("app_manifest_zon", manifest_mod);
568
+
569
+ const app_mod = if (ts_stage) |stage|
570
+ // TypeScript core: the app module roots at the staged generated
571
+ // wiring (ts_core_main.zig beside the transpiled core.zig, its rt
572
+ // kernel, and the app's markup).
573
+ b.createModule(.{
574
+ .root_source_file = stage.main_root,
575
+ .target = target,
576
+ .optimize = optimize,
577
+ })
578
+ else
579
+ localModule(b, target, optimize, appPath(b, app_options.app_root, app_options.main));
382
580
  app_mod.addImport("native_sdk", native_sdk_mod);
383
581
  app_mod.addImport("runner", runner_mod);
582
+ if (ts_stage != null) {
583
+ // The wiring derives scene/identity/security from app.zon itself.
584
+ app_mod.addImport("app_manifest_zon", manifest_mod);
585
+ }
384
586
  return app_mod;
385
587
  }
386
588
 
@@ -470,7 +672,7 @@ fn externalModule(b: *std.Build, dep: *std.Build.Dependency, target: std.Build.R
470
672
  // Reproduced with a 10-line `zig cc` program against both the 14.5 and
471
673
  // 26.0 SDKs. Release builds never hit it (no UBSan), which is why only
472
674
  // Debug-built examples (standardOptimizeOption default) crashed.
473
- fn linkPlatform(b: *std.Build, dep: *std.Build.Dependency, target: std.Build.ResolvedTarget, app_mod: *std.Build.Module, exe: *std.Build.Step.Compile, platform: PlatformOption, web_engine: WebEngineOption, cef_dir: []const u8, cef_auto_install: bool) void {
675
+ fn linkPlatform(b: *std.Build, dep: *std.Build.Dependency, target: std.Build.ResolvedTarget, app_mod: *std.Build.Module, exe: *std.Build.Step.Compile, platform: PlatformOption, web_engine: WebEngineOption, web_layer: bool, cef_dir: []const u8, cef_auto_install: bool) void {
474
676
  if (platform == .macos) {
475
677
  switch (web_engine) {
476
678
  .system => {
@@ -521,11 +723,23 @@ fn linkPlatform(b: *std.Build, dep: *std.Build.Dependency, target: std.Build.Res
521
723
  if (web_engine == .chromium) app_mod.linkSystemLibrary("c++", .{});
522
724
  } else if (platform == .linux) {
523
725
  switch (web_engine) {
524
- .system => {
726
+ .system => if (web_layer) {
525
727
  app_mod.addCSourceFile(.{ .file = dep.path("src/platform/linux/gtk_host.c"), .flags = &.{} });
526
728
  app_mod.linkSystemLibrary("gtk4", .{});
527
729
  app_mod.linkSystemLibrary("webkitgtk-6.0", .{});
528
730
  app_mod.linkSystemLibrary("dl", .{});
731
+ } else {
732
+ // Native-only app (nothing in app.zon declares web use):
733
+ // compile the GTK host without the embedded web layer.
734
+ // The stub define excludes the layer outright — the host
735
+ // honors it before probing for the WebKitGTK header, so
736
+ // the layer stays out even on machines where the
737
+ // development package is installed — libwebkitgtk is
738
+ // neither linked nor required at runtime, and the
739
+ // executable carries no WebKit reference at all.
740
+ app_mod.addCSourceFile(.{ .file = dep.path("src/platform/linux/gtk_host.c"), .flags = &.{"-DNATIVE_SDK_ALLOW_WEBKITGTK_STUB"} });
741
+ app_mod.linkSystemLibrary("gtk4", .{});
742
+ app_mod.linkSystemLibrary("dl", .{});
529
743
  },
530
744
  .chromium => {
531
745
  const cef_check = addCefCheck(b, target, cef_dir);
@@ -554,7 +768,7 @@ fn linkPlatform(b: *std.Build, dep: *std.Build.Dependency, target: std.Build.Res
554
768
  // bitmap-stretching a 96-DPI surface on scaled displays.
555
769
  exe.win32_manifest = dep.path("assets/native-sdk.manifest");
556
770
  switch (web_engine) {
557
- .system => {
771
+ .system => if (web_layer) {
558
772
  // The vendored WebView2 SDK header (third_party/webview2)
559
773
  // turns on the host's embedded-WebView layer; the host
560
774
  // fails the compile by design if it cannot be found.
@@ -566,6 +780,16 @@ fn linkPlatform(b: *std.Build, dep: *std.Build.Dependency, target: std.Build.Res
566
780
  // touch it.
567
781
  const loader = b.addInstallBinFile(dep.path(webView2LoaderSubPath(target)), "WebView2Loader.dll");
568
782
  b.getInstallStep().dependOn(&loader.step);
783
+ } else {
784
+ // Native-only app (nothing in app.zon declares web use):
785
+ // compile the host without the embedded-WebView layer.
786
+ // The stub define excludes the layer outright — the host
787
+ // honors it before probing for the WebView2 header, so
788
+ // the layer stays out even on machines where the SDK
789
+ // headers are reachable through the system include paths
790
+ // — no WebView2Loader.dll is installed or path-wired,
791
+ // and the executable carries no reference to it at all.
792
+ app_mod.addCSourceFile(.{ .file = dep.path("src/platform/windows/webview2_host.cpp"), .flags = &.{ "-std=c++17", "-DNATIVE_SDK_ALLOW_WEBVIEW2_STUB" } });
569
793
  },
570
794
  .chromium => {
571
795
  const cef_check = addCefCheck(b, target, cef_dir);
@@ -611,8 +835,9 @@ fn webView2LoaderSubPath(target: std.Build.ResolvedTarget) []const u8 {
611
835
  /// `zig build run` executes the cached artifact, which has no installed
612
836
  /// WebView2Loader.dll beside it; the vendored loader's directory goes on
613
837
  /// the run step's PATH so the host's LoadLibrary resolves it in dev runs.
614
- fn addWebView2RuntimeRunFiles(dep: *std.Build.Dependency, target: std.Build.ResolvedTarget, run: *std.Build.Step.Run, web_engine: WebEngineOption) void {
838
+ fn addWebView2RuntimeRunFiles(dep: *std.Build.Dependency, target: std.Build.ResolvedTarget, run: *std.Build.Step.Run, web_engine: WebEngineOption, web_layer: bool) void {
615
839
  if (web_engine != .system) return;
840
+ if (!web_layer) return;
616
841
  if (target.result.os.tag != .windows) return;
617
842
  const loader_dir = std.fs.path.dirname(webView2LoaderSubPath(target)).?;
618
843
  run.addPathDir(dep.builder.pathFromRoot(loader_dir));
@@ -676,10 +901,41 @@ fn addCefCheck(b: *std.Build, target: std.Build.ResolvedTarget, cef_dir: []const
676
901
  return b.addSystemCommand(&.{ "sh", "-c", script });
677
902
  }
678
903
 
679
- const AppWebEngineConfig = struct {
904
+ /// What the build graph reads out of app.zon: the web-engine/CEF knobs
905
+ /// and the web-layer inference inputs. An unreadable or unparsable
906
+ /// manifest falls back to the system engine WITH the web layer kept —
907
+ /// over-inclusion is a size cost, wrong exclusion is a broken app.
908
+ const AppManifestBuildConfig = struct {
680
909
  web_engine: WebEngineOption = .system,
681
910
  cef_dir: []const u8 = "third_party/cef/macos",
682
911
  cef_auto_install: bool = false,
912
+ webview_layer: WebLayerOption = .auto,
913
+ /// The first web declaration found (for teaching messages), or null
914
+ /// when app.zon declares no web use. `web_engine = "system"` alone is
915
+ /// NOT web intent — it is the default in many canvas manifests.
916
+ web_declaration: ?web_layer_contract.Declaration = null,
917
+ };
918
+
919
+ /// The lenient app.zon shape the build graph parses for inference: only
920
+ /// the fields that decide the web layer and the web engine; everything
921
+ /// else is ignored. Full schema validation stays with `native validate`
922
+ /// and the runner's comptime import.
923
+ const InferenceManifest = struct {
924
+ capabilities: []const []const u8 = &.{},
925
+ web_engine: []const u8 = "system",
926
+ webview_layer: []const u8 = "auto",
927
+ cef: struct {
928
+ dir: []const u8 = "third_party/cef/macos",
929
+ auto_install: bool = false,
930
+ } = .{},
931
+ frontend: ?struct {} = null,
932
+ shell: struct {
933
+ windows: []const struct {
934
+ views: []const struct {
935
+ kind: []const u8 = "",
936
+ } = &.{},
937
+ } = &.{},
938
+ } = .{},
683
939
  };
684
940
 
685
941
  fn defaultCefDir(platform: PlatformOption, configured: []const u8) []const u8 {
@@ -699,57 +955,37 @@ fn appPath(b: *std.Build, app_root: []const u8, sub_path: []const u8) []const u8
699
955
  return b.pathJoin(&.{ app_root, sub_path });
700
956
  }
701
957
 
702
- fn appWebEngineConfig(b: *std.Build, app_root: []const u8) AppWebEngineConfig {
703
- const source = b.build_root.handle.readFileAlloc(b.graph.io, appPath(b, app_root, "app.zon"), b.allocator, .limited(1024 * 1024)) catch return .{};
704
- var config: AppWebEngineConfig = .{};
705
- if (stringField(source, ".web_engine")) |value| {
706
- config.web_engine = parseWebEngine(value) orelse .system;
707
- }
708
- if (objectSection(source, ".cef")) |cef| {
709
- if (stringField(cef, ".dir")) |value| config.cef_dir = value;
710
- if (boolField(cef, ".auto_install")) |value| config.cef_auto_install = value;
711
- }
712
- return config;
713
- }
714
-
715
- fn parseWebEngine(value: []const u8) ?WebEngineOption {
716
- if (std.mem.eql(u8, value, "system")) return .system;
717
- if (std.mem.eql(u8, value, "chromium")) return .chromium;
718
- return null;
719
- }
720
-
721
- fn stringField(source: []const u8, field: []const u8) ?[]const u8 {
722
- const field_index = std.mem.indexOf(u8, source, field) orelse return null;
723
- const equals = std.mem.indexOfScalarPos(u8, source, field_index, '=') orelse return null;
724
- const start_quote = std.mem.indexOfScalarPos(u8, source, equals, '"') orelse return null;
725
- const end_quote = std.mem.indexOfScalarPos(u8, source, start_quote + 1, '"') orelse return null;
726
- return source[start_quote + 1 .. end_quote];
727
- }
728
-
729
- fn objectSection(source: []const u8, field: []const u8) ?[]const u8 {
730
- const field_index = std.mem.indexOf(u8, source, field) orelse return null;
731
- const open = std.mem.indexOfScalarPos(u8, source, field_index, '{') orelse return null;
732
- var depth: usize = 0;
733
- var index = open;
734
- while (index < source.len) : (index += 1) {
735
- switch (source[index]) {
736
- '{' => depth += 1,
737
- '}' => {
738
- depth -= 1;
739
- if (depth == 0) return source[open + 1 .. index];
740
- },
741
- else => {},
742
- }
743
- }
744
- return null;
958
+ fn appManifestBuildConfig(b: *std.Build, app_root: []const u8) AppManifestBuildConfig {
959
+ // The fallback for a manifest this lenient parse cannot read keeps
960
+ // the web layer (see AppManifestBuildConfig): a shape mismatch here
961
+ // is not proof the app declares no web use.
962
+ const fallback: AppManifestBuildConfig = .{ .web_declaration = .unreadable_manifest };
963
+ const source = b.build_root.handle.readFileAlloc(b.graph.io, appPath(b, app_root, "app.zon"), b.allocator, .limited(1024 * 1024)) catch return fallback;
964
+ const source_z = b.allocator.dupeZ(u8, source) catch return fallback;
965
+ @setEvalBranchQuota(2000);
966
+ const raw = std.zon.parse.fromSliceAlloc(InferenceManifest, b.allocator, source_z, null, .{ .ignore_unknown_fields = true }) catch return fallback;
967
+ return .{
968
+ .web_engine = web_layer_contract.parseWebEngine(raw.web_engine) orelse .system,
969
+ .cef_dir = raw.cef.dir,
970
+ .cef_auto_install = raw.cef.auto_install,
971
+ .webview_layer = web_layer_contract.parseWebViewLayer(raw.webview_layer) orelse @panic("app.zon .webview_layer must be \"auto\", \"include\", or \"exclude\""),
972
+ .web_declaration = web_layer_contract.manifestDeclaration(raw),
973
+ };
745
974
  }
746
975
 
747
- fn boolField(source: []const u8, field: []const u8) ?bool {
748
- const field_index = std.mem.indexOf(u8, source, field) orelse return null;
749
- const equals = std.mem.indexOfScalarPos(u8, source, field_index, '=') orelse return null;
750
- var index = equals + 1;
751
- while (index < source.len and std.ascii.isWhitespace(source[index])) : (index += 1) {}
752
- if (std.mem.startsWith(u8, source[index..], "true")) return true;
753
- if (std.mem.startsWith(u8, source[index..], "false")) return false;
754
- return null;
976
+ /// The web-layer decision for this build: the shared contract fed this
977
+ /// boundary's inputs — the manifest declarations from the lenient parse
978
+ /// and the engine RESOLVED from `-Dweb-engine` orelse app.zon. WEB means
979
+ /// the embedded-WebView layer compiles in; NATIVE-ONLY compiles the host
980
+ /// without it. `.webview_layer` (and `-Dweb-layer`) override the
981
+ /// inference — but an exclude that contradicts a web declaration is a
982
+ /// hard configure error, never a silently broken app.
983
+ fn resolveWebLayer(config: AppManifestBuildConfig, web_engine: WebEngineOption, override: ?WebLayerOption) bool {
984
+ const setting = override orelse config.webview_layer;
985
+ const declaration = web_layer_contract.foldEngine(config.web_declaration, web_engine);
986
+ const decision = web_layer_contract.decide(setting, declaration) catch std.debug.panic(
987
+ "the web layer is excluded ({s}) but the app declares web use ({s}); remove the exclude or drop the web declaration",
988
+ .{ if (override != null) "-Dweb-layer=exclude" else "app.zon .webview_layer = \"exclude\"", declaration.?.text() },
989
+ );
990
+ return decision.enabled;
755
991
  }
@@ -0,0 +1,63 @@
1
+ #!/usr/bin/env node
2
+
3
+ // Run a TypeScript module of the @native-sdk/core transpiler tier under
4
+ // node from ANY SDK layout:
5
+ //
6
+ // node ts_run.mjs <module.ts> [args...]
7
+ //
8
+ // From a repo checkout `node packages/core/src/cli.ts` works directly —
9
+ // node strips types natively. From the npm-installed @native-sdk/cli the
10
+ // SAME file sits inside node_modules, where node refuses its builtin type
11
+ // stripping by design (ERR_UNSUPPORTED_NODE_MODULES_TYPE_STRIPPING). This
12
+ // runner closes that gap without forking the layouts: it registers a load
13
+ // hook that strips ONLY node_modules-resident .ts modules, using the
14
+ // transpiler's own installed TypeScript (the `npm ci` dependency inside
15
+ // packages/core, resolved from the target module's location), and leaves
16
+ // every other module to node's native handling. Then it imports the
17
+ // requested module with argv respliced so the target sees its usual shape
18
+ // (its own path at argv[1], its arguments from argv[2]).
19
+ //
20
+ // On node builds without module.registerHooks (< 22.15) the hook is
21
+ // skipped: repo checkouts keep working natively and the npm layout fails
22
+ // with node's own teaching error naming the unsupported stripping.
23
+
24
+ import module, { createRequire } from 'node:module';
25
+ import { readFileSync } from 'node:fs';
26
+ import { resolve } from 'node:path';
27
+ import { pathToFileURL, fileURLToPath } from 'node:url';
28
+
29
+ const target = process.argv[2];
30
+ if (!target) {
31
+ console.error('usage: node ts_run.mjs <module.ts> [args...]');
32
+ process.exit(2);
33
+ }
34
+ const targetPath = resolve(target);
35
+ // Drop the runner from argv so the target module parses its own argv
36
+ // exactly as when node runs it directly.
37
+ process.argv.splice(1, 1);
38
+
39
+ if (typeof module.registerHooks === 'function') {
40
+ let ts = null;
41
+ module.registerHooks({
42
+ load(url, context, nextLoad) {
43
+ if (url.startsWith('file:') && url.endsWith('.ts') && url.includes('node_modules')) {
44
+ const filePath = fileURLToPath(url);
45
+ // The transpiler's own dependency, resolved from the transpiler's
46
+ // location (packages/core/node_modules after the taught `npm ci`).
47
+ ts ??= createRequire(targetPath)('@typescript/typescript6');
48
+ const { outputText } = ts.transpileModule(readFileSync(filePath, 'utf8'), {
49
+ fileName: filePath,
50
+ compilerOptions: {
51
+ target: ts.ScriptTarget.ESNext,
52
+ module: ts.ModuleKind.ESNext,
53
+ verbatimModuleSyntax: true,
54
+ },
55
+ });
56
+ return { format: 'module', source: outputText, shortCircuit: true };
57
+ }
58
+ return nextLoad(url, context);
59
+ },
60
+ });
61
+ }
62
+
63
+ await import(pathToFileURL(targetPath).href);