@native-sdk/cli 0.8.4 → 0.9.1

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 (161) hide show
  1. package/build/app.zig +1178 -74
  2. package/build.zig +715 -17
  3. package/build.zig.zon +1 -0
  4. package/native-sdk.d.ts +10 -0
  5. package/package.json +12 -11
  6. package/packages/core/compile-surface/core.ts +435 -3
  7. package/packages/core/package-lock.json +11 -11
  8. package/packages/core/package.json +2 -2
  9. package/packages/core/scripts/compiler_typecheck.mjs +116 -15
  10. package/packages/core/scripts/gen_service_surface.mjs +268 -0
  11. package/packages/core/scripts/merge_static_archives.mjs +78 -0
  12. package/packages/core/scripts/npm_static_spike.mjs +64 -0
  13. package/packages/core/scripts/run_external_core_compiler.mjs +122 -6
  14. package/packages/core/scripts/run_external_service_compiler.mjs +280 -0
  15. package/packages/core/scripts/stage_external_core.mjs +9 -1
  16. package/packages/core/scripts/stage_external_services.mjs +172 -0
  17. package/packages/core/scripts/surface_manifest_diff.mjs +253 -0
  18. package/packages/core/scripts/vendor_service_packages.mjs +189 -0
  19. package/packages/core/sdk/core.d.ts +224 -0
  20. package/packages/core/sdk/core.ts +694 -22
  21. package/packages/core/sdk/events.d.ts +89 -0
  22. package/packages/core/sdk/events.ts +128 -0
  23. package/packages/core/src/checker.ts +936 -15
  24. package/packages/core/src/cli.ts +156 -3
  25. package/packages/core/src/contract.ts +28 -5
  26. package/packages/core/src/devhost.ts +1876 -16
  27. package/packages/core/src/devhost_journal.mjs +183 -0
  28. package/packages/core/src/devhost_resolver.mjs +17 -1
  29. package/packages/core/src/devhost_service_worker.mjs +90 -0
  30. package/packages/core/src/diagnostics.ts +179 -22
  31. package/packages/core/src/frontend.ts +210 -34
  32. package/packages/core/src/infer.ts +24 -0
  33. package/packages/core/src/modules.ts +129 -80
  34. package/packages/core/src/service_contract.ts +597 -0
  35. package/packages/core/src/sqlite_cli.ts +93 -0
  36. package/packages/core/src/sqlite_codegen.ts +806 -0
  37. package/packages/core/src/sqlite_runtime_policy.ts +364 -0
  38. package/packages/core/src/typed_ast.ts +36 -8
  39. package/skill-data/automation/SKILL.md +1 -1
  40. package/skill-data/core/references/project-anatomy.md +1 -1
  41. package/skill-data/native-ui/SKILL.md +58 -5
  42. package/skill-data/ts-core/SKILL.md +123 -41
  43. package/skill-data/ts-services/SKILL.md +126 -0
  44. package/skill-data/ts-services/references/service-surface.md +604 -0
  45. package/skill-data/zig/SKILL.md +1 -1
  46. package/skills/native-sdk/SKILL.md +1 -1
  47. package/src/app_runner/no_migrations.zig +3 -0
  48. package/src/app_runner/no_services.zig +20 -0
  49. package/src/app_runner/root.zig +133 -4
  50. package/src/app_runner/ts_core_main.zig +254 -8
  51. package/src/app_runner/ts_core_mobile.zig +241 -0
  52. package/src/automation/protocol.zig +5 -1
  53. package/src/automation/snapshot.zig +31 -11
  54. package/src/embed/app_exports.zig +12 -1
  55. package/src/embed/c_api.zig +48 -2
  56. package/src/embed/conversions.zig +4 -5
  57. package/src/embed/host.zig +109 -1
  58. package/src/embed/root.zig +8 -0
  59. package/src/embed/tests.zig +241 -0
  60. package/src/embed/types.zig +51 -0
  61. package/src/embed/ui_host.zig +185 -5
  62. package/src/platform/android/NativeSdkActivity.java +131 -0
  63. package/src/platform/android/android_host.c +182 -1
  64. package/src/platform/android/native_sdk_app.h +17 -0
  65. package/src/platform/ios/native_sdk_app.h +17 -0
  66. package/src/platform/ios/uikit_host.m +115 -0
  67. package/src/platform/linux/cef_host.cpp +8 -2
  68. package/src/platform/linux/gtk_host.c +289 -22
  69. package/src/platform/linux/gtk_host.h +5 -1
  70. package/src/platform/linux/root.zig +109 -22
  71. package/src/platform/macos/appkit_host.h +24 -7
  72. package/src/platform/macos/appkit_host.m +686 -64
  73. package/src/platform/macos/cef_host.mm +400 -66
  74. package/src/platform/macos/root.zig +304 -47
  75. package/src/platform/null_platform.zig +435 -48
  76. package/src/platform/null_platform_tests.zig +113 -0
  77. package/src/platform/root.zig +19 -0
  78. package/src/platform/types.zig +281 -28
  79. package/src/platform/windows/root.zig +207 -27
  80. package/src/platform/windows/webview2_host.cpp +334 -51
  81. package/src/primitives/app_manifest/comptime_scene.zig +2 -0
  82. package/src/primitives/app_manifest/root.zig +4 -0
  83. package/src/primitives/app_manifest/tests.zig +3 -0
  84. package/src/primitives/app_manifest/types.zig +32 -0
  85. package/src/primitives/app_manifest/validation.zig +19 -1
  86. package/src/root.zig +53 -0
  87. package/src/runtime/api.zig +19 -0
  88. package/src/runtime/automation_commands.zig +35 -2
  89. package/src/runtime/automation_snapshot.zig +32 -20
  90. package/src/runtime/bridge_permission_tests.zig +58 -3
  91. package/src/runtime/bridge_responses.zig +4 -2
  92. package/src/runtime/builtin_bridge.zig +11 -1
  93. package/src/runtime/canvas_frame.zig +18 -11
  94. package/src/runtime/canvas_frame_animation_tests.zig +4 -0
  95. package/src/runtime/clock.zig +13 -1
  96. package/src/runtime/core.zig +145 -7
  97. package/src/runtime/credentials_store.zig +115 -0
  98. package/src/runtime/effects.zig +3701 -231
  99. package/src/runtime/effects_credentials_tests.zig +332 -0
  100. package/src/runtime/effects_file_tests.zig +587 -0
  101. package/src/runtime/effects_host_tests.zig +208 -1
  102. package/src/runtime/effects_notification_tests.zig +11 -0
  103. package/src/runtime/effects_relational_tests.zig +314 -0
  104. package/src/runtime/effects_store_tests.zig +211 -0
  105. package/src/runtime/file_access.zig +400 -0
  106. package/src/runtime/file_effect_crash_helper.zig +28 -0
  107. package/src/runtime/file_effect_crash_tests.zig +37 -0
  108. package/src/runtime/flow.zig +35 -10
  109. package/src/runtime/gpu_surface_events.zig +6 -1
  110. package/src/runtime/native_command_event_tests.zig +86 -2
  111. package/src/runtime/persist_store.zig +666 -0
  112. package/src/runtime/pty.zig +5 -2
  113. package/src/runtime/record_store.zig +788 -0
  114. package/src/runtime/relational_store.zig +854 -0
  115. package/src/runtime/root.zig +54 -0
  116. package/src/runtime/runtime_event_tests.zig +70 -0
  117. package/src/runtime/service_host.zig +711 -0
  118. package/src/runtime/service_pool.zig +1314 -0
  119. package/src/runtime/session_blobs.zig +4 -1
  120. package/src/runtime/session_journal.zig +158 -5
  121. package/src/runtime/session_record.zig +215 -0
  122. package/src/runtime/session_replay.zig +206 -11
  123. package/src/runtime/session_tests.zig +81 -0
  124. package/src/runtime/shell_layout.zig +1 -0
  125. package/src/runtime/shell_layout_tests.zig +120 -0
  126. package/src/runtime/sqlite_engine.zig +474 -0
  127. package/src/runtime/state.zig +16 -0
  128. package/src/runtime/system_services.zig +170 -38
  129. package/src/runtime/tests.zig +4 -0
  130. package/src/runtime/ts_core_host.zig +1067 -95
  131. package/src/runtime/ts_core_host_tests.zig +325 -11
  132. package/src/runtime/ts_ui_app.zig +953 -2
  133. package/src/runtime/ui_app.zig +434 -96
  134. package/src/runtime/ui_app_tests.zig +287 -11
  135. package/src/runtime/ui_app_window_tests.zig +61 -7
  136. package/src/runtime/validation.zig +42 -0
  137. package/src/runtime/view.zig +9 -0
  138. package/src/runtime/window_storage.zig +1 -0
  139. package/src/runtime/window_view_runtime.zig +2 -3
  140. package/src/runtime/window_views.zig +19 -0
  141. package/src/tooling/android.zig +21 -16
  142. package/src/tooling/db.zig +160 -0
  143. package/src/tooling/ios.zig +7 -1
  144. package/src/tooling/manifest.zig +214 -2
  145. package/src/tooling/package.zig +116 -0
  146. package/src/tooling/raw_manifest.zig +30 -0
  147. package/src/tooling/root.zig +1 -0
  148. package/src/tooling/templates.zig +189 -4
  149. package/src/tooling/ts_core.zig +366 -17
  150. package/src/tooling/verbs.zig +7 -0
  151. package/third_party/sqlite/README.md +13 -0
  152. package/third_party/sqlite/sqlite3.c +269649 -0
  153. package/third_party/sqlite/sqlite3.h +14349 -0
  154. package/tools/corewire/core_abi.zig +14 -2
  155. package/tools/corewire/emit.zig +98 -29
  156. package/tools/corewire/emit_facade.zig +442 -27
  157. package/tools/corewire/emit_profile.zig +6 -2
  158. package/tools/corewire/emit_service.zig +924 -0
  159. package/tools/corewire/main.zig +122 -0
  160. package/tools/corewire/service_contract.zig +250 -0
  161. package/tools/corewire/sidecar.zig +26 -15
package/build/app.zig CHANGED
@@ -4,6 +4,7 @@
4
4
  //! come from the native-sdk dependency.
5
5
 
6
6
  const std = @import("std");
7
+ const builtin = @import("builtin");
7
8
 
8
9
  /// The shared web-layer inference contract: this build graph is one thin
9
10
  /// adapter over it (the CLI's manifest tooling and the app runner are the
@@ -74,6 +75,156 @@ fn appFileExists(b: *std.Build, app_root: []const u8, sub_path: []const u8) bool
74
75
  return true;
75
76
  }
76
77
 
