1use std::collections::{BTreeMap, BTreeSet};
28use std::fmt;
29
30use rsjs_ir::abi::{
31 AbiSupport, AbiValidationError, AbiVersion, CapabilitySet, ComponentBindingSource,
32 ComponentBoundary, ComponentCallbackShape, ComponentDescriptor, ComponentEdgeId,
33 ComponentFieldBinding, ComponentFieldCodec, ComponentFieldId, ComponentFieldRole,
34 ComponentFieldSchema, ComponentLifecycleBranch, ComponentLifecycleControl,
35 ComponentSemanticKey, CrossingHookId, DependencyEdge, DependencyEdgeId, DependencyEdgeKind,
36 DependencyEndpoint, DescriptorBody, DescriptorEnvelope, DescriptorHeader, DescriptorKind,
37 DirectComponentEdge, EffectKind, HelperCallEdgeId, HelperDescriptor, HelperSemanticKey,
38 HydrationConstraint, KeyedCollectionSiteId, LocalControlRegionId, LocalEffectId, LocalValueId,
39 OriginId, OriginKind, OriginPermission, ProducerVersion, PropSiteId, PropUse, ProviderSiteId,
40 RegionSiteId, RenderKind, RuntimeCompatibility, SemanticHash, SharedStateProviderSite,
41 SharedStateRefId, SharedStateReference, SpanCardinality, StaticSlotCapability,
42 TemporalPropMode, VersionRange, WitnessRecordId, CLIENT_IR_SCHEMA_VERSION,
43 HELPER_CLIENT_IR_JSON_HASH_DOMAIN, HELPER_CODEGEN_IR_JSON_HASH_DOMAIN,
44 HELPER_SIGNATURE_JSON_HASH_DOMAIN,
45};
46use rsjs_ir::abi::{CanonicalEncode, CanonicalEncoder};
47use rsjs_ir::{
48 client_block_json, client_expr_json, collect_client_block_external_dependencies,
49 parse_client_block_json, parse_client_block_json_with_options,
50 parse_client_expr_json_with_options, parse_client_helper_type, validate_client_helper_block,
51 validate_client_helper_expr, walk_client_block, walk_client_expr, ClientBlock,
52 ClientBlockExternalDependencies, ClientExpr, ClientFunctionRef, ClientHelperTypePosition,
53 ClientJsonParseOptions, ClientModuleCall,
54};
55use rsjs_transport::{
56 canonical_json_bytes, component_field_record_id, component_helper_source_edge_id,
57 component_lifecycle_predicate_graph_commitment, component_record_id, component_source_edge_id,
58 decode_shared_state_schema_abi, helper_direct_call_source_edge_id,
59 shared_state_provider_source_edge_id, shared_state_schema_abi_hash,
60 SharedStateSchemaAbiResolution, SharedStateSchemaUnresolvedReason, TransportCallbackShape,
61 TransportComponentFieldRole, TransportComponentOriginPermission, TransportComponentRenderKind,
62 TransportDirectComponentBinding, TransportDirectComponentBoundary,
63 TransportDirectComponentBranch, TransportDirectComponentEdge, TransportDirectComponentField,
64 TransportDirectComponentLifecycle, TransportDirectLiveCallbackForm,
65 TransportDirectLiveValueSource, TransportDirectStaticCallbackForm, TransportRecordId,
66 TransportSharedStateProviderSite, SHARED_STATE_RUNTIME_ABI_VERSION,
67};
68use serde_json::{Map, Value};
69use thiserror::Error;
70
71use crate::rsjs::legacy_graph::{
72 collect_handler_browser_operations, parse_legacy_client_graph_with_inbound_signals,
73 LegacyAttributeBinding, LegacyBrowserConsumer, LegacyBrowserOperation,
74 LegacyBrowserOperationKind, LegacyClientGraph, LegacyClientOperation,
75 LegacyClientOperationConsumer, LegacyClientOperationKind, LegacyConditionalBinding,
76 LegacyInputBinding, LegacyKeyedCollection, LegacyKeyedCollectionSource, LegacyMutation,
77 LegacyQuery, LegacySignal, LegacyTextBinding,
78};
79use crate::rsjs::link::{
80 shared_state_acquisition_source_edge_id, LinkedComponentEdge, LinkedHelperEdge,
81 LinkedSemanticIdentity, LinkedSharedStateDefinition, LinkedTransportComponent,
82 LinkedTransportHelper, TransportDefinitionId, TransportLinkPlan,
83};
84
85const COMPONENT_PAYLOAD_FORMAT: &str = "rsjs.component_transport_payload";
86const COMPONENT_PAYLOAD_SCHEMA: u64 = 9;
87const COMPONENT_DESCRIPTOR_FORMAT: &str = "rsjs.component_descriptor";
88const COMPONENT_DESCRIPTOR_SCHEMA: u64 = 9;
89const CLIENT_IR_SCHEMA: u64 = CLIENT_IR_SCHEMA_VERSION as u64;
90const HELPER_PAYLOAD_FORMAT: &str = "rsjs.standalone_helper_descriptor";
91const HELPER_PAYLOAD_SCHEMA: u64 = 1;
92const HELPER_HIR_SCHEMA: u64 = 1;
93const HELPER_IR_SCHEMA: u64 = CLIENT_IR_SCHEMA_VERSION as u64;
94const HELPER_CODEC_ABI: u64 = 1;
95const COMPONENT_CLIENT_IR_HASH_DOMAIN: &str = "rsjs.legacy-component-client-program.v3";
96const PAYLOAD_HANDLER_CLIENT_IR_HASH_DOMAIN: &str = "rsjs.payload-handler-client-block.v3";
97
98#[derive(Clone, Debug, PartialEq, Eq)]
105pub struct ResolvedSemanticPath {
106 pub package: String,
108 pub crate_name: String,
110 pub module_path: Vec<String>,
112 pub item: String,
114}
115
116impl ResolvedSemanticPath {
117 pub fn new<I, S>(
120 package: impl Into<String>,
121 crate_name: impl Into<String>,
122 module_path: I,
123 item: impl Into<String>,
124 ) -> Self
125 where
126 I: IntoIterator<Item = S>,
127 S: Into<String>,
128 {
129 Self {
130 package: package.into(),
131 crate_name: crate_name.into(),
132 module_path: module_path.into_iter().map(Into::into).collect(),
133 item: item.into(),
134 }
135 }
136
137 fn component_key(&self) -> Result<ComponentSemanticKey, AbiValidationError> {
138 ComponentSemanticKey::v1(
139 self.package.clone(),
140 self.crate_name.clone(),
141 self.module_path.clone(),
142 self.item.clone(),
143 )
144 }
145
146 fn helper_key(&self) -> Result<HelperSemanticKey, AbiValidationError> {
147 HelperSemanticKey::v1(
148 self.package.clone(),
149 self.crate_name.clone(),
150 self.module_path.clone(),
151 self.item.clone(),
152 )
153 }
154}
155
156impl From<&LinkedSemanticIdentity> for ResolvedSemanticPath {
157 fn from(identity: &LinkedSemanticIdentity) -> Self {
158 Self {
159 package: identity.package.clone(),
160 crate_name: identity.crate_name.clone(),
161 module_path: identity.module_path.clone(),
162 item: identity.item.clone(),
163 }
164 }
165}
166
167#[derive(Clone, Debug)]
169pub struct AbiAdapterContext {
170 producer: ProducerVersion,
171 runtime_protocol: AbiVersion,
172 support: AbiSupport,
173 component_identities: BTreeMap<TransportDefinitionId, ResolvedSemanticPath>,
174 helper_identities: BTreeMap<TransportDefinitionId, ResolvedSemanticPath>,
175 shared_state_definitions: BTreeMap<TransportDefinitionId, ResolvedSharedStateDefinition>,
176}
177
178#[derive(Clone, Debug)]
179struct ResolvedSharedStateDefinition {
180 type_key: String,
181 schema_abi_hash: TransportRecordId,
182 schema_abi: Vec<u8>,
183}
184
185impl AbiAdapterContext {
186 pub fn v1(producer: ProducerVersion, runtime_protocol: AbiVersion) -> Self {
193 Self {
194 producer,
195 runtime_protocol,
196 support: AbiSupport::v1(runtime_protocol),
197 component_identities: BTreeMap::new(),
198 helper_identities: BTreeMap::new(),
199 shared_state_definitions: BTreeMap::new(),
200 }
201 }
202
203 pub fn from_transport_plan(
210 producer: ProducerVersion,
211 runtime_protocol: AbiVersion,
212 plan: &TransportLinkPlan,
213 ) -> Result<Self, AbiAdapterError> {
214 let mut context = Self::v1(producer, runtime_protocol);
215 for component in &plan.components {
216 context.insert_component_identity(
217 component.definition,
218 ResolvedSemanticPath::from(&component.identity),
219 );
220 }
221 for helper in &plan.helpers {
222 context.insert_helper_identity(
223 helper.definition,
224 ResolvedSemanticPath::from(&helper.identity),
225 );
226 }
227 for definition in &plan.shared_state_definitions {
228 context.insert_shared_state_definition(definition)?;
229 }
230 Ok(context)
231 }
232
233 fn insert_shared_state_definition(
234 &mut self,
235 definition: &LinkedSharedStateDefinition,
236 ) -> Result<(), AbiAdapterError> {
237 let resolved = ResolvedSharedStateDefinition {
238 type_key: definition.type_key.clone(),
239 schema_abi_hash: definition.schema_abi_hash,
240 schema_abi: definition.schema_abi.clone(),
241 };
242 if self
243 .shared_state_definitions
244 .insert(definition.definition, resolved)
245 .is_some()
246 {
247 return Err(invalid(
248 "SharedState definition",
249 definition.definition,
250 "the exact definition record appears more than once in the transport plan",
251 ));
252 }
253 Ok(())
254 }
255
256 pub fn insert_component_identity(
258 &mut self,
259 definition: TransportDefinitionId,
260 identity: ResolvedSemanticPath,
261 ) -> Option<ResolvedSemanticPath> {
262 self.component_identities.insert(definition, identity)
263 }
264
265 pub fn insert_helper_identity(
267 &mut self,
268 definition: TransportDefinitionId,
269 identity: ResolvedSemanticPath,
270 ) -> Option<ResolvedSemanticPath> {
271 self.helper_identities.insert(definition, identity)
272 }
273
274 pub fn with_component_identity(
276 mut self,
277 definition: TransportDefinitionId,
278 identity: ResolvedSemanticPath,
279 ) -> Self {
280 self.insert_component_identity(definition, identity);
281 self
282 }
283
284 pub fn with_helper_identity(
286 mut self,
287 definition: TransportDefinitionId,
288 identity: ResolvedSemanticPath,
289 ) -> Self {
290 self.insert_helper_identity(definition, identity);
291 self
292 }
293}
294
295#[derive(Clone, Debug, PartialEq, Eq)]
297#[non_exhaustive]
298pub enum ResolvedTransportWitness {
299 Definition(TransportDefinitionId),
301 ComponentEdge {
303 source_edge: TransportRecordId,
305 target: TransportDefinitionId,
307 },
308 ComponentField {
310 field_record: TransportRecordId,
312 target: TransportDefinitionId,
314 },
315 HelperEdge {
317 source_edge: TransportRecordId,
319 target: TransportDefinitionId,
321 },
322}
323
324#[derive(Clone, Copy, Debug, PartialEq, Eq)]
331pub enum ComponentFragmentRoot {
332 ExactOneElement,
335 Unsupported,
337}
338
339impl CanonicalEncode for ComponentFragmentRoot {
340 fn encode_canonical(&self, encoder: &mut CanonicalEncoder) {
341 encoder.variant(
342 "ComponentFragmentRoot",
343 match self {
344 Self::ExactOneElement => 1,
345 Self::Unsupported => 2,
346 },
347 0,
348 );
349 }
350}
351
352#[derive(Clone, Debug, PartialEq, Eq)]
354pub struct ComponentCodegenInboundField {
355 pub field_id: ComponentFieldId,
357 pub producer_value_id: u32,
359 pub canonical_value: LocalValueId,
361 pub crossing_hook_id: CrossingHookId,
363 pub callback_slot_id: Option<u32>,
365}
366
367impl CanonicalEncode for ComponentCodegenInboundField {
368 fn encode_canonical(&self, encoder: &mut CanonicalEncoder) {
369 encoder.record("ComponentCodegenInboundField", 5);
370 encoder.field(1, &self.field_id);
371 encoder.field(2, &self.producer_value_id);
372 encoder.field(3, &self.canonical_value);
373 encoder.field(4, &self.crossing_hook_id);
374 encoder.field(5, &self.callback_slot_id);
375 }
376}
377
378#[derive(Clone, Debug, PartialEq, Eq)]
380pub struct ComponentCodegenInboundTarget {
381 pub prop_site_id: PropSiteId,
383 pub field_id: ComponentFieldId,
385 pub producer_signal_id: u32,
387 pub canonical_signal_value: LocalValueId,
389}
390
391impl CanonicalEncode for ComponentCodegenInboundTarget {
392 fn encode_canonical(&self, encoder: &mut CanonicalEncoder) {
393 encoder.record("ComponentCodegenInboundTarget", 4);
394 encoder.field(1, &self.prop_site_id);
395 encoder.field(2, &self.field_id);
396 encoder.field(3, &self.producer_signal_id);
397 encoder.field(4, &self.canonical_signal_value);
398 }
399}
400
401#[derive(Clone, Debug, PartialEq, Eq)]
403pub struct ComponentCodegenSignal {
404 pub producer_signal_id: u32,
406 pub canonical_value: LocalValueId,
408}
409
410impl CanonicalEncode for ComponentCodegenSignal {
411 fn encode_canonical(&self, encoder: &mut CanonicalEncoder) {
412 encoder.record("ComponentCodegenSignal", 2);
413 encoder.field(1, &self.producer_signal_id);
414 encoder.field(2, &self.canonical_value);
415 }
416}
417
418#[derive(Clone, Debug, PartialEq, Eq)]
420pub struct ComponentCodegenExpression {
421 pub producer_expression_id: u32,
423 pub canonical_value: LocalValueId,
425}
426
427impl CanonicalEncode for ComponentCodegenExpression {
428 fn encode_canonical(&self, encoder: &mut CanonicalEncoder) {
429 encoder.record("ComponentCodegenExpression", 2);
430 encoder.field(1, &self.producer_expression_id);
431 encoder.field(2, &self.canonical_value);
432 }
433}
434
435#[derive(Clone, Debug, PartialEq, Eq)]
437pub struct ComponentCodegenPayloadHandler {
438 pub prelude_local_index: u32,
440 pub canonical_value: LocalValueId,
442}
443
444impl CanonicalEncode for ComponentCodegenPayloadHandler {
445 fn encode_canonical(&self, encoder: &mut CanonicalEncoder) {
446 encoder.record("ComponentCodegenPayloadHandler", 2);
447 encoder.field(1, &self.prelude_local_index);
448 encoder.field(2, &self.canonical_value);
449 }
450}
451
452#[derive(Clone, Debug, PartialEq, Eq)]
454pub struct ComponentCodegenCallbackSlot {
455 pub producer_callback_slot_id: u32,
457 pub canonical_value: LocalValueId,
459}
460
461impl CanonicalEncode for ComponentCodegenCallbackSlot {
462 fn encode_canonical(&self, encoder: &mut CanonicalEncoder) {
463 encoder.record("ComponentCodegenCallbackSlot", 2);
464 encoder.field(1, &self.producer_callback_slot_id);
465 encoder.field(2, &self.canonical_value);
466 }
467}
468
469#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
472pub enum ComponentNodeRefBindTarget {
473 Element,
475 HtmlElement,
477 Input,
479 TextArea,
481 Select,
483 Form,
485 Dialog,
487}
488
489impl CanonicalEncode for ComponentNodeRefBindTarget {
490 fn encode_canonical(&self, encoder: &mut CanonicalEncoder) {
491 let discriminant = match self {
492 Self::Element => 0,
493 Self::HtmlElement => 1,
494 Self::Input => 2,
495 Self::TextArea => 3,
496 Self::Select => 4,
497 Self::Form => 5,
498 Self::Dialog => 6,
499 };
500 encoder.variant("ComponentNodeRefBindTarget", discriminant, 0);
501 }
502}
503
504#[derive(Clone, Debug, PartialEq, Eq)]
510pub struct ComponentCodegenInboundNodeRef {
511 pub field_id: ComponentFieldId,
513 pub producer_node_ref_id: u32,
515 pub bind_target: Option<ComponentNodeRefBindTarget>,
520}
521
522impl CanonicalEncode for ComponentCodegenInboundNodeRef {
523 fn encode_canonical(&self, encoder: &mut CanonicalEncoder) {
524 encoder.record("ComponentCodegenInboundNodeRef", 3);
525 encoder.field(1, &self.field_id);
526 encoder.field(2, &self.producer_node_ref_id);
527 encoder.field(3, &self.bind_target);
528 }
529}
530
531#[derive(Clone, Debug, PartialEq, Eq)]
533pub struct ComponentCodegenDirectNodeRefAlias {
534 pub edge_id: ComponentEdgeId,
536 pub field_name: String,
538 pub producer_node_ref_id: u32,
540 pub canonical_value: LocalValueId,
542}
543
544impl CanonicalEncode for ComponentCodegenDirectNodeRefAlias {
545 fn encode_canonical(&self, encoder: &mut CanonicalEncoder) {
546 encoder.record("ComponentCodegenDirectNodeRefAlias", 4);
547 encoder.field(1, &self.edge_id);
548 encoder.field(2, &self.field_name);
549 encoder.field(3, &self.producer_node_ref_id);
550 encoder.field(4, &self.canonical_value);
551 }
552}
553
554#[derive(Clone, Debug, PartialEq, Eq)]
561pub struct ComponentCodegenBridge {
562 pub asset_id: String,
564 pub fragment_key: String,
569 pub fragment_root: ComponentFragmentRoot,
571 pub inbound_fields: Vec<ComponentCodegenInboundField>,
573 pub inbound_targets: Vec<ComponentCodegenInboundTarget>,
575 pub signals: Vec<ComponentCodegenSignal>,
577 pub expressions: Vec<ComponentCodegenExpression>,
579 pub payload_handlers: Vec<ComponentCodegenPayloadHandler>,
581 pub callback_slots: Vec<ComponentCodegenCallbackSlot>,
583 pub inbound_node_refs: Vec<ComponentCodegenInboundNodeRef>,
585 pub direct_node_ref_aliases: Vec<ComponentCodegenDirectNodeRefAlias>,
587 pub uses_queries: bool,
593 pub uses_mutations: bool,
599}
600
601impl CanonicalEncode for ComponentCodegenBridge {
602 fn encode_canonical(&self, encoder: &mut CanonicalEncoder) {
603 encoder.record("ComponentCodegenBridge", 13);
604 encoder.field(1, &self.asset_id);
605 encoder.field(2, &self.fragment_key);
606 encoder.field(3, &self.fragment_root);
607 encoder.field(4, &self.inbound_fields);
608 encoder.field(5, &self.inbound_targets);
609 encoder.field(6, &self.signals);
610 encoder.field(7, &self.expressions);
611 encoder.field(8, &self.payload_handlers);
612 encoder.field(9, &self.callback_slots);
613 encoder.field(10, &self.inbound_node_refs);
614 encoder.field(11, &self.direct_node_ref_aliases);
615 encoder.field(12, &self.uses_queries);
616 encoder.field(13, &self.uses_mutations);
617 }
618}
619
620#[derive(Clone, Debug, PartialEq, Eq)]
627pub struct HelperCodegenParam {
628 pub name: String,
631 pub rust_type: String,
633}
634
635impl CanonicalEncode for HelperCodegenParam {
636 fn encode_canonical(&self, encoder: &mut CanonicalEncoder) {
637 encoder.record("HelperCodegenParam", 2);
638 encoder.field(1, &self.name);
639 encoder.field(2, &self.rust_type);
640 }
641}
642
643#[derive(Clone, Debug, PartialEq, Eq)]
645pub struct HelperCodegenSignature {
646 pub params: Vec<HelperCodegenParam>,
648 pub return_type: String,
650}
651
652impl HelperCodegenSignature {
653 pub fn canonical_json(&self) -> Value {
656 serde_json::json!({
657 "params": self.params.iter().map(|param| serde_json::json!({
658 "name": param.name,
659 "rust_type": param.rust_type,
660 })).collect::<Vec<_>>(),
661 "return_type": self.return_type,
662 })
663 }
664
665 pub fn semantic_hash(&self) -> SemanticHash {
667 canonical_legacy_json_hash(HELPER_SIGNATURE_JSON_HASH_DOMAIN, &self.canonical_json())
668 }
669}
670
671impl CanonicalEncode for HelperCodegenSignature {
672 fn encode_canonical(&self, encoder: &mut CanonicalEncoder) {
673 encoder.record("HelperCodegenSignature", 2);
674 encoder.field(1, &self.params);
675 encoder.field(2, &self.return_type);
676 }
677}
678
679#[derive(Clone, Debug)]
686pub enum HelperCodegenBody {
687 Expr(ClientExpr),
689 Block(ClientBlock),
691}
692
693impl PartialEq for HelperCodegenBody {
694 fn eq(&self, other: &Self) -> bool {
695 self.canonical_json() == other.canonical_json()
696 }
697}
698
699impl Eq for HelperCodegenBody {}
704
705impl HelperCodegenBody {
706 pub fn canonical_json(&self) -> Value {
708 let encoded = match self {
709 Self::Expr(expr) => client_expr_json(expr),
710 Self::Block(block) => client_block_json(block),
711 };
712 serde_json::from_str(&encoded).expect("typed Client IR always serializes as canonical JSON")
713 }
714
715 pub fn semantic_hash(&self) -> SemanticHash {
717 canonical_legacy_json_hash(HELPER_CODEGEN_IR_JSON_HASH_DOMAIN, &self.canonical_json())
718 }
719
720 fn validate(
721 &self,
722 parameter_count: usize,
723 ) -> Result<rsjs_ir::ClientHelperValidationReport, rsjs_ir::ClientHelperValidationError> {
724 match self {
725 Self::Expr(expr) => validate_client_helper_expr(expr, parameter_count),
726 Self::Block(block) => validate_client_helper_block(block, parameter_count),
727 }
728 }
729}
730
731impl CanonicalEncode for HelperCodegenBody {
732 fn encode_canonical(&self, encoder: &mut CanonicalEncoder) {
733 let bytes = canonical_json_bytes(&self.canonical_json())
737 .expect("typed Client IR always serializes canonically");
738 match self {
739 Self::Expr(_) => {
740 encoder.variant("HelperCodegenBody", 0, 1);
741 encoder.field(1, &bytes);
742 }
743 Self::Block(_) => {
744 encoder.variant("HelperCodegenBody", 1, 1);
745 encoder.field(1, &bytes);
746 }
747 }
748 }
749}
750
751#[derive(Clone, Debug, PartialEq, Eq)]
759pub struct HelperCodegenBridge {
760 signature: HelperCodegenSignature,
762 source_ir_hash: SemanticHash,
764 body: HelperCodegenBody,
766}
767
768impl HelperCodegenBridge {
769 fn try_new(
777 definition: TransportDefinitionId,
778 signature: HelperCodegenSignature,
779 source_ir_hash: SemanticHash,
780 body: HelperCodegenBody,
781 descriptor: &HelperDescriptor,
782 ) -> Result<Self, String> {
783 let bridge = Self {
784 signature,
785 source_ir_hash,
786 body,
787 };
788 bridge.validate_against(definition, descriptor)?;
789 Ok(bridge)
790 }
791
792 #[cfg(test)]
798 pub(crate) fn try_new_for_test(
799 definition: TransportDefinitionId,
800 signature: HelperCodegenSignature,
801 source_ir_hash: SemanticHash,
802 body: HelperCodegenBody,
803 descriptor: &HelperDescriptor,
804 ) -> Result<Self, String> {
805 Self::try_new(definition, signature, source_ir_hash, body, descriptor)
806 }
807
808 pub fn signature(&self) -> &HelperCodegenSignature {
810 &self.signature
811 }
812
813 pub fn source_ir_hash(&self) -> SemanticHash {
815 self.source_ir_hash
816 }
817
818 pub fn body(&self) -> &HelperCodegenBody {
820 &self.body
821 }
822
823 pub fn body_ir_hash(&self) -> SemanticHash {
828 self.body.semantic_hash()
829 }
830
831 fn validate_against(
832 &self,
833 definition: TransportDefinitionId,
834 descriptor: &HelperDescriptor,
835 ) -> Result<(), String> {
836 validate_helper_codegen_bridge_parts(definition, self, descriptor)
837 }
838}
839
840impl CanonicalEncode for HelperCodegenBridge {
841 fn encode_canonical(&self, encoder: &mut CanonicalEncoder) {
842 encoder.record("HelperCodegenBridge", 4);
843 encoder.field(1, &self.signature);
844 encoder.field(2, &self.source_ir_hash);
845 encoder.field(3, &self.body);
846 encoder.field(4, &self.body_ir_hash());
847 }
848}
849
850fn validate_helper_codegen_body(
851 definition: TransportDefinitionId,
852 body: &HelperCodegenBody,
853 parameter_count: usize,
854 expected_edges: &[HelperCallEdgeId],
855) -> Result<(), String> {
856 let report = body.validate(parameter_count).map_err(|error| {
857 format!("origin-free helper codegen body for {definition:?} is invalid: {error}")
858 })?;
859 let actual_edges = report
860 .calls
861 .iter()
862 .map(|call| call.edge)
863 .collect::<Vec<_>>();
864 if actual_edges != expected_edges {
865 return Err(format!(
866 "helper codegen body has mismatched helper edges: computed {actual_edges:?}, expected \
867 {expected_edges:?}",
868 ));
869 }
870 Ok(())
871}
872
873pub fn validate_helper_codegen_bridge(
876 definition: TransportDefinitionId,
877 codegen: &HelperCodegenBridge,
878 descriptor: &HelperDescriptor,
879) -> Result<(), String> {
880 codegen.validate_against(definition, descriptor)
881}
882
883fn validate_helper_codegen_bridge_parts(
884 definition: TransportDefinitionId,
885 codegen: &HelperCodegenBridge,
886 descriptor: &HelperDescriptor,
887) -> Result<(), String> {
888 if codegen
889 .signature
890 .params
891 .iter()
892 .any(|param| param.name.is_empty() || param.rust_type.is_empty())
893 || codegen.signature.return_type.is_empty()
894 {
895 return Err("helper codegen signature contains an empty name or type".to_owned());
896 }
897 let mut names = BTreeSet::new();
898 if codegen
899 .signature
900 .params
901 .iter()
902 .any(|param| !names.insert(param.name.as_str()))
903 {
904 return Err("helper codegen signature contains duplicate parameter names".to_owned());
905 }
906 for param in &codegen.signature.params {
907 parse_client_helper_type(¶m.rust_type, ClientHelperTypePosition::Parameter).map_err(
908 |error| {
909 format!(
910 "helper codegen parameter `{}` has an invalid type: {error}",
911 param.name,
912 )
913 },
914 )?;
915 }
916 if let Err(error) = parse_client_helper_type(
917 &codegen.signature.return_type,
918 ClientHelperTypePosition::Return,
919 ) {
920 return Err(format!(
921 "helper codegen has an invalid return type: {error}"
922 ));
923 }
924 let signature_hash = codegen.signature.semantic_hash();
925 if signature_hash != descriptor.signature_hash {
926 return Err(format!(
927 "helper codegen signature hash {signature_hash} does not match descriptor hash {}",
928 descriptor.signature_hash,
929 ));
930 }
931 if codegen.source_ir_hash != descriptor.client_ir_hash {
932 return Err(format!(
933 "helper codegen source IR hash {} does not match descriptor hash {}",
934 codegen.source_ir_hash, descriptor.client_ir_hash,
935 ));
936 }
937 let expected_edges = descriptor
938 .direct_helpers
939 .keys()
940 .copied()
941 .collect::<Vec<_>>();
942 validate_helper_codegen_body(
943 definition,
944 &codegen.body,
945 codegen.signature.params.len(),
946 &expected_edges,
947 )
948}
949
950#[derive(Clone, Debug, PartialEq, Eq)]
956pub struct CanonicalDescriptorBridge {
957 pub(crate) envelope: DescriptorEnvelope,
959 pub(crate) witnesses: BTreeMap<WitnessRecordId, ResolvedTransportWitness>,
961 codegen: CanonicalDescriptorCodegen,
962}
963
964#[derive(Clone, Debug, PartialEq, Eq)]
965enum CanonicalDescriptorCodegen {
966 Component(ComponentCodegenBridge),
967 Helper(HelperCodegenBridge),
968}
969
970impl CanonicalDescriptorBridge {
971 pub fn envelope(&self) -> &DescriptorEnvelope {
973 &self.envelope
974 }
975
976 pub fn witnesses(&self) -> &BTreeMap<WitnessRecordId, ResolvedTransportWitness> {
978 &self.witnesses
979 }
980
981 pub fn component_codegen(&self) -> Option<&ComponentCodegenBridge> {
983 match &self.codegen {
984 CanonicalDescriptorCodegen::Component(codegen) => Some(codegen),
985 CanonicalDescriptorCodegen::Helper(_) => None,
986 }
987 }
988
989 pub fn helper_codegen(&self) -> Option<&HelperCodegenBridge> {
991 match &self.codegen {
992 CanonicalDescriptorCodegen::Component(_) => None,
993 CanonicalDescriptorCodegen::Helper(codegen) => Some(codegen),
994 }
995 }
996
997 pub(crate) fn try_component(
998 envelope: DescriptorEnvelope,
999 witnesses: BTreeMap<WitnessRecordId, ResolvedTransportWitness>,
1000 codegen: ComponentCodegenBridge,
1001 ) -> Result<Self, String> {
1002 let DescriptorBody::Component(descriptor) = &envelope.body else {
1003 return Err("component codegen requires a component descriptor".to_owned());
1004 };
1005 validate_component_codegen_bridge(&codegen, descriptor)?;
1006 Ok(Self {
1007 envelope,
1008 witnesses,
1009 codegen: CanonicalDescriptorCodegen::Component(codegen),
1010 })
1011 }
1012
1013 pub(crate) fn try_helper(
1014 definition: TransportDefinitionId,
1015 envelope: DescriptorEnvelope,
1016 witnesses: BTreeMap<WitnessRecordId, ResolvedTransportWitness>,
1017 codegen: HelperCodegenBridge,
1018 ) -> Result<Self, String> {
1019 let DescriptorBody::Helper(descriptor) = &envelope.body else {
1020 return Err("helper codegen requires a helper descriptor".to_owned());
1021 };
1022 validate_helper_codegen_bridge(definition, &codegen, descriptor)?;
1023 Ok(Self {
1024 envelope,
1025 witnesses,
1026 codegen: CanonicalDescriptorCodegen::Helper(codegen),
1027 })
1028 }
1029
1030 #[cfg(test)]
1031 pub(crate) fn component_codegen_mut(&mut self) -> Option<&mut ComponentCodegenBridge> {
1032 match &mut self.codegen {
1033 CanonicalDescriptorCodegen::Component(codegen) => Some(codegen),
1034 CanonicalDescriptorCodegen::Helper(_) => None,
1035 }
1036 }
1037
1038 #[cfg(test)]
1039 pub(crate) fn replace_component_codegen_unchecked(&mut self, codegen: ComponentCodegenBridge) {
1040 self.codegen = CanonicalDescriptorCodegen::Component(codegen);
1041 }
1042
1043 #[cfg(test)]
1044 pub(crate) fn replace_helper_codegen_unchecked(&mut self, codegen: HelperCodegenBridge) {
1045 self.codegen = CanonicalDescriptorCodegen::Helper(codegen);
1046 }
1047}
1048
1049#[derive(Clone, Debug, PartialEq, Eq)]
1051#[non_exhaustive]
1052pub enum AbiBridgeResult {
1053 Canonical(CanonicalDescriptorBridge),
1055 Unsupported(UnsupportedDescriptor),
1058}
1059
1060impl AbiBridgeResult {
1061 pub fn canonical(&self) -> Option<&CanonicalDescriptorBridge> {
1063 match self {
1064 Self::Canonical(descriptor) => Some(descriptor),
1065 Self::Unsupported(_) => None,
1066 }
1067 }
1068}
1069
1070#[derive(Clone, Debug, PartialEq, Eq)]
1072pub struct UnsupportedDescriptor {
1073 pub kind: DescriptorKind,
1075 pub definition: TransportDefinitionId,
1077 pub gaps: Vec<CompatibilityGap>,
1079}
1080
1081impl fmt::Display for UnsupportedDescriptor {
1082 fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
1083 write!(
1084 formatter,
1085 "{:?} descriptor {:?} cannot be converted to canonical ABI v1",
1086 self.kind, self.definition
1087 )?;
1088 for gap in &self.gaps {
1089 write!(formatter, "; {gap}")?;
1090 }
1091 Ok(())
1092 }
1093}
1094
1095#[derive(Clone, Debug, PartialEq, Eq)]
1097#[non_exhaustive]
1098pub enum CompatibilityGap {
1099 MissingResolvedSemanticIdentity,
1101 ComponentFieldWitnessesMissing {
1104 fields: Vec<String>,
1106 },
1107 ComponentClientGraphMetadataMissing {
1110 features: Vec<String>,
1112 },
1113 DirectComponentBindingMetadataMissing {
1115 edges: usize,
1117 },
1118 RepeatedDirectComponentSites {
1120 edges: Vec<u32>,
1122 },
1123 UnknownDirectComponentSites {
1125 edges: Vec<u32>,
1127 },
1128 SharedStateSchemaAbiMissing {
1131 stores: usize,
1133 },
1134 UnknownViewNodeKind,
1136}
1137
1138impl fmt::Display for CompatibilityGap {
1139 fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
1140 match self {
1141 Self::MissingResolvedSemanticIdentity => formatter.write_str(
1142 "missing normalized package/crate/module/item identity from the defining relocation",
1143 ),
1144 Self::ComponentFieldWitnessesMissing { fields } => write!(
1145 formatter,
1146 "legacy component fields lack concrete type/crossing witnesses: {}",
1147 fields.join(", ")
1148 ),
1149 Self::ComponentClientGraphMetadataMissing { features } => write!(
1150 formatter,
1151 "legacy client graph lacks canonical typed origin/effect/dependency metadata for: {}",
1152 features.join(", ")
1153 ),
1154 Self::DirectComponentBindingMetadataMissing { edges } => write!(
1155 formatter,
1156 "{edges} direct component edge(s) cannot be losslessly adapted as static \
1157 server-only composition"
1158 ),
1159 Self::RepeatedDirectComponentSites { edges } => write!(
1160 formatter,
1161 "repeated direct component edge(s) {edges:?} require a keyed instance lifecycle ABI"
1162 ),
1163 Self::UnknownDirectComponentSites { edges } => write!(
1164 formatter,
1165 "direct component edge(s) {edges:?} have nested/unknown structural lifecycle semantics"
1166 ),
1167 Self::SharedStateSchemaAbiMissing { stores } => write!(
1168 formatter,
1169 "{stores} SharedState acquisition(s) lack type_key/schema ABI metadata"
1170 ),
1171 Self::UnknownViewNodeKind => formatter.write_str(
1172 "legacy view-tree serialization contains an unknown node kind",
1173 ),
1174 }
1175 }
1176}
1177
1178#[derive(Clone, Debug, PartialEq, Eq)]
1180pub struct AdaptedTransportAbi {
1181 pub components: Vec<AbiBridgeResult>,
1183 pub helpers: Vec<AbiBridgeResult>,
1185}
1186
1187#[derive(Debug, Error)]
1189#[non_exhaustive]
1190pub enum AbiAdapterError {
1191 #[error("invalid linked {kind} payload for {definition:?}: {reason}")]
1193 InvalidPayload {
1194 kind: &'static str,
1196 definition: TransportDefinitionId,
1198 reason: String,
1200 },
1201 #[error(
1203 "linked {kind} payload hash disagrees with its transport link result for {definition:?}: payload {payload}, linked {linked}"
1204 )]
1205 SemanticHashMismatch {
1206 kind: &'static str,
1208 definition: TransportDefinitionId,
1210 payload: SemanticHash,
1212 linked: SemanticHash,
1214 },
1215 #[error(
1217 "linked {kind} source-edge set disagrees with payload for {definition:?}: payload {payload:?}, linked {linked:?}"
1218 )]
1219 SourceEdgeSetMismatch {
1220 kind: &'static str,
1222 definition: TransportDefinitionId,
1224 payload: Vec<String>,
1226 linked: Vec<String>,
1228 },
1229 #[error(
1232 "component field witness `{field}` for {definition:?} has record ID {actual}, expected {expected}"
1233 )]
1234 ComponentFieldRecordIdMismatch {
1235 definition: TransportDefinitionId,
1237 field: String,
1239 expected: String,
1241 actual: String,
1243 },
1244 #[error(
1246 "component field witnesses `{first_field}` and `{second_field}` for {definition:?} reuse record ID {field_record}"
1247 )]
1248 DuplicateComponentFieldRecordId {
1249 definition: TransportDefinitionId,
1251 first_field: String,
1253 second_field: String,
1255 field_record: String,
1257 },
1258 #[error("invalid resolved semantic identity for {kind} {definition:?}: {source}")]
1260 InvalidSemanticIdentity {
1261 kind: &'static str,
1263 definition: TransportDefinitionId,
1265 #[source]
1267 source: AbiValidationError,
1268 },
1269 #[error("canonical descriptor validation failed for {kind} {definition:?}: {source}")]
1271 CanonicalValidation {
1272 kind: &'static str,
1274 definition: TransportDefinitionId,
1276 #[source]
1278 source: AbiValidationError,
1279 },
1280}
1281
1282pub fn adapt_transport_plan(
1284 context: &AbiAdapterContext,
1285 plan: &TransportLinkPlan,
1286) -> Result<AdaptedTransportAbi, AbiAdapterError> {
1287 let projection_roles = resolve_deferred_projection_roles(plan)?;
1288 let components = plan
1289 .components
1290 .iter()
1291 .map(|component| {
1292 adapt_component_with_projection_roles(context, component, &projection_roles)
1293 })
1294 .collect::<Result<Vec<_>, _>>()?;
1295 let helpers = plan
1296 .helpers
1297 .iter()
1298 .map(|helper| adapt_helper(context, helper))
1299 .collect::<Result<Vec<_>, _>>()?;
1300 Ok(AdaptedTransportAbi {
1301 components,
1302 helpers,
1303 })
1304}
1305
1306pub fn adapt_component(
1312 context: &AbiAdapterContext,
1313 linked: &LinkedTransportComponent,
1314) -> Result<AbiBridgeResult, AbiAdapterError> {
1315 adapt_component_with_projection_roles(context, linked, &ResolvedProjectionRoles::default())
1316}
1317
1318fn adapt_component_with_projection_roles(
1319 context: &AbiAdapterContext,
1320 linked: &LinkedTransportComponent,
1321 projection_roles: &ResolvedProjectionRoles,
1322) -> Result<AbiBridgeResult, AbiAdapterError> {
1323 let root = payload_object("component", linked.definition, &linked.payload)?;
1324 require_known_fields(
1325 "component transport payload",
1326 root,
1327 &[
1328 "component_descriptor",
1329 "format",
1330 "schema_version",
1331 "semantic_hash",
1332 "transport",
1333 ],
1334 linked.definition,
1335 )?;
1336 require_exact_str(
1337 root,
1338 "format",
1339 COMPONENT_PAYLOAD_FORMAT,
1340 "component",
1341 linked.definition,
1342 )?;
1343 require_exact_u64(
1344 root,
1345 "schema_version",
1346 COMPONENT_PAYLOAD_SCHEMA,
1347 "component",
1348 linked.definition,
1349 )?;
1350 validate_linked_semantic_hash("component", linked.definition, root, linked.semantic_hash)?;
1351
1352 let transport = required_object(root, "transport", "component", linked.definition)?;
1353 require_known_fields(
1354 "component transport metadata",
1355 transport,
1356 &[
1357 "client_value_sources",
1358 "component_field_witnesses",
1359 "component_input_fingerprint",
1360 "definition_record_id",
1361 "direct_component_edges",
1362 "hydration_constraint",
1363 "reachable_helper_edges",
1364 "shared_state_acquisitions",
1365 "shared_state_provider_sites",
1366 ],
1367 linked.definition,
1368 )?;
1369 validate_definition_record(
1370 "component",
1371 linked.definition,
1372 transport,
1373 "definition_record_id",
1374 )?;
1375 let input_fingerprint = validated_component_input_fingerprint(linked, transport)?;
1376
1377 let descriptor = required_object(root, "component_descriptor", "component", linked.definition)?;
1378 validate_component_descriptor_header(linked.definition, descriptor)?;
1379 let (render_kind, origin_permission) = validate_component_definition_abi(linked, descriptor)?;
1380 let direct_component_edges = validate_component_edge_set(
1381 linked,
1382 transport,
1383 descriptor,
1384 input_fingerprint,
1385 projection_roles,
1386 )?;
1387 let direct_helper_edges =
1388 validate_component_helper_edge_set(linked, transport, input_fingerprint)?;
1389 let shared_state_acquisitions =
1390 validate_component_shared_state_acquisition_set(linked, transport, descriptor)?;
1391 let shared_state_provider_sites = validate_component_shared_state_provider_site_set(
1392 context,
1393 linked,
1394 transport,
1395 descriptor,
1396 input_fingerprint,
1397 &direct_component_edges,
1398 )?;
1399 let hydration_constraint = validate_hydration_constraint(linked.definition, transport)?;
1400 let inbound_inputs = validate_inbound_inputs_with_projection_roles(
1401 linked.definition,
1402 descriptor,
1403 projection_roles,
1404 )?;
1405 let payload_handlers = validate_payload_handler_values(
1406 linked,
1407 transport,
1408 descriptor,
1409 &inbound_inputs,
1410 &direct_component_edges,
1411 &direct_helper_edges,
1412 )?;
1413 let value_layout = ComponentValueLayout::new_with_handles(
1414 linked.definition,
1415 &inbound_inputs,
1416 descriptor,
1417 payload_handlers.len(),
1418 &direct_component_edges,
1419 )?;
1420 let reachable_helper_ordinals = direct_helper_edges
1421 .iter()
1422 .map(|edge| edge.local_ordinal)
1423 .collect::<BTreeSet<_>>();
1424 let authenticated_unknown_signal_types = authenticated_unknown_inbound_signals(&inbound_inputs);
1425 let extra_signal_roots = direct_component_edges
1426 .iter()
1427 .flat_map(|edge| &edge.fields)
1428 .filter_map(|field| match field.binding {
1429 ValidatedDirectComponentBinding::LiveValue { signal, .. } => Some(signal),
1430 _ => None,
1431 })
1432 .collect::<BTreeSet<_>>();
1433 let legacy_graph = parse_legacy_client_graph_with_inbound_signals(
1434 descriptor,
1435 &reachable_helper_ordinals,
1436 &authenticated_unknown_signal_types,
1437 &extra_signal_roots,
1438 )
1439 .map_err(|reason| {
1440 invalid(
1441 "component",
1442 linked.definition,
1443 format!("invalid schema-v9 client graph: {reason}"),
1444 )
1445 })?;
1446 let direct_node_ref_sources = direct_component_edges
1447 .iter()
1448 .flat_map(|edge| edge.fields.iter())
1449 .filter_map(|field| match field.binding {
1450 ValidatedDirectComponentBinding::NodeRefHandle { node_ref } => Some(node_ref),
1451 _ => None,
1452 })
1453 .collect::<BTreeSet<_>>();
1454 let reachable_node_refs = legacy_graph
1455 .reachable_node_refs
1456 .iter()
1457 .copied()
1458 .chain(direct_node_ref_sources.iter().copied())
1459 .collect::<BTreeSet<_>>()
1460 .into_iter()
1461 .collect::<Vec<_>>();
1462 validate_node_ref_handle_topology(
1463 linked.definition,
1464 &inbound_inputs,
1465 &legacy_graph,
1466 &direct_component_edges,
1467 )?;
1468 let active_shared_state = resolve_active_shared_state_plan(
1469 context,
1470 linked.definition,
1471 &legacy_graph,
1472 &shared_state_acquisitions,
1473 )?;
1474 validate_query_key_prop_targets(linked.definition, &inbound_inputs, &legacy_graph)?;
1475 let bound_handler_ids = legacy_graph
1476 .bindings
1477 .events
1478 .iter()
1479 .map(|binding| binding.handler)
1480 .collect::<BTreeSet<_>>();
1481 let bound_handler_count = legacy_graph
1482 .handlers
1483 .iter()
1484 .filter(|handler| bound_handler_ids.contains(&handler.id))
1485 .count();
1486 let legacy_expression_browser_operation_count = legacy_graph
1487 .expressions
1488 .iter()
1489 .map(|expression| expression.browser_operations.len())
1490 .try_fold(0_usize, |count, operations| count.checked_add(operations))
1491 .ok_or_else(|| {
1492 invalid(
1493 "component",
1494 linked.definition,
1495 "legacy expression browser-operation count overflows usize",
1496 )
1497 })?;
1498 let legacy_handler_browser_operation_count = legacy_graph
1499 .handlers
1500 .iter()
1501 .filter(|handler| bound_handler_ids.contains(&handler.id))
1502 .map(|handler| handler.browser_operations.len())
1503 .try_fold(0_usize, |count, operations| count.checked_add(operations))
1504 .ok_or_else(|| {
1505 invalid(
1506 "component",
1507 linked.definition,
1508 "legacy handler browser-operation count overflows usize",
1509 )
1510 })?;
1511 let legacy_browser_operation_count = legacy_expression_browser_operation_count
1512 .checked_add(legacy_handler_browser_operation_count)
1513 .ok_or_else(|| {
1514 invalid(
1515 "component",
1516 linked.definition,
1517 "legacy browser-operation count overflows usize",
1518 )
1519 })?;
1520 let payload_browser_operation_count = payload_handlers
1521 .iter()
1522 .map(|handler| handler.browser_operations.len())
1523 .try_fold(0_usize, |count, operations| count.checked_add(operations))
1524 .ok_or_else(|| {
1525 invalid(
1526 "component",
1527 linked.definition,
1528 "payload browser-operation count overflows usize",
1529 )
1530 })?;
1531 let browser_operation_count = payload_browser_operation_count
1532 .checked_add(legacy_browser_operation_count)
1533 .ok_or_else(|| {
1534 invalid(
1535 "component",
1536 linked.definition,
1537 "payload and legacy browser-operation counts overflow usize",
1538 )
1539 })?;
1540 let dom_binding_count = legacy_graph.bindings.text.len()
1541 + legacy_graph.bindings.attributes.len()
1542 + legacy_graph.bindings.inputs.len()
1543 + legacy_graph.bindings.conditionals.len()
1544 + legacy_graph.keyed_collections.len();
1545 let callback_values =
1546 payload_handler_value_map(linked.definition, &payload_handlers, &value_layout)?;
1547 let origin_layout = ComponentOriginLayout::new(
1548 linked.definition,
1549 inbound_inputs.prop_uses.len(),
1550 payload_handlers.len(),
1551 legacy_graph.signals.len(),
1552 legacy_graph.expressions.len(),
1553 bound_handler_count,
1554 browser_operation_count,
1555 reachable_node_refs.len(),
1556 legacy_graph.reachable_queries.len(),
1557 legacy_graph.reachable_mutations.len(),
1558 active_shared_state.stores.len(),
1559 dom_binding_count,
1560 direct_component_edges.len(),
1561 )?;
1562 let witness_layout = ComponentWitnessLayout::new(
1563 linked.definition,
1564 direct_component_edges.len(),
1565 inbound_inputs.fields.len(),
1566 direct_helper_edges.len(),
1567 )?;
1568 let field_witnesses = validate_component_field_witness_set(
1569 linked,
1570 transport,
1571 &inbound_inputs.fields,
1572 &witness_layout,
1573 )?;
1574 let adapted_fields = adapt_component_fields(
1575 linked.definition,
1576 descriptor,
1577 &inbound_inputs,
1578 &field_witnesses,
1579 &value_layout,
1580 )?;
1581 let immutable_static_slot_names = adapted_fields
1582 .canonical
1583 .values()
1584 .filter(|field| {
1585 field.role == ComponentFieldRole::Slot
1586 && matches!(field.static_slot, StaticSlotCapability::Immutable { .. })
1587 })
1588 .map(|field| field.source_name.clone())
1589 .collect::<BTreeSet<_>>();
1590 let view = validate_view_tree(
1591 linked.definition,
1592 descriptor,
1593 &direct_component_edges,
1594 &legacy_graph.bindings.conditionals,
1595 &immutable_static_slot_names,
1596 )?;
1597
1598 let mut gaps = Vec::new();
1599 let identity = context.component_identities.get(&linked.definition);
1600 if identity.is_none() {
1601 gaps.push(CompatibilityGap::MissingResolvedSemanticIdentity);
1602 }
1603
1604 let mut features = legacy_graph.unsupported_features.clone();
1605 if active_shared_state.operation_shapes_supported {
1606 features.retain(|feature| feature != "shared_backed_signals");
1607 }
1608 if payload_handlers
1609 .iter()
1610 .any(|handler| !handler.dependencies.client_module_calls.is_empty())
1611 {
1612 features.push("payload_handlers.client_module_calls".to_owned());
1613 features.sort();
1614 features.dedup();
1615 }
1616 for (used, feature) in [
1617 (
1618 payload_handlers
1619 .iter()
1620 .any(|handler| handler.dependencies.uses_node_payload),
1621 "payload_handlers.node_payload",
1622 ),
1623 (
1624 payload_handlers
1625 .iter()
1626 .any(|handler| !handler.dependencies.node_refs.is_empty()),
1627 "payload_handlers.node_refs",
1628 ),
1629 (
1630 payload_handlers
1631 .iter()
1632 .any(|handler| !handler.dependencies.queries.is_empty()),
1633 "payload_handlers.queries",
1634 ),
1635 (
1636 payload_handlers
1637 .iter()
1638 .any(|handler| !handler.dependencies.mutations.is_empty()),
1639 "payload_handlers.mutations",
1640 ),
1641 ] {
1642 if used {
1643 features.push(feature.to_owned());
1644 }
1645 }
1646 features.sort();
1647 features.dedup();
1648 let has_live_direct_component_bindings = direct_component_edges.iter().any(|edge| {
1649 edge.fields.iter().any(|field| {
1650 matches!(
1651 field.binding,
1652 ValidatedDirectComponentBinding::LiveValue { .. }
1653 | ValidatedDirectComponentBinding::LiveCallback { .. }
1654 | ValidatedDirectComponentBinding::ForwardedCallback { .. }
1655 | ValidatedDirectComponentBinding::NodeRefHandle { .. }
1656 )
1657 })
1658 });
1659 let static_repetition_is_the_only_unsupported_shape = features.as_slice()
1660 == ["unsupported_shapes"]
1661 && direct_component_edges
1662 .iter()
1663 .any(|edge| matches!(edge.lifecycle, ValidatedDirectComponentLifecycle::Repeated))
1664 && legacy_graph.signals.is_empty()
1665 && legacy_graph.expressions.is_empty()
1666 && legacy_graph.handlers.is_empty()
1667 && legacy_graph.callback_slots.is_empty()
1668 && legacy_graph.bindings.text.is_empty()
1669 && legacy_graph.bindings.attributes.is_empty()
1670 && legacy_graph.bindings.inputs.is_empty()
1671 && legacy_graph.bindings.events.is_empty()
1672 && legacy_graph.node_refs.is_empty()
1673 && legacy_graph.queries.is_empty()
1674 && legacy_graph.mutations.is_empty()
1675 && inbound_inputs.fields.is_empty()
1676 && payload_handlers.is_empty()
1677 && direct_helper_edges.is_empty()
1678 && !active_shared_state.is_active()
1679 && !has_live_direct_component_bindings;
1680 if static_repetition_is_the_only_unsupported_shape {
1681 features.clear();
1685 }
1686 let has_legacy_client_state = !features.is_empty()
1687 || !legacy_graph.signals.is_empty()
1688 || !legacy_graph.expressions.is_empty()
1689 || !legacy_graph.handlers.is_empty()
1690 || !legacy_graph.callback_slots.is_empty()
1691 || !legacy_graph.bindings.text.is_empty()
1692 || !legacy_graph.bindings.attributes.is_empty()
1693 || !legacy_graph.bindings.inputs.is_empty()
1694 || !legacy_graph.bindings.events.is_empty()
1695 || !legacy_graph.keyed_collections.is_empty()
1696 || !legacy_graph.node_refs.is_empty()
1697 || !legacy_graph.queries.is_empty()
1698 || !legacy_graph.mutations.is_empty()
1699 || !inbound_inputs.fields.is_empty()
1700 || !payload_handlers.is_empty()
1701 || !direct_helper_edges.is_empty()
1702 || active_shared_state.is_active()
1703 || has_live_direct_component_bindings;
1704 if !features.is_empty() {
1705 gaps.push(CompatibilityGap::ComponentClientGraphMetadataMissing { features });
1706 }
1707 if direct_component_edges
1708 .iter()
1709 .any(|edge| !edge.has_supported_binding_shape())
1710 {
1711 gaps.push(CompatibilityGap::DirectComponentBindingMetadataMissing {
1712 edges: linked.component_edges.len(),
1713 });
1714 }
1715 let repeated_component_edges = direct_component_edges
1716 .iter()
1717 .filter_map(|edge| {
1718 matches!(edge.lifecycle, ValidatedDirectComponentLifecycle::Repeated)
1719 .then_some(edge.local_ordinal)
1720 })
1721 .collect::<Vec<_>>();
1722 if !repeated_component_edges.is_empty() {
1723 gaps.push(CompatibilityGap::RepeatedDirectComponentSites {
1724 edges: repeated_component_edges,
1725 });
1726 }
1727 let unknown_component_edges = direct_component_edges
1728 .iter()
1729 .filter_map(|edge| {
1730 matches!(
1731 edge.lifecycle,
1732 ValidatedDirectComponentLifecycle::UnknownNestedConditionals
1733 )
1734 .then_some(edge.local_ordinal)
1735 })
1736 .collect::<Vec<_>>();
1737 if !unknown_component_edges.is_empty() {
1738 gaps.push(CompatibilityGap::UnknownDirectComponentSites {
1739 edges: unknown_component_edges,
1740 });
1741 }
1742 if view.has_unknown_kind {
1743 gaps.push(CompatibilityGap::UnknownViewNodeKind);
1744 }
1745
1746 if !gaps.is_empty() {
1747 return Ok(AbiBridgeResult::Unsupported(UnsupportedDescriptor {
1748 kind: DescriptorKind::Component,
1749 definition: linked.definition,
1750 gaps,
1751 }));
1752 }
1753
1754 let identity = identity.expect("missing identity returned as an unsupported gap");
1755 let semantic_key =
1756 identity
1757 .component_key()
1758 .map_err(|source| AbiAdapterError::InvalidSemanticIdentity {
1759 kind: "component",
1760 definition: linked.definition,
1761 source,
1762 })?;
1763 let mut descriptor_body = ComponentDescriptor::v1(
1764 semantic_key,
1765 WitnessRecordId::new(0),
1766 render_kind,
1767 origin_permission,
1768 view.root_span.clone(),
1769 );
1770 descriptor_body.root_eligible = immutable_static_slot_names.is_empty();
1776 descriptor_body.hydration = hydration_constraint;
1777 if has_legacy_client_state {
1778 descriptor_body.client_ir_hash = canonical_legacy_json_hash(
1779 COMPONENT_CLIENT_IR_HASH_DOMAIN,
1780 &legacy_component_client_program_material(descriptor, &payload_handlers),
1781 );
1782 }
1783 descriptor_body.fields.extend(adapted_fields.canonical);
1784 populate_component_input_graph(
1785 linked.definition,
1786 &mut descriptor_body,
1787 &inbound_inputs,
1788 &value_layout,
1789 origin_layout,
1790 )?;
1791 let shared_state_origins = populate_shared_state_references(
1792 linked.definition,
1793 &mut descriptor_body,
1794 &legacy_graph,
1795 &active_shared_state,
1796 &value_layout,
1797 origin_layout,
1798 )?;
1799 let mut browser_operation_ordinal = 0_u32;
1800 populate_payload_handler_graph(
1801 linked.definition,
1802 &mut descriptor_body,
1803 &payload_handlers,
1804 &inbound_inputs,
1805 &value_layout,
1806 origin_layout,
1807 &direct_helper_edges,
1808 &shared_state_origins,
1809 &mut browser_operation_ordinal,
1810 )?;
1811 populate_legacy_client_graph(
1812 linked.definition,
1813 &mut descriptor_body,
1814 &legacy_graph,
1815 &inbound_inputs,
1816 &value_layout,
1817 origin_layout,
1818 &direct_helper_edges,
1819 &shared_state_origins,
1820 &reachable_node_refs,
1821 &mut browser_operation_ordinal,
1822 )?;
1823 if browser_operation_ordinal != origin_layout.browser_operation_count {
1824 return Err(invalid(
1825 "component",
1826 linked.definition,
1827 format!(
1828 "canonical browser-operation lowering consumed {browser_operation_ordinal} origins, but the validated payload and legacy graphs reserved {}",
1829 origin_layout.browser_operation_count,
1830 ),
1831 ));
1832 }
1833 for edge in &direct_component_edges {
1834 let edge_id = ComponentEdgeId::new(edge.local_ordinal);
1835 let origin = origin_layout.component(linked.definition, edge.local_ordinal)?;
1836 let witness = witness_layout.component(linked.definition, edge.local_ordinal)?;
1837 descriptor_body
1838 .origins
1839 .insert(origin, OriginKind::SourceOnly);
1840 let bindings = adapt_direct_component_bindings(
1841 linked.definition,
1842 &edge.fields,
1843 &value_layout,
1844 &callback_values,
1845 origin,
1846 )?;
1847 let lifecycle_control = match edge.lifecycle {
1848 ValidatedDirectComponentLifecycle::StaticSingle => None,
1849 ValidatedDirectComponentLifecycle::ConditionalSingle {
1850 control,
1851 predicate_expression,
1852 branch,
1853 ..
1854 } => {
1855 let expected_predicate =
1856 value_layout.expr(linked.definition, predicate_expression)?;
1857 Some(canonical_component_lifecycle_control(
1858 linked.definition,
1859 &descriptor_body,
1860 control,
1861 expected_predicate,
1862 branch,
1863 )?)
1864 }
1865 ValidatedDirectComponentLifecycle::Repeated
1866 | ValidatedDirectComponentLifecycle::UnknownNestedConditionals => {
1867 unreachable!("unsupported component lifecycle returned before canonical lowering")
1868 }
1869 };
1870 descriptor_body.direct_components.insert(
1871 edge_id,
1872 DirectComponentEdge {
1873 witness,
1874 boundary: if edge.composed {
1875 ComponentBoundary::Composed
1876 } else {
1877 ComponentBoundary::IndependentIsland
1878 },
1879 bindings: bindings.clone(),
1880 lifecycle_control,
1881 origin,
1882 },
1883 );
1884 if let Some(lifecycle) = lifecycle_control {
1885 push_dependency(
1886 linked.definition,
1887 &mut descriptor_body,
1888 DependencyEdgeKind::Control,
1889 DependencyEndpoint::Control(lifecycle.control),
1890 DependencyEndpoint::Component(edge_id),
1891 origin,
1892 )?;
1893 }
1894 for binding in bindings.values() {
1895 let value = match binding.source {
1896 ComponentBindingSource::LiveValue { value }
1897 | ComponentBindingSource::LiveCallback { value, .. }
1898 | ComponentBindingSource::ClientHandle { value } => Some(value),
1899 _ => None,
1900 };
1901 let Some(value) = value else {
1902 continue;
1903 };
1904 for kind in [
1905 DependencyEdgeKind::Component,
1906 DependencyEdgeKind::OwnerCoupling,
1907 ] {
1908 push_dependency(
1909 linked.definition,
1910 &mut descriptor_body,
1911 kind,
1912 DependencyEndpoint::Value(value),
1913 DependencyEndpoint::Component(edge_id),
1914 origin,
1915 )?;
1916 }
1917 }
1918 }
1919 for site in &shared_state_provider_sites {
1920 descriptor_body.shared_state_providers.insert(
1921 ProviderSiteId::new(site.provider_site_id),
1922 SharedStateProviderSite {
1923 child_edge: ComponentEdgeId::new(site.child_edge_local_ordinal),
1924 type_key: site.type_key.clone(),
1925 schema_abi: site.schema_abi,
1926 },
1927 );
1928 }
1929 for (index, edge) in direct_helper_edges.iter().enumerate() {
1930 debug_assert!(
1931 index == 0 || direct_helper_edges[index - 1].local_ordinal < edge.local_ordinal,
1932 "validated component helper edges are ordered by producer-local ordinal"
1933 );
1934 let call = u32::try_from(index).map_err(|_| {
1935 invalid(
1936 "component",
1937 linked.definition,
1938 "reachable helper edge count exceeds the canonical u32 ID space",
1939 )
1940 })?;
1941 descriptor_body.direct_helpers.insert(
1942 HelperCallEdgeId::new(call),
1943 witness_layout.helper(linked.definition, call)?,
1944 );
1945 }
1946 if matches!(view.root_span, SpanCardinality::Unknown { .. }) {
1947 descriptor_body.region_sites.insert(RegionSiteId::new(0));
1948 }
1949
1950 let mut header = DescriptorHeader::v1(
1951 DescriptorKind::Component,
1952 context.producer,
1953 RuntimeCompatibility::new(
1954 VersionRange::exact(context.runtime_protocol),
1955 CapabilitySet::NONE,
1956 ),
1957 );
1958 header.capabilities =
1959 CapabilitySet::ORIGIN_EFFECT_TAXONOMY.union(CapabilitySet::DOM_SPAN_CARDINALITY);
1960 if !descriptor_body.dependencies.is_empty() {
1961 header.capabilities = header.capabilities.union(CapabilitySet::TYPED_DEPENDENCIES);
1962 }
1963 if !descriptor_body.fields.is_empty() {
1964 header.capabilities = header
1965 .capabilities
1966 .union(CapabilitySet::COMPONENT_FIELD_SCHEMA);
1967 }
1968 if !descriptor_body.prop_uses.is_empty() {
1969 header.capabilities = header.capabilities.union(CapabilitySet::TEMPORAL_PROPS);
1970 header.runtime.required_capabilities = header
1971 .runtime
1972 .required_capabilities
1973 .union(CapabilitySet::TEMPORAL_PROPS);
1974 }
1975 if descriptor_body
1976 .fields
1977 .values()
1978 .any(|field| matches!(field.static_slot, StaticSlotCapability::Immutable { .. }))
1979 || descriptor_body.direct_components.values().any(|edge| {
1980 edge.bindings
1981 .values()
1982 .any(|binding| matches!(binding.source, ComponentBindingSource::StaticSlot { .. }))
1983 })
1984 {
1985 header.capabilities = header
1986 .capabilities
1987 .union(CapabilitySet::STATIC_SLOT_CONTRACTS);
1988 }
1989 if !descriptor_body.direct_components.is_empty() {
1990 header.capabilities = header
1991 .capabilities
1992 .union(CapabilitySet::DIRECT_COMPONENT_BINDINGS)
1993 .union(CapabilitySet::OWNER_PARTITION_INPUTS);
1994 header.runtime.required_capabilities = header
1995 .runtime
1996 .required_capabilities
1997 .union(CapabilitySet::OWNER_PARTITION_INPUTS);
1998 }
1999 if !descriptor_body.shared_state_providers.is_empty() {
2000 header.capabilities = header
2001 .capabilities
2002 .union(CapabilitySet::SHARED_STATE_PROVIDER_TOPOLOGY);
2003 }
2004 if descriptor_body
2005 .direct_components
2006 .values()
2007 .any(|edge| edge.lifecycle_control.is_some())
2008 {
2009 header.capabilities = header
2010 .capabilities
2011 .union(CapabilitySet::CONDITIONAL_COMPONENT_LIFECYCLE);
2012 }
2013 if !descriptor_body.direct_helpers.is_empty() {
2014 header.capabilities = header
2015 .capabilities
2016 .union(CapabilitySet::ORIGIN_FREE_HELPERS);
2017 }
2018 if !descriptor_body.region_sites.is_empty() {
2019 header.runtime.required_capabilities = header
2020 .runtime
2021 .required_capabilities
2022 .union(CapabilitySet::DOM_SPAN_CARDINALITY);
2023 }
2024
2025 let component_codegen = build_component_codegen_bridge(
2026 linked.definition,
2027 descriptor,
2028 &inbound_inputs,
2029 &legacy_graph,
2030 &payload_handlers,
2031 &value_layout,
2032 &view,
2033 &direct_component_edges,
2034 )?;
2035 validate_component_codegen_bridge(&component_codegen, &descriptor_body).map_err(|reason| {
2036 invalid(
2037 "component",
2038 linked.definition,
2039 format!("invalid component codegen bridge: {reason}"),
2040 )
2041 })?;
2042
2043 let envelope =
2044 DescriptorEnvelope::new(header, DescriptorBody::Component(descriptor_body), None).map_err(
2045 |source| AbiAdapterError::CanonicalValidation {
2046 kind: "component",
2047 definition: linked.definition,
2048 source,
2049 },
2050 )?;
2051 envelope
2052 .validate(&context.support)
2053 .map_err(|source| AbiAdapterError::CanonicalValidation {
2054 kind: "component",
2055 definition: linked.definition,
2056 source,
2057 })?;
2058
2059 let witnesses = build_component_witness_table(
2060 linked,
2061 &direct_component_edges,
2062 &field_witnesses,
2063 &direct_helper_edges,
2064 witness_layout,
2065 )?;
2066 let bridge = CanonicalDescriptorBridge::try_component(envelope, witnesses, component_codegen)
2067 .map_err(|reason| {
2068 invalid(
2069 "component",
2070 linked.definition,
2071 format!("invalid canonical bridge: {reason}"),
2072 )
2073 })?;
2074 Ok(AbiBridgeResult::Canonical(bridge))
2075}
2076
2077pub fn adapt_helper(
2079 context: &AbiAdapterContext,
2080 linked: &LinkedTransportHelper,
2081) -> Result<AbiBridgeResult, AbiAdapterError> {
2082 let root = payload_object("helper", linked.definition, &linked.payload)?;
2083 require_known_fields(
2084 "standalone helper payload",
2085 root,
2086 &[
2087 "body_hir",
2088 "body_hir_version",
2089 "body_ir",
2090 "body_ir_version",
2091 "codec_abi_version",
2092 "defining_record_id",
2093 "direct_calls",
2094 "effect_class",
2095 "format",
2096 "provisional_identity",
2097 "schema_version",
2098 "semantic_hash",
2099 "signature",
2100 ],
2101 linked.definition,
2102 )?;
2103 require_exact_str(
2104 root,
2105 "format",
2106 HELPER_PAYLOAD_FORMAT,
2107 "helper",
2108 linked.definition,
2109 )?;
2110 require_exact_u64(
2111 root,
2112 "schema_version",
2113 HELPER_PAYLOAD_SCHEMA,
2114 "helper",
2115 linked.definition,
2116 )?;
2117 require_exact_u64(
2118 root,
2119 "body_hir_version",
2120 HELPER_HIR_SCHEMA,
2121 "helper",
2122 linked.definition,
2123 )?;
2124 require_exact_u64(
2125 root,
2126 "body_ir_version",
2127 HELPER_IR_SCHEMA,
2128 "helper",
2129 linked.definition,
2130 )?;
2131 require_exact_u64(
2132 root,
2133 "codec_abi_version",
2134 HELPER_CODEC_ABI,
2135 "helper",
2136 linked.definition,
2137 )?;
2138 require_exact_str(
2139 root,
2140 "effect_class",
2141 "origin_free",
2142 "helper",
2143 linked.definition,
2144 )?;
2145 validate_linked_semantic_hash("helper", linked.definition, root, linked.semantic_hash)?;
2146 validate_definition_record("helper", linked.definition, root, "defining_record_id")?;
2147 let direct_helper_edges = validate_helper_edge_set(linked, root)?;
2148
2149 let signature = required_object(root, "signature", "helper", linked.definition)?;
2150 require_known_fields(
2151 "helper signature",
2152 signature,
2153 &["params", "return_type"],
2154 linked.definition,
2155 )?;
2156 let params = required_array(signature, "params", "helper", linked.definition)?;
2157 let mut codegen_params = Vec::with_capacity(params.len());
2158 let mut parameter_names = BTreeSet::new();
2159 for (index, param) in params.iter().enumerate() {
2160 let param = param.as_object().ok_or_else(|| {
2161 invalid(
2162 "helper",
2163 linked.definition,
2164 format!("signature.params[{index}] must be an object"),
2165 )
2166 })?;
2167 require_known_fields(
2168 "helper signature parameter",
2169 param,
2170 &["name", "rust_type"],
2171 linked.definition,
2172 )?;
2173 let name = required_str(param, "name", "helper", linked.definition)?;
2174 let rust_type = required_str(param, "rust_type", "helper", linked.definition)?;
2175 if name.is_empty() || rust_type.is_empty() {
2176 return Err(invalid(
2177 "helper",
2178 linked.definition,
2179 format!(
2180 "signature.params[{index}] must carry a non-empty parameter name and Rust type"
2181 ),
2182 ));
2183 }
2184 parse_client_helper_type(rust_type, ClientHelperTypePosition::Parameter).map_err(
2185 |error| {
2186 invalid(
2187 "helper",
2188 linked.definition,
2189 format!(
2190 "signature.params[{index}] has an invalid normalized Rust type: {error}"
2191 ),
2192 )
2193 },
2194 )?;
2195 if !parameter_names.insert(name) {
2196 return Err(invalid(
2197 "helper",
2198 linked.definition,
2199 format!("signature parameter name `{name}` appears more than once"),
2200 ));
2201 }
2202 codegen_params.push(HelperCodegenParam {
2203 name: name.to_owned(),
2204 rust_type: rust_type.to_owned(),
2205 });
2206 }
2207 let return_type = required_str(signature, "return_type", "helper", linked.definition)?;
2208 if return_type.is_empty() {
2209 return Err(invalid(
2210 "helper",
2211 linked.definition,
2212 "signature.return_type must not be empty",
2213 ));
2214 }
2215 if let Err(error) = parse_client_helper_type(return_type, ClientHelperTypePosition::Return) {
2216 return Err(invalid(
2217 "helper",
2218 linked.definition,
2219 format!("signature.return_type has an invalid normalized Rust type: {error}"),
2220 ));
2221 }
2222 let codegen_signature = HelperCodegenSignature {
2223 params: codegen_params,
2224 return_type: return_type.to_owned(),
2225 };
2226 let body_ir = root.get("body_ir").ok_or_else(|| {
2227 invalid(
2228 "helper",
2229 linked.definition,
2230 "standalone helper payload is missing `body_ir`",
2231 )
2232 })?;
2233 let (normalized_body_ir, resolved_body_ir) =
2234 validate_standalone_helper_client_ir(linked.definition, body_ir, &direct_helper_edges)?;
2235 let expected_helper_edges = direct_helper_edges
2241 .iter()
2242 .map(|edge| HelperCallEdgeId::new(edge.ordinal))
2243 .collect::<Vec<_>>();
2244 validate_helper_codegen_body(
2245 linked.definition,
2246 &resolved_body_ir,
2247 codegen_signature.params.len(),
2248 &expected_helper_edges,
2249 )
2250 .map_err(|reason| {
2251 invalid(
2252 "helper",
2253 linked.definition,
2254 format!("invalid helper codegen body: {reason}"),
2255 )
2256 })?;
2257 let Some(identity) = context.helper_identities.get(&linked.definition) else {
2258 return Ok(AbiBridgeResult::Unsupported(UnsupportedDescriptor {
2259 kind: DescriptorKind::Helper,
2260 definition: linked.definition,
2261 gaps: vec![CompatibilityGap::MissingResolvedSemanticIdentity],
2262 }));
2263 };
2264 let semantic_key =
2265 identity
2266 .helper_key()
2267 .map_err(|source| AbiAdapterError::InvalidSemanticIdentity {
2268 kind: "helper",
2269 definition: linked.definition,
2270 source,
2271 })?;
2272 let signature_hash = canonical_legacy_json_hash(
2273 HELPER_SIGNATURE_JSON_HASH_DOMAIN,
2274 &Value::Object(signature.clone()),
2275 );
2276 let client_ir_hash =
2277 canonical_legacy_json_hash(HELPER_CLIENT_IR_JSON_HASH_DOMAIN, &normalized_body_ir);
2278 let mut descriptor_body = HelperDescriptor::v1(
2279 semantic_key,
2280 WitnessRecordId::new(0),
2281 signature_hash,
2282 client_ir_hash,
2283 );
2284
2285 let mut witnesses = BTreeMap::new();
2286 witnesses.insert(
2287 WitnessRecordId::new(0),
2288 ResolvedTransportWitness::Definition(linked.definition),
2289 );
2290 for edge in &direct_helper_edges {
2291 let call = HelperCallEdgeId::new(edge.ordinal);
2292 let witness_id = edge.ordinal.checked_add(1).ok_or_else(|| {
2293 invalid(
2294 "helper",
2295 linked.definition,
2296 "direct helper call count exceeds the canonical witness ID space",
2297 )
2298 })?;
2299 let witness = WitnessRecordId::new(witness_id);
2300 descriptor_body.direct_helpers.insert(call, witness);
2301 witnesses.insert(
2302 witness,
2303 ResolvedTransportWitness::HelperEdge {
2304 source_edge: edge.source_edge,
2305 target: edge.target,
2306 },
2307 );
2308 }
2309
2310 let mut header = DescriptorHeader::v1(
2311 DescriptorKind::Helper,
2312 context.producer,
2313 RuntimeCompatibility::new(
2314 VersionRange::exact(context.runtime_protocol),
2315 CapabilitySet::NONE,
2316 ),
2317 );
2318 header.capabilities =
2319 CapabilitySet::ORIGIN_EFFECT_TAXONOMY.union(CapabilitySet::ORIGIN_FREE_HELPERS);
2320 let envelope = DescriptorEnvelope::new(header, DescriptorBody::Helper(descriptor_body), None)
2321 .map_err(|source| AbiAdapterError::CanonicalValidation {
2322 kind: "helper",
2323 definition: linked.definition,
2324 source,
2325 })?;
2326 envelope
2327 .validate(&context.support)
2328 .map_err(|source| AbiAdapterError::CanonicalValidation {
2329 kind: "helper",
2330 definition: linked.definition,
2331 source,
2332 })?;
2333
2334 let DescriptorBody::Helper(helper_descriptor) = &envelope.body else {
2335 unreachable!("standalone helper adapter constructed a helper descriptor")
2336 };
2337 let helper_codegen = HelperCodegenBridge::try_new(
2338 linked.definition,
2339 codegen_signature,
2340 client_ir_hash,
2341 resolved_body_ir,
2342 helper_descriptor,
2343 )
2344 .map_err(|reason| {
2345 invalid(
2346 "helper",
2347 linked.definition,
2348 format!("invalid helper codegen bridge: {reason}"),
2349 )
2350 })?;
2351
2352 let bridge = CanonicalDescriptorBridge::try_helper(
2353 linked.definition,
2354 envelope,
2355 witnesses,
2356 helper_codegen,
2357 )
2358 .map_err(|reason| {
2359 invalid(
2360 "helper",
2361 linked.definition,
2362 format!("invalid canonical bridge: {reason}"),
2363 )
2364 })?;
2365 Ok(AbiBridgeResult::Canonical(bridge))
2366}
2367
2368#[derive(Debug)]
2369struct AdaptedComponentFields {
2370 canonical: BTreeMap<ComponentFieldId, ComponentFieldSchema>,
2371}
2372
2373#[derive(Clone, Copy, Debug, PartialEq, Eq)]
2374enum InboundFieldKind {
2375 Value,
2376 Callback,
2377 NodeRef,
2378 ServerOnly,
2379}
2380
2381#[derive(Clone, Copy, Debug, PartialEq, Eq)]
2382enum InboundCallbackShape {
2383 Required,
2384 Optional,
2385}
2386
2387#[derive(Clone, Debug)]
2388struct ValidatedInboundField {
2389 name: String,
2390 kind: InboundFieldKind,
2391 value: u64,
2392 crossing: u64,
2393 callback_slot: Option<u32>,
2394 callback_shape: Option<InboundCallbackShape>,
2395 record_role: TransportComponentFieldRole,
2398}
2399
2400#[derive(Clone, Debug)]
2401struct ValidatedInboundPropUse {
2402 site: u32,
2403 field: u32,
2404 value: u32,
2405 temporal: TemporalPropMode,
2406 target_signal: Option<u32>,
2407}
2408
2409#[derive(Clone, Debug)]
2410struct ValidatedInboundNodeRef {
2411 field: u32,
2412 value: u32,
2413 node_ref: u32,
2414 bind_target: Option<ComponentNodeRefBindTarget>,
2415}
2416
2417#[derive(Clone, Debug)]
2418struct ValidatedInboundInputs {
2419 fields: Vec<ValidatedInboundField>,
2420 prop_uses: Vec<ValidatedInboundPropUse>,
2421 node_refs: Vec<ValidatedInboundNodeRef>,
2422 projection_signals: BTreeSet<u32>,
2426}
2427
2428fn inbound_source_signals(inbound: &ValidatedInboundInputs) -> BTreeSet<u32> {
2434 inbound
2435 .prop_uses
2436 .iter()
2437 .filter_map(|prop_use| {
2438 matches!(
2439 prop_use.temporal,
2440 TemporalPropMode::LiveRead | TemporalPropMode::QueryKeyDependency
2441 )
2442 .then_some(prop_use.target_signal)
2443 .flatten()
2444 })
2445 .chain(inbound.projection_signals.iter().copied())
2446 .collect()
2447}
2448
2449fn authenticated_unknown_inbound_signals(inbound: &ValidatedInboundInputs) -> BTreeSet<u32> {
2461 inbound
2462 .prop_uses
2463 .iter()
2464 .filter_map(|prop_use| {
2465 matches!(
2466 prop_use.temporal,
2467 TemporalPropMode::LiveRead
2468 | TemporalPropMode::QueryKeyDependency
2469 | TemporalPropMode::SeedOnce(_)
2470 )
2471 .then_some(prop_use.target_signal)
2472 .flatten()
2473 })
2474 .chain(inbound.projection_signals.iter().copied())
2475 .collect()
2476}
2477
2478#[derive(Clone, Copy, Debug, PartialEq, Eq)]
2479enum ResolvedProjectionRole {
2480 ServerOnly,
2481 Value,
2482 Callback(InboundCallbackShape),
2483 NodeRef,
2484}
2485
2486impl ResolvedProjectionRole {
2487 fn label(self) -> &'static str {
2488 match self {
2489 Self::ServerOnly => "server-only",
2490 Self::Value => "live value",
2491 Self::Callback(InboundCallbackShape::Required) => "required callback",
2492 Self::Callback(InboundCallbackShape::Optional) => "optional callback",
2493 Self::NodeRef => "NodeRef handle",
2494 }
2495 }
2496}
2497
2498#[derive(Clone, Debug, Default)]
2499struct ResolvedProjectionRoles {
2500 fields: BTreeMap<(TransportDefinitionId, u32), ResolvedProjectionRole>,
2501 fields_by_name: BTreeMap<(TransportDefinitionId, String), ResolvedProjectionRole>,
2502}
2503
2504impl ResolvedProjectionRoles {
2505 fn field(
2506 &self,
2507 definition: TransportDefinitionId,
2508 field: u32,
2509 ) -> Option<ResolvedProjectionRole> {
2510 self.fields.get(&(definition, field)).copied()
2511 }
2512
2513 fn field_by_name(
2514 &self,
2515 definition: TransportDefinitionId,
2516 field: &str,
2517 ) -> Option<ResolvedProjectionRole> {
2518 self.fields_by_name
2519 .get(&(definition, field.to_owned()))
2520 .copied()
2521 }
2522}
2523
2524#[derive(Clone, Debug)]
2525struct ProjectionConstraint {
2526 parent: (TransportDefinitionId, u32),
2527 child: Option<(TransportDefinitionId, u32)>,
2528 child_server_only: bool,
2529 parent_name: String,
2530 child_name: String,
2531}
2532
2533fn resolve_deferred_projection_roles(
2540 plan: &TransportLinkPlan,
2541) -> Result<ResolvedProjectionRoles, AbiAdapterError> {
2542 let components = plan
2543 .components
2544 .iter()
2545 .map(|component| (component.definition, component))
2546 .collect::<BTreeMap<_, _>>();
2547 let mut roles = BTreeMap::<(TransportDefinitionId, u32), Option<ResolvedProjectionRole>>::new();
2548 let mut names = BTreeMap::<(TransportDefinitionId, u32), String>::new();
2549 let mut fields_by_name =
2550 BTreeMap::<(TransportDefinitionId, String), (u32, Option<ResolvedProjectionRole>)>::new();
2551
2552 for component in &plan.components {
2553 let root = payload_object("component", component.definition, &component.payload)?;
2554 let descriptor = required_object(
2555 root,
2556 "component_descriptor",
2557 "component",
2558 component.definition,
2559 )?;
2560 for (index, field) in
2561 required_array(descriptor, "fields", "component", component.definition)?
2562 .iter()
2563 .enumerate()
2564 {
2565 let field = field.as_object().ok_or_else(|| {
2566 invalid(
2567 "component",
2568 component.definition,
2569 format!("fields[{index}] must be an object"),
2570 )
2571 })?;
2572 let field_id = checked_u32(
2573 required_u64(field, "id", "component", component.definition)?,
2574 "component field ID",
2575 component.definition,
2576 )?;
2577 let name = required_str(field, "name", "component", component.definition)?.to_owned();
2578 let role = match required_str(field, "kind", "component", component.definition)? {
2579 "deferred_projection" => None,
2580 "prop" => Some(ResolvedProjectionRole::Value),
2581 "handler" => {
2582 let shape = match required_str(
2583 field,
2584 "callback_shape",
2585 "component",
2586 component.definition,
2587 )? {
2588 "required" => InboundCallbackShape::Required,
2589 "optional" => InboundCallbackShape::Optional,
2590 other => {
2591 return Err(invalid(
2592 "component",
2593 component.definition,
2594 format!(
2595 "callback field `{name}` has unsupported callback shape `{other}`"
2596 ),
2597 ));
2598 }
2599 };
2600 Some(ResolvedProjectionRole::Callback(shape))
2601 }
2602 "node_ref" => Some(ResolvedProjectionRole::NodeRef),
2603 "server_prop" | "static_slot" => Some(ResolvedProjectionRole::ServerOnly),
2604 other => {
2605 return Err(invalid(
2606 "component",
2607 component.definition,
2608 format!(
2609 "unsupported component field kind `{other}` while resolving deferred projections"
2610 ),
2611 ));
2612 }
2613 };
2614 let key = (component.definition, field_id);
2615 if roles.insert(key, role).is_some()
2616 || names.insert(key, name.clone()).is_some()
2617 || fields_by_name
2618 .insert((component.definition, name.clone()), (field_id, role))
2619 .is_some()
2620 {
2621 return Err(invalid(
2622 "component",
2623 component.definition,
2624 format!("component field `{name}` is not uniquely identified"),
2625 ));
2626 }
2627 }
2628 }
2629
2630 let mut constraints = Vec::new();
2631 for component in &plan.components {
2632 let root = payload_object("component", component.definition, &component.payload)?;
2633 let transport = required_object(root, "transport", "component", component.definition)?;
2634 for (edge_index, edge) in required_array(
2635 transport,
2636 "direct_component_edges",
2637 "component",
2638 component.definition,
2639 )?
2640 .iter()
2641 .enumerate()
2642 {
2643 let edge = edge.as_object().ok_or_else(|| {
2644 invalid(
2645 "component",
2646 component.definition,
2647 format!("direct_component_edges[{edge_index}] must be an object"),
2648 )
2649 })?;
2650 let source_edge =
2651 parse_record_field(edge, "source_edge_id", "component", component.definition)?;
2652 let target = component
2653 .component_edges
2654 .iter()
2655 .find(|candidate| candidate.source_edge == source_edge)
2656 .map(|candidate| candidate.target)
2657 .ok_or_else(|| {
2658 invalid(
2659 "component",
2660 component.definition,
2661 format!(
2662 "deferred projection edge {} has no rustc-resolved child",
2663 hex_record(&source_edge)
2664 ),
2665 )
2666 })?;
2667 if !components.contains_key(&target) {
2668 return Err(invalid(
2669 "component",
2670 component.definition,
2671 "deferred projection edge resolves to an unknown component definition",
2672 ));
2673 }
2674 for (field_index, field) in
2675 required_array(edge, "fields", "component", component.definition)?
2676 .iter()
2677 .enumerate()
2678 {
2679 let field = field.as_object().ok_or_else(|| {
2680 invalid(
2681 "component",
2682 component.definition,
2683 format!(
2684 "direct_component_edges[{edge_index}].fields[{field_index}] must be an object"
2685 ),
2686 )
2687 })?;
2688 let binding = required_object(field, "binding", "component", component.definition)?;
2689 if required_str(binding, "kind", "component", component.definition)?
2690 != "deferred_projection"
2691 {
2692 continue;
2693 }
2694 let parent_field = checked_u32(
2695 required_u64(
2696 binding,
2697 "parent_field_id",
2698 "component",
2699 component.definition,
2700 )?,
2701 "deferred parent field ID",
2702 component.definition,
2703 )?;
2704 let parent = (component.definition, parent_field);
2705 let parent_name = names.get(&parent).cloned().ok_or_else(|| {
2706 invalid(
2707 "component",
2708 component.definition,
2709 format!(
2710 "deferred projection references unknown parent field {parent_field}"
2711 ),
2712 )
2713 })?;
2714 let child_name =
2715 required_str(field, "name", "component", component.definition)?.to_owned();
2716 let child_schema = fields_by_name.get(&(target, child_name.clone()));
2717 let child_server_only = matches!(
2718 child_schema,
2719 None | Some((_, Some(ResolvedProjectionRole::ServerOnly)))
2720 );
2721 let child = (!child_server_only)
2722 .then(|| child_schema.map(|(field, _)| (target, *field)))
2723 .flatten();
2724 constraints.push(ProjectionConstraint {
2725 parent,
2726 child,
2727 child_server_only,
2728 parent_name,
2729 child_name,
2730 });
2731 }
2732 }
2733 }
2734
2735 let merge = |left: ResolvedProjectionRole,
2736 right: ResolvedProjectionRole,
2737 constraint: &ProjectionConstraint|
2738 -> Result<ResolvedProjectionRole, AbiAdapterError> {
2739 if left == right {
2740 Ok(left)
2741 } else {
2742 Err(invalid(
2743 "component",
2744 constraint.parent.0,
2745 format!(
2746 "deferred projection `self.{}` feeds child field `{}` with conflicting roles: {} versus {}\nhelp: use separate component fields for values, callbacks, and NodeRef handles",
2747 constraint.parent_name,
2748 constraint.child_name,
2749 left.label(),
2750 right.label(),
2751 ),
2752 ))
2753 }
2754 };
2755
2756 let mut changed = true;
2757 while changed {
2758 changed = false;
2759 for constraint in &constraints {
2760 if constraint.child_server_only {
2764 continue;
2765 }
2766 let parent_role = roles.get(&constraint.parent).copied().flatten();
2767 let child_role = constraint
2768 .child
2769 .and_then(|child| roles.get(&child).copied().flatten());
2770 match (parent_role, child_role) {
2771 (Some(parent), Some(child)) => {
2772 merge(parent, child, constraint)?;
2773 }
2774 (None, Some(child)) => {
2775 roles.insert(constraint.parent, Some(child));
2776 changed = true;
2777 }
2778 (Some(parent), None) => {
2779 let child = constraint
2780 .child
2781 .expect("a non-server unresolved constraint has a child field");
2782 roles.insert(child, Some(parent));
2783 changed = true;
2784 }
2785 (None, None) => {}
2786 }
2787 }
2788 }
2789
2790 let fields_by_name = fields_by_name
2794 .into_iter()
2795 .map(|((definition, name), (field, _))| {
2796 let role = roles
2797 .get(&(definition, field))
2798 .copied()
2799 .flatten()
2800 .unwrap_or(ResolvedProjectionRole::ServerOnly);
2801 ((definition, name), role)
2802 })
2803 .collect();
2804 let fields = roles
2805 .into_iter()
2806 .map(|(key, role)| (key, role.unwrap_or(ResolvedProjectionRole::ServerOnly)))
2807 .collect();
2808 Ok(ResolvedProjectionRoles {
2809 fields,
2810 fields_by_name,
2811 })
2812}
2813
2814#[cfg(test)]
2815fn inbound_temporal_mode_requires_client_program(mode: TemporalPropMode) -> bool {
2816 match mode {
2817 TemporalPropMode::LiveRead
2818 | TemporalPropMode::SeedOnce(_)
2819 | TemporalPropMode::EffectDependency
2820 | TemporalPropMode::QueryKeyDependency => true,
2821 TemporalPropMode::ForbiddenProviderSeed | TemporalPropMode::ForbiddenBoundaryCrossing => {
2822 false
2823 }
2824 _ => true,
2827 }
2828}
2829
2830#[derive(Clone, Debug)]
2831struct ValidatedComponentFieldWitness {
2832 field_record: TransportRecordId,
2833 witness: WitnessRecordId,
2834}
2835
2836#[derive(Clone, Debug, PartialEq, Eq)]
2837struct ValidatedPayloadHandlerValue {
2838 prelude_local_index: u32,
2839 payload_arity: u8,
2840 body_ir: Value,
2841 body_hash: SemanticHash,
2842 dependencies: ClientBlockExternalDependencies,
2843 browser_operations: Vec<LegacyBrowserOperation>,
2848}
2849
2850#[derive(Clone, Debug, PartialEq, Eq)]
2862struct ComponentValueLayout {
2863 inbound_count: u32,
2864 signal_start: u64,
2865 signal_count: u32,
2866 signal_ordinals: Option<BTreeMap<u32, u32>>,
2867 expr_start: u64,
2868 expr_count: u32,
2869 expr_ordinals: Option<BTreeMap<u32, u32>>,
2870 payload_handler_start: u64,
2871 payload_handler_count: u32,
2872 node_ref_handle_start: u64,
2873 node_ref_handle_count: u32,
2874 node_ref_values: BTreeMap<u32, LocalValueId>,
2875}
2876
2877impl ComponentValueLayout {
2878 #[cfg(test)]
2879 fn new(
2880 definition: TransportDefinitionId,
2881 inbound_fields: &[ValidatedInboundField],
2882 descriptor: &Map<String, Value>,
2883 payload_handler_count: usize,
2884 ) -> Result<Self, AbiAdapterError> {
2885 Self::new_with_handles(
2886 definition,
2887 &ValidatedInboundInputs {
2888 fields: inbound_fields.to_vec(),
2889 prop_uses: Vec::new(),
2890 node_refs: Vec::new(),
2891 projection_signals: BTreeSet::new(),
2892 },
2893 descriptor,
2894 payload_handler_count,
2895 &[],
2896 )
2897 }
2898
2899 fn new_with_handles(
2900 definition: TransportDefinitionId,
2901 inbound: &ValidatedInboundInputs,
2902 descriptor: &Map<String, Value>,
2903 payload_handler_count: usize,
2904 direct_component_edges: &[ValidatedDirectComponentEdge],
2905 ) -> Result<Self, AbiAdapterError> {
2906 for (index, field) in inbound.fields.iter().enumerate() {
2907 if field.value != index as u64 {
2908 return Err(invalid(
2909 "component",
2910 definition,
2911 format!(
2912 "inbound field `{}` has value ID {}, expected dense ID {index}",
2913 field.name, field.value
2914 ),
2915 ));
2916 }
2917 }
2918
2919 let signals = required_array(descriptor, "signals", "component", definition)?;
2920 let mut signal_ordinals = BTreeMap::new();
2921 let mut previous_signal = None;
2922 for (index, signal) in signals.iter().enumerate() {
2923 let signal = signal.as_object().ok_or_else(|| {
2924 invalid(
2925 "component",
2926 definition,
2927 format!("signals[{index}] must be an object"),
2928 )
2929 })?;
2930 let actual = checked_u32(
2931 required_u64(signal, "id", "component", definition)?,
2932 "legacy signal ID",
2933 definition,
2934 )?;
2935 if previous_signal.is_some_and(|previous| actual <= previous) {
2936 return Err(invalid(
2937 "component",
2938 definition,
2939 format!(
2940 "legacy signal IDs must be strictly increasing after optimization; \
2941 signals[{index}] has ID {actual} after {}",
2942 previous_signal.expect("checked above")
2943 ),
2944 ));
2945 }
2946 let ordinal = u32::try_from(index).map_err(|_| {
2947 invalid(
2948 "component",
2949 definition,
2950 "legacy signal count exceeds the canonical u32 value space",
2951 )
2952 })?;
2953 signal_ordinals.insert(actual, ordinal);
2954 previous_signal = Some(actual);
2955 }
2956
2957 let exprs = required_array(descriptor, "exprs", "component", definition)?;
2958 let mut expr_ordinals = BTreeMap::new();
2959 let mut previous_expr = None;
2960 for (index, expr) in exprs.iter().enumerate() {
2961 let expr = expr.as_object().ok_or_else(|| {
2962 invalid(
2963 "component",
2964 definition,
2965 format!("exprs[{index}] must be an object"),
2966 )
2967 })?;
2968 let actual = checked_u32(
2969 required_u64(expr, "id", "component", definition)?,
2970 "legacy expression ID",
2971 definition,
2972 )?;
2973 if previous_expr.is_some_and(|previous| actual <= previous) {
2974 return Err(invalid(
2975 "component",
2976 definition,
2977 format!(
2978 "legacy expression IDs must be strictly increasing after optimization; \
2979 exprs[{index}] has ID {actual} after {}",
2980 previous_expr.expect("checked above")
2981 ),
2982 ));
2983 }
2984 let ordinal = u32::try_from(index).map_err(|_| {
2985 invalid(
2986 "component",
2987 definition,
2988 "legacy expression count exceeds the canonical u32 value space",
2989 )
2990 })?;
2991 expr_ordinals.insert(actual, ordinal);
2992 previous_expr = Some(actual);
2993 }
2994
2995 let declared_node_refs = required_array(descriptor, "node_refs", "component", definition)?
2996 .iter()
2997 .enumerate()
2998 .map(|(index, node_ref)| {
2999 let node_ref = node_ref.as_object().ok_or_else(|| {
3000 invalid(
3001 "component",
3002 definition,
3003 format!("node_refs[{index}] must be an object"),
3004 )
3005 })?;
3006 checked_u32(
3007 required_u64(node_ref, "id", "component", definition)?,
3008 "legacy node-ref ID",
3009 definition,
3010 )
3011 })
3012 .collect::<Result<BTreeSet<_>, AbiAdapterError>>()?;
3013 let mut inbound_node_ref_values = BTreeMap::new();
3014 for node_ref in &inbound.node_refs {
3015 if inbound_node_ref_values
3016 .insert(node_ref.node_ref, LocalValueId::new(node_ref.value))
3017 .is_some()
3018 {
3019 return Err(invalid(
3020 "component",
3021 definition,
3022 format!(
3023 "producer NodeRef {} is represented by more than one inbound field",
3024 node_ref.node_ref
3025 ),
3026 ));
3027 }
3028 }
3029 let handle_sources = direct_component_edges
3030 .iter()
3031 .flat_map(|edge| edge.fields.iter())
3032 .filter_map(|field| match field.binding {
3033 ValidatedDirectComponentBinding::NodeRefHandle { node_ref } => Some(node_ref),
3034 _ => None,
3035 })
3036 .collect::<BTreeSet<_>>();
3037 if let Some(unknown) = handle_sources
3038 .iter()
3039 .find(|node_ref| !declared_node_refs.contains(node_ref))
3040 {
3041 return Err(invalid(
3042 "component",
3043 definition,
3044 format!("NodeRef handle refers to unknown producer NodeRef {unknown}"),
3045 ));
3046 }
3047 let allocated_node_refs = handle_sources
3048 .iter()
3049 .copied()
3050 .filter(|node_ref| !inbound_node_ref_values.contains_key(node_ref))
3051 .collect::<Vec<_>>();
3052
3053 let mut layout = Self::from_allocation(
3054 definition,
3055 u64::try_from(inbound.fields.len()).map_err(|_| {
3056 invalid(
3057 "component",
3058 definition,
3059 "inbound value count exceeds the canonical u64 count space",
3060 )
3061 })?,
3062 u64::try_from(signals.len()).map_err(|_| {
3063 invalid(
3064 "component",
3065 definition,
3066 "legacy signal count exceeds the canonical u64 count space",
3067 )
3068 })?,
3069 u64::try_from(exprs.len()).map_err(|_| {
3070 invalid(
3071 "component",
3072 definition,
3073 "legacy expression count exceeds the canonical u64 count space",
3074 )
3075 })?,
3076 u64::try_from(payload_handler_count).map_err(|_| {
3077 invalid(
3078 "component",
3079 definition,
3080 "payload-handler count exceeds the canonical u64 count space",
3081 )
3082 })?,
3083 u64::try_from(allocated_node_refs.len()).map_err(|_| {
3084 invalid(
3085 "component",
3086 definition,
3087 "NodeRef handle count exceeds the canonical u64 count space",
3088 )
3089 })?,
3090 Some(signal_ordinals),
3091 Some(expr_ordinals),
3092 )?;
3093 layout.node_ref_values = inbound_node_ref_values;
3094 for (ordinal, node_ref) in allocated_node_refs.into_iter().enumerate() {
3095 let ordinal = u64::try_from(ordinal).expect("usize fits u64");
3096 let value = layout
3097 .node_ref_handle_start
3098 .checked_add(ordinal)
3099 .and_then(|value| u32::try_from(value).ok())
3100 .ok_or_else(|| {
3101 invalid(
3102 "component",
3103 definition,
3104 "NodeRef handle value ID exceeds the canonical u32 value space",
3105 )
3106 })?;
3107 layout
3108 .node_ref_values
3109 .insert(node_ref, LocalValueId::new(value));
3110 }
3111 Ok(layout)
3112 }
3113
3114 #[cfg(test)]
3115 fn from_counts(
3116 definition: TransportDefinitionId,
3117 inbound_count: u64,
3118 signal_count: u64,
3119 payload_handler_count: u64,
3120 ) -> Result<Self, AbiAdapterError> {
3121 Self::from_allocation(
3122 definition,
3123 inbound_count,
3124 signal_count,
3125 0,
3126 payload_handler_count,
3127 0,
3128 None,
3129 None,
3130 )
3131 }
3132
3133 fn from_allocation(
3134 definition: TransportDefinitionId,
3135 inbound_count: u64,
3136 signal_count: u64,
3137 expr_count: u64,
3138 payload_handler_count: u64,
3139 node_ref_handle_count: u64,
3140 signal_ordinals: Option<BTreeMap<u32, u32>>,
3141 expr_ordinals: Option<BTreeMap<u32, u32>>,
3142 ) -> Result<Self, AbiAdapterError> {
3143 let inbound_count = u32::try_from(inbound_count).map_err(|_| {
3144 invalid(
3145 "component",
3146 definition,
3147 "inbound value count exceeds the canonical u32 value space",
3148 )
3149 })?;
3150 let signal_count = u32::try_from(signal_count).map_err(|_| {
3151 invalid(
3152 "component",
3153 definition,
3154 "legacy signal count exceeds the canonical u32 value space",
3155 )
3156 })?;
3157 let expr_count = u32::try_from(expr_count).map_err(|_| {
3158 invalid(
3159 "component",
3160 definition,
3161 "legacy expression count exceeds the canonical u32 value space",
3162 )
3163 })?;
3164 let payload_handler_count = u32::try_from(payload_handler_count).map_err(|_| {
3165 invalid(
3166 "component",
3167 definition,
3168 "payload-handler count exceeds the canonical u32 value space",
3169 )
3170 })?;
3171 let node_ref_handle_count = u32::try_from(node_ref_handle_count).map_err(|_| {
3172 invalid(
3173 "component",
3174 definition,
3175 "NodeRef handle count exceeds the canonical u32 value space",
3176 )
3177 })?;
3178 let signal_start = u64::from(inbound_count);
3179 let expr_start = signal_start
3180 .checked_add(u64::from(signal_count))
3181 .ok_or_else(|| {
3182 invalid(
3183 "component",
3184 definition,
3185 "legacy signals exhaust the canonical u64 value allocation space",
3186 )
3187 })?;
3188 let payload_handler_start =
3189 expr_start
3190 .checked_add(u64::from(expr_count))
3191 .ok_or_else(|| {
3192 invalid(
3193 "component",
3194 definition,
3195 "legacy expressions exhaust the canonical u64 value allocation space",
3196 )
3197 })?;
3198 let node_ref_handle_start = payload_handler_start
3199 .checked_add(u64::from(payload_handler_count))
3200 .ok_or_else(|| {
3201 invalid(
3202 "component",
3203 definition,
3204 "payload handlers exhaust the canonical u64 value allocation space",
3205 )
3206 })?;
3207 let allocation_end = node_ref_handle_start
3208 .checked_add(u64::from(node_ref_handle_count))
3209 .ok_or_else(|| {
3210 invalid(
3211 "component",
3212 definition,
3213 "NodeRef handles exhaust the canonical u64 value allocation space",
3214 )
3215 })?;
3216 if allocation_end > u64::from(u32::MAX) + 1 {
3217 return Err(invalid(
3218 "component",
3219 definition,
3220 "inbound values and legacy signals exhaust the canonical u32 value space",
3221 ));
3222 }
3223
3224 Ok(Self {
3225 inbound_count,
3226 signal_start,
3227 signal_count,
3228 signal_ordinals,
3229 expr_start,
3230 expr_count,
3231 expr_ordinals,
3232 payload_handler_start,
3233 payload_handler_count,
3234 node_ref_handle_start,
3235 node_ref_handle_count,
3236 node_ref_values: BTreeMap::new(),
3237 })
3238 }
3239
3240 fn inbound(
3241 &self,
3242 definition: TransportDefinitionId,
3243 value: u64,
3244 ) -> Result<LocalValueId, AbiAdapterError> {
3245 let value = u32::try_from(value).map_err(|_| {
3246 invalid(
3247 "component",
3248 definition,
3249 format!("inbound value ID {value} exceeds the canonical u32 value space"),
3250 )
3251 })?;
3252 if value >= self.inbound_count {
3253 return Err(invalid(
3254 "component",
3255 definition,
3256 format!(
3257 "inbound value ID {value} is outside its allocated range of {}",
3258 self.inbound_count
3259 ),
3260 ));
3261 }
3262 Ok(LocalValueId::new(value))
3263 }
3264
3265 fn signal(
3266 &self,
3267 definition: TransportDefinitionId,
3268 signal: u32,
3269 ) -> Result<LocalValueId, AbiAdapterError> {
3270 let ordinal = match &self.signal_ordinals {
3271 Some(ordinals) => ordinals.get(&signal).copied().ok_or_else(|| {
3272 invalid(
3273 "component",
3274 definition,
3275 format!(
3276 "legacy signal source {signal} is not present in the optimized descriptor"
3277 ),
3278 )
3279 })?,
3280 None if signal < self.signal_count => signal,
3281 None => {
3282 return Err(invalid(
3283 "component",
3284 definition,
3285 format!(
3286 "legacy signal source {signal} is outside its allocated range of {}",
3287 self.signal_count
3288 ),
3289 ));
3290 }
3291 };
3292 let value = self
3293 .signal_start
3294 .checked_add(u64::from(ordinal))
3295 .and_then(|value| u32::try_from(value).ok())
3296 .ok_or_else(|| {
3297 invalid(
3298 "component",
3299 definition,
3300 "legacy signal value ID exceeds the canonical u32 value space",
3301 )
3302 })?;
3303 Ok(LocalValueId::new(value))
3304 }
3305
3306 fn payload_handler(
3307 &self,
3308 definition: TransportDefinitionId,
3309 ordinal: u32,
3310 ) -> Result<LocalValueId, AbiAdapterError> {
3311 if ordinal >= self.payload_handler_count {
3312 return Err(invalid(
3313 "component",
3314 definition,
3315 format!(
3316 "payload-handler ordinal {ordinal} is outside its allocated range of {}",
3317 self.payload_handler_count
3318 ),
3319 ));
3320 }
3321 let value = self
3322 .payload_handler_start
3323 .checked_add(u64::from(ordinal))
3324 .and_then(|value| u32::try_from(value).ok())
3325 .ok_or_else(|| {
3326 invalid(
3327 "component",
3328 definition,
3329 "payload-handler value ID exceeds the canonical u32 value space",
3330 )
3331 })?;
3332 Ok(LocalValueId::new(value))
3333 }
3334
3335 fn expr(
3336 &self,
3337 definition: TransportDefinitionId,
3338 expr: u32,
3339 ) -> Result<LocalValueId, AbiAdapterError> {
3340 let ordinal = match &self.expr_ordinals {
3341 Some(ordinals) => ordinals.get(&expr).copied().ok_or_else(|| {
3342 invalid(
3343 "component",
3344 definition,
3345 format!(
3346 "legacy expression source {expr} is not present in the optimized descriptor"
3347 ),
3348 )
3349 })?,
3350 None if expr < self.expr_count => expr,
3351 None => {
3352 return Err(invalid(
3353 "component",
3354 definition,
3355 format!(
3356 "legacy expression source {expr} is outside its allocated range of {}",
3357 self.expr_count
3358 ),
3359 ));
3360 }
3361 };
3362 let value = self
3363 .expr_start
3364 .checked_add(u64::from(ordinal))
3365 .and_then(|value| u32::try_from(value).ok())
3366 .ok_or_else(|| {
3367 invalid(
3368 "component",
3369 definition,
3370 "legacy expression value ID exceeds the canonical u32 value space",
3371 )
3372 })?;
3373 Ok(LocalValueId::new(value))
3374 }
3375
3376 fn node_ref(
3377 &self,
3378 definition: TransportDefinitionId,
3379 node_ref: u32,
3380 ) -> Result<LocalValueId, AbiAdapterError> {
3381 self.node_ref_values.get(&node_ref).copied().ok_or_else(|| {
3382 invalid(
3383 "component",
3384 definition,
3385 format!(
3386 "producer NodeRef {node_ref} has no canonical handle value; only an inbound or direct-aliased NodeRef may cross a component edge"
3387 ),
3388 )
3389 })
3390 }
3391
3392 fn populate(&self, values: &mut BTreeSet<LocalValueId>) {
3393 values.extend((0..self.inbound_count).map(LocalValueId::new));
3394 values.extend((0..self.signal_count).map(|signal| {
3395 LocalValueId::new(
3396 u32::try_from(self.signal_start + u64::from(signal))
3397 .expect("validated component value allocation fits u32"),
3398 )
3399 }));
3400 values.extend((0..self.expr_count).map(|expr| {
3401 LocalValueId::new(
3402 u32::try_from(self.expr_start + u64::from(expr))
3403 .expect("validated component value allocation fits u32"),
3404 )
3405 }));
3406 values.extend((0..self.payload_handler_count).map(|handler| {
3407 LocalValueId::new(
3408 u32::try_from(self.payload_handler_start + u64::from(handler))
3409 .expect("validated component value allocation fits u32"),
3410 )
3411 }));
3412 values.extend((0..self.node_ref_handle_count).map(|node_ref| {
3413 LocalValueId::new(
3414 u32::try_from(self.node_ref_handle_start + u64::from(node_ref))
3415 .expect("validated component value allocation fits u32"),
3416 )
3417 }));
3418 }
3419}
3420
3421#[derive(Clone, Copy, Debug, PartialEq, Eq)]
3424struct ComponentOriginLayout {
3425 prop_use_count: u32,
3426 payload_handler_start: u64,
3427 payload_handler_count: u32,
3428 signal_start: u64,
3429 signal_count: u32,
3430 expr_start: u64,
3431 expr_count: u32,
3432 handler_start: u64,
3433 handler_count: u32,
3434 browser_operation_start: u64,
3435 browser_operation_count: u32,
3436 node_ref_start: u64,
3437 node_ref_count: u32,
3438 query_start: u64,
3439 query_count: u32,
3440 mutation_start: u64,
3441 mutation_count: u32,
3442 shared_state_start: u64,
3443 shared_state_count: u32,
3444 binding_start: u64,
3445 binding_count: u32,
3446 component_start: u64,
3447 component_count: u32,
3448}
3449
3450impl ComponentOriginLayout {
3451 fn new(
3452 definition: TransportDefinitionId,
3453 prop_use_count: usize,
3454 payload_handler_count: usize,
3455 signal_count: usize,
3456 expr_count: usize,
3457 handler_count: usize,
3458 browser_operation_count: usize,
3459 node_ref_count: usize,
3460 query_count: usize,
3461 mutation_count: usize,
3462 shared_state_count: usize,
3463 binding_count: usize,
3464 component_count: usize,
3465 ) -> Result<Self, AbiAdapterError> {
3466 let prop_use_count = u64::try_from(prop_use_count).map_err(|_| {
3467 invalid(
3468 "component",
3469 definition,
3470 "prop-use count exceeds the canonical u64 origin space",
3471 )
3472 })?;
3473 let component_count = u64::try_from(component_count).map_err(|_| {
3474 invalid(
3475 "component",
3476 definition,
3477 "component edge count exceeds the canonical u64 origin space",
3478 )
3479 })?;
3480 let payload_handler_count = u64::try_from(payload_handler_count).map_err(|_| {
3481 invalid(
3482 "component",
3483 definition,
3484 "payload-handler count exceeds the canonical u64 origin space",
3485 )
3486 })?;
3487 let signal_count = u64::try_from(signal_count).map_err(|_| {
3488 invalid(
3489 "component",
3490 definition,
3491 "legacy signal count exceeds the canonical u64 origin space",
3492 )
3493 })?;
3494 let expr_count = u64::try_from(expr_count).map_err(|_| {
3495 invalid(
3496 "component",
3497 definition,
3498 "legacy expression count exceeds the canonical u64 origin space",
3499 )
3500 })?;
3501 let handler_count = u64::try_from(handler_count).map_err(|_| {
3502 invalid(
3503 "component",
3504 definition,
3505 "bound legacy handler count exceeds the canonical u64 origin space",
3506 )
3507 })?;
3508 let browser_operation_count = u64::try_from(browser_operation_count).map_err(|_| {
3509 invalid(
3510 "component",
3511 definition,
3512 "browser-operation count exceeds the canonical u64 origin space",
3513 )
3514 })?;
3515 let node_ref_count = u64::try_from(node_ref_count).map_err(|_| {
3516 invalid(
3517 "component",
3518 definition,
3519 "reachable node-reference count exceeds the canonical u64 origin space",
3520 )
3521 })?;
3522 let query_count = u64::try_from(query_count).map_err(|_| {
3523 invalid(
3524 "component",
3525 definition,
3526 "reachable query count exceeds the canonical u64 origin space",
3527 )
3528 })?;
3529 let mutation_count = u64::try_from(mutation_count).map_err(|_| {
3530 invalid(
3531 "component",
3532 definition,
3533 "reachable mutation count exceeds the canonical u64 origin space",
3534 )
3535 })?;
3536 let shared_state_count = u64::try_from(shared_state_count).map_err(|_| {
3537 invalid(
3538 "component",
3539 definition,
3540 "active SharedState count exceeds the canonical u64 origin space",
3541 )
3542 })?;
3543 let binding_count = u64::try_from(binding_count).map_err(|_| {
3544 invalid(
3545 "component",
3546 definition,
3547 "legacy DOM-binding count exceeds the canonical u64 origin space",
3548 )
3549 })?;
3550 let prop_use_count = u32::try_from(prop_use_count).map_err(|_| {
3551 invalid(
3552 "component",
3553 definition,
3554 "prop-use count exceeds the canonical u32 origin space",
3555 )
3556 })?;
3557 let component_count = u32::try_from(component_count).map_err(|_| {
3558 invalid(
3559 "component",
3560 definition,
3561 "component edge count exceeds the canonical u32 origin space",
3562 )
3563 })?;
3564 let payload_handler_count = u32::try_from(payload_handler_count).map_err(|_| {
3565 invalid(
3566 "component",
3567 definition,
3568 "payload-handler count exceeds the canonical u32 origin space",
3569 )
3570 })?;
3571 let signal_count = u32::try_from(signal_count).map_err(|_| {
3572 invalid(
3573 "component",
3574 definition,
3575 "legacy signal count exceeds the canonical u32 origin space",
3576 )
3577 })?;
3578 let expr_count = u32::try_from(expr_count).map_err(|_| {
3579 invalid(
3580 "component",
3581 definition,
3582 "legacy expression count exceeds the canonical u32 origin space",
3583 )
3584 })?;
3585 let handler_count = u32::try_from(handler_count).map_err(|_| {
3586 invalid(
3587 "component",
3588 definition,
3589 "bound legacy handler count exceeds the canonical u32 origin space",
3590 )
3591 })?;
3592 let browser_operation_count = u32::try_from(browser_operation_count).map_err(|_| {
3593 invalid(
3594 "component",
3595 definition,
3596 "browser-operation count exceeds the canonical u32 origin space",
3597 )
3598 })?;
3599 let node_ref_count = u32::try_from(node_ref_count).map_err(|_| {
3600 invalid(
3601 "component",
3602 definition,
3603 "reachable node-reference count exceeds the canonical u32 origin space",
3604 )
3605 })?;
3606 let query_count = u32::try_from(query_count).map_err(|_| {
3607 invalid(
3608 "component",
3609 definition,
3610 "reachable query count exceeds the canonical u32 origin space",
3611 )
3612 })?;
3613 let mutation_count = u32::try_from(mutation_count).map_err(|_| {
3614 invalid(
3615 "component",
3616 definition,
3617 "reachable mutation count exceeds the canonical u32 origin space",
3618 )
3619 })?;
3620 let shared_state_count = u32::try_from(shared_state_count).map_err(|_| {
3621 invalid(
3622 "component",
3623 definition,
3624 "active SharedState count exceeds the canonical u32 origin space",
3625 )
3626 })?;
3627 let binding_count = u32::try_from(binding_count).map_err(|_| {
3628 invalid(
3629 "component",
3630 definition,
3631 "legacy DOM-binding count exceeds the canonical u32 origin space",
3632 )
3633 })?;
3634 let payload_handler_start = u64::from(prop_use_count);
3635 let signal_start = payload_handler_start
3636 .checked_add(u64::from(payload_handler_count))
3637 .ok_or_else(|| {
3638 invalid(
3639 "component",
3640 definition,
3641 "payload handlers exhaust the canonical u64 origin allocation space",
3642 )
3643 })?;
3644 let expr_start = signal_start
3645 .checked_add(u64::from(signal_count))
3646 .ok_or_else(|| {
3647 invalid(
3648 "component",
3649 definition,
3650 "legacy signals exhaust the canonical u64 origin allocation space",
3651 )
3652 })?;
3653 let handler_start = expr_start
3654 .checked_add(u64::from(expr_count))
3655 .ok_or_else(|| {
3656 invalid(
3657 "component",
3658 definition,
3659 "legacy expressions exhaust the canonical u64 origin allocation space",
3660 )
3661 })?;
3662 let browser_operation_start = handler_start
3663 .checked_add(u64::from(handler_count))
3664 .ok_or_else(|| {
3665 invalid(
3666 "component",
3667 definition,
3668 "bound legacy handlers exhaust the canonical u64 origin allocation space",
3669 )
3670 })?;
3671 let node_ref_start = browser_operation_start
3672 .checked_add(u64::from(browser_operation_count))
3673 .ok_or_else(|| {
3674 invalid(
3675 "component",
3676 definition,
3677 "browser operations exhaust the canonical u64 origin allocation space",
3678 )
3679 })?;
3680 let query_start = node_ref_start
3681 .checked_add(u64::from(node_ref_count))
3682 .ok_or_else(|| {
3683 invalid(
3684 "component",
3685 definition,
3686 "reachable node references exhaust the canonical u64 origin allocation space",
3687 )
3688 })?;
3689 let mutation_start = query_start
3690 .checked_add(u64::from(query_count))
3691 .ok_or_else(|| {
3692 invalid(
3693 "component",
3694 definition,
3695 "reachable queries exhaust the canonical u64 origin allocation space",
3696 )
3697 })?;
3698 let shared_state_start = mutation_start
3699 .checked_add(u64::from(mutation_count))
3700 .ok_or_else(|| {
3701 invalid(
3702 "component",
3703 definition,
3704 "reachable mutations exhaust the canonical u64 origin allocation space",
3705 )
3706 })?;
3707 let binding_start = shared_state_start
3708 .checked_add(u64::from(shared_state_count))
3709 .ok_or_else(|| {
3710 invalid(
3711 "component",
3712 definition,
3713 "active SharedState acquisitions exhaust the canonical u64 origin allocation space",
3714 )
3715 })?;
3716 let component_start = binding_start
3717 .checked_add(u64::from(binding_count))
3718 .ok_or_else(|| {
3719 invalid(
3720 "component",
3721 definition,
3722 "legacy DOM bindings exhaust the canonical u64 origin allocation space",
3723 )
3724 })?;
3725 let allocation_end = component_start
3726 .checked_add(u64::from(component_count))
3727 .ok_or_else(|| {
3728 invalid(
3729 "component",
3730 definition,
3731 "component edges exhaust the canonical u64 origin allocation space",
3732 )
3733 })?;
3734 if allocation_end > u64::from(u32::MAX) + 1 {
3735 return Err(invalid(
3736 "component",
3737 definition,
3738 "component graph origins exhaust the canonical u32 origin space",
3739 ));
3740 }
3741 Ok(Self {
3742 prop_use_count,
3743 payload_handler_start,
3744 payload_handler_count,
3745 signal_start,
3746 signal_count,
3747 expr_start,
3748 expr_count,
3749 handler_start,
3750 handler_count,
3751 browser_operation_start,
3752 browser_operation_count,
3753 node_ref_start,
3754 node_ref_count,
3755 query_start,
3756 query_count,
3757 mutation_start,
3758 mutation_count,
3759 shared_state_start,
3760 shared_state_count,
3761 binding_start,
3762 binding_count,
3763 component_start,
3764 component_count,
3765 })
3766 }
3767
3768 fn payload_handler(
3769 self,
3770 definition: TransportDefinitionId,
3771 ordinal: u32,
3772 ) -> Result<OriginId, AbiAdapterError> {
3773 if ordinal >= self.payload_handler_count {
3774 return Err(invalid(
3775 "component",
3776 definition,
3777 format!(
3778 "payload-handler ordinal {ordinal} is outside its allocated origin range of {}",
3779 self.payload_handler_count
3780 ),
3781 ));
3782 }
3783 let origin = self
3784 .payload_handler_start
3785 .checked_add(u64::from(ordinal))
3786 .and_then(|origin| u32::try_from(origin).ok())
3787 .ok_or_else(|| {
3788 invalid(
3789 "component",
3790 definition,
3791 "payload-handler origin ID exceeds the canonical u32 origin space",
3792 )
3793 })?;
3794 Ok(OriginId::new(origin))
3795 }
3796
3797 fn prop_use(
3798 self,
3799 definition: TransportDefinitionId,
3800 site: u32,
3801 ) -> Result<OriginId, AbiAdapterError> {
3802 if site >= self.prop_use_count {
3803 return Err(invalid(
3804 "component",
3805 definition,
3806 format!(
3807 "prop-use site {site} is outside its allocated origin range of {}",
3808 self.prop_use_count
3809 ),
3810 ));
3811 }
3812 Ok(OriginId::new(site))
3813 }
3814
3815 fn signal(
3816 self,
3817 definition: TransportDefinitionId,
3818 ordinal: u32,
3819 ) -> Result<OriginId, AbiAdapterError> {
3820 self.range_origin(
3821 definition,
3822 "legacy signal",
3823 self.signal_start,
3824 self.signal_count,
3825 ordinal,
3826 )
3827 }
3828
3829 fn expr(
3830 self,
3831 definition: TransportDefinitionId,
3832 ordinal: u32,
3833 ) -> Result<OriginId, AbiAdapterError> {
3834 self.range_origin(
3835 definition,
3836 "legacy expression",
3837 self.expr_start,
3838 self.expr_count,
3839 ordinal,
3840 )
3841 }
3842
3843 fn handler(
3844 self,
3845 definition: TransportDefinitionId,
3846 ordinal: u32,
3847 ) -> Result<OriginId, AbiAdapterError> {
3848 self.range_origin(
3849 definition,
3850 "bound legacy handler",
3851 self.handler_start,
3852 self.handler_count,
3853 ordinal,
3854 )
3855 }
3856
3857 fn binding(
3858 self,
3859 definition: TransportDefinitionId,
3860 ordinal: u32,
3861 ) -> Result<OriginId, AbiAdapterError> {
3862 self.range_origin(
3863 definition,
3864 "legacy DOM binding",
3865 self.binding_start,
3866 self.binding_count,
3867 ordinal,
3868 )
3869 }
3870
3871 fn browser_operation(
3872 self,
3873 definition: TransportDefinitionId,
3874 ordinal: u32,
3875 ) -> Result<OriginId, AbiAdapterError> {
3876 self.range_origin(
3877 definition,
3878 "browser operation",
3879 self.browser_operation_start,
3880 self.browser_operation_count,
3881 ordinal,
3882 )
3883 }
3884
3885 fn node_ref(
3886 self,
3887 definition: TransportDefinitionId,
3888 ordinal: u32,
3889 ) -> Result<OriginId, AbiAdapterError> {
3890 self.range_origin(
3891 definition,
3892 "reachable node reference",
3893 self.node_ref_start,
3894 self.node_ref_count,
3895 ordinal,
3896 )
3897 }
3898
3899 fn query(
3900 self,
3901 definition: TransportDefinitionId,
3902 ordinal: u32,
3903 ) -> Result<OriginId, AbiAdapterError> {
3904 self.range_origin(
3905 definition,
3906 "reachable query",
3907 self.query_start,
3908 self.query_count,
3909 ordinal,
3910 )
3911 }
3912
3913 fn mutation(
3914 self,
3915 definition: TransportDefinitionId,
3916 ordinal: u32,
3917 ) -> Result<OriginId, AbiAdapterError> {
3918 self.range_origin(
3919 definition,
3920 "reachable mutation",
3921 self.mutation_start,
3922 self.mutation_count,
3923 ordinal,
3924 )
3925 }
3926
3927 fn shared_state(
3928 self,
3929 definition: TransportDefinitionId,
3930 ordinal: u32,
3931 ) -> Result<OriginId, AbiAdapterError> {
3932 self.range_origin(
3933 definition,
3934 "active SharedState acquisition",
3935 self.shared_state_start,
3936 self.shared_state_count,
3937 ordinal,
3938 )
3939 }
3940
3941 fn range_origin(
3942 self,
3943 definition: TransportDefinitionId,
3944 label: &'static str,
3945 start: u64,
3946 count: u32,
3947 ordinal: u32,
3948 ) -> Result<OriginId, AbiAdapterError> {
3949 if ordinal >= count {
3950 return Err(invalid(
3951 "component",
3952 definition,
3953 format!("{label} ordinal {ordinal} is outside its origin range of {count}"),
3954 ));
3955 }
3956 let origin = start
3957 .checked_add(u64::from(ordinal))
3958 .and_then(|origin| u32::try_from(origin).ok())
3959 .ok_or_else(|| {
3960 invalid(
3961 "component",
3962 definition,
3963 format!("{label} origin ID exceeds the canonical u32 origin space"),
3964 )
3965 })?;
3966 Ok(OriginId::new(origin))
3967 }
3968
3969 fn component(
3970 self,
3971 definition: TransportDefinitionId,
3972 ordinal: u32,
3973 ) -> Result<OriginId, AbiAdapterError> {
3974 if ordinal >= self.component_count {
3975 return Err(invalid(
3976 "component",
3977 definition,
3978 format!(
3979 "component edge ordinal {ordinal} is outside its allocated origin range of {}",
3980 self.component_count
3981 ),
3982 ));
3983 }
3984 let origin = self
3985 .component_start
3986 .checked_add(u64::from(ordinal))
3987 .and_then(|origin| u32::try_from(origin).ok())
3988 .ok_or_else(|| {
3989 invalid(
3990 "component",
3991 definition,
3992 "component edge origin ID exceeds the canonical u32 origin space",
3993 )
3994 })?;
3995 Ok(OriginId::new(origin))
3996 }
3997}
3998
3999fn populate_component_input_graph(
4000 definition: TransportDefinitionId,
4001 descriptor: &mut ComponentDescriptor,
4002 inbound: &ValidatedInboundInputs,
4003 value_layout: &ComponentValueLayout,
4004 origin_layout: ComponentOriginLayout,
4005) -> Result<(), AbiAdapterError> {
4006 value_layout.populate(&mut descriptor.values);
4007
4008 for field in &inbound.fields {
4009 let crossing = u32::try_from(field.crossing).map_err(|_| {
4010 invalid(
4011 "component",
4012 definition,
4013 format!(
4014 "component field `{}` crossing hook exceeds the canonical u32 ID space",
4015 field.name
4016 ),
4017 )
4018 })?;
4019 descriptor
4020 .crossing_hooks
4021 .insert(CrossingHookId::new(crossing));
4022 }
4023
4024 for prop_use in &inbound.prop_uses {
4025 let site = PropSiteId::new(prop_use.site);
4026 let origin = origin_layout.prop_use(definition, prop_use.site)?;
4027 let value = value_layout.inbound(definition, u64::from(prop_use.value))?;
4028 descriptor.origins.insert(origin, OriginKind::SourceOnly);
4029 descriptor.prop_uses.insert(
4030 site,
4031 PropUse {
4032 field: ComponentFieldId::new(prop_use.field),
4033 value,
4034 temporal: prop_use.temporal,
4035 origin,
4036 },
4037 );
4038 if let Some(target_signal) = prop_use.target_signal {
4039 push_dependency(
4040 definition,
4041 descriptor,
4042 DependencyEdgeKind::Data,
4043 DependencyEndpoint::Value(value),
4044 DependencyEndpoint::Value(value_layout.signal(definition, target_signal)?),
4045 origin,
4046 )?;
4047 }
4048 }
4049
4050 Ok(())
4051}
4052
4053fn payload_handler_value_map(
4054 definition: TransportDefinitionId,
4055 handlers: &[ValidatedPayloadHandlerValue],
4056 value_layout: &ComponentValueLayout,
4057) -> Result<BTreeMap<u32, LocalValueId>, AbiAdapterError> {
4058 handlers
4059 .iter()
4060 .enumerate()
4061 .map(|(ordinal, handler)| {
4062 let ordinal = u32::try_from(ordinal).map_err(|_| {
4063 invalid(
4064 "component",
4065 definition,
4066 "payload-handler count exceeds the canonical u32 value space",
4067 )
4068 })?;
4069 Ok((
4070 handler.prelude_local_index,
4071 value_layout.payload_handler(definition, ordinal)?,
4072 ))
4073 })
4074 .collect()
4075}
4076
4077fn legacy_component_client_program_material(
4078 descriptor: &Map<String, Value>,
4079 handlers: &[ValidatedPayloadHandlerValue],
4080) -> Value {
4081 Value::Object(Map::from_iter([
4082 (
4083 "component_descriptor".to_owned(),
4084 Value::Object(descriptor.clone()),
4085 ),
4086 (
4087 "payload_handlers".to_owned(),
4088 Value::Array(
4089 handlers
4090 .iter()
4091 .map(|handler| {
4092 serde_json::json!({
4093 "body_hash": format!("sha256:{}", handler.body_hash),
4094 "body_ir": handler.body_ir,
4095 "payload_arity": handler.payload_arity,
4096 "prelude_local_index": handler.prelude_local_index,
4097 })
4098 })
4099 .collect(),
4100 ),
4101 ),
4102 ]))
4103}
4104
4105fn populate_shared_state_references(
4106 definition: TransportDefinitionId,
4107 descriptor: &mut ComponentDescriptor,
4108 graph: &LegacyClientGraph,
4109 shared_state: &ActiveSharedStatePlan,
4110 value_layout: &ComponentValueLayout,
4111 origin_layout: ComponentOriginLayout,
4112) -> Result<BTreeMap<u32, OriginId>, AbiAdapterError> {
4113 let mut store_origins = BTreeMap::new();
4114 for (ordinal, store) in shared_state.stores.iter().enumerate() {
4115 let ordinal = checked_ordinal(definition, ordinal, "active SharedState acquisition")?;
4116 let origin = origin_layout.shared_state(definition, ordinal)?;
4117 descriptor.origins.insert(origin, OriginKind::SharedState);
4118 descriptor.shared_state.insert(
4119 SharedStateRefId::new(ordinal),
4120 SharedStateReference {
4121 type_key: store.type_key.clone(),
4122 schema_abi: store.schema_abi,
4123 origin,
4124 },
4125 );
4126 store_origins.insert(store.store_id, origin);
4127 }
4128 let mut signal_origins = BTreeMap::new();
4129 for signal in &graph.signals {
4130 let Some(field) = &signal.shared_field else {
4131 continue;
4132 };
4133 let origin = store_origins.get(&field.store).copied().ok_or_else(|| {
4134 invalid(
4135 "component",
4136 definition,
4137 format!(
4138 "active SharedState signal {} lost store {} during canonical allocation",
4139 signal.id, field.store,
4140 ),
4141 )
4142 })?;
4143 push_dependency(
4144 definition,
4145 descriptor,
4146 DependencyEdgeKind::Component,
4147 DependencyEndpoint::Origin(origin),
4148 DependencyEndpoint::Value(value_layout.signal(definition, signal.id)?),
4149 origin,
4150 )?;
4151 signal_origins.insert(signal.id, origin);
4152 }
4153 Ok(signal_origins)
4154}
4155
4156fn populate_payload_handler_graph(
4157 definition: TransportDefinitionId,
4158 descriptor: &mut ComponentDescriptor,
4159 handlers: &[ValidatedPayloadHandlerValue],
4160 inbound: &ValidatedInboundInputs,
4161 value_layout: &ComponentValueLayout,
4162 origin_layout: ComponentOriginLayout,
4163 direct_helper_edges: &[ValidatedComponentHelperEdge],
4164 shared_state_origins: &BTreeMap<u32, OriginId>,
4165 browser_operation_ordinal: &mut u32,
4166) -> Result<(), AbiAdapterError> {
4167 let helper_ids = direct_helper_edges
4168 .iter()
4169 .enumerate()
4170 .map(|(dense, helper)| {
4171 let dense = u32::try_from(dense).map_err(|_| {
4172 invalid(
4173 "component",
4174 definition,
4175 "reachable helper count exceeds the canonical u32 ID space",
4176 )
4177 })?;
4178 Ok((helper.local_ordinal, HelperCallEdgeId::new(dense)))
4179 })
4180 .collect::<Result<BTreeMap<_, _>, AbiAdapterError>>()?;
4181 let callback_values = inbound_callback_values(definition, inbound, value_layout)?;
4182
4183 for (ordinal, handler) in handlers.iter().enumerate() {
4184 let ordinal = u32::try_from(ordinal).map_err(|_| {
4185 invalid(
4186 "component",
4187 definition,
4188 "payload-handler count exceeds the canonical u32 graph space",
4189 )
4190 })?;
4191 let value = value_layout.payload_handler(definition, ordinal)?;
4192 let effect = LocalEffectId::new(ordinal);
4193 let origin = origin_layout.payload_handler(definition, ordinal)?;
4194 descriptor.origins.insert(origin, OriginKind::EventHandler);
4195 descriptor.effects.insert(effect, EffectKind::EventHandler);
4196 push_dependency(
4197 definition,
4198 descriptor,
4199 DependencyEdgeKind::Data,
4200 DependencyEndpoint::Origin(origin),
4201 DependencyEndpoint::Value(value),
4202 origin,
4203 )?;
4204 push_dependency(
4205 definition,
4206 descriptor,
4207 DependencyEdgeKind::Effect,
4208 DependencyEndpoint::Value(value),
4209 DependencyEndpoint::Effect(effect),
4210 origin,
4211 )?;
4212
4213 let mut captured_signals = BTreeSet::new();
4214 for signal in handler
4215 .dependencies
4216 .signal_reads
4217 .iter()
4218 .chain(&handler.dependencies.signal_writes)
4219 {
4220 if captured_signals.insert(signal.0) {
4221 push_dependency(
4222 definition,
4223 descriptor,
4224 DependencyEdgeKind::Capture,
4225 DependencyEndpoint::Value(value_layout.signal(definition, signal.0)?),
4226 DependencyEndpoint::Effect(effect),
4227 origin,
4228 )?;
4229 }
4230 }
4231 for callback in &handler.dependencies.callback_slots {
4232 let Some(&callback_value) = callback_values.get(&callback.0) else {
4233 return Err(invalid(
4234 "component",
4235 definition,
4236 format!(
4237 "payload handler {} lost inbound callback slot {} during canonical allocation",
4238 handler.prelude_local_index, callback.0,
4239 ),
4240 ));
4241 };
4242 push_dependency(
4243 definition,
4244 descriptor,
4245 DependencyEdgeKind::Capture,
4246 DependencyEndpoint::Value(callback_value),
4247 DependencyEndpoint::Effect(effect),
4248 origin,
4249 )?;
4250 }
4251 for helper in &handler.dependencies.helper_edges {
4252 let Some(&helper) = helper_ids.get(&helper.index()) else {
4253 return Err(invalid(
4254 "component",
4255 definition,
4256 format!(
4257 "payload handler {} lost relocation-resolved helper edge {} during canonical allocation",
4258 handler.prelude_local_index,
4259 helper.index(),
4260 ),
4261 ));
4262 };
4263 push_dependency(
4264 definition,
4265 descriptor,
4266 DependencyEdgeKind::HelperCall,
4267 DependencyEndpoint::Helper(helper),
4268 DependencyEndpoint::Effect(effect),
4269 origin,
4270 )?;
4271 }
4272 populate_browser_operations(
4273 definition,
4274 descriptor,
4275 &handler.browser_operations,
4276 DependencyEndpoint::Effect(effect),
4277 value_layout,
4278 &callback_values,
4279 &helper_ids,
4280 origin_layout,
4281 browser_operation_ordinal,
4282 )?;
4283 }
4284 for (ordinal, handler) in handlers.iter().enumerate() {
4285 let ordinal = checked_ordinal(definition, ordinal, "payload handler")?;
4286 let enclosing = DependencyEndpoint::Effect(LocalEffectId::new(ordinal));
4287 populate_payload_shared_state_effects(
4293 definition,
4294 descriptor,
4295 handler,
4296 enclosing,
4297 value_layout,
4298 shared_state_origins,
4299 )?;
4300 }
4301 Ok(())
4302}
4303
4304fn populate_payload_shared_state_effects(
4305 definition: TransportDefinitionId,
4306 descriptor: &mut ComponentDescriptor,
4307 handler: &ValidatedPayloadHandlerValue,
4308 enclosing: DependencyEndpoint,
4309 value_layout: &ComponentValueLayout,
4310 shared_state_origins: &BTreeMap<u32, OriginId>,
4311) -> Result<(), AbiAdapterError> {
4312 let mut seen = BTreeSet::new();
4313 for (read, signal) in handler
4314 .dependencies
4315 .signal_reads
4316 .iter()
4317 .map(|signal| (true, signal.0))
4318 .chain(
4319 handler
4320 .dependencies
4321 .signal_writes
4322 .iter()
4323 .map(|signal| (false, signal.0)),
4324 )
4325 {
4326 let Some(&origin) = shared_state_origins.get(&signal) else {
4327 continue;
4328 };
4329 if !seen.insert((read, signal)) {
4330 continue;
4331 }
4332 let effect = next_effect_id(definition, descriptor)?;
4333 descriptor.effects.insert(
4334 effect,
4335 if read {
4336 EffectKind::SharedStateRead
4337 } else {
4338 EffectKind::SharedStateWrite
4339 },
4340 );
4341 push_dependency(
4342 definition,
4343 descriptor,
4344 DependencyEdgeKind::Effect,
4345 DependencyEndpoint::Origin(origin),
4346 DependencyEndpoint::Effect(effect),
4347 origin,
4348 )?;
4349 if read {
4350 push_dependency(
4351 definition,
4352 descriptor,
4353 DependencyEdgeKind::Data,
4354 DependencyEndpoint::Effect(effect),
4355 enclosing,
4356 origin,
4357 )?;
4358 } else {
4359 push_dependency(
4360 definition,
4361 descriptor,
4362 DependencyEdgeKind::Effect,
4363 enclosing,
4364 DependencyEndpoint::Effect(effect),
4365 origin,
4366 )?;
4367 push_dependency(
4368 definition,
4369 descriptor,
4370 DependencyEdgeKind::Effect,
4371 DependencyEndpoint::Effect(effect),
4372 DependencyEndpoint::Value(value_layout.signal(definition, signal)?),
4373 origin,
4374 )?;
4375 }
4376 }
4377 Ok(())
4378}
4379
4380fn inbound_callback_values(
4381 definition: TransportDefinitionId,
4382 inbound: &ValidatedInboundInputs,
4383 value_layout: &ComponentValueLayout,
4384) -> Result<BTreeMap<u32, LocalValueId>, AbiAdapterError> {
4385 let mut callbacks = BTreeMap::new();
4386 for field in &inbound.fields {
4387 if field.kind != InboundFieldKind::Callback {
4388 continue;
4389 }
4390 let Some(slot) = field.callback_slot else {
4391 continue;
4395 };
4396 let value = value_layout.inbound(definition, field.value)?;
4397 if callbacks.insert(slot, value).is_some() {
4398 return Err(invalid(
4399 "component",
4400 definition,
4401 format!("multiple inbound callback fields claim callback slot {slot}"),
4402 ));
4403 }
4404 }
4405 Ok(callbacks)
4406}
4407
4408fn validate_query_key_prop_targets(
4409 definition: TransportDefinitionId,
4410 inbound: &ValidatedInboundInputs,
4411 graph: &LegacyClientGraph,
4412) -> Result<(), AbiAdapterError> {
4413 let expressions = graph
4414 .expressions
4415 .iter()
4416 .map(|expression| (expression.id, expression))
4417 .collect::<BTreeMap<_, _>>();
4418 let reachable_queries = graph
4419 .reachable_queries
4420 .iter()
4421 .copied()
4422 .collect::<BTreeSet<_>>();
4423 for prop_use in &inbound.prop_uses {
4424 if prop_use.temporal != TemporalPropMode::QueryKeyDependency {
4425 continue;
4426 }
4427 let Some(target_signal) = prop_use.target_signal else {
4428 return Err(invalid(
4429 "component",
4430 definition,
4431 format!(
4432 "query-key prop site {} has no live-signal target",
4433 prop_use.site
4434 ),
4435 ));
4436 };
4437 let consumed_by_reachable_key = graph.queries.iter().any(|query| {
4438 reachable_queries.contains(&query.id)
4439 && expressions
4440 .get(&query.key_expression)
4441 .is_some_and(|expression| {
4442 expression
4443 .dependencies
4444 .signal_reads
4445 .iter()
4446 .any(|signal| signal.0 == target_signal)
4447 })
4448 });
4449 if !consumed_by_reachable_key {
4450 return Err(invalid(
4451 "component",
4452 definition,
4453 format!(
4454 "query-key prop site {} targets signal {}, but no reachable query key reads it",
4455 prop_use.site, target_signal
4456 ),
4457 ));
4458 }
4459 }
4460 Ok(())
4461}
4462
4463fn validate_node_ref_handle_topology(
4464 definition: TransportDefinitionId,
4465 inbound: &ValidatedInboundInputs,
4466 graph: &LegacyClientGraph,
4467 direct_edges: &[ValidatedDirectComponentEdge],
4468) -> Result<(), AbiAdapterError> {
4469 let mut local_bindings = BTreeMap::<u32, usize>::new();
4470 for binding in &graph.bindings.node_refs {
4471 *local_bindings.entry(binding.node_ref).or_default() += 1;
4472 }
4473 let mut outgoing_aliases = BTreeMap::<u32, Vec<(u32, String)>>::new();
4474 for edge in direct_edges {
4475 for field in &edge.fields {
4476 let ValidatedDirectComponentBinding::NodeRefHandle { node_ref } = field.binding else {
4477 continue;
4478 };
4479 outgoing_aliases
4480 .entry(node_ref)
4481 .or_default()
4482 .push((edge.local_ordinal, field.name.clone()));
4483 }
4484 }
4485
4486 let inbound_by_node_ref = inbound
4487 .node_refs
4488 .iter()
4489 .map(|node_ref| (node_ref.node_ref, node_ref))
4490 .collect::<BTreeMap<_, _>>();
4491 let involved = inbound_by_node_ref
4492 .keys()
4493 .copied()
4494 .chain(outgoing_aliases.keys().copied())
4495 .collect::<BTreeSet<_>>();
4496 for node_ref in involved {
4497 let local_count = local_bindings.get(&node_ref).copied().unwrap_or(0);
4498 let aliases = outgoing_aliases
4499 .get(&node_ref)
4500 .map(Vec::as_slice)
4501 .unwrap_or(&[]);
4502 let sink_count = local_count
4503 .checked_add(aliases.len())
4504 .expect("two in-memory collection lengths fit usize");
4505 if sink_count != 1 {
4506 return Err(invalid(
4507 "component",
4508 definition,
4509 format!(
4510 "NodeRef handle {node_ref} must have exactly one terminal local binding or one static direct alias, found {local_count} local binding(s) and {} alias edge(s)",
4511 aliases.len()
4512 ),
4513 ));
4514 }
4515 if let Some(inbound) = inbound_by_node_ref.get(&node_ref) {
4516 match (inbound.bind_target, local_count) {
4517 (Some(_), 1) | (None, 0) => {}
4518 (Some(_), _) => {
4519 return Err(invalid(
4520 "component",
4521 definition,
4522 format!(
4523 "inbound NodeRef handle {node_ref} claims a rustc-checked bind target but has {local_count} local bindings"
4524 ),
4525 ));
4526 }
4527 (None, _) => {
4528 return Err(invalid(
4529 "component",
4530 definition,
4531 format!(
4532 "inbound NodeRef handle {node_ref} has a local binding without a rustc-checked bind target"
4533 ),
4534 ));
4535 }
4536 }
4537 } else if local_count != 0 {
4538 return Err(invalid(
4539 "component",
4540 definition,
4541 format!(
4542 "locally created NodeRef handle {node_ref} cannot be both locally bound and passed through a component alias"
4543 ),
4544 ));
4545 }
4546 }
4547 Ok(())
4548}
4549
4550fn build_component_codegen_bridge(
4551 definition: TransportDefinitionId,
4552 descriptor: &Map<String, Value>,
4553 inbound: &ValidatedInboundInputs,
4554 graph: &LegacyClientGraph,
4555 payload_handlers: &[ValidatedPayloadHandlerValue],
4556 value_layout: &ComponentValueLayout,
4557 view: &ValidatedView,
4558 direct_component_edges: &[ValidatedDirectComponentEdge],
4559) -> Result<ComponentCodegenBridge, AbiAdapterError> {
4560 let asset_id = required_str(descriptor, "asset_id", "component", definition)?.to_owned();
4561 if !valid_component_artifact_key(&asset_id) {
4562 return Err(invalid(
4563 "component",
4564 definition,
4565 format!("component asset_id `{asset_id}` is not a non-empty ASCII asset key"),
4566 ));
4567 }
4568
4569 let inbound_fields = inbound
4570 .fields
4571 .iter()
4572 .enumerate()
4573 .filter(|(_, field)| field.kind != InboundFieldKind::ServerOnly)
4574 .map(|(field_index, field)| {
4575 let field_id = u32::try_from(field_index).map_err(|_| {
4576 invalid(
4577 "component",
4578 definition,
4579 "inbound component field count exceeds the canonical u32 ID space",
4580 )
4581 })?;
4582 Ok(ComponentCodegenInboundField {
4583 field_id: ComponentFieldId::new(field_id),
4584 producer_value_id: checked_u32(
4585 field.value,
4586 "inbound producer value ID",
4587 definition,
4588 )?,
4589 canonical_value: value_layout.inbound(definition, field.value)?,
4590 crossing_hook_id: CrossingHookId::new(checked_u32(
4591 field.crossing,
4592 "inbound crossing hook ID",
4593 definition,
4594 )?),
4595 callback_slot_id: field.callback_slot,
4596 })
4597 })
4598 .collect::<Result<Vec<_>, AbiAdapterError>>()?;
4599
4600 let inbound_targets = inbound
4601 .prop_uses
4602 .iter()
4603 .filter_map(|prop_use| {
4604 prop_use.target_signal.map(|producer_signal_id| {
4605 Ok(ComponentCodegenInboundTarget {
4606 prop_site_id: PropSiteId::new(prop_use.site),
4607 field_id: ComponentFieldId::new(prop_use.field),
4608 producer_signal_id,
4609 canonical_signal_value: value_layout.signal(definition, producer_signal_id)?,
4610 })
4611 })
4612 })
4613 .collect::<Result<Vec<_>, AbiAdapterError>>()?;
4614
4615 let signals = graph
4616 .signals
4617 .iter()
4618 .map(|signal| {
4619 Ok(ComponentCodegenSignal {
4620 producer_signal_id: signal.id,
4621 canonical_value: value_layout.signal(definition, signal.id)?,
4622 })
4623 })
4624 .collect::<Result<Vec<_>, AbiAdapterError>>()?;
4625 let expressions = graph
4626 .expressions
4627 .iter()
4628 .map(|expression| {
4629 Ok(ComponentCodegenExpression {
4630 producer_expression_id: expression.id,
4631 canonical_value: value_layout.expr(definition, expression.id)?,
4632 })
4633 })
4634 .collect::<Result<Vec<_>, AbiAdapterError>>()?;
4635 let payload_handlers = payload_handlers
4636 .iter()
4637 .enumerate()
4638 .map(|(ordinal, handler)| {
4639 let ordinal = u32::try_from(ordinal).map_err(|_| {
4640 invalid(
4641 "component",
4642 definition,
4643 "payload-handler count exceeds the canonical u32 value space",
4644 )
4645 })?;
4646 Ok(ComponentCodegenPayloadHandler {
4647 prelude_local_index: handler.prelude_local_index,
4648 canonical_value: value_layout.payload_handler(definition, ordinal)?,
4649 })
4650 })
4651 .collect::<Result<Vec<_>, AbiAdapterError>>()?;
4652
4653 let callback_values = inbound_callback_values(definition, inbound, value_layout)?;
4654 if callback_values.len() != graph.callback_slots.len() {
4655 return Err(invalid(
4656 "component",
4657 definition,
4658 format!(
4659 "producer callback slots must join one-to-one with inbound callback fields; \
4660 found {} callback slots and {} inbound callback fields",
4661 graph.callback_slots.len(),
4662 callback_values.len(),
4663 ),
4664 ));
4665 }
4666 let callback_slots = graph
4667 .callback_slots
4668 .iter()
4669 .map(|slot| {
4670 let Some(&canonical_value) = callback_values.get(&slot.id) else {
4671 return Err(invalid(
4672 "component",
4673 definition,
4674 format!(
4675 "producer callback slot {} (`{}`) has no matching inbound callback field",
4676 slot.id, slot.name,
4677 ),
4678 ));
4679 };
4680 Ok(ComponentCodegenCallbackSlot {
4681 producer_callback_slot_id: slot.id,
4682 canonical_value,
4683 })
4684 })
4685 .collect::<Result<Vec<_>, AbiAdapterError>>()?;
4686
4687 let inbound_node_refs = inbound
4688 .node_refs
4689 .iter()
4690 .map(|node_ref| ComponentCodegenInboundNodeRef {
4691 field_id: ComponentFieldId::new(node_ref.field),
4692 producer_node_ref_id: node_ref.node_ref,
4693 bind_target: node_ref.bind_target,
4694 })
4695 .collect::<Vec<_>>();
4696 let mut direct_node_ref_aliases = direct_component_edges
4697 .iter()
4698 .flat_map(|edge| {
4699 edge.fields.iter().filter_map(move |field| {
4700 let ValidatedDirectComponentBinding::NodeRefHandle { node_ref } = field.binding
4701 else {
4702 return None;
4703 };
4704 Some((edge.local_ordinal, field.name.clone(), node_ref))
4705 })
4706 })
4707 .map(|(edge, field_name, producer_node_ref_id)| {
4708 Ok(ComponentCodegenDirectNodeRefAlias {
4709 edge_id: ComponentEdgeId::new(edge),
4710 field_name,
4711 producer_node_ref_id,
4712 canonical_value: value_layout.node_ref(definition, producer_node_ref_id)?,
4713 })
4714 })
4715 .collect::<Result<Vec<_>, AbiAdapterError>>()?;
4716 direct_node_ref_aliases.sort_by(|left, right| {
4717 (left.edge_id, left.field_name.as_str()).cmp(&(right.edge_id, right.field_name.as_str()))
4718 });
4719
4720 Ok(ComponentCodegenBridge {
4721 asset_id: asset_id.clone(),
4722 fragment_key: asset_id,
4723 fragment_root: view.fragment_root,
4724 inbound_fields,
4725 inbound_targets,
4726 signals,
4727 expressions,
4728 payload_handlers,
4729 callback_slots,
4730 inbound_node_refs,
4731 direct_node_ref_aliases,
4732 uses_queries: !graph.reachable_queries.is_empty(),
4733 uses_mutations: !graph.reachable_mutations.is_empty(),
4734 })
4735}
4736
4737fn valid_component_artifact_key(value: &str) -> bool {
4738 !value.is_empty()
4739 && value
4740 .bytes()
4741 .all(|byte| byte.is_ascii_alphanumeric() || matches!(byte, b'_' | b'-'))
4742}
4743
4744pub fn validate_component_codegen_bridge(
4752 codegen: &ComponentCodegenBridge,
4753 descriptor: &ComponentDescriptor,
4754) -> Result<(), String> {
4755 if !valid_component_artifact_key(&codegen.asset_id) {
4756 return Err(format!(
4757 "asset_id `{}` is not a non-empty ASCII asset key",
4758 codegen.asset_id
4759 ));
4760 }
4761 if codegen.fragment_key != codegen.asset_id {
4762 return Err(format!(
4763 "fragment key `{}` does not match the legacy producer asset key `{}`",
4764 codegen.fragment_key, codegen.asset_id
4765 ));
4766 }
4767 if matches!(
4768 codegen.fragment_root,
4769 ComponentFragmentRoot::ExactOneElement
4770 ) && descriptor.span != SpanCardinality::Exact(1)
4771 {
4772 return Err(
4773 "exact-one-element fragment root disagrees with the canonical DOM span".to_owned(),
4774 );
4775 }
4776 let canonical_uses_queries = descriptor
4777 .origins
4778 .values()
4779 .any(|kind| matches!(kind, OriginKind::Query))
4780 || descriptor.effects.values().any(|kind| {
4781 matches!(
4782 kind,
4783 EffectKind::QueryObservation
4784 | EffectKind::QueryRefetch
4785 | EffectKind::QueryInvalidation
4786 )
4787 });
4788 if codegen.uses_queries != canonical_uses_queries {
4789 return Err(format!(
4790 "component codegen uses_queries={} disagrees with canonical reachable query work={canonical_uses_queries}",
4791 codegen.uses_queries
4792 ));
4793 }
4794 let canonical_uses_mutations = descriptor
4795 .origins
4796 .values()
4797 .any(|kind| matches!(kind, OriginKind::Mutation))
4798 || descriptor
4799 .effects
4800 .values()
4801 .any(|kind| matches!(kind, EffectKind::Mutation));
4802 if codegen.uses_mutations != canonical_uses_mutations {
4803 return Err(format!(
4804 "component codegen uses_mutations={} disagrees with canonical reachable mutation work={canonical_uses_mutations}",
4805 codegen.uses_mutations
4806 ));
4807 }
4808
4809 let expected_fields = descriptor
4810 .fields
4811 .iter()
4812 .filter(|(_, field)| field.client_value.is_some())
4813 .collect::<Vec<_>>();
4814 if expected_fields.len() != codegen.inbound_fields.len() {
4815 return Err(format!(
4816 "component codegen has {} inbound fields, but the canonical descriptor has {} client-visible fields",
4817 codegen.inbound_fields.len(),
4818 expected_fields.len(),
4819 ));
4820 }
4821
4822 let mut expected_callbacks = Vec::new();
4823 let mut allocated_values = BTreeSet::new();
4824 for ((expected_field_id, _), mapping) in expected_fields.iter().zip(&codegen.inbound_fields) {
4825 if mapping.field_id != **expected_field_id
4826 || mapping.producer_value_id != expected_field_id.index()
4827 {
4828 return Err(format!(
4829 "inbound fields must preserve canonical source order; expected field/value {}, found field {} value {}",
4830 expected_field_id.index(),
4831 mapping.field_id.index(),
4832 mapping.producer_value_id,
4833 ));
4834 }
4835 let Some(field) = descriptor.fields.get(&mapping.field_id) else {
4836 return Err(format!(
4837 "inbound codegen field {} does not exist in the canonical descriptor",
4838 mapping.field_id.index(),
4839 ));
4840 };
4841 if field.client_value != Some(mapping.canonical_value)
4842 || field.crossing_hook != Some(mapping.crossing_hook_id)
4843 {
4844 return Err(format!(
4845 "inbound codegen field {} disagrees with its canonical value or crossing hook",
4846 mapping.field_id.index(),
4847 ));
4848 }
4849 match field.role {
4850 ComponentFieldRole::Value => {
4851 if mapping.callback_slot_id.is_some() {
4852 return Err(format!(
4853 "value field {} unexpectedly names a callback slot",
4854 mapping.field_id.index(),
4855 ));
4856 }
4857 }
4858 ComponentFieldRole::Callback => {
4859 if let Some(callback_slot_id) = mapping.callback_slot_id {
4860 expected_callbacks.push((callback_slot_id, mapping.canonical_value));
4861 }
4862 }
4863 ComponentFieldRole::ClientHandle => {
4864 if mapping.callback_slot_id.is_some() {
4865 return Err(format!(
4866 "client-handle field {} unexpectedly names a callback slot",
4867 mapping.field_id.index(),
4868 ));
4869 }
4870 }
4871 _ => {
4872 return Err(format!(
4873 "client-visible field {} has unsupported codegen role {:?}",
4874 mapping.field_id.index(),
4875 field.role,
4876 ));
4877 }
4878 }
4879 if !allocated_values.insert(mapping.canonical_value) {
4880 return Err(format!(
4881 "canonical value {} is claimed by more than one producer value category",
4882 mapping.canonical_value.index(),
4883 ));
4884 }
4885 }
4886 if expected_fields
4887 .iter()
4888 .zip(&codegen.inbound_fields)
4889 .any(|((field_id, _), mapping)| **field_id != mapping.field_id)
4890 {
4891 return Err(
4892 "component codegen inbound fields do not exactly match canonical fields".into(),
4893 );
4894 }
4895
4896 ensure_strict_component_codegen_order(
4897 "signal",
4898 codegen
4899 .signals
4900 .iter()
4901 .map(|mapping| mapping.producer_signal_id),
4902 )?;
4903 ensure_strict_component_codegen_order(
4904 "expression",
4905 codegen
4906 .expressions
4907 .iter()
4908 .map(|mapping| mapping.producer_expression_id),
4909 )?;
4910 ensure_strict_component_codegen_order(
4911 "payload handler",
4912 codegen
4913 .payload_handlers
4914 .iter()
4915 .map(|mapping| mapping.prelude_local_index),
4916 )?;
4917 ensure_strict_component_codegen_order(
4918 "callback slot",
4919 codegen
4920 .callback_slots
4921 .iter()
4922 .map(|mapping| mapping.producer_callback_slot_id),
4923 )?;
4924 ensure_strict_component_codegen_order(
4925 "inbound target",
4926 codegen
4927 .inbound_targets
4928 .iter()
4929 .map(|mapping| mapping.prop_site_id.index()),
4930 )?;
4931 ensure_strict_component_codegen_order(
4932 "inbound NodeRef",
4933 codegen
4934 .inbound_node_refs
4935 .iter()
4936 .map(|mapping| mapping.field_id.index()),
4937 )?;
4938 if codegen.direct_node_ref_aliases.windows(2).any(|pair| {
4939 (pair[0].edge_id, pair[0].field_name.as_str())
4940 >= (pair[1].edge_id, pair[1].field_name.as_str())
4941 }) {
4942 return Err(
4943 "direct NodeRef aliases must be unique and strictly ordered by edge/field".to_owned(),
4944 );
4945 }
4946
4947 let expected_node_ref_fields = descriptor
4948 .fields
4949 .iter()
4950 .filter(|(_, field)| field.role == ComponentFieldRole::ClientHandle)
4951 .map(|(&field, _)| field)
4952 .collect::<Vec<_>>();
4953 let actual_node_ref_fields = codegen
4954 .inbound_node_refs
4955 .iter()
4956 .map(|mapping| mapping.field_id)
4957 .collect::<Vec<_>>();
4958 if actual_node_ref_fields != expected_node_ref_fields {
4959 return Err(format!(
4960 "inbound NodeRef mappings do not exactly match canonical client-handle fields; expected {expected_node_ref_fields:?}, found {actual_node_ref_fields:?}"
4961 ));
4962 }
4963 let mut producer_node_refs = BTreeSet::new();
4964 for mapping in &codegen.inbound_node_refs {
4965 if !producer_node_refs.insert(mapping.producer_node_ref_id) {
4966 return Err(format!(
4967 "producer NodeRef {} is represented by more than one inbound field",
4968 mapping.producer_node_ref_id
4969 ));
4970 }
4971 let field = &descriptor.fields[&mapping.field_id];
4972 if field.crossing_hook.is_none() || field.client_value.is_none() {
4973 return Err(format!(
4974 "inbound NodeRef field {} lacks its canonical value/crossing contract",
4975 mapping.field_id.index()
4976 ));
4977 }
4978 }
4979 let mut alias_values = BTreeMap::<LocalValueId, u32>::new();
4980 for alias in &codegen.direct_node_ref_aliases {
4981 let edge = descriptor
4982 .direct_components
4983 .get(&alias.edge_id)
4984 .ok_or_else(|| {
4985 format!(
4986 "direct NodeRef alias refers to absent edge {}",
4987 alias.edge_id.index()
4988 )
4989 })?;
4990 if edge.boundary != ComponentBoundary::Composed || edge.lifecycle_control.is_some() {
4991 return Err(format!(
4992 "direct NodeRef alias edge {} must be static composed",
4993 alias.edge_id.index()
4994 ));
4995 }
4996 let binding = edge.bindings.get(&alias.field_name).ok_or_else(|| {
4997 format!(
4998 "direct NodeRef alias edge {} field `{}` has no canonical binding",
4999 alias.edge_id.index(),
5000 alias.field_name
5001 )
5002 })?;
5003 if binding.source
5004 != (ComponentBindingSource::ClientHandle {
5005 value: alias.canonical_value,
5006 })
5007 {
5008 return Err(format!(
5009 "direct NodeRef alias edge {} field `{}` disagrees with its canonical ClientHandle value",
5010 alias.edge_id.index(),
5011 alias.field_name
5012 ));
5013 }
5014 if let Some(previous) =
5015 alias_values.insert(alias.canonical_value, alias.producer_node_ref_id)
5016 {
5017 return Err(format!(
5018 "canonical NodeRef handle value {} is aliased more than once (producer refs {previous} and {})",
5019 alias.canonical_value.index(),
5020 alias.producer_node_ref_id
5021 ));
5022 }
5023 }
5024
5025 for canonical_value in codegen
5026 .signals
5027 .iter()
5028 .map(|mapping| mapping.canonical_value)
5029 .chain(
5030 codegen
5031 .expressions
5032 .iter()
5033 .map(|mapping| mapping.canonical_value),
5034 )
5035 .chain(
5036 codegen
5037 .payload_handlers
5038 .iter()
5039 .map(|mapping| mapping.canonical_value),
5040 )
5041 {
5042 if !allocated_values.insert(canonical_value) {
5043 return Err(format!(
5044 "canonical value {} is claimed by more than one producer value category",
5045 canonical_value.index(),
5046 ));
5047 }
5048 }
5049 for alias in &codegen.direct_node_ref_aliases {
5050 if allocated_values.contains(&alias.canonical_value) {
5051 let inbound_matches = codegen.inbound_node_refs.iter().any(|inbound| {
5052 descriptor.fields[&inbound.field_id].client_value == Some(alias.canonical_value)
5053 && inbound.producer_node_ref_id == alias.producer_node_ref_id
5054 });
5055 if !inbound_matches {
5056 return Err(format!(
5057 "canonical NodeRef handle value {} collides with another producer value category",
5058 alias.canonical_value.index()
5059 ));
5060 }
5061 } else {
5062 allocated_values.insert(alias.canonical_value);
5063 }
5064 }
5065 if allocated_values != descriptor.values {
5066 return Err(format!(
5067 "component codegen value mappings do not exactly partition canonical values; mapped {:?}, descriptor {:?}",
5068 allocated_values
5069 .iter()
5070 .map(|value| value.index())
5071 .collect::<Vec<_>>(),
5072 descriptor
5073 .values
5074 .iter()
5075 .map(|value| value.index())
5076 .collect::<Vec<_>>(),
5077 ));
5078 }
5079
5080 expected_callbacks.sort_unstable_by_key(|(slot, _)| *slot);
5081 let actual_callbacks = codegen
5082 .callback_slots
5083 .iter()
5084 .map(|mapping| (mapping.producer_callback_slot_id, mapping.canonical_value))
5085 .collect::<Vec<_>>();
5086 if actual_callbacks != expected_callbacks {
5087 return Err(format!(
5088 "callback-slot mappings do not exactly join inbound callback fields; expected {expected_callbacks:?}, found {actual_callbacks:?}"
5089 ));
5090 }
5091
5092 let expected_target_sites = descriptor
5093 .prop_uses
5094 .iter()
5095 .filter_map(|(&site, prop_use)| match prop_use.temporal {
5096 TemporalPropMode::LiveRead | TemporalPropMode::QueryKeyDependency => Some(site),
5097 TemporalPropMode::SeedOnce(seed_site) if seed_site == site => Some(site),
5098 _ => None,
5099 })
5100 .collect::<Vec<_>>();
5101 if expected_target_sites.len() != codegen.inbound_targets.len() {
5102 return Err(format!(
5103 "component codegen has {} inbound signal targets, but the canonical descriptor has {} signal-backed prop-use sites",
5104 codegen.inbound_targets.len(),
5105 expected_target_sites.len(),
5106 ));
5107 }
5108 for (&expected_site, target) in expected_target_sites.iter().zip(&codegen.inbound_targets) {
5109 if target.prop_site_id != expected_site {
5110 return Err(format!(
5111 "inbound target order mismatch: expected prop site {}, found {}",
5112 expected_site.index(),
5113 target.prop_site_id.index(),
5114 ));
5115 }
5116 let prop_use = &descriptor.prop_uses[&expected_site];
5117 if prop_use.field != target.field_id {
5118 return Err(format!(
5119 "inbound target at prop site {} names field {}, expected {}",
5120 expected_site.index(),
5121 target.field_id.index(),
5122 prop_use.field.index(),
5123 ));
5124 }
5125 let Some(inbound) = codegen
5126 .inbound_fields
5127 .iter()
5128 .find(|mapping| mapping.field_id == target.field_id)
5129 else {
5130 return Err(format!(
5131 "inbound target at prop site {} names absent field {}",
5132 expected_site.index(),
5133 target.field_id.index(),
5134 ));
5135 };
5136 if inbound.canonical_value != prop_use.value {
5137 return Err(format!(
5138 "inbound target at prop site {} is attached to the wrong canonical field value",
5139 expected_site.index(),
5140 ));
5141 }
5142 let Some(signal) = codegen
5143 .signals
5144 .iter()
5145 .find(|mapping| mapping.producer_signal_id == target.producer_signal_id)
5146 else {
5147 return Err(format!(
5148 "inbound target at prop site {} names absent producer signal {}",
5149 expected_site.index(),
5150 target.producer_signal_id,
5151 ));
5152 };
5153 if signal.canonical_value != target.canonical_signal_value {
5154 return Err(format!(
5155 "inbound target at prop site {} maps producer signal {} to canonical value {}, but the signal table maps it to {}",
5156 expected_site.index(),
5157 target.producer_signal_id,
5158 target.canonical_signal_value.index(),
5159 signal.canonical_value.index(),
5160 ));
5161 }
5162 if !descriptor.dependencies.values().any(|edge| {
5163 edge.kind == DependencyEdgeKind::Data
5164 && edge.from == DependencyEndpoint::Value(prop_use.value)
5165 && edge.to == DependencyEndpoint::Value(target.canonical_signal_value)
5166 }) {
5167 return Err(format!(
5168 "inbound target at prop site {} has no canonical value-to-signal dependency",
5169 expected_site.index(),
5170 ));
5171 }
5172 }
5173
5174 Ok(())
5175}
5176
5177fn ensure_strict_component_codegen_order(
5178 label: &str,
5179 ids: impl IntoIterator<Item = u32>,
5180) -> Result<(), String> {
5181 let mut previous = None;
5182 for id in ids {
5183 if previous.is_some_and(|previous| previous >= id) {
5184 return Err(format!(
5185 "component codegen {label} IDs must be unique and strictly increasing"
5186 ));
5187 }
5188 previous = Some(id);
5189 }
5190 Ok(())
5191}
5192
5193fn populate_legacy_client_graph(
5194 definition: TransportDefinitionId,
5195 descriptor: &mut ComponentDescriptor,
5196 graph: &LegacyClientGraph,
5197 inbound: &ValidatedInboundInputs,
5198 value_layout: &ComponentValueLayout,
5199 origin_layout: ComponentOriginLayout,
5200 direct_helper_edges: &[ValidatedComponentHelperEdge],
5201 shared_state_origins: &BTreeMap<u32, OriginId>,
5202 reachable_node_refs: &[u32],
5203 browser_operation_ordinal: &mut u32,
5204) -> Result<(), AbiAdapterError> {
5205 let callback_values = inbound_callback_values(definition, inbound, value_layout)?;
5206 let live_input_signals = inbound_source_signals(inbound);
5207 let helper_ids = direct_helper_edges
5208 .iter()
5209 .enumerate()
5210 .map(|(dense, helper)| {
5211 let dense = u32::try_from(dense).map_err(|_| {
5212 invalid(
5213 "component",
5214 definition,
5215 "reachable helper count exceeds the canonical u32 ID space",
5216 )
5217 })?;
5218 Ok((helper.local_ordinal, HelperCallEdgeId::new(dense)))
5219 })
5220 .collect::<Result<BTreeMap<_, _>, AbiAdapterError>>()?;
5221 let mut node_ref_effects = BTreeMap::new();
5222 let inbound_node_refs = inbound
5223 .node_refs
5224 .iter()
5225 .map(|node_ref| node_ref.node_ref)
5226 .collect::<BTreeSet<_>>();
5227 for (ordinal, node_ref) in reachable_node_refs.iter().copied().enumerate() {
5228 let ordinal = checked_ordinal(definition, ordinal, "reachable node reference")?;
5229 let origin = origin_layout.node_ref(definition, ordinal)?;
5230 let effect = next_effect_id(definition, descriptor)?;
5231 descriptor.origins.insert(
5232 origin,
5233 if inbound_node_refs.contains(&node_ref) {
5234 OriginKind::SourceOnly
5235 } else {
5236 OriginKind::NodeRef
5237 },
5238 );
5239 descriptor.effects.insert(effect, EffectKind::NodeReference);
5240 push_dependency(
5241 definition,
5242 descriptor,
5243 DependencyEdgeKind::Effect,
5244 DependencyEndpoint::Origin(origin),
5245 DependencyEndpoint::Effect(effect),
5246 origin,
5247 )?;
5248 node_ref_effects.insert(node_ref, effect);
5249 }
5250 let queries_by_id = graph
5251 .queries
5252 .iter()
5253 .map(|query| (query.id, query))
5254 .collect::<BTreeMap<_, _>>();
5255 let mut query_origins = BTreeMap::new();
5256 for (ordinal, query) in graph.reachable_queries.iter().copied().enumerate() {
5257 let ordinal = checked_ordinal(definition, ordinal, "reachable query")?;
5258 let origin = origin_layout.query(definition, ordinal)?;
5259 descriptor.origins.insert(origin, OriginKind::Query);
5260 query_origins.insert(query, origin);
5261 }
5262 let mutations_by_id = graph
5263 .mutations
5264 .iter()
5265 .map(|mutation| (mutation.id, mutation))
5266 .collect::<BTreeMap<_, _>>();
5267 let mut mutation_origins = BTreeMap::new();
5268 for (ordinal, mutation) in graph.reachable_mutations.iter().copied().enumerate() {
5269 let ordinal = checked_ordinal(definition, ordinal, "reachable mutation")?;
5270 let origin = origin_layout.mutation(definition, ordinal)?;
5271 descriptor.origins.insert(origin, OriginKind::Mutation);
5272 mutation_origins.insert(mutation, origin);
5273 }
5274 let reachable_expressions = graph
5275 .reachable_expressions
5276 .iter()
5277 .copied()
5278 .collect::<BTreeSet<_>>();
5279
5280 for (ordinal, signal) in graph.signals.iter().enumerate() {
5281 let ordinal = checked_ordinal(definition, ordinal, "legacy signal")?;
5282 let origin = origin_layout.signal(definition, ordinal)?;
5283 let value = value_layout.signal(definition, signal.id)?;
5284 descriptor.origins.insert(
5285 origin,
5286 if signal.shared_field.is_some()
5287 || signal.derived_expression.is_some()
5288 || live_input_signals.contains(&signal.id)
5289 {
5290 OriginKind::SourceOnly
5291 } else {
5292 OriginKind::WritableSignal
5293 },
5294 );
5295 push_dependency(
5296 definition,
5297 descriptor,
5298 DependencyEdgeKind::Data,
5299 DependencyEndpoint::Origin(origin),
5300 DependencyEndpoint::Value(value),
5301 origin,
5302 )?;
5303 if let Some(expression) = signal.derived_expression {
5304 push_dependency(
5305 definition,
5306 descriptor,
5307 DependencyEdgeKind::Data,
5308 DependencyEndpoint::Value(value_layout.expr(definition, expression)?),
5309 DependencyEndpoint::Value(value),
5310 origin,
5311 )?;
5312 }
5313 }
5314
5315 for (ordinal, expression) in graph.expressions.iter().enumerate() {
5316 let ordinal = checked_ordinal(definition, ordinal, "legacy expression")?;
5317 let origin = origin_layout.expr(definition, ordinal)?;
5318 let value = value_layout.expr(definition, expression.id)?;
5319 descriptor.origins.insert(origin, OriginKind::SourceOnly);
5320 push_dependency(
5321 definition,
5322 descriptor,
5323 DependencyEdgeKind::Data,
5324 DependencyEndpoint::Origin(origin),
5325 DependencyEndpoint::Value(value),
5326 origin,
5327 )?;
5328 push_legacy_external_dependencies(
5329 definition,
5330 descriptor,
5331 &expression.dependencies,
5332 value_layout,
5333 &callback_values,
5334 &helper_ids,
5335 DependencyEndpoint::Value(value),
5336 DependencyEdgeKind::Data,
5337 origin,
5338 )?;
5339 if reachable_expressions.contains(&expression.id) {
5340 populate_query_operations(
5341 definition,
5342 descriptor,
5343 &expression.client_operations,
5344 DependencyEndpoint::Value(value),
5345 &query_origins,
5346 &queries_by_id,
5347 value_layout,
5348 )?;
5349 populate_mutation_operations(
5350 definition,
5351 descriptor,
5352 &expression.client_operations,
5353 DependencyEndpoint::Value(value),
5354 &mutation_origins,
5355 &mutations_by_id,
5356 value_layout,
5357 )?;
5358 }
5359 populate_shared_state_operations(
5360 definition,
5361 descriptor,
5362 &expression.client_operations,
5363 DependencyEndpoint::Value(value),
5364 value_layout,
5365 &callback_values,
5366 &helper_ids,
5367 shared_state_origins,
5368 )?;
5369 populate_node_ref_operations(
5370 definition,
5371 descriptor,
5372 &expression.client_operations,
5373 DependencyEndpoint::Value(value),
5374 &node_ref_effects,
5375 origin,
5376 )?;
5377 populate_browser_operations(
5378 definition,
5379 descriptor,
5380 &expression.browser_operations,
5381 DependencyEndpoint::Value(value),
5382 value_layout,
5383 &callback_values,
5384 &helper_ids,
5385 origin_layout,
5386 browser_operation_ordinal,
5387 )?;
5388 }
5389
5390 let bound_handler_ids = graph
5391 .bindings
5392 .events
5393 .iter()
5394 .map(|binding| binding.handler)
5395 .collect::<BTreeSet<_>>();
5396 let mut bound_ordinal = 0_u32;
5397 for handler in &graph.handlers {
5398 if !bound_handler_ids.contains(&handler.id) {
5399 continue;
5400 }
5401 let origin = origin_layout.handler(definition, bound_ordinal)?;
5402 bound_ordinal = bound_ordinal.checked_add(1).ok_or_else(|| {
5403 invalid(
5404 "component",
5405 definition,
5406 "bound legacy handler origin allocation overflowed u32",
5407 )
5408 })?;
5409 let effect = next_effect_id(definition, descriptor)?;
5410 descriptor.origins.insert(origin, OriginKind::EventHandler);
5411 descriptor.effects.insert(effect, EffectKind::EventHandler);
5412 push_dependency(
5413 definition,
5414 descriptor,
5415 DependencyEdgeKind::Effect,
5416 DependencyEndpoint::Origin(origin),
5417 DependencyEndpoint::Effect(effect),
5418 origin,
5419 )?;
5420 push_legacy_external_dependencies(
5421 definition,
5422 descriptor,
5423 &handler.dependencies,
5424 value_layout,
5425 &callback_values,
5426 &helper_ids,
5427 DependencyEndpoint::Effect(effect),
5428 DependencyEdgeKind::Capture,
5429 origin,
5430 )?;
5431 populate_query_operations(
5432 definition,
5433 descriptor,
5434 &handler.client_operations,
5435 DependencyEndpoint::Effect(effect),
5436 &query_origins,
5437 &queries_by_id,
5438 value_layout,
5439 )?;
5440 populate_mutation_operations(
5441 definition,
5442 descriptor,
5443 &handler.client_operations,
5444 DependencyEndpoint::Effect(effect),
5445 &mutation_origins,
5446 &mutations_by_id,
5447 value_layout,
5448 )?;
5449 populate_shared_state_operations(
5450 definition,
5451 descriptor,
5452 &handler.client_operations,
5453 DependencyEndpoint::Effect(effect),
5454 value_layout,
5455 &callback_values,
5456 &helper_ids,
5457 shared_state_origins,
5458 )?;
5459 populate_node_ref_operations(
5460 definition,
5461 descriptor,
5462 &handler.client_operations,
5463 DependencyEndpoint::Effect(effect),
5464 &node_ref_effects,
5465 origin,
5466 )?;
5467 populate_browser_operations(
5468 definition,
5469 descriptor,
5470 &handler.browser_operations,
5471 DependencyEndpoint::Effect(effect),
5472 value_layout,
5473 &callback_values,
5474 &helper_ids,
5475 origin_layout,
5476 browser_operation_ordinal,
5477 )?;
5478 }
5479
5480 let mut binding_ordinal = 0_u32;
5481 for binding in &graph.bindings.text {
5482 populate_text_binding(
5483 definition,
5484 descriptor,
5485 binding,
5486 value_layout,
5487 origin_layout.binding(definition, binding_ordinal)?,
5488 )?;
5489 binding_ordinal = binding_ordinal.checked_add(1).ok_or_else(|| {
5490 invalid(
5491 "component",
5492 definition,
5493 "legacy DOM-binding origin allocation overflowed u32",
5494 )
5495 })?;
5496 }
5497 for binding in &graph.bindings.attributes {
5498 populate_attribute_binding(
5499 definition,
5500 descriptor,
5501 binding,
5502 value_layout,
5503 origin_layout.binding(definition, binding_ordinal)?,
5504 )?;
5505 binding_ordinal = binding_ordinal.checked_add(1).ok_or_else(|| {
5506 invalid(
5507 "component",
5508 definition,
5509 "legacy DOM-binding origin allocation overflowed u32",
5510 )
5511 })?;
5512 }
5513 for binding in &graph.bindings.inputs {
5514 populate_input_binding(
5515 definition,
5516 descriptor,
5517 binding,
5518 value_layout,
5519 origin_layout.binding(definition, binding_ordinal)?,
5520 )?;
5521 binding_ordinal = binding_ordinal.checked_add(1).ok_or_else(|| {
5522 invalid(
5523 "component",
5524 definition,
5525 "legacy DOM-binding origin allocation overflowed u32",
5526 )
5527 })?;
5528 }
5529 for binding in &graph.bindings.conditionals {
5530 populate_conditional_binding(
5531 definition,
5532 descriptor,
5533 binding,
5534 value_layout,
5535 origin_layout.binding(definition, binding_ordinal)?,
5536 )?;
5537 binding_ordinal = binding_ordinal.checked_add(1).ok_or_else(|| {
5538 invalid(
5539 "component",
5540 definition,
5541 "legacy DOM-binding origin allocation overflowed u32",
5542 )
5543 })?;
5544 }
5545 for collection in &graph.keyed_collections {
5546 populate_keyed_collection(
5547 definition,
5548 descriptor,
5549 collection,
5550 value_layout,
5551 origin_layout.binding(definition, binding_ordinal)?,
5552 )?;
5553 binding_ordinal = binding_ordinal.checked_add(1).ok_or_else(|| {
5554 invalid(
5555 "component",
5556 definition,
5557 "keyed-collection binding origin allocation overflowed u32",
5558 )
5559 })?;
5560 }
5561 debug_assert_eq!(binding_ordinal, origin_layout.binding_count);
5562 Ok(())
5563}
5564
5565#[allow(clippy::too_many_arguments)]
5566fn populate_shared_state_operations(
5567 definition: TransportDefinitionId,
5568 descriptor: &mut ComponentDescriptor,
5569 operations: &[LegacyClientOperation],
5570 enclosing: DependencyEndpoint,
5571 value_layout: &ComponentValueLayout,
5572 callback_values: &BTreeMap<u32, LocalValueId>,
5573 helper_ids: &BTreeMap<u32, HelperCallEdgeId>,
5574 shared_state_origins: &BTreeMap<u32, OriginId>,
5575) -> Result<(), AbiAdapterError> {
5576 let mut operation_effects = BTreeMap::new();
5577 for (index, operation) in operations.iter().enumerate() {
5578 let (signal, effect_kind, read) = match &operation.kind {
5579 LegacyClientOperationKind::SharedRead { signal, .. } => {
5580 (*signal, EffectKind::SharedStateRead, true)
5581 }
5582 LegacyClientOperationKind::SharedSet { signal, .. }
5583 | LegacyClientOperationKind::SharedUpdate { signal, .. } => {
5584 (*signal, EffectKind::SharedStateWrite, false)
5585 }
5586 _ => continue,
5587 };
5588 let Some(&origin) = shared_state_origins.get(&signal) else {
5589 return Err(invalid(
5590 "component",
5591 definition,
5592 format!(
5593 "SharedState operation for signal {signal} has no active relocation-resolved acquisition"
5594 ),
5595 ));
5596 };
5597 let effect = next_effect_id(definition, descriptor)?;
5598 descriptor.effects.insert(effect, effect_kind);
5599 push_dependency(
5600 definition,
5601 descriptor,
5602 DependencyEdgeKind::Effect,
5603 DependencyEndpoint::Origin(origin),
5604 DependencyEndpoint::Effect(effect),
5605 origin,
5606 )?;
5607
5608 for dependency in &operation.dependencies.signal_reads {
5609 push_dependency(
5610 definition,
5611 descriptor,
5612 DependencyEdgeKind::Capture,
5613 DependencyEndpoint::Value(value_layout.signal(definition, dependency.0)?),
5614 DependencyEndpoint::Effect(effect),
5615 origin,
5616 )?;
5617 }
5618 for dependency in &operation.dependencies.signal_writes {
5619 if dependency.0 != signal {
5620 push_dependency(
5621 definition,
5622 descriptor,
5623 DependencyEdgeKind::Effect,
5624 DependencyEndpoint::Effect(effect),
5625 DependencyEndpoint::Value(value_layout.signal(definition, dependency.0)?),
5626 origin,
5627 )?;
5628 }
5629 }
5630 for callback in &operation.dependencies.callback_slots {
5631 let Some(&value) = callback_values.get(&callback.0) else {
5632 return Err(invalid(
5633 "component",
5634 definition,
5635 format!(
5636 "SharedState operation lost inbound callback slot {} during canonical allocation",
5637 callback.0,
5638 ),
5639 ));
5640 };
5641 push_dependency(
5642 definition,
5643 descriptor,
5644 DependencyEdgeKind::Capture,
5645 DependencyEndpoint::Value(value),
5646 DependencyEndpoint::Effect(effect),
5647 origin,
5648 )?;
5649 }
5650 for helper in &operation.dependencies.helper_edges {
5651 let Some(&helper_id) = helper_ids.get(&helper.index()) else {
5652 return Err(invalid(
5653 "component",
5654 definition,
5655 format!(
5656 "SharedState operation lost relocation-resolved helper edge {} during canonical allocation",
5657 helper.index(),
5658 ),
5659 ));
5660 };
5661 push_dependency(
5662 definition,
5663 descriptor,
5664 DependencyEdgeKind::HelperCall,
5665 DependencyEndpoint::Helper(helper_id),
5666 DependencyEndpoint::Effect(effect),
5667 origin,
5668 )?;
5669 }
5670
5671 let consumer = match operation.consumer {
5672 LegacyClientOperationConsumer::Enclosing => enclosing,
5673 LegacyClientOperationConsumer::Operation(parent) => {
5674 let parent = usize::try_from(parent).map_err(|_| {
5675 invalid(
5676 "component",
5677 definition,
5678 "SharedState operation parent exceeds the host index space",
5679 )
5680 })?;
5681 operation_effects.get(&parent).copied().map_or_else(
5682 || {
5683 Err(invalid(
5684 "component",
5685 definition,
5686 format!(
5687 "SharedState operation {index} depends on operation {parent}, which has no canonical SharedState effect"
5688 ),
5689 ))
5690 },
5691 |effect| Ok(DependencyEndpoint::Effect(effect)),
5692 )?
5693 }
5694 };
5695 if read {
5696 push_dependency(
5697 definition,
5698 descriptor,
5699 DependencyEdgeKind::Data,
5700 DependencyEndpoint::Effect(effect),
5701 consumer,
5702 origin,
5703 )?;
5704 } else {
5705 push_dependency(
5706 definition,
5707 descriptor,
5708 DependencyEdgeKind::Effect,
5709 consumer,
5710 DependencyEndpoint::Effect(effect),
5711 origin,
5712 )?;
5713 push_dependency(
5714 definition,
5715 descriptor,
5716 DependencyEdgeKind::Effect,
5717 DependencyEndpoint::Effect(effect),
5718 DependencyEndpoint::Value(value_layout.signal(definition, signal)?),
5719 origin,
5720 )?;
5721 }
5722 operation_effects.insert(index, effect);
5723 }
5724 Ok(())
5725}
5726
5727fn populate_query_operations(
5728 definition: TransportDefinitionId,
5729 descriptor: &mut ComponentDescriptor,
5730 operations: &[crate::rsjs::legacy_graph::LegacyClientOperation],
5731 enclosing: DependencyEndpoint,
5732 query_origins: &BTreeMap<u32, OriginId>,
5733 queries: &BTreeMap<u32, &LegacyQuery>,
5734 value_layout: &ComponentValueLayout,
5735) -> Result<(), AbiAdapterError> {
5736 for operation in operations {
5737 let (query, effect_kind, read) = match operation.kind {
5738 LegacyClientOperationKind::QueryRead { query, .. } => {
5739 (query, EffectKind::QueryObservation, true)
5740 }
5741 LegacyClientOperationKind::QueryRefetch { query } => {
5742 (query, EffectKind::QueryRefetch, false)
5743 }
5744 LegacyClientOperationKind::QueryInvalidate { query } => {
5745 (query, EffectKind::QueryInvalidation, false)
5746 }
5747 _ => continue,
5748 };
5749 if !matches!(operation.consumer, LegacyClientOperationConsumer::Enclosing) {
5750 return Err(invalid(
5751 "component",
5752 definition,
5753 "nested query operation escaped the fail-closed legacy graph gate",
5754 ));
5755 }
5756 let Some(&origin) = query_origins.get(&query) else {
5757 continue;
5761 };
5762 let Some(query_declaration) = queries.get(&query).copied() else {
5763 return Err(invalid(
5764 "component",
5765 definition,
5766 format!("reachable query operation refers to missing query {query}"),
5767 ));
5768 };
5769 let effect = next_effect_id(definition, descriptor)?;
5770 descriptor.effects.insert(effect, effect_kind);
5771 push_dependency(
5772 definition,
5773 descriptor,
5774 DependencyEdgeKind::Effect,
5775 DependencyEndpoint::Origin(origin),
5776 DependencyEndpoint::Effect(effect),
5777 origin,
5778 )?;
5779
5780 let input_expressions: &[u32] = match effect_kind {
5781 EffectKind::QueryObservation => &[
5782 query_declaration.key_expression,
5783 query_declaration.server_initial_expression,
5784 query_declaration.client_fetcher_expression,
5785 ],
5786 EffectKind::QueryRefetch => &[
5787 query_declaration.key_expression,
5788 query_declaration.client_fetcher_expression,
5789 ],
5790 EffectKind::QueryInvalidation => &[query_declaration.key_expression],
5791 _ => unreachable!("query operation selected a non-query effect kind"),
5792 };
5793 let mut captured = BTreeSet::new();
5794 for expression in input_expressions {
5795 if captured.insert(*expression) {
5796 push_dependency(
5797 definition,
5798 descriptor,
5799 DependencyEdgeKind::Capture,
5800 DependencyEndpoint::Value(value_layout.expr(definition, *expression)?),
5801 DependencyEndpoint::Effect(effect),
5802 origin,
5803 )?;
5804 }
5805 }
5806
5807 let (kind, from, to) = if read {
5808 (
5809 DependencyEdgeKind::Data,
5810 DependencyEndpoint::Effect(effect),
5811 enclosing,
5812 )
5813 } else {
5814 (
5815 DependencyEdgeKind::Effect,
5816 enclosing,
5817 DependencyEndpoint::Effect(effect),
5818 )
5819 };
5820 push_dependency(definition, descriptor, kind, from, to, origin)?;
5821 }
5822 Ok(())
5823}
5824
5825fn populate_mutation_operations(
5826 definition: TransportDefinitionId,
5827 descriptor: &mut ComponentDescriptor,
5828 operations: &[LegacyClientOperation],
5829 enclosing: DependencyEndpoint,
5830 mutation_origins: &BTreeMap<u32, OriginId>,
5831 mutations: &BTreeMap<u32, &LegacyMutation>,
5832 value_layout: &ComponentValueLayout,
5833) -> Result<(), AbiAdapterError> {
5834 for operation in operations {
5835 let (mutation, read) = match operation.kind {
5836 LegacyClientOperationKind::MutationRead { mutation, .. } => (mutation, true),
5837 LegacyClientOperationKind::MutationRun { mutation } => (mutation, false),
5838 _ => continue,
5839 };
5840 if !matches!(operation.consumer, LegacyClientOperationConsumer::Enclosing) {
5841 return Err(invalid(
5842 "component",
5843 definition,
5844 "nested mutation operation escaped the fail-closed legacy graph gate",
5845 ));
5846 }
5847 let Some(&origin) = mutation_origins.get(&mutation) else {
5848 continue;
5852 };
5853 let Some(mutation_declaration) = mutations.get(&mutation).copied() else {
5854 return Err(invalid(
5855 "component",
5856 definition,
5857 format!("reachable mutation operation refers to missing mutation {mutation}"),
5858 ));
5859 };
5860 let effect = next_effect_id(definition, descriptor)?;
5861 descriptor.effects.insert(effect, EffectKind::Mutation);
5862 push_dependency(
5863 definition,
5864 descriptor,
5865 DependencyEdgeKind::Effect,
5866 DependencyEndpoint::Origin(origin),
5867 DependencyEndpoint::Effect(effect),
5868 origin,
5869 )?;
5870
5871 let mut captured = BTreeSet::new();
5875 for expression in [
5876 mutation_declaration.key_expression,
5877 mutation_declaration.client_runner_expression,
5878 ]
5879 .into_iter()
5880 .chain(mutation_declaration.invalidates.iter().copied())
5881 {
5882 if captured.insert(expression) {
5883 push_dependency(
5884 definition,
5885 descriptor,
5886 DependencyEdgeKind::Capture,
5887 DependencyEndpoint::Value(value_layout.expr(definition, expression)?),
5888 DependencyEndpoint::Effect(effect),
5889 origin,
5890 )?;
5891 }
5892 }
5893
5894 let (kind, from, to) = if read {
5895 (
5896 DependencyEdgeKind::Data,
5897 DependencyEndpoint::Effect(effect),
5898 enclosing,
5899 )
5900 } else {
5901 (
5902 DependencyEdgeKind::Effect,
5903 enclosing,
5904 DependencyEndpoint::Effect(effect),
5905 )
5906 };
5907 push_dependency(definition, descriptor, kind, from, to, origin)?;
5908 }
5909 Ok(())
5910}
5911
5912fn populate_node_ref_operations(
5913 definition: TransportDefinitionId,
5914 descriptor: &mut ComponentDescriptor,
5915 operations: &[crate::rsjs::legacy_graph::LegacyClientOperation],
5916 enclosing: DependencyEndpoint,
5917 node_ref_effects: &BTreeMap<u32, LocalEffectId>,
5918 origin: OriginId,
5919) -> Result<(), AbiAdapterError> {
5920 for operation in operations {
5921 let (node_ref, read) = match &operation.kind {
5922 LegacyClientOperationKind::NodeRefRead { node_ref } => (*node_ref, true),
5923 LegacyClientOperationKind::NodeRefWrite { node_ref } => (*node_ref, false),
5924 _ => continue,
5925 };
5926 if !matches!(operation.consumer, LegacyClientOperationConsumer::Enclosing) {
5927 return Err(invalid(
5928 "component",
5929 definition,
5930 "nested node-reference operation escaped the fail-closed legacy graph gate",
5931 ));
5932 }
5933 let Some(&effect) = node_ref_effects.get(&node_ref) else {
5934 continue;
5938 };
5939 let (kind, from, to) = if read {
5940 (
5941 DependencyEdgeKind::Data,
5942 DependencyEndpoint::Effect(effect),
5943 enclosing,
5944 )
5945 } else {
5946 (
5947 DependencyEdgeKind::Effect,
5948 enclosing,
5949 DependencyEndpoint::Effect(effect),
5950 )
5951 };
5952 push_dependency(definition, descriptor, kind, from, to, origin)?;
5953 }
5954 Ok(())
5955}
5956
5957#[allow(clippy::too_many_arguments)]
5958fn populate_browser_operations(
5959 definition: TransportDefinitionId,
5960 descriptor: &mut ComponentDescriptor,
5961 operations: &[LegacyBrowserOperation],
5962 enclosing: DependencyEndpoint,
5963 value_layout: &ComponentValueLayout,
5964 callback_values: &BTreeMap<u32, LocalValueId>,
5965 helper_ids: &BTreeMap<u32, HelperCallEdgeId>,
5966 origin_layout: ComponentOriginLayout,
5967 global_ordinal: &mut u32,
5968) -> Result<(), AbiAdapterError> {
5969 let mut operation_effects = Vec::with_capacity(operations.len());
5970 for (local_ordinal, operation) in operations.iter().enumerate() {
5971 let local_ordinal = checked_ordinal(definition, local_ordinal, "browser operation")?;
5972 let origin = origin_layout.browser_operation(definition, *global_ordinal)?;
5973 *global_ordinal = global_ordinal.checked_add(1).ok_or_else(|| {
5974 invalid(
5975 "component",
5976 definition,
5977 "browser-operation origin allocation overflowed u32",
5978 )
5979 })?;
5980 let effect = next_effect_id(definition, descriptor)?;
5981 let (origin_kind, effect_kind) = match operation.kind {
5982 LegacyBrowserOperationKind::Read => {
5983 (OriginKind::BrowserCapabilityRead, EffectKind::BrowserRead)
5984 }
5985 LegacyBrowserOperationKind::Write => {
5986 (OriginKind::BrowserCapabilityWrite, EffectKind::BrowserWrite)
5987 }
5988 };
5989 descriptor.origins.insert(origin, origin_kind);
5990 descriptor.effects.insert(effect, effect_kind);
5991 push_dependency(
5992 definition,
5993 descriptor,
5994 DependencyEdgeKind::Effect,
5995 DependencyEndpoint::Origin(origin),
5996 DependencyEndpoint::Effect(effect),
5997 origin,
5998 )?;
5999 push_browser_operation_dependencies(
6000 definition,
6001 descriptor,
6002 &operation.dependencies,
6003 effect,
6004 value_layout,
6005 callback_values,
6006 helper_ids,
6007 origin,
6008 )?;
6009
6010 let consumer = match operation.consumer {
6011 LegacyBrowserConsumer::Enclosing => enclosing,
6012 LegacyBrowserConsumer::Operation(parent) => {
6013 if parent >= local_ordinal {
6014 return Err(invalid(
6015 "component",
6016 definition,
6017 format!(
6018 "browser operation {local_ordinal} references non-enclosing operation {parent}"
6019 ),
6020 ));
6021 }
6022 let parent = usize::try_from(parent).map_err(|_| {
6023 invalid(
6024 "component",
6025 definition,
6026 format!("browser operation parent {parent} exceeds usize"),
6027 )
6028 })?;
6029 DependencyEndpoint::Effect(operation_effects[parent])
6030 }
6031 };
6032 let (kind, from, to) = match operation.kind {
6033 LegacyBrowserOperationKind::Read => (
6034 DependencyEdgeKind::Data,
6035 DependencyEndpoint::Effect(effect),
6036 consumer,
6037 ),
6038 LegacyBrowserOperationKind::Write => (
6039 DependencyEdgeKind::Effect,
6040 consumer,
6041 DependencyEndpoint::Effect(effect),
6042 ),
6043 };
6044 push_dependency(definition, descriptor, kind, from, to, origin)?;
6045 operation_effects.push(effect);
6046 }
6047 Ok(())
6048}
6049
6050#[allow(clippy::too_many_arguments)]
6051fn push_browser_operation_dependencies(
6052 definition: TransportDefinitionId,
6053 descriptor: &mut ComponentDescriptor,
6054 dependencies: &ClientBlockExternalDependencies,
6055 effect: LocalEffectId,
6056 value_layout: &ComponentValueLayout,
6057 callback_values: &BTreeMap<u32, LocalValueId>,
6058 helper_ids: &BTreeMap<u32, HelperCallEdgeId>,
6059 origin: OriginId,
6060) -> Result<(), AbiAdapterError> {
6061 for signal in &dependencies.signal_reads {
6062 push_dependency(
6063 definition,
6064 descriptor,
6065 DependencyEdgeKind::Capture,
6066 DependencyEndpoint::Value(value_layout.signal(definition, signal.0)?),
6067 DependencyEndpoint::Effect(effect),
6068 origin,
6069 )?;
6070 }
6071 for signal in &dependencies.signal_writes {
6072 push_dependency(
6073 definition,
6074 descriptor,
6075 DependencyEdgeKind::Effect,
6076 DependencyEndpoint::Effect(effect),
6077 DependencyEndpoint::Value(value_layout.signal(definition, signal.0)?),
6078 origin,
6079 )?;
6080 }
6081 for callback in &dependencies.callback_slots {
6082 let Some(&value) = callback_values.get(&callback.0) else {
6083 return Err(invalid(
6084 "component",
6085 definition,
6086 format!(
6087 "browser operation references callback slot {}, but no inbound callback value was allocated",
6088 callback.0
6089 ),
6090 ));
6091 };
6092 push_dependency(
6093 definition,
6094 descriptor,
6095 DependencyEdgeKind::Capture,
6096 DependencyEndpoint::Value(value),
6097 DependencyEndpoint::Effect(effect),
6098 origin,
6099 )?;
6100 }
6101 for helper in &dependencies.helper_edges {
6102 let Some(&helper_id) = helper_ids.get(&helper.index()) else {
6103 return Err(invalid(
6104 "component",
6105 definition,
6106 format!(
6107 "browser operation lost relocation-resolved helper edge {} during canonical allocation",
6108 helper.index()
6109 ),
6110 ));
6111 };
6112 push_dependency(
6113 definition,
6114 descriptor,
6115 DependencyEdgeKind::HelperCall,
6116 DependencyEndpoint::Helper(helper_id),
6117 DependencyEndpoint::Effect(effect),
6118 origin,
6119 )?;
6120 }
6121 Ok(())
6122}
6123
6124#[allow(clippy::too_many_arguments)]
6125fn push_legacy_external_dependencies(
6126 definition: TransportDefinitionId,
6127 descriptor: &mut ComponentDescriptor,
6128 dependencies: &ClientBlockExternalDependencies,
6129 value_layout: &ComponentValueLayout,
6130 callback_values: &BTreeMap<u32, LocalValueId>,
6131 helper_ids: &BTreeMap<u32, HelperCallEdgeId>,
6132 target: DependencyEndpoint,
6133 value_edge_kind: DependencyEdgeKind,
6134 origin: OriginId,
6135) -> Result<(), AbiAdapterError> {
6136 let mut signals = BTreeSet::new();
6137 for signal in dependencies
6138 .signal_reads
6139 .iter()
6140 .chain(&dependencies.signal_writes)
6141 {
6142 if signals.insert(signal.0) {
6143 push_dependency(
6144 definition,
6145 descriptor,
6146 value_edge_kind,
6147 DependencyEndpoint::Value(value_layout.signal(definition, signal.0)?),
6148 target,
6149 origin,
6150 )?;
6151 }
6152 }
6153 for callback in &dependencies.callback_slots {
6154 let Some(&value) = callback_values.get(&callback.0) else {
6155 return Err(invalid(
6156 "component",
6157 definition,
6158 format!(
6159 "legacy Client IR references callback slot {}, but no inbound callback value was allocated",
6160 callback.0
6161 ),
6162 ));
6163 };
6164 push_dependency(
6165 definition,
6166 descriptor,
6167 value_edge_kind,
6168 DependencyEndpoint::Value(value),
6169 target,
6170 origin,
6171 )?;
6172 }
6173 for helper in &dependencies.helper_edges {
6174 let Some(&helper_id) = helper_ids.get(&helper.index()) else {
6175 return Err(invalid(
6176 "component",
6177 definition,
6178 format!(
6179 "legacy Client IR lost relocation-resolved helper edge {} during canonical allocation",
6180 helper.index()
6181 ),
6182 ));
6183 };
6184 push_dependency(
6185 definition,
6186 descriptor,
6187 DependencyEdgeKind::HelperCall,
6188 DependencyEndpoint::Helper(helper_id),
6189 target,
6190 origin,
6191 )?;
6192 }
6193 Ok(())
6194}
6195
6196fn populate_text_binding(
6197 definition: TransportDefinitionId,
6198 descriptor: &mut ComponentDescriptor,
6199 binding: &LegacyTextBinding,
6200 value_layout: &ComponentValueLayout,
6201 origin: OriginId,
6202) -> Result<(), AbiAdapterError> {
6203 populate_dom_binding_effect(
6204 definition,
6205 descriptor,
6206 EffectKind::DomTextUpdate,
6207 value_layout.expr(definition, binding.expression)?,
6208 origin,
6209 )
6210}
6211
6212fn populate_attribute_binding(
6213 definition: TransportDefinitionId,
6214 descriptor: &mut ComponentDescriptor,
6215 binding: &LegacyAttributeBinding,
6216 value_layout: &ComponentValueLayout,
6217 origin: OriginId,
6218) -> Result<(), AbiAdapterError> {
6219 populate_dom_binding_effect(
6220 definition,
6221 descriptor,
6222 EffectKind::DomAttributeUpdate,
6223 value_layout.expr(definition, binding.expression)?,
6224 origin,
6225 )
6226}
6227
6228fn populate_input_binding(
6229 definition: TransportDefinitionId,
6230 descriptor: &mut ComponentDescriptor,
6231 binding: &LegacyInputBinding,
6232 value_layout: &ComponentValueLayout,
6233 origin: OriginId,
6234) -> Result<(), AbiAdapterError> {
6235 populate_dom_binding_effect(
6236 definition,
6237 descriptor,
6238 EffectKind::DomPropertyUpdate,
6239 value_layout.signal(definition, binding.signal)?,
6240 origin,
6241 )
6242}
6243
6244fn populate_keyed_collection(
6245 definition: TransportDefinitionId,
6246 descriptor: &mut ComponentDescriptor,
6247 collection: &LegacyKeyedCollection,
6248 value_layout: &ComponentValueLayout,
6249 origin: OriginId,
6250) -> Result<(), AbiAdapterError> {
6251 let site = KeyedCollectionSiteId::new(collection.id);
6252 if !descriptor.keyed_collection_sites.insert(site) {
6253 return Err(invalid(
6254 "component",
6255 definition,
6256 format!(
6257 "keyed collection site {} is declared more than once",
6258 collection.id
6259 ),
6260 ));
6261 }
6262 let source = match collection.source {
6263 LegacyKeyedCollectionSource::Signal(signal) => value_layout.signal(definition, signal)?,
6264 LegacyKeyedCollectionSource::Expression(expression) => {
6265 value_layout.expr(definition, expression)?
6266 }
6267 };
6268 populate_dom_binding_effect(
6269 definition,
6270 descriptor,
6271 EffectKind::DomStructuralUpdate,
6272 source,
6273 origin,
6274 )
6275}
6276
6277fn populate_conditional_binding(
6278 definition: TransportDefinitionId,
6279 descriptor: &mut ComponentDescriptor,
6280 binding: &LegacyConditionalBinding,
6281 value_layout: &ComponentValueLayout,
6282 origin: OriginId,
6283) -> Result<(), AbiAdapterError> {
6284 let control = LocalControlRegionId::new(binding.control);
6285 if !descriptor.control_regions.insert(control) {
6286 return Err(invalid(
6287 "component",
6288 definition,
6289 format!(
6290 "conditional control {} is declared more than once",
6291 binding.control
6292 ),
6293 ));
6294 }
6295 let effect = next_effect_id(definition, descriptor)?;
6296 descriptor.origins.insert(origin, OriginKind::SourceOnly);
6297 descriptor
6298 .effects
6299 .insert(effect, EffectKind::DomStructuralUpdate);
6300 push_dependency(
6301 definition,
6302 descriptor,
6303 DependencyEdgeKind::Effect,
6304 DependencyEndpoint::Origin(origin),
6305 DependencyEndpoint::Effect(effect),
6306 origin,
6307 )?;
6308 push_dependency(
6309 definition,
6310 descriptor,
6311 DependencyEdgeKind::Control,
6312 DependencyEndpoint::Value(value_layout.expr(definition, binding.condition)?),
6313 DependencyEndpoint::Control(control),
6314 origin,
6315 )?;
6316 push_dependency(
6317 definition,
6318 descriptor,
6319 DependencyEdgeKind::Control,
6320 DependencyEndpoint::Control(control),
6321 DependencyEndpoint::Effect(effect),
6322 origin,
6323 )
6324}
6325
6326fn populate_dom_binding_effect(
6327 definition: TransportDefinitionId,
6328 descriptor: &mut ComponentDescriptor,
6329 kind: EffectKind,
6330 value: LocalValueId,
6331 origin: OriginId,
6332) -> Result<(), AbiAdapterError> {
6333 let effect = next_effect_id(definition, descriptor)?;
6334 descriptor.origins.insert(origin, OriginKind::SourceOnly);
6335 descriptor.effects.insert(effect, kind);
6336 push_dependency(
6337 definition,
6338 descriptor,
6339 DependencyEdgeKind::Effect,
6340 DependencyEndpoint::Origin(origin),
6341 DependencyEndpoint::Effect(effect),
6342 origin,
6343 )?;
6344 push_dependency(
6345 definition,
6346 descriptor,
6347 DependencyEdgeKind::Data,
6348 DependencyEndpoint::Value(value),
6349 DependencyEndpoint::Effect(effect),
6350 origin,
6351 )
6352}
6353
6354fn checked_ordinal(
6355 definition: TransportDefinitionId,
6356 ordinal: usize,
6357 label: &'static str,
6358) -> Result<u32, AbiAdapterError> {
6359 u32::try_from(ordinal).map_err(|_| {
6360 invalid(
6361 "component",
6362 definition,
6363 format!("{label} count exceeds the canonical u32 ID space"),
6364 )
6365 })
6366}
6367
6368fn next_effect_id(
6369 definition: TransportDefinitionId,
6370 descriptor: &ComponentDescriptor,
6371) -> Result<LocalEffectId, AbiAdapterError> {
6372 u32::try_from(descriptor.effects.len())
6373 .map(LocalEffectId::new)
6374 .map_err(|_| {
6375 invalid(
6376 "component",
6377 definition,
6378 "canonical effect count exceeds the u32 ID space",
6379 )
6380 })
6381}
6382
6383fn push_dependency(
6384 definition: TransportDefinitionId,
6385 descriptor: &mut ComponentDescriptor,
6386 kind: DependencyEdgeKind,
6387 from: DependencyEndpoint,
6388 to: DependencyEndpoint,
6389 origin: OriginId,
6390) -> Result<(), AbiAdapterError> {
6391 let id = u32::try_from(descriptor.dependencies.len()).map_err(|_| {
6392 invalid(
6393 "component",
6394 definition,
6395 "canonical dependency count exceeds the u32 ID space",
6396 )
6397 })?;
6398 descriptor.dependencies.insert(
6399 DependencyEdgeId::new(id),
6400 DependencyEdge::new(kind, from, to, origin),
6401 );
6402 Ok(())
6403}
6404
6405fn canonical_component_lifecycle_control(
6406 definition: TransportDefinitionId,
6407 descriptor: &ComponentDescriptor,
6408 control: u32,
6409 expected_predicate: LocalValueId,
6410 branch: ComponentLifecycleBranch,
6411) -> Result<ComponentLifecycleControl, AbiAdapterError> {
6412 let control = LocalControlRegionId::new(control);
6418 let predicate_dependencies = descriptor
6419 .dependencies
6420 .values()
6421 .filter(|dependency| dependency.to == DependencyEndpoint::Control(control))
6422 .collect::<Vec<_>>();
6423 let [dependency] = predicate_dependencies.as_slice() else {
6424 return Err(invalid(
6425 "component",
6426 definition,
6427 format!(
6428 "conditional component lifecycle control {} must have exactly one canonical \
6429 predicate dependency, found {}",
6430 control.index(),
6431 predicate_dependencies.len(),
6432 ),
6433 ));
6434 };
6435 let DependencyEdge {
6436 kind: DependencyEdgeKind::Control,
6437 from: DependencyEndpoint::Value(predicate),
6438 origin: predicate_origin,
6439 ..
6440 } = **dependency
6441 else {
6442 return Err(invalid(
6443 "component",
6444 definition,
6445 format!(
6446 "conditional component lifecycle control {} is not driven by a canonical \
6447 Value -> Control dependency",
6448 control.index(),
6449 ),
6450 ));
6451 };
6452 if predicate != expected_predicate {
6453 return Err(invalid(
6454 "component",
6455 definition,
6456 format!(
6457 "conditional component lifecycle control {} resolves predicate value {}, but \
6458 its relocation-authenticated expression maps to value {}",
6459 control.index(),
6460 predicate.index(),
6461 expected_predicate.index(),
6462 ),
6463 ));
6464 }
6465 Ok(ComponentLifecycleControl {
6466 control,
6467 predicate,
6468 predicate_origin,
6469 branch,
6470 })
6471}
6472
6473fn adapt_direct_component_bindings(
6474 definition: TransportDefinitionId,
6475 fields: &[ValidatedDirectComponentField],
6476 value_layout: &ComponentValueLayout,
6477 callback_values: &BTreeMap<u32, LocalValueId>,
6478 origin: OriginId,
6479) -> Result<BTreeMap<String, ComponentFieldBinding>, AbiAdapterError> {
6480 let mut bindings = BTreeMap::new();
6481 for field in fields {
6482 let source = match field.binding {
6483 ValidatedDirectComponentBinding::ServerOnly => ComponentBindingSource::ServerOnly,
6484 ValidatedDirectComponentBinding::StaticSlotExactOne => {
6485 ComponentBindingSource::StaticSlot {
6486 span: SpanCardinality::Exact(1),
6487 }
6488 }
6489 ValidatedDirectComponentBinding::StaticCallback { shape, .. } => {
6490 ComponentBindingSource::StaticCallback { shape }
6491 }
6492 ValidatedDirectComponentBinding::LiveValue { signal, .. } => {
6493 ComponentBindingSource::LiveValue {
6494 value: value_layout.signal(definition, signal)?,
6495 }
6496 }
6497 ValidatedDirectComponentBinding::LiveCallback {
6498 handler_prelude_local,
6499 shape,
6500 ..
6501 } => {
6502 let Some(&value) = callback_values.get(&handler_prelude_local) else {
6503 return Err(invalid(
6504 "component",
6505 definition,
6506 format!(
6507 "live callback field `{}` references missing payload-handler prelude binding {handler_prelude_local}",
6508 field.name
6509 ),
6510 ));
6511 };
6512 ComponentBindingSource::LiveCallback { value, shape }
6513 }
6514 ValidatedDirectComponentBinding::ForwardedCallback {
6515 parent_field,
6516 shape,
6517 } => ComponentBindingSource::LiveCallback {
6518 value: value_layout.inbound(definition, u64::from(parent_field))?,
6519 shape,
6520 },
6521 ValidatedDirectComponentBinding::NodeRefHandle { node_ref } => {
6522 ComponentBindingSource::ClientHandle {
6523 value: value_layout.node_ref(definition, node_ref)?,
6524 }
6525 }
6526 ValidatedDirectComponentBinding::Unsupported => {
6527 return Err(invalid(
6528 "component",
6529 definition,
6530 format!(
6531 "unproven direct component field `{}` reached canonical adaptation",
6532 field.name
6533 ),
6534 ));
6535 }
6536 };
6537 if bindings
6538 .insert(field.name.clone(), ComponentFieldBinding { source, origin })
6539 .is_some()
6540 {
6541 return Err(invalid(
6542 "component",
6543 definition,
6544 format!(
6545 "direct component bindings contain duplicate field `{}`",
6546 field.name
6547 ),
6548 ));
6549 }
6550 }
6551 Ok(bindings)
6552}
6553
6554#[derive(Clone, Copy, Debug, PartialEq, Eq)]
6560struct ComponentWitnessLayout {
6561 component_start: u64,
6562 component_count: u32,
6563 field_start: u64,
6564 field_count: u32,
6565 helper_start: u64,
6566 helper_count: u32,
6567}
6568
6569impl ComponentWitnessLayout {
6570 fn new(
6571 definition: TransportDefinitionId,
6572 component_count: usize,
6573 field_count: usize,
6574 helper_count: usize,
6575 ) -> Result<Self, AbiAdapterError> {
6576 let component_count = u64::try_from(component_count).map_err(|_| {
6577 invalid(
6578 "component",
6579 definition,
6580 "component edge count exceeds the canonical u64 count space",
6581 )
6582 })?;
6583 let field_count = u64::try_from(field_count).map_err(|_| {
6584 invalid(
6585 "component",
6586 definition,
6587 "component field count exceeds the canonical u64 count space",
6588 )
6589 })?;
6590 let helper_count = u64::try_from(helper_count).map_err(|_| {
6591 invalid(
6592 "component",
6593 definition,
6594 "reachable helper edge count exceeds the canonical u64 count space",
6595 )
6596 })?;
6597 Self::from_counts(definition, component_count, field_count, helper_count)
6598 }
6599
6600 fn from_counts(
6601 definition: TransportDefinitionId,
6602 component_count: u64,
6603 field_count: u64,
6604 helper_count: u64,
6605 ) -> Result<Self, AbiAdapterError> {
6606 let component_count = u32::try_from(component_count).map_err(|_| {
6607 invalid(
6608 "component",
6609 definition,
6610 "component edge count exceeds the canonical u32 witness space",
6611 )
6612 })?;
6613 let field_count = u32::try_from(field_count).map_err(|_| {
6614 invalid(
6615 "component",
6616 definition,
6617 "component field count exceeds the canonical u32 witness space",
6618 )
6619 })?;
6620 let helper_count = u32::try_from(helper_count).map_err(|_| {
6621 invalid(
6622 "component",
6623 definition,
6624 "reachable helper edge count exceeds the canonical u32 witness space",
6625 )
6626 })?;
6627
6628 let component_start = 1_u64;
6629 let field_start = component_start
6630 .checked_add(u64::from(component_count))
6631 .ok_or_else(|| {
6632 invalid(
6633 "component",
6634 definition,
6635 "component edge witnesses exhaust the canonical u64 allocation space",
6636 )
6637 })?;
6638 let helper_start = field_start
6639 .checked_add(u64::from(field_count))
6640 .ok_or_else(|| {
6641 invalid(
6642 "component",
6643 definition,
6644 "component field witnesses exhaust the canonical u64 allocation space",
6645 )
6646 })?;
6647 let allocation_end = helper_start
6648 .checked_add(u64::from(helper_count))
6649 .ok_or_else(|| {
6650 invalid(
6651 "component",
6652 definition,
6653 "reachable helper witnesses exhaust the canonical u64 allocation space",
6654 )
6655 })?;
6656 if allocation_end > u64::from(u32::MAX) + 1 {
6657 return Err(invalid(
6658 "component",
6659 definition,
6660 "component witnesses exhaust the canonical u32 witness space",
6661 ));
6662 }
6663
6664 Ok(Self {
6665 component_start,
6666 component_count,
6667 field_start,
6668 field_count,
6669 helper_start,
6670 helper_count,
6671 })
6672 }
6673
6674 fn component(
6675 self,
6676 definition: TransportDefinitionId,
6677 ordinal: u32,
6678 ) -> Result<WitnessRecordId, AbiAdapterError> {
6679 self.witness(
6680 definition,
6681 "component edge",
6682 self.component_start,
6683 self.component_count,
6684 ordinal,
6685 )
6686 }
6687
6688 fn field(
6689 self,
6690 definition: TransportDefinitionId,
6691 field: u32,
6692 ) -> Result<WitnessRecordId, AbiAdapterError> {
6693 self.witness(
6694 definition,
6695 "component field",
6696 self.field_start,
6697 self.field_count,
6698 field,
6699 )
6700 }
6701
6702 fn helper(
6703 self,
6704 definition: TransportDefinitionId,
6705 ordinal: u32,
6706 ) -> Result<WitnessRecordId, AbiAdapterError> {
6707 self.witness(
6708 definition,
6709 "reachable helper edge",
6710 self.helper_start,
6711 self.helper_count,
6712 ordinal,
6713 )
6714 }
6715
6716 fn witness(
6717 self,
6718 definition: TransportDefinitionId,
6719 category: &'static str,
6720 start: u64,
6721 count: u32,
6722 ordinal: u32,
6723 ) -> Result<WitnessRecordId, AbiAdapterError> {
6724 if ordinal >= count {
6725 return Err(invalid(
6726 "component",
6727 definition,
6728 format!(
6729 "{category} ordinal {ordinal} is outside its allocated witness range of {count}"
6730 ),
6731 ));
6732 }
6733 let witness = start
6734 .checked_add(u64::from(ordinal))
6735 .and_then(|witness| u32::try_from(witness).ok())
6736 .ok_or_else(|| {
6737 invalid(
6738 "component",
6739 definition,
6740 format!("{category} witness ID exceeds the canonical u32 witness space"),
6741 )
6742 })?;
6743 Ok(WitnessRecordId::new(witness))
6744 }
6745}
6746
6747fn build_component_witness_table(
6748 linked: &LinkedTransportComponent,
6749 component_edges: &[ValidatedDirectComponentEdge],
6750 field_witnesses: &BTreeMap<u32, ValidatedComponentFieldWitness>,
6751 helper_edges: &[ValidatedComponentHelperEdge],
6752 layout: ComponentWitnessLayout,
6753) -> Result<BTreeMap<WitnessRecordId, ResolvedTransportWitness>, AbiAdapterError> {
6754 let mut witnesses = BTreeMap::new();
6755 insert_component_witness(
6756 linked.definition,
6757 &mut witnesses,
6758 WitnessRecordId::new(0),
6759 ResolvedTransportWitness::Definition(linked.definition),
6760 )?;
6761
6762 for edge in component_edges {
6763 let linked_edge = linked
6764 .component_edges
6765 .iter()
6766 .find(|linked_edge| linked_edge.source_edge == edge.source_edge)
6767 .ok_or_else(|| {
6768 invalid(
6769 "component",
6770 linked.definition,
6771 format!(
6772 "direct component local ordinal {} has no relocation-resolved source edge",
6773 edge.local_ordinal
6774 ),
6775 )
6776 })?;
6777 insert_component_witness(
6778 linked.definition,
6779 &mut witnesses,
6780 layout.component(linked.definition, edge.local_ordinal)?,
6781 ResolvedTransportWitness::ComponentEdge {
6782 source_edge: edge.source_edge,
6783 target: linked_edge.target,
6784 },
6785 )?;
6786 }
6787
6788 for (&field, witness) in field_witnesses {
6789 let expected = layout.field(linked.definition, field)?;
6790 if witness.witness != expected {
6791 return Err(invalid(
6792 "component",
6793 linked.definition,
6794 format!(
6795 "component field {field} carries witness {:?}, expected {:?}",
6796 witness.witness, expected
6797 ),
6798 ));
6799 }
6800 insert_component_witness(
6801 linked.definition,
6802 &mut witnesses,
6803 expected,
6804 ResolvedTransportWitness::ComponentField {
6805 field_record: witness.field_record,
6806 target: linked.definition,
6807 },
6808 )?;
6809 }
6810
6811 if helper_edges
6812 .windows(2)
6813 .any(|pair| pair[0].local_ordinal >= pair[1].local_ordinal)
6814 {
6815 return Err(invalid(
6816 "component",
6817 linked.definition,
6818 "reachable helper witnesses must be strictly ordered by producer-local ordinal",
6819 ));
6820 }
6821 for (index, edge) in helper_edges.iter().enumerate() {
6822 let call = u32::try_from(index).map_err(|_| {
6823 invalid(
6824 "component",
6825 linked.definition,
6826 "reachable helper edge count exceeds the canonical u32 ID space",
6827 )
6828 })?;
6829 insert_component_witness(
6830 linked.definition,
6831 &mut witnesses,
6832 layout.helper(linked.definition, call)?,
6833 ResolvedTransportWitness::HelperEdge {
6834 source_edge: edge.source_edge,
6835 target: edge.target,
6836 },
6837 )?;
6838 }
6839
6840 Ok(witnesses)
6841}
6842
6843fn insert_component_witness(
6844 definition: TransportDefinitionId,
6845 witnesses: &mut BTreeMap<WitnessRecordId, ResolvedTransportWitness>,
6846 witness: WitnessRecordId,
6847 resolved: ResolvedTransportWitness,
6848) -> Result<(), AbiAdapterError> {
6849 if witnesses.insert(witness, resolved).is_some() {
6850 return Err(invalid(
6851 "component",
6852 definition,
6853 format!("canonical witness ID {witness:?} was allocated more than once"),
6854 ));
6855 }
6856 Ok(())
6857}
6858
6859fn validate_inbound_inputs_with_projection_roles(
6866 definition: TransportDefinitionId,
6867 descriptor: &Map<String, Value>,
6868 projection_roles: &ResolvedProjectionRoles,
6869) -> Result<ValidatedInboundInputs, AbiAdapterError> {
6870 let fields_json = required_array(descriptor, "fields", "component", definition)?;
6871 let mut fields = Vec::<ValidatedInboundField>::new();
6872 for (index, value) in fields_json.iter().enumerate() {
6873 let field = value.as_object().ok_or_else(|| {
6874 invalid(
6875 "component",
6876 definition,
6877 format!("fields[{index}] must be an object"),
6878 )
6879 })?;
6880 require_exact_u64(field, "id", index as u64, "component", definition)?;
6881 let raw_kind = required_str(field, "kind", "component", definition)?;
6882 let (kind, record_role) = match raw_kind {
6883 "prop" => (InboundFieldKind::Value, TransportComponentFieldRole::Value),
6884 "handler" => (
6885 InboundFieldKind::Callback,
6886 TransportComponentFieldRole::Callback,
6887 ),
6888 "node_ref" => (
6889 InboundFieldKind::NodeRef,
6890 TransportComponentFieldRole::NodeRef,
6891 ),
6892 "deferred_projection" => {
6893 let field_id = checked_u32(
6894 required_u64(field, "id", "component", definition)?,
6895 "deferred projection field ID",
6896 definition,
6897 )?;
6898 let resolved = projection_roles.field(definition, field_id).ok_or_else(|| {
6899 invalid(
6900 "component",
6901 definition,
6902 format!(
6903 "deferred projection field {field_id} requires complete transport-plan adaptation"
6904 ),
6905 )
6906 })?;
6907 (
6908 match resolved {
6909 ResolvedProjectionRole::ServerOnly => InboundFieldKind::ServerOnly,
6910 ResolvedProjectionRole::Value => InboundFieldKind::Value,
6911 ResolvedProjectionRole::Callback(_) => InboundFieldKind::Callback,
6912 ResolvedProjectionRole::NodeRef => InboundFieldKind::NodeRef,
6913 },
6914 TransportComponentFieldRole::DeferredProjection,
6915 )
6916 }
6917 "server_prop" | "static_slot" => continue,
6918 other => {
6919 return Err(invalid(
6920 "component",
6921 definition,
6922 format!("unsupported schema-v9 component field kind `{other}`"),
6923 ));
6924 }
6925 };
6926 if index != fields.len() {
6927 return Err(invalid(
6928 "component",
6929 definition,
6930 "inbound fields must be a dense prefix of the component field ID space",
6931 ));
6932 }
6933 let name = required_str(field, "name", "component", definition)?.to_owned();
6934 let crossing = required_u64(field, "crossing_id", "component", definition)?;
6935 let (value, callback_slot, callback_shape) = match kind {
6936 InboundFieldKind::Value => (
6937 required_u64(field, "value_id", "component", definition)?,
6938 None,
6939 None,
6940 ),
6941 InboundFieldKind::Callback => {
6942 let (slot, callback_shape) = if record_role
6943 == TransportComponentFieldRole::DeferredProjection
6944 {
6945 let shape = match projection_roles
6946 .field(definition, index as u32)
6947 .expect("deferred field resolution was checked above")
6948 {
6949 ResolvedProjectionRole::Callback(shape) => shape,
6950 _ => unreachable!("resolved callback kind must carry a callback shape"),
6951 };
6952 (None, shape)
6953 } else {
6954 require_exact_str(
6955 field,
6956 "dispatch",
6957 "resolve_current",
6958 "component",
6959 definition,
6960 )?;
6961 let slot = required_u64(field, "callback_slot", "component", definition)?;
6962 let callback_slots =
6963 required_array(descriptor, "callback_slots", "component", definition)?;
6964 let valid_slot = callback_slots.iter().any(|candidate| {
6965 candidate.as_object().is_some_and(|candidate| {
6966 required_u64(candidate, "id", "component", definition).ok()
6967 == Some(slot)
6968 && required_str(candidate, "name", "component", definition).ok()
6969 == Some(name.as_str())
6970 })
6971 });
6972 if !valid_slot {
6973 return Err(invalid(
6974 "component",
6975 definition,
6976 format!(
6977 "callback field `{name}` refers to unknown or differently named callback slot {slot}"
6978 ),
6979 ));
6980 }
6981 let callback_shape = match required_str(
6982 field,
6983 "callback_shape",
6984 "component",
6985 definition,
6986 )? {
6987 "required" => InboundCallbackShape::Required,
6988 "optional" => InboundCallbackShape::Optional,
6989 other => {
6990 return Err(invalid(
6991 "component",
6992 definition,
6993 format!(
6994 "callback field `{name}` has unsupported callback_shape `{other}`"
6995 ),
6996 ));
6997 }
6998 };
6999 (
7000 Some(checked_u32(slot, "callback slot ID", definition)?),
7001 callback_shape,
7002 )
7003 };
7004 (
7005 required_u64(field, "value_id", "component", definition)?,
7006 slot,
7007 Some(callback_shape),
7008 )
7009 }
7010 InboundFieldKind::NodeRef => (
7011 required_u64(field, "value_id", "component", definition)?,
7012 None,
7013 None,
7014 ),
7015 InboundFieldKind::ServerOnly => (
7016 required_u64(field, "value_id", "component", definition)?,
7017 None,
7018 None,
7019 ),
7020 };
7021 validate_source_anchor(field, "source_anchor", definition)?;
7022 fields.push(ValidatedInboundField {
7023 name,
7024 kind,
7025 value,
7026 crossing,
7027 callback_slot,
7028 callback_shape,
7029 record_role,
7030 });
7031 }
7032
7033 let inbound = required_object(descriptor, "inbound_inputs", "component", definition)?;
7034 require_known_fields(
7035 "component inbound input metadata",
7036 inbound,
7037 &[
7038 "crossings",
7039 "node_ref_fields",
7040 "projection_fields",
7041 "prop_sites",
7042 "values",
7043 ],
7044 definition,
7045 )?;
7046
7047 let values = required_array(inbound, "values", "component", definition)?;
7048 if values.len() != fields.len() {
7049 return Err(invalid(
7050 "component",
7051 definition,
7052 format!(
7053 "schema-v9 inbound values must be one-to-one with inbound fields; found {} values for {} fields",
7054 values.len(),
7055 fields.len()
7056 ),
7057 ));
7058 }
7059 for (index, value) in values.iter().enumerate() {
7060 let value = value.as_object().ok_or_else(|| {
7061 invalid(
7062 "component",
7063 definition,
7064 format!("inbound_inputs.values[{index}] must be an object"),
7065 )
7066 })?;
7067 require_known_fields(
7068 "inbound component value",
7069 value,
7070 &["field_id", "id", "source_anchor"],
7071 definition,
7072 )?;
7073 require_exact_u64(value, "id", index as u64, "component", definition)?;
7074 let field = required_u64(value, "field_id", "component", definition)?;
7075 let field_index = checked_descriptor_index(field, "inbound field", definition)?;
7076 let Some(field_schema) = fields.get(field_index) else {
7077 return Err(invalid(
7078 "component",
7079 definition,
7080 format!("inbound value {index} refers to unknown field {field}"),
7081 ));
7082 };
7083 if field_schema.value != index as u64 {
7084 return Err(invalid(
7085 "component",
7086 definition,
7087 format!(
7088 "inbound value {index} conflicts with field `{}` value metadata",
7089 field_schema.name
7090 ),
7091 ));
7092 }
7093 validate_source_anchor(value, "source_anchor", definition)?;
7094 }
7095
7096 let crossings = required_array(inbound, "crossings", "component", definition)?;
7097 if crossings.len() != fields.len() {
7098 return Err(invalid(
7099 "component",
7100 definition,
7101 format!(
7102 "inbound crossing hooks must be one-to-one with inbound fields; found {} crossings for {} fields",
7103 crossings.len(),
7104 fields.len()
7105 ),
7106 ));
7107 }
7108 for (index, crossing) in crossings.iter().enumerate() {
7109 let crossing = crossing.as_object().ok_or_else(|| {
7110 invalid(
7111 "component",
7112 definition,
7113 format!("inbound_inputs.crossings[{index}] must be an object"),
7114 )
7115 })?;
7116 require_known_fields(
7117 "inbound component crossing",
7118 crossing,
7119 &["field_id", "id", "kind", "source_anchor"],
7120 definition,
7121 )?;
7122 require_exact_u64(crossing, "id", index as u64, "component", definition)?;
7123 let field = required_u64(crossing, "field_id", "component", definition)?;
7124 let field_index = checked_descriptor_index(field, "inbound field", definition)?;
7125 let Some(field_schema) = fields.get(field_index) else {
7126 return Err(invalid(
7127 "component",
7128 definition,
7129 format!("inbound crossing {index} refers to unknown field {field}"),
7130 ));
7131 };
7132 if field_schema.crossing != index as u64 {
7133 return Err(invalid(
7134 "component",
7135 definition,
7136 format!(
7137 "inbound crossing {index} conflicts with field `{}` crossing_id {}",
7138 field_schema.name, field_schema.crossing
7139 ),
7140 ));
7141 }
7142 let expected = match field_schema.record_role {
7143 TransportComponentFieldRole::Value => "value",
7144 TransportComponentFieldRole::Callback => "callback_resolve_current",
7145 TransportComponentFieldRole::NodeRef => "node_ref_alias",
7146 TransportComponentFieldRole::DeferredProjection => "deferred_projection",
7147 };
7148 require_exact_str(crossing, "kind", expected, "component", definition)?;
7149 validate_source_anchor(crossing, "source_anchor", definition)?;
7150 }
7151
7152 let prop_sites = required_array(inbound, "prop_sites", "component", definition)?;
7153 let signals = required_array(descriptor, "signals", "component", definition)?;
7154 let mut validated_prop_uses = Vec::with_capacity(prop_sites.len());
7155 for (index, site) in prop_sites.iter().enumerate() {
7156 let site = site.as_object().ok_or_else(|| {
7157 invalid(
7158 "component",
7159 definition,
7160 format!("inbound_inputs.prop_sites[{index}] must be an object"),
7161 )
7162 })?;
7163 require_known_fields(
7164 "inbound component prop site",
7165 site,
7166 &[
7167 "crossing_id",
7168 "field_id",
7169 "id",
7170 "source_anchor",
7171 "target",
7172 "temporal",
7173 "value_id",
7174 ],
7175 definition,
7176 )?;
7177 require_exact_u64(site, "id", index as u64, "component", definition)?;
7178 let field = required_u64(site, "field_id", "component", definition)?;
7179 let value = required_u64(site, "value_id", "component", definition)?;
7180 let crossing = required_u64(site, "crossing_id", "component", definition)?;
7181 let field_index = checked_descriptor_index(field, "inbound field", definition)?;
7182 let Some(field_schema) = fields.get(field_index) else {
7183 return Err(invalid(
7184 "component",
7185 definition,
7186 format!("inbound prop site {index} refers to unknown field {field}"),
7187 ));
7188 };
7189 if field_schema.kind != InboundFieldKind::Value
7190 || field_schema.value != value
7191 || field_schema.crossing != crossing
7192 || values
7193 .get(checked_descriptor_index(
7194 value,
7195 "inbound value",
7196 definition,
7197 )?)
7198 .is_none()
7199 || crossings
7200 .get(checked_descriptor_index(
7201 crossing,
7202 "inbound crossing",
7203 definition,
7204 )?)
7205 .is_none()
7206 {
7207 return Err(invalid(
7208 "component",
7209 definition,
7210 format!(
7211 "inbound prop site {index} conflicts with field `{}` value/crossing metadata",
7212 field_schema.name
7213 ),
7214 ));
7215 }
7216
7217 let temporal = required_object(site, "temporal", "component", definition)?;
7218 let target = required_object(site, "target", "component", definition)?;
7219 let (temporal, target_signal) =
7220 match required_str(temporal, "kind", "component", definition)? {
7221 "live_read" => {
7222 require_known_fields(
7223 "LiveRead temporal mode",
7224 temporal,
7225 &["kind"],
7226 definition,
7227 )?;
7228 require_known_fields(
7229 "live-signal prop target",
7230 target,
7231 &["kind", "signal_id"],
7232 definition,
7233 )?;
7234 require_exact_str(target, "kind", "live_signal", "component", definition)?;
7235 let signal = required_u64(target, "signal_id", "component", definition)?;
7236 if !signals.iter().any(|candidate| {
7237 candidate.as_object().is_some_and(|candidate| {
7238 required_u64(candidate, "id", "component", definition).ok()
7239 == Some(signal)
7240 })
7241 }) {
7242 return Err(invalid(
7243 "component",
7244 definition,
7245 format!("inbound prop site {index} targets unknown signal {signal}"),
7246 ));
7247 }
7248 (
7249 TemporalPropMode::LiveRead,
7250 Some(checked_u32(signal, "live-signal target", definition)?),
7251 )
7252 }
7253 "query_key_dependency" => {
7254 require_known_fields(
7255 "QueryKeyDependency temporal mode",
7256 temporal,
7257 &["kind"],
7258 definition,
7259 )?;
7260 require_known_fields(
7261 "query-key live-signal prop target",
7262 target,
7263 &["kind", "signal_id"],
7264 definition,
7265 )?;
7266 require_exact_str(target, "kind", "live_signal", "component", definition)?;
7267 let signal = required_u64(target, "signal_id", "component", definition)?;
7268 if !signals.iter().any(|candidate| {
7269 candidate.as_object().is_some_and(|candidate| {
7270 required_u64(candidate, "id", "component", definition).ok()
7271 == Some(signal)
7272 })
7273 }) {
7274 return Err(invalid(
7275 "component",
7276 definition,
7277 format!(
7278 "inbound query-key prop site {index} targets unknown signal {signal}"
7279 ),
7280 ));
7281 }
7282 (
7283 TemporalPropMode::QueryKeyDependency,
7284 Some(checked_u32(
7285 signal,
7286 "query-key live-signal target",
7287 definition,
7288 )?),
7289 )
7290 }
7291 "seed_once" => {
7292 require_known_fields(
7293 "SeedOnce temporal mode",
7294 temporal,
7295 &["kind", "site_id"],
7296 definition,
7297 )?;
7298 require_exact_u64(temporal, "site_id", index as u64, "component", definition)?;
7299 require_known_fields(
7300 "signal-seed prop target",
7301 target,
7302 &["kind", "signal_id"],
7303 definition,
7304 )?;
7305 require_exact_str(target, "kind", "signal_seed", "component", definition)?;
7306 let signal = required_u64(target, "signal_id", "component", definition)?;
7307 if !signals.iter().any(|candidate| {
7308 candidate.as_object().is_some_and(|candidate| {
7309 required_u64(candidate, "id", "component", definition).ok()
7310 == Some(signal)
7311 })
7312 }) {
7313 return Err(invalid(
7314 "component",
7315 definition,
7316 format!("inbound prop site {index} targets unknown signal {signal}"),
7317 ));
7318 }
7319 let site = u32::try_from(index).map_err(|_| {
7320 invalid(
7321 "component",
7322 definition,
7323 "inbound prop-use site count exceeds the canonical u32 ID space",
7324 )
7325 })?;
7326 (
7327 TemporalPropMode::SeedOnce(PropSiteId::new(site)),
7328 Some(checked_u32(signal, "signal-seed target", definition)?),
7329 )
7330 }
7331 "forbidden_boundary_crossing" => {
7332 require_known_fields(
7333 "forbidden-boundary temporal mode",
7334 temporal,
7335 &["kind"],
7336 definition,
7337 )?;
7338 require_known_fields(
7339 "explicit-island prop target",
7340 target,
7341 &["kind"],
7342 definition,
7343 )?;
7344 require_exact_str(
7345 target,
7346 "kind",
7347 "explicit_island_boundary",
7348 "component",
7349 definition,
7350 )?;
7351 (TemporalPropMode::ForbiddenBoundaryCrossing, None)
7352 }
7353 "forbidden_provider_seed" => {
7354 require_known_fields(
7355 "forbidden-provider-seed temporal mode",
7356 temporal,
7357 &["kind"],
7358 definition,
7359 )?;
7360 require_known_fields(
7361 "SharedStateProvider seed prop target",
7362 target,
7363 &["kind"],
7364 definition,
7365 )?;
7366 require_exact_str(
7367 target,
7368 "kind",
7369 "shared_state_provider_seed",
7370 "component",
7371 definition,
7372 )?;
7373 (TemporalPropMode::ForbiddenProviderSeed, None)
7374 }
7375 other => {
7376 return Err(invalid(
7377 "component",
7378 definition,
7379 format!("unsupported inbound temporal mode `{other}`"),
7380 ));
7381 }
7382 };
7383 validated_prop_uses.push(ValidatedInboundPropUse {
7384 site: u32::try_from(index).map_err(|_| {
7385 invalid(
7386 "component",
7387 definition,
7388 "inbound prop-use site count exceeds the canonical u32 ID space",
7389 )
7390 })?,
7391 field: u32::try_from(field).map_err(|_| {
7392 invalid(
7393 "component",
7394 definition,
7395 format!("inbound prop site {index} field ID exceeds u32"),
7396 )
7397 })?,
7398 value: u32::try_from(value).map_err(|_| {
7399 invalid(
7400 "component",
7401 definition,
7402 format!("inbound prop site {index} value ID exceeds u32"),
7403 )
7404 })?,
7405 temporal,
7406 target_signal,
7407 });
7408 validate_source_anchor(site, "source_anchor", definition)?;
7409 }
7410
7411 let declared_node_refs = required_array(descriptor, "node_refs", "component", definition)?
7412 .iter()
7413 .enumerate()
7414 .map(|(index, node_ref)| {
7415 let node_ref = node_ref.as_object().ok_or_else(|| {
7416 invalid(
7417 "component",
7418 definition,
7419 format!("node_refs[{index}] must be an object"),
7420 )
7421 })?;
7422 checked_u32(
7423 required_u64(node_ref, "id", "component", definition)?,
7424 "legacy node-ref ID",
7425 definition,
7426 )
7427 })
7428 .collect::<Result<BTreeSet<_>, AbiAdapterError>>()?;
7429 let node_ref_fields = required_array(inbound, "node_ref_fields", "component", definition)?;
7430 let expected_node_ref_fields = fields
7431 .iter()
7432 .filter(|field| field.record_role == TransportComponentFieldRole::NodeRef)
7433 .count();
7434 if node_ref_fields.len() != expected_node_ref_fields {
7435 return Err(invalid(
7436 "component",
7437 definition,
7438 format!(
7439 "inbound node-ref records must be one-to-one with NodeRef fields; found {} records for {expected_node_ref_fields} fields",
7440 node_ref_fields.len()
7441 ),
7442 ));
7443 }
7444 let mut validated_node_refs = Vec::with_capacity(node_ref_fields.len());
7445 let mut claimed_node_ref_fields = BTreeSet::new();
7446 let mut claimed_node_refs = BTreeSet::new();
7447 for (index, node_ref) in node_ref_fields.iter().enumerate() {
7448 let node_ref = node_ref.as_object().ok_or_else(|| {
7449 invalid(
7450 "component",
7451 definition,
7452 format!("inbound_inputs.node_ref_fields[{index}] must be an object"),
7453 )
7454 })?;
7455 require_known_fields(
7456 "inbound NodeRef field",
7457 node_ref,
7458 &[
7459 "bind_target",
7460 "crossing_id",
7461 "field_id",
7462 "id",
7463 "node_ref_id",
7464 "source_anchor",
7465 "value_id",
7466 ],
7467 definition,
7468 )?;
7469 require_exact_u64(node_ref, "id", index as u64, "component", definition)?;
7470 let field = checked_u32(
7471 required_u64(node_ref, "field_id", "component", definition)?,
7472 "inbound NodeRef field ID",
7473 definition,
7474 )?;
7475 let value = checked_u32(
7476 required_u64(node_ref, "value_id", "component", definition)?,
7477 "inbound NodeRef value ID",
7478 definition,
7479 )?;
7480 let crossing = checked_u32(
7481 required_u64(node_ref, "crossing_id", "component", definition)?,
7482 "inbound NodeRef crossing ID",
7483 definition,
7484 )?;
7485 let producer_node_ref = checked_u32(
7486 required_u64(node_ref, "node_ref_id", "component", definition)?,
7487 "inbound producer NodeRef ID",
7488 definition,
7489 )?;
7490 let Some(field_schema) = fields.get(field as usize) else {
7491 return Err(invalid(
7492 "component",
7493 definition,
7494 format!("inbound NodeRef record {index} refers to unknown field {field}"),
7495 ));
7496 };
7497 if field_schema.kind != InboundFieldKind::NodeRef
7498 || field_schema.value != u64::from(value)
7499 || field_schema.crossing != u64::from(crossing)
7500 {
7501 return Err(invalid(
7502 "component",
7503 definition,
7504 format!(
7505 "inbound NodeRef record {index} disagrees with field `{}` value/crossing identity",
7506 field_schema.name
7507 ),
7508 ));
7509 }
7510 if !declared_node_refs.contains(&producer_node_ref) {
7511 return Err(invalid(
7512 "component",
7513 definition,
7514 format!(
7515 "inbound NodeRef record {index} refers to unknown producer NodeRef {producer_node_ref}"
7516 ),
7517 ));
7518 }
7519 if !claimed_node_ref_fields.insert(field) {
7520 return Err(invalid(
7521 "component",
7522 definition,
7523 format!(
7524 "component field `{}` has more than one inbound NodeRef identity",
7525 field_schema.name
7526 ),
7527 ));
7528 }
7529 if !claimed_node_refs.insert(producer_node_ref) {
7530 return Err(invalid(
7531 "component",
7532 definition,
7533 format!(
7534 "producer NodeRef {producer_node_ref} is represented by more than one inbound field"
7535 ),
7536 ));
7537 }
7538 let bind_target = node_ref
7539 .get("bind_target")
7540 .map(|target| {
7541 let target = target.as_str().ok_or_else(|| {
7542 invalid(
7543 "component",
7544 definition,
7545 format!("inbound NodeRef record {index} bind_target must be a string"),
7546 )
7547 })?;
7548 match target {
7549 "element" => Ok(ComponentNodeRefBindTarget::Element),
7550 "html_element" => Ok(ComponentNodeRefBindTarget::HtmlElement),
7551 "input" => Ok(ComponentNodeRefBindTarget::Input),
7552 "textarea" => Ok(ComponentNodeRefBindTarget::TextArea),
7553 "select" => Ok(ComponentNodeRefBindTarget::Select),
7554 "form" => Ok(ComponentNodeRefBindTarget::Form),
7555 "dialog" => Ok(ComponentNodeRefBindTarget::Dialog),
7556 other => Err(invalid(
7557 "component",
7558 definition,
7559 format!(
7560 "inbound NodeRef record {index} has unsupported bind_target `{other}`"
7561 ),
7562 )),
7563 }
7564 })
7565 .transpose()?;
7566 validate_source_anchor(node_ref, "source_anchor", definition)?;
7567 validated_node_refs.push(ValidatedInboundNodeRef {
7568 field,
7569 value,
7570 node_ref: producer_node_ref,
7571 bind_target,
7572 });
7573 }
7574
7575 let declared_signals = required_array(descriptor, "signals", "component", definition)?
7576 .iter()
7577 .enumerate()
7578 .map(|(index, signal)| {
7579 let signal = signal.as_object().ok_or_else(|| {
7580 invalid(
7581 "component",
7582 definition,
7583 format!("signals[{index}] must be an object"),
7584 )
7585 })?;
7586 checked_u32(
7587 required_u64(signal, "id", "component", definition)?,
7588 "legacy signal ID",
7589 definition,
7590 )
7591 })
7592 .collect::<Result<BTreeSet<_>, AbiAdapterError>>()?;
7593 let projections = required_array(inbound, "projection_fields", "component", definition)?;
7594 let mut claimed_projection_fields = BTreeSet::new();
7595 let mut projection_signals = BTreeSet::new();
7596 for (index, projection) in projections.iter().enumerate() {
7597 let projection = projection.as_object().ok_or_else(|| {
7598 invalid(
7599 "component",
7600 definition,
7601 format!("inbound_inputs.projection_fields[{index}] must be an object"),
7602 )
7603 })?;
7604 require_known_fields(
7605 "inbound deferred projection",
7606 projection,
7607 &[
7608 "crossing_id",
7609 "field_id",
7610 "id",
7611 "node_ref_id",
7612 "signal_id",
7613 "source_anchor",
7614 "value_id",
7615 ],
7616 definition,
7617 )?;
7618 require_exact_u64(projection, "id", index as u64, "component", definition)?;
7619 let field = checked_u32(
7620 required_u64(projection, "field_id", "component", definition)?,
7621 "deferred projection field ID",
7622 definition,
7623 )?;
7624 let value = checked_u32(
7625 required_u64(projection, "value_id", "component", definition)?,
7626 "deferred projection value ID",
7627 definition,
7628 )?;
7629 let crossing = checked_u32(
7630 required_u64(projection, "crossing_id", "component", definition)?,
7631 "deferred projection crossing ID",
7632 definition,
7633 )?;
7634 let signal = checked_u32(
7635 required_u64(projection, "signal_id", "component", definition)?,
7636 "deferred projection signal ID",
7637 definition,
7638 )?;
7639 let node_ref = checked_u32(
7640 required_u64(projection, "node_ref_id", "component", definition)?,
7641 "deferred projection NodeRef ID",
7642 definition,
7643 )?;
7644 let Some(field_schema) = fields.get(field as usize) else {
7645 return Err(invalid(
7646 "component",
7647 definition,
7648 format!("deferred projection {index} refers to unknown field {field}"),
7649 ));
7650 };
7651 if field_schema.value != u64::from(value) || field_schema.crossing != u64::from(crossing) {
7652 return Err(invalid(
7653 "component",
7654 definition,
7655 format!(
7656 "deferred projection {index} disagrees with field `{}` value/crossing identity",
7657 field_schema.name
7658 ),
7659 ));
7660 }
7661 if !claimed_projection_fields.insert(field) {
7662 return Err(invalid(
7663 "component",
7664 definition,
7665 format!(
7666 "component field `{}` has more than one deferred projection record",
7667 field_schema.name
7668 ),
7669 ));
7670 }
7671 if !declared_signals.contains(&signal) {
7672 return Err(invalid(
7673 "component",
7674 definition,
7675 format!("deferred projection {index} refers to unknown producer signal {signal}"),
7676 ));
7677 }
7678 projection_signals.insert(signal);
7679 if !declared_node_refs.contains(&node_ref) {
7680 return Err(invalid(
7681 "component",
7682 definition,
7683 format!(
7684 "deferred projection {index} refers to unknown producer NodeRef {node_ref}"
7685 ),
7686 ));
7687 }
7688 validate_source_anchor(projection, "source_anchor", definition)?;
7689
7690 match field_schema.kind {
7691 InboundFieldKind::Value => {
7692 if !validated_prop_uses
7693 .iter()
7694 .any(|prop_use| prop_use.field == field)
7695 {
7696 let site = u32::try_from(validated_prop_uses.len()).map_err(|_| {
7697 invalid(
7698 "component",
7699 definition,
7700 "inbound prop-use site count exceeds the canonical u32 ID space",
7701 )
7702 })?;
7703 validated_prop_uses.push(ValidatedInboundPropUse {
7704 site,
7705 field,
7706 value,
7707 temporal: TemporalPropMode::LiveRead,
7708 target_signal: Some(signal),
7709 });
7710 }
7711 }
7712 InboundFieldKind::NodeRef => {
7713 if !validated_node_refs
7714 .iter()
7715 .any(|inbound| inbound.field == field)
7716 {
7717 if !claimed_node_refs.insert(node_ref) {
7718 return Err(invalid(
7719 "component",
7720 definition,
7721 format!(
7722 "producer NodeRef {node_ref} is represented by more than one inbound field"
7723 ),
7724 ));
7725 }
7726 validated_node_refs.push(ValidatedInboundNodeRef {
7727 field,
7728 value,
7729 node_ref,
7730 bind_target: None,
7731 });
7732 }
7733 }
7734 InboundFieldKind::Callback | InboundFieldKind::ServerOnly => {}
7735 }
7736 }
7737 for (field_id, field) in fields.iter().enumerate() {
7738 let field_id = u32::try_from(field_id).map_err(|_| {
7739 invalid(
7740 "component",
7741 definition,
7742 "component field count exceeds the canonical u32 ID space",
7743 )
7744 })?;
7745 if field.record_role == TransportComponentFieldRole::DeferredProjection
7746 && !claimed_projection_fields.contains(&field_id)
7747 {
7748 return Err(invalid(
7749 "component",
7750 definition,
7751 format!(
7752 "deferred projection field `{}` has no latent projection record",
7753 field.name
7754 ),
7755 ));
7756 }
7757 }
7758
7759 for (field_id, field) in fields.iter().enumerate() {
7760 let field_id = u32::try_from(field_id).map_err(|_| {
7761 invalid(
7762 "component",
7763 definition,
7764 "component field count exceeds the canonical u32 ID space",
7765 )
7766 })?;
7767 if field.kind == InboundFieldKind::Value
7768 && !validated_prop_uses
7769 .iter()
7770 .any(|prop_use| prop_use.field == field_id)
7771 {
7772 return Err(invalid(
7773 "component",
7774 definition,
7775 format!("inbound value field `{}` has no prop-use site", field.name),
7776 ));
7777 }
7778 }
7779
7780 Ok(ValidatedInboundInputs {
7781 fields,
7782 prop_uses: validated_prop_uses,
7783 node_refs: validated_node_refs,
7784 projection_signals,
7785 })
7786}
7787
7788#[cfg(test)]
7789fn validate_inbound_inputs(
7790 definition: TransportDefinitionId,
7791 descriptor: &Map<String, Value>,
7792) -> Result<ValidatedInboundInputs, AbiAdapterError> {
7793 validate_inbound_inputs_with_projection_roles(
7794 definition,
7795 descriptor,
7796 &ResolvedProjectionRoles::default(),
7797 )
7798}
7799
7800fn validated_component_input_fingerprint<'a>(
7801 linked: &LinkedTransportComponent,
7802 transport: &'a Map<String, Value>,
7803) -> Result<&'a str, AbiAdapterError> {
7804 let fingerprint = required_str(
7805 transport,
7806 "component_input_fingerprint",
7807 "component",
7808 linked.definition,
7809 )?;
7810 let fingerprint_hex = fingerprint.strip_prefix("sha256:").ok_or_else(|| {
7811 invalid(
7812 "component",
7813 linked.definition,
7814 "`component_input_fingerprint` must use the `sha256:` prefix",
7815 )
7816 })?;
7817 parse_hex_32(
7818 fingerprint_hex,
7819 "component",
7820 linked.definition,
7821 "component_input_fingerprint",
7822 )?;
7823 let fingerprint_record = component_record_id(fingerprint);
7824 if fingerprint_record != linked.definition.record {
7825 return Err(invalid(
7826 "component",
7827 linked.definition,
7828 format!(
7829 "component_input_fingerprint derives definition record {}, but the \
7830 relocation-linked component definition is {}",
7831 hex_record(&fingerprint_record),
7832 hex_record(&linked.definition.record),
7833 ),
7834 ));
7835 }
7836 Ok(fingerprint)
7837}
7838
7839fn validate_component_field_witness_set(
7840 linked: &LinkedTransportComponent,
7841 transport: &Map<String, Value>,
7842 inbound_fields: &[ValidatedInboundField],
7843 witness_layout: &ComponentWitnessLayout,
7844) -> Result<BTreeMap<u32, ValidatedComponentFieldWitness>, AbiAdapterError> {
7845 let fingerprint = required_str(
7846 transport,
7847 "component_input_fingerprint",
7848 "component",
7849 linked.definition,
7850 )?;
7851 let fingerprint_hex = fingerprint.strip_prefix("sha256:").ok_or_else(|| {
7852 invalid(
7853 "component",
7854 linked.definition,
7855 "`component_input_fingerprint` must use the `sha256:` prefix",
7856 )
7857 })?;
7858 parse_hex_32(
7859 fingerprint_hex,
7860 "component",
7861 linked.definition,
7862 "component_input_fingerprint",
7863 )?;
7864
7865 let claims = required_array(
7866 transport,
7867 "component_field_witnesses",
7868 "component",
7869 linked.definition,
7870 )?;
7871 if claims.len() != inbound_fields.len() || claims.len() != linked.field_witnesses.len() {
7872 return Err(invalid(
7873 "component",
7874 linked.definition,
7875 format!(
7876 "component field witnesses must be one-to-one with inbound fields; \
7877 found {} payload claims, {} linked records, and {} inbound fields",
7878 claims.len(),
7879 linked.field_witnesses.len(),
7880 inbound_fields.len()
7881 ),
7882 ));
7883 }
7884
7885 let mut validated = BTreeMap::new();
7886 let mut seen_records = BTreeMap::<TransportRecordId, String>::new();
7887 for (index, (claim, linked_field)) in claims.iter().zip(&linked.field_witnesses).enumerate() {
7888 let claim = claim.as_object().ok_or_else(|| {
7889 invalid(
7890 "component",
7891 linked.definition,
7892 format!("component_field_witnesses[{index}] must be an object"),
7893 )
7894 })?;
7895 require_known_fields(
7896 "component field witness",
7897 claim,
7898 &[
7899 "callback_shape",
7900 "crossing_hook_id",
7901 "field_id",
7902 "field_name",
7903 "field_record_id",
7904 "role",
7905 ],
7906 linked.definition,
7907 )?;
7908 require_exact_u64(
7909 claim,
7910 "field_id",
7911 index as u64,
7912 "component",
7913 linked.definition,
7914 )?;
7915 let inbound = &inbound_fields[index];
7916 let field_name = required_str(claim, "field_name", "component", linked.definition)?;
7917 if field_name != inbound.name {
7918 return Err(invalid(
7919 "component",
7920 linked.definition,
7921 format!(
7922 "component field witness {index} names `{field_name}`, \
7923 but descriptor field {index} is `{}`",
7924 inbound.name
7925 ),
7926 ));
7927 }
7928 require_exact_u64(
7929 claim,
7930 "crossing_hook_id",
7931 inbound.crossing,
7932 "component",
7933 linked.definition,
7934 )?;
7935 let (role, callback_shape) = match inbound.record_role {
7936 TransportComponentFieldRole::Value if inbound.callback_shape.is_none() => {
7937 require_exact_str(claim, "role", "value", "component", linked.definition)?;
7938 require_exact_str(
7939 claim,
7940 "callback_shape",
7941 "not_callback",
7942 "component",
7943 linked.definition,
7944 )?;
7945 (
7946 TransportComponentFieldRole::Value,
7947 TransportCallbackShape::NotCallback,
7948 )
7949 }
7950 TransportComponentFieldRole::Callback
7951 if inbound.callback_shape == Some(InboundCallbackShape::Required) =>
7952 {
7953 require_exact_str(claim, "role", "callback", "component", linked.definition)?;
7954 require_exact_str(
7955 claim,
7956 "callback_shape",
7957 "required",
7958 "component",
7959 linked.definition,
7960 )?;
7961 (
7962 TransportComponentFieldRole::Callback,
7963 TransportCallbackShape::Required,
7964 )
7965 }
7966 TransportComponentFieldRole::Callback
7967 if inbound.callback_shape == Some(InboundCallbackShape::Optional) =>
7968 {
7969 require_exact_str(claim, "role", "callback", "component", linked.definition)?;
7970 require_exact_str(
7971 claim,
7972 "callback_shape",
7973 "optional",
7974 "component",
7975 linked.definition,
7976 )?;
7977 (
7978 TransportComponentFieldRole::Callback,
7979 TransportCallbackShape::Optional,
7980 )
7981 }
7982 TransportComponentFieldRole::NodeRef if inbound.callback_shape.is_none() => {
7983 require_exact_str(claim, "role", "node_ref", "component", linked.definition)?;
7984 require_exact_str(
7985 claim,
7986 "callback_shape",
7987 "not_callback",
7988 "component",
7989 linked.definition,
7990 )?;
7991 (
7992 TransportComponentFieldRole::NodeRef,
7993 TransportCallbackShape::NotCallback,
7994 )
7995 }
7996 TransportComponentFieldRole::DeferredProjection => {
7997 require_exact_str(
7998 claim,
7999 "role",
8000 "deferred_projection",
8001 "component",
8002 linked.definition,
8003 )?;
8004 require_exact_str(
8005 claim,
8006 "callback_shape",
8007 "not_callback",
8008 "component",
8009 linked.definition,
8010 )?;
8011 (
8012 TransportComponentFieldRole::DeferredProjection,
8013 TransportCallbackShape::NotCallback,
8014 )
8015 }
8016 _ => {
8017 return Err(invalid(
8018 "component",
8019 linked.definition,
8020 format!(
8021 "descriptor field `{}` has an inconsistent role/callback shape",
8022 inbound.name
8023 ),
8024 ));
8025 }
8026 };
8027
8028 let field_record =
8029 parse_record_field(claim, "field_record_id", "component", linked.definition)?;
8030 if let Some(first_field) = seen_records.insert(field_record, inbound.name.clone()) {
8031 return Err(AbiAdapterError::DuplicateComponentFieldRecordId {
8032 definition: linked.definition,
8033 first_field,
8034 second_field: inbound.name.clone(),
8035 field_record: hex_record(&field_record),
8036 });
8037 }
8038 let index = u32::try_from(index).map_err(|_| {
8039 invalid(
8040 "component",
8041 linked.definition,
8042 "component field count exceeds the canonical u32 ID space",
8043 )
8044 })?;
8045 let crossing = u32::try_from(inbound.crossing).map_err(|_| {
8046 invalid(
8047 "component",
8048 linked.definition,
8049 format!(
8050 "component field witness `{}` crossing hook exceeds the canonical u32 ID space",
8051 inbound.name
8052 ),
8053 )
8054 })?;
8055 let expected_record =
8056 component_field_record_id(fingerprint, index, crossing, role, callback_shape);
8057 if field_record != expected_record {
8058 return Err(AbiAdapterError::ComponentFieldRecordIdMismatch {
8059 definition: linked.definition,
8060 field: inbound.name.clone(),
8061 expected: hex_record(&expected_record),
8062 actual: hex_record(&field_record),
8063 });
8064 }
8065 if linked_field.field_record != field_record || linked_field.target != linked.definition {
8066 return Err(invalid(
8067 "component",
8068 linked.definition,
8069 format!(
8070 "component field witness `{}` does not match its rustc-resolved record",
8071 inbound.name
8072 ),
8073 ));
8074 }
8075 validated.insert(
8076 index,
8077 ValidatedComponentFieldWitness {
8078 field_record,
8079 witness: witness_layout.field(linked.definition, index)?,
8080 },
8081 );
8082 }
8083 Ok(validated)
8084}
8085
8086fn checked_descriptor_index(
8087 id: u64,
8088 label: &str,
8089 definition: TransportDefinitionId,
8090) -> Result<usize, AbiAdapterError> {
8091 usize::try_from(id).map_err(|_| {
8092 invalid(
8093 "component",
8094 definition,
8095 format!("{label} id {id} exceeds this target's index space"),
8096 )
8097 })
8098}
8099
8100fn validate_source_anchor(
8101 object: &Map<String, Value>,
8102 field: &str,
8103 definition: TransportDefinitionId,
8104) -> Result<(), AbiAdapterError> {
8105 let anchor = required_object(object, field, "component", definition)?;
8106 require_known_fields(
8107 "source anchor",
8108 anchor,
8109 &["start_column", "start_line"],
8110 definition,
8111 )?;
8112 required_u64(anchor, "start_line", "component", definition)?;
8113 required_u64(anchor, "start_column", "component", definition)?;
8114 Ok(())
8115}
8116
8117fn adapt_component_fields(
8132 definition: TransportDefinitionId,
8133 descriptor: &Map<String, Value>,
8134 inbound: &ValidatedInboundInputs,
8135 field_witnesses: &BTreeMap<u32, ValidatedComponentFieldWitness>,
8136 value_layout: &ComponentValueLayout,
8137) -> Result<AdaptedComponentFields, AbiAdapterError> {
8138 let fields = required_array(descriptor, "fields", "component", definition)?;
8139 let mut canonical = BTreeMap::new();
8140
8141 for (index, value) in fields.iter().enumerate() {
8142 let field = value.as_object().ok_or_else(|| {
8143 invalid(
8144 "component",
8145 definition,
8146 format!("fields[{index}] must be an object"),
8147 )
8148 })?;
8149 let kind = required_str(field, "kind", "component", definition)?;
8150 let name = required_str(field, "name", "component", definition)?.to_owned();
8151 let field_index = u32::try_from(index).map_err(|_| {
8152 invalid(
8153 "component",
8154 definition,
8155 "component field count exceeds the canonical u32 ID space",
8156 )
8157 })?;
8158 let field_id = ComponentFieldId::new(field_index);
8159 require_exact_u64(
8160 field,
8161 "id",
8162 u64::try_from(index).expect("usize always fits u64 on supported targets"),
8163 "component",
8164 definition,
8165 )?;
8166
8167 match kind {
8168 "server_prop" => {
8169 require_known_fields(
8170 "server-only component field",
8171 field,
8172 &["id", "kind", "name", "source"],
8173 definition,
8174 )?;
8175 required_str(field, "source", "component", definition)?;
8176 canonical.insert(
8177 field_id,
8178 ComponentFieldSchema {
8179 source_name: name,
8180 role: ComponentFieldRole::ServerOnly,
8181 type_witness: None,
8182 crossing_hook: None,
8183 client_value: None,
8184 callback_shape: None,
8185 codec: ComponentFieldCodec::None,
8186 static_slot: StaticSlotCapability::Unsupported,
8187 },
8188 );
8189 }
8190 "static_slot" => {
8191 require_known_fields(
8192 "immutable static-only component slot",
8193 field,
8194 &[
8195 "id",
8196 "kind",
8197 "name",
8198 "permits_nested_owner",
8199 "source",
8200 "span",
8201 ],
8202 definition,
8203 )?;
8204 require_exact_str(
8205 field,
8206 "source",
8207 "inferred_single_unconditional_server_slot",
8208 "component",
8209 definition,
8210 )?;
8211 require_exact_str(field, "span", "exact_one", "component", definition)?;
8212 if required_bool(field, "permits_nested_owner", "component", definition)? {
8213 return Err(invalid(
8214 "component",
8215 definition,
8216 "v9 inferred static slots cannot preserve nested owners",
8217 ));
8218 }
8219 canonical.insert(
8220 field_id,
8221 ComponentFieldSchema {
8222 source_name: name,
8223 role: ComponentFieldRole::Slot,
8224 type_witness: None,
8225 crossing_hook: None,
8226 client_value: None,
8227 callback_shape: None,
8228 codec: ComponentFieldCodec::None,
8229 static_slot: StaticSlotCapability::Immutable {
8230 permits_nested_owner: false,
8231 },
8232 },
8233 );
8234 }
8235 "prop" => {
8236 require_known_fields(
8237 "client value component field",
8238 field,
8239 &[
8240 "crossing_id",
8241 "id",
8242 "kind",
8243 "name",
8244 "source",
8245 "source_anchor",
8246 "value_id",
8247 ],
8248 definition,
8249 )?;
8250 let client_value = value_layout.inbound(
8251 definition,
8252 required_u64(field, "value_id", "component", definition)?,
8253 )?;
8254 let crossing_id =
8255 u32::try_from(required_u64(field, "crossing_id", "component", definition)?)
8256 .map_err(|_| {
8257 invalid(
8258 "component",
8259 definition,
8260 format!("component field `{name}` crossing_id exceeds u32"),
8261 )
8262 })?;
8263 required_str(field, "source", "component", definition)?;
8264 validate_source_anchor(field, "source_anchor", definition)?;
8265 let witness = field_witnesses.get(&field_index).ok_or_else(|| {
8266 invalid(
8267 "component",
8268 definition,
8269 format!("component value field `{name}` has no rustc field witness"),
8270 )
8271 })?;
8272 canonical.insert(
8273 field_id,
8274 ComponentFieldSchema {
8275 source_name: name,
8276 role: ComponentFieldRole::Value,
8277 type_witness: Some(witness.witness),
8278 crossing_hook: Some(CrossingHookId::new(crossing_id)),
8279 client_value: Some(client_value),
8280 callback_shape: None,
8281 codec: ComponentFieldCodec::None,
8282 static_slot: StaticSlotCapability::Unsupported,
8283 },
8284 );
8285 }
8286 "node_ref" => {
8287 require_known_fields(
8288 "client NodeRef handle component field",
8289 field,
8290 &[
8291 "crossing_id",
8292 "id",
8293 "kind",
8294 "name",
8295 "source",
8296 "source_anchor",
8297 "value_id",
8298 ],
8299 definition,
8300 )?;
8301 require_exact_str(
8302 field,
8303 "source",
8304 "node_ref_handle_alias",
8305 "component",
8306 definition,
8307 )?;
8308 let client_value = value_layout.inbound(
8309 definition,
8310 required_u64(field, "value_id", "component", definition)?,
8311 )?;
8312 let crossing_id = checked_u32(
8313 required_u64(field, "crossing_id", "component", definition)?,
8314 "NodeRef field crossing ID",
8315 definition,
8316 )?;
8317 validate_source_anchor(field, "source_anchor", definition)?;
8318 let witness = field_witnesses.get(&field_index).ok_or_else(|| {
8319 invalid(
8320 "component",
8321 definition,
8322 format!("component NodeRef field `{name}` has no rustc field witness"),
8323 )
8324 })?;
8325 canonical.insert(
8326 field_id,
8327 ComponentFieldSchema {
8328 source_name: name,
8329 role: ComponentFieldRole::ClientHandle,
8330 type_witness: Some(witness.witness),
8331 crossing_hook: Some(CrossingHookId::new(crossing_id)),
8332 client_value: Some(client_value),
8333 callback_shape: None,
8334 codec: ComponentFieldCodec::None,
8335 static_slot: StaticSlotCapability::Unsupported,
8336 },
8337 );
8338 }
8339 "handler" => {
8340 require_known_fields(
8341 "client callback component field",
8342 field,
8343 &[
8344 "callback_slot",
8345 "callback_shape",
8346 "crossing_id",
8347 "dispatch",
8348 "id",
8349 "kind",
8350 "name",
8351 "source",
8352 "source_anchor",
8353 "value_id",
8354 ],
8355 definition,
8356 )?;
8357 required_u64(field, "callback_slot", "component", definition)?;
8358 let client_value = value_layout.inbound(
8359 definition,
8360 required_u64(field, "value_id", "component", definition)?,
8361 )?;
8362 let callback_shape =
8363 match required_str(field, "callback_shape", "component", definition)? {
8364 "required" => ComponentCallbackShape::Required,
8365 "optional" => ComponentCallbackShape::Optional,
8366 other => {
8367 return Err(invalid(
8368 "component",
8369 definition,
8370 format!(
8371 "callback field `{name}` has unsupported callback_shape `{other}`"
8372 ),
8373 ));
8374 }
8375 };
8376 let crossing_id =
8377 u32::try_from(required_u64(field, "crossing_id", "component", definition)?)
8378 .map_err(|_| {
8379 invalid(
8380 "component",
8381 definition,
8382 format!("component field `{name}` crossing_id exceeds u32"),
8383 )
8384 })?;
8385 require_exact_str(
8386 field,
8387 "dispatch",
8388 "resolve_current",
8389 "component",
8390 definition,
8391 )?;
8392 required_str(field, "source", "component", definition)?;
8393 validate_source_anchor(field, "source_anchor", definition)?;
8394 let witness = field_witnesses.get(&field_index).ok_or_else(|| {
8395 invalid(
8396 "component",
8397 definition,
8398 format!("component callback field `{name}` has no rustc field witness"),
8399 )
8400 })?;
8401 canonical.insert(
8402 field_id,
8403 ComponentFieldSchema {
8404 source_name: name,
8405 role: ComponentFieldRole::Callback,
8406 type_witness: Some(witness.witness),
8407 crossing_hook: Some(CrossingHookId::new(crossing_id)),
8408 client_value: Some(client_value),
8409 callback_shape: Some(callback_shape),
8410 codec: ComponentFieldCodec::None,
8411 static_slot: StaticSlotCapability::Unsupported,
8412 },
8413 );
8414 }
8415 "deferred_projection" => {
8416 require_known_fields(
8417 "deferred component field projection",
8418 field,
8419 &[
8420 "crossing_id",
8421 "id",
8422 "kind",
8423 "name",
8424 "source",
8425 "source_anchor",
8426 "value_id",
8427 ],
8428 definition,
8429 )?;
8430 require_exact_str(
8431 field,
8432 "source",
8433 "rustc_linked_child_field",
8434 "component",
8435 definition,
8436 )?;
8437 validate_source_anchor(field, "source_anchor", definition)?;
8438 let resolved = inbound.fields.get(index).ok_or_else(|| {
8439 invalid(
8440 "component",
8441 definition,
8442 format!("deferred field `{name}` has no resolved inbound metadata"),
8443 )
8444 })?;
8445 let crossing_id = checked_u32(
8446 required_u64(field, "crossing_id", "component", definition)?,
8447 "deferred field crossing ID",
8448 definition,
8449 )?;
8450 let client_value = value_layout.inbound(
8451 definition,
8452 required_u64(field, "value_id", "component", definition)?,
8453 )?;
8454 let witness = field_witnesses.get(&field_index).ok_or_else(|| {
8455 invalid(
8456 "component",
8457 definition,
8458 format!("deferred field `{name}` has no rustc field witness"),
8459 )
8460 })?;
8461 let (role, type_witness, crossing_hook, client_value, callback_shape) = match (
8462 resolved.kind,
8463 resolved.callback_shape,
8464 ) {
8465 (InboundFieldKind::ServerOnly, None) => {
8466 (ComponentFieldRole::ServerOnly, None, None, None, None)
8467 }
8468 (InboundFieldKind::Value, None) => (
8469 ComponentFieldRole::Value,
8470 Some(witness.witness),
8471 Some(CrossingHookId::new(crossing_id)),
8472 Some(client_value),
8473 None,
8474 ),
8475 (InboundFieldKind::NodeRef, None) => (
8476 ComponentFieldRole::ClientHandle,
8477 Some(witness.witness),
8478 Some(CrossingHookId::new(crossing_id)),
8479 Some(client_value),
8480 None,
8481 ),
8482 (InboundFieldKind::Callback, Some(InboundCallbackShape::Required)) => (
8483 ComponentFieldRole::Callback,
8484 Some(witness.witness),
8485 Some(CrossingHookId::new(crossing_id)),
8486 Some(client_value),
8487 Some(ComponentCallbackShape::Required),
8488 ),
8489 (InboundFieldKind::Callback, Some(InboundCallbackShape::Optional)) => (
8490 ComponentFieldRole::Callback,
8491 Some(witness.witness),
8492 Some(CrossingHookId::new(crossing_id)),
8493 Some(client_value),
8494 Some(ComponentCallbackShape::Optional),
8495 ),
8496 _ => {
8497 return Err(invalid(
8498 "component",
8499 definition,
8500 format!(
8501 "deferred field `{name}` resolved to an inconsistent role/callback shape"
8502 ),
8503 ));
8504 }
8505 };
8506 canonical.insert(
8507 field_id,
8508 ComponentFieldSchema {
8509 source_name: name,
8510 role,
8511 type_witness,
8512 crossing_hook,
8513 client_value,
8514 callback_shape,
8515 codec: ComponentFieldCodec::None,
8516 static_slot: StaticSlotCapability::Unsupported,
8517 },
8518 );
8519 }
8520 other => {
8521 return Err(invalid(
8522 "component",
8523 definition,
8524 format!("unsupported schema-v9 component field kind `{other}`"),
8525 ));
8526 }
8527 }
8528 }
8529
8530 Ok(AdaptedComponentFields { canonical })
8531}
8532
8533#[derive(Debug)]
8534struct ValidatedView {
8535 root_span: SpanCardinality,
8536 fragment_root: ComponentFragmentRoot,
8537 has_unknown_kind: bool,
8538}
8539
8540fn validate_component_descriptor_header(
8541 definition: TransportDefinitionId,
8542 descriptor: &Map<String, Value>,
8543) -> Result<(), AbiAdapterError> {
8544 require_known_fields(
8545 "component descriptor v9",
8546 descriptor,
8547 &[
8548 "asset_id",
8549 "bindings",
8550 "callback_slots",
8551 "client_ir_version",
8552 "client_origin_permission",
8553 "counts",
8554 "descriptor_hash",
8555 "exprs",
8556 "fields",
8557 "format",
8558 "handlers",
8559 "inbound_inputs",
8560 "intervals",
8561 "is_async",
8562 "js_hash",
8563 "keyed_collections",
8564 "mutation_initializers",
8565 "mutations",
8566 "node_refs",
8567 "queries",
8568 "query_initializers",
8569 "schema_version",
8570 "self_ty",
8571 "shared_stores",
8572 "shared_state_provider_sites",
8573 "signals",
8574 "struct_name",
8575 "view_tree",
8576 ],
8577 definition,
8578 )?;
8579 require_exact_str(
8580 descriptor,
8581 "format",
8582 COMPONENT_DESCRIPTOR_FORMAT,
8583 "component",
8584 definition,
8585 )?;
8586 require_exact_u64(
8587 descriptor,
8588 "schema_version",
8589 COMPONENT_DESCRIPTOR_SCHEMA,
8590 "component",
8591 definition,
8592 )?;
8593 require_exact_u64(
8594 descriptor,
8595 "client_ir_version",
8596 CLIENT_IR_SCHEMA,
8597 "component",
8598 definition,
8599 )?;
8600 for field in [
8601 "asset_id",
8602 "descriptor_hash",
8603 "js_hash",
8604 "self_ty",
8605 "struct_name",
8606 "client_origin_permission",
8607 ] {
8608 required_str(descriptor, field, "component", definition)?;
8609 }
8610 required_bool(descriptor, "is_async", "component", definition)?;
8611
8612 for field in [
8613 "callback_slots",
8614 "exprs",
8615 "fields",
8616 "handlers",
8617 "mutations",
8618 "node_refs",
8619 "queries",
8620 "shared_stores",
8621 "shared_state_provider_sites",
8622 "signals",
8623 ] {
8624 required_array(descriptor, field, "component", definition)?;
8625 }
8626 for field in ["intervals", "mutation_initializers", "query_initializers"] {
8627 optional_array(descriptor, field, "component", definition)?;
8628 }
8629 optional_array(descriptor, "keyed_collections", "component", definition)?;
8630 required_object(descriptor, "bindings", "component", definition)?;
8631 required_object(descriptor, "counts", "component", definition)?;
8632 required_object(descriptor, "inbound_inputs", "component", definition)?;
8633 required_object(descriptor, "view_tree", "component", definition)?;
8634
8635 validate_sha256_field(descriptor, "descriptor_hash", "component", definition)?;
8636 validate_sha256_field(descriptor, "js_hash", "component", definition)?;
8637 validate_counts(definition, descriptor)
8638}
8639
8640fn validate_component_definition_abi(
8641 linked: &LinkedTransportComponent,
8642 descriptor: &Map<String, Value>,
8643) -> Result<(RenderKind, OriginPermission), AbiAdapterError> {
8644 let claimed_async = required_bool(descriptor, "is_async", "component", linked.definition)?;
8645 let witnessed_async = matches!(
8646 linked.component_abi.render_kind,
8647 TransportComponentRenderKind::Async
8648 );
8649 if claimed_async != witnessed_async {
8650 return Err(invalid(
8651 "component",
8652 linked.definition,
8653 format!(
8654 "legacy `is_async` claim {claimed_async} disagrees with the rustc-authenticated component ABI ({})",
8655 if witnessed_async { "async" } else { "sync" },
8656 ),
8657 ));
8658 }
8659
8660 let claimed_origin = match required_str(
8661 descriptor,
8662 "client_origin_permission",
8663 "component",
8664 linked.definition,
8665 )? {
8666 "participant_only" => TransportComponentOriginPermission::ParticipantOnly,
8667 "origin_capable" => TransportComponentOriginPermission::OriginCapable,
8668 other => {
8669 return Err(invalid(
8670 "component",
8671 linked.definition,
8672 format!(
8673 "unsupported `client_origin_permission` `{other}`; expected `participant_only` or `origin_capable`"
8674 ),
8675 ));
8676 }
8677 };
8678 if claimed_origin != linked.component_abi.origin_permission {
8679 let witnessed = match linked.component_abi.origin_permission {
8680 TransportComponentOriginPermission::ParticipantOnly => "participant_only",
8681 TransportComponentOriginPermission::OriginCapable => "origin_capable",
8682 };
8683 return Err(invalid(
8684 "component",
8685 linked.definition,
8686 format!(
8687 "legacy `client_origin_permission` claim `{}` disagrees with the rustc-authenticated component ABI (`{witnessed}`)",
8688 match claimed_origin {
8689 TransportComponentOriginPermission::ParticipantOnly => "participant_only",
8690 TransportComponentOriginPermission::OriginCapable => "origin_capable",
8691 },
8692 ),
8693 ));
8694 }
8695
8696 let render_kind = match linked.component_abi.render_kind {
8697 TransportComponentRenderKind::Sync => RenderKind::WebRenderSync,
8698 TransportComponentRenderKind::Async => RenderKind::WebRender,
8699 };
8700 let origin_permission = match linked.component_abi.origin_permission {
8701 TransportComponentOriginPermission::ParticipantOnly => OriginPermission::ParticipantOnly,
8702 TransportComponentOriginPermission::OriginCapable => OriginPermission::OriginCapable,
8703 };
8704 Ok((render_kind, origin_permission))
8705}
8706
8707fn validate_counts(
8708 definition: TransportDefinitionId,
8709 descriptor: &Map<String, Value>,
8710) -> Result<(), AbiAdapterError> {
8711 let counts = required_object(descriptor, "counts", "component", definition)?;
8712 require_known_fields(
8713 "component descriptor counts",
8714 counts,
8715 &[
8716 "callback_slots",
8717 "crossings",
8718 "exprs",
8719 "fields",
8720 "handlers",
8721 "keyed_collections",
8722 "node_ref_fields",
8723 "node_refs",
8724 "nodes",
8725 "projection_fields",
8726 "prop_sites",
8727 "signals",
8728 "shared_state_provider_sites",
8729 "values",
8730 ],
8731 definition,
8732 )?;
8733 let expected = [
8734 ("fields", "fields"),
8735 ("signals", "signals"),
8736 ("handlers", "handlers"),
8737 ("callback_slots", "callback_slots"),
8738 ("node_refs", "node_refs"),
8739 ("exprs", "exprs"),
8740 ("shared_state_provider_sites", "shared_state_provider_sites"),
8741 ];
8742 for (count_name, array_name) in expected {
8743 let actual = required_u64(counts, count_name, "component", definition)?;
8744 let array_len = required_array(descriptor, array_name, "component", definition)?.len();
8745 if actual != array_len as u64 {
8746 return Err(invalid(
8747 "component",
8748 definition,
8749 format!(
8750 "counts.{count_name} is {actual}, but `{array_name}` has {array_len} entries"
8751 ),
8752 ));
8753 }
8754 }
8755 if let Some(collections) =
8756 optional_array(descriptor, "keyed_collections", "component", definition)?
8757 {
8758 require_exact_u64(
8759 counts,
8760 "keyed_collections",
8761 collections.len() as u64,
8762 "component",
8763 definition,
8764 )?;
8765 } else if counts.contains_key("keyed_collections") {
8766 require_exact_u64(counts, "keyed_collections", 0, "component", definition)?;
8767 }
8768 let inbound = required_object(descriptor, "inbound_inputs", "component", definition)?;
8769 for (count_name, array_name) in [
8770 ("values", "values"),
8771 ("prop_sites", "prop_sites"),
8772 ("crossings", "crossings"),
8773 ("node_ref_fields", "node_ref_fields"),
8774 ("projection_fields", "projection_fields"),
8775 ] {
8776 let actual = required_u64(counts, count_name, "component", definition)?;
8777 let array_len = required_array(inbound, array_name, "component", definition)?.len();
8778 if actual != array_len as u64 {
8779 return Err(invalid(
8780 "component",
8781 definition,
8782 format!(
8783 "counts.{count_name} is {actual}, but `inbound_inputs.{array_name}` has {array_len} entries"
8784 ),
8785 ));
8786 }
8787 }
8788 let view = required_object(descriptor, "view_tree", "component", definition)?;
8789 let nodes = required_array(view, "nodes", "component", definition)?.len();
8790 let count = required_u64(counts, "nodes", "component", definition)?;
8791 if count != nodes as u64 {
8792 return Err(invalid(
8793 "component",
8794 definition,
8795 format!("counts.nodes is {count}, but `view_tree.nodes` has {nodes} entries"),
8796 ));
8797 }
8798 Ok(())
8799}
8800
8801fn validate_view_tree(
8802 definition: TransportDefinitionId,
8803 descriptor: &Map<String, Value>,
8804 direct_component_edges: &[ValidatedDirectComponentEdge],
8805 conditional_bindings: &[LegacyConditionalBinding],
8806 immutable_static_slot_names: &BTreeSet<String>,
8807) -> Result<ValidatedView, AbiAdapterError> {
8808 let tree = required_object(descriptor, "view_tree", "component", definition)?;
8809 require_known_fields("component view tree", tree, &["nodes", "root"], definition)?;
8810 let nodes = required_array(tree, "nodes", "component", definition)?;
8811 let mut kinds = Vec::with_capacity(nodes.len());
8812 let mut direct_component_sites = BTreeSet::new();
8813 let mut immutable_static_slot_counts = BTreeMap::<String, usize>::new();
8814 let mut children = Vec::<Vec<u32>>::with_capacity(nodes.len());
8815 let mut server_sources = Vec::<Option<String>>::with_capacity(nodes.len());
8816 let mut for_loop_nodes = BTreeSet::new();
8817 let mut has_unknown_kind = false;
8818
8819 for (expected_id, record) in nodes.iter().enumerate() {
8820 let mut node_children = Vec::new();
8821 let mut server_source = None;
8822 let record = record.as_object().ok_or_else(|| {
8823 invalid(
8824 "component",
8825 definition,
8826 format!("view_tree.nodes[{expected_id}] must be an object"),
8827 )
8828 })?;
8829 require_known_fields(
8830 "component view-tree node record",
8831 record,
8832 &["id", "node"],
8833 definition,
8834 )?;
8835 let id = required_u64(record, "id", "component", definition)?;
8836 if id != expected_id as u64 {
8837 return Err(invalid(
8838 "component",
8839 definition,
8840 format!("view_tree node IDs must be dense; expected {expected_id}, found {id}"),
8841 ));
8842 }
8843 let node = required_object(record, "node", "component", definition)?;
8844 let kind = required_str(node, "kind", "component", definition)?;
8845 match kind {
8846 "element" => {
8847 require_known_fields(
8848 "element view node",
8849 node,
8850 &[
8851 "children",
8852 "kind",
8853 "payload_attrs",
8854 "server_attrs",
8855 "static_attrs",
8856 "tag",
8857 ],
8858 definition,
8859 )?;
8860 required_str(node, "tag", "component", definition)?;
8861 node_children = required_u32_array(node, "children", definition)?;
8862 required_array(node, "static_attrs", "component", definition)?;
8863 required_array(node, "server_attrs", "component", definition)?;
8864 required_array(node, "payload_attrs", "component", definition)?;
8865 }
8866 "text_binding_slot" => {
8867 require_known_fields("text binding view node", node, &["kind"], definition)?;
8868 }
8869 "static_text" => {
8870 require_known_fields("static text view node", node, &["kind", "text"], definition)?;
8871 required_str(node, "text", "component", definition)?;
8872 }
8873 "server_only" => {
8874 require_known_fields(
8875 "server-only view node",
8876 node,
8877 &["kind", "source", "tokens"],
8878 definition,
8879 )?;
8880 let source = required_str(node, "source", "component", definition)?;
8881 server_source = Some(source.to_owned());
8882 if source == "direct_component_site" {
8883 direct_component_sites.insert(expected_id);
8884 }
8885 let tokens = required_str(node, "tokens", "component", definition)?;
8886 if source == "inferred_simple_ssr" {
8887 if let Some(field_name) = direct_self_field_name_from_tokens(tokens) {
8888 if immutable_static_slot_names.contains(&field_name) {
8889 *immutable_static_slot_counts.entry(field_name).or_default() += 1;
8890 }
8891 }
8892 }
8893 }
8894 "for_loop" => {
8895 require_known_fields(
8896 "server loop view node",
8897 node,
8898 &[
8899 "attrs",
8900 "body_prefix",
8901 "children",
8902 "expr",
8903 "kind",
8904 "label",
8905 "pat",
8906 ],
8907 definition,
8908 )?;
8909 for field in ["attrs", "body_prefix", "expr", "label", "pat"] {
8910 required_str(node, field, "component", definition)?;
8911 }
8912 node_children = required_u32_array(node, "children", definition)?;
8913 for_loop_nodes.insert(expected_id as u32);
8914 }
8915 "unknown" => {
8916 require_known_fields("unknown view node", node, &["kind"], definition)?;
8917 has_unknown_kind = true;
8918 }
8919 other => {
8920 return Err(invalid(
8921 "component",
8922 definition,
8923 format!("unsupported view node kind `{other}` in schema v9"),
8924 ));
8925 }
8926 }
8927 kinds.push(kind.to_owned());
8928 children.push(node_children);
8929 server_sources.push(server_source);
8930 }
8931
8932 let mut claimed_component_sites = BTreeSet::new();
8933 for edge in direct_component_edges {
8934 let site = usize::try_from(edge.site_node).map_err(|_| {
8935 invalid(
8936 "component",
8937 definition,
8938 format!(
8939 "direct component edge {} site node {} exceeds host usize",
8940 edge.local_ordinal, edge.site_node
8941 ),
8942 )
8943 })?;
8944 let expected_source = if edge.composed {
8945 "direct_component_site"
8946 } else {
8947 "explicit_island_boundary"
8948 };
8949 if kinds.get(site).map(String::as_str) != Some("server_only")
8950 || server_sources.get(site).and_then(Option::as_deref) != Some(expected_source)
8951 {
8952 return Err(invalid(
8953 "component",
8954 definition,
8955 format!(
8956 "direct component edge {} claims site node {}, but that node is not a `{expected_source}` server site",
8957 edge.local_ordinal, edge.site_node
8958 ),
8959 ));
8960 }
8961 if !claimed_component_sites.insert(edge.site_node) {
8962 return Err(invalid(
8963 "component",
8964 definition,
8965 format!(
8966 "more than one direct component edge claims schema-v9 site node {}",
8967 edge.site_node
8968 ),
8969 ));
8970 }
8971
8972 let containing_controls =
8973 containing_conditional_controls(edge.site_node, conditional_bindings, &children);
8974 let inside_loop = node_has_ancestor_in(edge.site_node, &for_loop_nodes, &children);
8975 match edge.lifecycle {
8976 ValidatedDirectComponentLifecycle::StaticSingle => {
8977 if inside_loop || !containing_controls.is_empty() {
8978 return Err(invalid(
8979 "component",
8980 definition,
8981 format!(
8982 "direct component edge {} claims `static_single`, but site node {} is structurally controlled",
8983 edge.local_ordinal, edge.site_node
8984 ),
8985 ));
8986 }
8987 }
8988 ValidatedDirectComponentLifecycle::ConditionalSingle {
8989 control, branch, ..
8990 } => {
8991 if inside_loop {
8992 return Err(invalid(
8993 "component",
8994 definition,
8995 format!(
8996 "direct component edge {} claims `conditional_single`, but site node {} is repeated by a loop",
8997 edge.local_ordinal, edge.site_node
8998 ),
8999 ));
9000 }
9001 let expected = vec![(control, branch)];
9002 if containing_controls != expected {
9003 return Err(invalid(
9004 "component",
9005 definition,
9006 format!(
9007 "direct component edge {} conditional lifecycle claims control {control} branch `{}`, but site node {} is contained by {containing_controls:?}",
9008 edge.local_ordinal,
9009 component_lifecycle_branch_name(branch),
9010 edge.site_node,
9011 ),
9012 ));
9013 }
9014 }
9015 ValidatedDirectComponentLifecycle::Repeated => {
9016 if !inside_loop {
9017 return Err(invalid(
9018 "component",
9019 definition,
9020 format!(
9021 "direct component edge {} claims `repeated`, but site node {} has no loop ancestor",
9022 edge.local_ordinal, edge.site_node
9023 ),
9024 ));
9025 }
9026 }
9027 ValidatedDirectComponentLifecycle::UnknownNestedConditionals => {
9028 if inside_loop || containing_controls.len() < 2 {
9029 return Err(invalid(
9030 "component",
9031 definition,
9032 format!(
9033 "direct component edge {} claims unknown nested conditionals, but site node {} is contained by {} conditional control(s){}",
9034 edge.local_ordinal,
9035 edge.site_node,
9036 containing_controls.len(),
9037 if inside_loop { " and a loop" } else { "" },
9038 ),
9039 ));
9040 }
9041 }
9042 }
9043 }
9044
9045 let composed_edge_count = direct_component_edges
9046 .iter()
9047 .filter(|edge| edge.composed)
9048 .count();
9049 if direct_component_sites.len() != composed_edge_count {
9050 return Err(invalid(
9051 "component",
9052 definition,
9053 format!(
9054 "view tree carries {} direct component site(s), but transport carries \
9055 {composed_edge_count} rustc-resolved composed edge(s); every preserved \
9056 composed edge must own exactly one site",
9057 direct_component_sites.len()
9058 ),
9059 ));
9060 }
9061 for field_name in immutable_static_slot_names {
9062 if immutable_static_slot_counts.get(field_name) != Some(&1) {
9063 return Err(invalid(
9064 "component",
9065 definition,
9066 format!(
9067 "immutable static-slot field `{field_name}` must name exactly one \
9068 unconditional `self.{field_name}` server node"
9069 ),
9070 ));
9071 }
9072 }
9073
9074 let root = tree
9075 .get("root")
9076 .ok_or_else(|| invalid("component", definition, "missing `view_tree.root`"))?;
9077 let (root_span, fragment_root) = if root.is_null() {
9078 if !nodes.is_empty() {
9079 return Err(invalid(
9080 "component",
9081 definition,
9082 "view_tree.root is null but nodes are present",
9083 ));
9084 }
9085 (
9086 SpanCardinality::Exact(0),
9087 ComponentFragmentRoot::Unsupported,
9088 )
9089 } else {
9090 let root = root.as_u64().ok_or_else(|| {
9091 invalid(
9092 "component",
9093 definition,
9094 "`view_tree.root` must be null or an unsigned node ID",
9095 )
9096 })?;
9097 let root = usize::try_from(root).map_err(|_| {
9098 invalid(
9099 "component",
9100 definition,
9101 "`view_tree.root` exceeds host usize",
9102 )
9103 })?;
9104 let kind = kinds.get(root).ok_or_else(|| {
9105 invalid(
9106 "component",
9107 definition,
9108 format!("view_tree.root {root} does not name a node"),
9109 )
9110 })?;
9111 let (span, fragment_root) = match kind.as_str() {
9112 "element" => (
9113 SpanCardinality::Exact(1),
9114 ComponentFragmentRoot::ExactOneElement,
9115 ),
9116 "static_text" | "text_binding_slot" => (
9117 SpanCardinality::Exact(1),
9118 ComponentFragmentRoot::Unsupported,
9119 ),
9120 "server_only" if direct_component_sites.contains(&root) => (
9121 SpanCardinality::Exact(1),
9125 ComponentFragmentRoot::ExactOneElement,
9126 ),
9127 "server_only" | "for_loop" | "unknown" => (
9128 SpanCardinality::Unknown {
9129 region: RegionSiteId::new(0),
9130 anchored: false,
9131 },
9132 ComponentFragmentRoot::Unsupported,
9133 ),
9134 _ => unreachable!("all accepted node kinds handled above"),
9135 };
9136 (span, fragment_root)
9137 };
9138 Ok(ValidatedView {
9139 root_span,
9140 fragment_root,
9141 has_unknown_kind,
9142 })
9143}
9144
9145fn containing_conditional_controls(
9146 site: u32,
9147 conditionals: &[LegacyConditionalBinding],
9148 children: &[Vec<u32>],
9149) -> Vec<(u32, ComponentLifecycleBranch)> {
9150 let mut controls = Vec::new();
9151 for conditional in conditionals {
9152 if conditional
9153 .then_children
9154 .iter()
9155 .copied()
9156 .any(|root| subtree_contains_node(root, site, children))
9157 {
9158 controls.push((conditional.control, ComponentLifecycleBranch::Then));
9159 }
9160 if conditional
9161 .else_children
9162 .iter()
9163 .copied()
9164 .any(|root| subtree_contains_node(root, site, children))
9165 {
9166 controls.push((conditional.control, ComponentLifecycleBranch::Else));
9167 }
9168 }
9169 controls
9170}
9171
9172fn subtree_contains_node(root: u32, target: u32, children: &[Vec<u32>]) -> bool {
9173 let mut stack = vec![root];
9174 let mut visited = BTreeSet::new();
9175 while let Some(node) = stack.pop() {
9176 if node == target {
9177 return true;
9178 }
9179 if !visited.insert(node) {
9180 continue;
9181 }
9182 if let Some(node_children) = children.get(node as usize) {
9183 stack.extend(node_children.iter().copied());
9184 }
9185 }
9186 false
9187}
9188
9189fn node_has_ancestor_in(node: u32, ancestors: &BTreeSet<u32>, children: &[Vec<u32>]) -> bool {
9190 ancestors
9191 .iter()
9192 .copied()
9193 .any(|ancestor| ancestor != node && subtree_contains_node(ancestor, node, children))
9194}
9195
9196const fn component_lifecycle_branch_name(branch: ComponentLifecycleBranch) -> &'static str {
9197 match branch {
9198 ComponentLifecycleBranch::Then => "then",
9199 ComponentLifecycleBranch::Else => "else",
9200 }
9201}
9202
9203fn direct_self_field_name_from_tokens(tokens: &str) -> Option<String> {
9204 fn inner(expression: &syn::Expr) -> Option<String> {
9205 let expression = match expression {
9206 syn::Expr::Paren(paren) => return inner(&paren.expr),
9207 syn::Expr::Group(group) => return inner(&group.expr),
9208 syn::Expr::Reference(reference) => return inner(&reference.expr),
9209 expression => expression,
9210 };
9211 let syn::Expr::Field(field) = expression else {
9212 return None;
9213 };
9214 let syn::Expr::Path(base) = field.base.as_ref() else {
9215 return None;
9216 };
9217 if !base.path.is_ident("self") {
9218 return None;
9219 }
9220 let syn::Member::Named(name) = &field.member else {
9221 return None;
9222 };
9223 Some(name.to_string())
9224 }
9225
9226 syn::parse_str::<syn::Expr>(tokens)
9227 .ok()
9228 .as_ref()
9229 .and_then(inner)
9230}
9231
9232fn validate_hydration_constraint(
9233 definition: TransportDefinitionId,
9234 transport: &Map<String, Value>,
9235) -> Result<HydrationConstraint, AbiAdapterError> {
9236 let constraint = required_object(transport, "hydration_constraint", "component", definition)?;
9237 let kind = required_str(constraint, "kind", "component", definition)?;
9238 match kind {
9239 "unconstrained" => {
9240 require_known_fields(
9241 "component hydration constraint",
9242 constraint,
9243 &["kind"],
9244 definition,
9245 )?;
9246 Ok(HydrationConstraint::Unconstrained)
9247 }
9248 "eager" => {
9249 require_known_fields(
9250 "component hydration constraint",
9251 constraint,
9252 &["kind"],
9253 definition,
9254 )?;
9255 Ok(HydrationConstraint::Eager)
9256 }
9257 "visible" => {
9258 require_known_fields(
9259 "component hydration constraint",
9260 constraint,
9261 &["kind"],
9262 definition,
9263 )?;
9264 Ok(HydrationConstraint::Visible)
9265 }
9266 "idle" => {
9267 require_known_fields(
9268 "component hydration constraint",
9269 constraint,
9270 &["kind"],
9271 definition,
9272 )?;
9273 Ok(HydrationConstraint::Idle)
9274 }
9275 "interaction" => {
9276 require_known_fields(
9277 "component hydration constraint",
9278 constraint,
9279 &["event", "kind"],
9280 definition,
9281 )?;
9282 let event = match constraint.get("event") {
9283 Some(Value::Null) => None,
9284 Some(Value::String(event)) if !event.trim().is_empty() => Some(event.clone()),
9285 Some(Value::String(_)) => {
9286 return Err(invalid(
9287 "component",
9288 definition,
9289 "interaction hydration event cannot be empty",
9290 ));
9291 }
9292 Some(_) => {
9293 return Err(invalid(
9294 "component",
9295 definition,
9296 "interaction hydration `event` must be a string or null",
9297 ));
9298 }
9299 None => {
9300 return Err(invalid(
9301 "component",
9302 definition,
9303 "interaction hydration constraint is missing `event`",
9304 ));
9305 }
9306 };
9307 Ok(HydrationConstraint::Interaction { event })
9308 }
9309 "media" => {
9310 require_known_fields(
9311 "component hydration constraint",
9312 constraint,
9313 &["kind", "query"],
9314 definition,
9315 )?;
9316 let query = required_str(constraint, "query", "component", definition)?;
9317 if query.trim().is_empty() {
9318 return Err(invalid(
9319 "component",
9320 definition,
9321 "media hydration query cannot be empty",
9322 ));
9323 }
9324 Ok(HydrationConstraint::Media {
9325 query: query.to_owned(),
9326 })
9327 }
9328 other => Err(invalid(
9329 "component",
9330 definition,
9331 format!("unsupported hydration constraint kind `{other}`"),
9332 )),
9333 }
9334}
9335
9336fn validate_payload_handler_values(
9337 linked: &LinkedTransportComponent,
9338 transport: &Map<String, Value>,
9339 descriptor: &Map<String, Value>,
9340 inbound: &ValidatedInboundInputs,
9341 direct_component_edges: &[ValidatedDirectComponentEdge],
9342 direct_helper_edges: &[ValidatedComponentHelperEdge],
9343) -> Result<Vec<ValidatedPayloadHandlerValue>, AbiAdapterError> {
9344 let sources = required_object(
9345 transport,
9346 "client_value_sources",
9347 "component",
9348 linked.definition,
9349 )?;
9350 require_known_fields(
9351 "component client value sources",
9352 sources,
9353 &["payload_handlers"],
9354 linked.definition,
9355 )?;
9356 let handlers = required_array(sources, "payload_handlers", "component", linked.definition)?;
9357
9358 let referenced = direct_component_edges
9359 .iter()
9360 .flat_map(|edge| &edge.fields)
9361 .filter_map(|field| match field.binding {
9362 ValidatedDirectComponentBinding::LiveCallback {
9363 handler_prelude_local,
9364 ..
9365 } => Some(handler_prelude_local),
9366 _ => None,
9367 })
9368 .collect::<BTreeSet<_>>();
9369 if handlers.len() != referenced.len() {
9370 return Err(invalid(
9371 "component",
9372 linked.definition,
9373 format!(
9374 "payload-handler values must be one-to-one with referenced live callbacks; found {} records for {} referenced prelude bindings",
9375 handlers.len(),
9376 referenced.len(),
9377 ),
9378 ));
9379 }
9380
9381 let mut validated = Vec::with_capacity(handlers.len());
9382 let mut actual_bindings = Vec::with_capacity(handlers.len());
9383 for (index, handler) in handlers.iter().enumerate() {
9384 let handler = handler.as_object().ok_or_else(|| {
9385 invalid(
9386 "component",
9387 linked.definition,
9388 format!("client_value_sources.payload_handlers[{index}] must be an object"),
9389 )
9390 })?;
9391 require_known_fields(
9392 "payload-handler client value",
9393 handler,
9394 &[
9395 "body_ir",
9396 "body_ir_version",
9397 "dependencies",
9398 "kind",
9399 "payload_arity",
9400 "prelude_local_index",
9401 "source_anchor",
9402 ],
9403 linked.definition,
9404 )?;
9405 require_exact_str(
9406 handler,
9407 "kind",
9408 "payload_handler",
9409 "component",
9410 linked.definition,
9411 )?;
9412 require_exact_u64(
9413 handler,
9414 "body_ir_version",
9415 CLIENT_IR_SCHEMA,
9416 "component",
9417 linked.definition,
9418 )?;
9419 let prelude_local_index = checked_u32(
9420 required_u64(
9421 handler,
9422 "prelude_local_index",
9423 "component",
9424 linked.definition,
9425 )?,
9426 "payload-handler prelude_local_index",
9427 linked.definition,
9428 )?;
9429 if actual_bindings
9430 .last()
9431 .is_some_and(|previous| *previous >= prelude_local_index)
9432 {
9433 return Err(invalid(
9434 "component",
9435 linked.definition,
9436 "payload-handler values must be strictly ordered by prelude_local_index",
9437 ));
9438 }
9439 actual_bindings.push(prelude_local_index);
9440
9441 let payload_arity = required_u64(handler, "payload_arity", "component", linked.definition)?;
9442 let payload_arity = match payload_arity {
9443 0 | 1 => payload_arity as u8,
9444 other => {
9445 return Err(invalid(
9446 "component",
9447 linked.definition,
9448 format!(
9449 "payload handler at prelude binding {prelude_local_index} has unsupported payload_arity {other}; expected 0 or 1"
9450 ),
9451 ));
9452 }
9453 };
9454
9455 let source_anchor =
9456 required_object(handler, "source_anchor", "component", linked.definition)?;
9457 require_known_fields(
9458 "payload-handler source anchor",
9459 source_anchor,
9460 &["column", "line"],
9461 linked.definition,
9462 )?;
9463 required_u64(source_anchor, "line", "component", linked.definition)?;
9464 required_u64(source_anchor, "column", "component", linked.definition)?;
9465
9466 let body_json = handler.get("body_ir").ok_or_else(|| {
9467 invalid(
9468 "component",
9469 linked.definition,
9470 "payload-handler client value is missing `body_ir`",
9471 )
9472 })?;
9473 let body = parse_client_block_json(body_json).map_err(|error| {
9474 invalid(
9475 "component",
9476 linked.definition,
9477 format!(
9478 "payload handler at prelude binding {prelude_local_index} has invalid Client IR v3: {error}"
9479 ),
9480 )
9481 })?;
9482 let normalized_body: Value = serde_json::from_str(&client_block_json(&body)).map_err(
9483 |error| {
9484 invalid(
9485 "component",
9486 linked.definition,
9487 format!(
9488 "failed to normalize payload handler at prelude binding {prelude_local_index}: {error}"
9489 ),
9490 )
9491 },
9492 )?;
9493 if normalized_body != *body_json {
9494 return Err(invalid(
9495 "component",
9496 linked.definition,
9497 format!(
9498 "payload handler at prelude binding {prelude_local_index} is not canonical Client IR v3 JSON or contains unknown semantic fields"
9499 ),
9500 ));
9501 }
9502
9503 let dependencies =
9504 collect_client_block_external_dependencies(&body).map_err(|error| {
9505 invalid(
9506 "component",
9507 linked.definition,
9508 format!(
9509 "payload handler at prelude binding {prelude_local_index} is not a closed transportable Client IR block: {error:?}"
9510 ),
9511 )
9512 })?;
9513 let browser_operations = collect_handler_browser_operations(&body).map_err(|error| {
9514 invalid(
9515 "component",
9516 linked.definition,
9517 format!(
9518 "payload handler at prelude binding {prelude_local_index} has invalid browser-operation structure: {error}"
9519 ),
9520 )
9521 })?;
9522 if payload_arity == 0 && dependencies.uses_callback_payload {
9523 return Err(invalid(
9524 "component",
9525 linked.definition,
9526 format!(
9527 "zero-argument payload handler at prelude binding {prelude_local_index} reads CallbackPayload"
9528 ),
9529 ));
9530 }
9531 if dependencies.uses_event_payload {
9532 return Err(invalid(
9533 "component",
9534 linked.definition,
9535 format!(
9536 "payload handler at prelude binding {prelude_local_index} reads DOM EventPayload, but component callbacks receive only CallbackPayload"
9537 ),
9538 ));
9539 }
9540 validate_payload_handler_dependency_claims(
9541 linked.definition,
9542 prelude_local_index,
9543 handler,
9544 &dependencies,
9545 )?;
9546 validate_payload_handler_dependency_ids(
9547 linked.definition,
9548 descriptor,
9549 inbound,
9550 direct_helper_edges,
9551 &dependencies,
9552 )?;
9553
9554 validated.push(ValidatedPayloadHandlerValue {
9555 prelude_local_index,
9556 payload_arity,
9557 body_hash: canonical_legacy_json_hash(
9558 PAYLOAD_HANDLER_CLIENT_IR_HASH_DOMAIN,
9559 &normalized_body,
9560 ),
9561 body_ir: normalized_body,
9562 dependencies,
9563 browser_operations,
9564 });
9565 }
9566
9567 let expected_bindings = referenced.into_iter().collect::<Vec<_>>();
9568 if actual_bindings != expected_bindings {
9569 return Err(invalid(
9570 "component",
9571 linked.definition,
9572 format!(
9573 "payload-handler values do not exactly match referenced live-callback prelude bindings; expected {expected_bindings:?}, found {actual_bindings:?}"
9574 ),
9575 ));
9576 }
9577 Ok(validated)
9578}
9579
9580fn validate_payload_handler_dependency_claims(
9581 definition: TransportDefinitionId,
9582 prelude_local_index: u32,
9583 handler: &Map<String, Value>,
9584 computed: &ClientBlockExternalDependencies,
9585) -> Result<(), AbiAdapterError> {
9586 let claims = required_object(handler, "dependencies", "component", definition)?;
9587 require_known_fields(
9588 "payload-handler dependency claims",
9589 claims,
9590 &[
9591 "callback_slots",
9592 "client_module_calls",
9593 "helper_edges",
9594 "mutations",
9595 "node_refs",
9596 "queries",
9597 "signal_reads",
9598 "signal_writes",
9599 ],
9600 definition,
9601 )?;
9602
9603 for (field, expected) in [
9604 (
9605 "signal_reads",
9606 computed
9607 .signal_reads
9608 .iter()
9609 .map(|id| id.0)
9610 .collect::<Vec<_>>(),
9611 ),
9612 (
9613 "signal_writes",
9614 computed
9615 .signal_writes
9616 .iter()
9617 .map(|id| id.0)
9618 .collect::<Vec<_>>(),
9619 ),
9620 (
9621 "queries",
9622 computed.queries.iter().map(|id| id.0).collect::<Vec<_>>(),
9623 ),
9624 (
9625 "mutations",
9626 computed.mutations.iter().map(|id| id.0).collect::<Vec<_>>(),
9627 ),
9628 (
9629 "node_refs",
9630 computed.node_refs.iter().map(|id| id.0).collect::<Vec<_>>(),
9631 ),
9632 (
9633 "callback_slots",
9634 computed
9635 .callback_slots
9636 .iter()
9637 .map(|id| id.0)
9638 .collect::<Vec<_>>(),
9639 ),
9640 (
9641 "helper_edges",
9642 computed
9643 .helper_edges
9644 .iter()
9645 .map(|id| id.index())
9646 .collect::<Vec<_>>(),
9647 ),
9648 ] {
9649 let actual = required_u32_array(claims, field, definition)?;
9650 if actual != expected {
9651 return Err(invalid(
9652 "component",
9653 definition,
9654 format!(
9655 "payload handler at prelude binding {prelude_local_index} claims {field} {actual:?}, but its Client IR computes {expected:?}"
9656 ),
9657 ));
9658 }
9659 }
9660
9661 let calls = required_array(claims, "client_module_calls", "component", definition)?;
9662 let mut actual_calls = Vec::with_capacity(calls.len());
9663 for (index, call) in calls.iter().enumerate() {
9664 let call = call.as_object().ok_or_else(|| {
9665 invalid(
9666 "component",
9667 definition,
9668 format!("client_module_calls[{index}] must be an object"),
9669 )
9670 })?;
9671 require_known_fields(
9672 "payload-handler client-module call",
9673 call,
9674 &["module", "name"],
9675 definition,
9676 )?;
9677 actual_calls.push(ClientModuleCall {
9678 module: required_str(call, "module", "component", definition)?.to_owned(),
9679 name: required_str(call, "name", "component", definition)?.to_owned(),
9680 });
9681 }
9682 if actual_calls != computed.client_module_calls {
9683 return Err(invalid(
9684 "component",
9685 definition,
9686 format!(
9687 "payload handler at prelude binding {prelude_local_index} claims client-module calls {actual_calls:?}, but its Client IR computes {:?}",
9688 computed.client_module_calls,
9689 ),
9690 ));
9691 }
9692 Ok(())
9693}
9694
9695fn validate_payload_handler_dependency_ids(
9696 definition: TransportDefinitionId,
9697 descriptor: &Map<String, Value>,
9698 inbound: &ValidatedInboundInputs,
9699 direct_helper_edges: &[ValidatedComponentHelperEdge],
9700 dependencies: &ClientBlockExternalDependencies,
9701) -> Result<(), AbiAdapterError> {
9702 validate_descriptor_ids(
9703 definition,
9704 descriptor,
9705 "signals",
9706 dependencies
9707 .signal_reads
9708 .iter()
9709 .chain(&dependencies.signal_writes)
9710 .map(|id| id.0),
9711 )?;
9712 validate_descriptor_ids(
9713 definition,
9714 descriptor,
9715 "queries",
9716 dependencies.queries.iter().map(|id| id.0),
9717 )?;
9718 validate_descriptor_ids(
9719 definition,
9720 descriptor,
9721 "mutations",
9722 dependencies.mutations.iter().map(|id| id.0),
9723 )?;
9724 validate_descriptor_ids(
9725 definition,
9726 descriptor,
9727 "node_refs",
9728 dependencies.node_refs.iter().map(|id| id.0),
9729 )?;
9730 validate_descriptor_ids(
9731 definition,
9732 descriptor,
9733 "callback_slots",
9734 dependencies.callback_slots.iter().map(|id| id.0),
9735 )?;
9736
9737 let callback_slots = required_array(descriptor, "callback_slots", "component", definition)?;
9738 for callback in &dependencies.callback_slots {
9739 let record = callback_slots
9740 .iter()
9741 .filter_map(Value::as_object)
9742 .find(|record| {
9743 record
9744 .get("id")
9745 .and_then(Value::as_u64)
9746 .is_some_and(|id| id == u64::from(callback.0))
9747 })
9748 .expect("validated descriptor callback ID is present");
9749 let name = required_str(record, "name", "component", definition)?;
9750 if !inbound
9751 .fields
9752 .iter()
9753 .any(|field| field.kind == InboundFieldKind::Callback && field.name == name)
9754 {
9755 return Err(invalid(
9756 "component",
9757 definition,
9758 format!(
9759 "payload handler invokes callback slot {} (`{name}`), but it has no matching inbound callback field",
9760 callback.0,
9761 ),
9762 ));
9763 }
9764 }
9765
9766 let helper_ordinals = direct_helper_edges
9767 .iter()
9768 .map(|edge| edge.local_ordinal)
9769 .collect::<BTreeSet<_>>();
9770 for helper in &dependencies.helper_edges {
9771 if !helper_ordinals.contains(&helper.index()) {
9772 return Err(invalid(
9773 "component",
9774 definition,
9775 format!(
9776 "payload handler references helper edge {}, but no relocation-resolved reachable helper has that producer-local ordinal",
9777 helper.index(),
9778 ),
9779 ));
9780 }
9781 }
9782 Ok(())
9783}
9784
9785fn validate_descriptor_ids(
9786 definition: TransportDefinitionId,
9787 descriptor: &Map<String, Value>,
9788 collection: &'static str,
9789 referenced: impl IntoIterator<Item = u32>,
9790) -> Result<(), AbiAdapterError> {
9791 let records = required_array(descriptor, collection, "component", definition)?;
9792 let mut present = BTreeSet::new();
9793 let mut previous = None;
9794 for (index, record) in records.iter().enumerate() {
9795 let record = record.as_object().ok_or_else(|| {
9796 invalid(
9797 "component",
9798 definition,
9799 format!("{collection}[{index}] must be an object"),
9800 )
9801 })?;
9802 let id = checked_u32(
9803 required_u64(record, "id", "component", definition)?,
9804 &format!("{collection} ID"),
9805 definition,
9806 )?;
9807 if previous.is_some_and(|previous| id <= previous) {
9808 return Err(invalid(
9809 "component",
9810 definition,
9811 format!(
9812 "{collection} IDs must be strictly increasing after optimization; \
9813 {collection}[{index}] has ID {id} after {}",
9814 previous.expect("checked above")
9815 ),
9816 ));
9817 }
9818 present.insert(id);
9819 previous = Some(id);
9820 }
9821 for id in referenced {
9822 if !present.contains(&id) {
9823 return Err(invalid(
9824 "component",
9825 definition,
9826 format!("payload-handler dependency references unknown {collection} ID {id}"),
9827 ));
9828 }
9829 }
9830 Ok(())
9831}
9832
9833fn required_u32_array(
9834 object: &Map<String, Value>,
9835 field: &str,
9836 definition: TransportDefinitionId,
9837) -> Result<Vec<u32>, AbiAdapterError> {
9838 required_array(object, field, "component", definition)?
9839 .iter()
9840 .enumerate()
9841 .map(|(index, value)| {
9842 let value = value.as_u64().ok_or_else(|| {
9843 invalid(
9844 "component",
9845 definition,
9846 format!("`{field}[{index}]` must be an unsigned integer"),
9847 )
9848 })?;
9849 checked_u32(value, field, definition)
9850 })
9851 .collect()
9852}
9853
9854fn checked_u32(
9855 value: u64,
9856 label: &str,
9857 definition: TransportDefinitionId,
9858) -> Result<u32, AbiAdapterError> {
9859 u32::try_from(value).map_err(|_| {
9860 invalid(
9861 "component",
9862 definition,
9863 format!("{label} {value} exceeds the canonical u32 ID space"),
9864 )
9865 })
9866}
9867
9868#[derive(Debug)]
9869struct ValidatedDirectComponentEdge {
9870 local_ordinal: u32,
9871 source_edge: TransportRecordId,
9872 composed: bool,
9873 has_rest: bool,
9874 lifecycle: ValidatedDirectComponentLifecycle,
9875 site_node: u32,
9876 fields: Vec<ValidatedDirectComponentField>,
9877}
9878
9879impl ValidatedDirectComponentEdge {
9880 fn has_supported_binding_shape(&self) -> bool {
9881 !self.has_rest
9882 && self.fields.iter().all(|field| {
9883 matches!(
9884 (self.composed, field.binding),
9885 (true, ValidatedDirectComponentBinding::ServerOnly)
9886 | (false, ValidatedDirectComponentBinding::ServerOnly)
9887 | (true, ValidatedDirectComponentBinding::StaticCallback { .. })
9888 | (
9889 false,
9890 ValidatedDirectComponentBinding::StaticCallback { .. }
9891 )
9892 | (true, ValidatedDirectComponentBinding::LiveValue { .. })
9893 | (true, ValidatedDirectComponentBinding::LiveCallback { .. })
9894 | (
9895 true,
9896 ValidatedDirectComponentBinding::ForwardedCallback { .. }
9897 )
9898 | (true, ValidatedDirectComponentBinding::NodeRefHandle { .. })
9899 | (false, ValidatedDirectComponentBinding::StaticSlotExactOne)
9900 )
9901 })
9902 }
9903}
9904
9905#[derive(Clone, Copy, Debug, PartialEq, Eq)]
9906enum ValidatedDirectComponentLifecycle {
9907 StaticSingle,
9908 ConditionalSingle {
9909 control: u32,
9910 predicate_expression: u32,
9911 predicate_graph: TransportRecordId,
9912 branch: ComponentLifecycleBranch,
9913 },
9914 Repeated,
9915 UnknownNestedConditionals,
9916}
9917
9918impl ValidatedDirectComponentLifecycle {
9919 fn transport(self) -> TransportDirectComponentLifecycle {
9920 match self {
9921 Self::StaticSingle => TransportDirectComponentLifecycle::StaticSingle,
9922 Self::ConditionalSingle {
9923 control,
9924 predicate_expression,
9925 predicate_graph,
9926 branch,
9927 } => TransportDirectComponentLifecycle::ConditionalSingle {
9928 control,
9929 predicate_expression,
9930 predicate_graph,
9931 branch: match branch {
9932 ComponentLifecycleBranch::Then => TransportDirectComponentBranch::Then,
9933 ComponentLifecycleBranch::Else => TransportDirectComponentBranch::Else,
9934 },
9935 },
9936 Self::Repeated => TransportDirectComponentLifecycle::Repeated,
9937 Self::UnknownNestedConditionals => {
9938 TransportDirectComponentLifecycle::UnknownNestedConditionals
9939 }
9940 }
9941 }
9942}
9943
9944#[derive(Debug)]
9945struct ValidatedDirectComponentField {
9946 name: String,
9947 binding: ValidatedDirectComponentBinding,
9948 transport_binding: TransportDirectComponentBinding,
9949}
9950
9951#[derive(Clone, Copy, Debug, PartialEq, Eq)]
9952enum ValidatedDirectComponentBinding {
9953 ServerOnly,
9954 StaticSlotExactOne,
9955 StaticCallback {
9956 shape: ComponentCallbackShape,
9957 form: TransportDirectStaticCallbackForm,
9958 },
9959 LiveValue {
9960 signal: u32,
9961 source: TransportDirectLiveValueSource,
9962 },
9963 LiveCallback {
9964 handler_prelude_local: u32,
9965 shape: ComponentCallbackShape,
9966 form: TransportDirectLiveCallbackForm,
9967 },
9968 ForwardedCallback {
9969 parent_field: u32,
9970 shape: ComponentCallbackShape,
9971 },
9972 NodeRefHandle {
9973 node_ref: u32,
9974 },
9975 Unsupported,
9976}
9977
9978impl ValidatedDirectComponentBinding {
9979 fn transport(self) -> TransportDirectComponentBinding {
9980 match self {
9981 Self::ServerOnly => TransportDirectComponentBinding::ServerOnly,
9982 Self::StaticSlotExactOne => TransportDirectComponentBinding::StaticSlotExactOne,
9983 Self::StaticCallback { form, .. } => {
9984 TransportDirectComponentBinding::StaticCallback { form }
9985 }
9986 Self::LiveValue { signal, source } => {
9987 TransportDirectComponentBinding::LiveValue { signal, source }
9988 }
9989 Self::LiveCallback {
9990 handler_prelude_local,
9991 form,
9992 ..
9993 } => TransportDirectComponentBinding::LiveCallback {
9994 handler_prelude_local,
9995 form,
9996 },
9997 Self::ForwardedCallback { .. } => {
9998 unreachable!("a resolved forwarded callback retains a separate raw commitment")
9999 }
10000 Self::NodeRefHandle { node_ref } => {
10001 TransportDirectComponentBinding::NodeRefHandle { node_ref }
10002 }
10003 Self::Unsupported => TransportDirectComponentBinding::Unsupported,
10004 }
10005 }
10006}
10007
10008#[derive(Clone, Copy, Debug, PartialEq, Eq)]
10009enum ValidatedLiveValueSourceForm {
10010 DirectSignalRead,
10011 ClientAlias,
10012 InboundField,
10013}
10014
10015fn validate_component_edge_set(
10016 linked: &LinkedTransportComponent,
10017 transport: &Map<String, Value>,
10018 descriptor: &Map<String, Value>,
10019 input_fingerprint: &str,
10020 projection_roles: &ResolvedProjectionRoles,
10021) -> Result<Vec<ValidatedDirectComponentEdge>, AbiAdapterError> {
10022 let payload_edges = required_array(
10023 transport,
10024 "direct_component_edges",
10025 "component",
10026 linked.definition,
10027 )?;
10028 let payload_ids = payload_edges
10034 .iter()
10035 .enumerate()
10036 .map(|(index, edge)| {
10037 let edge = edge.as_object().ok_or_else(|| {
10038 invalid(
10039 "component",
10040 linked.definition,
10041 format!("direct_component_edges[{index}] must be an object"),
10042 )
10043 })?;
10044 parse_record_field(edge, "source_edge_id", "component", linked.definition)
10045 })
10046 .collect::<Result<Vec<_>, _>>()?;
10047 compare_component_edges(
10048 linked.definition,
10049 "component",
10050 &payload_ids,
10051 &linked.component_edges,
10052 )?;
10053 let mut validated = Vec::with_capacity(payload_edges.len());
10054 for (index, edge) in payload_edges.iter().enumerate() {
10055 let edge = edge.as_object().ok_or_else(|| {
10056 invalid(
10057 "component",
10058 linked.definition,
10059 format!("direct_component_edges[{index}] must be an object"),
10060 )
10061 })?;
10062 require_known_fields(
10063 "component source edge",
10064 edge,
10065 &[
10066 "authored_path",
10067 "boundary",
10068 "fields",
10069 "has_rest",
10070 "identity_authority",
10071 "lifecycle",
10072 "local_ordinal",
10073 "site_node",
10074 "source_anchor",
10075 "source_edge_id",
10076 ],
10077 linked.definition,
10078 )?;
10079 require_exact_str(
10080 edge,
10081 "identity_authority",
10082 "rustc_component_witness_relocation",
10083 "component",
10084 linked.definition,
10085 )?;
10086 let composed = match required_str(edge, "boundary", "component", linked.definition)? {
10087 "composed" => true,
10088 "explicit_island" => false,
10089 other => {
10090 return Err(invalid(
10091 "component",
10092 linked.definition,
10093 format!("unsupported direct component boundary `{other}`"),
10094 ));
10095 }
10096 };
10097 required_str(edge, "authored_path", "component", linked.definition)?;
10098 let has_rest = required_bool(edge, "has_rest", "component", linked.definition)?;
10099 let local_ordinal = u32::try_from(required_u64(
10100 edge,
10101 "local_ordinal",
10102 "component",
10103 linked.definition,
10104 )?)
10105 .map_err(|_| {
10106 invalid(
10107 "component",
10108 linked.definition,
10109 format!("direct_component_edges[{index}].local_ordinal exceeds u32"),
10110 )
10111 })?;
10112 if local_ordinal as usize != index {
10113 return Err(invalid(
10114 "component",
10115 linked.definition,
10116 format!(
10117 "direct component local ordinals must be dense and source ordered; \
10118 expected {index}, found {local_ordinal}"
10119 ),
10120 ));
10121 }
10122 let source_edge = payload_ids[index];
10123 let target = linked
10124 .component_edges
10125 .iter()
10126 .find(|candidate| candidate.source_edge == source_edge)
10127 .map(|candidate| candidate.target)
10128 .ok_or_else(|| {
10129 invalid(
10130 "component",
10131 linked.definition,
10132 format!(
10133 "direct component local ordinal {local_ordinal} source edge {} has no rustc-resolved child definition",
10134 hex_record(&source_edge),
10135 ),
10136 )
10137 })?;
10138 let lifecycle = validate_direct_component_lifecycle(
10139 linked.definition,
10140 required_object(edge, "lifecycle", "component", linked.definition)?,
10141 descriptor,
10142 )?;
10143 let site_node = checked_u32(
10144 required_u64(edge, "site_node", "component", linked.definition)?,
10145 "direct component site node",
10146 linked.definition,
10147 )?;
10148 let mut fields = Vec::new();
10149 let mut field_names = BTreeSet::new();
10150 for (field_index, field) in required_array(edge, "fields", "component", linked.definition)?
10151 .iter()
10152 .enumerate()
10153 {
10154 let field = field.as_object().ok_or_else(|| {
10155 invalid(
10156 "component",
10157 linked.definition,
10158 format!(
10159 "direct_component_edges[{index}].fields[{field_index}] must be an object"
10160 ),
10161 )
10162 })?;
10163 require_known_fields(
10164 "direct component field binding",
10165 field,
10166 &["binding", "field_ordinal", "name"],
10167 linked.definition,
10168 )?;
10169 let field_ordinal =
10170 required_u64(field, "field_ordinal", "component", linked.definition)?;
10171 if field_ordinal != field_index as u64 {
10172 return Err(invalid(
10173 "component",
10174 linked.definition,
10175 format!(
10176 "direct component field ordinals must be dense and source ordered; \
10177 expected {field_index}, found {field_ordinal}"
10178 ),
10179 ));
10180 }
10181 let name = required_str(field, "name", "component", linked.definition)?.to_owned();
10182 if !field_names.insert(name.clone()) {
10183 return Err(invalid(
10184 "component",
10185 linked.definition,
10186 format!("direct component edge contains duplicate field `{name}`"),
10187 ));
10188 }
10189 let binding = required_object(field, "binding", "component", linked.definition)?;
10190 let (mut binding, transport_binding) =
10191 validate_direct_component_binding_with_projection_roles(
10192 linked.definition,
10193 binding,
10194 projection_roles,
10195 )?;
10196 if matches!(
10203 binding,
10204 ValidatedDirectComponentBinding::StaticCallback {
10205 shape: ComponentCallbackShape::Optional,
10206 form: TransportDirectStaticCallbackForm::None,
10207 }
10208 ) {
10209 match projection_roles.field_by_name(target, &name) {
10210 Some(ResolvedProjectionRole::Callback(InboundCallbackShape::Optional)) => {}
10211 Some(ResolvedProjectionRole::Callback(InboundCallbackShape::Required)) => {
10212 return Err(invalid(
10213 "component",
10214 linked.definition,
10215 format!(
10216 "direct component local ordinal {local_ordinal} field `{name}` uses literal `None`, but rustc-resolved child definition {target:?} declares a required callback",
10217 ),
10218 ));
10219 }
10220 Some(
10221 ResolvedProjectionRole::ServerOnly
10222 | ResolvedProjectionRole::Value
10223 | ResolvedProjectionRole::NodeRef,
10224 ) => {
10225 binding = ValidatedDirectComponentBinding::ServerOnly;
10226 }
10227 None => {
10228 return Err(invalid(
10229 "component",
10230 linked.definition,
10231 format!(
10232 "direct component local ordinal {local_ordinal} field `{name}` uses literal `None`, but the exact field role for rustc-resolved child definition {target:?} is unavailable\nhelp: adapt the complete transport plan so the child field can be resolved before assigning semantic callback behavior",
10233 ),
10234 ));
10235 }
10236 }
10237 }
10238 if let ValidatedDirectComponentBinding::LiveValue { signal, .. } = binding {
10239 validate_legacy_signal_source(linked.definition, descriptor, signal)?;
10240 }
10241 if let ValidatedDirectComponentBinding::NodeRefHandle { node_ref } = binding {
10242 validate_legacy_node_ref_source(linked.definition, descriptor, node_ref)?;
10243 }
10244 if let TransportDirectComponentBinding::DeferredProjection {
10245 field: parent_field,
10246 signal,
10247 node_ref,
10248 } = transport_binding
10249 {
10250 validate_legacy_signal_source(linked.definition, descriptor, signal)?;
10251 validate_legacy_node_ref_source(linked.definition, descriptor, node_ref)?;
10252 let inbound =
10253 required_object(descriptor, "inbound_inputs", "component", linked.definition)?;
10254 let exact_projection =
10255 required_array(inbound, "projection_fields", "component", linked.definition)?
10256 .iter()
10257 .filter_map(Value::as_object)
10258 .filter(|projection| {
10259 required_u64(projection, "field_id", "component", linked.definition)
10260 .ok()
10261 == Some(u64::from(parent_field))
10262 && required_u64(
10263 projection,
10264 "signal_id",
10265 "component",
10266 linked.definition,
10267 )
10268 .ok()
10269 == Some(u64::from(signal))
10270 && required_u64(
10271 projection,
10272 "node_ref_id",
10273 "component",
10274 linked.definition,
10275 )
10276 .ok()
10277 == Some(u64::from(node_ref))
10278 })
10279 .count();
10280 if exact_projection != 1 {
10281 return Err(invalid(
10282 "component",
10283 linked.definition,
10284 format!(
10285 "deferred direct field `{name}` does not resolve to exactly one authenticated parent projection"
10286 ),
10287 ));
10288 }
10289 }
10290 if !composed
10291 && matches!(
10292 binding,
10293 ValidatedDirectComponentBinding::LiveValue { .. }
10294 | ValidatedDirectComponentBinding::LiveCallback { .. }
10295 | ValidatedDirectComponentBinding::ForwardedCallback { .. }
10296 | ValidatedDirectComponentBinding::NodeRefHandle { .. }
10297 )
10298 {
10299 return Err(invalid(
10300 "component",
10301 linked.definition,
10302 format!(
10303 "direct component field `{name}` carries a live binding across an explicit island boundary"
10304 ),
10305 ));
10306 }
10307 fields.push(ValidatedDirectComponentField {
10308 name,
10309 binding,
10310 transport_binding,
10311 });
10312 }
10313 if fields.iter().any(|field| {
10314 matches!(
10315 field.binding,
10316 ValidatedDirectComponentBinding::NodeRefHandle { .. }
10317 )
10318 }) && (!composed
10319 || has_rest
10320 || !matches!(lifecycle, ValidatedDirectComponentLifecycle::StaticSingle))
10321 {
10322 return Err(invalid(
10323 "component",
10324 linked.definition,
10325 format!(
10326 "direct component edge {local_ordinal} carries a NodeRef handle, but NodeRef handles require one non-rest static composed edge"
10327 ),
10328 ));
10329 }
10330 let source_anchor = required_object(edge, "source_anchor", "component", linked.definition)?;
10331 require_known_fields(
10332 "direct component source anchor",
10333 source_anchor,
10334 &["column", "line"],
10335 linked.definition,
10336 )?;
10337 required_u64(source_anchor, "line", "component", linked.definition)?;
10338 required_u64(source_anchor, "column", "component", linked.definition)?;
10339 let field_commitments = fields
10340 .iter()
10341 .map(|field| TransportDirectComponentField {
10342 name: &field.name,
10343 binding: field.transport_binding,
10344 })
10345 .collect::<Vec<_>>();
10346 let expected_source_edge = component_source_edge_id(
10347 input_fingerprint,
10348 local_ordinal,
10349 &TransportDirectComponentEdge {
10350 boundary: if composed {
10351 TransportDirectComponentBoundary::Composed
10352 } else {
10353 TransportDirectComponentBoundary::ExplicitIsland
10354 },
10355 site_node,
10356 lifecycle: lifecycle.transport(),
10357 has_rest,
10358 fields: &field_commitments,
10359 },
10360 );
10361 if source_edge != expected_source_edge {
10362 return Err(invalid(
10363 "component",
10364 linked.definition,
10365 format!(
10366 "direct component local ordinal {local_ordinal} has source edge {}, \
10367 expected deterministic edge {}",
10368 hex_record(&source_edge),
10369 hex_record(&expected_source_edge),
10370 ),
10371 ));
10372 }
10373 validated.push(ValidatedDirectComponentEdge {
10374 local_ordinal,
10375 source_edge,
10376 composed,
10377 has_rest,
10378 lifecycle,
10379 site_node,
10380 fields,
10381 });
10382 }
10383 Ok(validated)
10384}
10385
10386fn validate_direct_component_lifecycle(
10387 definition: TransportDefinitionId,
10388 lifecycle: &Map<String, Value>,
10389 descriptor: &Map<String, Value>,
10390) -> Result<ValidatedDirectComponentLifecycle, AbiAdapterError> {
10391 let kind = required_str(lifecycle, "kind", "component", definition)?;
10392 match kind {
10393 "static_single" => {
10394 require_known_fields(
10395 "static-single direct component lifecycle",
10396 lifecycle,
10397 &["kind"],
10398 definition,
10399 )?;
10400 Ok(ValidatedDirectComponentLifecycle::StaticSingle)
10401 }
10402 "conditional_single" => {
10403 require_known_fields(
10404 "conditional-single direct component lifecycle",
10405 lifecycle,
10406 &["branch", "control", "kind", "predicate_expression"],
10407 definition,
10408 )?;
10409 let control = checked_u32(
10410 required_u64(lifecycle, "control", "component", definition)?,
10411 "conditional component lifecycle control",
10412 definition,
10413 )?;
10414 let branch = match required_str(lifecycle, "branch", "component", definition)? {
10415 "then" => ComponentLifecycleBranch::Then,
10416 "else" => ComponentLifecycleBranch::Else,
10417 other => {
10418 return Err(invalid(
10419 "component",
10420 definition,
10421 format!(
10422 "conditional component lifecycle branch must be `then` or `else`, found `{other}`"
10423 ),
10424 ));
10425 }
10426 };
10427 let predicate_expression = checked_u32(
10428 required_u64(lifecycle, "predicate_expression", "component", definition)?,
10429 "conditional component lifecycle predicate expression",
10430 definition,
10431 )?;
10432 let conditionals = required_array(
10433 required_object(descriptor, "bindings", "component", definition)?,
10434 "conditionals",
10435 "component",
10436 definition,
10437 )?;
10438 let conditional = conditionals.get(control as usize).ok_or_else(|| {
10439 invalid(
10440 "component",
10441 definition,
10442 format!("conditional component lifecycle claims unknown control {control}"),
10443 )
10444 })?;
10445 let conditional = conditional.as_object().ok_or_else(|| {
10446 invalid(
10447 "component",
10448 definition,
10449 format!("conditional binding {control} must be an object"),
10450 )
10451 })?;
10452 let graph_predicate = checked_u32(
10453 required_u64(conditional, "condition", "component", definition)?,
10454 "conditional binding predicate expression",
10455 definition,
10456 )?;
10457 if predicate_expression != graph_predicate {
10458 return Err(invalid(
10459 "component",
10460 definition,
10461 format!(
10462 "conditional component lifecycle control {control} claims predicate expression \
10463 {predicate_expression}, but the analyzed conditional graph names {graph_predicate}"
10464 ),
10465 ));
10466 }
10467 let predicate_graph = component_lifecycle_predicate_graph_commitment(
10471 descriptor,
10472 control,
10473 predicate_expression,
10474 );
10475 Ok(ValidatedDirectComponentLifecycle::ConditionalSingle {
10476 control,
10477 predicate_expression,
10478 predicate_graph,
10479 branch,
10480 })
10481 }
10482 "repeated" => {
10483 require_known_fields(
10484 "repeated direct component lifecycle",
10485 lifecycle,
10486 &["kind"],
10487 definition,
10488 )?;
10489 Ok(ValidatedDirectComponentLifecycle::Repeated)
10490 }
10491 "unknown" => {
10492 require_known_fields(
10493 "unknown direct component lifecycle",
10494 lifecycle,
10495 &["kind", "reason"],
10496 definition,
10497 )?;
10498 require_exact_str(
10499 lifecycle,
10500 "reason",
10501 "nested_conditionals",
10502 "component",
10503 definition,
10504 )?;
10505 Ok(ValidatedDirectComponentLifecycle::UnknownNestedConditionals)
10506 }
10507 other => Err(invalid(
10508 "component",
10509 definition,
10510 format!("unsupported direct component lifecycle kind `{other}`"),
10511 )),
10512 }
10513}
10514
10515fn validate_legacy_signal_source(
10516 definition: TransportDefinitionId,
10517 descriptor: &Map<String, Value>,
10518 signal: u32,
10519) -> Result<(), AbiAdapterError> {
10520 let signals = required_array(descriptor, "signals", "component", definition)?;
10521 let record = signals
10522 .iter()
10523 .filter_map(Value::as_object)
10524 .find(|record| {
10525 record
10526 .get("id")
10527 .and_then(Value::as_u64)
10528 .is_some_and(|id| id == u64::from(signal))
10529 })
10530 .ok_or_else(|| {
10531 invalid(
10532 "component",
10533 definition,
10534 format!("live component value refers to unknown legacy signal {signal}"),
10535 )
10536 })?;
10537 require_exact_u64(record, "id", signal as u64, "component", definition)
10538}
10539
10540fn validate_legacy_node_ref_source(
10541 definition: TransportDefinitionId,
10542 descriptor: &Map<String, Value>,
10543 node_ref: u32,
10544) -> Result<(), AbiAdapterError> {
10545 let node_refs = required_array(descriptor, "node_refs", "component", definition)?;
10546 let record = node_refs
10547 .iter()
10548 .filter_map(Value::as_object)
10549 .find(|record| {
10550 record
10551 .get("id")
10552 .and_then(Value::as_u64)
10553 .is_some_and(|id| id == u64::from(node_ref))
10554 })
10555 .ok_or_else(|| {
10556 invalid(
10557 "component",
10558 definition,
10559 format!("NodeRef handle refers to unknown legacy node ref {node_ref}"),
10560 )
10561 })?;
10562 require_exact_u64(record, "id", node_ref as u64, "component", definition)
10563}
10564
10565fn validate_direct_component_binding_with_projection_roles(
10566 definition: TransportDefinitionId,
10567 binding: &Map<String, Value>,
10568 projection_roles: &ResolvedProjectionRoles,
10569) -> Result<
10570 (
10571 ValidatedDirectComponentBinding,
10572 TransportDirectComponentBinding,
10573 ),
10574 AbiAdapterError,
10575> {
10576 let kind = required_str(binding, "kind", "component", definition)?;
10577 let proof = required_str(binding, "proof", "component", definition)?;
10578 let validated = match kind {
10579 "server_only" => {
10580 require_known_fields(
10581 "direct server-only component field binding",
10582 binding,
10583 &["kind", "proof"],
10584 definition,
10585 )?;
10586 require_exact_binding_proof(
10587 definition,
10588 kind,
10589 proof,
10590 "visible_syntax_has_no_client_dependency_v1",
10591 )?;
10592 Ok(ValidatedDirectComponentBinding::ServerOnly)
10593 }
10594 "immutable_static_slot_exact_one" => {
10595 require_known_fields(
10596 "direct immutable static-slot component field binding",
10597 binding,
10598 &["kind", "proof"],
10599 definition,
10600 )?;
10601 require_exact_binding_proof(
10602 definition,
10603 kind,
10604 proof,
10605 "direct_fully_static_single_root_html_macro_v1",
10606 )?;
10607 Ok(ValidatedDirectComponentBinding::StaticSlotExactOne)
10608 }
10609 "static_callback" => {
10610 require_known_fields(
10611 "direct static callback component field binding",
10612 binding,
10613 &["callback_shape", "kind", "proof", "source_form"],
10614 definition,
10615 )?;
10616 let shape = parse_direct_callback_shape(definition, binding)?;
10617 let source_form = required_str(binding, "source_form", "component", definition)?;
10618 let (expected, form) = match (source_form, shape) {
10619 ("none", ComponentCallbackShape::Optional) => (
10620 "literal_none_callback_candidate_v1",
10621 TransportDirectStaticCallbackForm::None,
10622 ),
10623 ("noop_handler", ComponentCallbackShape::Required) => (
10624 "rsjs_noop_handler_v1",
10625 TransportDirectStaticCallbackForm::NoopHandler,
10626 ),
10627 ("some_noop_handler", ComponentCallbackShape::Optional) => (
10628 "some_rsjs_noop_handler_v1",
10629 TransportDirectStaticCallbackForm::SomeNoopHandler,
10630 ),
10631 _ => {
10632 return Err(invalid(
10633 "component",
10634 definition,
10635 format!(
10636 "static callback source form `{source_form}` is incompatible with callback shape `{}`",
10637 direct_callback_shape_name(shape)
10638 ),
10639 ));
10640 }
10641 };
10642 require_exact_binding_proof(definition, kind, proof, expected)?;
10643 Ok(ValidatedDirectComponentBinding::StaticCallback { shape, form })
10644 }
10645 "live_value" => {
10646 require_known_fields(
10647 "direct live-value component field binding",
10648 binding,
10649 &["kind", "parent_source", "proof", "source_form"],
10650 definition,
10651 )?;
10652 let (source_form, source) =
10653 match required_str(binding, "source_form", "component", definition)? {
10654 "direct_signal_read" => (
10655 ValidatedLiveValueSourceForm::DirectSignalRead,
10656 TransportDirectLiveValueSource::DirectSignalRead,
10657 ),
10658 "client_alias" => (
10659 ValidatedLiveValueSourceForm::ClientAlias,
10660 TransportDirectLiveValueSource::ClientAlias,
10661 ),
10662 "inbound_field" => (
10663 ValidatedLiveValueSourceForm::InboundField,
10664 TransportDirectLiveValueSource::InboundField,
10665 ),
10666 other => {
10667 return Err(invalid(
10668 "component",
10669 definition,
10670 format!("unsupported live-value source_form `{other}`"),
10671 ));
10672 }
10673 };
10674 let expected = match source_form {
10675 ValidatedLiveValueSourceForm::DirectSignalRead => "exact_signal_read_v1",
10676 ValidatedLiveValueSourceForm::ClientAlias => {
10677 "client_alias_resolves_to_exact_signal_read_v1"
10678 }
10679 ValidatedLiveValueSourceForm::InboundField => {
10680 "inbound_live_field_reuses_exact_live_signal_v1"
10681 }
10682 };
10683 require_exact_binding_proof(definition, kind, proof, expected)?;
10684 let signal =
10685 parse_direct_parent_source(definition, binding, "legacy_signal", "live-value")?;
10686 Ok(ValidatedDirectComponentBinding::LiveValue { signal, source })
10687 }
10688 "live_callback" => {
10689 require_known_fields(
10690 "direct live callback component field binding",
10691 binding,
10692 &["callback_shape", "kind", "parent_source", "proof"],
10693 definition,
10694 )?;
10695 let shape = parse_direct_callback_shape(definition, binding)?;
10696 let expected = match shape {
10697 ComponentCallbackShape::Required => "payload_handler_prelude_binding_v1",
10698 ComponentCallbackShape::Optional => "some_payload_handler_prelude_binding_v1",
10699 };
10700 require_exact_binding_proof(definition, kind, proof, expected)?;
10701 let handler_prelude_local = parse_direct_parent_source(
10702 definition,
10703 binding,
10704 "payload_handler_prelude_binding",
10705 "live-callback",
10706 )?;
10707 Ok(ValidatedDirectComponentBinding::LiveCallback {
10708 handler_prelude_local,
10709 shape,
10710 form: match shape {
10711 ComponentCallbackShape::Required => TransportDirectLiveCallbackForm::Handler,
10712 ComponentCallbackShape::Optional => {
10713 TransportDirectLiveCallbackForm::SomeHandler
10714 }
10715 },
10716 })
10717 }
10718 "node_ref_handle" => {
10719 require_known_fields(
10720 "direct NodeRef handle component field binding",
10721 binding,
10722 &["handle_kind", "kind", "parent_source", "proof"],
10723 definition,
10724 )?;
10725 require_exact_str(binding, "handle_kind", "node_ref", "component", definition)?;
10726 require_exact_binding_proof(definition, kind, proof, "exact_node_ref_handle_alias_v1")?;
10727 let node_ref = parse_direct_parent_source(
10728 definition,
10729 binding,
10730 "legacy_node_ref",
10731 "NodeRef-handle",
10732 )?;
10733 Ok(ValidatedDirectComponentBinding::NodeRefHandle { node_ref })
10734 }
10735 "deferred_projection" => {
10736 require_known_fields(
10737 "deferred direct component field projection",
10738 binding,
10739 &[
10740 "kind",
10741 "latent_node_ref_id",
10742 "latent_signal_id",
10743 "parent_field_id",
10744 "proof",
10745 ],
10746 definition,
10747 )?;
10748 require_exact_binding_proof(
10749 definition,
10750 kind,
10751 proof,
10752 "rustc_linked_child_field_resolves_exact_projection_role_v1",
10753 )?;
10754 let parent_field = checked_u32(
10755 required_u64(binding, "parent_field_id", "component", definition)?,
10756 "deferred parent field ID",
10757 definition,
10758 )?;
10759 let signal = checked_u32(
10760 required_u64(binding, "latent_signal_id", "component", definition)?,
10761 "deferred latent signal ID",
10762 definition,
10763 )?;
10764 let node_ref = checked_u32(
10765 required_u64(binding, "latent_node_ref_id", "component", definition)?,
10766 "deferred latent NodeRef ID",
10767 definition,
10768 )?;
10769 let resolved = projection_roles.field(definition, parent_field).ok_or_else(|| {
10770 invalid(
10771 "component",
10772 definition,
10773 format!(
10774 "deferred projection field {parent_field} requires complete transport-plan adaptation"
10775 ),
10776 )
10777 })?;
10778 let concrete = match resolved {
10779 ResolvedProjectionRole::ServerOnly => ValidatedDirectComponentBinding::ServerOnly,
10780 ResolvedProjectionRole::Value => ValidatedDirectComponentBinding::LiveValue {
10781 signal,
10782 source: TransportDirectLiveValueSource::InboundField,
10783 },
10784 ResolvedProjectionRole::Callback(shape) => {
10785 ValidatedDirectComponentBinding::ForwardedCallback {
10786 parent_field,
10787 shape: match shape {
10788 InboundCallbackShape::Required => ComponentCallbackShape::Required,
10789 InboundCallbackShape::Optional => ComponentCallbackShape::Optional,
10790 },
10791 }
10792 }
10793 ResolvedProjectionRole::NodeRef => {
10794 ValidatedDirectComponentBinding::NodeRefHandle { node_ref }
10795 }
10796 };
10797 return Ok((
10798 concrete,
10799 TransportDirectComponentBinding::DeferredProjection {
10800 field: parent_field,
10801 signal,
10802 node_ref,
10803 },
10804 ));
10805 }
10806 "unsupported" => {
10807 require_known_fields(
10808 "unsupported direct component field binding",
10809 binding,
10810 &["kind", "proof"],
10811 definition,
10812 )?;
10813 require_exact_binding_proof(definition, kind, proof, "not_proven")?;
10814 Ok(ValidatedDirectComponentBinding::Unsupported)
10815 }
10816 _ => Err(invalid(
10817 "component",
10818 definition,
10819 format!("unsupported direct component field binding kind `{kind}`"),
10820 )),
10821 }?;
10822 let transport = validated.transport();
10823 Ok((validated, transport))
10824}
10825
10826#[cfg(test)]
10827fn validate_direct_component_binding(
10828 definition: TransportDefinitionId,
10829 binding: &Map<String, Value>,
10830) -> Result<ValidatedDirectComponentBinding, AbiAdapterError> {
10831 validate_direct_component_binding_with_projection_roles(
10832 definition,
10833 binding,
10834 &ResolvedProjectionRoles::default(),
10835 )
10836 .map(|(binding, _)| binding)
10837}
10838
10839fn require_exact_binding_proof(
10840 definition: TransportDefinitionId,
10841 kind: &str,
10842 actual: &str,
10843 expected: &str,
10844) -> Result<(), AbiAdapterError> {
10845 if actual == expected {
10846 Ok(())
10847 } else {
10848 Err(invalid(
10849 "component",
10850 definition,
10851 format!(
10852 "direct component field binding `{kind}` requires proof `{expected}`, found `{actual}`"
10853 ),
10854 ))
10855 }
10856}
10857
10858fn parse_direct_callback_shape(
10859 definition: TransportDefinitionId,
10860 binding: &Map<String, Value>,
10861) -> Result<ComponentCallbackShape, AbiAdapterError> {
10862 match required_str(binding, "callback_shape", "component", definition)? {
10863 "required" => Ok(ComponentCallbackShape::Required),
10864 "optional" => Ok(ComponentCallbackShape::Optional),
10865 other => Err(invalid(
10866 "component",
10867 definition,
10868 format!("unsupported direct callback shape `{other}`"),
10869 )),
10870 }
10871}
10872
10873fn direct_callback_shape_name(shape: ComponentCallbackShape) -> &'static str {
10874 match shape {
10875 ComponentCallbackShape::Required => "required",
10876 ComponentCallbackShape::Optional => "optional",
10877 }
10878}
10879
10880fn parse_direct_parent_source(
10881 definition: TransportDefinitionId,
10882 binding: &Map<String, Value>,
10883 expected_namespace: &str,
10884 binding_kind: &str,
10885) -> Result<u32, AbiAdapterError> {
10886 let source = required_object(binding, "parent_source", "component", definition)?;
10887 require_known_fields(
10888 "direct component parent source",
10889 source,
10890 &["id", "namespace"],
10891 definition,
10892 )?;
10893 require_exact_str(
10894 source,
10895 "namespace",
10896 expected_namespace,
10897 "component",
10898 definition,
10899 )?;
10900 u32::try_from(required_u64(source, "id", "component", definition)?).map_err(|_| {
10901 invalid(
10902 "component",
10903 definition,
10904 format!("{binding_kind} parent source ID exceeds u32"),
10905 )
10906 })
10907}
10908
10909#[derive(Clone, Debug)]
10910struct ActiveSharedStateStore {
10911 store_id: u32,
10912 type_key: String,
10913 schema_abi: SemanticHash,
10914}
10915
10916#[derive(Clone, Debug, Default)]
10917struct ActiveSharedStatePlan {
10918 stores: Vec<ActiveSharedStateStore>,
10919 operation_shapes_supported: bool,
10920}
10921
10922#[derive(Clone, Debug)]
10923struct DecodedSharedStateDefinition {
10924 type_key: String,
10925 schema_abi: SemanticHash,
10926 fields: BTreeSet<String>,
10927}
10928
10929fn resolve_shared_state_definition(
10930 context: &AbiAdapterContext,
10931 component: TransportDefinitionId,
10932 target: TransportDefinitionId,
10933 usage: &str,
10934) -> Result<DecodedSharedStateDefinition, AbiAdapterError> {
10935 let raw = context
10936 .shared_state_definitions
10937 .get(&target)
10938 .ok_or_else(|| {
10939 invalid(
10940 "component",
10941 component,
10942 format!("{usage} resolves to missing definition {target:?}"),
10943 )
10944 })?;
10945 let expected_schema_hash = shared_state_schema_abi_hash(&raw.schema_abi);
10946 if raw.schema_abi_hash != expected_schema_hash {
10947 return Err(invalid(
10948 "component",
10949 component,
10950 format!(
10951 "SharedState definition {target:?} has schema ABI hash {}, but its canonical bytes hash to {}",
10952 hex_record(&raw.schema_abi_hash),
10953 hex_record(&expected_schema_hash),
10954 ),
10955 ));
10956 }
10957 let schema = decode_shared_state_schema_abi(&raw.schema_abi).map_err(|error| {
10958 invalid(
10959 "component",
10960 component,
10961 format!(
10962 "SharedState definition {target:?} has an invalid canonical schema ABI: {error}"
10963 ),
10964 )
10965 })?;
10966 if schema.runtime_abi_version != SHARED_STATE_RUNTIME_ABI_VERSION {
10967 return Err(invalid(
10968 "component",
10969 component,
10970 format!(
10971 "SharedState definition {target:?} uses runtime ABI {}, but this compiler supports {}",
10972 schema.runtime_abi_version, SHARED_STATE_RUNTIME_ABI_VERSION,
10973 ),
10974 ));
10975 }
10976 match schema.resolution {
10977 SharedStateSchemaAbiResolution::Resolved => {}
10978 SharedStateSchemaAbiResolution::Unresolved(
10979 SharedStateSchemaUnresolvedReason::NestedClientProps,
10980 ) => {
10981 return Err(invalid(
10982 "component",
10983 component,
10984 format!(
10985 "SharedState definition {target:?} is unresolved because a field contains nested ClientProps"
10986 ),
10987 ));
10988 }
10989 }
10990 Ok(DecodedSharedStateDefinition {
10991 type_key: raw.type_key.clone(),
10992 schema_abi: SemanticHash::from_bytes(raw.schema_abi_hash),
10993 fields: schema.fields.into_iter().map(|field| field.name).collect(),
10994 })
10995}
10996
10997impl ActiveSharedStatePlan {
10998 fn is_active(&self) -> bool {
10999 !self.stores.is_empty()
11000 }
11001}
11002
11003fn resolve_active_shared_state_plan(
11004 context: &AbiAdapterContext,
11005 definition: TransportDefinitionId,
11006 graph: &LegacyClientGraph,
11007 acquisitions: &BTreeMap<u32, TransportDefinitionId>,
11008) -> Result<ActiveSharedStatePlan, AbiAdapterError> {
11009 let mut decoded_definitions = BTreeMap::new();
11010 let mut active_stores = BTreeMap::new();
11011 let signals = graph
11012 .signals
11013 .iter()
11014 .map(|signal| (signal.id, signal))
11015 .collect::<BTreeMap<_, _>>();
11016
11017 for signal in &graph.signals {
11018 let Some(field) = &signal.shared_field else {
11019 continue;
11020 };
11021 let target = acquisitions.get(&field.store).copied().ok_or_else(|| {
11022 invalid(
11023 "component",
11024 definition,
11025 format!(
11026 "active SharedState signal {} refers to store {}, but no exact acquisition target exists",
11027 signal.id, field.store,
11028 ),
11029 )
11030 })?;
11031 let decoded = if let Some(decoded) = decoded_definitions.get(&target) {
11032 decoded
11033 } else {
11034 let decoded = resolve_shared_state_definition(
11035 context,
11036 definition,
11037 target,
11038 &format!("active SharedState store {}", field.store),
11039 )?;
11040 decoded_definitions.insert(target, decoded);
11041 decoded_definitions
11042 .get(&target)
11043 .expect("the decoded SharedState definition was just inserted")
11044 };
11045 if !decoded.fields.contains(&field.field) {
11046 return Err(invalid(
11047 "component",
11048 definition,
11049 format!(
11050 "SharedState signal {} refers to field `{}` on store {}, but definition {target:?} does not contain that field",
11051 signal.id, field.field, field.store,
11052 ),
11053 ));
11054 }
11055 active_stores
11056 .entry(field.store)
11057 .or_insert_with(|| ActiveSharedStateStore {
11058 store_id: field.store,
11059 type_key: decoded.type_key.clone(),
11060 schema_abi: decoded.schema_abi,
11061 });
11062 }
11063
11064 let mut operation_shapes_supported = true;
11065 for expression in &graph.expressions {
11066 operation_shapes_supported &= validate_shared_state_operation_shapes(
11067 definition,
11068 &expression.client_operations,
11069 &signals,
11070 )?;
11071 }
11072 let bound_handlers = graph
11073 .bindings
11074 .events
11075 .iter()
11076 .map(|binding| binding.handler)
11077 .collect::<BTreeSet<_>>();
11078 for handler in &graph.handlers {
11079 if bound_handlers.contains(&handler.id) {
11080 operation_shapes_supported &= validate_shared_state_operation_shapes(
11081 definition,
11082 &handler.client_operations,
11083 &signals,
11084 )?;
11085 }
11086 }
11087
11088 Ok(ActiveSharedStatePlan {
11089 stores: active_stores.into_values().collect(),
11090 operation_shapes_supported,
11091 })
11092}
11093
11094fn validate_shared_state_operation_shapes(
11095 definition: TransportDefinitionId,
11096 operations: &[LegacyClientOperation],
11097 signals: &BTreeMap<u32, &LegacySignal>,
11098) -> Result<bool, AbiAdapterError> {
11099 let mut supported = true;
11100 for (index, operation) in operations.iter().enumerate() {
11101 let (signal_id, field) = match &operation.kind {
11102 LegacyClientOperationKind::SharedRead { signal, field }
11103 | LegacyClientOperationKind::SharedSet { signal, field }
11104 | LegacyClientOperationKind::SharedUpdate { signal, field } => (*signal, field),
11105 _ => continue,
11106 };
11107 let signal = signals.get(&signal_id).copied().ok_or_else(|| {
11108 invalid(
11109 "component",
11110 definition,
11111 format!("SharedState operation refers to missing signal {signal_id}"),
11112 )
11113 })?;
11114 if signal.shared_field.as_ref() != Some(field) {
11115 return Err(invalid(
11116 "component",
11117 definition,
11118 format!(
11119 "SharedState operation for signal {signal_id} claims store {} field `{}`, but the signal has {:?}",
11120 field.store, field.field, signal.shared_field,
11121 ),
11122 ));
11123 }
11124 if let LegacyClientOperationConsumer::Operation(parent) = operation.consumer {
11125 let parent = usize::try_from(parent).map_err(|_| {
11126 invalid(
11127 "component",
11128 definition,
11129 "SharedState operation parent exceeds the host index space",
11130 )
11131 })?;
11132 if parent >= index {
11133 return Err(invalid(
11134 "component",
11135 definition,
11136 format!(
11137 "SharedState operation {index} refers to non-enclosing operation {parent}"
11138 ),
11139 ));
11140 }
11141 supported &= matches!(
11142 operations[parent].kind,
11143 LegacyClientOperationKind::SharedRead { .. }
11144 | LegacyClientOperationKind::SharedSet { .. }
11145 | LegacyClientOperationKind::SharedUpdate { .. }
11146 );
11147 }
11148 }
11149 Ok(supported)
11150}
11151
11152#[derive(Clone, Copy, Debug, PartialEq, Eq)]
11153struct ValidatedComponentHelperEdge {
11154 local_ordinal: u32,
11155 source_edge: TransportRecordId,
11156 target: TransportDefinitionId,
11157}
11158
11159fn validate_component_shared_state_acquisition_set(
11160 linked: &LinkedTransportComponent,
11161 transport: &Map<String, Value>,
11162 descriptor: &Map<String, Value>,
11163) -> Result<BTreeMap<u32, TransportDefinitionId>, AbiAdapterError> {
11164 let input_fingerprint = required_str(
11165 transport,
11166 "component_input_fingerprint",
11167 "component",
11168 linked.definition,
11169 )?;
11170 let claims = required_array(
11171 transport,
11172 "shared_state_acquisitions",
11173 "component",
11174 linked.definition,
11175 )?;
11176 let stores = required_array(descriptor, "shared_stores", "component", linked.definition)?;
11177 if claims.len() != stores.len() || claims.len() != linked.shared_state_acquisitions.len() {
11178 return Err(invalid(
11179 "component",
11180 linked.definition,
11181 format!(
11182 "SharedState acquisition ownership must be one-to-one with descriptor stores; \
11183 found {} payload claims, {} linked records, and {} descriptor stores",
11184 claims.len(),
11185 linked.shared_state_acquisitions.len(),
11186 stores.len()
11187 ),
11188 ));
11189 }
11190
11191 let mut seen_edges = BTreeSet::new();
11192 let mut acquisitions = BTreeMap::new();
11193 for (index, ((claim, store), linked_acquisition)) in claims
11194 .iter()
11195 .zip(stores)
11196 .zip(&linked.shared_state_acquisitions)
11197 .enumerate()
11198 {
11199 let claim = claim.as_object().ok_or_else(|| {
11200 invalid(
11201 "component",
11202 linked.definition,
11203 format!("shared_state_acquisitions[{index}] must be an object"),
11204 )
11205 })?;
11206 require_known_fields(
11207 "component SharedState acquisition",
11208 claim,
11209 &["source_edge_id", "store_id"],
11210 linked.definition,
11211 )?;
11212 require_exact_u64(
11213 claim,
11214 "store_id",
11215 index as u64,
11216 "component",
11217 linked.definition,
11218 )?;
11219 let store = store.as_object().ok_or_else(|| {
11220 invalid(
11221 "component",
11222 linked.definition,
11223 format!("shared_stores[{index}] must be an object"),
11224 )
11225 })?;
11226 require_exact_u64(store, "id", index as u64, "component", linked.definition)?;
11227 let source_edge =
11228 parse_record_field(claim, "source_edge_id", "component", linked.definition)?;
11229 let store_id = u32::try_from(index).map_err(|_| {
11230 invalid(
11231 "component",
11232 linked.definition,
11233 "SharedState acquisition count exceeds the canonical u32 store-ID space",
11234 )
11235 })?;
11236 let expected_source_edge =
11237 shared_state_acquisition_source_edge_id(input_fingerprint, store_id);
11238 if source_edge != expected_source_edge {
11239 return Err(invalid(
11240 "component",
11241 linked.definition,
11242 format!(
11243 "SharedState store {store_id} has source edge {}, expected deterministic edge {}",
11244 hex_record(&source_edge),
11245 hex_record(&expected_source_edge),
11246 ),
11247 ));
11248 }
11249 if !seen_edges.insert(source_edge) {
11250 return Err(invalid(
11251 "component",
11252 linked.definition,
11253 format!(
11254 "SharedState acquisition source edge {} appears more than once",
11255 hex_record(&source_edge)
11256 ),
11257 ));
11258 }
11259 if linked_acquisition.store_id != store_id || linked_acquisition.source_edge != source_edge
11260 {
11261 return Err(invalid(
11262 "component",
11263 linked.definition,
11264 format!(
11265 "SharedState store {index} ownership disagrees with the relocation-linked \
11266 acquisition"
11267 ),
11268 ));
11269 }
11270 acquisitions.insert(store_id, linked_acquisition.target);
11271 }
11272
11273 Ok(acquisitions)
11274}
11275
11276#[derive(Clone, Debug)]
11277struct ValidatedSharedStateProviderSite {
11278 provider_site_id: u32,
11279 child_edge_local_ordinal: u32,
11280 type_key: String,
11281 schema_abi: SemanticHash,
11282}
11283
11284fn validate_component_shared_state_provider_site_set(
11285 context: &AbiAdapterContext,
11286 linked: &LinkedTransportComponent,
11287 transport: &Map<String, Value>,
11288 descriptor: &Map<String, Value>,
11289 input_fingerprint: &str,
11290 direct_edges: &[ValidatedDirectComponentEdge],
11291) -> Result<Vec<ValidatedSharedStateProviderSite>, AbiAdapterError> {
11292 let claims = required_array(
11293 transport,
11294 "shared_state_provider_sites",
11295 "component",
11296 linked.definition,
11297 )?;
11298 let descriptor_sites = required_array(
11299 descriptor,
11300 "shared_state_provider_sites",
11301 "component",
11302 linked.definition,
11303 )?;
11304 if claims.len() != descriptor_sites.len()
11305 || claims.len() != linked.shared_state_provider_sites.len()
11306 {
11307 return Err(invalid(
11308 "component",
11309 linked.definition,
11310 format!(
11311 "SharedState provider topology must be one-to-one; found {} transport claims, {} \
11312 linked records, and {} descriptor sites",
11313 claims.len(),
11314 linked.shared_state_provider_sites.len(),
11315 descriptor_sites.len(),
11316 ),
11317 ));
11318 }
11319
11320 let mut claimed_children = BTreeSet::new();
11321 let mut validated = Vec::with_capacity(claims.len());
11322 for (index, ((claim, descriptor_site), linked_site)) in claims
11323 .iter()
11324 .zip(descriptor_sites)
11325 .zip(&linked.shared_state_provider_sites)
11326 .enumerate()
11327 {
11328 let provider_site_id = u32::try_from(index).map_err(|_| {
11329 invalid(
11330 "component",
11331 linked.definition,
11332 "SharedState provider-site count exceeds the canonical u32 site-ID space",
11333 )
11334 })?;
11335 let claim = claim.as_object().ok_or_else(|| {
11336 invalid(
11337 "component",
11338 linked.definition,
11339 format!("shared_state_provider_sites[{index}] must be an object"),
11340 )
11341 })?;
11342 require_known_fields(
11343 "component SharedState provider site",
11344 claim,
11345 &[
11346 "child_edge_local_ordinal",
11347 "child_source_edge_id",
11348 "identity_authority",
11349 "provider_site_id",
11350 "site_node",
11351 "source_anchor",
11352 "source_edge_id",
11353 "state_rust_type",
11354 "topology",
11355 ],
11356 linked.definition,
11357 )?;
11358 require_exact_u64(
11359 claim,
11360 "provider_site_id",
11361 u64::from(provider_site_id),
11362 "component",
11363 linked.definition,
11364 )?;
11365 require_exact_str(
11366 claim,
11367 "identity_authority",
11368 "rustc_shared_state_witness_relocation",
11369 "component",
11370 linked.definition,
11371 )?;
11372 require_exact_str(
11373 claim,
11374 "topology",
11375 "static_single_wrapperless",
11376 "component",
11377 linked.definition,
11378 )?;
11379 let child_edge_local_ordinal = checked_u32(
11380 required_u64(
11381 claim,
11382 "child_edge_local_ordinal",
11383 "component",
11384 linked.definition,
11385 )?,
11386 "SharedState provider child edge",
11387 linked.definition,
11388 )?;
11389 if !claimed_children.insert(child_edge_local_ordinal) {
11390 return Err(invalid(
11391 "component",
11392 linked.definition,
11393 format!(
11394 "direct child edge {child_edge_local_ordinal} is claimed by more than one \
11395 SharedState provider"
11396 ),
11397 ));
11398 }
11399 let site_node = checked_u32(
11400 required_u64(claim, "site_node", "component", linked.definition)?,
11401 "SharedState provider server node",
11402 linked.definition,
11403 )?;
11404 let state_rust_type =
11405 required_str(claim, "state_rust_type", "component", linked.definition)?;
11406
11407 let source_anchor =
11408 required_object(claim, "source_anchor", "component", linked.definition)?;
11409 require_known_fields(
11410 "SharedState provider transport source anchor",
11411 source_anchor,
11412 &["column", "line"],
11413 linked.definition,
11414 )?;
11415 let source_line = required_u64(source_anchor, "line", "component", linked.definition)?;
11416 let source_column = required_u64(source_anchor, "column", "component", linked.definition)?;
11417
11418 let descriptor_site = descriptor_site.as_object().ok_or_else(|| {
11419 invalid(
11420 "component",
11421 linked.definition,
11422 format!("descriptor shared_state_provider_sites[{index}] must be an object"),
11423 )
11424 })?;
11425 require_known_fields(
11426 "descriptor SharedState provider site",
11427 descriptor_site,
11428 &[
11429 "child_edge",
11430 "id",
11431 "site_node",
11432 "source_anchor",
11433 "state_rust_type",
11434 "topology",
11435 ],
11436 linked.definition,
11437 )?;
11438 require_exact_u64(
11439 descriptor_site,
11440 "id",
11441 u64::from(provider_site_id),
11442 "component",
11443 linked.definition,
11444 )?;
11445 require_exact_u64(
11446 descriptor_site,
11447 "child_edge",
11448 u64::from(child_edge_local_ordinal),
11449 "component",
11450 linked.definition,
11451 )?;
11452 require_exact_u64(
11453 descriptor_site,
11454 "site_node",
11455 u64::from(site_node),
11456 "component",
11457 linked.definition,
11458 )?;
11459 require_exact_str(
11460 descriptor_site,
11461 "state_rust_type",
11462 state_rust_type,
11463 "component",
11464 linked.definition,
11465 )?;
11466 require_exact_str(
11467 descriptor_site,
11468 "topology",
11469 "static_single_wrapperless",
11470 "component",
11471 linked.definition,
11472 )?;
11473 let descriptor_anchor = required_object(
11474 descriptor_site,
11475 "source_anchor",
11476 "component",
11477 linked.definition,
11478 )?;
11479 require_known_fields(
11480 "SharedState provider descriptor source anchor",
11481 descriptor_anchor,
11482 &["start_column", "start_line"],
11483 linked.definition,
11484 )?;
11485 require_exact_u64(
11486 descriptor_anchor,
11487 "start_line",
11488 source_line,
11489 "component",
11490 linked.definition,
11491 )?;
11492 require_exact_u64(
11493 descriptor_anchor,
11494 "start_column",
11495 source_column,
11496 "component",
11497 linked.definition,
11498 )?;
11499
11500 let child = direct_edges
11501 .get(child_edge_local_ordinal as usize)
11502 .filter(|edge| edge.local_ordinal == child_edge_local_ordinal)
11503 .ok_or_else(|| {
11504 invalid(
11505 "component",
11506 linked.definition,
11507 format!(
11508 "SharedState provider site {provider_site_id} refers to missing direct \
11509 child edge {child_edge_local_ordinal}"
11510 ),
11511 )
11512 })?;
11513 if !child.composed
11514 || !matches!(
11515 child.lifecycle,
11516 ValidatedDirectComponentLifecycle::StaticSingle
11517 )
11518 || child.has_rest
11519 || child.site_node != site_node
11520 || child.fields.iter().any(|field| {
11521 !matches!(
11522 field.binding,
11523 ValidatedDirectComponentBinding::ServerOnly
11524 | ValidatedDirectComponentBinding::StaticCallback { .. }
11525 )
11526 })
11527 {
11528 return Err(invalid(
11529 "component",
11530 linked.definition,
11531 format!(
11532 "SharedState provider site {provider_site_id} must own one wrapperless static \
11533 composed child edge at server node {site_node} with only \
11534 server/static-callback fields"
11535 ),
11536 ));
11537 }
11538
11539 let child_source_edge = parse_record_field(
11540 claim,
11541 "child_source_edge_id",
11542 "component",
11543 linked.definition,
11544 )?;
11545 if child_source_edge != child.source_edge {
11546 return Err(invalid(
11547 "component",
11548 linked.definition,
11549 format!(
11550 "SharedState provider site {provider_site_id} claims child source edge {}, \
11551 but direct child {child_edge_local_ordinal} has {}",
11552 hex_record(&child_source_edge),
11553 hex_record(&child.source_edge),
11554 ),
11555 ));
11556 }
11557 let child_target = linked
11558 .component_edges
11559 .iter()
11560 .find(|edge| edge.source_edge == child_source_edge)
11561 .map(|edge| edge.target)
11562 .ok_or_else(|| {
11563 invalid(
11564 "component",
11565 linked.definition,
11566 format!(
11567 "SharedState provider site {provider_site_id} child edge {} is absent from \
11568 the relocation-linked component set",
11569 hex_record(&child_source_edge),
11570 ),
11571 )
11572 })?;
11573 let source_edge =
11574 parse_record_field(claim, "source_edge_id", "component", linked.definition)?;
11575 let expected_source_edge = shared_state_provider_source_edge_id(
11576 input_fingerprint,
11577 provider_site_id,
11578 &TransportSharedStateProviderSite {
11579 site_node,
11580 child_edge_ordinal: child_edge_local_ordinal,
11581 child_source_edge_id: child_source_edge,
11582 },
11583 );
11584 if source_edge != expected_source_edge {
11585 return Err(invalid(
11586 "component",
11587 linked.definition,
11588 format!(
11589 "SharedState provider site {provider_site_id} has source edge {}, expected \
11590 deterministic edge {}",
11591 hex_record(&source_edge),
11592 hex_record(&expected_source_edge),
11593 ),
11594 ));
11595 }
11596 if linked_site.provider_site_id != provider_site_id
11597 || linked_site.source_edge != source_edge
11598 || linked_site.child_edge_local_ordinal != child_edge_local_ordinal
11599 || linked_site.child_source_edge != child_source_edge
11600 || linked_site.child_target != child_target
11601 || linked_site.site_node != site_node
11602 {
11603 return Err(invalid(
11604 "component",
11605 linked.definition,
11606 format!(
11607 "SharedState provider site {provider_site_id} disagrees with its \
11608 relocation-authenticated linked topology"
11609 ),
11610 ));
11611 }
11612
11613 let state = resolve_shared_state_definition(
11614 context,
11615 linked.definition,
11616 linked_site.target,
11617 &format!("SharedState provider site {provider_site_id}"),
11618 )?;
11619 validated.push(ValidatedSharedStateProviderSite {
11620 provider_site_id,
11621 child_edge_local_ordinal,
11622 type_key: state.type_key,
11623 schema_abi: state.schema_abi,
11624 });
11625 }
11626 Ok(validated)
11627}
11628
11629fn validate_component_helper_edge_set(
11630 linked: &LinkedTransportComponent,
11631 transport: &Map<String, Value>,
11632 input_fingerprint: &str,
11633) -> Result<Vec<ValidatedComponentHelperEdge>, AbiAdapterError> {
11634 let payload_edges = required_array(
11635 transport,
11636 "reachable_helper_edges",
11637 "component",
11638 linked.definition,
11639 )?;
11640 let mut payload_ids = Vec::with_capacity(payload_edges.len());
11641 let mut edges_by_ordinal = BTreeMap::new();
11642 for (index, edge) in payload_edges.iter().enumerate() {
11643 let edge = edge.as_object().ok_or_else(|| {
11644 invalid(
11645 "component",
11646 linked.definition,
11647 format!("reachable_helper_edges[{index}] must be an object"),
11648 )
11649 })?;
11650 require_known_fields(
11651 "component helper source edge",
11652 edge,
11653 &[
11654 "authored_path",
11655 "identity_authority",
11656 "local_ordinal",
11657 "source_edge_id",
11658 ],
11659 linked.definition,
11660 )?;
11661 require_exact_str(
11662 edge,
11663 "identity_authority",
11664 "rustc_function_relocation",
11665 "component",
11666 linked.definition,
11667 )?;
11668 required_str(edge, "authored_path", "component", linked.definition)?;
11669 let local_ordinal = u32::try_from(required_u64(
11670 edge,
11671 "local_ordinal",
11672 "component",
11673 linked.definition,
11674 )?)
11675 .map_err(|_| {
11676 invalid(
11677 "component",
11678 linked.definition,
11679 format!("reachable_helper_edges[{index}].local_ordinal exceeds u32"),
11680 )
11681 })?;
11682 let source_edge =
11683 parse_record_field(edge, "source_edge_id", "component", linked.definition)?;
11684 let expected_source_edge =
11685 component_helper_source_edge_id(input_fingerprint, local_ordinal);
11686 if source_edge != expected_source_edge {
11687 return Err(invalid(
11688 "component",
11689 linked.definition,
11690 format!(
11691 "reachable helper local ordinal {local_ordinal} has source edge {}, \
11692 expected deterministic edge {}",
11693 hex_record(&source_edge),
11694 hex_record(&expected_source_edge),
11695 ),
11696 ));
11697 }
11698 payload_ids.push(source_edge);
11699 if edges_by_ordinal
11700 .insert(local_ordinal, source_edge)
11701 .is_some()
11702 {
11703 return Err(invalid(
11704 "component",
11705 linked.definition,
11706 format!("reachable helper local ordinal {local_ordinal} appears more than once"),
11707 ));
11708 }
11709 }
11710 compare_helper_edges(
11711 linked.definition,
11712 "component helper",
11713 &payload_ids,
11714 &linked.helper_edges,
11715 )?;
11716
11717 edges_by_ordinal
11718 .into_iter()
11719 .map(|(local_ordinal, source_edge)| {
11720 let linked_edge = linked
11721 .helper_edges
11722 .iter()
11723 .find(|edge| edge.source_edge == source_edge)
11724 .ok_or_else(|| {
11725 invalid(
11726 "component",
11727 linked.definition,
11728 format!(
11729 "reachable helper local ordinal {local_ordinal} has no \
11730 relocation-resolved source edge"
11731 ),
11732 )
11733 })?;
11734 Ok(ValidatedComponentHelperEdge {
11735 local_ordinal,
11736 source_edge,
11737 target: linked_edge.target,
11738 })
11739 })
11740 .collect()
11741}
11742
11743#[derive(Clone, Debug, PartialEq, Eq)]
11744struct ValidatedStandaloneHelperEdge {
11745 ordinal: u32,
11746 authored_path: String,
11747 source_edge: TransportRecordId,
11748 target: TransportDefinitionId,
11749}
11750
11751fn validate_helper_edge_set(
11752 linked: &LinkedTransportHelper,
11753 root: &Map<String, Value>,
11754) -> Result<Vec<ValidatedStandaloneHelperEdge>, AbiAdapterError> {
11755 let payload_edges = required_array(root, "direct_calls", "helper", linked.definition)?;
11756 let mut payload_ids = Vec::with_capacity(payload_edges.len());
11757 let mut edges_by_ordinal = BTreeMap::new();
11758 for (index, edge) in payload_edges.iter().enumerate() {
11759 let edge = edge.as_object().ok_or_else(|| {
11760 invalid(
11761 "helper",
11762 linked.definition,
11763 format!("direct_calls[{index}] must be an object"),
11764 )
11765 })?;
11766 require_known_fields(
11767 "helper direct call",
11768 edge,
11769 &["authored_path", "ordinal", "source_edge_id"],
11770 linked.definition,
11771 )?;
11772 let authored_path =
11773 required_str(edge, "authored_path", "helper", linked.definition)?.to_owned();
11774 if authored_path.is_empty() {
11775 return Err(invalid(
11776 "helper",
11777 linked.definition,
11778 format!("direct_calls[{index}].authored_path cannot be empty"),
11779 ));
11780 }
11781 let ordinal = u32::try_from(required_u64(edge, "ordinal", "helper", linked.definition)?)
11782 .map_err(|_| {
11783 invalid(
11784 "helper",
11785 linked.definition,
11786 format!("direct_calls[{index}].ordinal exceeds u32"),
11787 )
11788 })?;
11789 let source_edge = parse_record_field(edge, "source_edge_id", "helper", linked.definition)?;
11790 let expected_source_edge =
11791 helper_direct_call_source_edge_id(linked.definition.record, ordinal);
11792 if source_edge != expected_source_edge {
11793 return Err(invalid(
11794 "helper",
11795 linked.definition,
11796 format!(
11797 "direct helper call ordinal {ordinal} has source edge {}, \
11798 expected deterministic edge {}",
11799 hex_record(&source_edge),
11800 hex_record(&expected_source_edge),
11801 ),
11802 ));
11803 }
11804 payload_ids.push(source_edge);
11805 if edges_by_ordinal
11806 .insert(ordinal, (authored_path, source_edge))
11807 .is_some()
11808 {
11809 return Err(invalid(
11810 "helper",
11811 linked.definition,
11812 format!("direct helper call ordinal {ordinal} appears more than once"),
11813 ));
11814 }
11815 }
11816 compare_helper_edges(
11817 linked.definition,
11818 "helper",
11819 &payload_ids,
11820 &linked.helper_edges,
11821 )?;
11822
11823 edges_by_ordinal
11824 .into_iter()
11825 .enumerate()
11826 .map(|(expected, (ordinal, (authored_path, source_edge)))| {
11827 let expected = u32::try_from(expected).map_err(|_| {
11828 invalid(
11829 "helper",
11830 linked.definition,
11831 "direct helper call count exceeds the canonical u32 ID space",
11832 )
11833 })?;
11834 if ordinal != expected {
11835 return Err(invalid(
11836 "helper",
11837 linked.definition,
11838 format!(
11839 "direct helper call ordinals must be dense from zero; \
11840 expected ordinal {expected}, found {ordinal}"
11841 ),
11842 ));
11843 }
11844 let linked_edge = linked
11845 .helper_edges
11846 .iter()
11847 .find(|edge| edge.source_edge == source_edge)
11848 .ok_or_else(|| {
11849 invalid(
11850 "helper",
11851 linked.definition,
11852 format!(
11853 "direct helper call ordinal {ordinal} has no \
11854 relocation-resolved source edge"
11855 ),
11856 )
11857 })?;
11858 Ok(ValidatedStandaloneHelperEdge {
11859 ordinal,
11860 authored_path,
11861 source_edge,
11862 target: linked_edge.target,
11863 })
11864 })
11865 .collect()
11866}
11867
11868fn parse_standalone_helper_body(
11869 definition: TransportDefinitionId,
11870 body_ir: &Value,
11871 options: &ClientJsonParseOptions<'_>,
11872) -> Result<HelperCodegenBody, AbiAdapterError> {
11873 let parsed = if body_ir.get("kind").and_then(Value::as_str) == Some("block") {
11874 HelperCodegenBody::Block(
11875 parse_client_block_json_with_options(body_ir, options).map_err(|error| {
11876 invalid(
11877 "helper",
11878 definition,
11879 format!("standalone helper has invalid Client IR v3 block: {error}"),
11880 )
11881 })?,
11882 )
11883 } else {
11884 HelperCodegenBody::Expr(
11885 parse_client_expr_json_with_options(body_ir, options).map_err(|error| {
11886 invalid(
11887 "helper",
11888 definition,
11889 format!("standalone helper has invalid Client IR v3 expression: {error}"),
11890 )
11891 })?,
11892 )
11893 };
11894 Ok(parsed)
11895}
11896
11897fn transported_helper_paths(body: &HelperCodegenBody) -> Vec<String> {
11898 let mut paths = Vec::new();
11899 let mut visit = |expression: &ClientExpr| {
11900 if let ClientExpr::Call {
11901 function: ClientFunctionRef::Unresolved(path),
11902 ..
11903 } = expression
11904 {
11905 paths.push(path.clone());
11906 }
11907 };
11908 match body {
11909 HelperCodegenBody::Expr(expression) => walk_client_expr(expression, &mut visit),
11910 HelperCodegenBody::Block(block) => walk_client_block(block, &mut visit),
11911 }
11912 paths
11913}
11914
11915fn validate_standalone_helper_client_ir(
11916 definition: TransportDefinitionId,
11917 body_ir: &Value,
11918 direct_edges: &[ValidatedStandaloneHelperEdge],
11919) -> Result<(Value, HelperCodegenBody), AbiAdapterError> {
11920 let transported =
11921 parse_standalone_helper_body(definition, body_ir, &ClientJsonParseOptions::new())?;
11922 let normalized = transported.canonical_json();
11923 if normalized != *body_ir {
11924 return Err(invalid(
11925 "helper",
11926 definition,
11927 "standalone helper body is not canonical Client IR v3 JSON or contains unknown \
11928 semantic fields",
11929 ));
11930 }
11931
11932 let transported_paths = transported_helper_paths(&transported);
11936 if transported_paths.len() != direct_edges.len() {
11937 return Err(invalid(
11938 "helper",
11939 definition,
11940 format!(
11941 "standalone helper Client IR contains {} direct helper call(s), but the \
11942 relocation payload contains {}",
11943 transported_paths.len(),
11944 direct_edges.len(),
11945 ),
11946 ));
11947 }
11948 for (index, (actual, edge)) in transported_paths.iter().zip(direct_edges).enumerate() {
11949 if actual != &edge.authored_path {
11950 return Err(invalid(
11951 "helper",
11952 definition,
11953 format!(
11954 "standalone helper direct call ordinal {index} is `{actual}` in Client IR, \
11955 but the relocation payload names `{}`",
11956 edge.authored_path,
11957 ),
11958 ));
11959 }
11960 }
11961
11962 let next_ordinal = std::cell::Cell::new(0_usize);
11963 let resolution_error = std::cell::RefCell::new(None::<String>);
11964 let resolve = |path: &str| {
11965 let ordinal = next_ordinal.get();
11966 let Some(next) = ordinal.checked_add(1) else {
11967 *resolution_error.borrow_mut() =
11968 Some("direct helper call count exceeds usize".to_owned());
11969 return None;
11970 };
11971 next_ordinal.set(next);
11972 let Some(edge) = direct_edges.get(ordinal) else {
11973 *resolution_error.borrow_mut() = Some(format!(
11974 "Client IR contains an unexpected direct helper call `{path}` at ordinal {ordinal}"
11975 ));
11976 return None;
11977 };
11978 if path != edge.authored_path {
11979 *resolution_error.borrow_mut() = Some(format!(
11980 "Client IR direct helper call ordinal {ordinal} is `{path}`, but the relocation \
11981 payload names `{}`",
11982 edge.authored_path,
11983 ));
11984 return None;
11985 }
11986 Some(ClientFunctionRef::Helper {
11987 edge: HelperCallEdgeId::new(edge.ordinal),
11988 authored_path: path.to_owned(),
11989 name: path.rsplit("::").next().unwrap_or(path).to_owned(),
11990 })
11991 };
11992 let options = ClientJsonParseOptions::new().with_unresolved_function_ref(&resolve);
11993 let resolved = parse_standalone_helper_body(definition, body_ir, &options)?;
11994 if let Some(reason) = resolution_error.into_inner() {
11995 return Err(invalid("helper", definition, reason));
11996 }
11997 if next_ordinal.get() != direct_edges.len() {
11998 return Err(invalid(
11999 "helper",
12000 definition,
12001 format!(
12002 "standalone helper Client IR resolved {} direct call(s), but the relocation \
12003 payload contains {}",
12004 next_ordinal.get(),
12005 direct_edges.len(),
12006 ),
12007 ));
12008 }
12009
12010 Ok((normalized, resolved))
12011}
12012
12013fn compare_component_edges(
12014 definition: TransportDefinitionId,
12015 kind: &'static str,
12016 payload: &[TransportRecordId],
12017 linked: &[LinkedComponentEdge],
12018) -> Result<(), AbiAdapterError> {
12019 compare_edge_ids(
12020 definition,
12021 kind,
12022 payload,
12023 linked.iter().map(|edge| edge.source_edge),
12024 )
12025}
12026
12027fn compare_helper_edges(
12028 definition: TransportDefinitionId,
12029 kind: &'static str,
12030 payload: &[TransportRecordId],
12031 linked: &[LinkedHelperEdge],
12032) -> Result<(), AbiAdapterError> {
12033 compare_edge_ids(
12034 definition,
12035 kind,
12036 payload,
12037 linked.iter().map(|edge| edge.source_edge),
12038 )
12039}
12040
12041fn compare_edge_ids(
12042 definition: TransportDefinitionId,
12043 kind: &'static str,
12044 payload: &[TransportRecordId],
12045 linked: impl IntoIterator<Item = TransportRecordId>,
12046) -> Result<(), AbiAdapterError> {
12047 let mut payload_set = payload.to_vec();
12048 payload_set.sort();
12049 if payload_set.windows(2).any(|pair| pair[0] == pair[1]) {
12050 return Err(invalid(
12051 kind,
12052 definition,
12053 "payload contains a duplicate source edge ID",
12054 ));
12055 }
12056 let mut linked_set = linked.into_iter().collect::<Vec<_>>();
12057 linked_set.sort();
12058 if payload_set != linked_set {
12059 return Err(AbiAdapterError::SourceEdgeSetMismatch {
12060 kind,
12061 definition,
12062 payload: payload_set.iter().map(hex_record).collect(),
12063 linked: linked_set.iter().map(hex_record).collect(),
12064 });
12065 }
12066 Ok(())
12067}
12068
12069fn validate_definition_record(
12070 kind: &'static str,
12071 definition: TransportDefinitionId,
12072 object: &Map<String, Value>,
12073 field: &str,
12074) -> Result<(), AbiAdapterError> {
12075 let payload = parse_record_field(object, field, kind, definition)?;
12076 if payload != definition.record {
12077 return Err(invalid(
12078 kind,
12079 definition,
12080 format!(
12081 "`{field}` is {}, but linked definition record is {}",
12082 hex_record(&payload),
12083 hex_record(&definition.record)
12084 ),
12085 ));
12086 }
12087 Ok(())
12088}
12089
12090fn validate_linked_semantic_hash(
12091 kind: &'static str,
12092 definition: TransportDefinitionId,
12093 root: &Map<String, Value>,
12094 linked: SemanticHash,
12095) -> Result<(), AbiAdapterError> {
12096 let payload = parse_sha256(
12097 required_str(root, "semantic_hash", kind, definition)?,
12098 kind,
12099 definition,
12100 "semantic_hash",
12101 )?;
12102 let payload = SemanticHash::from_bytes(payload);
12103 if payload != linked {
12104 return Err(AbiAdapterError::SemanticHashMismatch {
12105 kind,
12106 definition,
12107 payload,
12108 linked,
12109 });
12110 }
12111 Ok(())
12112}
12113
12114fn validate_sha256_field(
12115 object: &Map<String, Value>,
12116 field: &str,
12117 kind: &'static str,
12118 definition: TransportDefinitionId,
12119) -> Result<(), AbiAdapterError> {
12120 parse_sha256(
12121 required_str(object, field, kind, definition)?,
12122 kind,
12123 definition,
12124 field,
12125 )?;
12126 Ok(())
12127}
12128
12129fn parse_record_field(
12130 object: &Map<String, Value>,
12131 field: &str,
12132 kind: &'static str,
12133 definition: TransportDefinitionId,
12134) -> Result<TransportRecordId, AbiAdapterError> {
12135 parse_hex_32(
12136 required_str(object, field, kind, definition)?,
12137 kind,
12138 definition,
12139 field,
12140 )
12141}
12142
12143fn parse_sha256(
12144 value: &str,
12145 kind: &'static str,
12146 definition: TransportDefinitionId,
12147 field: &str,
12148) -> Result<[u8; 32], AbiAdapterError> {
12149 let value = value.strip_prefix("sha256:").ok_or_else(|| {
12150 invalid(
12151 kind,
12152 definition,
12153 format!("`{field}` must start with `sha256:`"),
12154 )
12155 })?;
12156 parse_hex_32(value, kind, definition, field)
12157}
12158
12159fn parse_hex_32(
12160 value: &str,
12161 kind: &'static str,
12162 definition: TransportDefinitionId,
12163 field: &str,
12164) -> Result<[u8; 32], AbiAdapterError> {
12165 if value.len() != 64
12166 || !value
12167 .bytes()
12168 .all(|byte| byte.is_ascii_digit() || (b'a'..=b'f').contains(&byte))
12169 {
12170 return Err(invalid(
12171 kind,
12172 definition,
12173 format!("`{field}` must be exactly 64 lower-case hexadecimal characters"),
12174 ));
12175 }
12176 let mut output = [0_u8; 32];
12177 for (index, byte) in output.iter_mut().enumerate() {
12178 let offset = index * 2;
12179 *byte = u8::from_str_radix(&value[offset..offset + 2], 16).map_err(|error| {
12180 invalid(
12181 kind,
12182 definition,
12183 format!("invalid hexadecimal `{field}`: {error}"),
12184 )
12185 })?;
12186 }
12187 Ok(output)
12188}
12189
12190fn payload_object<'a>(
12191 kind: &'static str,
12192 definition: TransportDefinitionId,
12193 value: &'a Value,
12194) -> Result<&'a Map<String, Value>, AbiAdapterError> {
12195 value
12196 .as_object()
12197 .ok_or_else(|| invalid(kind, definition, "payload must be a JSON object"))
12198}
12199
12200fn required_object<'a>(
12201 object: &'a Map<String, Value>,
12202 field: &str,
12203 kind: &'static str,
12204 definition: TransportDefinitionId,
12205) -> Result<&'a Map<String, Value>, AbiAdapterError> {
12206 object
12207 .get(field)
12208 .and_then(Value::as_object)
12209 .ok_or_else(|| invalid(kind, definition, format!("missing object `{field}`")))
12210}
12211
12212fn required_array<'a>(
12213 object: &'a Map<String, Value>,
12214 field: &str,
12215 kind: &'static str,
12216 definition: TransportDefinitionId,
12217) -> Result<&'a Vec<Value>, AbiAdapterError> {
12218 object
12219 .get(field)
12220 .and_then(Value::as_array)
12221 .ok_or_else(|| invalid(kind, definition, format!("missing array `{field}`")))
12222}
12223
12224fn optional_array<'a>(
12225 object: &'a Map<String, Value>,
12226 field: &str,
12227 kind: &'static str,
12228 definition: TransportDefinitionId,
12229) -> Result<Option<&'a Vec<Value>>, AbiAdapterError> {
12230 match object.get(field) {
12231 Some(value) => value
12232 .as_array()
12233 .map(Some)
12234 .ok_or_else(|| invalid(kind, definition, format!("`{field}` must be an array"))),
12235 None => Ok(None),
12236 }
12237}
12238
12239fn required_str<'a>(
12240 object: &'a Map<String, Value>,
12241 field: &str,
12242 kind: &'static str,
12243 definition: TransportDefinitionId,
12244) -> Result<&'a str, AbiAdapterError> {
12245 object
12246 .get(field)
12247 .and_then(Value::as_str)
12248 .ok_or_else(|| invalid(kind, definition, format!("missing string `{field}`")))
12249}
12250
12251fn required_u64(
12252 object: &Map<String, Value>,
12253 field: &str,
12254 kind: &'static str,
12255 definition: TransportDefinitionId,
12256) -> Result<u64, AbiAdapterError> {
12257 object.get(field).and_then(Value::as_u64).ok_or_else(|| {
12258 invalid(
12259 kind,
12260 definition,
12261 format!("missing unsigned integer `{field}`"),
12262 )
12263 })
12264}
12265
12266fn required_bool(
12267 object: &Map<String, Value>,
12268 field: &str,
12269 kind: &'static str,
12270 definition: TransportDefinitionId,
12271) -> Result<bool, AbiAdapterError> {
12272 object
12273 .get(field)
12274 .and_then(Value::as_bool)
12275 .ok_or_else(|| invalid(kind, definition, format!("missing boolean `{field}`")))
12276}
12277
12278fn require_exact_str(
12279 object: &Map<String, Value>,
12280 field: &str,
12281 expected: &str,
12282 kind: &'static str,
12283 definition: TransportDefinitionId,
12284) -> Result<(), AbiAdapterError> {
12285 let actual = required_str(object, field, kind, definition)?;
12286 if actual == expected {
12287 Ok(())
12288 } else {
12289 Err(invalid(
12290 kind,
12291 definition,
12292 format!("unsupported `{field}` `{actual}`; expected `{expected}`"),
12293 ))
12294 }
12295}
12296
12297fn require_exact_u64(
12298 object: &Map<String, Value>,
12299 field: &str,
12300 expected: u64,
12301 kind: &'static str,
12302 definition: TransportDefinitionId,
12303) -> Result<(), AbiAdapterError> {
12304 let actual = required_u64(object, field, kind, definition)?;
12305 if actual == expected {
12306 Ok(())
12307 } else {
12308 Err(invalid(
12309 kind,
12310 definition,
12311 format!("unsupported `{field}` {actual}; expected {expected}"),
12312 ))
12313 }
12314}
12315
12316fn require_known_fields(
12317 label: &str,
12318 object: &Map<String, Value>,
12319 allowed: &[&str],
12320 definition: TransportDefinitionId,
12321) -> Result<(), AbiAdapterError> {
12322 let allowed = allowed.iter().copied().collect::<BTreeSet<_>>();
12323 if let Some(field) = object
12324 .keys()
12325 .find(|field| !allowed.contains(field.as_str()))
12326 {
12327 return Err(invalid(
12328 "descriptor",
12329 definition,
12330 format!(
12331 "{label} contains unknown field `{field}`; refusing to ignore possible semantic data"
12332 ),
12333 ));
12334 }
12335 Ok(())
12336}
12337
12338fn invalid(
12339 kind: &'static str,
12340 definition: TransportDefinitionId,
12341 reason: impl Into<String>,
12342) -> AbiAdapterError {
12343 AbiAdapterError::InvalidPayload {
12344 kind,
12345 definition,
12346 reason: reason.into(),
12347 }
12348}
12349
12350fn hex_record(record: &TransportRecordId) -> String {
12351 use std::fmt::Write as _;
12352
12353 let mut result = String::with_capacity(64);
12354 for byte in record {
12355 let _ = write!(result, "{byte:02x}");
12356 }
12357 result
12358}
12359
12360pub fn canonical_legacy_json_hash(domain: &str, value: &Value) -> SemanticHash {
12366 let bytes = canonical_json_bytes(value)
12367 .expect("a parsed serde_json::Value always serializes canonically");
12368 rsjs_ir::abi::canonical_legacy_json_bytes_hash(domain, &bytes)
12369}
12370
12371#[cfg(test)]
12372mod tests;