@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,980 @@
1
+ /** Native markup compiled beside the committed TypeScript core. Unsupported
2
+ * constructs fail at build time; no bindings are evaluated by the native host.
3
+ */
4
+ import { portableSourceText } from "./portable_sources.ts";
5
+
6
+ interface Ref { kind: string; name?: string; elem?: Ref; inner?: Ref; class?: string; type?: Ref }
7
+ interface Arm { name: string; member?: string; payload: Ref }
8
+ export interface ViewContract {
9
+ model: string;
10
+ types: { structs: { name: string; fields: { name: string; type: Ref }[] }[]; enums?: { name: string; members: string[] }[]; unions?: { name: string; arms?: Arm[] }[] };
11
+ model_helpers: { name: string; params: Ref[]; returns: Ref }[];
12
+ msg: { name?: string; arms: Arm[] };
13
+ }
14
+ interface Element { name: string; attrs: Map<string, string>; children: Element[]; content: (Element | { text: string; at: number; end: number })[]; text: string; at: number; end: number; file: string }
15
+ interface Expr { code: string; type: Ref; virtualIndex?: string }
16
+ type Scope = ReadonlyMap<string, Expr>;
17
+ interface Slot { children: Element[]; scope: Scope; slot?: Slot }
18
+ export interface ViewSources { entry?: string; sources?: ReadonlyMap<string, string> }
19
+
20
+ export interface WindowViewSource extends ViewSources { label: string; source: string }
21
+
22
+ const colorTokenNames = ["background", "surface", "surface_subtle", "surface_pressed", "text", "text_muted", "syntax_plain", "syntax_comment", "syntax_keyword", "syntax_literal", "syntax_function", "syntax_property", "syntax_constant", "border", "accent", "accent_text", "destructive", "destructive_text", "success", "success_text", "warning", "warning_text", "info", "info_text", "focus_ring", "shadow", "scrim", "disabled"];
23
+
24
+ const nonHitTargetNames = ["row", "column", "stack", "list", "grid", "split", "tree", "breadcrumb", "button-group", "pagination", "radio-group", "tabs", "toggle-group", "badge", "avatar", "tooltip", "separator", "spacer", "table", "data-grid", "table-row", "skeleton", "spinner", "icon"];
25
+
26
+ export function compileView(source: string, contract: ViewContract, options: ViewSources = {}): string {
27
+ return compileViewBundle(source, contract, options, []);
28
+ }
29
+
30
+ /** One shared prelude, primary view, and a closed label-addressed window set.
31
+ * Window source paths are relative to src/windows, preserving its import boundary.
32
+ */
33
+ export function compileViewBundle(source: string, contract: ViewContract, options: ViewSources,
34
+ windows: readonly WindowViewSource[]): string {
35
+ let generated = viewPrelude + compileViewFunction(source, contract, options, "nscvMainView", false) +
36
+ "export function native_view(): Uint8Array { return nscvMainView(nscvEmptyVideo()); }\n" +
37
+ "export function native_media_view(request: Uint8Array): Uint8Array { return nscvMainView(nscvVideoState(request)); }\n";
38
+ const labels = new Set<string>();
39
+ const branches: string[] = [];
40
+ for (const [index, window] of windows.entries()) {
41
+ if (!window.label || new TextEncoder().encode(window.label).length > 64 ||
42
+ /[\\/\0]/.test(window.label) || [".", ".."].includes(window.label) || labels.has(window.label)) {
43
+ throw new Error("compiled TypeScript view: invalid or duplicate window label");
44
+ }
45
+ labels.add(window.label);
46
+ generated += compileViewFunction(window.source, contract, window, `nscvWindow${index}`, false);
47
+ branches.push(`if (nscvWindowLabel(label, ${JSON.stringify(window.label)})) return nscvWindow${index}(nscvVideo);`);
48
+ }
49
+ const virtual = [source, ...options.sources?.values() ?? [], ...windows.flatMap(window => [window.source, ...window.sources?.values() ?? []])].some(value => /<virtual-window\b/.test(value));
50
+ if (windows.length === 0 && !virtual) return generated;
51
+ generated += `function nscvWindowLabel(label: Uint8Array, expected: string): boolean { const bytes = new TextEncoder().encode(expected); if (label.length !== bytes.length) return false; for (let i = 0; i < bytes.length; i++) if (label[i] !== bytes[i]) return false; return true; }\n`;
52
+ if (windows.length) generated +=
53
+ `function nscvWindowView(label: Uint8Array, nscvVideo: NscVideoPlaybackState): Uint8Array {\n${branches.join("\n")}\nthrow new Error("unknown compiled window view label");\n}\n` +
54
+ `export function native_window_view(label: Uint8Array): Uint8Array { return nscvWindowView(label, nscvEmptyVideo()); }\n` +
55
+ `export function native_media_window_view(label: Uint8Array, request: Uint8Array): Uint8Array { return nscvWindowView(label, nscvVideoState(request)); }\n`;
56
+ if (virtual) generated += `function nscvVirtualView(label: Uint8Array, nscvVideo: NscVideoPlaybackState, nscvVirtual: NscVirtualBuild): Uint8Array {\nif (label.length === 0) return nscvMainView(nscvVideo, nscvVirtual);\n${windows.map((window, index) => `if (nscvWindowLabel(label, ${JSON.stringify(window.label)})) return nscvWindow${index}(nscvVideo, nscvVirtual);`).join("\n")}\nthrow new Error("unknown compiled virtual window label");\n}\n` +
57
+ `export function native_virtual_requests(label: Uint8Array, video: Uint8Array): Uint8Array { return nscvVirtualView(label, nscvVideoState(video), { requestsOnly: true, requests: [], ranges: [], consumed: [] }); }\n` +
58
+ `export function native_virtual_view(label: Uint8Array, context: Uint8Array, video: Uint8Array): Uint8Array { return nscvVirtualView(label, nscvVideoState(video), nscvVirtualContext(context)); }\n`;
59
+ return generated;
60
+ }
61
+
62
+ function compileViewFunction(source: string, contract: ViewContract, options: ViewSources, functionName: string, exported: boolean): string {
63
+ const entry = options.entry ?? "app.native";
64
+ const sources = new Map(options.sources); sources.set(entry, source);
65
+ const fail: (node: Pick<Element, "file" | "at">, message: string) => never = (node, message) => {
66
+ const before = sources.get(node.file)!.slice(0, node.at).split("\n");
67
+ throw new Error(`${node.file}:${before.length}:${before.at(-1)!.length + 1}: compiled TypeScript view: ${message}`);
68
+ };
69
+ const origin = { file: entry, at: 0 };
70
+ const reserved = ["NscAppearanceColor", "NscAppearanceVisual", "NscAppearanceContext", "NscViewSpan", "NscViewNode", "NscChartSeries", "NscChartDecimal", "NscChartSource", "NscChartPlan", "NscChartPrepared", "NscTimelineItem", "NscComponentText", "NscSurfaceRect", "native_view", "native_window_view", "native_media_view", "native_media_window_view", "native_virtual_requests", "native_virtual_view", "NscVirtualRequest", "NscVirtualRange", "NscVirtualBuild", "nscvMainView", "NscVideoPlaybackState", "native_radio_policy", "native_tabs_policy", "native_tree_policy", "native_list_policy", "native_menu_policy", "native_toggle_policy", "native_accordion_policy", "native_slider_policy", "native_split_policy", "native_scroll_policy", "native_resizable_policy", "native_text_policy", "native_timer_policy", "native_db_policy", "native_effect_policy", "native_stream_policy", "native_window_policy", "native_theme_policy", "native_status_policy", "JSON", "TextEncoder", "TextDecoder", "DataView", "String", "Number", "Array"];
71
+ const names = [...contract.types.structs, ...contract.types.enums ?? [], ...contract.types.unions ?? [], ...contract.model_helpers];
72
+ if (names.some(item => reserved.includes(item.name) || (item.name.startsWith("nscv") || item.name.startsWith("nscMd") || item.name.startsWith("NscMd") || item.name.startsWith("NscAudit"))) || reserved.includes(contract.msg.name ?? "")) {
73
+ fail(origin, "core name collides with compiled view wiring");
74
+ }
75
+ let count = 0, sourceBytes = 0;
76
+ const parse = (file: string): Element[] => {
77
+ const src = sources.get(file)!;
78
+ sourceBytes += new TextEncoder().encode(src).length;
79
+ if (sourceBytes > 64 * 1024) fail({ file, at: 0 }, "source closure exceeds 64 KiB");
80
+ let pos = 0;
81
+ const error: (message: string) => never = message => fail({ file, at: pos }, message);
82
+ const decode = (raw: string): string => raw.replace(/&([^;\s]*);|&/g, (_all, entity: string | undefined) => {
83
+ const known: Record<string, string> = { amp: "&", lt: "<", gt: ">", quot: '"', apos: "'" };
84
+ if (entity && Object.hasOwn(known, entity)) return known[entity]!;
85
+ return error(`unsupported entity &${entity ?? ""};`);
86
+ });
87
+ const skip = () => {
88
+ for (;;) {
89
+ while (/\s/.test(src[pos] ?? "") && pos < src.length) pos++;
90
+ if (!src.startsWith("<!--", pos)) return;
91
+ const end = src.indexOf("-->", pos + 4);
92
+ if (end < 0) error("unterminated comment");
93
+ pos = end + 3;
94
+ }
95
+ };
96
+ const element = (depth: number): Element => {
97
+ skip();
98
+ const at = pos;
99
+ if (depth > 64 || ++count > 1024) error("view exceeds 64 levels or 1024 elements");
100
+ const start = /^<([a-z][a-z0-9-]*)\b/.exec(src.slice(pos));
101
+ if (!start) error("expected an element");
102
+ pos += start[0].length;
103
+ const node: Element = { name: start[1]!, attrs: new Map(), children: [], content: [], text: "", at, end: at, file };
104
+ for (;;) {
105
+ while (/\s/.test(src[pos] ?? "") && pos < src.length) pos++;
106
+ if (src.startsWith("/>", pos)) { pos += 2; node.end = pos; return node; }
107
+ if (src[pos] === ">") { pos++; break; }
108
+ const attr = /^([a-z][a-z0-9-]*)\s*=\s*"([^"]*)"/.exec(src.slice(pos));
109
+ if (!attr) error("expected a quoted attribute or >");
110
+ if (node.attrs.has(attr[1]!)) error(`duplicate attribute ${attr[1]}`);
111
+ node.attrs.set(attr[1]!, decode(attr[2]!)); pos += attr[0].length;
112
+ }
113
+ for (;;) {
114
+ if (pos >= src.length) fail(node, `unclosed <${node.name}>`);
115
+ if (src.startsWith("<!--", pos)) {
116
+ const end = src.indexOf("-->", pos + 4);
117
+ if (end < 0) error("unterminated comment");
118
+ pos = end + 3; continue;
119
+ }
120
+ if (src.startsWith("</", pos)) {
121
+ const close = /^<\/([a-z][a-z0-9-]*)\s*>/.exec(src.slice(pos));
122
+ if (!close || close[1] !== node.name) error(`expected </${node.name}>`);
123
+ pos += close[0].length; node.end = pos; return node;
124
+ }
125
+ if (src[pos] === "<") { const child = element(depth + 1); node.children.push(child); node.content.push(child); }
126
+ else {
127
+ const end = src.indexOf("<", pos), stop = end < 0 ? src.length : end;
128
+ const value = decode(src.slice(pos, stop)); node.text += value; node.content.push({ text: value, at: pos, end: stop }); pos = stop;
129
+ }
130
+ }
131
+ };
132
+ const nodes: Element[] = []; skip();
133
+ while (pos < src.length) { nodes.push(element(0)); skip(); }
134
+ return nodes;
135
+ };
136
+ const templates = new Map<string, Element>(), loaded = new Set<string>();
137
+ const load = (file: string, stack: string[]): Element[] => {
138
+ if (stack.includes(file)) fail({ file, at: 0 }, "cyclic markup import");
139
+ if (loaded.has(file)) return [];
140
+ loaded.add(file);
141
+ const roots: Element[] = [];
142
+ for (const node of parse(file)) {
143
+ if (node.name === "import") {
144
+ if (node.attrs.size !== 1 || !node.attrs.has("src") || node.children.length || node.text.trim()) fail(node, "import requires only src");
145
+ const raw = node.attrs.get("src")!;
146
+ if (!raw || raw.startsWith("/") || /[\\:\0]/.test(raw)) fail(node, "import must be a relative markup path");
147
+ const parts = file.split("/").slice(0, -1);
148
+ for (const part of raw.split("/")) {
149
+ if (part === "..") { if (!parts.length) fail(node, "import escapes the source directory"); parts.pop(); }
150
+ else if (part && part !== ".") parts.push(part);
151
+ }
152
+ const target = parts.join("/");
153
+ if (!sources.has(target)) fail(node, `missing imported source ${target}`);
154
+ if (load(target, [...stack, file]).length) fail(node, "imported files may contain only imports and templates");
155
+ } else if (node.name === "template") {
156
+ const name = node.attrs.get("name");
157
+ if (!name || !/^[a-z][a-z0-9-]*$/.test(name) || templates.has(name)) fail(node, "invalid or duplicate template name");
158
+ if ([...node.attrs.keys()].some(key => key !== "name" && key !== "args") || node.text.trim()) fail(node, "template accepts only name, args and child elements");
159
+ templates.set(name, node);
160
+ } else roots.push(node);
161
+ }
162
+ return roots;
163
+ };
164
+ const roots = load(entry, []);
165
+ if (roots.length !== 1) fail(origin, "expected exactly one root element");
166
+ const fields = contract.types.structs.find(item => item.name === contract.model)?.fields;
167
+ if (!fields) fail(origin, "contract has no model fields");
168
+ const rangeFields = ["start_index", "end_index", "first_visible_index", "last_visible_index", "item_extent", "item_gap", "scroll_offset", "layout_offset", "content_extent", "before_extent", "after_extent", "anchor_extent"];
169
+ const rangeType = (ref: Ref): boolean => {
170
+ const record = ["node", "value"].includes(ref.kind) ? contract.types.structs.find(item => item.name === ref.name) : undefined;
171
+ return !!record && record.fields.length === 12 && record.fields.every((field, i) => field.name === rangeFields[i] && (i < 4 ? ["i64", "f64"].includes(field.type.kind) : field.type.kind === "f64"));
172
+ };
173
+ const category = (ref: Ref): string => ["i64", "f64"].includes(ref.kind) ? "number" : ref.kind === "bool" ? "boolean" : ref.kind;
174
+ const path = (raw: string, node: Element, scope: Scope): Expr => {
175
+ if (!/^[A-Za-z_][A-Za-z0-9_]*(?:\.[A-Za-z_][A-Za-z0-9_]*)*$/.test(raw)) fail(node, `unsupported binding path ${raw}`);
176
+ const [name, ...members] = raw.split(".");
177
+ const field = fields!.find(item => item.name === name);
178
+ const helper = contract.model_helpers.find(item => item.name === name && item.params.length === 0);
179
+ let value = scope.get(name!) ?? (field ? { code: `nscfCommitted[${JSON.stringify(name)}]`, type: field.type } : helper ? { code: `${name}(nscfCommitted)`, type: helper.returns } : null);
180
+ if (!value) fail(node, `unknown binding ${name}`);
181
+ for (const member of members) {
182
+ const record: ViewContract["types"]["structs"][number] | undefined = ["node", "value"].includes(value.type.kind) ? contract.types.structs.find(item => item.name === value!.type.name) : undefined;
183
+ const next: { name: string; type: Ref } | undefined = record?.fields.find(item => item.name === member);
184
+ if (!next) fail(node, `unsupported field ${member} on ${raw}`);
185
+ value = { code: `${value.code}[${JSON.stringify(member)}]`, type: next.type };
186
+ }
187
+ return value;
188
+ };
189
+ const expression = (raw: string, node: Element, scope: Scope): Expr => {
190
+ const tokens: string[] = []; let offset = 0;
191
+ while (offset < raw.length) {
192
+ const token = /^\s*('[^'\\]*'|\d+(?:\.\d+)?|[A-Za-z_][A-Za-z0-9_]*(?:\.[A-Za-z_][A-Za-z0-9_]*)*|===|!==|==|!=|<=|>=|&&|\|\||[()!+*\/<>=-])/.exec(raw.slice(offset));
193
+ if (!token) { if (!raw.slice(offset).trim()) break; fail(node, `unsupported expression ${raw}`); }
194
+ tokens.push(({ and: "&&", or: "||", not: "!" } as Record<string, string>)[token[1]!] ?? token[1]!); offset += token[0].length;
195
+ if (tokens.length > 128) fail(node, "expression exceeds 128 tokens");
196
+ }
197
+ let cursor = 0;
198
+ const precedences: Record<string, number> = { "||": 1, "&&": 2, "===": 3, "!==": 3, "==": 3, "!=": 3, "<": 4, "<=": 4, ">": 4, ">=": 4, "+": 5, "-": 5, "*": 6, "/": 6 };
199
+ const parseExpr = (min: number): Expr => {
200
+ const token = tokens[cursor++]; let left: Expr;
201
+ if (token === "(") { left = parseExpr(0); if (tokens[cursor++] !== ")") fail(node, "expected )"); }
202
+ else if (token === "!" || token === "-") {
203
+ const inner = parseExpr(7), expected = token === "!" ? "boolean" : "number";
204
+ if (category(inner.type) !== expected) fail(node, `${token} requires ${expected}`);
205
+ left = { code: `(${token}${inner.code})`, type: { kind: token === "!" ? "bool" : "f64" } };
206
+ } else if (token === "true" || token === "false") left = { code: token, type: { kind: "bool" } };
207
+ else if (token?.startsWith("'")) left = { code: JSON.stringify(token.slice(1, -1)), type: { kind: "string", name: token.slice(1, -1) } };
208
+ else if (token && /^\d/.test(token)) {
209
+ if (!Number.isFinite(Number(token))) fail(node, "non-finite literal");
210
+ left = { code: token, type: { kind: token.includes(".") ? "f64" : "i64" } };
211
+ } else left = path(token ?? "", node, scope);
212
+ for (;;) {
213
+ const op = tokens[cursor], precedence = op && Object.hasOwn(precedences, op) ? precedences[op] : undefined;
214
+ if (precedence === undefined || precedence < min) break;
215
+ cursor++; const right = parseExpr(precedence + 1);
216
+ const logical = op === "&&" || op === "||", equality = ["==", "!=", "===", "!=="].includes(op!);
217
+ const comparison = ["<", "<=", ">", ">="].includes(op!);
218
+ let valid = category(left.type) === category(right.type) && (logical ? category(left.type) === "boolean" : category(left.type) === "number" || equality && category(left.type) === "boolean");
219
+ if (equality && left.type.kind === "enum" && right.type.kind === "enum") {
220
+ valid = left.type.name === right.type.name;
221
+ } else if (equality && [left.type.kind, right.type.kind].includes("enum")) {
222
+ const enumRef = left.type.kind === "enum" ? left : right, literal = left.type.kind === "string" ? left : right;
223
+ valid = literal.type.kind === "string" && !!contract.types.enums?.find(item => item.name === enumRef.type.name)?.members.includes(literal.type.name!);
224
+ }
225
+ if (!valid) fail(node, `invalid operands for ${op}`);
226
+ left = { code: `(${left.code} ${op === "==" ? "===" : op === "!=" ? "!==" : op} ${right.code})`, type: { kind: logical || equality || comparison ? "bool" : "f64" } };
227
+ }
228
+ return left;
229
+ };
230
+ const result = parseExpr(0);
231
+ if (cursor !== tokens.length) fail(node, `unsupported expression ${raw}`);
232
+ return result;
233
+ };
234
+ const binding = (raw: string, node: Element, scope: Scope): Expr => expression(/^\{([^{}]*)\}$/.exec(raw)?.[1] ?? raw, node, scope);
235
+ const bound = (raw: string, type: string, node: Element, scope: Scope): string => {
236
+ const expr = binding(raw, node, scope);
237
+ if (category(expr.type) !== type) fail(node, `expected ${type} binding`);
238
+ return expr.code;
239
+ };
240
+ const condition = (raw: string, node: Element, scope: Scope): string => {
241
+ const expr = binding(raw, node, scope);
242
+ if (expr.type.kind === "bool") return expr.code;
243
+ if (category(expr.type) === "number") return `(${expr.code} !== 0)`;
244
+ if (["bytes", "string", "enum"].includes(expr.type.kind)) return `(${expr.code}.length > 0)`;
245
+ return fail(node, "condition requires a scalar or text binding");
246
+ };
247
+ const textValue = (expr: Expr, node: Element): string => {
248
+ if (expr.type.kind === "bytes") return `new TextDecoder().decode(${expr.code})`;
249
+ if (["number", "boolean", "enum", "string"].includes(category(expr.type))) return `String(${expr.code})`;
250
+ return fail(node, "text requires bytes, an enum or a scalar binding");
251
+ };
252
+ const text = (raw: string, node: Element, scope: Scope): string => {
253
+ const parts: string[] = []; let last = 0;
254
+ for (const match of raw.matchAll(/\{([^{}]*)\}/g)) {
255
+ parts.push(JSON.stringify(raw.slice(last, match.index)), textValue(expression(match[1]!, node, scope), node)); last = match.index + match[0].length;
256
+ }
257
+ parts.push(JSON.stringify(raw.slice(last)));
258
+ if (raw.replace(/\{[^{}]*\}/g, "").match(/[{}]/)) fail(node, "unbalanced text binding");
259
+ return parts.join(" + ");
260
+ };
261
+ const byteText = (raw: string, node: Element, scope: Scope): string | null => {
262
+ const parts: string[] = []; let last = 0, hasBytes = false;
263
+ for (const match of raw.matchAll(/\{([^{}]*)\}/g)) {
264
+ if (match.index > last) parts.push(`new TextEncoder().encode(${JSON.stringify(raw.slice(last, match.index))})`);
265
+ const expr = expression(match[1]!, node, scope);
266
+ if (expr.type.kind === "bytes") { hasBytes = true; parts.push(expr.code); }
267
+ else parts.push(`new TextEncoder().encode(${textValue(expr, node)})`);
268
+ last = match.index + match[0].length;
269
+ }
270
+ if (!hasBytes) return null;
271
+ if (last < raw.length) parts.push(`new TextEncoder().encode(${JSON.stringify(raw.slice(last))})`);
272
+ return `nscvTextBytes([${parts.join(", ")}])`;
273
+ };
274
+ const key = (raw: string, node: Element, scope: Scope): Expr => {
275
+ if (/^-?\d+$/.test(raw)) {
276
+ if (!Number.isSafeInteger(Number(raw))) fail(node, "key is not an exact integer");
277
+ return { code: `nscvInteger(${raw})`, type: { kind: "i64" } };
278
+ }
279
+ if (!raw.startsWith("{")) {
280
+ if (/^(?:[-+]?\d|[.]\d|true$|false$)/.test(raw)) fail(node, "keys must be integers or strings");
281
+ return { code: JSON.stringify(raw), type: { kind: "string" } };
282
+ }
283
+ const expr = binding(raw, node, scope);
284
+ if (expr.type.kind !== "i64" && expr.type.kind !== "bytes" && expr.type.kind !== "string") fail(node, "keys must be integers or strings");
285
+ return expr.type.kind === "i64" ? { code: `nscvInteger(${expr.code})`, type: expr.type } : expr.type.kind === "bytes" ? expr : { code: textValue(expr, node), type: { kind: "string" } };
286
+ };
287
+ const output: string[] = []; let next = 0;
288
+ const textInputUnion = (ref: Ref): boolean => {
289
+ const arms = ref.kind === "union" ? contract.types.unions?.find(item => item.name === ref.name)?.arms : undefined;
290
+ const verbs = ["delete_backward", "delete_forward", "delete_word_backward", "delete_word_forward", "delete_to_start", "delete_to_line_start", "clear", "commit_composition", "cancel_composition"];
291
+ if (!arms || arms.length !== 13 || !verbs.every(name => arms.some(arm => arm.name === name && arm.payload.kind === "void"))) return false;
292
+ const payload = (name: string) => arms.find(arm => arm.name === name)?.payload;
293
+ const record = (name: string) => {
294
+ const type = payload(name);
295
+ return type && ["value", "record"].includes(type.kind) ? contract.types.structs.find(item => item.name === type.name)?.fields : undefined;
296
+ };
297
+ const move = record("move_caret"), selection = record("set_selection"), composition = record("set_composition");
298
+ const direction = move?.find(field => field.name === "direction")?.type;
299
+ const members = direction?.kind === "enum" ? contract.types.enums?.find(item => item.name === direction.name)?.members : undefined;
300
+ const directions = ["previous", "next", "previous_word", "next_word", "start", "end"];
301
+ const cursor = composition?.find(field => field.name === "cursor")?.type;
302
+ return payload("insert_text")?.kind === "bytes" && move?.length === 2 &&
303
+ !!members && members.length === 6 && directions.every(name => members.includes(name)) &&
304
+ move.some(field => field.name === "extend" && field.type.kind === "bool") &&
305
+ selection?.length === 2 && ["anchor", "focus"].every(name => selection.some(field => field.name === name && category(field.type) === "number")) &&
306
+ composition?.length === 2 && composition.some(field => field.name === "text" && field.type.kind === "bytes") &&
307
+ cursor?.kind === "optional" && !!cursor.inner && category(cursor.inner) === "number";
308
+ };
309
+ const emitChildren = (nodes: Element[], scope: Scope, slot: Slot | undefined, stack: string[], depth: number) => {
310
+ for (let i = 0; i < nodes.length; i++) {
311
+ const node = nodes[i]!;
312
+ if (node.name === "else") fail(node, "else must immediately follow if or for");
313
+ if (node.name !== "if" && node.name !== "for") { emit(node, scope, slot, stack, depth); continue; }
314
+ if (node.name === "for") {
315
+ emit(node, scope, slot, stack, depth);
316
+ const alternate = nodes[i + 1];
317
+ if (alternate?.name === "else") {
318
+ if (alternate.attrs.size || alternate.text.trim()) fail(alternate, "else accepts only child elements");
319
+ const items = path(node.attrs.get("each")!, node, scope);
320
+ output.push(`if (${items.code}.length === 0) {`);
321
+ emitChildren(alternate.children, scope, slot, stack, depth + 1); output.push("}"); i++;
322
+ }
323
+ continue;
324
+ }
325
+ if (node.attrs.size !== 1 || !node.attrs.has("test") || node.text.trim()) fail(node, "if requires only test and child elements");
326
+ output.push(`if (${condition(node.attrs.get("test")!, node, scope)}) {`);
327
+ emitChildren(node.children, scope, slot, stack, depth + 1); output.push("}");
328
+ const alternate = nodes[i + 1];
329
+ if (alternate?.name === "else") {
330
+ if (alternate.attrs.size || alternate.text.trim()) fail(alternate, "else accepts only child elements");
331
+ output.push("else {"); emitChildren(alternate.children, scope, slot, stack, depth + 1); output.push("}"); i++;
332
+ }
333
+ }
334
+ };
335
+ const event = (raw: string, channel: string, node: Element, scope: Scope): string => {
336
+ const match = /^([A-Za-z_][A-Za-z0-9_]*)(?::\{([^{}]+)\})?$/.exec(raw);
337
+ const arm = contract.msg.arms.find(item => item.name === match?.[1]);
338
+ if (!arm || !match) fail(node, `unknown or unsupported event ${raw}`);
339
+ const payload = match[2] ? path(match[2], node, scope) : null;
340
+ if (channel === "value" || channel === "resize") {
341
+ if (payload || arm.payload.kind !== "number" || (arm.payload.class ?? "f64") !== "f64") fail(node, channel === "resize" ? "split on-resize requires a bare one-number float Msg arm" : "slider on-change requires a bare one-number float or void Msg arm");
342
+ return String(contract.msg.arms.indexOf(arm));
343
+ }
344
+ if (channel === "input") {
345
+ if (payload || !textInputUnion(arm.payload)) fail(node, "on-input requires a bare TextInputEvent Msg arm");
346
+ return String(contract.msg.arms.indexOf(arm));
347
+ }
348
+ if (channel === "terminal") {
349
+ const record = arm.payload.kind === "record" ? contract.types.structs.find(item => item.name === arm.payload.name) : null;
350
+ const names = ["scrollback", "history", "cols", "rows"];
351
+ if (payload || !record || record.fields.length !== 4 || !names.every(name => record.fields.some(field => field.name === name && category(field.type) === "number"))) fail(node, "on-terminal requires a bare TerminalState Msg arm");
352
+ return String(contract.msg.arms.indexOf(arm));
353
+ }
354
+ if (channel === "scroll") {
355
+ const record = arm.payload.kind === "record" ? contract.types.structs.find(item => item.name === arm.payload.name) : null;
356
+ const names = ["offsetX", "offsetY", "velocityX", "velocityY", "viewportExtentX", "viewportExtentY", "contentExtentX", "contentExtentY"];
357
+ if (payload || !record || record.fields.length !== 8 || !names.every(name => record.fields.some(field => field.name === name && category(field.type) === "number"))) fail(node, "on-scroll requires a bare ScrollState Msg arm");
358
+ return String(contract.msg.arms.indexOf(arm));
359
+ }
360
+ let props = `kind: ${JSON.stringify(arm.name)}`;
361
+ if (channel === "drag") {
362
+ const record = arm.payload.kind === "record" ? contract.types.structs.find(item => item.name === arm.payload.name) : null;
363
+ const names = ["sourceId", "phase", "x", "y", "viewWidth", "viewHeight"];
364
+ if (!payload || category(payload.type) !== "number" || !record || record.fields.length !== 6 || !names.every(name => record.fields.some(field => field.name === name && (["x", "y", "viewWidth", "viewHeight"].includes(name) ? field.type.kind === "f64" : category(field.type) === "number")))) fail(node, "on-drag requires a sourceId binding and the six-field drag Msg record");
365
+ props += `, sourceId: ${payload.code}, phase: 0, x: 0, y: 0, viewWidth: 0, viewHeight: 0`;
366
+ } else if (arm.payload.kind === "void") { if (payload) fail(node, "void Msg arm cannot take a payload"); }
367
+ else {
368
+ const type = arm.payload.kind === "number" ? { kind: arm.payload.class ?? "f64" } : arm.payload.kind === "scalar" ? arm.payload.type! : arm.payload;
369
+ if (!payload || !arm.member || category(type) !== category(payload.type) || !["number", "boolean", "bytes", "enum"].includes(category(type)) || (type.kind === "enum" && type.name !== payload.type.name)) fail(node, "event requires a matching scalar Msg payload binding");
370
+ props += `, ${JSON.stringify(arm.member)}: ${payload.code}`;
371
+ }
372
+ return `Array.from(nscfPackMsg({ ${props} }))`;
373
+ };
374
+ const emit = (node: Element, scope: Scope, slot: Slot | undefined, stack: string[], depth: number, inputActionsAllowed = false): void => {
375
+ if (depth > 64 || next > 4096) fail(node, "expanded view exceeds 64 levels or 4096 elements");
376
+ if (node.name === "virtual-window") {
377
+ if ([...scope.values()].some(value => value.virtualIndex !== undefined)) fail(node, "virtual-window declarations cannot nest");
378
+ const allowed = ["id", "as", "item-count", "item-extent", "gap", "overscan", "viewport-fallback", "extent-estimate", "index-base", "anchor"];
379
+ const name = node.attrs.get("as"), identity = node.attrs.get("id");
380
+ if (!name || !/^[A-Za-z_][A-Za-z0-9_]*$/.test(name) || !identity || identity.includes("{") || new TextEncoder().encode(identity).length > 256 || node.children.length !== 1 || node.text.trim()) fail(node, "virtual-window requires a literal id, as and one root child");
381
+ if ([...node.attrs.keys()].some(attr => !allowed.includes(attr)) || !node.attrs.has("item-count")) fail(node, "unsupported virtual-window attributes");
382
+ const estimateName = node.attrs.get("extent-estimate");
383
+ const estimator = contract.model_helpers.find(helper => helper.name === estimateName && helper.params.length === 1 && ["i64", "f64"].includes(helper.params[0]!.kind) && ["i64", "f64"].includes(helper.returns.kind));
384
+ if (estimateName !== undefined && !estimator) fail(node, "extent-estimate requires a Model-first numeric index helper returning a number");
385
+ const range = contract.model_helpers.flatMap(helper => helper.params).find(rangeType);
386
+ if (!range) fail(node, "virtual-window requires a row helper taking the complete VirtualListRange");
387
+ const numeric = (attr: string, fallback: string, integer = false): string => {
388
+ const raw = node.attrs.get(attr);
389
+ if (raw === undefined) return fallback;
390
+ const value = raw.startsWith("{") ? binding(raw, node, scope) : expression(raw, node, scope);
391
+ if (!["i64", "f64"].includes(value.type.kind) || integer && value.type.kind !== "i64") fail(node, `${attr} requires ${integer ? "an integer" : "a number"}`);
392
+ return value.code;
393
+ };
394
+ const anchor = node.attrs.get("anchor") ?? "leading";
395
+ if (anchor !== "leading" && anchor !== "trailing") fail(node, "virtual-window anchor requires leading or trailing");
396
+ const id = next++, variable = `nscvRange${id}`, index = `nscvWindowIndex${id}`;
397
+ output.push('if (nscvVirtual === undefined) throw new Error("virtual view requires retained window context");',
398
+ `const ${index} = nscvVirtualRequest(nscvVirtual.requests, { id: ${JSON.stringify(identity)}, itemCount: ${numeric("item-count", "0", true)}, itemExtent: ${numeric("item-extent", "0")}, gap: ${numeric("gap", "0")}, overscan: ${numeric("overscan", "4", true)}, viewportFallback: ${numeric("viewport-fallback", "0")}, indexBase: ${numeric("index-base", "0", true)}, trailing: ${anchor === "trailing"}, estimateHelper: ${estimator ? contract.model_helpers.indexOf(estimator) : -1} });`,
399
+ 'if (!nscvVirtual.requestsOnly) {', `const ${variable} = nscvVirtual.ranges[${index}];`, `if (${variable} === undefined) throw new Error("missing virtual window range");`);
400
+ const inner = new Map(scope); inner.set(name, { code: variable, type: range, virtualIndex: index });
401
+ emitChildren(node.children, inner, slot, stack, depth + 1);
402
+ output.push("}"); return;
403
+ }
404
+ if (node.name === "virtual-list") {
405
+ const windowName = node.attrs.get("window"), window = windowName ? scope.get(windowName) : undefined;
406
+ const helper = contract.model_helpers.find(helper => helper.name === node.attrs.get("each"));
407
+ const name = node.attrs.get("as");
408
+ if (!window?.virtualIndex || !helper || helper.params.length !== 1 || !rangeType(helper.params[0]!) || helper.returns.kind !== "slice" || !helper.returns.elem || !name || !/^[A-Za-z_][A-Za-z0-9_]*$/.test(name) || node.children.length !== 1 || node.text.trim()) fail(node, "virtual-list requires an enclosing window, a Model-first range query, as and one keyed root per row");
409
+ if (!node.children[0]!.attrs.has("key") && !node.children[0]!.attrs.has("global-key")) fail(node, "virtual-list requires one keyed root per row");
410
+ const allowed = ["window", "each", "as", "grow", "width", "height", "min-width", "padding", "label", "background", "foreground", "border-color", "focus-ring", "radius", "overscroll", "on-scroll", "on-reach-end", "on-reach-start"];
411
+ if ([...node.attrs.keys()].some(attr => !allowed.includes(attr))) fail(node, "unsupported virtual-list attribute");
412
+ const attrs = new Map(node.attrs); for (const attr of ["window", "each", "as", "on-reach-end", "on-reach-start"]) attrs.delete(attr);
413
+ const id = next++, start = `nscvListStart${id}`, item = `nscvVirtualItem${id}`;
414
+ output.push(`nscvVirtualConsume(nscvVirtual!, ${window.virtualIndex});`, `const ${start} = nscvNodes.length;`);
415
+ emit({ ...node, name: "scroll", attrs, children: [], content: [] }, scope, slot, stack, depth + 1);
416
+ for (const [attr, property] of [["on-reach-end", "reachEnd"], ["on-reach-start", "reachStart"]]) if (node.attrs.has(attr!)) output.push(`nscvNodes[${start}]!.${property} = ${event(node.attrs.get(attr!)!, attr!.slice(3), node, scope)};`);
417
+ output.push(`nscvNodes[${start}]!.virtualWindow = ${window.virtualIndex};`, `for (const ${item} of ${helper.name}(nscfCommitted, ${window.code})) {`, `const nscvRowStart${id} = nscvNodes.length;`);
418
+ const inner = new Map(scope); inner.set(name, { code: item, type: helper.returns.elem });
419
+ emitChildren(node.children, inner, slot, stack, depth + 1);
420
+ output.push(`nscvVirtualRow(nscvNodes, nscvRowStart${id});`, "}", `nscvNodes[${start}]!.end = nscvNodes.length;`, `nscvVirtualList(nscvNodes, ${start}, ${window.code});`);
421
+ return;
422
+ }
423
+ if (node.name === "use") {
424
+ const name = node.attrs.get("template"), template = name ? templates.get(name) : null;
425
+ if (!template) fail(node, `unknown template ${name}`);
426
+ if (stack.includes(name!)) fail(node, "recursive template use");
427
+ if (node.text.trim()) fail(node, "use accepts only child elements");
428
+ const args = (template.attrs.get("args") ?? "").split(/[\s,]+/).filter(Boolean), inner = new Map<string, Expr>();
429
+ for (const arg of args) {
430
+ if (!/^[A-Za-z_][A-Za-z0-9_]*$/.test(arg) || inner.has(arg)) fail(template, "invalid or duplicate template argument");
431
+ const raw = node.attrs.get(arg);
432
+ if (raw === undefined) fail(node, `missing template argument ${arg}`);
433
+ const value = raw.startsWith("{") ? binding(raw, node, scope) : { code: JSON.stringify(raw), type: { kind: "string" } };
434
+ const variable = `nscvArg${next++}`; output.push(`const ${variable} = ${value.code};`); inner.set(arg, { ...value, code: variable });
435
+ }
436
+ if ([...node.attrs.keys()].some(arg => arg !== "template" && !args.includes(arg))) fail(node, "unknown template argument");
437
+ emitChildren(template.children, inner, { children: node.children, scope, slot }, [...stack, name!], depth + 1); return;
438
+ }
439
+ if (node.name === "slot") {
440
+ if (!slot || node.attrs.size || node.children.length || node.text.trim()) fail(node, "slot requires a template use and no attributes or children");
441
+ emitChildren(slot.children, slot.scope, slot.slot, stack, depth + 1); return;
442
+ }
443
+ if (node.name === "for") {
444
+ const each = node.attrs.get("each"), as = node.attrs.get("as"), field = node.attrs.get("key");
445
+ if (!each || !as || !/^[A-Za-z_][A-Za-z0-9_]*$/.test(as) || node.attrs.size !== (field === undefined ? 2 : 3) || field === "" || node.text.trim()) fail(node, "for requires each, as, an optional key and child elements");
446
+ const items = path(each, node, scope);
447
+ if (items.type.kind !== "slice" || !items.type.elem) fail(node, "each requires a list binding");
448
+ const id = next++, variable = `nscvItem${id}`, inner = new Map(scope); inner.set(as, { code: variable, type: items.type.elem });
449
+ const base = field === undefined ? null : key(`{${as}.${field}}`, node, inner);
450
+ output.push(`for (const ${variable} of ${items.code}) {`, `const nscvFirst${id} = nscvNodes.length;`);
451
+ emitChildren(node.children, inner, slot, stack, depth + 1);
452
+ if (base !== null) output.push(`${base.type.kind === "bytes" ? "nscvLoopByteKeys" : "nscvLoopKeys"}(nscvNodes, nscvFirst${id}, ${base.code});`);
453
+ output.push("}"); return;
454
+ }
455
+ const stringAttr = (name: string, fallback = ""): string => {
456
+ const raw = node.attrs.get(name);
457
+ if (raw === undefined) return JSON.stringify(fallback);
458
+ const value = raw.startsWith("{") ? binding(raw, node, scope) : { code: JSON.stringify(raw), type: { kind: "string" } };
459
+ if (!["bytes", "string", "enum"].includes(value.type.kind)) fail(node, `${name} requires text`);
460
+ return textValue(value, node);
461
+ };
462
+ const componentRoot = (allowed: string[]): string[] => {
463
+ if (node.text.trim()) fail(node, "component accepts only child elements");
464
+ for (const name of node.attrs.keys()) if (!allowed.includes(name)) fail(node, `unsupported ${node.name} attribute ${name}`);
465
+ const props = ['end: 0', 'kind: "row"', 'text: ""'];
466
+ for (const name of ["key", "global-key"]) {
467
+ const raw = node.attrs.get(name);
468
+ if (raw !== undefined) {
469
+ const expr = key(raw, node, scope);
470
+ props.push(`${name === "key" ? "key" : "globalKey"}${expr.type.kind === "i64" ? "Int" : expr.type.kind === "bytes" ? "Bytes" : ""}: ${expr.type.kind === "bytes" ? `nscvTextBytes([${expr.code}])` : expr.code}`);
471
+ }
472
+ }
473
+ if (node.attrs.has("label")) {
474
+ const bytes = byteText(node.attrs.get("label")!, node, scope);
475
+ props.push(bytes === null ? `label: ${stringAttr("label")}` : `label: "", labelBytes: ${bytes}`);
476
+ }
477
+ return props;
478
+ };
479
+ if (node.name === "input-group" || node.name === "input-group-actions") {
480
+ const actions = node.name === "input-group-actions";
481
+ if (actions && !inputActionsAllowed) fail(node, "input-group-actions requires an input-group parent");
482
+ const props = componentRoot(actions ? ["gap", "key", "global-key"] : ["label", "width", "height", "min-width", "grow", "key", "global-key"]);
483
+ props[1] = `kind: "${actions ? "input_group_actions" : "input_group"}"`;
484
+ for (const name of actions ? ["gap"] : ["width", "height", "min-width", "grow"]) {
485
+ const raw = node.attrs.get(name);
486
+ if (raw !== undefined) props.push(`${name === "min-width" ? "minWidth" : name}: ${bound(raw, "number", node, scope)}`);
487
+ }
488
+ const id = next++;
489
+ output.push(`const nscvGroup${id}: NscViewNode = { ${props.join(", ")} };`, `nscvPush(nscvNodes, nscvGroup${id});`);
490
+ if (actions) {
491
+ if (!node.attrs.has("gap")) output.push(`nscvGroup${id}.gap = 6;`);
492
+ if (node.children.some(child => child.name === "#text")) fail(node, "input-group-actions requires element children");
493
+ emitChildren(node.children, scope, slot, stack, depth + 1);
494
+ } else {
495
+ if (node.children.length < 1 || node.children.length > 2 || node.children[0]!.name !== "textarea" ||
496
+ node.children.length === 2 && node.children[1]!.name !== "input-group-actions") fail(node, "input-group requires a textarea then optional input-group-actions");
497
+ emit(node.children[0]!, scope, slot, stack, depth + 1);
498
+ if (node.children[1]) emit(node.children[1], scope, slot, stack, depth + 1, true);
499
+ }
500
+ output.push(`nscvGroup${id}.end = nscvNodes.length;`);
501
+ return;
502
+ }
503
+ if (node.name === "chart") {
504
+ const props = componentRoot(["key", "global-key", "label", "width", "height", "grow", "padding", "y-min", "y-max", "grid-lines", "baseline", "y-labels", "hover-details", "stroke-width", "x-labels"]);
505
+ for (const name of ["width", "height", "grow", "padding", "y-min", "y-max", "stroke-width", "grid-lines"]) {
506
+ const raw = node.attrs.get(name);
507
+ if (raw === undefined) continue;
508
+ const value = bound(raw, "number", node, scope);
509
+ const field = { "y-min": "chartYMin", "y-max": "chartYMax", "stroke-width": "chartStrokeWidth", "grid-lines": "chartGridLines" }[name];
510
+ props.push(`${field ?? name}: ${name === "grid-lines" ? `nscvChartGrid(${value})` : field ? `nscvChartWord(${value})` : value}`);
511
+ }
512
+ for (const [name, field] of [["baseline", "chartBaseline"], ["y-labels", "chartYLabels"], ["hover-details", "chartHoverDetails"]]) {
513
+ const raw = node.attrs.get(name!);
514
+ if (raw !== undefined) props.push(`${field}: ${bound(raw, "boolean", node, scope)}`);
515
+ }
516
+ const series = node.children.map(child => {
517
+ if (child.name !== "series" || child.text.trim() || child.children.length || [...child.attrs.keys()].some(name => !["kind", "values", "color", "label"].includes(name))) fail(child, "chart requires series leaves");
518
+ const raw = child.attrs.get("values");
519
+ if (raw === undefined) fail(child, "series requires a values binding");
520
+ const values = binding(raw, child, scope);
521
+ if (values.type.kind !== "slice" || !values.type.elem || !["i64", "f64"].includes(values.type.elem.kind)) fail(child, "series values requires a number array binding");
522
+ const kind = child.attrs.get("kind") ?? "line", color = child.attrs.get("color") ?? "accent";
523
+ if (!["line", "area", "bar"].includes(kind)) fail(child, "series kind requires line, area or bar");
524
+ if (!["background", "surface", "surface_subtle", "surface_pressed", "text", "text_muted", "syntax_plain", "syntax_comment", "syntax_keyword", "syntax_literal", "syntax_function", "syntax_property", "syntax_constant", "border", "accent", "accent_text", "destructive", "destructive_text", "success", "success_text", "warning", "warning_text", "info", "info_text", "focus_ring", "shadow", "scrim", "disabled"].includes(color)) fail(child, "series color requires a literal color token");
525
+ const label = child.attrs.get("label");
526
+ const bytes = label === undefined ? "[]" : byteText(label, child, scope) ?? `nscvTextBytes([new TextEncoder().encode(${label.startsWith("{") ? textValue(binding(label, child, scope), child) : JSON.stringify(label)})])`;
527
+ return `{ kind: ${JSON.stringify(kind === "bar" ? "bar" : "line")}, fill: ${kind === "area"}, color: ${JSON.stringify(color)}, label: ${bytes}, values: nscvChartWords(${values.code}) }`;
528
+ });
529
+ if (series.length === 0) fail(node, "chart requires at least one series");
530
+ const rawLabels = node.attrs.get("x-labels"); let labels = "[]";
531
+ if (rawLabels !== undefined) {
532
+ const values = binding(rawLabels, node, scope);
533
+ if (values.type.kind !== "slice" || !values.type.elem || !["bytes", "string"].includes(values.type.elem.kind)) fail(node, "chart x-labels requires a text array binding");
534
+ labels = `${values.code}.map(value => nscvTextBytes([${values.type.elem.kind === "bytes" ? "value" : "new TextEncoder().encode(value)"}]))`;
535
+ }
536
+ output.push(`nscvChart(nscvNodes, { ${props.join(", ")} }, [${series.join(", ")}], ${labels});`);
537
+ return;
538
+ }
539
+ if (node.name === "stepper") {
540
+ const props = componentRoot(["active", "key", "global-key", "label"]);
541
+ const raw = node.attrs.get("active");
542
+ if (raw === undefined) fail(node, "stepper requires active");
543
+ const active = raw.startsWith("{") ? binding(raw, node, scope) : expression(raw, node, scope);
544
+ if (active.type.kind !== "i64") fail(node, "stepper active requires an integer");
545
+ let steps = node.children, stepScope = scope;
546
+ if (steps.length === 1 && steps[0]!.name === "slot") {
547
+ if (!slot || steps[0]!.attrs.size || steps[0]!.children.length || steps[0]!.text.trim()) fail(node, "stepper slot requires a template use");
548
+ steps = slot.children; stepScope = slot.scope;
549
+ }
550
+ const labels = steps.map(step => {
551
+ if (step.name !== "step" || step.attrs.size || step.children.length) fail(step, "stepper takes only step text leaves");
552
+ const raw = step.text.trim(), bytes = byteText(raw, step, stepScope);
553
+ return bytes === null ? `{ text: ${text(raw, step, stepScope)} }` : `{ text: "", bytes: ${bytes} }`;
554
+ });
555
+ output.push(`nscvStepper(nscvNodes, { ${props.join(", ")} }, ${active.code}, [${labels.join(", ")}]);`);
556
+ return;
557
+ }
558
+ if (node.name === "timeline") {
559
+ const props = componentRoot(["gap", "grow", "key", "global-key", "label"]);
560
+ props[1] = 'kind: "column"'; props.push('role: "list"');
561
+ for (const name of ["gap", "grow"]) if (node.attrs.has(name)) props.push(`${name}: ${bound(node.attrs.get(name)!, "number", node, scope)}`);
562
+ const id = next++;
563
+ output.push(`const nscvNode${id}: NscViewNode = { ${props.join(", ")} };`,
564
+ `const nscvRecipe${id} = nscvCompositionRequest(7, 0, 0, 0, 0, 0, 0, nscvNode${id}.gap ?? 0);`,
565
+ `nscvNode${id}.gap = new DataView(nscvRecipe${id}.buffer).getFloat32(32, true);`, `nscvPush(nscvNodes, nscvNode${id});`);
566
+ emitChildren(node.children, scope, slot, stack, depth + 1);
567
+ output.push(`nscvNode${id}.end = nscvNodes.length;`);
568
+ return;
569
+ }
570
+ if (node.name === "timeline-item") {
571
+ const props = componentRoot(["title", "description", "meta", "indicator", "icon", "variant", "connector", "selected", "on-press", "key", "global-key"]);
572
+ if (!node.attrs.has("title") || node.children.length) fail(node, "timeline-item requires title and no children");
573
+ if (node.attrs.has("on-press")) props.push(`press: ${event(node.attrs.get("on-press")!, "press", node, scope)}`);
574
+ if (node.attrs.has("selected")) props.push(`selected: ${bound(node.attrs.get("selected")!, "boolean", node, scope)}`);
575
+ const variant = stringAttr("variant", "outline");
576
+ const connector = node.attrs.has("connector") ? bound(node.attrs.get("connector")!, "boolean", node, scope) : "true";
577
+ const itemText = (name: string): string => {
578
+ const raw = node.attrs.get(name), bytes = raw === undefined ? null : byteText(raw, node, scope);
579
+ return bytes === null ? `{ text: ${stringAttr(name)} }` : `{ text: "", bytes: ${bytes} }`;
580
+ };
581
+ output.push(`nscvTimelineItem(nscvNodes, { root: { ${props.join(", ")} }, title: ${itemText("title")}, description: ${itemText("description")}, meta: ${itemText("meta")}, indicator: ${itemText("indicator")}, icon: ${stringAttr("icon")}, variant: nscvVariant(${variant}), connector: ${connector} });`);
582
+ return;
583
+ }
584
+ if (node.name === "video") {
585
+ const props = componentRoot(["src", "controls", "autoplay", "loop", "muted", "key", "global-key", "width", "height", "grow", "label"]);
586
+ if (node.children.length || node.text.trim()) fail(node, "video is a leaf");
587
+ for (const name of ["width", "height", "grow"]) if (node.attrs.has(name)) props.push(`${name}: ${bound(node.attrs.get(name)!, "number", node, scope)}`);
588
+ const flag = (name: string, fallback: string) => node.attrs.has(name) ? bound(node.attrs.get(name)!, "boolean", node, scope) : fallback;
589
+ output.push(`nscvVideoElement(nscvNodes, { ${props.join(", ")} }, nscvVideo, ${stringAttr("src")}, ${flag("controls", "false")}, ${flag("autoplay", "true")}, ${flag("loop", "false")}, ${flag("muted", "false")});`);
590
+ return;
591
+ }
592
+ if (node.name === "markdown") {
593
+ const allowed = ["source", "on-link", "on-details", "details-expanded", "issue-link-base", "images"];
594
+ if (node.children.length || node.text.trim() || !node.attrs.has("source") || [...node.attrs.keys()].some(name => !allowed.includes(name))) fail(node, "markdown requires source, no children, and its closed presentation attributes");
595
+ const source = binding(node.attrs.get("source")!, node, scope);
596
+ if (!/^\{[^{}]+\}$/.test(node.attrs.get("source")!) || source.type.kind !== "bytes") fail(node, "markdown source requires one byte binding");
597
+ let expanded = "[]", issue = "null", images = "[]", wordImages = false;
598
+ if (node.attrs.has("details-expanded")) {
599
+ const raw = node.attrs.get("details-expanded")!, value = binding(raw, node, scope);
600
+ if (!/^\{[^{}]+\}$/.test(raw) || value.type.kind !== "slice" || value.type.elem?.kind !== "bool") fail(node, "details-expanded requires one boolean-array binding");
601
+ expanded = value.code;
602
+ }
603
+ if (node.attrs.has("images")) {
604
+ const raw = node.attrs.get("images")!, value = binding(raw, node, scope), record = value.type.kind === "slice" && value.type.elem && ["node", "value"].includes(value.type.elem.kind) ? contract.types.structs.find(item => item.name === value.type.elem!.name) : null;
605
+ const imageField = record?.fields.find(field => field.name === "image");
606
+ const identity = imageField && ["node", "value"].includes(imageField.type.kind) ? contract.types.structs.find(item => item.name === imageField.type.name) : null;
607
+ wordImages = !!identity && identity.fields.length === 2 && ["imageLower", "imageUpper"].every(name => identity.fields.some(field => field.name === name && category(field.type) === "number"));
608
+ if (!/^\{[^{}]+\}$/.test(raw) || !record || record.fields.length !== 4 || !record.fields.some(field => field.name === "source" && field.type.kind === "bytes") || !["width", "height"].every(name => record.fields.some(field => field.name === name && category(field.type) === "number")) || !(wordImages || imageField && category(imageField.type) === "number")) fail(node, "images requires source bytes, an exact registered image identity, width and height records");
609
+ images = value.code;
610
+ }
611
+ if (node.attrs.has("issue-link-base")) {
612
+ const raw = node.attrs.get("issue-link-base")!;
613
+ if (raw.startsWith("{")) { const value = binding(raw, node, scope); if (!/^\{[^{}]+\}$/.test(raw) || value.type.kind !== "bytes") fail(node, "issue-link-base requires literal text or one byte binding"); issue = value.code; }
614
+ else { if (/[{}]/.test(raw)) fail(node, "invalid issue-link-base literal"); issue = `new TextEncoder().encode(${JSON.stringify(raw)})`; }
615
+ }
616
+ const channels: string[] = [];
617
+ for (const [attribute, property, kind] of [["on-link", "markdownLink", "bytes"], ["on-details", "markdownDetails", "number"]]) {
618
+ const raw = node.attrs.get(attribute!); if (raw === undefined) continue;
619
+ const arm = contract.msg.arms.find(item => item.name === raw);
620
+ if (!/^[A-Za-z_][A-Za-z0-9_]*$/.test(raw) || !arm || arm.payload.kind !== kind) fail(node, `${attribute} requires a bare ${kind} Msg arm`);
621
+ channels.push(`${property}: ${contract.msg.arms.indexOf(arm)}`);
622
+ }
623
+ output.push(`nscvNodes.push({ end: nscvNodes.length + 1, kind: "markdown", text: "", markdownRecipe: ${wordImages ? "nscvMarkdownRecipeWords" : "nscvMarkdownRecipe"}(${source.code}, ${expanded}, ${issue}, ${images})${channels.length ? ", " + channels.join(", ") : ""} });`);
624
+ return;
625
+ }
626
+ const kinds: Record<string, string> = { image: "image", terminal: "terminal", icon: "icon", combobox: "combobox", bubble: "bubble", table: "table", "data-grid": "data_grid", popover: "popover", "menu-surface": "menu_surface", "table-row": "data_row", "table-cell": "data_cell", progress: "progress", skeleton: "skeleton", spinner: "spinner", column: "column", row: "row", stack: "stack", grid: "grid", card: "card", alert: "alert", dialog: "dialog", drawer: "drawer", sheet: "sheet", tooltip: "tooltip", panel: "panel", badge: "badge", input: "input", "text-field": "text_field", textarea: "textarea", code: "textarea", "search-field": "search_field", select: "select", text: "text", button: "button", checkbox: "checkbox", switch: "switch_control", toggle: "toggle", slider: "slider", "status-bar": "status_bar", spacer: "spacer", scroll: "scroll", avatar: "avatar", radio: "radio", "radio-group": "radio_group", "button-group": "button_group", breadcrumb: "breadcrumb", pagination: "pagination", "toggle-group": "toggle_group", "toggle-button": "toggle_button", accordion: "accordion", tabs: "tabs", "segmented-control": "segmented_control", tree: "tree", list: "list", "list-item": "list_item", "dropdown-menu": "dropdown_menu", "menu-item": "menu_item", separator: "separator", split: "split", resizable: "resizable", "media-surface": "media_surface" };
627
+ if (!Object.hasOwn(kinds, node.name)) fail(node, `unsupported element <${node.name}>`);
628
+ if (node.name === "image" && (!node.attrs.has("image") || node.text.trim() || node.children.length)) fail(node, "image requires an identity binding and no content");
629
+ if (node.name === "terminal" && (!node.attrs.has("pty") || node.text.trim() || node.children.length || node.attrs.has("text"))) fail(node, "terminal requires pty and no authored content");
630
+ if (node.name === "icon" && (!node.attrs.has("name") || node.text.trim() || node.children.length)) fail(node, "icon requires name and no content");
631
+ if (node.name === "radio-group" && !node.attrs.has("label")) fail(node, "radio-group requires a label");
632
+ const menus = node.children.filter(child => child.name === "context-menu");
633
+ if (menus.length > 1) fail(node, "an element takes at most one direct context-menu");
634
+ const reactions = node.children.filter(child => child.name === "reactions");
635
+ if (reactions.length && node.name !== "bubble") fail(node, "reactions requires bubble");
636
+ if (reactions.length > 1) fail(node, "bubble takes at most one reactions child");
637
+ const contentChildren = node.children.filter(child => child.name !== "context-menu" && child.name !== "reactions");
638
+ const container = ["bubble", "table", "data-grid", "popover", "menu-surface", "table-row", "column", "row", "stack", "grid", "card", "alert", "dialog", "drawer", "sheet", "scroll", "panel", "radio-group", "button-group", "breadcrumb", "pagination", "toggle-group", "accordion", "tabs", "tree", "list", "list-item", "dropdown-menu", "split", "resizable"].includes(node.name);
639
+ if (node.attrs.get("role") === "treeitem" && !["column", "row", "panel", "list-item"].includes(node.name)) fail(node, "compiled treeitem requires column, row, panel or list-item");
640
+ if (node.attrs.get("role") === "tree" && !["column", "row", "panel", "scroll", "tree"].includes(node.name)) fail(node, "tree role requires a generic container");
641
+ const paragraph = node.name === "text" && contentChildren.length > 0;
642
+ if (!paragraph && (["list-item", "card", "alert"].includes(node.name) ? node.text.trim() !== "" && contentChildren.length !== 0 : container ? node.text.trim() !== "" : contentChildren.length !== 0)) fail(node, "mixed content is unsupported");
643
+ const textSource = node.name === "icon" ? node.attrs.get("name")! : node.text.trim();
644
+ const rawText = byteText(textSource, node, scope);
645
+ const props: string[] = [`kind: ${JSON.stringify(kinds[node.name])}`, `text: ${rawText === null ? text(textSource, node, scope) : '""'}`];
646
+ if (node.name === "icon" && (textSource.startsWith("{") || textSource.startsWith("app:"))) {
647
+ props[1] = 'text: ""';
648
+ props.push(rawText === null ? `icon: ${text(textSource, node, scope)}` : `iconBytes: ${rawText}`);
649
+ } else if (rawText !== null) props.push(`textBytes: ${rawText}`);
650
+ if (reactions.length) {
651
+ const pill = reactions[0]!;
652
+ if (pill.children.length || !pill.text.trim()) fail(pill, "reactions requires a nonempty text run");
653
+ for (const name of pill.attrs.keys()) if (name !== "text-alignment") fail(pill, "reactions takes only text-alignment");
654
+ const alignment = pill.attrs.get("text-alignment") ?? "end";
655
+ if (!["start", "center", "end"].includes(alignment)) fail(pill, "unsupported reactions text-alignment");
656
+ const raw = byteText(pill.text.trim(), pill, scope);
657
+ props[1] = `text: ${raw === null ? text(pill.text.trim(), pill, scope) : '""'}`;
658
+ if (raw !== null) props.push(`textBytes: ${raw}`);
659
+ props.push(`textAlignment: ${JSON.stringify(alignment)}`);
660
+ }
661
+ if (menus.length) {
662
+ const menu = menus[0]!;
663
+ if (nonHitTargetNames.includes(node.name) && !["on-press", "on-double-press", "on-toggle", "on-hold", "on-drag"].some(name => node.attrs.has(name))) fail(menu, "context-menu requires an interactive host");
664
+ if (menu.attrs.size || menu.text.trim()) fail(menu, "context-menu accepts only item declarations");
665
+ const menuId = next++, menuName = `nscvContext${menuId}`;
666
+ output.push(`const ${menuName}: NscContextMenuItem[] = [];`);
667
+ let leaves = 0, items = 0;
668
+ const emitMenu = (nodes: Element[], menuScope: Scope, menuDepth: number): void => {
669
+ if (menuDepth > 64) fail(menu, "context-menu nesting exceeds 64");
670
+ for (let i = 0; i < nodes.length; i++) {
671
+ const item = nodes[i]!;
672
+ if (item.name === "if") {
673
+ if (item.attrs.size !== 1 || !item.attrs.has("test") || item.text.trim()) fail(item, "if requires only test and child elements");
674
+ output.push(`if (${condition(item.attrs.get("test")!, item, menuScope)}) {`);
675
+ emitMenu(item.children, menuScope, menuDepth + 1); output.push("}");
676
+ const alternate = nodes[i + 1];
677
+ if (alternate?.name === "else") {
678
+ if (alternate.attrs.size || alternate.text.trim()) fail(alternate, "else accepts only child elements");
679
+ output.push("else {"); emitMenu(alternate.children, menuScope, menuDepth + 1); output.push("}"); i++;
680
+ }
681
+ continue;
682
+ }
683
+ if (item.name === "else") fail(item, "else must immediately follow if");
684
+ leaves++;
685
+ if (leaves > 32) fail(menu, "context-menu takes at most 32 declared leaves");
686
+ let value: string;
687
+ if (item.name === "separator") {
688
+ if (item.attrs.size || item.children.length || item.text.trim()) fail(item, "context-menu separator must be empty");
689
+ value = '{ label: "", enabled: true, separator: true }';
690
+ } else {
691
+ if (item.name !== "menu-item" || item.children.length || !item.text.trim()) fail(item, "context-menu takes labeled menu-item leaves or conditional declarations");
692
+ for (const name of item.attrs.keys()) if (!["on-press", "disabled"].includes(name)) fail(item, `unsupported context-menu item attribute ${name}`);
693
+ const press = item.attrs.get("on-press"), disabled = item.attrs.get("disabled");
694
+ if (press === undefined) fail(item, "context-menu menu-item requires on-press");
695
+ const rawLabel = byteText(item.text.trim(), item, menuScope);
696
+ value = `{ label: ${rawLabel === null ? text(item.text.trim(), item, menuScope) : '""'}, ${rawLabel === null ? "" : `labelBytes: ${rawLabel}, `}enabled: ${disabled === undefined ? "true" : `!(${bound(disabled, "boolean", item, menuScope)})`}, separator: false, press: ${event(press, "press", item, menuScope)} }`;
697
+ items++;
698
+ }
699
+ output.push(`${menuName}.push(${value});`);
700
+ }
701
+ };
702
+ emitMenu(menu.children, scope, 0);
703
+ if (items === 0) fail(menu, "context-menu requires at least one menu-item");
704
+ props.push(`contextMenu: ${menuName}`);
705
+ }
706
+ if (paragraph) {
707
+ if (node.attrs.has("wrap") || node.attrs.has("overflow")) fail(node, "span paragraphs always word-wrap; drop wrap and overflow");
708
+ const runs: string[] = [];
709
+ let separator = false;
710
+ for (const part of node.content) {
711
+ if ("name" in part && part.name === "context-menu") continue;
712
+ const isSpan = "name" in part;
713
+ if (isSpan && (part.name !== "span" || part.children.length || part.content.length !== 1 || !part.text.trim())) fail(part, "text takes nonempty span leaves without nesting");
714
+ const raw = part.text;
715
+ const visible = raw.replace(/^[ \t\r\n]+|[ \t\r\n]+$/g, "");
716
+ if (!isSpan && /^[ \t\r\n]/.test(raw)) separator = true;
717
+ if (!visible) { if (/[ \t\r\n]/.test(raw)) separator = true; continue; }
718
+ if (runs.length && separator) runs.push('{ text: " " }');
719
+ const rawSpan = byteText(visible, node, scope);
720
+ const fields = [`text: ${rawSpan === null ? text(visible, node, scope) : '""'}`];
721
+ if (rawSpan !== null) fields.push(`textBytes: ${rawSpan}`);
722
+ if (isSpan) for (const [name, value] of part.attrs) {
723
+ if (["mono", "italic", "underline"].includes(name)) fields.push(`${name === "mono" ? "monospace" : name}: ${bound(value, "boolean", part, scope)}`);
724
+ else if (name === "scale") {
725
+ if (!value.startsWith("{") && (!Number.isFinite(Number(value)) || Number(value) <= 0)) fail(part, "span scale requires a positive finite number");
726
+ fields.push(`scale: nscvSpanScale(${bound(value, "number", part, scope)})`);
727
+ } else if (name === "weight") {
728
+ if (value.startsWith("{")) {
729
+ const expr = binding(value, part, scope);
730
+ const members = contract.types.enums?.find(item => item.name === expr.type.name)?.members;
731
+ if (expr.type.kind !== "enum" || !members?.every(member => ["regular", "medium", "bold"].includes(member))) fail(part, "span weight requires regular, medium or bold");
732
+ fields.push(`weight: ${expr.code}`);
733
+ } else {
734
+ if (!["regular", "medium", "bold"].includes(value)) fail(part, "unsupported span weight");
735
+ fields.push(`weight: ${JSON.stringify(value)}`);
736
+ }
737
+ } else if (name === "foreground") {
738
+ if (value.startsWith("{")) {
739
+ const expr = binding(value, part, scope);
740
+ const members = contract.types.enums?.find(item => item.name === expr.type.name)?.members;
741
+ if (expr.type.kind !== "enum" || !members?.length || !members.every(member => colorTokenNames.includes(member))) fail(part, "span foreground requires its closed token vocabulary");
742
+ fields.push(`color: ${expr.code}`);
743
+ } else {
744
+ if (!colorTokenNames.includes(value)) fail(part, "unsupported span foreground token");
745
+ fields.push(`color: ${JSON.stringify(value)}`);
746
+ }
747
+ } else fail(part, `unsupported span attribute ${name}; layout, identity and events belong on text`);
748
+ }
749
+ runs.push(`{ ${fields.join(", ")} }`);
750
+ separator = !isSpan && /[ \t\r\n]$/.test(raw);
751
+ }
752
+ props[1] = 'text: ""';
753
+ props.push(`spans: [${runs.join(", ")}]`);
754
+ }
755
+ if (node.name === "code") {
756
+ const editable = node.attrs.get("editable") ?? "false", wrap = node.attrs.get("wrap") ?? "true";
757
+ const editableCode = bound(editable, "boolean", node, scope);
758
+ if (wrap !== "true" && wrap !== "false") fail(node, "code wrap requires a literal boolean");
759
+ if (editable === "false" && node.attrs.has("on-input")) fail(node, "read-only code cannot declare on-input");
760
+ if (editable !== "true" || wrap !== "false") {
761
+ props[0] = 'kind: "code"';
762
+ props.push(`codeEditable: ${editableCode}`, `wrap: ${wrap}`);
763
+ }
764
+ if (!node.attrs.has("source") || node.text.trim()) fail(node, "code requires a source binding and no element text");
765
+ const expr = binding(node.attrs.get("source")!, node, scope);
766
+ if (expr.type.kind !== "bytes") fail(node, "code source requires UTF-8 bytes");
767
+ props[1] = 'text: ""';
768
+ props.push(`textBytes: nscvTextBytes([${expr.code}])`);
769
+ const language = (node.attrs.get("language") ?? "plain").replace(/^[ \t\r\n]+|[ \t\r\n]+$/g, "").toLowerCase();
770
+ const aliases: Record<string, string> = { text: "plain", js: "javascript", mjs: "javascript", ts: "typescript", jsonc: "json", yml: "yaml", sh: "shell", bash: "shell", zsh: "shell", py: "python", rs: "rust", c: "c_like", h: "c_like", cc: "c_like", cpp: "c_like", "c++": "c_like", cs: "c_like", csharp: "c_like", java: "c_like", kotlin: "c_like", swift: "c_like", golang: "go", xml: "html", svg: "html", scss: "css", less: "css", md: "markdown" };
771
+ const canonical = aliases[language] ?? language;
772
+ if (language === "c_like" || !["plain", "zig", "javascript", "typescript", "json", "yaml", "shell", "python", "rust", "c_like", "go", "html", "css", "sql", "jsx", "tsx", "markdown"].includes(canonical)) fail(node, "code language requires a supported literal name");
773
+ props.push(`codeLanguage: ${JSON.stringify(canonical)}`);
774
+ const attrs = ["source", "language", "editable", "line-numbers", "added-lines", "removed-lines", "wrap", "width", "height", "min-width", "grow", "label", "key", "global-key", "on-input"];
775
+ for (const name of node.attrs.keys()) if (!attrs.includes(name)) fail(node, `unsupported compiled code attribute ${name}`);
776
+ if (node.attrs.has("on-input")) props.push(`input: (${editableCode}) ? ${event(node.attrs.get("on-input")!, "input", node, scope)} : undefined`);
777
+ }
778
+ for (const [name, value] of node.attrs) {
779
+ if (node.name === "code" && ["source", "language", "editable", "wrap", "line-numbers", "added-lines", "removed-lines", "on-input"].includes(name)) continue;
780
+ if (name === "gap" && node.name === "resizable") fail(node, "resizable is a stacking surface; put gap on a row or column inside");
781
+ if (name === "image") {
782
+ if (!["image", "avatar"].includes(node.name) || !/^\{[^{}]+\}$/.test(value)) fail(node, "image requires one identity binding on image or avatar");
783
+ const identity = binding(value, node, scope);
784
+ if (identity.type.kind === "bytes") {
785
+ const local = `nscvImage${next++}`;
786
+ output.push(`const ${local} = nscvImageIdentity(${identity.code});`);
787
+ props.push(`imageLower: ${local}.imageLower`, `imageUpper: ${local}.imageUpper`);
788
+ } else props.push(`image: ${bound(value, "number", node, scope)}`);
789
+ }
790
+ else if (name === "fit") {
791
+ if (node.name !== "image" || !["contain", "cover", "stretch"].includes(value)) fail(node, "fit requires contain, cover or stretch on image");
792
+ props.push(`imageFit: ${JSON.stringify(value)}`);
793
+ }
794
+ else if (["gap", "padding", "grow", "width", "height", "value"].includes(name)) props.push(`${name}: ${bound(value, "number", node, scope)}`);
795
+ else if (["padding-top", "padding-bottom", "padding-left", "padding-right"].includes(name)) {
796
+ const property = name.replace(/-([a-z])/g, (_, letter: string) => letter.toUpperCase());
797
+ props.push(`${property}: ${bound(value, "number", node, scope)}`);
798
+ }
799
+ else if (name === "surface") {
800
+ if (node.name !== "media-surface") fail(node, "surface requires media-surface");
801
+ props.push(`image: ${bound(value, "number", node, scope)}`);
802
+ }
803
+ else if (name === "columns" || name === "virtual-item-extent" || name === "virtualized") {
804
+ if (node.name !== "grid") fail(node, `${name} requires grid`);
805
+ const prop = name === "virtual-item-extent" ? "virtualItemExtent" : name;
806
+ const expr = bound(value, name === "virtualized" ? "boolean" : "number", node, scope);
807
+ props.push(`${prop}: ${name === "columns" ? `nscvGridCount(${expr})` : expr}`);
808
+ }
809
+ else if (name === "value-x") {
810
+ if (node.name !== "scroll" || !node.attrs.has("axis") || node.attrs.get("axis") === "vertical") fail(node, "value-x requires scroll with axis=horizontal or both");
811
+ props.push(`valueX: ${bound(value, "number", node, scope)}`);
812
+ } else if (name === "axis" || name === "overscroll") {
813
+ if (node.name !== "scroll") fail(node, `${name} requires scroll`);
814
+ const vocabulary = name === "axis" ? ["vertical", "horizontal", "both"] : ["default", "none", "rubber_band"];
815
+ if (value.startsWith("{")) {
816
+ const expr = binding(value, node, scope);
817
+ const members = contract.types.enums?.find(item => item.name === expr.type.name)?.members;
818
+ if (expr.type.kind !== "enum" || !members?.every(member => vocabulary.includes(member))) fail(node, `${name} requires its closed enum vocabulary`);
819
+ props.push(`${name}: ${expr.code}`);
820
+ } else {
821
+ if (!vocabulary.includes(value)) fail(node, `unsupported ${name}=${value}`);
822
+ props.push(`${name}: ${JSON.stringify(value)}`);
823
+ }
824
+ }
825
+ else if (name === "backdrop-blur") {
826
+ if (value.startsWith("{")) {
827
+ const expr = binding(value, node, scope);
828
+ const members = contract.types.enums?.find(item => item.name === expr.type.name)?.members;
829
+ if (expr.type.kind !== "enum" || !members?.every(member => ["none", "sm", "md"].includes(member))) fail(node, "backdrop-blur requires its closed token vocabulary");
830
+ props.push(`backdropBlur: ${expr.code}`);
831
+ } else {
832
+ if (!["none", "sm", "md"].includes(value)) fail(node, "unsupported backdrop-blur token");
833
+ props.push(`backdropBlur: ${JSON.stringify(value)}`);
834
+ }
835
+ }
836
+ else if (name === "overflow") {
837
+ if (!["clip", "ellipsis"].includes(value)) fail(node, "unsupported overflow");
838
+ props.push(`overflow: ${JSON.stringify(value)}`);
839
+ }
840
+ else if (name === "text-alignment") {
841
+ if (!["start", "center", "end"].includes(value)) fail(node, "unsupported text-alignment");
842
+ props.push(`textAlignment: ${JSON.stringify(value)}`);
843
+ }
844
+ else if (name === "min-width" || name === "max-width") props.push(`${name === "min-width" ? "minWidth" : "maxWidth"}: ${bound(value, "number", node, scope)}`);
845
+ else if (["resize-duration", "resize-easing", "resize-origin"].includes(name)) {
846
+ if (node.name !== "split") fail(node, `${name} requires split`);
847
+ if (name !== "resize-duration" && (!node.attrs.has("resize-duration") || node.attrs.get("resize-duration") === "0")) fail(node, `${name} requires nonzero resize-duration`);
848
+ if (name === "resize-duration") props.push(`resizeDuration: nscvResizeDuration(${bound(value, "number", node, scope)})`);
849
+ else if (name === "resize-origin") {
850
+ if (!Number.isFinite(Number(value)) || Number(value) < 0 || Number(value) > 1) fail(node, "resize-origin requires a literal fraction from 0 to 1");
851
+ props.push(`resizeOrigin: ${Number(value)}`);
852
+ } else {
853
+ if (!["linear", "standard", "emphasized", "spring"].includes(value)) fail(node, "unsupported resize-easing");
854
+ props.push(`resizeEasing: ${JSON.stringify(value)}`);
855
+ }
856
+ }
857
+ else if (name === "pty") {
858
+ if (node.name !== "terminal" || !value.startsWith("{")) fail(node, "pty requires a terminal binding");
859
+ const expr = binding(value, node, scope);
860
+ if (expr.type.kind === "bytes") props.push(`ptyBytes: Array.from(${expr.code})`);
861
+ else if (expr.type.kind === "i64") props.push(`pty: nscvPtyKey(${expr.code})`);
862
+ else fail(node, "pty requires a byte name or integer key");
863
+ } else if (name === "scrollback") {
864
+ if (node.name !== "terminal") fail(node, "scrollback requires terminal");
865
+ props.push(`scrollback: nscvScrollback(${bound(value, "number", node, scope)})`);
866
+ }
867
+ else if (name === "quiet-hover") {
868
+ if (nonHitTargetNames.includes(node.name)) fail(node, "quiet-hover requires a hit target element");
869
+ props.push(`quietHover: ${bound(value, "boolean", node, scope)}`);
870
+ }
871
+ else if (["checked", "disabled", "selected", "window-drag", "wrap", "expanded", "submit-on-enter", "autofocus", "focusable"].includes(name)) {
872
+ if (name === "autofocus" && !["input", "text-field", "search-field", "textarea", "combobox", "terminal"].includes(node.name)) fail(node, "autofocus requires a text-entry widget");
873
+ if (name === "checked" && !["checkbox", "switch", "toggle", "radio"].includes(node.name)) fail(node, "checked requires checkbox, switch, toggle or radio");
874
+ if (name === "submit-on-enter" && node.name !== "textarea") fail(node, "submit-on-enter requires textarea");
875
+ if (name === "wrap" && node.name !== "text") fail(node, "wrap requires text");
876
+ if (name === "expanded" && node.attrs.get("role") !== "treeitem") fail(node, "expanded requires role=treeitem");
877
+ props.push(`${name === "window-drag" ? "windowDrag" : name === "submit-on-enter" ? "submitOnEnter" : name}: ${bound(value, "boolean", node, scope)}`);
878
+ } else if (name === "tree-level") {
879
+ if (node.attrs.get("role") !== "treeitem") fail(node, "tree-level requires role=treeitem");
880
+ props.push(`treeLevel: nscvTreeLevel(${bound(value, "number", node, scope)})`);
881
+ } else if (name === "key" || name === "global-key") {
882
+ const expr = key(value, node, scope), prop = name === "key" ? "key" : "globalKey";
883
+ props.push(`${prop}${expr.type.kind === "i64" ? "Int" : expr.type.kind === "bytes" ? "Bytes" : ""}: ${expr.type.kind === "bytes" ? `nscvTextBytes([${expr.code}])` : expr.code}`);
884
+ } else if (["label", "text", "placeholder", "command"].includes(name)) {
885
+ if (name === "text" && !["input", "text-field", "search-field", "textarea", "combobox", "select", "accordion", "checkbox", "radio", "switch", "toggle", "button", "toggle-button", "table-cell", "status-bar", "badge", "menu-item", "list-item", "avatar", "tooltip", "text", "card", "alert", "dialog", "drawer", "sheet", "data-grid"].includes(node.name)) fail(node, "text requires a text-entry widget, select, accordion header, checkbox or captioned surface");
886
+ if (name === "placeholder" && !["input", "text-field", "search-field", "textarea", "combobox", "select"].includes(node.name)) fail(node, "placeholder requires a text-entry widget or select");
887
+ if (name === "text" && node.text.trim()) fail(node, "text attribute cannot be combined with element text");
888
+ const expr = value.startsWith("{") ? binding(value, node, scope) : { code: JSON.stringify(value), type: { kind: "string" } };
889
+ if (!["bytes", "string", "enum"].includes(expr.type.kind)) fail(node, `${name} requires text`);
890
+ const rawBytes = name === "command" ? null : byteText(value, node, scope);
891
+ const display = rawBytes === null ? textValue(expr, node) : '""';
892
+ if (name === "text") props[1] = `text: ${display}`;
893
+ else props.push(`${name}: ${display}`);
894
+ if (rawBytes !== null) props.push(`${name}Bytes: ${rawBytes}`);
895
+ }
896
+ else if (name === "name" && node.name === "icon") {
897
+ if (!value || /[{}]/.test(value) && !/^\{[^{}]+\}$/.test(value)) fail(node, "icon name requires a literal name or one text binding");
898
+ if (value.startsWith("{") && !["bytes", "string", "enum"].includes(binding(value, node, scope).type.kind)) fail(node, "icon name requires text");
899
+ }
900
+ else if (name === "icon") {
901
+ if (value.startsWith("{")) {
902
+ const expr = binding(value, node, scope);
903
+ if (!["bytes", "string", "enum"].includes(expr.type.kind)) fail(node, "icon requires text");
904
+ if (expr.type.kind === "bytes") props.push(`iconBytes: nscvTextBytes([${expr.code}])`);
905
+ else props.push(`icon: ${expr.code}`);
906
+ } else { if (/[{}]/.test(value)) fail(node, "invalid icon name"); props.push(`icon: ${JSON.stringify(value)}`); }
907
+ }
908
+ else if (name === "icon-placement") {
909
+ if (!["leading", "trailing"].includes(value)) fail(node, "unsupported icon-placement");
910
+ props.push(`iconPlacement: ${JSON.stringify(value)}`);
911
+ }
912
+ else if (name === "tooltip-delay") {
913
+ if (node.name !== "tooltip" || !node.attrs.has("anchor")) fail(node, "tooltip-delay requires anchored tooltip");
914
+ const delay = value.startsWith("{") ? binding(value, node, scope) : { code: String(Number(value)), type: { kind: "i64" } };
915
+ if (delay.type.kind !== "i64" || !value.startsWith("{") &&
916
+ (!/^[0-9]+$/.test(value) || !Number.isInteger(Number(value)) || Number(value) > 2147483647))
917
+ fail(node, "tooltip-delay requires a non-negative i32 integer");
918
+ props.push(`tooltipDelay: nscvTooltipDelay(${delay.code})`);
919
+ }
920
+ else if (["anchor", "anchor-alignment", "anchor-offset"].includes(name)) {
921
+ if (node.name !== "dropdown-menu" && node.name !== "tooltip") fail(node, `${name} requires dropdown-menu or tooltip`);
922
+ if (name !== "anchor" && !node.attrs.has("anchor")) fail(node, `${name} requires anchor`);
923
+ if (name === "anchor-offset") {
924
+ if (value.trim() === "" || !Number.isFinite(Number(value))) fail(node, "anchor-offset requires a finite literal number");
925
+ props.push(`anchorOffset: ${Number(value)}`);
926
+ }
927
+ else {
928
+ const vocabulary = name === "anchor" ? ["below", "above"] : ["start", "end", "stretch"];
929
+ if (!vocabulary.includes(value)) fail(node, `unsupported ${name}=${value}`);
930
+ props.push(`${name === "anchor" ? "anchor" : "anchorAlignment"}: ${JSON.stringify(value)}`);
931
+ }
932
+ }
933
+ else if (["main", "cross", "size", "variant", "role", "background", "foreground", "border-color", "focus-ring", "accent", "accent-foreground", "radius"].includes(name)) {
934
+ const vocab: Record<string, string[]> = { main: ["start", "center", "end", "space_between"], cross: ["start", "center", "end", "stretch"], size: ["default", "sm", "lg", "icon", "heading", "display"], variant: ["default", "primary", "secondary", "ghost", "destructive", "outline"], role: ["list", "listitem", "tree", "treeitem", "tab"], background: colorTokenNames, foreground: colorTokenNames, "border-color": colorTokenNames, "focus-ring": colorTokenNames, accent: colorTokenNames, "accent-foreground": colorTokenNames, radius: ["sm", "md", "lg", "xl", "none"] };
935
+ if (["variant", "background", "foreground", "border-color", "focus-ring", "accent", "accent-foreground", "radius"].includes(name) && value.startsWith("{")) {
936
+ const expr = binding(value, node, scope);
937
+ const members = contract.types.enums?.find(item => item.name === expr.type.name)?.members;
938
+ if (expr.type.kind !== "enum" || !members?.length || !members.every(member => vocab[name]!.includes(member))) fail(node, `${name} requires its closed token vocabulary`);
939
+ const property = name === "border-color" ? "borderColor" : name === "focus-ring" ? "focusRing" : name === "accent-foreground" ? "accentForeground" : name;
940
+ props.push(`${property}: ${expr.code}`);
941
+ continue;
942
+ }
943
+ if (!vocab[name]!.includes(value)) fail(node, `unsupported ${name}=${value}`);
944
+ if (name === "size" && (value === "heading" || value === "display") && node.name !== "text") fail(node, `${value} size requires text`);
945
+ props.push(`${name === "border-color" ? "borderColor" : name === "focus-ring" ? "focusRing" : name === "accent-foreground" ? "accentForeground" : name}: ${JSON.stringify(value)}`);
946
+ } else if (["on-press", "on-double-press", "on-hold", "on-toggle", "on-change", "on-drag", "on-scroll", "on-terminal", "on-input", "on-submit", "on-dismiss", "on-resize", "on-hover-enter", "on-hover-leave"].includes(name)) {
947
+ const channel = name.slice(3);
948
+ const treeRow = container && node.attrs.get("role") === "treeitem";
949
+ if (channel === "change" && !treeRow && !["radio", "slider", "list-item"].includes(node.name) || channel === "scroll" && node.name !== "scroll" || channel === "dismiss" && !["dropdown-menu", "popover", "menu-surface", "dialog", "drawer", "sheet"].includes(node.name)) fail(node, `${name} is unsupported on ${node.name}`);
950
+ if ((channel === "input" || channel === "submit" && !treeRow) && !["input", "text-field", "search-field", "textarea", "combobox", "code"].includes(node.name)) fail(node, `${name} is unsupported on ${node.name}`);
951
+ if (channel === "terminal" && node.name !== "terminal") fail(node, "on-terminal requires terminal");
952
+ if (channel === "resize" && node.name !== "split") fail(node, "on-resize requires split");
953
+ if (channel === "change" && node.name === "slider" && contract.msg.arms.find(arm => arm.name === value)?.payload.kind !== "void") {
954
+ props.push(`valueChange: ${event(value, "value", node, scope)}`);
955
+ } else props.push(`${channel === "double-press" ? "doublePress" : channel === "hover-enter" ? "hoverEnter" : channel === "hover-leave" ? "hoverLeave" : channel}: ${event(value, channel, node, scope)}`);
956
+ } else fail(node, `unsupported attribute ${name}`);
957
+ }
958
+ const id = next++;
959
+ if (node.name === "tabs" || node.name === "split") output.push(`const nscvStart${id} = nscvNodes.length;`);
960
+ output.push(`const nscvNode${id}: NscViewNode = { end: 0, ${props.join(", ")} };`, `nscvNodes.push(nscvNode${id});`, 'if (nscvNodes.length > 1024) throw new Error("compiled view exceeds 1024 nodes");');
961
+ if (!paragraph) emitChildren(contentChildren, scope, slot, stack, depth + 1); output.push(`nscvNode${id}.end = nscvNodes.length;`);
962
+ if (node.name === "code") {
963
+ const spec = (name: string): string => {
964
+ const raw = node.attrs.get(name);
965
+ if (raw === undefined) return 'new Uint8Array(0)';
966
+ if (!raw.startsWith("{")) return `new TextEncoder().encode(${JSON.stringify(raw)})`;
967
+ const value = binding(raw, node, scope);
968
+ if (value.type.kind !== "bytes") fail(node, `${name} requires one text binding or a literal line list`);
969
+ return value.code;
970
+ };
971
+ output.push(`nscvCodeEditor(nscvNode${id}, ${node.attrs.has("line-numbers") ? bound(node.attrs.get("line-numbers")!, "boolean", node, scope) : "false"}, ${spec("added-lines")}, ${spec("removed-lines")});`);
972
+ }
973
+ if (node.name === "tabs") output.push(`nscvTabs(nscvNodes, nscvStart${id});`);
974
+ if (node.name === "split") output.push(`nscvSplit(nscvNodes, nscvStart${id});`);
975
+ };
976
+ emit(roots[0]!, new Map(), undefined, [], 0);
977
+ return `${exported ? "export " : ""}function ${functionName}(nscvVideo: NscVideoPlaybackState, nscvVirtual?: NscVirtualBuild): Uint8Array {\nconst nscvNodes: NscViewNode[] = [];\n${output.join("\n")}\nif (nscvVirtual?.requestsOnly) return new TextEncoder().encode(JSON.stringify({ format: 1, requests: nscvVirtual.requests }));\nif (nscvVirtual !== undefined && (nscvVirtual.requests.length !== nscvVirtual.ranges.length || nscvVirtual.consumed.length !== nscvVirtual.requests.length)) throw new Error("virtual window context count mismatch");\nif (nscvNodes.length === 0 || nscvNodes[0]!.end !== nscvNodes.length) throw new Error("compiled view requires one rendered root");\nreturn new TextEncoder().encode(JSON.stringify({ format: 2, nodes: nscvNodes }));\n}\n`;
978
+ }
979
+
980
+ const viewPrelude = "\n// Portable Native components compiled beside the committed model.\n" + portableSourceText;