@native-sdk/cli 0.10.1 → 0.11.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 (462) hide show
  1. package/README.md +8 -6
  2. package/bin/native.js +2 -1
  3. package/build/app.zig +320 -60
  4. package/build/corewire.zig +53 -0
  5. package/build/test_shards.zig +49 -0
  6. package/build/ts_run.mjs +3 -3
  7. package/build.zig +1796 -83
  8. package/package.json +19 -14
  9. package/packages/core/compile-surface/core.ts +134 -72
  10. package/packages/core/package-lock.json +75 -357
  11. package/packages/core/package.json +25 -4
  12. package/packages/core/scripts/compiler_command.mjs +17 -12
  13. package/packages/core/scripts/compiler_typecheck.mjs +1 -0
  14. package/packages/core/scripts/gen_declarations.mjs +3 -2
  15. package/packages/core/scripts/gen_service_surface.mjs +22 -10
  16. package/packages/core/scripts/install_scriptc.mjs +182 -0
  17. package/packages/core/scripts/invoke_scriptc.mjs +18 -0
  18. package/packages/core/scripts/merge_static_archives.mjs +6 -1
  19. package/packages/core/scripts/npm_static_spike.mjs +2 -2
  20. package/packages/core/scripts/run_external_core_compiler.mjs +22 -10
  21. package/packages/core/scripts/run_external_service_compiler.mjs +15 -15
  22. package/packages/core/scripts/run_library_compiler.mjs +51 -0
  23. package/packages/core/scripts/run_native_tests.mjs +22 -0
  24. package/packages/core/scripts/scriptc-toolchain.json +101 -0
  25. package/packages/core/scripts/scriptc_toolchain.mjs +121 -0
  26. package/packages/core/scripts/stage_external_core.mjs +57 -1
  27. package/packages/core/scripts/surface_manifest_diff.mjs +19 -12
  28. package/packages/core/sdk/bytes.d.ts +2 -0
  29. package/packages/core/sdk/bytes.ts +86 -0
  30. package/packages/core/sdk/core.d.ts +308 -4
  31. package/packages/core/sdk/core.ts +320 -84
  32. package/packages/core/sdk/events.d.ts +247 -0
  33. package/packages/core/sdk/events.ts +230 -2
  34. package/packages/core/sdk/internal/image_identity.d.ts +7 -0
  35. package/packages/core/sdk/internal/image_identity.ts +71 -0
  36. package/packages/core/sdk/internal/markdown_policy.d.ts +5 -0
  37. package/packages/core/sdk/internal/markdown_policy.ts +878 -0
  38. package/packages/core/sdk/text.d.ts +27 -0
  39. package/packages/core/sdk/text.ts +206 -15
  40. package/packages/core/sdk/theme.d.ts +251 -0
  41. package/packages/core/sdk/theme.ts +267 -0
  42. package/packages/core/src/authorization.ts +137 -0
  43. package/packages/core/src/automation_commands.ts +201 -0
  44. package/packages/core/src/automation_interactions.ts +92 -0
  45. package/packages/core/src/bridge_descriptors.ts +104 -0
  46. package/packages/core/src/builtin_coordination.ts +172 -0
  47. package/packages/core/src/canvas_frame_coordination.ts +81 -0
  48. package/packages/core/src/canvas_presentation_lifecycle.ts +84 -0
  49. package/packages/core/src/canvas_scene_observation.ts +145 -0
  50. package/packages/core/src/chart_content.ts +161 -0
  51. package/packages/core/src/chart_plans.ts +432 -0
  52. package/packages/core/src/checker.ts +166 -19
  53. package/packages/core/src/code_content.ts +580 -0
  54. package/packages/core/src/command_coordination.ts +140 -0
  55. package/packages/core/src/component_composition.ts +94 -0
  56. package/packages/core/src/component_construction.ts +149 -0
  57. package/packages/core/src/contract.ts +25 -7
  58. package/packages/core/src/control_appearance.ts +232 -0
  59. package/packages/core/src/control_commands.ts +115 -0
  60. package/packages/core/src/control_content.ts +105 -0
  61. package/packages/core/src/control_geometry.ts +107 -0
  62. package/packages/core/src/control_payloads.ts +119 -0
  63. package/packages/core/src/control_primitives.ts +134 -0
  64. package/packages/core/src/devhost.ts +82 -7
  65. package/packages/core/src/devhost_journal.mjs +30 -7
  66. package/packages/core/src/effect_plans.ts +71 -0
  67. package/packages/core/src/flow_measurement.ts +121 -0
  68. package/packages/core/src/font_registry.ts +37 -0
  69. package/packages/core/src/glyph_atlas.ts +86 -0
  70. package/packages/core/src/gpu_packet_preparation.ts +130 -0
  71. package/packages/core/src/gpu_planning.ts +123 -0
  72. package/packages/core/src/gpu_presentation.ts +55 -0
  73. package/packages/core/src/host_flow.ts +89 -0
  74. package/packages/core/src/host_input_regions.ts +165 -0
  75. package/packages/core/src/image_registry.ts +66 -0
  76. package/packages/core/src/indicator_plans.ts +132 -0
  77. package/packages/core/src/infer.ts +150 -8
  78. package/packages/core/src/input_composition.ts +116 -0
  79. package/packages/core/src/intrinsic_measure.ts +100 -0
  80. package/packages/core/src/layout_coordination.ts +207 -0
  81. package/packages/core/src/leaf_plans.ts +134 -0
  82. package/packages/core/src/markup_development.ts +160 -0
  83. package/packages/core/src/measurement_coordination.ts +185 -0
  84. package/packages/core/src/modules.ts +1 -1
  85. package/packages/core/src/motion_sampling.ts +100 -0
  86. package/packages/core/src/paragraph_layout.ts +192 -0
  87. package/packages/core/src/portable_sources.json +74 -0
  88. package/packages/core/src/portable_sources.ts +17 -0
  89. package/packages/core/src/registered_font.ts +93 -0
  90. package/packages/core/src/render_animation_lifecycle.ts +128 -0
  91. package/packages/core/src/render_coordination.ts +170 -0
  92. package/packages/core/src/render_resources.ts +234 -0
  93. package/packages/core/src/runtime_policy.ts +3930 -0
  94. package/packages/core/src/scalar_text.ts +84 -0
  95. package/packages/core/src/service_contract.ts +2 -1
  96. package/packages/core/src/session_codecs.ts +309 -0
  97. package/packages/core/src/shell_admission.ts +126 -0
  98. package/packages/core/src/shell_coordination.ts +93 -0
  99. package/packages/core/src/sqlite_cli.ts +11 -0
  100. package/packages/core/src/status_validation.ts +232 -0
  101. package/packages/core/src/stream_policy.ts +63 -0
  102. package/packages/core/src/surface_recipes.ts +136 -0
  103. package/packages/core/src/system_admission.ts +60 -0
  104. package/packages/core/src/terminal_paint.ts +436 -0
  105. package/packages/core/src/text_document_width.ts +81 -0
  106. package/packages/core/src/text_measurement_cache.ts +69 -0
  107. package/packages/core/src/text_query_layout.ts +179 -0
  108. package/packages/core/src/text_run_layout.ts +410 -0
  109. package/packages/core/src/text_span_queries.ts +355 -0
  110. package/packages/core/src/typed_ast.ts +18 -1
  111. package/packages/core/src/types.ts +7 -5
  112. package/packages/core/src/vector_effects.ts +98 -0
  113. package/packages/core/src/vector_raster.ts +243 -0
  114. package/packages/core/src/view_components.ts +2415 -0
  115. package/packages/core/src/view_coordination.ts +198 -0
  116. package/packages/core/src/view_frontend.ts +980 -0
  117. package/packages/core/src/widget_audits.ts +202 -0
  118. package/packages/core/src/widget_changes.ts +258 -0
  119. package/packages/core/src/widget_metrics.ts +139 -0
  120. package/packages/core/src/widget_motion.ts +171 -0
  121. package/packages/core/src/widget_paint.ts +272 -0
  122. package/packages/core/src/widget_paint_walk.ts +203 -0
  123. package/packages/core/src/widget_presentation.ts +141 -0
  124. package/packages/core/src/widget_routing.ts +262 -0
  125. package/packages/core/src/window_lifecycle.ts +92 -0
  126. package/packages/core/testing/index.ts +430 -0
  127. package/schemas/app.schema.json +13 -0
  128. package/skill-data/core/SKILL.md +2 -2
  129. package/skill-data/native-ui/SKILL.md +76 -17
  130. package/skill-data/ts-core/SKILL.md +113 -9
  131. package/skill-data/ts-services/SKILL.md +1 -1
  132. package/skill-data/ts-services/references/service-surface.md +264 -144
  133. package/src/app_runner/root.zig +25 -12
  134. package/src/app_runner/ts_compiled_view.zig +1631 -0
  135. package/src/app_runner/ts_core_main.zig +143 -10
  136. package/src/app_runner/ts_core_mobile.zig +24 -12
  137. package/src/automation/server.zig +1 -3
  138. package/src/automation/snapshot.zig +9 -637
  139. package/src/automation/snapshot_reference.zig +656 -0
  140. package/src/automation/snapshot_serialization.zig +566 -0
  141. package/src/platform/linux/gtk_host.c +36 -24
  142. package/src/platform/linux/gtk_pixels.h +118 -0
  143. package/src/platform/linux/gtk_pixels_test.c +241 -0
  144. package/src/platform/linux/root.zig +2 -0
  145. package/src/platform/macos/appkit_host.m +188 -30
  146. package/src/platform/macos/pointer_motion_test.m +96 -0
  147. package/src/platform/macos/scroll_driver_test.m +105 -0
  148. package/src/platform/macos/spectrum_bins.h +34 -0
  149. package/src/platform/macos/spectrum_bins_test.c +56 -0
  150. package/src/platform/macos/text_keyboard_test.m +80 -0
  151. package/src/platform/macos/widget_focus_test.m +66 -0
  152. package/src/platform/null_platform.zig +26 -2
  153. package/src/platform/null_platform_tests.zig +13 -0
  154. package/src/platform/root.zig +1 -0
  155. package/src/platform/types.zig +13 -0
  156. package/src/platform/windows/root.zig +2 -0
  157. package/src/platform/windows/webview2_host.cpp +7 -2
  158. package/src/primitives/app_manifest/comptime_scene.zig +1 -1
  159. package/src/primitives/app_manifest/root.zig +2 -0
  160. package/src/primitives/app_manifest/tests.zig +4 -1
  161. package/src/primitives/app_manifest/validation.zig +2 -0
  162. package/src/primitives/canvas/a11y_audit.zig +3 -1
  163. package/src/primitives/canvas/canvas_frame_coordination_policy.zig +134 -0
  164. package/src/primitives/canvas/chart_content_policy.zig +75 -0
  165. package/src/primitives/canvas/chart_plan_policy.zig +196 -0
  166. package/src/primitives/canvas/code_content_policy.zig +162 -0
  167. package/src/primitives/canvas/commands.zig +29 -1
  168. package/src/primitives/canvas/component_composition.zig +125 -0
  169. package/src/primitives/canvas/component_composition_policy.zig +44 -0
  170. package/src/primitives/canvas/component_construction_policy.zig +187 -0
  171. package/src/primitives/canvas/container_layout_policy.zig +87 -0
  172. package/src/primitives/canvas/control_appearance_policy.zig +142 -0
  173. package/src/primitives/canvas/control_command_policy.zig +75 -0
  174. package/src/primitives/canvas/control_content_policy.zig +90 -0
  175. package/src/primitives/canvas/control_geometry_policy.zig +165 -0
  176. package/src/primitives/canvas/control_payload_policy.zig +48 -0
  177. package/src/primitives/canvas/control_primitive_policy.zig +129 -0
  178. package/src/primitives/canvas/effect_plan_policy.zig +96 -0
  179. package/src/primitives/canvas/events.zig +1027 -1
  180. package/src/primitives/canvas/flow_measurement_policy.zig +237 -0
  181. package/src/primitives/canvas/frame.zig +92 -23
  182. package/src/primitives/canvas/glyph_atlas_policy.zig +40 -0
  183. package/src/primitives/canvas/gpu.zig +10 -0
  184. package/src/primitives/canvas/gpu_packet_preparation_policy.zig +325 -0
  185. package/src/primitives/canvas/gpu_planning_policy.zig +364 -0
  186. package/src/primitives/canvas/gpu_presentation_policy.zig +74 -0
  187. package/src/primitives/canvas/grid_layout_policy.zig +51 -0
  188. package/src/primitives/canvas/indicator_plan_policy.zig +128 -0
  189. package/src/primitives/canvas/intrinsic_layout_policy.zig +87 -0
  190. package/src/primitives/canvas/intrinsic_measure_policy.zig +128 -0
  191. package/src/primitives/canvas/layout_audit.zig +5 -2
  192. package/src/primitives/canvas/layout_coordination_policy.zig +262 -0
  193. package/src/primitives/canvas/leaf_plan_policy.zig +117 -0
  194. package/src/primitives/canvas/markdown.zig +13 -3
  195. package/src/primitives/canvas/markdown_content_policy.zig +227 -0
  196. package/src/primitives/canvas/markdown_image_binding.zig +81 -0
  197. package/src/primitives/canvas/measurement_coordination_policy.zig +288 -0
  198. package/src/primitives/canvas/numeric_capabilities.zig +14 -0
  199. package/src/primitives/canvas/reference.zig +12 -6
  200. package/src/primitives/canvas/registered_font_policy.zig +152 -0
  201. package/src/primitives/canvas/render.zig +48 -0
  202. package/src/primitives/canvas/render_cache_policy.zig +184 -0
  203. package/src/primitives/canvas/render_coordination_policy.zig +163 -0
  204. package/src/primitives/canvas/render_damage_policy.zig +160 -0
  205. package/src/primitives/canvas/render_effects.zig +14 -0
  206. package/src/primitives/canvas/render_generic_resources.zig +14 -0
  207. package/src/primitives/canvas/render_images.zig +14 -0
  208. package/src/primitives/canvas/render_layers.zig +14 -0
  209. package/src/primitives/canvas/render_override_policy.zig +119 -0
  210. package/src/primitives/canvas/render_paths.zig +14 -0
  211. package/src/primitives/canvas/render_plan_policy.zig +199 -0
  212. package/src/primitives/canvas/render_resource_policy.zig +476 -0
  213. package/src/primitives/canvas/root.zig +100 -0
  214. package/src/primitives/canvas/semantic_tree_policy.zig +158 -0
  215. package/src/primitives/canvas/serialization.zig +8 -1
  216. package/src/primitives/canvas/surface_layout_policy.zig +36 -0
  217. package/src/primitives/canvas/surface_recipe_policy.zig +231 -0
  218. package/src/primitives/canvas/terminal_grid.zig +10 -696
  219. package/src/primitives/canvas/terminal_grid_reference.zig +709 -0
  220. package/src/primitives/canvas/terminal_paint_policy.zig +191 -0
  221. package/src/primitives/canvas/text.zig +1 -0
  222. package/src/primitives/canvas/text_atlas.zig +113 -0
  223. package/src/primitives/canvas/text_cache_policy.zig +94 -0
  224. package/src/primitives/canvas/text_document_policy.zig +120 -0
  225. package/src/primitives/canvas/text_layout.zig +51 -2
  226. package/src/primitives/canvas/text_layout_cache.zig +29 -0
  227. package/src/primitives/canvas/text_layout_hash.zig +1 -0
  228. package/src/primitives/canvas/text_layout_types.zig +3 -0
  229. package/src/primitives/canvas/text_measure_cache.zig +46 -0
  230. package/src/primitives/canvas/text_measurement_policy.zig +124 -0
  231. package/src/primitives/canvas/text_metrics.zig +23 -0
  232. package/src/primitives/canvas/text_query_policy.zig +156 -0
  233. package/src/primitives/canvas/text_run_policy.zig +252 -0
  234. package/src/primitives/canvas/text_scalar_policy.zig +156 -0
  235. package/src/primitives/canvas/text_span_query_policy.zig +232 -0
  236. package/src/primitives/canvas/text_spans.zig +280 -8
  237. package/src/primitives/canvas/text_tests.zig +10 -0
  238. package/src/primitives/canvas/tokens.zig +38 -0
  239. package/src/primitives/canvas/ui.zig +250 -83
  240. package/src/primitives/canvas/ui_markup.zig +139 -33
  241. package/src/primitives/canvas/ui_markup_compiled.zig +319 -59
  242. package/src/primitives/canvas/ui_markup_compiled_tests.zig +225 -0
  243. package/src/primitives/canvas/ui_markup_contract.zig +146 -14
  244. package/src/primitives/canvas/ui_markup_contract_tests.zig +77 -0
  245. package/src/primitives/canvas/ui_markup_reflect.zig +56 -0
  246. package/src/primitives/canvas/ui_markup_tests.zig +116 -0
  247. package/src/primitives/canvas/ui_markup_view.zig +258 -32
  248. package/src/primitives/canvas/ui_markup_view_tests.zig +142 -10
  249. package/src/primitives/canvas/ui_schema.zig +13 -1
  250. package/src/primitives/canvas/ui_schema_tests.zig +11 -7
  251. package/src/primitives/canvas/ui_tests.zig +1 -0
  252. package/src/primitives/canvas/vector.zig +36 -2
  253. package/src/primitives/canvas/vector_effect_policy.zig +236 -0
  254. package/src/primitives/canvas/vector_raster_policy.zig +190 -0
  255. package/src/primitives/canvas/virtual_extent_policy.zig +292 -0
  256. package/src/primitives/canvas/virtual_extents.zig +99 -3
  257. package/src/primitives/canvas/virtual_flow_policy.zig +108 -0
  258. package/src/primitives/canvas/widget_audit_policy.zig +293 -0
  259. package/src/primitives/canvas/widget_change_policy.zig +298 -0
  260. package/src/primitives/canvas/widget_invalidation.zig +113 -2
  261. package/src/primitives/canvas/widget_layout.zig +673 -128
  262. package/src/primitives/canvas/widget_layout_tests.zig +4 -0
  263. package/src/primitives/canvas/widget_metric_policy.zig +126 -0
  264. package/src/primitives/canvas/widget_metrics.zig +45 -6
  265. package/src/primitives/canvas/widget_paint_policy.zig +166 -0
  266. package/src/primitives/canvas/widget_paint_walk_policy.zig +252 -0
  267. package/src/primitives/canvas/widget_presentation_policy.zig +168 -0
  268. package/src/primitives/canvas/widget_render.zig +744 -74
  269. package/src/primitives/canvas/widget_render_controls.zig +1217 -133
  270. package/src/primitives/canvas/widget_render_scroll.zig +11 -3
  271. package/src/primitives/canvas/widget_render_style.zig +94 -0
  272. package/src/primitives/canvas/widget_render_surfaces.zig +61 -50
  273. package/src/primitives/canvas/widget_routing.zig +75 -0
  274. package/src/primitives/canvas/widget_routing_policy.zig +135 -0
  275. package/src/primitives/canvas/widget_runtime.zig +20 -1
  276. package/src/primitives/canvas/widget_semantics.zig +25 -0
  277. package/src/primitives/canvas/widget_text_input.zig +86 -23
  278. package/src/primitives/canvas/widget_text_select.zig +1 -0
  279. package/src/primitives/canvas/widget_tree.zig +8 -1
  280. package/src/primitives/canvas/widgets.zig +42 -12
  281. package/src/primitives/canvas/wrapped_layout_policy.zig +104 -0
  282. package/src/root.zig +21 -0
  283. package/src/runtime/accessibility_policy.zig +122 -0
  284. package/src/runtime/api.zig +28 -0
  285. package/src/runtime/app_dispatch_policy.zig +68 -0
  286. package/src/runtime/authorization_policy.zig +150 -0
  287. package/src/runtime/automation_command_policy.zig +241 -0
  288. package/src/runtime/automation_interaction_policy.zig +107 -0
  289. package/src/runtime/automation_snapshot.zig +52 -22
  290. package/src/runtime/automation_snapshot_reference.zig +290 -0
  291. package/src/runtime/automation_widget_dispatch.zig +267 -355
  292. package/src/runtime/automation_widget_dispatch_reference.zig +900 -0
  293. package/src/runtime/blob_policy.zig +58 -0
  294. package/src/runtime/blob_reference.zig +64 -0
  295. package/src/runtime/bridge_descriptor_policy.zig +206 -0
  296. package/src/runtime/builtin_bridge.zig +180 -44
  297. package/src/runtime/builtin_coordination_policy.zig +121 -0
  298. package/src/runtime/callback_policy_test_reference.zig +97 -0
  299. package/src/runtime/canvas_drag_policy.zig +94 -0
  300. package/src/runtime/canvas_fonts.zig +38 -10
  301. package/src/runtime/canvas_frame.zig +590 -134
  302. package/src/runtime/canvas_frame_helpers.zig +1 -0
  303. package/src/runtime/canvas_hover_policy.zig +131 -0
  304. package/src/runtime/canvas_images.zig +59 -30
  305. package/src/runtime/canvas_keyboard_focus_policy.zig +154 -0
  306. package/src/runtime/canvas_limits.zig +1 -1
  307. package/src/runtime/canvas_presentation_lifecycle_policy.zig +86 -0
  308. package/src/runtime/canvas_scene_observation_policy.zig +181 -0
  309. package/src/runtime/canvas_widget_context_menu.zig +4 -4
  310. package/src/runtime/canvas_widget_display.zig +110 -9
  311. package/src/runtime/canvas_widget_events.zig +718 -328
  312. package/src/runtime/canvas_widget_runtime.zig +437 -81
  313. package/src/runtime/canvas_widget_scroll_drivers.zig +39 -1
  314. package/src/runtime/canvas_widget_scroll_tests.zig +31 -0
  315. package/src/runtime/canvas_widget_state.zig +93 -56
  316. package/src/runtime/channel_sources.zig +80 -0
  317. package/src/runtime/command_policy.zig +161 -0
  318. package/src/runtime/component_policy.zig +83 -0
  319. package/src/runtime/core.zig +156 -6
  320. package/src/runtime/desktop_files.zig +189 -0
  321. package/src/runtime/effects.zig +466 -29
  322. package/src/runtime/effects_tests.zig +28 -0
  323. package/src/runtime/file_policy_test_reference.zig +113 -0
  324. package/src/runtime/flow.zig +418 -341
  325. package/src/runtime/flow_reference.zig +1426 -0
  326. package/src/runtime/font_registry_policy.zig +72 -0
  327. package/src/runtime/frame_profile.zig +24 -33
  328. package/src/runtime/gpu_surface_events.zig +97 -35
  329. package/src/runtime/host_event_pump.zig +303 -0
  330. package/src/runtime/host_event_pump_reference.zig +268 -0
  331. package/src/runtime/host_flow_policy.zig +155 -0
  332. package/src/runtime/host_input_regions_policy.zig +156 -0
  333. package/src/runtime/image_registry_policy.zig +94 -0
  334. package/src/runtime/input_composition_policy.zig +138 -0
  335. package/src/runtime/journal_policy.zig +66 -0
  336. package/src/runtime/journal_reference.zig +53 -0
  337. package/src/runtime/lifecycle_policy_test_reference.zig +97 -0
  338. package/src/runtime/markup_development_policy.zig +91 -0
  339. package/src/runtime/media_surface.zig +40 -1
  340. package/src/runtime/motion_sampling_policy.zig +159 -0
  341. package/src/runtime/recording_policy.zig +42 -0
  342. package/src/runtime/render_animation_policy.zig +206 -0
  343. package/src/runtime/replay_policy.zig +66 -0
  344. package/src/runtime/replay_policy_reference.zig +326 -0
  345. package/src/runtime/replay_progress_policy.zig +64 -0
  346. package/src/runtime/replay_progress_reference.zig +34 -0
  347. package/src/runtime/request_policy_test_reference.zig +188 -0
  348. package/src/runtime/root.zig +13 -0
  349. package/src/runtime/session_blobs.zig +157 -58
  350. package/src/runtime/session_blobs_reference.zig +692 -0
  351. package/src/runtime/session_codec.zig +361 -0
  352. package/src/runtime/session_codec_reference.zig +1027 -0
  353. package/src/runtime/session_journal.zig +246 -983
  354. package/src/runtime/session_record.zig +224 -45
  355. package/src/runtime/session_replay.zig +157 -415
  356. package/src/runtime/session_tests.zig +552 -0
  357. package/src/runtime/shell_admission_policy.zig +225 -0
  358. package/src/runtime/shell_coordination_policy.zig +138 -0
  359. package/src/runtime/shell_layout.zig +126 -1
  360. package/src/runtime/snapshot_policy.zig +60 -0
  361. package/src/runtime/snapshot_reference.zig +64 -0
  362. package/src/runtime/state.zig +16 -0
  363. package/src/runtime/status_validation.zig +190 -0
  364. package/src/runtime/system_admission_policy.zig +140 -0
  365. package/src/runtime/system_services.zig +46 -36
  366. package/src/runtime/tests.zig +1 -0
  367. package/src/runtime/ts_canvas_hooks.zig +261 -0
  368. package/src/runtime/ts_canvas_hooks_tests.zig +279 -0
  369. package/src/runtime/ts_canvas_icons.zig +234 -0
  370. package/src/runtime/ts_core_host.zig +2325 -411
  371. package/src/runtime/ts_core_host_tests.zig +1982 -0
  372. package/src/runtime/ts_test_host.zig +699 -0
  373. package/src/runtime/ts_ui_app.zig +1087 -45
  374. package/src/runtime/ui_app.zig +1117 -629
  375. package/src/runtime/ui_app_provenance.zig +147 -5
  376. package/src/runtime/ui_app_provenance_reference.zig +370 -0
  377. package/src/runtime/ui_app_tests.zig +619 -9
  378. package/src/runtime/ui_app_window_tests.zig +89 -0
  379. package/src/runtime/view.zig +25 -0
  380. package/src/runtime/view_canvas.zig +30 -6
  381. package/src/runtime/view_coordination_policy.zig +147 -0
  382. package/src/runtime/view_widget_control.zig +51 -14
  383. package/src/runtime/view_widget_scroll.zig +16 -5
  384. package/src/runtime/view_widget_text.zig +153 -68
  385. package/src/runtime/view_widget_tree.zig +460 -56
  386. package/src/runtime/webview_view_bridge_tests.zig +2 -0
  387. package/src/runtime/widget_motion_policy.zig +238 -0
  388. package/src/runtime/window_command_bridge_tests.zig +63 -0
  389. package/src/runtime/window_lifecycle_policy.zig +127 -0
  390. package/src/runtime/window_storage.zig +74 -8
  391. package/src/runtime/window_view_runtime.zig +148 -33
  392. package/src/runtime/window_views.zig +163 -10
  393. package/src/tooling/components/identity_tests.zig +62 -36
  394. package/src/tooling/components/stepper.native +24 -0
  395. package/src/tooling/components/stepper.zig +0 -19
  396. package/src/tooling/components/timeline-item.native +22 -0
  397. package/src/tooling/components/timeline.native +5 -3
  398. package/src/tooling/components/timeline_item.zig +0 -32
  399. package/src/tooling/eject_components.zig +76 -8
  400. package/src/tooling/ios.zig +66 -12
  401. package/src/tooling/manifest.zig +35 -0
  402. package/src/tooling/raw_manifest.zig +6 -0
  403. package/src/tooling/templates.zig +15 -3
  404. package/src/tooling/ts_core.zig +13 -3
  405. package/src/tooling/verbs.zig +22 -0
  406. package/tools/corewire/build_profile.mjs +54 -0
  407. package/tools/corewire/contract_intake.ts +303 -0
  408. package/tools/corewire/contract_intake.zig +82 -0
  409. package/tools/corewire/core.test.ts +166 -0
  410. package/tools/corewire/core_abi.zig +51 -0
  411. package/tools/corewire/core_cases.ts +233 -0
  412. package/tools/corewire/core_contract.ts +407 -0
  413. package/tools/corewire/core_emission.ts +136 -0
  414. package/tools/corewire/core_emission.zig +69 -0
  415. package/tools/corewire/core_goldens.json +3110 -0
  416. package/tools/corewire/core_policy.ts +14 -0
  417. package/tools/corewire/core_policy.zig +48 -0
  418. package/tools/corewire/core_projection.ts +360 -0
  419. package/tools/corewire/core_vocabulary.ts +6 -0
  420. package/tools/corewire/emit.zig +19 -1590
  421. package/tools/corewire/emit_facade.ts +714 -0
  422. package/tools/corewire/emit_facade.zig +10 -3752
  423. package/tools/corewire/emit_mirror.ts +290 -0
  424. package/tools/corewire/emit_profile.ts +50 -0
  425. package/tools/corewire/emit_service.ts +331 -0
  426. package/tools/corewire/emit_service.zig +23 -842
  427. package/tools/corewire/entry.test.ts +95 -0
  428. package/tools/corewire/entry_coordination.ts +127 -0
  429. package/tools/corewire/entry_coordination.zig +190 -0
  430. package/tools/corewire/facade_templates.ts +85 -0
  431. package/tools/corewire/filesystem.test.ts +166 -0
  432. package/tools/corewire/filesystem_coordination.ts +213 -0
  433. package/tools/corewire/filesystem_coordination.zig +245 -0
  434. package/tools/corewire/intake.test.ts +35 -0
  435. package/tools/corewire/intake_cases.ts +55 -0
  436. package/tools/corewire/intake_goldens.json +12237 -0
  437. package/tools/corewire/invocation.test.ts +24 -0
  438. package/tools/corewire/invocation.ts +175 -0
  439. package/tools/corewire/invocation.zig +136 -0
  440. package/tools/corewire/invocation_cases.ts +60 -0
  441. package/tools/corewire/invocation_fixture.ts +33 -0
  442. package/tools/corewire/invocation_goldens.json +1143 -0
  443. package/tools/corewire/invocation_tests.zig +111 -0
  444. package/tools/corewire/invocation_usage.ts +2 -0
  445. package/tools/corewire/lossless_projection.ts +96 -0
  446. package/tools/corewire/main.zig +7 -680
  447. package/tools/corewire/main_reference.zig +415 -0
  448. package/tools/corewire/mirror_templates.ts +55 -0
  449. package/tools/corewire/profile.test.ts +248 -0
  450. package/tools/corewire/profile.zig +56 -0
  451. package/tools/corewire/profile_emission.ts +202 -0
  452. package/tools/corewire/profile_library.json +29 -0
  453. package/tools/corewire/profile_tests.zig +136 -0
  454. package/tools/corewire/service.test.ts +75 -0
  455. package/tools/corewire/service_cases.ts +61 -0
  456. package/tools/corewire/service_contract.zig +40 -146
  457. package/tools/corewire/service_goldens.json +650 -0
  458. package/tools/corewire/service_projection.zig +52 -0
  459. package/tools/corewire/service_templates.ts +14 -0
  460. package/tools/corewire/shim_rt.zig +9 -0
  461. package/tools/corewire/sidecar.zig +267 -1438
  462. package/tools/corewire/emit_profile.zig +0 -521
