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