78
+ const TsWindowView = struct {
79
+ label: []const u8,
80
+ source_path: []const u8,
81
+ staged_path: []const u8,
82
+ };
83
+
84
+ const TsWindowSource = struct {
85
+ set_path: []const u8,
86
+ source_path: []const u8,
87
+ staged_path: []const u8,
88
+ };
89
+
90
+ const TsWindowViews = struct {
91
+ views: []const TsWindowView,
92
+ sources: []const TsWindowSource,
93
+ };
94
+
95
+ /// Default TypeScript secondary-window views are statically discovered under
96
+ /// `src/windows/`: `settings.native` serves descriptor label `settings`.
97
+ /// Direct files form the generated launcher's closed, comptime-compiled view
98
+ /// set while nested `.native` files are the shared import source set and
99
+ /// `windows(model)` owns dynamic liveness.
100
+ fn collectTsWindowViews(b: *std.Build, app_root: []const u8) TsWindowViews {
101
+ const windows_path = appPath(b, app_root, "src/windows");
102
+ var dir = b.build_root.handle.openDir(b.graph.io, windows_path, .{ .iterate = true }) catch return .{ .views = &.{}, .sources = &.{} };
103
+ defer dir.close(b.graph.io);
104
+ var walker = dir.walk(b.allocator) catch return .{ .views = &.{}, .sources = &.{} };
105
+ defer walker.deinit();
106
+ var views: std.ArrayList(TsWindowView) = .empty;
107
+ var sources: std.ArrayList(TsWindowSource) = .empty;
108
+ while (walker.next(b.graph.io) catch null) |entry| {
109
+ if (entry.kind != .file or !std.mem.endsWith(u8, entry.path, ".native")) continue;
110
+ const normalized_path = b.dupe(entry.path);
111
+ for (normalized_path) |*char| {
112
+ if (char.* == '\\') char.* = '/';
113
+ }
114
+ sources.append(b.allocator, .{
115
+ .set_path = normalized_path,
116
+ .source_path = b.fmt("src/windows/{s}", .{normalized_path}),
117
+ .staged_path = b.fmt("windows/{s}", .{normalized_path}),
118
+ }) catch @panic("OOM");
119
+ // Direct children are label-addressed window roots. Nested files
120
+ // are component sources those roots may import transitively.
121
+ if (std.mem.indexOfScalar(u8, entry.path, '/') != null or std.mem.indexOfScalar(u8, entry.path, '\\') != null) continue;
122
+ const label = entry.path[0 .. entry.path.len - ".native".len];
123
+ if (label.len == 0 or label.len > 64 or std.mem.eql(u8, label, ".") or std.mem.eql(u8, label, "..")) {
124
+ @panic("\ninvalid TypeScript secondary-window view filename: use src/windows/<label>.native with a non-empty label of at most 64 bytes\n");
125
+ }
126
+ for (label) |ch| {
127
+ if (ch == 0 or ch == '/' or ch == '\\') {
128
+ @panic("\ninvalid TypeScript secondary-window view filename: the filename stem must be a valid window label\n");
129
+ }
130
+ }
131
+ views.append(b.allocator, .{
132
+ .label = b.dupe(label),
133
+ .source_path = b.fmt("src/windows/{s}", .{entry.path}),
134
+ .staged_path = b.fmt("windows/{s}", .{entry.path}),
135
+ }) catch @panic("OOM");
136
+ }
137
+ const less = struct {
138
+ fn than(_: void, a: TsWindowView, z: TsWindowView) bool {
139
+ return std.mem.order(u8, a.label, z.label) == .lt;
140
+ }
141
+ }.than;
142
+ std.mem.sort(TsWindowView, views.items, {}, less);
143
+ const source_less = struct {
144
+ fn than(_: void, a: TsWindowSource, z: TsWindowSource) bool {
145
+ return std.mem.order(u8, a.set_path, z.set_path) == .lt;
146
+ }
147
+ }.than;
148
+ std.mem.sort(TsWindowSource, sources.items, {}, source_less);
149
+ return .{ .views = views.items, .sources = sources.items };
150
+ }
151
+
152
+ fn tsWindowRegistrySource(b: *std.Build, registry: TsWindowViews) []const u8 {
153
+ const views = registry.views;
154
+ var out: std.ArrayList(u8) = .empty;
155
+ out.appendSlice(b.allocator,
156
+ \\//! Generated by build/app.zig from src/windows/<label>.native.
157
+ \\const std = @import("std");
158
+ \\const native_sdk = @import("native_sdk");
159
+ \\const core = @import("core.zig");
160
+ \\const canvas = native_sdk.canvas;
161
+ \\const Adapter = native_sdk.TsUiApp(core);
162
+ \\const App = Adapter.App;
163
+ \\
164
+ ) catch @panic("OOM");
165
+ if (registry.sources.len > 0) {
166
+ out.appendSlice(b.allocator,
167
+ \\const window_sources = [_]canvas.ui_markup.SourceFile{
168
+ \\
169
+ ) catch @panic("OOM");
170
+ for (registry.sources) |source| {
171
+ const line = std.fmt.allocPrint(
172
+ b.allocator,
173
+ " .{{ .path = \"{f}\", .source = @embedFile(\"{f}\") }},\n",
174
+ .{ std.zig.fmtString(source.set_path), std.zig.fmtString(source.staged_path) },
175
+ ) catch @panic("OOM");
176
+ out.appendSlice(b.allocator, line) catch @panic("OOM");
177
+ }
178
+ out.appendSlice(b.allocator, "};\n") catch @panic("OOM");
179
+ }
180
+ for (views, 0..) |view, index| {
181
+ const line = std.fmt.allocPrint(
182
+ b.allocator,
183
+ "const WindowView{d} = canvas.CompiledMarkupImports(core.Model, core.Msg, \"{f}\", &window_sources);\n",
184
+ .{ index, std.zig.fmtString(std.fs.path.basename(view.staged_path)) },
185
+ ) catch @panic("OOM");
186
+ out.appendSlice(b.allocator, line) catch @panic("OOM");
187
+ }
188
+ if (views.len == 0) {
189
+ out.appendSlice(b.allocator,
190
+ \\pub fn build(_: *App.Ui, _: *const core.Model, _: []const u8) App.Ui.Node {
191
+ \\ @compileError("this TypeScript core exports windows(model), but the app has no src/windows/<label>.native views");
192
+ \\}
193
+ \\pub const fragments = [_]canvas.MarkupFragment{};
194
+ \\
195
+ ) catch @panic("OOM");
196
+ return out.items;
197
+ }
198
+ out.appendSlice(b.allocator,
199
+ \\pub fn build(ui: *App.Ui, model: *const core.Model, label: []const u8) App.Ui.Node {
200
+ \\
201
+ ) catch @panic("OOM");
202
+ for (views, 0..) |view, index| {
203
+ const line = std.fmt.allocPrint(
204
+ b.allocator,
205
+ " if (std.mem.eql(u8, label, \"{f}\")) return WindowView{d}.build(ui, model);\n",
206
+ .{ std.zig.fmtString(view.label), index },
207
+ ) catch @panic("OOM");
208
+ out.appendSlice(b.allocator, line) catch @panic("OOM");
209
+ }
210
+ out.appendSlice(b.allocator,
211
+ \\ @panic("windows(model) declared a label with no src/windows/<label>.native view");
212
+ \\}
213
+ \\pub const fragments = [_]canvas.MarkupFragment{
214
+ \\
215
+ ) catch @panic("OOM");
216
+ for (views, 0..) |view, index| {
217
+ const line = std.fmt.allocPrint(
218
+ b.allocator,
219
+ " WindowView{d}.fragment(\"{f}\"),\n",
220
+ .{ index, std.zig.fmtString(view.source_path) },
221
+ ) catch @panic("OOM");
222
+ out.appendSlice(b.allocator, line) catch @panic("OOM");
223
+ }
224
+ out.appendSlice(b.allocator, "};\n") catch @panic("OOM");
225
+ return out.items;
226
+ }
227
+
77
228
  /// How a TypeScript core compiles: through the external core compiler,
78
229
  /// always. The frontend checks the core and emits its contract sidecar,
79
230
  /// corewire projects the compile entry and profile, the exact-pinned
@@ -95,15 +246,212 @@ const core_compiler_teaching =
95
246
  /// and test modules.
96
247
  const TsCoreStage = struct {
97
248
  main_root: std.Build.LazyPath,
249
+ /// The staged mobile wiring (ts_core_mobile.zig beside the same
250
+ /// mirror/markup/registry files): the embed static library's `app`
251
+ /// module roots here on iOS/Android targets.
252
+ mobile_root: std.Build.LazyPath,
98
253
  /// The compiled-core archive: the app module links it (with libc,
99
254
  /// for the toolchain's runtime) beside the staged mirror.
100
255
  archive: std.Build.LazyPath,
256
+ /// Plain-scriptc service host compiled from src/services/, when that
257
+ /// class exists and the child carrier is selected. It is installed/
258
+ /// packaged beside the app executable.
259
+ service_exe: ?std.Build.LazyPath = null,
260
+ /// The in-process carrier's service archive (thread-instanced,
261
+ /// runtime-localized), when that class exists and the in-process
262
+ /// carrier is selected. The app module links it beside the core's
263
+ /// archive.
264
+ service_archive: ?std.Build.LazyPath = null,
265
+ migrations: std.Build.LazyPath,
101
266
  };
102
267
 
268
+ /// Which carrier runs src/services/ operations. Auto preserves the isolated,
269
+ /// single-instance child carrier; apps can explicitly opt into the parallel
270
+ /// in-process pool wherever the pinned service compiler can build the
271
+ /// runtime-localized service archive for the target (see
272
+ /// serviceArchiveSupported). `.service_carrier` in app.zon and the
273
+ /// `-Dservice-carrier` flag state the choice.
274
+ const ServiceCarrierOption = enum { auto, in_process, child };
275
+
276
+ const ServiceCarrier = enum { none, child, in_process };
277
+
278
+ /// Whether the pinned compiler can build TypeScript archives/executables for
279
+ /// this host/target pairing. Native desktop targets use their host toolchain,
280
+ /// including native Windows/MSVC. Cross-Windows builds use Zig's bundled GNU
281
+ /// sysroot; an MSVC cross target has no CRT headers or libraries to compile
282
+ /// the ScriptC runtime against. Mobile targets are aarch64 only and
283
+ /// archive-only (library mode — the app links the archive; no standalone
284
+ /// executable exists there): iOS device/simulator archives build on a macOS
285
+ /// host against the selected Apple SDK, Android archives build on any
286
+ /// desktop host against a discovered NDK sysroot.
287
+ pub fn scriptcCompileSupported(host: std.Target, target: std.Build.ResolvedTarget) bool {
288
+ const desktop_host = switch (host.os.tag) {
289
+ .macos, .linux, .windows => true,
290
+ else => false,
291
+ };
292
+ if (!desktop_host) return false;
293
+ const cross = scriptcTargetIsCross(host, target);
294
+ return switch (target.result.os.tag) {
295
+ .linux => if (target.result.abi.isAndroid()) target.result.cpu.arch == .aarch64 else true,
296
+ .windows => !cross or target.result.abi == .gnu,
297
+ .macos => host.os.tag == .macos,
298
+ .ios => host.os.tag == .macos and target.result.cpu.arch == .aarch64,
299
+ else => false,
300
+ };
301
+ }
302
+
303
+ /// Whether the pinned service compiler can build the in-process carrier's
304
+ /// archive (runtime-localized, thread-instanced) on this build host for
305
+ /// this target. Its object localizers are deliberately architecture-aware:
306
+ /// native Linux uses host binutils, cross-ELF accepts x86_64/aarch64
307
+ /// (Android's aarch64 archives ride this lane), COFF accepts x86_64 (GNU
308
+ /// when cross-compiled; the host ABI when native), and Mach-O — macOS, iOS
309
+ /// device, and iOS simulator — needs a macOS host (Apple linking rides the
310
+ /// host toolchain's SDK).
311
+ pub fn serviceArchiveSupported(host: std.Target, target: std.Build.ResolvedTarget) bool {
312
+ if (!scriptcCompileSupported(host, target)) return false;
313
+ const cross = scriptcTargetIsCross(host, target);
314
+ return switch (target.result.os.tag) {
315
+ .linux => !cross or target.result.cpu.arch == .x86_64 or target.result.cpu.arch == .aarch64,
316
+ .windows => target.result.cpu.arch == .x86_64,
317
+ .macos, .ios => host.os.tag == .macos,
318
+ else => false,
319
+ };
320
+ }
321
+
322
+ /// Whether a Linux target's spelling lands on Zig's default glibc floor,
323
+ /// which predates `arc4random_buf` — a symbol the compiled service
324
+ /// runtime references, so the link fails late and opaquely without the
325
+ /// configure-time teaching. A native target (no `-Dtarget` os) resolves
326
+ /// the system's own glibc and is exempt; an explicitly spelled `-gnu`
327
+ /// target needs a stated glibc of 2.36 or later (or `-musl`, whose libc
328
+ /// always has the symbol).
329
+ pub fn linuxGlibcSpellingHitsDefaultFloor(target: std.Build.ResolvedTarget) bool {
330
+ if (target.result.os.tag != .linux or !target.result.abi.isGnu()) return false;
331
+ if (target.query.os_tag == null) return false;
332
+ const glibc = target.query.glibc_version orelse return true;
333
+ return glibc.order(.{ .major = 2, .minor = 36, .patch = 0 }) == .lt;
334
+ }
335
+
336
+ /// Whether ScriptC needs its zig-cc target lane rather than the native host
337
+ /// compiler. Keep this identical to the driver scripts' platform-triple
338
+ /// comparison: a stated glibc version makes an otherwise same-triple Linux
339
+ /// target cross because that floor must reach Zig's `-target` argument.
340
+ pub fn scriptcTargetIsCross(host: std.Target, target: std.Build.ResolvedTarget) bool {
341
+ if (target.result.os.tag != host.os.tag or target.result.cpu.arch != host.cpu.arch) return true;
342
+ // Zig's Windows host triple defaults to GNU even when native clang uses
343
+ // the installed Windows toolchain. A same-architecture MSVC target is
344
+ // therefore still native compiler work. Preserve an exact native GNU
345
+ // triple too; every other ABI change needs the zig-cc cross lane.
346
+ if (target.result.os.tag == .windows) {
347
+ return target.result.abi != host.abi and target.result.abi != .msvc;
348
+ }
349
+ return target.result.abi != host.abi or target.query.glibc_version != null;
350
+ }
351
+
352
+ /// The glibc-floor teaching for explicitly targeted ScriptC builds. Both the
353
+ /// core archive and either service carrier carry the compiled TypeScript
354
+ /// runtime, so all of them hit the same missing symbol. This is independent of
355
+ /// whether the target triple happens to match the build host.
356
+ pub fn scriptcLinuxGlibcSpellingTeaching(b: *std.Build, target: std.Build.ResolvedTarget) []const u8 {
357
+ return b.fmt(
358
+ "\nTypeScript target {t}-linux-gnu uses Zig's default glibc floor, which" ++
359
+ " predates arc4random_buf — a symbol the compiled runtime needs (glibc" ++
360
+ " 2.36+).\nSpell the target as \"{t}-linux-gnu.2.36\" (or later), or" ++
361
+ " \"{t}-linux-musl\".\n",
362
+ .{ target.result.cpu.arch, target.result.cpu.arch, target.result.cpu.arch },
363
+ );
364
+ }
365
+
366
+ pub fn panicScriptcLinuxGlibcSpelling(b: *std.Build, target: std.Build.ResolvedTarget) noreturn {
367
+ @panic(scriptcLinuxGlibcSpellingTeaching(b, target));
368
+ }
369
+
370
+ pub fn panicUnsupportedScriptcTarget(b: *std.Build, host: std.Target, target: std.Build.ResolvedTarget) noreturn {
371
+ if (target.result.os.tag == .windows and scriptcTargetIsCross(host, target) and target.result.abi != .gnu) {
372
+ @panic(b.fmt(
373
+ "\nTypeScript cross-target Windows builds require the GNU ABI: Zig supplies" ++
374
+ " that target's CRT and system libraries, while an MSVC target needs a native" ++
375
+ " Windows toolchain.\nBuild {t}-windows-msvc on a matching Windows host, or" ++
376
+ " cross-compile as \"{t}-windows-gnu\".\n",
377
+ .{ target.result.cpu.arch, target.result.cpu.arch },
378
+ ));
379
+ }
380
+ if (target.result.os.tag == .ios and host.os.tag != .macos) {
381
+ @panic(
382
+ "\nTypeScript iOS builds run on a macOS build host only: the Apple SDK sysroot" ++
383
+ " and Mach-O symbol localization live there.\nBuild iOS apps on a Mac.\n",
384
+ );
385
+ }
386
+ @panic(
387
+ "\nTypeScript builds support native host targets, Linux and Windows GNU cross" ++
388
+ " targets from macOS/Linux/Windows, macOS targets from macOS, and the mobile" ++
389
+ " targets aarch64 iOS/iOS-simulator (from macOS) and aarch64 Android." ++
390
+ "\nChoose a supported target/host pairing.\n",
391
+ );
392
+ }
393
+
394
+ fn resolveServiceCarrier(
395
+ choice: ServiceCarrierOption,
396
+ has_services: bool,
397
+ b: *std.Build,
398
+ target: std.Build.ResolvedTarget,
399
+ ) ServiceCarrier {
400
+ if (!has_services) return .none;
401
+ const host = b.graph.host.result;
402
+ const supported = serviceArchiveSupported(host, target);
403
+ // Mobile has no child processes, so the in-process pool is the only
404
+ // carrier there: auto resolves to it, and an explicit "child" is a
405
+ // stated impossibility, taught rather than quietly rewritten.
406
+ if (target.result.os.tag == .ios or target.result.abi.isAndroid()) {
407
+ return switch (choice) {
408
+ .auto, .in_process => if (supported) .in_process else panicUnsupportedScriptcTarget(b, host, target),
409
+ .child => @panic(
410
+ "\nservice_carrier = \"child\" is unavailable on mobile targets: iOS and Android" ++
411
+ " apps cannot spawn a sibling service process, so src/services operations run" ++
412
+ " on the in-process pool there.\nUse \"auto\" or \"in_process\" (desktop" ++
413
+ " builds of the same app keep the child carrier under auto).\n",
414
+ ),
415
+ };
416
+ }
417
+ const carrier: ServiceCarrier = switch (choice) {
418
+ .auto, .child => .child,
419
+ .in_process => if (supported) .in_process else @panic(
420
+ "\nservice_carrier = \"in_process\" requires a target the pinned service compiler" ++
421
+ " can produce a runtime-localized archive for: native Linux, cross-Linux" ++
422
+ " x86_64/aarch64, native Windows x86_64, cross-Windows x86_64 GNU," ++
423
+ " macOS from a macOS build host, or a mobile target." ++
424
+ "\nUse \"child\" (or drop the setting — auto selects the child carrier)" ++
425
+ " for this target.\n",
426
+ ),
427
+ };
428
+ return carrier;
429
+ }
430
+
431
+ /// The `arch-os-abi` platform spelling every ScriptC compile lane receives.
432
+ /// A stated glibc version rides the abi (`gnu.2.36`) so the compiler's
433
+ /// cross lane builds at the spelled floor rather than the default one.
434
+ pub fn scriptcPlatformTriple(b: *std.Build, target: std.Build.ResolvedTarget) []const u8 {
435
+ const triple = b.fmt("{t}-{t}-{t}", .{ target.result.cpu.arch, target.result.os.tag, target.result.abi });
436
+ if (target.result.os.tag != .linux or !target.result.abi.isGnu()) return triple;
437
+ const glibc = target.query.glibc_version orelse return triple;
438
+ return if (glibc.patch == 0)
439
+ b.fmt("{s}.{d}.{d}", .{ triple, glibc.major, glibc.minor })
440
+ else
441
+ b.fmt("{s}.{d}.{d}.{d}", .{ triple, glibc.major, glibc.minor, glibc.patch });
442
+ }
443
+
444
+ fn parseServiceCarrierOption(raw: []const u8) ServiceCarrierOption {
445
+ if (std.mem.eql(u8, raw, "auto")) return .auto;
446
+ if (std.mem.eql(u8, raw, "in_process")) return .in_process;
447
+ if (std.mem.eql(u8, raw, "child")) return .child;
448
+ @panic("\n.service_carrier must be \"auto\", \"in_process\", or \"child\"\n");
449
+ }
450
+
103
451
  /// The frontend's own sources — the staleness set of every build step
104
452
  /// that runs it (a frontend edit re-checks every core).
105
453
  const frontend_sources = [_][]const u8{
106
- "checker.ts", "cli.ts", "contract.ts", "diagnostics.ts", "frontend.ts", "infer.ts", "modules.ts", "ownership.ts", "typed_ast.ts", "types.ts", "wyhash.ts",
454
+ "checker.ts", "cli.ts", "contract.ts", "diagnostics.ts", "frontend.ts", "infer.ts", "modules.ts", "ownership.ts", "service_contract.ts", "sqlite_codegen.ts", "sqlite_cli.ts", "sqlite_runtime_policy.ts", "typed_ast.ts", "types.ts", "wyhash.ts",
107
455
  };
108
456
 
109
457
  /// Whether the frontend's TypeScript compiler (@typescript/old, the
@@ -261,6 +609,25 @@ fn tsExternalCompilerJs(b: *std.Build, dep: *std.Build.Dependency) ?[]const u8 {
261
609
  }
262
610
  }
263
611
 
612
+ fn requireTsExternalCompilerJs(b: *std.Build, dep: *std.Build.Dependency) []const u8 {
613
+ return tsExternalCompilerJs(b, dep) orelse {
614
+ const sdk_root = tsSdkRoot(dep.builder.allocator, dep.builder.graph.io, dep);
615
+ std.debug.print(
616
+ \\
617
+ \\error: the external TypeScript compiler is not installed (cores and services
618
+ \\compile through it). It ships as an exact-pinned dependency of the SDK's
619
+ \\packages/core — install it once with:
620
+ \\ cd {s}/packages/core && npm ci
621
+ \\(or point NATIVE_SDK_CORE_COMPILER at the pinned release's command; an
622
+ \\npm-installed @native-sdk/cli carries the compiler automatically — if it is
623
+ \\missing there, the install is broken: reinstall @native-sdk/cli).
624
+ \\
625
+ \\
626
+ , .{sdk_root});
627
+ std.process.exit(1);
628
+ };
629
+ }
630
+
264
631
  /// The SDK dependency's real root, resolved the way both the toolchain
265
632
  /// check and its teaching name it.
266
633
  fn tsSdkRoot(allocator: std.mem.Allocator, io: std.Io, dep: *std.Build.Dependency) []const u8 {
@@ -268,19 +635,19 @@ fn tsSdkRoot(allocator: std.mem.Allocator, io: std.Io, dep: *std.Build.Dependenc
268
635
  return std.Io.Dir.cwd().realPathFileAlloc(io, raw_root, allocator) catch raw_root;
269
636
  }
270
637
 
271
- /// The TS-core preflight — the markup view, node, and the frontend
272
- /// toolchain gate — returning the resolved node program. The frontend
273
- /// (the subset checker and the contract-sidecar emitter) runs under
274
- /// node; the compile itself is the external toolchain's.
275
- fn tsCorePreflight(b: *std.Build, dep: *std.Build.Dependency, app_root: []const u8) []const u8 {
276
- if (!appFileExists(b, app_root, "src/app.native")) {
277
- @panic("\nthis app has a TypeScript core (src/core.ts) but no view: TS apps render markup," ++
278
- " so add src/app.native (the whole view tier binds the core's model)\n");
279
- }
280
- const node = b.findProgram(&.{"node"}, &.{}) catch {
281
- @panic("\nbuilding a TypeScript app core needs node on PATH (the @native-sdk/core frontend checks the" ++
638
+ const TsToolingConsumer = enum { app_core, sqlite_schema };
639
+
640
+ /// Resolve the node + pinned TypeScript loader shared by the app-core
641
+ /// frontend and relational schema generator. Keep app-shape assertions out
642
+ /// of this helper: a Zig core may use SQLite without carrying a markup view.
643
+ fn tsToolingPreflight(b: *std.Build, dep: *std.Build.Dependency, consumer: TsToolingConsumer) []const u8 {
644
+ const node = b.findProgram(&.{"node"}, &.{}) catch switch (consumer) {
645
+ .app_core => @panic("\nbuilding a TypeScript app core needs node on PATH (the @native-sdk/core frontend checks the" ++
282
646
  " core at build time; the binary you ship carries no JS runtime).\nInstall Node.js 22.15+ (on the 23" ++
283
- " line: 23.5+) — https://nodejs.org or `brew install node` — and re-run.\n");
647
+ " line: 23.5+) — https://nodejs.org or `brew install node` — and re-run.\n"),
648
+ .sqlite_schema => @panic("\nbuilding relational SQLite migrations needs node on PATH (the schema checker and" ++
649
+ " migration generator run at build time; the binary you ship carries no JS runtime).\nInstall Node.js" ++
650
+ " 22.15+ (on the 23 line: 23.5+) — https://nodejs.org or `brew install node` — and re-run.\n"),
284
651
  };
285
652
  switch (tsToolchainResolution(b, dep)) {
286
653
  .resolved => {},
@@ -292,16 +659,28 @@ fn tsCorePreflight(b: *std.Build, dep: *std.Build.Dependency, app_root: []const
292
659
  // fail the configure phase cleanly — a teaching message, never
293
660
  // a panic stack trace.
294
661
  const sdk_root = tsSdkRoot(dep.builder.allocator, dep.builder.graph.io, dep);
295
- std.debug.print(
296
- \\
297
- \\error: the @native-sdk/core frontend cannot resolve its TypeScript toolchain
298
- \\(its compiler, @typescript/old). On a repo checkout, install it once with:
299
- \\ cd {s}/packages/core && npm ci --include=dev
300
- \\(An npm-installed @native-sdk/cli carries the toolchain automatically; if it
301
- \\is missing there, the install is broken - reinstall @native-sdk/cli.)
302
- \\
303
- \\
304
- , .{sdk_root});
662
+ switch (consumer) {
663
+ .app_core => std.debug.print(
664
+ \\
665
+ \\error: the @native-sdk/core frontend cannot resolve its TypeScript toolchain
666
+ \\(its compiler, @typescript/old). On a repo checkout, install it once with:
667
+ \\ cd {s}/packages/core && npm ci --include=dev
668
+ \\(An npm-installed @native-sdk/cli carries the toolchain automatically; if it
669
+ \\is missing there, the install is broken - reinstall @native-sdk/cli.)
670
+ \\
671
+ \\
672
+ , .{sdk_root}),
673
+ .sqlite_schema => std.debug.print(
674
+ \\
675
+ \\error: the relational SQLite schema generator cannot resolve its TypeScript toolchain
676
+ \\(its compiler, @typescript/old). On a repo checkout, install it once with:
677
+ \\ cd {s}/packages/core && npm ci --include=dev
678
+ \\(An npm-installed @native-sdk/cli carries the toolchain automatically; if it
679
+ \\is missing there, the install is broken - reinstall @native-sdk/cli.)
680
+ \\
681
+ \\
682
+ , .{sdk_root}),
683
+ }
305
684
  std.process.exit(1);
306
685
  },
307
686
  .version_mismatch => |mismatch| {
@@ -310,22 +689,45 @@ fn tsCorePreflight(b: *std.Build, dep: *std.Build.Dependency, app_root: []const
310
689
  // @typescript/old shadows the SDK's exact pin, and no install
311
690
  // command fixes what is already installed — the conflict has
312
691
  // to move.
313
- std.debug.print(
314
- \\
315
- \\error: the @native-sdk/core frontend's TypeScript compiler resolves at the
316
- \\wrong version: @typescript/old resolves to typescript {s}, but the SDK pins
317
- \\npm:typescript@{s}. Another package in this tree pins a conflicting
318
- \\@typescript/old - align it with the SDK's pin (or remove it) and reinstall,
319
- \\so the SDK's exact pin is the copy that resolves.
320
- \\
321
- \\
322
- , .{ mismatch.resolved, mismatch.pinned });
692
+ switch (consumer) {
693
+ .app_core => std.debug.print(
694
+ \\
695
+ \\error: the @native-sdk/core frontend's TypeScript compiler resolves at the
696
+ \\wrong version: @typescript/old resolves to typescript {s}, but the SDK pins
697
+ \\npm:typescript@{s}. Another package in this tree pins a conflicting
698
+ \\@typescript/old - align it with the SDK's pin (or remove it) and reinstall,
699
+ \\so the SDK's exact pin is the copy that resolves.
700
+ \\
701
+ \\
702
+ , .{ mismatch.resolved, mismatch.pinned }),
703
+ .sqlite_schema => std.debug.print(
704
+ \\
705
+ \\error: the relational SQLite schema generator's TypeScript compiler resolves at the
706
+ \\wrong version: @typescript/old resolves to typescript {s}, but the SDK pins
707
+ \\npm:typescript@{s}. Another package in this tree pins a conflicting
708
+ \\@typescript/old - align it with the SDK's pin (or remove it) and reinstall,
709
+ \\so the SDK's exact pin is the copy that resolves.
710
+ \\
711
+ \\
712
+ , .{ mismatch.resolved, mismatch.pinned }),
713
+ }
323
714
  std.process.exit(1);
324
715
  },
325
716
  }
326
717
  return node;
327
718
  }
328
719
 
720
+ /// The TS-core-only shape gate plus the shared tooling preflight. The
721
+ /// frontend (the subset checker and contract-sidecar emitter) runs under
722
+ /// node; the compile itself is the external toolchain's.
723
+ fn tsCorePreflight(b: *std.Build, dep: *std.Build.Dependency, app_root: []const u8) []const u8 {
724
+ if (!appFileExists(b, app_root, "src/app.native")) {
725
+ @panic("\nthis app has a TypeScript core (src/core.ts) but no view: TS apps render markup," ++
726
+ " so add src/app.native (the whole view tier binds the core's model)\n");
727
+ }
728
+ return tsToolingPreflight(b, dep, .app_core);
729
+ }
730
+
329
731
  /// The TypeScript-core compile lane: the frontend checks the core and
330
732
  /// emits its contract sidecar, corewire projects the generated compile
331
733
  /// entry and library-mode profile, the stager assembles the compile
@@ -337,8 +739,70 @@ fn tsCorePreflight(b: *std.Build, dep: *std.Build.Dependency, app_root: []const
337
739
  /// its own compile. The staged module directory carries core.zig (the
338
740
  /// mirror) + its staged runtime + app.native + main.zig, so the
339
741
  /// generated wiring imports one fixed shape.
340
- fn tsCoreStage(b: *std.Build, dep: *std.Build.Dependency, app_root: []const u8, app_name: []const u8) TsCoreStage {
742
+ fn tsCoreStage(
743
+ b: *std.Build,
744
+ dep: *std.Build.Dependency,
745
+ target: std.Build.ResolvedTarget,
746
+ app_root: []const u8,
747
+ app_name: []const u8,
748
+ persist_capability: bool,
749
+ store_capability: bool,
750
+ relational_capability: bool,
751
+ credentials_capability: bool,
752
+ credentials_permission: bool,
753
+ persist_version: ?u64,
754
+ service_packages: []const ServicePackageConfig,
755
+ service_carrier_choice: ServiceCarrierOption,
756
+ service_pool_workers: ?u8,
757
+ ) TsCoreStage {
341
758
  const node = tsCorePreflight(b, dep, app_root);
759
+ const window_views = collectTsWindowViews(b, app_root);
760
+ const has_services = appHasServiceFiles(b, app_root);
761
+ if (!scriptcCompileSupported(b.graph.host.result, target)) {
762
+ panicUnsupportedScriptcTarget(b, b.graph.host.result, target);
763
+ }
764
+ // Every TypeScript app compiles its core archive for the target. Any
765
+ // explicitly spelled Linux GNU target without a sufficient glibc version
766
+ // lands on Zig's too-old default floor, even when its triple matches the
767
+ // build host; reject it before either compile lane reaches the linker.
768
+ if (linuxGlibcSpellingHitsDefaultFloor(target)) {
769
+ panicScriptcLinuxGlibcSpelling(b, target);
770
+ }
771
+ const service_carrier = resolveServiceCarrier(service_carrier_choice, has_services, b, target);
772
+
773
+ // Relational schema analysis runs the real SQLite parser in memory before
774
+ // the ordinary core checker. Its generated SDK/static surfaces carry the
775
+ // named Cmd.q/Sub.q members, while the Zig projection embeds the exact
776
+ // append-only migration chain the checker accepted.
777
+ var checked_sdk_core: std.Build.LazyPath = dep.path("packages/core/sdk/core.ts");
778
+ var checked_static_core: std.Build.LazyPath = dep.path("packages/core/compile-surface/core.ts");
779
+ var migrations_zig: std.Build.LazyPath = dep.path("src/app_runner/no_migrations.zig");
780
+ if (relational_capability) {
781
+ const sqlite_check = b.addSystemCommand(&.{node});
782
+ sqlite_check.addFileArg(dep.path("build/ts_run.mjs"));
783
+ sqlite_check.addFileArg(dep.path("packages/core/src/sqlite_cli.ts"));
784
+ sqlite_check.addArg("--src");
785
+ sqlite_check.addDirectoryArg(b.path(appPath(b, app_root, "src")));
786
+ sqlite_check.addArg("--sdk-in");
787
+ sqlite_check.addFileArg(dep.path("packages/core/sdk/core.ts"));
788
+ sqlite_check.addArg("--static-in");
789
+ sqlite_check.addFileArg(dep.path("packages/core/compile-surface/core.ts"));
790
+ sqlite_check.addArg("--sdk-out");
791
+ checked_sdk_core = sqlite_check.addOutputFileArg("core.ts");
792
+ sqlite_check.addArg("--static-out");
793
+ checked_static_core = sqlite_check.addOutputFileArg("core_static.ts");
794
+ sqlite_check.addArg("--zig-out");
795
+ migrations_zig = sqlite_check.addOutputFileArg("migrations.zig");
796
+ sqlite_check.addArg("--metadata-out");
797
+ _ = sqlite_check.addOutputFileArg("sqlite.meta.json");
798
+ sqlite_check.addArgs(&.{ "--state", b.pathFromRoot(appPath(b, app_root, "src/schema/migrations.lock.json")) });
799
+ if (appFileExists(b, app_root, "src/schema/migrations.lock.json")) {
800
+ sqlite_check.addFileInput(b.path(appPath(b, app_root, "src/schema/migrations.lock.json")));
801
+ }
802
+ sqlite_check.addFileInput(dep.path("packages/core/src/sqlite_codegen.ts"));
803
+ sqlite_check.addFileInput(dep.path("packages/core/src/sqlite_runtime_policy.ts"));
804
+ addAppSqlDirInputs(b, sqlite_check, appPath(b, app_root, "src"));
805
+ }
342
806
 
343
807
  // The frontend, in check-only mode: the subset checker and the
344
808
  // contract sidecar, no emission. Every check-time teaching gates the
@@ -363,11 +827,42 @@ fn tsCoreStage(b: *std.Build, dep: *std.Build.Dependency, app_root: []const u8,
363
827
  // The document's entry spelling is app-relative (the sidecar/facade
364
828
  // contract carries no machine paths).
365
829
  check.addArgs(&.{ "--contract-entry", "src/core.ts" });
830
+ const services_contract: ?std.Build.LazyPath = if (has_services) services_contract: {
831
+ check.addArg("--services-contract");
832
+ break :services_contract check.addOutputFileArg("services.contract.json");
833
+ } else null;
834
+ if (persist_capability) check.addArgs(&.{ "--capability", "persist" });
835
+ for (service_packages) |package_entry| {
836
+ check.addArgs(&.{
837
+ "--service-package",
838
+ b.fmt("{s}|{s}|{s}", .{ package_entry.name, package_entry.version, package_entry.content_hash }),
839
+ });
840
+ }
841
+ if (store_capability) check.addArgs(&.{ "--capability", "store" });
842
+ if (relational_capability) check.addArgs(&.{ "--capability", "sqlite" });
843
+ if (credentials_capability) check.addArgs(&.{ "--capability", "credentials" });
844
+ if (credentials_permission) check.addArgs(&.{ "--permission", "credentials" });
845
+ // Activate the cross-tier registry check even when discovery found no
846
+ // roots: the empty set must reject a core that declares a window.
847
+ check.addArg("--window-views");
848
+ for (window_views.views) |view| check.addArgs(&.{ "--window-view", view.label });
849
+ if (relational_capability) {
850
+ check.addArg("--sdk-core");
851
+ check.addFileArg(checked_sdk_core);
852
+ }
853
+ if (persist_version) |version| {
854
+ check.addArgs(&.{ "--persist-version", b.fmt("{d}", .{version}) });
855
+ check.addArgs(&.{ "--persist-state", appPath(b, app_root, ".native/cache/persist-schema.json") });
856
+ }
366
857
  addTsDirInputs(b, dep.builder, check, "packages/core/sdk");
367
858
  addAppTsDirInputs(b, check, appPath(b, app_root, "src"));
368
859
  for (frontend_sources) |source| {
369
860
  check.addFileInput(dep.path(b.fmt("packages/core/src/{s}", .{source})));
370
861
  }
862
+ // Service contracts echo the exact scriptc pin read from this manifest.
863
+ // Declare that runtime read explicitly so a compiler bump invalidates a
864
+ // warm build cache before the compile lane checks the echoed version.
865
+ if (has_services) check.addFileInput(dep.path("packages/core/package.json"));
371
866
 
372
867
  // corewire, compiled from the SDK dependency for the build host: one
373
868
  // invocation projects the generated compile entry and its profile,
@@ -381,6 +876,97 @@ fn tsCoreStage(b: *std.Build, dep: *std.Build.Dependency, app_root: []const u8,
381
876
  project.addArg("--profile");
382
877
  const profile = project.addOutputFileArg("core_profile.json");
383
878
 
879
+ // The fourth corewire projection is intentionally driven only by the
880
+ // service sidecar: the generated TypeScript dispatch loop and Zig
881
+ // name/index registry never rediscover facts from author source.
882
+ var service_registry: std.Build.LazyPath = dep.path("src/app_runner/no_services.zig");
883
+ var service_exe: ?std.Build.LazyPath = null;
884
+ var service_archive: ?std.Build.LazyPath = null;
885
+ var service_client: ?std.Build.LazyPath = null;
886
+ if (services_contract) |service_contract| {
887
+ const service_project = b.addRunArtifact(corewire_exe);
888
+ service_project.addArg("--services-sidecar");
889
+ service_project.addFileArg(service_contract);
890
+ service_project.addArg("--service-host-main");
891
+ const service_host_main = service_project.addOutputFileArg("service_host_main.ts");
892
+ service_project.addArg("--service-registry");
893
+ service_registry = service_project.addOutputFileArg("services.zig");
894
+ service_project.addArg("--service-client");
895
+ service_client = service_project.addOutputFileArg("services.gen.ts");
896
+ const service_inproc_main: ?std.Build.LazyPath = if (service_carrier == .in_process) inproc: {
897
+ service_project.addArg("--service-inproc-main");
898
+ break :inproc service_project.addOutputFileArg("service_inproc_main.ts");
899
+ } else null;
900
+ const service_inproc_profile: ?std.Build.LazyPath = if (service_carrier == .in_process) inproc: {
901
+ service_project.addArg("--service-inproc-profile");
902
+ break :inproc service_project.addOutputFileArg("service_profile.json");
903
+ } else null;
904
+
905
+ // Ordinary service TypeScript is staged without core-subset rewrites.
906
+ // The one service-boundary lowering turns NS1067's `{ kind, message }`
907
+ // throw into the tagged Error shape the pinned compiler can catch from an
908
+ // imported op; no deterministic profile fences participate here.
909
+ const service_stage_run = b.addSystemCommand(&.{node});
910
+ service_stage_run.addFileArg(dep.path("packages/core/scripts/stage_external_services.mjs"));
911
+ service_stage_run.addArg("--src");
912
+ service_stage_run.addDirectoryArg(b.path(appPath(b, app_root, "src")));
913
+ service_stage_run.addArg("--host-main");
914
+ service_stage_run.addFileArg(service_host_main);
915
+ if (service_inproc_main) |inproc_main| {
916
+ service_stage_run.addArg("--inproc-main");
917
+ service_stage_run.addFileArg(inproc_main);
918
+ }
919
+ if (service_inproc_profile) |inproc_profile| {
920
+ service_stage_run.addArg("--inproc-profile");
921
+ service_stage_run.addFileArg(inproc_profile);
922
+ }
923
+ service_stage_run.addArg("--contract");
924
+ service_stage_run.addFileArg(service_contract);
925
+ service_stage_run.addArg("--out");
926
+ const service_stage_dir = service_stage_run.addOutputDirectoryArg("services-stage");
927
+ // The staging script discovers nested service modules recursively;
928
+ // a directory LazyPath alone does not hash those discovered files.
929
+ service_stage_run.has_side_effects = true;
930
+
931
+ const service_compile = b.addSystemCommand(&.{node});
932
+ service_compile.addFileArg(dep.path("packages/core/scripts/run_external_service_compiler.mjs"));
933
+ service_compile.addArg("--stage");
934
+ service_compile.addDirectoryArg(service_stage_dir);
935
+ service_compile.addArg("--manifest");
936
+ service_compile.addFileArg(dep.path("packages/core/package.json"));
937
+ service_compile.addArg("--contract");
938
+ service_compile.addFileArg(service_contract);
939
+ if (service_carrier == .in_process) {
940
+ // The in-process carrier links the service class into the app
941
+ // binary; no sibling executable is built or packaged.
942
+ service_compile.addArg("--out-archive");
943
+ service_archive = service_compile.addOutputFileArg(b.fmt("lib{s}_services.a", .{externalCoreSymbolName(b, app_name)}));
944
+ } else {
945
+ service_compile.addArg("--out-exe");
946
+ const service_suffix = if (target.result.os.tag == .windows) ".exe" else "";
947
+ service_exe = service_compile.addOutputFileArg(b.fmt("{s}_services{s}", .{ app_name, service_suffix }));
948
+ }
949
+ service_compile.addArgs(&.{
950
+ "--host-platform",
951
+ b.fmt("{t}-{t}-{t}", .{ b.graph.host.result.cpu.arch, b.graph.host.result.os.tag, b.graph.host.result.abi }),
952
+ "--target-platform",
953
+ scriptcPlatformTriple(b, target),
954
+ // Cross service compiles run the pinned compiler's zig-cc
955
+ // lane; hand over this build's own zig so the lane never
956
+ // depends on a PATH zig (native compiles ignore it).
957
+ "--zig-exe",
958
+ b.graph.zig_exe,
959
+ });
960
+ addScriptcAndroidNdk(b, service_compile, target);
961
+ if (b.graph.environ_map.get("NATIVE_SDK_CORE_COMPILER")) |override| {
962
+ service_compile.addArgs(&.{ "--compiler", override });
963
+ } else {
964
+ const compiler_js = requireTsExternalCompilerJs(b, dep);
965
+ service_compile.addArg("--compiler-js");
966
+ service_compile.addFileArg(.{ .cwd_relative = compiler_js });
967
+ }
968
+ }
969
+
384
970
  // The compile stage: author sources + staged SDK + static surface +
385
971
  // generated entry/profile, one scratch tree.
386
972
  const stage_run = b.addSystemCommand(&.{node});
@@ -390,11 +976,15 @@ fn tsCoreStage(b: *std.Build, dep: *std.Build.Dependency, app_root: []const u8,
390
976
  stage_run.addArg("--sdk");
391
977
  stage_run.addDirectoryArg(dep.path("packages/core/sdk"));
392
978
  stage_run.addArg("--static");
393
- stage_run.addFileArg(dep.path("packages/core/compile-surface/core.ts"));
979
+ stage_run.addFileArg(checked_static_core);
394
980
  stage_run.addArg("--facade");
395
981
  stage_run.addFileArg(facade);
396
982
  stage_run.addArg("--profile");
397
983
  stage_run.addFileArg(profile);
984
+ if (service_client) |client| {
985
+ stage_run.addArg("--services-client");
986
+ stage_run.addFileArg(client);
987
+ }
398
988
  stage_run.addArg("--out");
399
989
  const stage_dir = stage_run.addOutputDirectoryArg("stage");
400
990
 
@@ -408,31 +998,29 @@ fn tsCoreStage(b: *std.Build, dep: *std.Build.Dependency, app_root: []const u8,
408
998
  compile.addArgs(&.{ "--name", symbol_name });
409
999
  compile.addArg("--manifest");
410
1000
  compile.addFileArg(dep.path("packages/core/package.json"));
1001
+ compile.addArg("--frontend-sidecar");
1002
+ compile.addFileArg(contract);
411
1003
  compile.addArg("--out-archive");
412
1004
  const archive = compile.addOutputFileArg(b.fmt("lib{s}.a", .{symbol_name}));
413
1005
  compile.addArg("--out-sidecar");
414
1006
  const compiled_sidecar = compile.addOutputFileArg("core.contract.json");
1007
+ compile.addArgs(&.{
1008
+ "--host-platform",
1009
+ b.fmt("{t}-{t}-{t}", .{ b.graph.host.result.cpu.arch, b.graph.host.result.os.tag, b.graph.host.result.abi }),
1010
+ "--target-platform",
1011
+ scriptcPlatformTriple(b, target),
1012
+ // Keep the core and service archives on the same cross compiler and
1013
+ // target. Native compiles ignore the supplied Zig path.
1014
+ "--zig-exe",
1015
+ b.graph.zig_exe,
1016
+ });
1017
+ addScriptcAndroidNdk(b, compile, target);
415
1018
  if (b.graph.environ_map.get("NATIVE_SDK_CORE_COMPILER")) |override| {
416
1019
  // The development override: point at any toolchain command; the
417
1020
  // driver still refuses a release other than the SDK's pin.
418
1021
  compile.addArgs(&.{ "--compiler", override });
419
1022
  } else {
420
- const compiler_js = tsExternalCompilerJs(b, dep) orelse {
421
- const sdk_root = tsSdkRoot(dep.builder.allocator, dep.builder.graph.io, dep);
422
- std.debug.print(
423
- \\
424
- \\error: the external core compiler is not installed (TypeScript cores compile
425
- \\through it). It ships as an exact-pinned dependency of the SDK's packages/core
426
- \\— install it once with:
427
- \\ cd {s}/packages/core && npm ci
428
- \\(or point NATIVE_SDK_CORE_COMPILER at the pinned release's command; an
429
- \\npm-installed @native-sdk/cli carries the compiler automatically — if it is
430
- \\missing there, the install is broken: reinstall @native-sdk/cli).
431
- \\
432
- \\
433
- , .{sdk_root});
434
- std.process.exit(1);
435
- };
1023
+ const compiler_js = requireTsExternalCompilerJs(b, dep);
436
1024
  compile.addArg("--compiler-js");
437
1025
  compile.addFileArg(.{ .cwd_relative = compiler_js });
438
1026
  }
@@ -450,9 +1038,67 @@ fn tsCoreStage(b: *std.Build, dep: *std.Build.Dependency, app_root: []const u8,
450
1038
  _ = staged.addCopyFile(shim, "core.zig");
451
1039
  _ = staged.addCopyFile(dep.path("tools/corewire/shim_rt.zig"), "shim_rt.zig");
452
1040
  _ = staged.addCopyFile(dep.path("tools/corewire/core_abi.zig"), "core_abi.zig");
1041
+ _ = staged.addCopyFile(service_registry, "services.zig");
1042
+ // The carrier selection, as one staged constant module: the generated
1043
+ // wiring comptime-switches its service transport on it.
1044
+ _ = staged.add("service_carrier.zig", b.fmt(
1045
+ \\//! Generated by the app build: the resolved service-carrier selection.
1046
+ \\pub const Kind = enum {{ none, child, in_process }};
1047
+ \\pub const kind: Kind = .{t};
1048
+ \\/// Pool width for the in-process carrier; null resolves the
1049
+ \\/// runtime default (min(4, cores)).
1050
+ \\pub const pool_workers: ?usize = {?d};
1051
+ \\
1052
+ , .{ service_carrier, service_pool_workers }));
1053
+ _ = staged.addCopyFile(migrations_zig, "migrations.zig");
453
1054
  _ = staged.addCopyFile(b.path(appPath(b, app_root, "src/app.native")), "app.native");
1055
+ for (window_views.sources) |source| {
1056
+ _ = staged.addCopyFile(b.path(appPath(b, app_root, source.source_path)), source.staged_path);
1057
+ }
1058
+ _ = staged.add("window_views.zig", tsWindowRegistrySource(b, window_views));
454
1059
  const main_root = staged.addCopyFile(dep.path("src/app_runner/ts_core_main.zig"), "main.zig");
455
- return .{ .main_root = main_root, .archive = archive };
1060
+ // The mobile wiring stages beside the desktop entry: same mirror, same
1061
+ // registry, same carrier constant — only the shell differs (the embed
1062
+ // host's AppDef contract instead of a process `main`).
1063
+ const mobile_root = staged.addCopyFile(dep.path("src/app_runner/ts_core_mobile.zig"), "mobile.zig");
1064
+ return .{
1065
+ .main_root = main_root,
1066
+ .mobile_root = mobile_root,
1067
+ .archive = archive,
1068
+ .service_exe = service_exe,
1069
+ .service_archive = service_archive,
1070
+ .migrations = migrations_zig,
1071
+ };
1072
+ }
1073
+
1074
+ fn sqliteMigrationsStage(b: *std.Build, dep: *std.Build.Dependency, app_root: []const u8) std.Build.LazyPath {
1075
+ const node = tsToolingPreflight(b, dep, .sqlite_schema);
1076
+ const generate = b.addSystemCommand(&.{node});
1077
+ generate.addFileArg(dep.path("build/ts_run.mjs"));
1078
+ generate.addFileArg(dep.path("packages/core/src/sqlite_cli.ts"));
1079
+ generate.addArg("--src");
1080
+ generate.addDirectoryArg(b.path(appPath(b, app_root, "src")));
1081
+ generate.addArg("--zig-out");
1082
+ const migrations = generate.addOutputFileArg("migrations.zig");
1083
+ generate.addArgs(&.{ "--state", b.pathFromRoot(appPath(b, app_root, "src/schema/migrations.lock.json")) });
1084
+ if (appFileExists(b, app_root, "src/schema/migrations.lock.json")) {
1085
+ generate.addFileInput(b.path(appPath(b, app_root, "src/schema/migrations.lock.json")));
1086
+ }
1087
+ generate.addFileInput(dep.path("packages/core/src/sqlite_codegen.ts"));
1088
+ generate.addFileInput(dep.path("packages/core/src/sqlite_runtime_policy.ts"));
1089
+ addAppSqlDirInputs(b, generate, appPath(b, app_root, "src"));
1090
+ return migrations;
1091
+ }
1092
+
1093
+ fn addAppSqlDirInputs(b: *std.Build, run: *std.Build.Step.Run, src_path: []const u8) void {
1094
+ var dir = b.build_root.handle.openDir(b.graph.io, src_path, .{ .iterate = true }) catch return;
1095
+ defer dir.close(b.graph.io);
1096
+ var walker = dir.walk(b.allocator) catch return;
1097
+ defer walker.deinit();
1098
+ while (walker.next(b.graph.io) catch null) |entry| {
1099
+ if (entry.kind != .file or !std.mem.endsWith(u8, entry.basename, ".sql")) continue;
1100
+ run.addFileInput(b.path(b.fmt("{s}/{s}", .{ src_path, entry.path })));
1101
+ }
456
1102
  }
457
1103
 
458
1104
  /// corewire (the contract-sidecar shim generator), compiled from the SDK
@@ -510,10 +1156,24 @@ fn addAppTsDirInputs(b: *std.Build, transpile: *std.Build.Step.Run, src_path: []
510
1156
  }
511
1157
  }
512
1158
 
1159
+ fn appHasServiceFiles(b: *std.Build, app_root: []const u8) bool {
1160
+ const services_path = appPath(b, app_root, "src/services");
1161
+ var dir = b.build_root.handle.openDir(b.graph.io, services_path, .{ .iterate = true }) catch return false;
1162
+ defer dir.close(b.graph.io);
1163
+ var walker = dir.walk(b.allocator) catch return false;
1164
+ defer walker.deinit();
1165
+ while (walker.next(b.graph.io) catch null) |entry| {
1166
+ if (entry.kind == .file and std.mem.endsWith(u8, entry.basename, ".ts") and
1167
+ !std.mem.endsWith(u8, entry.basename, ".d.ts")) return true;
1168
+ }
1169
+ return false;
1170
+ }
1171
+
513
1172
  /// The `native_sdk_app_*` C ABI every embed static library exports.
514
1173
  pub const mobile_export_symbol_names = [_][]const u8{
515
1174
  "native_sdk_app_create",
516
1175
  "native_sdk_app_destroy",
1176
+ "native_sdk_app_destroy_with_status",
517
1177
  "native_sdk_app_start",
518
1178
  "native_sdk_app_activate",
519
1179
  "native_sdk_app_deactivate",
@@ -525,9 +1185,11 @@ pub const mobile_export_symbol_names = [_][]const u8{
525
1185
  "native_sdk_app_text_input_state",
526
1186
  "native_sdk_app_set_text_measure",
527
1187
  "native_sdk_app_set_audio_service",
1188
+ "native_sdk_app_set_credential_service",
528
1189
  "native_sdk_app_audio_event",
529
1190
  "native_sdk_app_set_image_service",
530
1191
  "native_sdk_app_set_automation_dir",
1192
+ "native_sdk_app_set_data_root",
531
1193
  "native_sdk_app_touch",
532
1194
  "native_sdk_app_scroll",
533
1195
  "native_sdk_app_key",
@@ -575,6 +1237,43 @@ pub const MobileLibOptions = struct {
575
1237
  /// `src/embed/ui_host.zig`. Ignored for `.scene = .webview`.
576
1238
  main: []const u8 = "src/main.zig",
577
1239
  scene: MobileSceneOption = .canvas,
1240
+ /// Link and install the engine-owned Tier-2 record store. Standard
1241
+ /// `addApp` builds infer this from app.zon; direct `addMobileLib`
1242
+ /// callers state it here because that lower-level API has no manifest.
1243
+ store_capability: bool = false,
1244
+ /// Link and install the engine-owned Tier-3 relational database.
1245
+ relational_capability: bool = false,
1246
+ /// Generated append-only migration module. Direct low-level callers may
1247
+ /// omit it and open an empty version-0 database.
1248
+ relational_migrations: ?std.Build.LazyPath = null,
1249
+ /// Compile the Tier-4 core credential effects into the mobile host.
1250
+ credentials_capability: bool = false,
1251
+ /// Grant those effects access to the registered OS credential service.
1252
+ credentials_permission: bool = false,
1253
+ /// Grant raw file effects access outside the OS-owned app data root.
1254
+ filesystem_permission: bool = false,
1255
+ /// Stable app identity used as the Keychain/Keystore service namespace.
1256
+ credentials_service: []const u8 = "dev.native_sdk.app",
1257
+ /// A TypeScript core's staged mobile wiring: set by `addAppArtifacts`
1258
+ /// when the tree carries src/core.ts. The `app` module roots at the
1259
+ /// staged mobile entry instead of `main`, and the compiled core (and
1260
+ /// in-process service) archives merge into the embed static library —
1261
+ /// the host tiers keep linking exactly one archive.
1262
+ ts_core: ?MobileTsCore = null,
1263
+ };
1264
+
1265
+ /// The TypeScript pieces a mobile embed library consumes (see
1266
+ /// `MobileLibOptions.ts_core`).
1267
+ pub const MobileTsCore = struct {
1268
+ /// The staged mobile wiring (mobile.zig beside the generated mirror).
1269
+ main_root: std.Build.LazyPath,
1270
+ /// The compiled-core archive; merged into the embed library.
1271
+ archive: std.Build.LazyPath,
1272
+ /// The in-process service archive, when src/services exists.
1273
+ service_archive: ?std.Build.LazyPath,
1274
+ /// The app.zon module the mobile wiring reads scene chrome, identity,
1275
+ /// and theme from (`app_manifest_zon`).
1276
+ manifest_mod: *std.Build.Module,
578
1277
  };
579
1278
 
580
1279
  /// Mobile counterpart of `addApp`: produce the embed static library
@@ -612,10 +1311,53 @@ fn addMobileLibWithTarget(b: *std.Build, dep: *std.Build.Dependency, target: std
612
1311
  });
613
1312
  exports_mod.addImport("native_sdk", native_sdk_mod);
614
1313
  if (options.scene == .canvas) {
615
- const app_mod = localModule(b, target, optimize, options.main);
1314
+ const mobile_options = b.addOptions();
1315
+ mobile_options.addOption(bool, "store_capability", options.store_capability);
1316
+ mobile_options.addOption(bool, "relational_capability", options.relational_capability);
1317
+ mobile_options.addOption(bool, "credentials_capability", options.credentials_capability);
1318
+ mobile_options.addOption(bool, "credentials_permission", options.credentials_permission);
1319
+ mobile_options.addOption(bool, "filesystem_permission", options.filesystem_permission);
1320
+ mobile_options.addOption([]const u8, "credentials_service", options.credentials_service);
1321
+ exports_mod.addImport("mobile_build_options", mobile_options.createModule());
1322
+ const migration_path = options.relational_migrations orelse dep.path("src/app_runner/no_migrations.zig");
1323
+ const migration_mod = b.createModule(.{ .root_source_file = migration_path, .target = target, .optimize = optimize });
1324
+ migration_mod.addImport("native_sdk", native_sdk_mod);
1325
+ exports_mod.addImport("relational_migrations", migration_mod);
1326
+ // A TypeScript core's app module roots at the staged mobile wiring;
1327
+ // a Zig core's at the app's own mobile entry. Either way the embed
1328
+ // host sees the same AppDef contract (Model/Msg/initModel/
1329
+ // mobileOptions).
1330
+ const app_mod = if (options.ts_core) |ts| ts_app: {
1331
+ const mod = b.createModule(.{
1332
+ .root_source_file = ts.main_root,
1333
+ .target = target,
1334
+ .optimize = optimize,
1335
+ });
1336
+ mod.addImport("app_manifest_zon", ts.manifest_mod);
1337
+ break :ts_app mod;
1338
+ } else localModule(b, target, optimize, options.main);
616
1339
  app_mod.addImport("native_sdk", native_sdk_mod);
617
1340
  exports_mod.addImport("app", app_mod);
618
1341
  }
1342
+ if (options.ts_core) |ts| {
1343
+ // The compiled TypeScript archives merge into the embed static
1344
+ // library (Zig's static-lib emission bundles archive inputs), so
1345
+ // the iOS/Android host tiers keep linking the one archive they
1346
+ // already stage. The toolchain's runtime needs libc; the host
1347
+ // link supplies it (plus -lm/-ldl on Android, which the Android
1348
+ // host link already passes).
1349
+ exports_mod.link_libc = true;
1350
+ exports_mod.addObjectFile(ts.archive);
1351
+ if (ts.service_archive) |service_archive| exports_mod.addObjectFile(service_archive);
1352
+ }
1353
+ if (options.store_capability or options.relational_capability) {
1354
+ exports_mod.addIncludePath(dep.path("third_party/sqlite"));
1355
+ exports_mod.addCSourceFile(.{
1356
+ .file = dep.path("third_party/sqlite/sqlite3.c"),
1357
+ .flags = sqliteCFlags(b, target),
1358
+ });
1359
+ exports_mod.link_libc = true;
1360
+ }
619
1361
  exports_mod.export_symbol_names = &mobile_export_symbol_names;
620
1362
 
621
1363
  const lib = b.addLibrary(.{
@@ -630,10 +1372,39 @@ fn addMobileLibWithTarget(b: *std.Build, dep: *std.Build.Dependency, target: std
630
1372
  // Intel simulators). Force LLVM there; Release already uses it.
631
1373
  .use_llvm = useLlvmWorkaround(target),
632
1374
  });
633
- b.installArtifact(lib);
634
1375
 
635
1376
  const lib_step = b.step("lib", "Build the mobile embed static library");
636
- lib_step.dependOn(&b.addInstallArtifact(lib, .{}).step);
1377
+ if (options.ts_core != null and target.result.abi.isAndroid()) {
1378
+ // Zig's ELF static-library emission stores the compiled TypeScript
1379
+ // archives as nested members instead of merging their objects (the
1380
+ // Mach-O emission merges), and the NDK's -shared host link would
1381
+ // skip those blobs with only a warning. Flatten to one plain
1382
+ // object archive so the Android host tier keeps linking exactly
1383
+ // the archive it already stages.
1384
+ const merged = mergeMobileArchive(b, dep, lib, options.name);
1385
+ const lib_name = b.fmt("lib{s}.a", .{options.name});
1386
+ b.getInstallStep().dependOn(&b.addInstallFileWithDir(merged, .lib, lib_name).step);
1387
+ lib_step.dependOn(&b.addInstallFileWithDir(merged, .lib, lib_name).step);
1388
+ } else {
1389
+ b.installArtifact(lib);
1390
+ lib_step.dependOn(&b.addInstallArtifact(lib, .{}).step);
1391
+ }
1392
+ }
1393
+
1394
+ /// Flatten an Android embed library whose members include the compiled
1395
+ /// TypeScript archives (see the call site above). Runs under node like the
1396
+ /// rest of the TypeScript lane's drivers.
1397
+ fn mergeMobileArchive(b: *std.Build, dep: *std.Build.Dependency, lib: *std.Build.Step.Compile, name: []const u8) std.Build.LazyPath {
1398
+ const node = b.findProgram(&.{"node"}, &.{}) catch
1399
+ @panic("\nmerging the mobile TypeScript archives needs node on PATH (the TypeScript core lane already requires it).\n");
1400
+ const merge = b.addSystemCommand(&.{node});
1401
+ merge.addFileArg(dep.path("packages/core/scripts/merge_static_archives.mjs"));
1402
+ merge.addArgs(&.{ "--zig", b.graph.zig_exe, "--format", "gnu" });
1403
+ merge.addArg("--out");
1404
+ const merged = merge.addOutputFileArg(b.fmt("lib{s}.a", .{name}));
1405
+ merge.addArg("--in");
1406
+ merge.addFileArg(lib.getEmittedBin());
1407
+ return merged;
637
1408
  }
638
1409
 
639
1410
  /// The pieces `addApp` wires, for callers that extend the standard app
@@ -684,28 +1455,72 @@ pub fn addAppArtifacts(b: *std.Build, dep: *std.Build.Dependency, app_options: A
684
1455
  " a Zig core.\nDrop the flag or port the core to TypeScript.\n");
685
1456
  }
686
1457
  }
687
- // Mobile targets are taught BEFORE lane selection: TypeScript cores
688
- // are desktop-only until the external core toolchain grows mobile
689
- // targets; Zig/markup cores stay fully supported on mobile.
690
- if (core_tree == .ts and (target.result.os.tag == .ios or target.result.abi.isAndroid())) {
691
- @panic("\nTypeScript app cores are desktop-only today: the external core compiler does not" ++
692
- " target mobile yet.\nBuild for a desktop target, or port the core to a Zig" ++
693
- " `mobileOptions` app — Zig and markup cores are fully supported on mobile.\n");
694
- }
1458
+ // The service-carrier selection: `-Dservice-carrier` overrides app.zon's
1459
+ // `.service_carrier`; both default to auto (the child carrier).
1460
+ const service_carrier_choice: ServiceCarrierOption = choice: {
1461
+ if (b.option([]const u8, "service-carrier", "How src/services operations run: auto (default), in_process, child")) |flag| {
1462
+ break :choice parseServiceCarrierOption(flag);
1463
+ }
1464
+ break :choice parseServiceCarrierOption(app_config.service_carrier);
1465
+ };
1466
+ const service_pool_workers: ?u8 = workers: {
1467
+ const configured = b.option(u8, "service-pool-size", "In-process service carrier worker threads (1-16; default min(4, cores))") orelse
1468
+ app_config.service_pool_size;
1469
+ if (configured) |count| {
1470
+ if (count < 1 or count > 16) @panic("\nservice pool size must be between 1 and 16\n");
1471
+ }
1472
+ break :workers configured;
1473
+ };
695
1474
  const ts_stage: ?TsCoreStage = if (core_tree == .ts)
696
- tsCoreStage(b, dep, app_options.app_root, app_options.name)
1475
+ tsCoreStage(
1476
+ b,
1477
+ dep,
1478
+ target,
1479
+ app_options.app_root,
1480
+ app_options.name,
1481
+ app_config.persist_capability,
1482
+ app_config.store_capability,
1483
+ app_config.relational_capability,
1484
+ app_config.credentials_capability,
1485
+ app_config.credentials_permission,
1486
+ app_config.persist_version,
1487
+ app_config.service_packages,
1488
+ service_carrier_choice,
1489
+ service_pool_workers,
1490
+ )
697
1491
  else
698
1492
  null;
1493
+ const relational_migrations = if (ts_stage) |stage|
1494
+ stage.migrations
1495
+ else if (app_config.relational_capability)
1496
+ sqliteMigrationsStage(b, dep, app_options.app_root)
1497
+ else
1498
+ dep.path("src/app_runner/no_migrations.zig");
699
1499
 
700
1500
  // Mobile targets get the embed static library as a `lib` step: the
701
1501
  // artifact the toolkit-owned iOS host (and any hand-written shim)
702
1502
  // links, so `native dev|package --target ios` works against every
703
1503
  // standard app build — generated graph or ejected — with nothing but
704
- // `-Dtarget`. Desktop targets keep the step absent.
1504
+ // `-Dtarget`. Desktop targets keep the step absent. A TypeScript core
1505
+ // roots the library's app module at the staged mobile wiring and
1506
+ // merges the compiled archives into it.
705
1507
  if (target.result.os.tag == .ios or target.result.abi.isAndroid()) {
706
1508
  addMobileLibWithTarget(b, dep, target, optimize, .{
707
1509
  .name = app_options.name,
708
1510
  .main = appPath(b, app_options.app_root, app_options.main),
1511
+ .store_capability = app_config.store_capability,
1512
+ .relational_capability = app_config.relational_capability,
1513
+ .relational_migrations = relational_migrations,
1514
+ .credentials_capability = app_config.credentials_capability,
1515
+ .credentials_permission = app_config.credentials_permission,
1516
+ .filesystem_permission = app_config.filesystem_permission,
1517
+ .credentials_service = app_config.app_id,
1518
+ .ts_core = if (ts_stage) |stage| .{
1519
+ .main_root = stage.mobile_root,
1520
+ .archive = stage.archive,
1521
+ .service_archive = stage.service_archive,
1522
+ .manifest_mod = b.createModule(.{ .root_source_file = b.path(appPath(b, app_options.app_root, "app.zon")) }),
1523
+ } else null,
709
1524
  });
710
1525
  }
711
1526
  const platform_option = b.option(PlatformOption, "platform", "Desktop backend: auto, null, macos, linux, windows") orelse .auto;
@@ -754,7 +1569,7 @@ pub fn addAppArtifacts(b: *std.Build, dep: *std.Build.Dependency, app_options: A
754
1569
  options.addOption(bool, "web_layer", web_layer);
755
1570
  const options_mod = options.createModule();
756
1571
 
757
- const app_mod = appModule(b, dep, target, app_optimize, app_options, options_mod, ts_stage, app_config);
1572
+ const app_mod = appModule(b, dep, target, app_optimize, app_options, options_mod, ts_stage, relational_migrations, app_config);
758
1573
  const exe = b.addExecutable(.{
759
1574
  .name = app_options.name,
760
1575
  .root_module = app_mod,
@@ -787,13 +1602,29 @@ pub fn addAppArtifacts(b: *std.Build, dep: *std.Build.Dependency, app_options: A
787
1602
  const install = b.addInstallArtifact(exe, .{});
788
1603
  b.getInstallStep().dependOn(&install.step);
789
1604
 
790
- const run = b.addRunArtifact(exe);
1605
+ const service_install: ?*std.Build.Step.InstallFile = if (ts_stage) |stage| if (stage.service_exe) |service_exe| service_install: {
1606
+ const suffix = if (target.result.os.tag == .windows) ".exe" else "";
1607
+ const value = b.addInstallFileWithDir(service_exe, .bin, b.fmt("{s}_services{s}", .{ app_options.name, suffix }));
1608
+ b.getInstallStep().dependOn(&value.step);
1609
+ break :service_install value;
1610
+ } else null else null;
1611
+
1612
+ // A service-bearing app runs from the installed layout so the host is
1613
+ // a real sibling exactly as it is in a package. Service-free apps keep
1614
+ // the direct cached-artifact fast path.
1615
+ const run = if (service_install != null) run: {
1616
+ const suffix = if (target.result.os.tag == .windows) ".exe" else "";
1617
+ const value = b.addSystemCommand(&.{b.getInstallPath(.bin, b.fmt("{s}{s}", .{ app_options.name, suffix }))});
1618
+ value.step.dependOn(&install.step);
1619
+ value.step.dependOn(&service_install.?.step);
1620
+ break :run value;
1621
+ } else b.addRunArtifact(exe);
791
1622
  addCefRuntimeRunFiles(b, target, run, exe, web_engine, cef_dir);
792
1623
  addWebView2RuntimeRunFiles(dep, target, run, web_engine, web_layer);
793
1624
  const run_step = b.step("run", "Run the app");
794
1625
  run_step.dependOn(&run.step);
795
1626
 
796
- const test_app_mod = if (app_optimize == optimize) app_mod else appModule(b, dep, target, optimize, app_options, options_mod, ts_stage, app_config);
1627
+ const test_app_mod = if (app_optimize == optimize) app_mod else appModule(b, dep, target, optimize, app_options, options_mod, ts_stage, relational_migrations, app_config);
797
1628
  const tests = b.addTest(.{ .root_module = test_app_mod, .use_llvm = useLlvmWorkaround(target) });
798
1629
  const test_step = b.step("test", "Run tests");
799
1630
  test_step.dependOn(&b.addRunArtifact(tests).step);
@@ -896,6 +1727,10 @@ pub fn addAppArtifacts(b: *std.Build, dep: *std.Build.Dependency, app_options: A
896
1727
  b.fmt("zig-out/package/{s}", .{package_target_name}));
897
1728
  package_run.addArg("--binary");
898
1729
  package_run.addFileArg(exe.getEmittedBin());
1730
+ if (ts_stage) |stage| if (stage.service_exe) |service_exe| {
1731
+ package_run.addArg("--service-binary");
1732
+ package_run.addFileArg(service_exe);
1733
+ };
899
1734
  // The archive and report names carry an optimize label; this
900
1735
  // build graph knows the packaged binary's REAL mode, so forward
901
1736
  // it instead of letting the CLI assume one.
@@ -962,7 +1797,7 @@ fn exampleOptimizeMode(b: *std.Build, requested: ?std.builtin.OptimizeMode, defa
962
1797
  };
963
1798
  }
964
1799
 
965
- 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, app_config: AppManifestBuildConfig) *std.Build.Module {
1800
+ 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, relational_migrations: std.Build.LazyPath, app_config: AppManifestBuildConfig) *std.Build.Module {
966
1801
  const native_sdk_mod = nativeSdkModuleWithTerminal(b, dep, target, optimize, app_options.terminal_sessions);
967
1802
  const runner_mod = b.createModule(.{
968
1803
  .root_source_file = dep.path("src/app_runner/root.zig"),
@@ -973,6 +1808,9 @@ fn appModule(b: *std.Build, dep: *std.Build.Dependency, target: std.Build.Resolv
973
1808
  runner_mod.addImport("native_sdk", native_sdk_mod);
974
1809
  runner_mod.addImport("build_options", options_mod);
975
1810
  runner_mod.addImport("app_manifest_zon", manifest_mod);
1811
+ const migration_mod = b.createModule(.{ .root_source_file = relational_migrations, .target = target, .optimize = optimize });
1812
+ migration_mod.addImport("native_sdk", native_sdk_mod);
1813
+ runner_mod.addImport("relational_migrations", migration_mod);
976
1814
 
977
1815
  const app_mod = if (ts_stage) |stage|
978
1816
  // TypeScript core: the app module roots at the staged generated
@@ -996,6 +1834,21 @@ fn appModule(b: *std.Build, dep: *std.Build.Dependency, target: std.Build.Resolv
996
1834
  // toolchain's runtime needs libc.
997
1835
  app_mod.link_libc = true;
998
1836
  app_mod.addObjectFile(stage.archive);
1837
+ // The in-process service archive links beside it (distinct symbol
1838
+ // prefix; its runtime internals are localized).
1839
+ if (stage.service_archive) |service_archive| app_mod.addObjectFile(service_archive);
1840
+ }
1841
+ if (app_config.sqlite_capability) {
1842
+ // `store` and the relational `sqlite` tier share this exact object.
1843
+ // The source is absent from every artifact declaring neither
1844
+ // capability, which keeps capability inference a real binary-size
1845
+ // boundary rather than a runtime flag.
1846
+ app_mod.addIncludePath(dep.path("third_party/sqlite"));
1847
+ app_mod.addCSourceFile(.{
1848
+ .file = dep.path("third_party/sqlite/sqlite3.c"),
1849
+ .flags = &sqlite_c_defines,
1850
+ });
1851
+ app_mod.link_libc = true;
999
1852
  }
1000
1853
  addMacosPrivacyInfoPlist(b, app_mod, target, app_config);
1001
1854
  return app_mod;
@@ -1043,6 +1896,206 @@ fn nativeSdkTarget(b: *std.Build) std.Build.ResolvedTarget {
1043
1896
  return b.resolveTargetQuery(query);
1044
1897
  }
1045
1898
 
1899
+ const sqlite_c_defines = [_][]const u8{
1900
+ "-DSQLITE_THREADSAFE=2",
1901
+ "-DSQLITE_OMIT_LOAD_EXTENSION",
1902
+ "-DSQLITE_DQS=0",
1903
+ "-DSQLITE_ENABLE_FTS5",
1904
+ "-DSQLITE_ENABLE_JSON1",
1905
+ "-DSQLITE_ENABLE_UPDATE_HOOK",
1906
+ "-DSQLITE_DEFAULT_WAL_SYNCHRONOUS=1",
1907
+ "-DSQLITE_DEFAULT_MEMSTATUS=0",
1908
+ };
1909
+
1910
+ /// Zig deliberately supplies no libc headers for Apple/Android cross targets.
1911
+ /// Store-capable mobile libraries therefore compile the vendored amalgamation
1912
+ /// against the same platform SDK the host tier will use to link the archive.
1913
+ /// Desktop targets keep Zig's ordinary libc discovery. Pub because the SDK's
1914
+ /// own build graph compiles the same amalgamation into modules that also
1915
+ /// configure under a mobile -Dtarget (the mobile e2e battery).
1916
+ pub fn sqliteCFlags(b: *std.Build, target: std.Build.ResolvedTarget) []const []const u8 {
1917
+ if (target.result.os.tag == .ios) {
1918
+ const sysroot = b.sysroot orelse iosSdkPath(b, target.result.abi == .simulator) orelse
1919
+ std.debug.panic("a store-capable iOS library needs the Apple SDK; install Xcode or pass --sysroot <iphone SDK path>", .{});
1920
+ return b.dupeStrings(&.{
1921
+ sqlite_c_defines[0],
1922
+ sqlite_c_defines[1],
1923
+ sqlite_c_defines[2],
1924
+ sqlite_c_defines[3],
1925
+ sqlite_c_defines[4],
1926
+ sqlite_c_defines[5],
1927
+ sqlite_c_defines[6],
1928
+ sqlite_c_defines[7],
1929
+ "-isysroot",
1930
+ sysroot,
1931
+ b.fmt("-isystem{s}/usr/include", .{sysroot}),
1932
+ });
1933
+ }
1934
+ if (target.result.abi.isAndroid()) {
1935
+ const sysroot = b.sysroot orelse androidNdkSysrootPath(b) orelse
1936
+ std.debug.panic("a store-capable Android library needs the NDK; set ANDROID_NDK_ROOT or ANDROID_HOME, or pass --sysroot <NDK sysroot>", .{});
1937
+ const triple = target.result.linuxTriple(b.allocator) catch @panic("out of memory");
1938
+ return b.dupeStrings(&.{
1939
+ sqlite_c_defines[0],
1940
+ sqlite_c_defines[1],
1941
+ sqlite_c_defines[2],
1942
+ sqlite_c_defines[3],
1943
+ sqlite_c_defines[4],
1944
+ sqlite_c_defines[5],
1945
+ sqlite_c_defines[6],
1946
+ sqlite_c_defines[7],
1947
+ b.fmt("-isystem{s}/usr/include/{s}", .{ sysroot, triple }),
1948
+ b.fmt("-isystem{s}/usr/include", .{sysroot}),
1949
+ });
1950
+ }
1951
+ return &sqlite_c_defines;
1952
+ }
1953
+
1954
+ fn iosSdkPath(b: *std.Build, simulator: bool) ?[]const u8 {
1955
+ const result = std.process.run(b.allocator, b.graph.io, .{
1956
+ .argv = &.{ "xcrun", "--sdk", if (simulator) "iphonesimulator" else "iphoneos", "--show-sdk-path" },
1957
+ .stdout_limit = .limited(4096),
1958
+ .stderr_limit = .limited(4096),
1959
+ }) catch return null;
1960
+ defer b.allocator.free(result.stderr);
1961
+ if (result.term != .exited or result.term.exited != 0) {
1962
+ b.allocator.free(result.stdout);
1963
+ return null;
1964
+ }
1965
+ return std.mem.trimEnd(u8, result.stdout, "\r\n");
1966
+ }
1967
+
1968
+ /// Thread the Android NDK location into a ScriptC driver invocation the
1969
+ /// way `--zig-exe` threads this build's zig: resolved here, at the one
1970
+ /// boundary that already knows how to discover it, so the compiler's own
1971
+ /// discovery never depends on the ambient environment. A missing NDK stays
1972
+ /// quiet — the driver and compiler own the teaching when an Android
1973
+ /// compile actually needs one.
1974
+ pub fn addScriptcAndroidNdk(b: *std.Build, run: *std.Build.Step.Run, target: std.Build.ResolvedTarget) void {
1975
+ if (!target.result.abi.isAndroid()) return;
1976
+ const ndk_root = androidNdkRootPath(b) orelse return;
1977
+ run.addArgs(&.{ "--android-ndk", ndk_root });
1978
+ }
1979
+
1980
+ /// The NDK's root directory (the directory holding toolchains/llvm):
1981
+ /// ANDROID_NDK_ROOT/ANDROID_NDK_HOME wins, else the newest ndk/<version>
1982
+ /// under the platform SDK location — the same order the compiler's own
1983
+ /// discovery uses, so threading it changes nothing but the authority.
1984
+ fn androidNdkRootPath(b: *std.Build) ?[]const u8 {
1985
+ for ([_][]const u8{ "ANDROID_NDK_ROOT", "ANDROID_NDK_HOME", "ANDROID_NDK_LATEST_HOME" }) |name| {
1986
+ if (b.graph.environ_map.get(name)) |root| {
1987
+ if (root.len > 0 and buildDirExists(b, root)) return root;
1988
+ }
1989
+ }
1990
+ const sdk_root = androidSdkRoot(b) orelse return null;
1991
+ return latestVersionSubdir(b, sdk_root, "ndk") orelse blk: {
1992
+ const legacy = b.pathJoin(&.{ sdk_root, "ndk-bundle" });
1993
+ break :blk if (buildDirExists(b, legacy)) legacy else null;
1994
+ };
1995
+ }
1996
+
1997
+ fn androidNdkSysrootPath(b: *std.Build) ?[]const u8 {
1998
+ for ([_][]const u8{ "ANDROID_NDK_ROOT", "ANDROID_NDK_HOME", "ANDROID_NDK_LATEST_HOME" }) |name| {
1999
+ if (b.graph.environ_map.get(name)) |root| {
2000
+ if (root.len > 0) {
2001
+ if (ndkSysrootUnder(b, root)) |sysroot| return sysroot;
2002
+ }
2003
+ }
2004
+ }
2005
+
2006
+ const sdk_root = androidSdkRoot(b) orelse return null;
2007
+ const ndk_root = latestVersionSubdir(b, sdk_root, "ndk") orelse blk: {
2008
+ const legacy = b.pathJoin(&.{ sdk_root, "ndk-bundle" });
2009
+ break :blk if (buildDirExists(b, legacy)) legacy else return null;
2010
+ };
2011
+ return ndkSysrootUnder(b, ndk_root);
2012
+ }
2013
+
2014
+ fn androidSdkRoot(b: *std.Build) ?[]const u8 {
2015
+ for ([_][]const u8{ "ANDROID_HOME", "ANDROID_SDK_ROOT" }) |name| {
2016
+ if (b.graph.environ_map.get(name)) |root| {
2017
+ if (root.len > 0 and buildDirExists(b, root)) return root;
2018
+ }
2019
+ }
2020
+ return switch (builtin.os.tag) {
2021
+ .macos => if (b.graph.environ_map.get("HOME")) |home|
2022
+ b.pathJoin(&.{ home, "Library", "Android", "sdk" })
2023
+ else
2024
+ null,
2025
+ .windows => if (b.graph.environ_map.get("LOCALAPPDATA")) |local_app_data|
2026
+ b.pathJoin(&.{ local_app_data, "Android", "Sdk" })
2027
+ else
2028
+ null,
2029
+ else => if (b.graph.environ_map.get("HOME")) |home|
2030
+ b.pathJoin(&.{ home, "Android", "Sdk" })
2031
+ else
2032
+ null,
2033
+ };
2034
+ }
2035
+
2036
+ fn ndkSysrootUnder(b: *std.Build, ndk_root: []const u8) ?[]const u8 {
2037
+ const prebuilt_path = b.pathJoin(&.{ ndk_root, "toolchains", "llvm", "prebuilt" });
2038
+ var cwd = std.Io.Dir.cwd();
2039
+ var dir = cwd.openDir(b.graph.io, prebuilt_path, .{ .iterate = true }) catch return null;
2040
+ defer dir.close(b.graph.io);
2041
+ var iterator = dir.iterate();
2042
+ while (iterator.next(b.graph.io) catch return null) |entry| {
2043
+ if (entry.kind != .directory) continue;
2044
+ const sysroot = b.pathJoin(&.{ prebuilt_path, entry.name, "sysroot" });
2045
+ if (buildDirExists(b, b.pathJoin(&.{ sysroot, "usr", "include" }))) return sysroot;
2046
+ }
2047
+ return null;
2048
+ }
2049
+
2050
+ fn latestVersionSubdir(b: *std.Build, root: []const u8, parent: []const u8) ?[]const u8 {
2051
+ const parent_path = b.pathJoin(&.{ root, parent });
2052
+ var cwd = std.Io.Dir.cwd();
2053
+ var dir = cwd.openDir(b.graph.io, parent_path, .{ .iterate = true }) catch return null;
2054
+ defer dir.close(b.graph.io);
2055
+ var best: ?[]const u8 = null;
2056
+ defer if (best) |name| b.allocator.free(name);
2057
+ var iterator = dir.iterate();
2058
+ while (iterator.next(b.graph.io) catch return null) |entry| {
2059
+ if (entry.kind != .directory) continue;
2060
+ if (best) |current| {
2061
+ if (!versionLess(current, entry.name)) continue;
2062
+ b.allocator.free(current);
2063
+ best = null;
2064
+ }
2065
+ best = b.allocator.dupe(u8, entry.name) catch @panic("out of memory");
2066
+ }
2067
+ const name = best orelse return null;
2068
+ return b.pathJoin(&.{ parent_path, name });
2069
+ }
2070
+
2071
+ fn versionLess(a: []const u8, b: []const u8) bool {
2072
+ var a_parts = std.mem.splitScalar(u8, a, '.');
2073
+ var b_parts = std.mem.splitScalar(u8, b, '.');
2074
+ while (true) {
2075
+ const a_part = a_parts.next();
2076
+ const b_part = b_parts.next();
2077
+ if (a_part == null and b_part == null) return false;
2078
+ if (a_part == null) return true;
2079
+ if (b_part == null) return false;
2080
+ const a_num = std.fmt.parseUnsigned(u64, a_part.?, 10) catch null;
2081
+ const b_num = std.fmt.parseUnsigned(u64, b_part.?, 10) catch null;
2082
+ if (a_num != null and b_num != null) {
2083
+ if (a_num.? != b_num.?) return a_num.? < b_num.?;
2084
+ } else switch (std.mem.order(u8, a_part.?, b_part.?)) {
2085
+ .lt => return true,
2086
+ .gt => return false,
2087
+ .eq => {},
2088
+ }
2089
+ }
2090
+ }
2091
+
2092
+ fn buildDirExists(b: *std.Build, path: []const u8) bool {
2093
+ var cwd = std.Io.Dir.cwd();
2094
+ var dir = cwd.openDir(b.graph.io, path, .{}) catch return false;
2095
+ dir.close(b.graph.io);
2096
+ return true;
2097
+ }
2098
+
1046
2099
  fn macosSdkPath(b: *std.Build) ?[]const u8 {
1047
2100
  if (b.graph.environ_map.get("SDKROOT")) |sdkroot| {
1048
2101
  if (sdkroot.len > 0) return sdkroot;
@@ -1090,6 +2143,10 @@ fn nativeSdkModuleWithTerminal(b: *std.Build, dep: *std.Build.Dependency, target
1090
2143
  debug_mod.addImport("trace", trace_mod);
1091
2144
 
1092
2145
  const native_sdk_mod = externalModule(b, dep, target, optimize, "src/root.zig");
2146
+ // The header makes the internal wrapper parsable even when lazy exports
2147
+ // are reflected; the amalgamation itself is attached below only for an
2148
+ // opted-in store/sqlite artifact.
2149
+ native_sdk_mod.addIncludePath(dep.path("third_party/sqlite"));
1093
2150
  native_sdk_mod.addImport("geometry", geometry_mod);
1094
2151
  native_sdk_mod.addImport("assets", assets_mod);
1095
2152
  native_sdk_mod.addImport("app_dirs", app_dirs_mod);
@@ -1321,9 +2378,12 @@ fn linkPlatform(b: *std.Build, dep: *std.Build.Dependency, target: std.Build.Res
1321
2378
  app_mod.linkSystemLibrary("oleacc", .{});
1322
2379
  app_mod.linkSystemLibrary("shell32", .{});
1323
2380
  // TypeScript cores link ScriptC's host runtime, whose network-interface
1324
- // helpers use GetAdaptersAddresses and Winsock address conversion.
2381
+ // helpers use GetAdaptersAddresses and Winsock address conversion; the
2382
+ // in-process service archive shares the same runtime and additionally
2383
+ // reaches advapi32 (crypto-backed randomness).
1325
2384
  app_mod.linkSystemLibrary("iphlpapi", .{});
1326
2385
  app_mod.linkSystemLibrary("ws2_32", .{});
2386
+ app_mod.linkSystemLibrary("advapi32", .{});
1327
2387
  // The audio backend: Media Foundation (session + source resolver
1328
2388
  // + streaming audio renderer) and WinHTTP (the cache fill).
1329
2389
  app_mod.linkSystemLibrary("mf", .{});
@@ -1416,23 +2476,42 @@ fn addCefCheck(b: *std.Build, target: std.Build.ResolvedTarget, cef_dir: []const
1416
2476
  /// manifest falls back to the system engine WITH the web layer kept —
1417
2477
  /// over-inclusion is a size cost, wrong exclusion is a broken app.
1418
2478
  const AppManifestBuildConfig = struct {
2479
+ app_id: []const u8 = "dev.native_sdk.app",
1419
2480
  web_engine: WebEngineOption = .system,
1420
2481
  cef_dir: []const u8 = "third_party/cef/macos",
1421
2482
  cef_auto_install: bool = false,
1422
2483
  webview_layer: WebLayerOption = .auto,
1423
2484
  microphone_permission: bool = false,
1424
2485
  system_audio_permission: bool = false,
2486
+ persist_capability: bool = false,
2487
+ persist_version: ?u64 = null,
2488
+ service_packages: []const ServicePackageConfig = &.{},
2489
+ service_carrier: []const u8 = "auto",
2490
+ service_pool_size: ?u8 = null,
2491
+ store_capability: bool = false,
2492
+ relational_capability: bool = false,
2493
+ credentials_capability: bool = false,
2494
+ credentials_permission: bool = false,
2495
+ filesystem_permission: bool = false,
2496
+ sqlite_capability: bool = false,
1425
2497
  /// The first web declaration found (for teaching messages), or null
1426
2498
  /// when app.zon declares no web use. `web_engine = "system"` alone is
1427
2499
  /// NOT web intent — it is the default in many canvas manifests.
1428
2500
  web_declaration: ?web_layer_contract.Declaration = null,
1429
2501
  };
1430
2502
 
1431
- /// The lenient app.zon shape the build graph parses for inference: only
1432
- /// the fields that decide the web layer and the web engine; everything
1433
- /// else is ignored. Full schema validation stays with `native validate`
1434
- /// and the runner's comptime import.
2503
+ const ServicePackageConfig = struct {
2504
+ name: []const u8,
2505
+ version: []const u8,
2506
+ content_hash: []const u8,
2507
+ };
2508
+
2509
+ /// The lenient app.zon shape the build graph parses for inference: web
2510
+ /// inclusion, permissions, and the persistence capability/version handed to
2511
+ /// the TypeScript checker. Everything else is ignored. Full schema validation
2512
+ /// stays with `native validate` and the runner's comptime import.
1435
2513
  const InferenceManifest = struct {
2514
+ id: []const u8 = "dev.native_sdk.app",
1436
2515
  capabilities: []const []const u8 = &.{},
1437
2516
  permissions: []const []const u8 = &.{},
1438
2517
  web_engine: []const u8 = "system",
@@ -1443,6 +2522,12 @@ const InferenceManifest = struct {
1443
2522
  auto_install: bool = false,
1444
2523
  } = .{},
1445
2524
  frontend: ?struct {} = null,
2525
+ persist: ?struct {
2526
+ version: u64,
2527
+ } = null,
2528
+ service_packages: []const ServicePackageConfig = &.{},
2529
+ service_carrier: []const u8 = "auto",
2530
+ service_pool_size: u8 = 0,
1446
2531
  shell: struct {
1447
2532
  windows: []const struct {
1448
2533
  views: []const struct {
@@ -1485,12 +2570,24 @@ fn appManifestBuildConfig(b: *std.Build, app_root: []const u8) AppManifestBuildC
1485
2570
  @panic("\napp.zon .core_compiler must be \"external\" (the default and only lane)\n");
1486
2571
  }
1487
2572
  return .{
2573
+ .app_id = raw.id,
1488
2574
  .web_engine = web_layer_contract.parseWebEngine(raw.web_engine) orelse .system,
1489
2575
  .cef_dir = raw.cef.dir,
1490
2576
  .cef_auto_install = raw.cef.auto_install,
1491
2577
  .webview_layer = web_layer_contract.parseWebViewLayer(raw.webview_layer) orelse @panic("app.zon .webview_layer must be \"auto\", \"include\", or \"exclude\""),
1492
2578
  .microphone_permission = hasManifestPermission(raw.permissions, "microphone"),
1493
2579
  .system_audio_permission = hasManifestPermission(raw.permissions, "system_audio"),
2580
+ .persist_capability = hasManifestCapability(raw.capabilities, "persist"),
2581
+ .persist_version = if (raw.persist) |persist| persist.version else null,
2582
+ .service_packages = raw.service_packages,
2583
+ .service_carrier = raw.service_carrier,
2584
+ .service_pool_size = if (raw.service_pool_size == 0) null else raw.service_pool_size,
2585
+ .store_capability = hasManifestCapability(raw.capabilities, "store"),
2586
+ .relational_capability = hasManifestCapability(raw.capabilities, "sqlite"),
2587
+ .credentials_capability = hasManifestCapability(raw.capabilities, "credentials"),
2588
+ .credentials_permission = hasManifestPermission(raw.permissions, "credentials"),
2589
+ .filesystem_permission = hasManifestPermission(raw.permissions, "filesystem"),
2590
+ .sqlite_capability = hasManifestCapability(raw.capabilities, "store") or hasManifestCapability(raw.capabilities, "sqlite"),
1494
2591
  .web_declaration = web_layer_contract.manifestDeclaration(raw),
1495
2592
  };
1496
2593
  }
@@ -1502,6 +2599,13 @@ fn hasManifestPermission(permissions: []const []const u8, expected: []const u8)
1502
2599
  return false;
1503
2600
  }
1504
2601
 
2602
+ fn hasManifestCapability(capabilities: []const []const u8, expected: []const u8) bool {
2603
+ for (capabilities) |capability| {
2604
+ if (std.mem.eql(u8, capability, expected)) return true;
2605
+ }
2606
+ return false;
2607
+ }
2608
+
1505
2609
  /// The web-layer decision for this build: the shared contract fed this
1506
2610
  /// boundary's inputs — the manifest declarations from the lenient parse
1507
2611
  /// and the engine RESOLVED from `-Dweb-engine` orelse app.zon. WEB means