@@ -0,0 +1,714 @@
1
+ // The TypeScript entry projection of the compiled core's complete contract.
2
+ import type { TypeRef, Payload, RecordType, MsgArm } from "./core_contract.ts";
3
+ import { findRecord, findEnum, findUnion } from "./core_contract.ts";
4
+ import { projectionPlan, validateFacade } from "./core_projection.ts";
5
+ import type { ProjectionPlan } from "./core_projection.ts";
6
+ import { CodeWriter, commentText, tsString, tsProp, tsAccess, synthesized, scrollIndexes, scrollFields, isTextInputUnion } from "./core_emission.ts";
7
+ import type { EmissionInput, EmissionContract, EmissionResult } from "./core_emission.ts";
8
+ import * as text from "./facade_templates.ts";
9
+
10
+ const maxSafe = "9007199254740991";
11
+ function lowerBound(className: string | null): string { return className === "u64" ? "0" : "-9007199254740991"; }
12
+ function payloadNumberClass(p: Payload): string | null {
13
+ if (p.kind === "number") return p.class!;
14
+ if (p.kind === "scalar" && (p.type!.kind === "f64" || p.type!.kind === "i64")) return p.type!.kind;
15
+ return null;
16
+ }
17
+ export function emitFacade(input: EmissionInput): EmissionResult {
18
+ const plan = projectionPlan(input.sidecar), diagnostics = validateFacade(input.sidecar, plan);
19
+ if (diagnostics.length > 0) return { output: "", diagnostics };
20
+ const model = findRecord(input.sidecar, input.sidecar.model)!;
21
+ for (const name of input.sidecar.msg.unbound) {
22
+ if (model.fields.some(field => field.name === name) || input.sidecar.model_helpers.some(helper => helper.name === name)) {
23
+ diagnostics.push({ path: "msg.unbound", message: `"${name}" is an unbound message arm shadowed by a homonymous Model field or exported helper — the compiler resolves Model fields and helpers before message arms, so the projection's single unbound list cannot mark this arm; rename one side in the core source` });
24
+ }
25
+ }
26
+ if (diagnostics.length > 0) return { output: "", diagnostics };
27
+ const emitter = new FacadeEmitter(input, plan); emitter.run();
28
+ return { output: emitter.out, diagnostics };
29
+ }
30
+ class FacadeEmitter extends CodeWriter {
31
+ input: EmissionInput; s: EmissionContract; plan: ProjectionPlan;
32
+ usedCodec: string[] = []; referenced: string[] = [];
33
+ needsPinchPhase: boolean = false; needsMemberTrap: boolean = false; tempCounter: number = 0;
34
+ neededEnumTables: string[] = []; neededEnumIndexes: string[] = [];
35
+ neededRecordWriters: string[] = []; neededUnionWriters: string[] = []; neededUnionDecoders: string[] = [];
36
+ constructor(input: EmissionInput, plan: ProjectionPlan) { super(); this.input = input; this.s = input.sidecar; this.plan = plan; }
37
+ use(id: string): void {
38
+ if (this.usedCodec.includes(id)) return;
39
+ this.usedCodec.push(id);
40
+ let deps: string[] = [];
41
+ if (["read_i64", "read_i64_saturating", "read_u64_saturating"].includes(id)) deps = ["read_u32"];
42
+ else if (["read_u8", "read_u32", "read_f64", "read_bool", "read_bytes_body", "assert_consumed"].includes(id)) deps = ["trap"];
43
+ else if (["w_u32", "w_u8", "w_f64", "w_bool"].includes(id)) deps = ["sink"];
44
+ else if (["w_i64", "w_u64"].includes(id)) deps = ["w_u32", "trunc_toward_zero", "trap"];
45
+ else if (id === "w_bytes") deps = ["w_u32"];
46
+ else if (id === "short_text") deps = ["sink", "trap"];
47
+ else if (id === "enum_index") deps = ["trap"];
48
+ else if (id === "cmd_encoder") deps = ["w_u8", "w_f64", "w_bytes", "short_text", "utf8_text", "enum_index", "trap"];
49
+ else if (id === "sub_encoder") deps = ["w_u8", "w_u32", "w_f64", "w_bytes", "short_text", "utf8_text", "trap"];
50
+ for (const dep of deps) this.use(dep);
51
+ }
52
+ reference(name: string): void {
53
+ if (!this.isGeneratedOnlyType(name) && this.isExportedType(name) && !this.referenced.includes(name)) this.referenced.push(name);
54
+ }
55
+ memberOf(member: string | null): string { return member ?? "value"; }
56
+ originOf(name: string): string {
57
+ for (const r of this.s.types.structs) if (r.name === name) return r.origin ?? this.entryBasename();
58
+ for (const e of this.s.types.enums) if (e.name === name) return e.origin ?? this.entryBasename();
59
+ for (const u of this.s.types.unions) if (u.name === name) return u.origin ?? this.entryBasename();
60
+ return this.entryBasename();
61
+ }
62
+ entryBasename(): string {
63
+ const entry = this.s.entry.replace(/\/+$/, "");
64
+ return entry.slice(entry.lastIndexOf("/") + 1);
65
+ }
66
+ isGeneratedOnlyType(name: string): boolean {
67
+ if (name === this.s.model || name === this.s.msg.name) return false;
68
+ for (const r of this.s.types.structs) if (r.name === name) return r.origin === null;
69
+ for (const e of this.s.types.enums) if (e.name === name) return e.origin === null;
70
+ for (const u of this.s.types.unions) if (u.name === name) return u.origin === null;
71
+ return false;
72
+ }
73
+ isExportedType(name: string): boolean {
74
+ if (name === this.s.model || name === this.s.msg.name) return true;
75
+ for (const r of this.s.types.structs) if (r.name === name) return r.exported;
76
+ for (const e of this.s.types.enums) if (e.name === name) return e.exported;
77
+ for (const u of this.s.types.unions) if (u.name === name) return u.exported;
78
+ return true;
79
+ }
80
+ slotClassAt(path: string): string | null {
81
+ for (const entry of this.s.integer_slots) if (entry.slot === path) return entry.class;
82
+ return null;
83
+ }
84
+ slotClass(container: string, member: string): string | null { return this.slotClassAt(container + "." + member); }
85
+ nestedSlotClass(container: string, member: string, field: string): string | null { return this.slotClassAt(container + "." + member + "." + field); }
86
+ intWriter(container: string, member: string): string {
87
+ if (this.slotClass(container, member) === "u64") { this.use("w_u64"); return "nscfWU64"; }
88
+ this.use("w_i64"); return "nscfWI64";
89
+ }
90
+ run(): void {
91
+ const body = new FacadeEmitter(this.input, this.plan);
92
+ body.privateTypeDeclarations(); body.channelConsts(); body.unboundDecl(); body.helperWrappers(); body.entryPoints();
93
+ body.tagTable(); body.dispatchSurface(); body.channelEntries(); body.postCycle(); body.helperCall();
94
+ body.generatedTables(); body.codecSection(); body.bootState();
95
+ this.header(); this.imports(body); this.reexports(); this.raw(body.out);
96
+ }
97
+ header(): void { this.print(text.header, [commentText(this.s.entry), commentText(this.s.compiler_version), this.input.build_id_hex]); }
98
+ importPath(origin: string): string { return '"./' + tsString(origin) + '"'; }
99
+ groups(names: string[]): { origin: string; names: string[] }[] {
100
+ const groups: { origin: string; names: string[] }[] = [];
101
+ for (const name of names) {
102
+ const origin = this.originOf(name);
103
+ let group = groups.find(g => g.origin === origin);
104
+ if (group === undefined) { group = { origin, names: [] }; groups.push(group); }
105
+ group.names.push(name);
106
+ }
107
+ return groups;
108
+ }
109
+ imports(body: FacadeEmitter): void {
110
+ const values = ["initialModel as nscfInitialModel", "update as nscfUpdate"];
111
+ if (this.s.has_migrate) values.push("migrate as nscfMigrate");
112
+ if (this.s.has_subscriptions) values.push("subscriptions as nscfSubscriptions");
113
+ const c = this.s.channels;
114
+ if (c.command_msg) values.push("commandMsg as nscfChanCommandMsg");
115
+ if (c.frame_msg) values.push("frameMsg as nscfChanFrameMsg");
116
+ if (c.key_msg) values.push("keyMsg as nscfChanKeyMsg");
117
+ if (c.pinch_msg) values.push("pinchMsg as nscfChanPinchMsg");
118
+ if (c.drop_msg) values.push("dropMsg as nscfChanDropMsg");
119
+ for (const h of this.s.model_helpers) values.push(h.name + " as nscfH_" + h.name);
120
+ this.raw("\nimport {\n"); for (const value of values) this.print(" {s},\n", [value]);
121
+ this.print("}} from {s};\n", [this.importPath(this.entryBasename())]);
122
+ const ordered = [this.s.model, this.s.msg.name];
123
+ for (const name of body.referenced) if (!ordered.includes(name)) ordered.push(name);
124
+ for (const group of this.groups(ordered)) this.print("import type {{ {s} }} from {s};\n", [group.names.join(", "), this.importPath(group.origin)]);
125
+ const cmd = body.usedCodec.includes("cmd_encoder"), sub = body.usedCodec.includes("sub_encoder");
126
+ if (cmd && sub) this.raw('import type { Cmd as nscfCmd, Sub as nscfSub, DbText as nscfDbText } from "./sdk/core.ts";\n');
127
+ else if (cmd) this.raw('import type { Cmd as nscfCmd, DbText as nscfDbText } from "./sdk/core.ts";\n');
128
+ else if (sub) this.raw('import type { Sub as nscfSub, DbText as nscfDbText } from "./sdk/core.ts";\n');
129
+ if (body.needsPinchPhase) this.raw('import type { PinchPhase } from "./sdk/events.ts";\n');
130
+ if (c.drop_msg) this.raw('import type { FileDropPoint } from "./sdk/events.ts";\n');
131
+ this.needsPinchPhase = body.needsPinchPhase;
132
+ }
133
+ reexports(): void {
134
+ const ordered = [this.s.model, this.s.msg.name];
135
+ for (const r of this.s.types.structs) if (!this.plan.inlined.includes(r.name) && !this.isGeneratedOnlyType(r.name) && r.exported && !ordered.includes(r.name)) ordered.push(r.name);
136
+ for (const e of this.s.types.enums) if (!this.isGeneratedOnlyType(e.name) && e.exported && !ordered.includes(e.name)) ordered.push(e.name);
137
+ for (const u of this.s.types.unions) if (!this.isGeneratedOnlyType(u.name) && u.exported && !ordered.includes(u.name)) ordered.push(u.name);
138
+ this.raw(text.reexportPrelude);
139
+ for (const g of this.groups(ordered)) this.print("export type {{ {s} }} from {s};\n", [g.names.join(", "), this.importPath(g.origin)]);
140
+ }
141
+ privateTypeDeclarations(): void {
142
+ if (![...this.s.types.structs, ...this.s.types.enums, ...this.s.types.unions].some(e => !e.exported)) return;
143
+ this.raw(text.privateTypes);
144
+ for (const r of this.s.types.structs) {
145
+ if (r.exported) continue; this.print("type {s} = {{\n", [r.name]);
146
+ for (const f of r.fields) this.print(" readonly {s}: {s};\n", [tsProp(f.name), this.spellRef(f.type)]);
147
+ this.raw("};\n\n");
148
+ }
149
+ for (const e of this.s.types.enums) {
150
+ if (e.exported) continue; this.print("type {s} = ", [e.name]);
151
+ for (let i = 0; i < e.members.length; i++) this.print('{s}"{s}"', [i === 0 ? "" : " | ", tsString(e.members[i])]);
152
+ this.raw(";\n\n");
153
+ }
154
+ for (const u of this.s.types.unions) {
155
+ if (u.exported) continue; this.print("type {s} =\n", [u.name]);
156
+ for (const a of u.arms) {
157
+ this.print(' | {{ readonly kind: "{s}"', [tsString(a.name)]);
158
+ if (a.payload.kind !== "void") {
159
+ const r = this.synthesizedRecordOf(a.payload, u.name, a.name);
160
+ if (r !== null) for (const f of r.fields) this.print("; readonly {s}: {s}", [tsProp(f.name), this.spellRef(f.type)]);
161
+ else this.print("; readonly {s}: {s}", [tsProp(this.memberOf(a.member)), this.spellRef(a.payload)]);
162
+ }
163
+ this.raw(" }\n");
164
+ }
165
+ this.raw(";\n\n");
166
+ }
167
+ }
168
+ channelConsts(): void {
169
+ const c = this.s.channels;
170
+ if (c.appearance_msg === null && c.chrome_msg === null && c.env_msgs.length === 0) return;
171
+ this.raw(text.channels);
172
+ if (c.appearance_msg !== null) this.print('\nexport const appearanceMsg = "{s}";\n', [tsString(c.appearance_msg)]);
173
+ if (c.chrome_msg !== null) this.print('\nexport const chromeMsg = "{s}";\n', [tsString(c.chrome_msg)]);
174
+ if (c.env_msgs.length > 0) {
175
+ this.raw("\nexport const envMsgs = [\n");
176
+ for (const e of c.env_msgs) this.print(' {{ env: "{s}", msg: "{s}" }},\n', [tsString(e.env), tsString(e.msg)]);
177
+ this.raw("];\n");
178
+ }
179
+ }
180
+ unboundDecl(): void {
181
+ const model = findRecord(this.s, this.s.model)!;
182
+ const fields = this.s.model_unbound.filter(n => model.fields.some(f => f.name === n));
183
+ const helpers = this.s.model_unbound.filter(n => this.s.model_helpers.some(h => h.name === n));
184
+ if (fields.length === 0 && helpers.length === 0 && this.s.msg.unbound.length === 0) return;
185
+ this.raw(text.unbound);
186
+ for (const n of [...this.s.msg.unbound, ...fields, ...helpers]) this.print(' "{s}",\n', [tsString(n)]);
187
+ this.raw("];\n");
188
+ }
189
+ helperWrappers(): void {
190
+ if (this.s.model_helpers.length === 0) return;
191
+ this.raw(text.helperPrelude);
192
+ for (const h of this.s.model_helpers) {
193
+ const returns = this.spellRef(h.returns), optionalInt = h.returns.kind === "optional" && h.returns.inner!.kind === "i64";
194
+ if (h.params.length > 0) {
195
+ const params = h.params.map((p, index) => `p${index}: ${this.spellRef(p)}`);
196
+ const args = h.params.map((_p, index) => `p${index}`);
197
+ this.print("\nexport function {s}(model: {s}, {s}): {s} {{\n", [h.name, this.s.model, params.join(", "), returns]);
198
+ this.print(" const nscfValue = nscfH_{s}(model, {s});\n", [h.name, args.join(", ")]);
199
+ if (h.returns.kind === "i64" || optionalInt) {
200
+ if (optionalInt) this.raw(" if (nscfValue === null) return null;\n");
201
+ this.print(" if (nscfValue >= {s} && nscfValue <= {s}) return Math.trunc(nscfValue);\n", [lowerBound(this.nestedSlotClass("helpers", h.name, "return")), maxSafe]);
202
+ this.raw(' nscfTrap("a helper return is outside its attested integer range");\n');
203
+ this.use("trap");
204
+ } else this.print(" return nscfValue as {s};\n", [returns]);
205
+ this.raw("}\n");
206
+ } else if (h.returns.kind === "i64" || optionalInt) {
207
+ const lower = lowerBound(this.nestedSlotClass("helpers", h.name, "return"));
208
+ this.print(optionalInt ? text.helperOptionalInteger : text.helperInteger, optionalInt
209
+ ? [h.name, this.s.model, returns, h.name, lower, maxSafe] : [h.name, this.s.model, h.name, lower, maxSafe]);
210
+ this.use("trap");
211
+ } else if (h.returns.kind === "slice") this.print(text.helperSequence, [h.name, this.s.model, returns, h.name, returns]);
212
+ else this.print(text.helperValue, [h.name, this.s.model, returns, h.name]);
213
+ }
214
+ }
215
+ entryPoints(): void {
216
+ this.raw(text.entries);
217
+ if (this.s.init_returns_cmd) this.use("cmd_encoder");
218
+ this.print(this.s.init_returns_cmd ? (this.s.init_returns_bare ? text.initMixed : text.initCommand) : text.initModel, [this.s.model]);
219
+ }
220
+ tagTable(): void {
221
+ this.raw(text.messageTags); for (const a of this.s.msg.arms) this.print(' "{s}",\n', [tsString(a.name)]); this.raw("];\n\n");
222
+ for (let i = 0; i < this.s.msg.arms.length; i++) this.print("const nscfTag_{s} = {d};\n", [this.s.msg.arms[i].name, String(i)]);
223
+ this.use("trap"); this.raw(text.unknownTag);
224
+ if (this.s.update_returns_cmd) this.use("cmd_encoder");
225
+ this.print(this.s.update_returns_cmd ? (this.s.update_returns_bare ? text.updateMixed : text.updateCommand) : text.updateModel, [this.s.model, this.s.msg.name, this.s.model]);
226
+ if (this.s.has_subscriptions) { this.use("sub_encoder"); this.print(text.subscriptions, [this.s.model]); }
227
+ }
228
+ dispatchSurface(): void {
229
+ this.use("trap"); this.raw(text.dispatchPrelude);
230
+ this.print(this.s.update_returns_cmd ? text.commitCommand : text.commitModel, [this.s.model]);
231
+ this.raw(text.bootstrap); this.raw(this.s.init_returns_cmd ? text.bootCommand : text.bootEmpty);
232
+ this.dispatchVoid(); this.dispatchBytes(); this.dispatchNumber(); this.dispatchNumberBytes(); this.dispatchBool();
233
+ this.dispatchEnum(); this.dispatchRecord(); this.dispatchTextInput(); this.dispatchScrollState();
234
+ }
235
+ bootState(): void {
236
+ this.raw("\n// Boot after the command encoder's lookup tables are initialized.\n");
237
+ if (this.s.init_returns_cmd) this.print("const nscfBootPair = init();\nlet nscfCommitted: {s} = nscfBootPair[0];\n", [this.s.model]);
238
+ else this.print("let nscfCommitted: {s} = nscfInitialModel();\n", [this.s.model]);
239
+ }
240
+ commitLine(object: string): string { return "return nscfCommit(coreUpdate(nscfCommitted, " + object + "));"; }
241
+ armObject(arm: MsgArm, value: string): string {
242
+ return '{ kind: "' + tsString(arm.name) + '", ' + tsProp(this.memberOf(arm.member)) + ": " + value + " }";
243
+ }
244
+ dispatchVoid(): void {
245
+ this.raw("\nexport function dispatch_void(tag: number): Uint8Array {\n");
246
+ for (const a of this.s.msg.arms) if (a.payload.kind === "void")
247
+ this.print(" if (tag === nscfTag_{s}) {s}\n", [a.name, this.commitLine('{ kind: "' + tsString(a.name) + '" }')]);
248
+ this.raw(' nscfUnknownTag("bare", tag);\n}\n');
249
+ }
250
+ dispatchBytes(): void {
251
+ this.raw("\nexport function dispatch_bytes(tag: number, payload: Uint8Array): Uint8Array {\n");
252
+ for (const a of this.s.msg.arms) if (a.payload.kind === "bytes" || (a.payload.kind === "scalar" && a.payload.type!.kind === "bytes"))
253
+ this.print(" if (tag === nscfTag_{s}) {s}\n", [a.name, this.commitLine(this.armObject(a, "payload"))]);
254
+ this.raw(' nscfUnknownTag("bytes", tag);\n}\n');
255
+ }
256
+ dispatchNumber(): void {
257
+ this.raw("\nexport function dispatch_number(tag: number, value: number): Uint8Array {\n");
258
+ if (this.s.msg.arms.some(a => payloadNumberClass(a.payload) === "f64")) {
259
+ this.raw(" // These arms remain f64-classed in the contract: preserve the value\n // exactly instead of routing it through the integer proof below.\n");
260
+ for (const a of this.s.msg.arms) if (payloadNumberClass(a.payload) === "f64")
261
+ this.print(" if (tag === nscfTag_{s}) {s}\n", [a.name, this.commitLine(this.armObject(a, "value"))]);
262
+ }
263
+ for (const a of this.s.msg.arms) if (payloadNumberClass(a.payload) === "i64")
264
+ this.print(text.dispatchInteger, [a.name, lowerBound(this.slotClass(this.s.msg.name, a.name)), maxSafe, this.armObject(a, "whole")]);
265
+ this.raw(' nscfUnknownTag("number", tag);\n}\n');
266
+ }
267
+ dispatchNumberBytes(): void {
268
+ this.raw("\nexport function dispatch_number_bytes(tag: number, value: number, payload: Uint8Array): Uint8Array {\n");
269
+ for (const a of this.s.msg.arms) {
270
+ const p = a.payload; if (p.kind !== "number_bytes") continue;
271
+ const kind = tsString(a.name), number = tsProp(p.number_field!), bytes = tsProp(p.bytes_field!);
272
+ if (p.number_class === "i64") this.print(text.dispatchNumberBytesInteger, [a.name, lowerBound(this.nestedSlotClass(this.s.msg.name, a.name, p.number_field!)), maxSafe, kind, number, bytes]);
273
+ else this.print(' if (tag === nscfTag_{s}) return nscfCommit(coreUpdate(nscfCommitted, {{ kind: "{s}", {s}: value, {s}: payload }}));\n', [a.name, kind, number, bytes]);
274
+ }
275
+ this.raw(' nscfUnknownTag("number-with-bytes", tag);\n}\n');
276
+ }
277
+ dispatchBool(): void {
278
+ this.raw("\nexport function dispatch_bool(tag: number, value: number): Uint8Array {\n");
279
+ for (const a of this.s.msg.arms) if (a.payload.kind === "scalar" && a.payload.type!.kind === "bool")
280
+ this.print(" if (tag === nscfTag_{s}) {s}\n", [a.name, this.commitLine(this.armObject(a, "value !== 0"))]);
281
+ this.raw(' nscfUnknownTag("boolean", tag);\n}\n');
282
+ }
283
+ dispatchEnum(): void {
284
+ this.raw("\nexport function dispatch_enum(tag: number, member: number): Uint8Array {\n");
285
+ for (const a of this.s.msg.arms) if (a.payload.kind === "enum_ref") {
286
+ const name = a.payload.name!; this.needEnumTable(name);
287
+ this.print(text.dispatchEnumGuard, [a.name, name, tsString(name), this.commitLine(this.armObject(a, "nscfMembers" + name + "[member]!"))]);
288
+ this.needsMemberTrap = true;
289
+ }
290
+ this.raw(' nscfUnknownTag("enum", tag);\n}\n');
291
+ }
292
+ dispatchRecord(): void {
293
+ this.raw("\nexport function dispatch_record(tag: number, fields: Uint8Array): Uint8Array {\n");
294
+ for (const a of this.s.msg.arms) {
295
+ const p = a.payload;
296
+ if (p.kind === "record") {
297
+ const r = findRecord(this.s, p.name!); if (r === null) continue;
298
+ this.print(" if (tag === nscfTag_{s}) {{\n", [a.name]);
299
+ this.recordDecodeCommit(r, a.name, this.synthesizedRecordOf({ kind: "value", name: p.name! }, this.s.msg.name, a.name) !== null ? null : this.memberOf(a.member));
300
+ this.raw(" }\n");
301
+ } else if (p.kind === "union_ref") {
302
+ this.needUnionDecoder(p.name!);
303
+ this.print(' if (tag === nscfTag_{s}) return nscfCommit(coreUpdate(nscfCommitted, {{ kind: "{s}", {s}: nscfDecode{s}(fields) }}));\n', [a.name, tsString(a.name), tsProp(this.memberOf(a.member)), p.name!]);
304
+ }
305
+ }
306
+ this.raw(' nscfUnknownTag("record", tag);\n}\n');
307
+ }
308
+ dispatchTextInput(): void {
309
+ this.raw("\nexport function dispatch_text_input(tag: number, event: Uint8Array): Uint8Array {\n");
310
+ for (const a of this.s.msg.arms) if (a.payload.kind === "union_ref") {
311
+ this.needUnionDecoder(a.payload.name!);
312
+ this.print(' if (tag === nscfTag_{s}) return nscfCommit(coreUpdate(nscfCommitted, {{ kind: "{s}", {s}: nscfDecode{s}(event) }}));\n', [a.name, tsString(a.name), tsProp(this.memberOf(a.member)), a.payload.name!]);
313
+ }
314
+ this.raw(' nscfUnknownTag("text-input", tag);\n}\n');
315
+ }
316
+ dispatchScrollState(): void {
317
+ this.raw(text.scrollDispatch);
318
+ for (const a of this.s.msg.arms) {
319
+ const p = a.payload; if (p.kind !== "record" || scrollIndexes(this.s, p.name!) === null) continue;
320
+ const r = findRecord(this.s, p.name!)!, fields: string[] = [], guards: string[] = [];
321
+ for (const f of r.fields) {
322
+ const index = scrollFields[0].indexOf(f.name), snake = scrollFields[1].indexOf(f.name);
323
+ const param = index >= 0 ? scrollFields[0][index] : snake >= 0 ? scrollFields[0][snake] : f.name;
324
+ let value = param;
325
+ if (f.type.kind === "i64") {
326
+ guards.push(param + " >= " + lowerBound(this.slotClass(r.name, f.name)) + " && " + param + " <= " + maxSafe);
327
+ value = "Math.trunc(" + param + ")";
328
+ }
329
+ fields.push(tsProp(f.name) + ": " + value);
330
+ }
331
+ const flat = this.synthesizedRecordOf({ kind: "value", name: p.name! }, this.s.msg.name, a.name) !== null;
332
+ const object = '{ kind: "' + tsString(a.name) + '", ' + (flat ? fields.join(", ") : tsProp(this.memberOf(a.member)) + ": { " + fields.join(", ") + " }") + " }";
333
+ if (guards.length === 0) this.print(" if (tag === nscfTag_{s}) {s}\n", [a.name, this.commitLine(object)]);
334
+ else { this.print(text.scrollDispatchGuard, [a.name, guards.join(" && "), object]); this.use("trap"); }
335
+ }
336
+ this.raw(' nscfUnknownTag("scroll-state", tag);\n}\n');
337
+ }
338
+ channelEntries(): void {
339
+ const c = this.s.channels; this.use("sink"); this.use("trap");
340
+ this.print(text.messageEnvelope, [this.s.msg.name]); this.msgPayloadWriter();
341
+ if (c.key_msg || c.command_msg && !c.command_bytes) this.use("ascii_string");
342
+ if (c.command_msg) this.raw(c.command_bytes ? text.commandBytesEntry : text.commandEntry);
343
+ if (c.frame_msg) this.raw(this.s.abi.exports.includes("frame_msg_ns") ? text.frameEntryNs : text.frameEntry);
344
+ if (c.key_msg) this.raw(text.keyEntry);
345
+ if (c.pinch_msg) { this.needsPinchPhase = true; this.use("ascii_string"); this.raw(text.pinchEntry); this.needsMemberTrap = true; }
346
+ if (c.drop_msg) {
347
+ for (const id of ["read_f64", "read_u32", "read_bool", "read_bytes_body", "assert_consumed", "ascii_string"]) this.use(id);
348
+ this.raw(text.dropEntry);
349
+ }
350
+ }
351
+ msgPayloadWriter(): void {
352
+ this.print("\nfunction nscfMsgPayload(sink: nscfSink, value: {s}): void {{\n", [this.s.msg.name]);
353
+ for (const a of this.s.msg.arms) {
354
+ this.print(' if (value.kind === "{s}") {{\n', [tsString(a.name)]);
355
+ const p = a.payload, member = this.memberOf(a.member), access = tsAccess("value", member);
356
+ switch (p.kind) {
357
+ case "void": break;
358
+ case "bytes": this.use("w_bytes"); this.print(" nscfWBytes(sink, {s});\n", [access]); break;
359
+ case "number":
360
+ if (p.class === "i64") this.print(" {s}(sink, {s});\n", [this.intWriter(this.s.msg.name, a.name), access]);
361
+ else { this.use("w_f64"); this.print(" nscfWF64(sink, {s});\n", [access]); }
362
+ break;
363
+ case "number_bytes":
364
+ if (p.number_class === "i64") this.print(" {s}(sink, {s});\n", [this.intWriter(this.s.msg.name, a.name + "." + p.number_field!), tsAccess("value", p.number_field!)]);
365
+ else { this.use("w_f64"); this.print(" nscfWF64(sink, {s});\n", [tsAccess("value", p.number_field!)]); }
366
+ this.use("w_bytes"); this.print(" nscfWBytes(sink, {s});\n", [tsAccess("value", p.bytes_field!)]); break;
367
+ case "record": {
368
+ const r = findRecord(this.s, p.name!)!;
369
+ if (this.synthesizedRecordOf({ kind: "value", name: p.name! }, this.s.msg.name, a.name) !== null) {
370
+ for (const f of r.fields) this.fieldWriteStatements(f.type, tsAccess("value", f.name), r.name, f.name, 2);
371
+ } else { this.needRecordWriter(p.name!); this.print(" nscfWrite{s}(sink, {s});\n", [p.name!, access]); }
372
+ break;
373
+ }
374
+ case "union_ref": this.needUnionWriter(p.name!); this.print(" nscfWrite{s}(sink, {s});\n", [p.name!, access]); break;
375
+ case "enum_ref": this.needEnumIndex(p.name!); this.use("w_u32"); this.print(" nscfWU32(sink, nscfIndex{s}({s}));\n", [p.name!, access]); break;
376
+ case "scalar":
377
+ if (p.type!.kind === "i64") this.print(" {s}(sink, {s});\n", [this.intWriter(this.s.msg.name, a.name), access]);
378
+ else if (p.type!.kind === "bool") { this.use("w_bool"); this.print(" nscfWBool(sink, {s});\n", [access]); }
379
+ else if (p.type!.kind === "f64") { this.use("w_f64"); this.print(" nscfWF64(sink, {s});\n", [access]); }
380
+ else if (p.type!.kind === "bytes") { this.use("w_bytes"); this.print(" nscfWBytes(sink, {s});\n", [access]); }
381
+ else throw new Error("unsupported validated channel scalar");
382
+ break;
383
+ default: throw new Error("unknown channel payload");
384
+ }
385
+ this.raw(" return;\n }\n");
386
+ }
387
+ this.raw(' nscfTrap("a channel produced a message outside the declared union — the value and the contract disagree");\n}\n');
388
+ }
389
+ postCycle(): void {
390
+ this.raw("\n// --------------------------------------------------------- post-cycle\n");
391
+ this.raw(this.s.has_subscriptions ? text.subscriptionsAfterCycle : text.emptySubscriptions);
392
+ const model = findRecord(this.s, this.s.model)!;
393
+ this.use("sink"); this.use("w_u32"); this.use("w_bytes"); this.needRecordWriter(this.s.model);
394
+ this.print(text.snapshot, [this.s.model]);
395
+ this.print(text.persistPrelude, [this.input.snapshot_text, this.s.model, this.s.model, String(model.fields.length)]);
396
+ this.tempCounter = 0;
397
+ for (let i = 0; i < model.fields.length; i++) {
398
+ const f = model.fields[i], index = String(i);
399
+ this.print(" {{\n const nscfFieldSink{d} = nscfNewSink();\n {{\n const sink = nscfFieldSink{d};\n", [index, index]);
400
+ this.fieldWriteStatements(f.type, tsAccess("value", f.name), model.name, f.name, 3);
401
+ this.print(" }}\n nscfWU32(sink, {d});\n nscfWBytes(sink, nscfFinish(nscfFieldSink{d}));\n }}\n", [index, index]);
402
+ }
403
+ this.print(text.persistEnd, [this.s.model]);
404
+ this.print("\nfunction nscfDecodeSnapshot{s}(bytes: Uint8Array): {s} {{\n", [this.s.model, this.s.model]);
405
+ const decode = new RecordDecode(this, "bytes", 1, "0", false); decode.run(model);
406
+ this.use("assert_consumed"); this.print(" nscfAssertConsumed(bytes, {s});\n", [decode.offsetText()]);
407
+ const construction = decode.constructionText();
408
+ if (decode.guards.length > 0) {
409
+ this.print(' if ({s}) return {s};\n nscfTrap("a restored integer value is NaN or outside its attested exact-integer range — the snapshot cannot represent this Model");\n', [decode.guards.join(" && "), construction]);
410
+ this.use("trap");
411
+ } else this.print(" return {s};\n", [construction]);
412
+ this.raw("}\n"); this.raw(text.restorePrelude);
413
+ this.use("read_u32"); this.use("read_bytes_body"); this.use("trap");
414
+ this.print(' const nscfFieldCount = nscfReadU32(snapshot, nscfAt);\n nscfAt += 4;\n if (nscfFieldCount !== {d}) nscfTrap("a model snapshot carries the wrong field count for this Model");\n', [String(model.fields.length)]);
415
+ for (let i = 0; i < model.fields.length; i++) {
416
+ const index = String(i);
417
+ this.print(' const nscfFieldTag{d} = nscfReadU32(snapshot, nscfAt);\n nscfAt += 4;\n if (nscfFieldTag{d} !== {d}) nscfTrap("a model snapshot field tag does not match this Model");\n const nscfFieldLen{d} = nscfReadU32(snapshot, nscfAt);\n nscfAt += 4;\n const nscfFieldBytes{d} = nscfReadBytesBody(snapshot, nscfAt, nscfFieldLen{d});\n nscfAt += nscfFieldLen{d};\n for (let nscfFieldAt{d} = 0; nscfFieldAt{d} < nscfFieldBytes{d}.length; nscfFieldAt{d}++) sink.push(nscfFieldBytes{d}[nscfFieldAt{d}]!);\n',
418
+ [index, index, index, index, index, index, index, index, index, index, index, index, index]);
419
+ }
420
+ this.raw(text.restoreFieldsEnd); this.print(text.restoreFinish, [this.s.model]);
421
+ if (this.s.has_migrate) this.print(text.migration, [this.s.model]);
422
+ else this.raw(text.noMigration);
423
+ }
424
+ helperCall(): void {
425
+ this.use("trap"); this.use("assert_consumed");
426
+ if (this.s.model_helpers.length === 0) { this.raw(text.helperEmpty); return; }
427
+ const parameterized = this.s.model_helpers.some(h => h.params.length > 0);
428
+ this.use("sink"); this.raw(parameterized ? text.helperCallPrelude.replace(" nscfAssertConsumed(args, 0);\n", "") : text.helperCallPrelude);
429
+ for (let i = 0; i < this.s.model_helpers.length; i++) {
430
+ const h = this.s.model_helpers[i];
431
+ this.print(" if (helper === {d}) {{\n", [String(i)]);
432
+ let argumentsText = "";
433
+ let guards: string[] = [];
434
+ if (h.params.length > 0) {
435
+ const decode = new RecordDecode(this, "args", 2, "0", false);
436
+ for (let index = 0; index < h.params.length; index++) decode.fieldLocal(`p${index}`, h.params[index], "helpers", `${h.name}.params[${index}]`);
437
+ this.print(" nscfAssertConsumed(args, {s});\n", [decode.offsetText()]);
438
+ argumentsText = ", " + decode.exprs.map(p => p.text).join(", ");
439
+ guards = decode.guards;
440
+ } else if (parameterized) this.raw(" nscfAssertConsumed(args, 0);\n");
441
+ if (guards.length) this.print(" if ({s}) {{\n", [guards.join(" && ")]);
442
+ this.print(" const sink = nscfNewSink();\n const nscfValue = {s}(nscfCommitted{s});\n", [h.name, argumentsText]);
443
+ this.fieldWriteStatements(h.returns, "nscfValue", "helpers", h.name + ".return", 2);
444
+ this.raw(" return nscfFinish(sink);\n");
445
+ if (guards.length) this.raw(' }\n nscfTrap("a helper argument is outside its attested integer range");\n');
446
+ this.raw(" }\n");
447
+ }
448
+ this.raw(' nscfTrap("helper index " + helper + " does not name an exported model helper of this core — the host and this core disagree about the contract");\n}\n');
449
+ }
450
+ needEnumTable(name: string): void { if (!this.neededEnumTables.includes(name)) { this.neededEnumTables.push(name); this.reference(name); } }
451
+ needEnumIndex(name: string): void { this.needEnumTable(name); if (!this.neededEnumIndexes.includes(name)) this.neededEnumIndexes.push(name); }
452
+ needRecordWriter(name: string): void { if (!this.neededRecordWriters.includes(name)) { this.neededRecordWriters.push(name); this.reference(name); } }
453
+ needUnionWriter(name: string): void { if (!this.neededUnionWriters.includes(name)) { this.neededUnionWriters.push(name); this.reference(name); } }
454
+ needUnionDecoder(name: string): void { if (!this.neededUnionDecoders.includes(name)) { this.neededUnionDecoders.push(name); this.reference(name); } }
455
+ generatedTables(): void {
456
+ let header = false, enumAt = 0, enumIndexAt = 0, recordAt = 0, unionWriteAt = 0, unionDecodeAt = 0;
457
+ while (enumAt < this.neededEnumTables.length || enumIndexAt < this.neededEnumIndexes.length || recordAt < this.neededRecordWriters.length
458
+ || unionWriteAt < this.neededUnionWriters.length || unionDecodeAt < this.neededUnionDecoders.length) {
459
+ if (!header) { header = true; this.raw(text.generatedTablesPrelude); }
460
+ while (enumAt < this.neededEnumTables.length) this.enumTable(this.neededEnumTables[enumAt++]);
461
+ while (enumIndexAt < this.neededEnumIndexes.length) this.enumIndexFn(this.neededEnumIndexes[enumIndexAt++]);
462
+ while (recordAt < this.neededRecordWriters.length) this.recordWriter(this.neededRecordWriters[recordAt++]);
463
+ while (unionWriteAt < this.neededUnionWriters.length) this.unionWriter(this.neededUnionWriters[unionWriteAt++]);
464
+ while (unionDecodeAt < this.neededUnionDecoders.length) this.unionDecoder(this.neededUnionDecoders[unionDecodeAt++]);
465
+ }
466
+ if (this.needsMemberTrap) { this.use("trap"); this.raw(text.memberTrap); }
467
+ }
468
+ enumTable(name: string): void {
469
+ const entry = findEnum(this.s, name)!;
470
+ this.print("\nconst nscfMembers{s}: {s}[] = [", [name, name]);
471
+ for (let i = 0; i < entry.members.length; i++) this.print('{s}"{s}"', [i === 0 ? "" : ", ", tsString(entry.members[i])]);
472
+ this.raw("];\n");
473
+ }
474
+ enumIndexFn(name: string): void { this.use("trap"); this.print(text.enumIndex, [name, name, name, name]); }
475
+ fieldWriteStatements(ref: TypeRef, expr: string, container: string, member: string, depth: number): void {
476
+ const pad = this.indentText(depth);
477
+ switch (ref.kind) {
478
+ case "bool": this.use("w_bool"); this.print("{s}nscfWBool(sink, {s});\n", [pad, expr]); break;
479
+ case "i64": this.print("{s}{s}(sink, {s});\n", [pad, this.intWriter(container, member), expr]); break;
480
+ case "f64": this.use("w_f64"); this.print("{s}nscfWF64(sink, {s});\n", [pad, expr]); break;
481
+ case "bytes":
482
+ this.use("w_bytes");
483
+ if (this.isThemeStateAccent(container, member)) { this.use("utf8_text"); this.print("{s}nscfWBytes(sink, nscfUtf8TextBytes({s}));\n", [pad, expr]); }
484
+ else this.print("{s}nscfWBytes(sink, {s});\n", [pad, expr]);
485
+ break;
486
+ case "void": break;
487
+ case "optional": {
488
+ this.use("w_bool"); const temp = "nscfOpt" + this.tempCounter++;
489
+ this.print("{s}const {s} = {s};\n{s}if ({s} === null || {s} === undefined) {{\n{s} nscfWBool(sink, false);\n{s}}} else {{\n{s} nscfWBool(sink, true);\n", [pad, temp, expr, pad, temp, temp, pad, pad, pad]);
490
+ this.fieldWriteStatements(ref.inner!, temp, container, member, depth + 1); this.print("{s}}}\n", [pad]); break;
491
+ }
492
+ case "slice": {
493
+ this.use("w_u32"); const index = "nscfIdx" + this.tempCounter++;
494
+ this.print("{s}nscfWU32(sink, {s}.length);\n{s}for (let {s} = 0; {s} < {s}.length; {s}++) {{\n", [pad, expr, pad, index, index, expr, index]);
495
+ this.fieldWriteStatements(ref.elem!, expr + "[" + index + "]!", container, member, depth + 1); this.print("{s}}}\n", [pad]); break;
496
+ }
497
+ case "node": case "value": {
498
+ const name = ref.name!;
499
+ if (this.plan.flattened.includes(name)) {
500
+ const r = findRecord(this.s, name)!;
501
+ for (const f of r.fields) this.fieldWriteStatements(f.type, expr + "." + f.name, name, f.name, depth);
502
+ } else { this.needRecordWriter(name); this.print("{s}nscfWrite{s}(sink, {s});\n", [pad, name, expr]); }
503
+ break;
504
+ }
505
+ case "enum": this.needEnumIndex(ref.name!); this.use("w_u32"); this.print("{s}nscfWU32(sink, nscfIndex{s}({s}));\n", [pad, ref.name!, expr]); break;
506
+ case "union": this.needUnionWriter(ref.name!); this.print("{s}nscfWrite{s}(sink, {s});\n", [pad, ref.name!, expr]); break;
507
+ default: throw new Error("unknown writer type");
508
+ }
509
+ }
510
+ isThemeStateAccent(container: string, member: string): boolean {
511
+ if (member !== "accent") return false;
512
+ for (const h of this.s.model_helpers) if (h.name === "themeState")
513
+ return (h.returns.kind === "node" || h.returns.kind === "value") && h.returns.name === container;
514
+ return false;
515
+ }
516
+ recordWriter(name: string): void {
517
+ const r = findRecord(this.s, name)!; this.use("sink"); this.tempCounter = 0;
518
+ this.print("\nfunction nscfWrite{s}(sink: nscfSink, value: {s}): void {{\n", [name, name]);
519
+ for (const f of r.fields) this.fieldWriteStatements(f.type, tsAccess("value", f.name), name, f.name, 1);
520
+ this.raw("}\n");
521
+ }
522
+ unionWriter(name: string): void {
523
+ const u = findUnion(this.s, name)!; this.use("sink"); this.use("w_u8"); this.use("trap"); this.tempCounter = 0;
524
+ this.print("\nfunction nscfWrite{s}(sink: nscfSink, value: {s}): void {{\n", [name, name]);
525
+ for (let i = 0; i < u.arms.length; i++) {
526
+ const a = u.arms[i]; this.print(' if (value.kind === "{s}") {{\n nscfWU8(sink, {d});\n', [tsString(a.name), String(i)]);
527
+ if (a.payload.kind !== "void") {
528
+ const r = this.synthesizedRecordOf(a.payload, u.name, a.name);
529
+ if (r !== null) for (const f of r.fields) this.fieldWriteStatements(f.type, tsAccess("value", f.name), r.name, f.name, 2);
530
+ else this.fieldWriteStatements(a.payload, tsAccess("value", this.memberOf(a.member)), u.name, a.name, 2);
531
+ }
532
+ this.raw(" return;\n }\n");
533
+ }
534
+ this.print(' nscfTrap("{s} carries an arm outside its declared union — the value and the contract disagree");\n}}\n', [tsString(name)]);
535
+ }
536
+ recordDecodeCommit(r: RecordType, arm: string, member: string | null): void {
537
+ const decode = new RecordDecode(this, "fields", 2, "0", false); decode.run(r);
538
+ this.use("assert_consumed"); this.print(" nscfAssertConsumed(fields, {s});\n", [decode.offsetText()]);
539
+ const construction = decode.constructionText();
540
+ const object = member !== null ? '{ kind: "' + tsString(arm) + '", ' + tsProp(member) + ": " + construction + " }"
541
+ : '{ kind: "' + tsString(arm) + '",' + construction.slice(1, -1) + "}";
542
+ if (decode.guards.length > 0) {
543
+ this.print(' if ({s}) {{\n return nscfCommit(coreUpdate(nscfCommitted, {s}));\n }}\n nscfTrap("a decoded integer value is NaN or outside its attested exact-integer range — the integer slot has no honest value for it");\n', [decode.guards.join(" && "), object]);
544
+ this.use("trap");
545
+ } else this.print(" return nscfCommit(coreUpdate(nscfCommitted, {s}));\n", [object]);
546
+ }
547
+ unionDecoder(name: string): void {
548
+ const u = findUnion(this.s, name)!; this.use("trap"); this.use("assert_consumed");
549
+ this.print(text.unionDecoderPrelude, [name, name]);
550
+ for (let i = 0; i < u.arms.length; i++) {
551
+ const a = u.arms[i], kind = tsString(a.name); this.print(" if (arm === {d}) {{\n", [String(i)]);
552
+ if (a.payload.kind === "void") this.print(' nscfAssertConsumed(bytes, 1);\n return {{ kind: "{s}" }};\n', [kind]);
553
+ else {
554
+ const decode = new RecordDecode(this, "bytes", 2, "1", isTextInputUnion(this.s, name) && a.name === "set_selection");
555
+ const r = this.synthesizedRecordOf(a.payload, u.name, a.name); let construction = "";
556
+ if (r !== null) {
557
+ decode.run(r); const inner = decode.constructionText();
558
+ construction = '{ kind: "' + kind + '",' + inner.slice(1, -1) + "}";
559
+ } else {
560
+ decode.fieldLocal(this.memberOf(a.member), a.payload, u.name, a.name);
561
+ construction = '{ kind: "' + kind + '", ' + tsProp(this.memberOf(a.member)) + ": " + decode.exprs[0].text + " }";
562
+ }
563
+ this.print(" nscfAssertConsumed(bytes, {s});\n", [decode.offsetText()]);
564
+ if (decode.guards.length > 0) this.print(' if ({s}) {{\n return {s};\n }}\n nscfTrap("a decoded integer value is NaN or outside its attested exact-integer range — the integer slot has no honest value for it");\n', [decode.guards.join(" && "), construction]);
565
+ else this.print(" return {s};\n", [construction]);
566
+ }
567
+ this.raw(" }\n");
568
+ }
569
+ this.raw(' nscfTrap("a dispatched union payload carries a union arm index past the declared arms — the host and this core disagree about the contract");\n}\n');
570
+ }
571
+ codecSection(): void {
572
+ if (this.usedCodec.length === 0) return; this.raw(text.codecPrelude);
573
+ const snippets = [
574
+ { id: "trap", code: text.trap }, { id: "read_u8", code: text.readU8 }, { id: "read_u32", code: text.readU32 },
575
+ { id: "read_f64", code: text.readF64 }, { id: "read_i64", code: text.readI64 }, { id: "read_i64_saturating", code: text.readI64Saturating },
576
+ { id: "read_u64_saturating", code: text.readU64Saturating }, { id: "read_bool", code: text.readBool }, { id: "read_bytes_body", code: text.readBytesBody },
577
+ { id: "assert_consumed", code: text.assertConsumed }, { id: "trunc_toward_zero", code: text.truncTowardZero }, { id: "sink", code: text.sink },
578
+ { id: "w_u8", code: text.writeU8 }, { id: "w_u32", code: text.writeU32 }, { id: "w_f64", code: text.writeF64 },
579
+ { id: "w_i64", code: text.writeI64 }, { id: "w_u64", code: text.writeU64 }, { id: "w_bool", code: text.writeBool },
580
+ { id: "w_bytes", code: text.writeBytes }, { id: "short_text", code: text.shortText }, { id: "utf8_text", code: text.utf8Text },
581
+ { id: "ascii_string", code: text.asciiString }, { id: "enum_index", code: text.enumIndexCodec },
582
+ ];
583
+ for (const snippet of snippets) if (this.usedCodec.includes(snippet.id)) this.raw(snippet.code);
584
+ if (this.usedCodec.includes("cmd_encoder")) this.cmdEncoder();
585
+ if (this.usedCodec.includes("sub_encoder")) this.subEncoder();
586
+ }
587
+ cmdEncoder(): void { this.print(text.commandEncoderPrefix, [this.s.msg.name]); this.raw(text.commandEncoderBody); this.print(text.commandEncoderSuffix, [this.s.msg.name]); }
588
+ subEncoder(): void { this.print(text.subscriptionEncoder, [this.s.msg.name, this.s.msg.name]); }
589
+ spellRef(ref: TypeRef): string {
590
+ switch (ref.kind) {
591
+ case "bool": return "boolean";
592
+ case "f64": case "i64": return "number";
593
+ case "bytes": return "Uint8Array";
594
+ case "void": return "void";
595
+ case "optional": return this.spellRef(ref.inner!) + " | null";
596
+ case "slice": {
597
+ const elem = this.spellRef(ref.elem!);
598
+ return (elem.includes(" ") || elem.includes("|") ? "(" + elem + ")" : elem) + "[]";
599
+ }
600
+ case "node": case "value": case "enum": case "union": this.reference(ref.name!); return ref.name!;
601
+ default: throw new Error("unknown facade type");
602
+ }
603
+ }
604
+ indentText(depth: number): string { return " ".repeat(depth * 2); }
605
+ synthesizedRecordOf(ref: TypeRef, container: string, member: string): RecordType | null {
606
+ if (ref.kind !== "value" || !synthesized(container, member, ref.name!) || !this.plan.inlined.includes(ref.name!)) return null;
607
+ const r = findRecord(this.s, ref.name!); return r !== null && r.origin === null ? r : null;
608
+ }
609
+ }
610
+
611
+ class RecordDecode {
612
+ em: FacadeEmitter; buf: string; indent: number; start: string; saturatingSelection: boolean;
613
+ localCount: number = 0; cursorStarted: boolean = false;
614
+ guards: string[] = []; exprs: { name: string; text: string }[] = [];
615
+ constructor(em: FacadeEmitter, buf: string, indent: number, start: string, saturatingSelection: boolean) {
616
+ this.em = em; this.buf = buf; this.indent = indent; this.start = start; this.saturatingSelection = saturatingSelection;
617
+ }
618
+ offsetText(): string { return "nscfAt"; }
619
+ nextLocal(): string { return "nscfV" + this.localCount++; }
620
+ line(code: string, args: string[]): void { this.em.raw(this.em.indentText(this.indent)); this.em.print(code, args); }
621
+ ensureCursor(): void { if (!this.cursorStarted) { this.cursorStarted = true; this.line("let nscfAt = {s};\n", [this.start]); } }
622
+ advance(amount: string): void { this.line("nscfAt += {s};\n", [amount]); }
623
+ addGuard(guards: string[], local: string, className: string | null): void {
624
+ guards.push(local + " >= " + lowerBound(className) + " && " + local + " <= " + maxSafe);
625
+ }
626
+ guardedStatement(guards: string[], statement: string): void {
627
+ if (guards.length === 0) { this.line("{s}\n", [statement]); return; }
628
+ this.line("if ({s}) {{\n", [guards.join(" && ")]); this.indent++; this.line("{s}\n", [statement]); this.indent--;
629
+ this.line("}} else {{\n", []); this.indent++;
630
+ this.line('nscfTrap("a decoded integer value is NaN or outside its attested exact-integer range — the integer slot has no honest value for it");\n', []);
631
+ this.indent--; this.line("}}\n", []); this.em.use("trap");
632
+ }
633
+ run(r: RecordType): void { this.ensureCursor(); for (const f of r.fields) this.fieldLocal(f.name, f.type, r.name, f.name); }
634
+ fieldLocal(name: string, ref: TypeRef, container: string, member: string): void {
635
+ this.ensureCursor(); this.exprs.push({ name, text: this.decodeRef(ref, name, container, member, this.guards) });
636
+ }
637
+ decodeRecord(r: RecordType, guards: string[]): string {
638
+ const parts: string[] = [];
639
+ for (const f of r.fields) parts.push(tsProp(f.name) + ": " + this.decodeRef(f.type, f.name, r.name, f.name, guards));
640
+ return "{ " + parts.join(", ") + " }";
641
+ }
642
+ decodeUnion(name: string): string {
643
+ const u = findUnion(this.em.s, name)!; this.em.use("read_u8"); this.em.reference(name);
644
+ const tag = this.nextLocal(); this.line("const {s} = nscfReadU8({s}, nscfAt);\n", [tag, this.buf]); this.advance("1");
645
+ const local = this.nextLocal(); this.line("let {s}: {s};\n", [local, name]);
646
+ for (let i = 0; i < u.arms.length; i++) {
647
+ const a = u.arms[i]; this.line("{s}if ({s} === {d}) {{\n", [i === 0 ? "" : "else ", tag, String(i)]); this.indent++;
648
+ const guards: string[] = []; let object = "";
649
+ if (a.payload.kind === "void") object = '{ kind: "' + tsString(a.name) + '" }';
650
+ else {
651
+ const r = this.em.synthesizedRecordOf(a.payload, u.name, a.name);
652
+ if (r !== null) { const inner = this.decodeRecord(r, guards); object = '{ kind: "' + tsString(a.name) + '",' + inner.slice(1, -1) + "}"; }
653
+ else {
654
+ const value = this.decodeRef(a.payload, this.em.memberOf(a.member), u.name, a.name, guards);
655
+ object = '{ kind: "' + tsString(a.name) + '", ' + tsProp(this.em.memberOf(a.member)) + ": " + value + " }";
656
+ }
657
+ }
658
+ this.guardedStatement(guards, local + " = " + object + ";"); this.indent--; this.line("}}\n", []);
659
+ }
660
+ this.line("else {{\n", []); this.indent++;
661
+ this.line('nscfTrap("a dispatched union payload carries a union arm index past the declared arms — the host and this core disagree about the contract");\n', []);
662
+ this.indent--; this.line("}}\n", []); this.em.use("trap"); return local;
663
+ }
664
+ decodeRef(ref: TypeRef, fieldName: string, container: string, member: string, guards: string[]): string {
665
+ const em = this.em;
666
+ switch (ref.kind) {
667
+ case "f64": {
668
+ em.use("read_f64"); const local = this.nextLocal();
669
+ this.line("const {s} = nscfReadF64({s}, nscfAt);\n", [local, this.buf]); this.advance("8"); return local;
670
+ }
671
+ case "i64": {
672
+ const className = em.slotClass(container, member), selection = fieldName === "anchor" || fieldName === "focus";
673
+ const reader = this.saturatingSelection && selection ? (className === "u64" ? "read_u64_saturating" : "read_i64_saturating") : "read_i64";
674
+ const readerName = reader === "read_u64_saturating" ? "nscfReadU64Saturating" : reader === "read_i64_saturating" ? "nscfReadI64Saturating" : "nscfReadI64";
675
+ em.use(reader); const local = this.nextLocal();
676
+ this.line("const {s} = {s}({s}, nscfAt);\n", [local, readerName, this.buf]); this.advance("8");
677
+ this.addGuard(guards, local, className); return "Math.trunc(" + local + ")";
678
+ }
679
+ case "bool": {
680
+ em.use("read_bool"); const local = this.nextLocal();
681
+ this.line("const {s} = nscfReadBool({s}, nscfAt);\n", [local, this.buf]); this.advance("1"); return local;
682
+ }
683
+ case "bytes": {
684
+ em.use("read_u32"); em.use("read_bytes_body"); const len = this.nextLocal();
685
+ this.line("const {s} = nscfReadU32({s}, nscfAt);\n", [len, this.buf]); this.advance("4"); const local = this.nextLocal();
686
+ this.line("const {s} = nscfReadBytesBody({s}, nscfAt, {s});\n", [local, this.buf, len]); this.advance(len); return local;
687
+ }
688
+ case "enum": {
689
+ const name = ref.name!; em.use("read_u32"); em.needEnumTable(name); em.needsMemberTrap = true; const local = this.nextLocal();
690
+ this.line("const {s} = nscfReadU32({s}, nscfAt);\n", [local, this.buf]);
691
+ this.line('if ({s} >= nscfMembers{s}.length) nscfMember("{s}", {s});\n', [local, name, tsString(name), local]); this.advance("4");
692
+ return "nscfMembers" + name + "[" + local + "]!";
693
+ }
694
+ case "node": case "value": return this.decodeRecord(findRecord(em.s, ref.name!)!, guards);
695
+ case "optional": {
696
+ em.use("read_bool"); const present = this.nextLocal();
697
+ this.line("const {s} = nscfReadBool({s}, nscfAt);\n", [present, this.buf]); this.advance("1"); const local = this.nextLocal();
698
+ this.line("let {s}: {s} | null = null;\n", [local, em.spellRef(ref.inner!)]); this.line("if ({s}) {{\n", [present]); this.indent++;
699
+ const innerGuards: string[] = [], value = this.decodeRef(ref.inner!, fieldName, container, member, innerGuards);
700
+ this.guardedStatement(innerGuards, local + " = " + value + ";"); this.indent--; this.line("}}\n", []); return local;
701
+ }
702
+ case "slice": {
703
+ em.use("read_u32"); const len = this.nextLocal(); this.line("const {s} = nscfReadU32({s}, nscfAt);\n", [len, this.buf]); this.advance("4");
704
+ const local = this.nextLocal(); this.line("const {s}: {s} = [];\n", [local, em.spellRef(ref)]); const index = this.nextLocal();
705
+ this.line("for (let {s} = 0; {s} < {s}; {s}++) {{\n", [index, index, len, index]); this.indent++;
706
+ const elemGuards: string[] = [], value = this.decodeRef(ref.elem!, fieldName, container, member, elemGuards);
707
+ this.guardedStatement(elemGuards, local + ".push(" + value + ");"); this.indent--; this.line("}}\n", []); return local;
708
+ }
709
+ case "union": return this.decodeUnion(ref.name!);
710
+ default: throw new Error("unknown decoded type");
711
+ }
712
+ }
713
+ constructionText(): string { return "{ " + this.exprs.map(e => tsProp(e.name) + ": " + e.text).join(", ") + " }"; }
714
+ }