livewire-rust 0.1.4

Livewire for Rust: server-rendered reactive components for Laravel for Rust.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
//! The authoring contract: what a component is, what it renders, and how the browser's calls reach
//! it.
//!
//! A component is a Rust struct whose fields are the wire-public state, plus an inherent
//! implementation annotated with [`#[livewire::component]`](macro@livewire::component) that
//! publishes its actions. The derive macro writes [`LivewireState`], so the server never reflects
//! over a type at runtime.

use std::sync::Arc;

use laravel::http::Request;
use serde::de::DeserializeOwned;
use serde_json::{Map, Value};

use crate::error::LivewireError;

/// The result of an operation in this crate.
pub type Result<T, E = LivewireError> = std::result::Result<T, E>;

/// What a component's `render` asks the engine to render.
#[derive(Debug, Clone, PartialEq)]
pub enum ComponentView {
    /// A template found through the view finder, such as `livewire.counter`.
    Named(String),
    /// Markup written in the component module, rendered with `data` on top of the component's
    /// fields.
    Inline {
        /// The template source.
        source: &'static str,
        /// Extra data the source renders with.
        data: Map<String, Value>,
    },
}

impl ComponentView {
    /// The view name, or `inline` for a component that carries its own source.
    #[must_use]
    pub fn name(&self) -> &str {
        match self {
            Self::Named(name) => name,
            Self::Inline { .. } => "inline",
        }
    }
}

/// One action call's parameters, as the browser sent them.
#[derive(Debug, Clone, PartialEq)]
pub enum Params {
    /// Positional parameters, in the order the action declared them.
    List(Vec<Value>),
    /// Named parameters, as `{param: 'value'}` sent them.
    Named(Map<String, Value>),
}

impl Default for Params {
    fn default() -> Self {
        Self::List(Vec::new())
    }
}

impl Params {
    /// Reads the parameters the browser sent, rejecting anything that is neither a list nor an
    /// object.
    pub fn from_json(value: Value) -> Result<Self> {
        match value {
            Value::Array(list) => Ok(Self::List(list)),
            Value::Object(map) => Ok(Self::Named(map)),
            Value::Null => Ok(Self::List(Vec::new())),
            _ => Err(LivewireError::MalformedPayload(
                "a call's params must be a list or an object".to_owned(),
            )),
        }
    }

    /// The parameter at `index`, or under `name`.
    ///
    /// The macro-generated dispatch reads each declared parameter this way, so a browser that
    /// sends named parameters and one that sends positional ones both reach the same action.
    pub fn arg<T: DeserializeOwned>(&self, name: &str, index: usize) -> Result<T> {
        let value = match self {
            Self::List(list) => list.get(index).cloned(),
            Self::Named(map) => map.get(name).cloned().or_else(|| map.get(&index.to_string()).cloned()),
        };

        match value {
            Some(value) => decode(value, name),
            None => Err(LivewireError::MalformedPayload(format!(
                "the call is missing its parameter [{name}]"
            ))),
        }
    }

    /// The parameter at `index`, or under `name`, or `None` when the browser sent neither, for an
    /// optional parameter.
    pub fn optional<T: DeserializeOwned>(&self, name: &str, index: usize) -> Result<Option<T>> {
        let value = match self {
            Self::List(list) => list.get(index).cloned(),
            Self::Named(map) => map.get(name).cloned().or_else(|| map.get(&index.to_string()).cloned()),
        };

        value.map(|value| decode(value, name)).transpose()
    }

    /// Whether the browser sent no parameters at all.
    #[must_use]
    pub fn is_empty(&self) -> bool {
        match self {
            Self::List(list) => list.is_empty(),
            Self::Named(map) => map.is_empty(),
        }
    }

    /// Decodes the whole parameter list into `T`, for actions that take one struct.
    pub fn decode<T: DeserializeOwned>(self) -> Result<T> {
        let value = match self {
            Self::List(list) => Value::Array(list),
            Self::Named(map) => Value::Object(map),
        };

        decode(value, "params")
    }
}

/// Decodes one wire value into the parameter's Rust type.
fn decode<T: DeserializeOwned>(value: Value, name: &str) -> Result<T> {
    serde_json::from_value(value)
        .map_err(|error| LivewireError::MalformedPayload(format!("the parameter [{name}] can't be decoded: {error}")))
}

/// One action call, as the browser sent it.
#[derive(Debug, Clone, PartialEq)]
pub struct Call {
    /// The method the browser called.
    pub method: String,
    /// The call's parameters.
    pub params: Params,
    /// Per-call metadata, such as the island the call came from.
    pub metadata: Map<String, Value>,
}

impl Call {
    /// Whether the call is one of the refresh-only signals the client sends, which do not name a
    /// method of the component.
    #[must_use]
    pub fn is_signal(&self) -> bool {
        matches!(
            self.method.as_str(),
            "$refresh" | "$commit" | "$set" | "$sync" | "__dispatch" | "__lazyLoad" | "__lazyLoadIsland"
        )
    }
}

/// The context one lifecycle hook or action receives.
#[derive(Debug, Clone)]
pub struct ComponentContext {
    /// The component's instance ID.
    pub id: String,
    /// The component's registered name, such as `counter`.
    pub name: String,
    /// Whether this render is the component's first.
    pub mounting: bool,
    /// Metadata the browser sent with the call, such as `island` or `async`.
    pub request_metadata: Map<String, Value>,
    /// Effects the component adds during this request.
    pub effects: Map<String, Value>,
    /// Memo entries the component adds during this request.
    pub memo: Map<String, Value>,
    /// The browser's request, so an action can read the signed-in user, run a policy, or use a
    /// service without the framework cloning the request per component.
    pub request: Option<Arc<Request>>,
    /// The frames an action streamed, in the order it wrote them.
    pub streamed: Vec<Value>,
}

/// Reads a browser-sent value into a field's type, accepting the strings form inputs send.
///
/// `wire:model` sends `"4"` for a number field and `""` for an emptied one; a snapshot this crate
/// wrote carries real JSON types. Both reach here, so a value that is already the field's type is
/// read as it is, and a string is read as JSON text, with the empty string as `null`.
///
/// # Errors
///
/// Returns the decoder's error when neither reading fits the type.
pub fn coerce<T: DeserializeOwned>(value: &Value) -> std::result::Result<T, serde_json::Error> {
    match serde_json::from_value::<T>(value.clone()) {
        Ok(value) => Ok(value),
        Err(error) => {
            let Some(text) = value.as_str() else {
                return Err(error);
            };

            if text.is_empty() {
                return serde_json::from_value(Value::Null);
            }

            serde_json::from_str::<T>(text.trim())
        }
    }
}

impl ComponentContext {
    /// A context for a component that is mounting, in a request that has `request`.
    #[must_use]
    pub fn mounting(id: impl Into<String>, name: impl Into<String>, request: Option<Arc<Request>>) -> Self {
        Self {
            id: id.into(),
            name: name.into(),
            mounting: true,
            request_metadata: Map::new(),
            effects: Map::new(),
            memo: Map::new(),
            request,
            streamed: Vec::new(),
        }
    }

    /// A context for a component that is updating.
    #[must_use]
    pub fn updating(id: impl Into<String>, name: impl Into<String>, request: Option<Arc<Request>>) -> Self {
        Self {
            mounting: false,
            ..Self::mounting(id, name, request)
        }
    }

    /// Runs the component's declared rules against its current state.
    ///
    /// Every failing field's first message is recorded in the snapshot's `memo.errors`, which the
    /// browser's `$errors` reads, and the whole set comes back in [`LivewireError::ValidationFailed`]
    /// so the caller can answer without an HTTP failure.
    ///
    /// # Errors
    ///
    /// Returns [`LivewireError::ValidationFailed`] when a rule rejects a field, and the framework's
    /// own error when a rule could not run at all, such as a check that needs the database.
    pub async fn validate(&mut self, component: &dyn Component) -> Result<()> {
        let mut data = Map::new();
        component.dehydrate_fields(&mut data);

        let rules = component.validation_rules();

        match rules.validate(&data).await {
            Ok(()) => Ok(()),
            Err(laravel::validation::ValidationError::Invalid(invalid)) => {
                let errors = serde_json::to_value(&invalid)
                    .ok()
                    .and_then(|value| value.as_object().cloned())
                    .unwrap_or_default();

                for (field, messages) in &errors {
                    let message = messages
                        .as_array()
                        .and_then(|messages| messages.first())
                        .and_then(Value::as_str)
                        .unwrap_or_default();

                    self.add_error(field.clone(), message);
                }

                Err(LivewireError::ValidationFailed { errors })
            }
            Err(laravel::validation::ValidationError::Failed(error)) => Err(LivewireError::MalformedPayload(format!(
                "a validation rule could not run: {error}"
            ))),
        }
    }

    /// Records a validation error for `field`, which the browser reads from the snapshot's
    /// `memo.errors` and shows through `$errors`.
    pub fn add_error(&mut self, field: impl Into<String>, message: impl Into<String>) {
        let request = crate::context::LivewireRequest::current().unwrap_or_default();
        let id = self.id.clone();
        let field = field.into();
        // The client's `$errors.first(field)` reads `messages[0]`, so each field maps to a list of
        // messages, as upstream sends it.
        let messages = Value::Array(vec![Value::from(message.into())]);

        request.change(&id, |state| {
            state.errors.insert(field, messages);
        });
    }

    /// Sends `content` to the element marked `wire:stream="name"`, as the action runs.
    ///
    /// The browser appends it as the frame arrives, so a long action can show progress; the
    /// ordinary response follows the frames.
    pub fn stream(&mut self, name: impl Into<String>, content: impl Into<String>) {
        self.streamed.push(Value::Object(Map::from_iter([
            ("stream".to_owned(), Value::Bool(true)),
            (
                "body".to_owned(),
                Value::Object(Map::from_iter([
                    ("id".to_owned(), Value::from(self.id.clone())),
                    ("type".to_owned(), Value::from("directive")),
                    ("name".to_owned(), Value::from(name.into())),
                    ("content".to_owned(), Value::from(content.into())),
                ])),
            ),
            ("endStream".to_owned(), Value::Bool(true)),
        ])));
    }

    /// Adds `value` under `name`, replacing any value already there.
    pub fn add_effect(&mut self, name: &str, value: Value) {
        self.effects.insert(name.to_owned(), value);
    }

    /// Queues a JavaScript expression the browser evaluates once the answer morphed.
    ///
    /// The client reads `effects.xjs` as a list of `{expression, params}` entries, so a second
    /// call appends instead of replacing what the first one asked for.
    pub fn xjs(&mut self, expression: impl Into<String>) {
        self.push_effect(
            "xjs",
            serde_json::json!({"expression": expression.into(), "params": {}}),
        );
    }

    /// Adds `value` to the list under `name`, keeping a list that is already there.
    pub fn push_effect(&mut self, name: &str, value: Value) {
        match self.effects.get_mut(name) {
            Some(Value::Array(values)) => values.push(value),
            Some(existing) => {
                let first = std::mem::replace(existing, Value::Array(Vec::new()));
                if let Some(Value::Array(values)) = self.effects.get_mut(name) {
                    values.push(first);
                    values.push(value);
                }
            }
            None => {
                self.effects.insert(name.to_owned(), Value::Array(vec![value]));
            }
        }
    }

    /// Adds a memo entry.
    pub fn add_memo(&mut self, key: &str, value: Value) {
        self.memo.insert(key.to_owned(), value);
    }

    /// Sends `content` to the browser as a file, instead of replacing the component's markup.
    ///
    /// The response carries the file base64-encoded in the `download` effect, which the runtime
    /// turns into a save dialog; the component renders nothing.
    pub fn download(&mut self, name: impl Into<String>, content: impl AsRef<[u8]>, content_type: impl Into<String>) {
        use base64::Engine as _;

        self.add_effect(
            "download",
            serde_json::json!({
                "name": name.into(),
                "content": base64::engine::general_purpose::STANDARD.encode(content.as_ref()),
                "contentType": content_type.into(),
            }),
        );
        self.add_effect("skipRender", Value::Bool(true));
    }

    /// The browser's request, or `None` when the component rendered outside a request.
    #[must_use]
    pub fn request(&self) -> Option<&Request> {
        self.request.as_deref()
    }

    /// The signed-in user of the browser's request.
    ///
    /// # Errors
    ///
    /// Fails when the component rendered outside a request.
    pub async fn user<U: laravel::auth::Authenticatable>(&self) -> Result<Option<U>> {
        let Some(request) = self.request() else {
            return Err(LivewireError::MalformedPayload(
                "the component has no request, so it has no user".to_owned(),
            ));
        };

        request
            .user()
            .await
            .map_err(|error| LivewireError::MalformedPayload(format!("the request's user can't be read: {error}")))
    }
}

/// One wire-public field's rules, generated by the derive in declaration order.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct WireField {
    /// The field's name on the wire.
    pub name: &'static str,
    /// Whether the browser may change the field at all.
    pub locked: bool,
    /// Whether a parent component may bind the field with `wire:model`.
    pub modelable: bool,
    /// Whether the field resets the component when its parent changes it.
    pub reactive: bool,
    /// The query string binding of a `#[livewire(url)]` field.
    pub url: Option<UrlBinding>,
    /// The session binding of a `#[livewire(session)]` field.
    pub session: Option<SessionBinding>,
    /// The synthesizer that reads and writes the field, when it needs one.
    pub synth: Option<&'static str>,
    /// The validation rules the field declares, in the framework's rule syntax.
    pub rules: &'static [&'static str],
    /// The Rust type the field declares, for diagnostics and the testing helpers.
    pub type_name: &'static str,
}

/// How a field follows the page's query string.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct UrlBinding {
    /// The query string key, which defaults to the field name.
    pub as_name: Option<&'static str>,
    /// Whether a change pushes a history entry or replaces the current one.
    pub push: bool,
    /// Whether the key stays in the query string when the field is at its default.
    pub always_show: bool,
    /// Keys to leave out of the generated query string.
    pub except: &'static str,
}

/// How a field persists in the session.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct SessionBinding {
    /// The session key, or `None` for the key derived from the component and field names.
    pub key: Option<&'static str>,
}

/// The wire-public state of a component, generated by `#[derive(LivewireComponent)]`.
///
/// The derive writes one arm per field in declaration order, so the server never reflects over a
/// type at runtime and skipped fields never touch the wire.
pub trait LivewireState: Send + Sync + 'static {
    /// The wire-public fields, in declaration order.
    fn wire_fields() -> &'static [WireField]
    where
        Self: Sized;

    /// The component's name, which the registry replaces with the name the application registered
    /// and which diagnostics use until then.
    fn component_name() -> &'static str
    where
        Self: Sized,
    {
        std::any::type_name::<Self>()
    }

    /// Writes the wire-public fields into `data`, in declaration order.
    fn dehydrate_fields(&self, data: &mut Map<String, Value>);

    /// Reads the fields present in `data`. A field that is absent keeps its default.
    ///
    /// # Errors
    ///
    /// Fails when a present value cannot be hydrated into its field.
    fn hydrate_fields(&mut self, data: &Map<String, Value>) -> Result<()>;

    /// Sets one wire-public field, without interpreting dots in its name.
    ///
    /// # Errors
    ///
    /// Fails when the field is not wire-public, or when the value cannot be assigned.
    fn set_field(&mut self, field: &str, value: Value) -> Result<()>;

    /// The values a template reads, which are the fields as they cross the wire unless the
    /// component shows more.
    ///
    /// The derive overrides this for `#[livewire(model)]` fields: the view reads the fetched row,
    /// while the snapshot keeps only the reference.
    fn render_values(&self, data: &mut Map<String, Value>) {
        self.dehydrate_fields(data);
    }

    /// The view the component renders by default.
    fn default_view(&self) -> ComponentView;

    /// The rules the component's fields declare, ready to run against its own state.
    ///
    /// The derive generates this from `#[livewire(validate(..))]`; a component without those
    /// returns an empty set.
    fn validation_rules(&self) -> laravel::validation::Rules {
        laravel::validation::Rules::new()
    }
}

/// The options a class-level `#[component(..)]` attribute declares.
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
pub struct ClassOptions {
    /// The layout a page component renders inside, or `None` for the configured default.
    pub layout: Option<&'static str>,
    /// The page title a page component sets.
    pub title: Option<&'static str>,
    /// The Alpine transition the component's updates use.
    pub transition: Option<&'static str>,
    /// Whether the component renders a placeholder first and loads itself afterwards.
    pub lazy: bool,
    /// Whether the component loads itself after the page has loaded.
    pub defer: bool,
    /// Whether the component's requests skip the components around it.
    pub isolate: bool,
}

/// A listener or dispatch a component declares statically.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct Listener {
    /// The event name. A `{placeholder}` is filled from the component's state.
    pub event: &'static str,
    /// The method that runs, when the listener does not run the method of the same name.
    pub method: Option<&'static str>,
}

/// What an action's return value means to the response.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum ActionResultKind {
    /// The action's return value is ignored.
    #[default]
    Ignored,
    /// The action's return value is a `returns` effect, which the browser's promise resolves with.
    Returned,
    /// The action answers with JSON instead of new HTML, and its return value is the body.
    Json,
}

/// A component: wire-public state plus the lifecycle the server runs around it.
///
/// Every method has a default, so a component implements only the hooks it needs. The derive and
/// [`#[livewire::component]`](macro@livewire::component) generate the state methods and the action
/// dispatch; an inherent method is reachable from the browser only when it appears in the annotated
/// implementation.
#[async_trait::async_trait]
pub trait Component: LivewireState {
    /// Runs before the component mounts or hydrates, on every request.
    fn boot(&mut self) -> Result<()> {
        Ok(())
    }

    /// Runs after `boot`, before the component mounts or hydrates.
    fn initialize(&mut self, context: &mut ComponentContext) -> Result<()> {
        let _ = context;
        Ok(())
    }

    /// Runs when the component first appears on the page.
    ///
    /// # Errors
    ///
    /// Fails when the props cannot be read into the component's fields.
    fn mount(&mut self, params: Params, context: &mut ComponentContext) -> Result<()> {
        let _ = (params, context);
        Ok(())
    }

    /// Runs after the component mounted, on its first request.
    fn booted(&mut self) -> Result<()> {
        Ok(())
    }

    /// Runs when a later request rebuilds the component from its snapshot.
    fn hydrate(&mut self, context: &mut ComponentContext) -> Result<()> {
        let _ = context;
        Ok(())
    }

    /// Produces the component's markup.
    ///
    /// # Errors
    ///
    /// Fails when the component cannot name its view or its data.
    fn render(&self) -> Result<ComponentView> {
        Ok(self.default_view())
    }

    /// Runs before the snapshot is written.
    fn dehydrate(&mut self, context: &mut ComponentContext) -> Result<()> {
        let _ = context;
        Ok(())
    }

    /// Runs after the response is built, when the component instance is dropped.
    fn destroy(&mut self) {}

    /// Runs before an update assigns `property`.
    fn updating(&mut self, property: &str, value: &Value, context: &mut ComponentContext) -> Result<()> {
        let _ = (property, value, context);
        Ok(())
    }

    /// Runs after every update of a batch is assigned.
    fn updated(&mut self, property: &str, context: &mut ComponentContext) -> Result<()> {
        let _ = (property, context);
        Ok(())
    }

    /// Runs one action the browser called.
    ///
    /// # Errors
    ///
    /// Fails when the method is unknown, its parameters do not decode, or the action fails.
    async fn call(&mut self, call: Call, context: &mut ComponentContext) -> Result<Option<Value>>;

    /// Whether the browser may run `method`, which an action's `authorize` path decides.
    ///
    /// # Errors
    ///
    /// Fails when the policy itself cannot run.
    async fn authorize(&mut self, method: &str, context: &ComponentContext) -> Result<bool> {
        let _ = (method, context);
        Ok(true)
    }

    /// Fetches the model references this component holds, before the hooks, the actions, and the
    /// render read them.
    ///
    /// The derive generates this for `#[livewire(model)]` fields; a component without one keeps the
    /// default, which resolves nothing.
    async fn hydrate_models(&mut self, context: &mut ComponentContext) -> Result<()> {
        let _ = context;

        Ok(())
    }

    /// The token a redeployment changes, so a stale browser page is asked to reload.
    fn release_token(&self) -> &'static str {
        "a"
    }

    /// The events the component listens to.
    fn listeners(&self) -> &'static [Listener] {
        &[]
    }

    /// The events the component dispatches when it mounts.
    fn dispatches(&self) -> &'static [Listener] {
        &[]
    }

    /// Runs when an action failed, before the failure becomes a response.
    fn exception(&mut self, error: &LivewireError, context: &mut ComponentContext) {
        let _ = (error, context);
    }

    /// Whether an action's return value becomes a `returns` effect or JSON.
    fn action_result_kind(&self, method: &str) -> ActionResultKind {
        let _ = method;
        ActionResultKind::Ignored
    }

    /// The options the component's class-level attribute declared.
    fn class_options(&self) -> ClassOptions {
        ClassOptions::default()
    }

    /// The actions the browser sends ahead of the others.
    fn async_methods(&self) -> &'static [&'static str] {
        &[]
    }

    /// The actions that answer with JSON instead of new markup.
    fn json_methods(&self) -> &'static [&'static str] {
        &[]
    }

    /// The component's computed properties, which its template reads like fields.
    ///
    /// A computed property is memoized for the rest of the request, so a template that prints it
    /// twice computes it once.
    fn computed_values(&self, id: &str) -> Map<String, Value> {
        let _ = id;
        Map::new()
    }
}

/// Turns `postEditor` into `postEditor`, which is how a browser-written prop name reaches a field.
///
/// The macro-generated mount matches a kebab-case prop such as `post-id` to the field `post_id` and
/// to the camel-case name, as upstream's `separateParamsAndAttributes` does.
#[must_use]
pub fn camel_case(name: &str) -> String {
    if !name.contains('-') {
        return name.to_owned();
    }

    let mut out = String::with_capacity(name.len());
    let mut upper = false;
    for character in name.chars() {
        if character == '-' {
            upper = true;
        } else if upper {
            out.extend(character.to_uppercase());
            upper = false;
        } else {
            out.push(character);
        }
    }
    out
}

/// Serializes a field for the wire, normalizing negative zero so that snapshots stay stable.
#[must_use]
pub fn to_wire<T: serde::Serialize>(value: &T) -> Value {
    let mut value = serde_json::to_value(value).unwrap_or(Value::Null);
    normalize(&mut value);
    value
}

/// Replaces `-0.0` with `0.0` wherever it appears in a wire value.
fn normalize(value: &mut Value) {
    match value {
        Value::Number(number) => {
            if number
                .as_f64()
                .is_some_and(|float| float == 0.0 && float.is_sign_negative())
            {
                *number = serde_json::Number::from(0);
            }
        }
        Value::Array(values) => values.iter_mut().for_each(normalize),
        Value::Object(map) => map.values_mut().for_each(normalize),
        _ => {}
    }
}

/// Reads a scalar out of a wire map by dot path, as a session key's `{placeholder}` needs it.
#[must_use]
pub fn lookup_scalar(data: &Map<String, Value>, path: &str) -> Option<String> {
    let mut current = data;
    let mut segments = path.split('.').peekable();

    while let Some(segment) = segments.next() {
        let value = current.get(segment)?;

        if segments.peek().is_none() {
            return match value {
                Value::String(text) => Some(text.clone()),
                Value::Number(number) => Some(number.to_string()),
                Value::Bool(flag) => Some(flag.to_string()),
                _ => None,
            };
        }

        current = value.as_object()?;
    }

    None
}

#[cfg(test)]
mod derive_tests {
    use super::*;
    use crate::{LivewireComponent, component};

    #[derive(Default, LivewireComponent)]
    #[livewire(view = "livewire.counter")]
    struct Counter {
        count: i32,
        #[livewire(locked)]
        id: String,
        #[livewire(session(key = "counter-step"))]
        step: i32,
        #[livewire(validate(required, max_length(255)))]
        label: Option<String>,
        #[livewire(skip)]
        cache: Vec<String>,
    }

    #[component]
    impl Counter {
        pub fn mount(&mut self, count: Option<i32>) {
            self.count = count.unwrap_or(7);
            self.id = "fixed".to_owned();
        }

        pub fn increment(&mut self, by: i32) {
            self.count += by;
        }

        pub fn describe(&mut self) -> String {
            format!("count={}", self.count)
        }

        pub fn fail(&mut self) -> Result<(), LivewireError> {
            Err(LivewireError::MalformedPayload("the action failed".to_owned()))
        }

        #[livewire(renderless)]
        pub fn quietly(&mut self) {}

        #[livewire(json)]
        pub fn as_json(&mut self) -> serde_json::Value {
            serde_json::json!({"ok": true})
        }

        #[livewire(on = "refresh-counter")]
        pub fn refreshed(&mut self) {}
    }

    fn context() -> ComponentContext {
        ComponentContext::mounting("abc", "counter", None)
    }

    #[test]
    fn the_derive_lists_the_wire_public_fields_in_declaration_order() {
        let fields = Counter::wire_fields();

        assert_eq!(
            fields.iter().map(|field| field.name).collect::<Vec<_>>(),
            ["count", "id", "step", "label"]
        );
        assert!(
            fields
                .iter()
                .find(|field| field.name == "id")
                .is_some_and(|field| field.locked)
        );
        assert_eq!(
            fields
                .iter()
                .find(|field| field.name == "step")
                .and_then(|field| field.session)
                .and_then(|session| session.key),
            Some("counter-step")
        );
        assert_eq!(
            fields
                .iter()
                .find(|field| field.name == "label")
                .map(|field| field.rules),
            Some(&["required", "max_length(255)"][..])
        );
    }

    #[test]
    fn a_mount_prop_reaches_its_field_and_the_hook_runs() {
        let mut counter = Counter::default();
        let mut context = context();

        Component::mount(
            &mut counter,
            Params::Named(Map::from_iter([("count".to_owned(), Value::from(3))])),
            &mut context,
        )
        .expect("mounts");

        // The hook saw the prop and overrode it, and set the locked field.
        assert_eq!(counter.count, 3);
        assert_eq!(counter.id, "fixed");
    }

    #[test]
    fn a_missing_optional_mount_prop_uses_the_default() {
        let mut counter = Counter::default();

        Component::mount(&mut counter, Params::default(), &mut context()).expect("mounts");

        assert_eq!(counter.count, 7);
    }

    #[test]
    fn a_form_string_reads_into_a_typed_field() {
        use super::coerce;

        assert_eq!(coerce::<i32>(&Value::from("4")).expect("a numeral"), 4);
        assert_eq!(coerce::<i32>(&Value::from(4)).expect("real JSON"), 4);
        assert!(coerce::<bool>(&Value::from("true")).expect("a boolean"));
        assert_eq!(coerce::<Option<i32>>(&Value::from("")).expect("an emptied field"), None);
        assert_eq!(coerce::<String>(&Value::from("plain")).expect("text"), "plain");
        assert!(coerce::<i32>(&Value::from("not a number")).is_err());
    }

    #[test]
    fn the_state_round_trips_without_the_skipped_field() {
        let mut counter = Counter {
            count: 4,
            id: "fixed".to_owned(),
            step: 2,
            label: Some("hi".to_owned()),
            cache: vec!["not on the wire".to_owned()],
        };
        counter.cache.push("still not".to_owned());

        let mut data = Map::new();
        counter.dehydrate_fields(&mut data);

        assert!(!data.contains_key("cache"));
        assert_eq!(data["count"], serde_json::json!(4));

        let mut restored = Counter::default();
        restored.cache.push("kept".to_owned());
        restored.hydrate_fields(&data).expect("hydrates");

        assert_eq!(restored.count, 4);
        assert_eq!(restored.label.as_deref(), Some("hi"));
        // A skipped field never crosses the wire, so the restored instance keeps its own value.
        assert_eq!(restored.cache, ["kept".to_owned()]);
    }

    #[test]
    fn a_locked_field_rejects_updates_but_hydrates() {
        let mut counter = Counter::default();
        counter
            .hydrate_fields(&Map::from_iter([("id".to_owned(), Value::from("from-snapshot"))]))
            .expect("hydrates");
        assert_eq!(counter.id, "from-snapshot");

        let error = counter.set_field("id", Value::from("hacked")).expect_err("locked");
        assert!(matches!(error, LivewireError::LockedProperty { .. }));
    }

    #[test]
    fn an_unknown_field_is_reported() {
        let mut counter = Counter::default();

        let error = counter.set_field("nope", Value::from(1)).expect_err("unknown");

        assert!(matches!(error, LivewireError::UnknownProperty { .. }));
        assert!(error.to_string().contains("[$nope]"));
    }

    #[test]
    fn an_action_decodes_its_typed_parameters() {
        let mut counter = Counter::default();

        let value = futures_util::FutureExt::now_or_never(Component::call(
            &mut counter,
            Call {
                method: "increment".to_owned(),
                params: Params::List(vec![Value::from(5)]),
                metadata: Map::new(),
            },
            &mut context(),
        ))
        .expect("the action future is ready")
        .expect("the action runs");

        assert_eq!(value, None);
        assert_eq!(counter.count, 5);
    }

    #[test]
    fn a_returning_action_becomes_a_returns_value() {
        let mut counter = Counter {
            count: 2,
            ..Counter::default()
        };

        let value = futures_util::FutureExt::now_or_never(Component::call(
            &mut counter,
            Call {
                method: "describe".to_owned(),
                params: Params::default(),
                metadata: Map::new(),
            },
            &mut context(),
        ))
        .expect("ready")
        .expect("runs");

        assert_eq!(value, Some(serde_json::json!("count=2")));
    }

    #[test]
    fn a_failing_action_propagates_its_error() {
        let mut counter = Counter::default();

        let error = futures_util::FutureExt::now_or_never(Component::call(
            &mut counter,
            Call {
                method: "fail".to_owned(),
                params: Params::default(),
                metadata: Map::new(),
            },
            &mut context(),
        ))
        .expect("ready")
        .expect_err("fails");

        assert!(error.to_string().contains("the action failed"));
    }

    #[test]
    fn an_unknown_action_is_a_419_error() {
        let mut counter = Counter::default();

        let error = futures_util::FutureExt::now_or_never(Component::call(
            &mut counter,
            Call {
                method: "deleteEverything".to_owned(),
                params: Params::default(),
                metadata: Map::new(),
            },
            &mut context(),
        ))
        .expect("ready")
        .expect_err("unknown method");

        assert!(matches!(error, LivewireError::MethodNotFound { .. }));
        assert_eq!(error.status().as_u16(), 419);
    }

    #[test]
    fn the_refresh_signals_do_nothing() {
        let mut counter = Counter::default();

        for method in ["$refresh", "$commit", "$sync"] {
            let value = futures_util::FutureExt::now_or_never(Component::call(
                &mut counter,
                Call {
                    method: method.to_owned(),
                    params: Params::default(),
                    metadata: Map::new(),
                },
                &mut context(),
            ))
            .expect("ready")
            .expect("runs");
            assert_eq!(value, None, "{method}");
        }
    }

    #[test]
    fn action_options_reach_the_response() {
        let counter = Counter::default();

        assert_eq!(counter.action_result_kind("as_json"), ActionResultKind::Json);
        assert_eq!(counter.action_result_kind("increment"), ActionResultKind::Ignored);

        let listeners = Component::listeners(&counter);
        assert_eq!(listeners.len(), 1);
        assert_eq!(listeners[0].event, "refresh-counter");
        assert_eq!(listeners[0].method, Some("refreshed"));
    }

    #[test]
    fn a_renderless_action_asks_for_no_html() {
        let mut counter = Counter::default();
        let mut context = context();

        futures_util::FutureExt::now_or_never(Component::call(
            &mut counter,
            Call {
                method: "quietly".to_owned(),
                params: Params::default(),
                metadata: Map::new(),
            },
            &mut context,
        ))
        .expect("ready")
        .expect("runs");

        assert_eq!(context.effects["skipRender"], serde_json::json!(true));
    }

    #[test]
    fn the_default_view_comes_from_the_struct_attribute() {
        assert_eq!(
            Counter::default().default_view(),
            ComponentView::Named("livewire.counter".to_owned())
        );
    }

    #[test]
    fn a_computed_property_reaches_the_template_and_is_not_an_action() {
        use std::sync::atomic::{AtomicUsize, Ordering};

        static CALLS: AtomicUsize = AtomicUsize::new(0);

        #[derive(Default, LivewireComponent)]
        #[livewire(inline = "<div>{{ doubled }}</div>")]
        struct Totals {
            count: i32,
        }

        #[component]
        impl Totals {
            #[livewire(computed)]
            pub fn doubled(&self) -> i32 {
                CALLS.fetch_add(1, Ordering::SeqCst);
                self.count * 2
            }
        }

        let totals = Totals { count: 4 };

        assert_eq!(
            Component::computed_values(&totals, "id")["doubled"],
            serde_json::json!(8)
        );

        // A computed property is read by the template, never dispatched by the browser.
        let error = futures_util::FutureExt::now_or_never(Component::call(
            &mut Totals::default(),
            Call {
                method: "doubled".to_owned(),
                params: Params::default(),
                metadata: Map::new(),
            },
            &mut context(),
        ))
        .expect("ready")
        .expect_err("not an action");

        assert!(matches!(error, LivewireError::MethodNotFound { .. }));
    }

    #[test]
    fn a_negative_zero_is_normalized_on_the_wire() {
        assert_eq!(to_wire(&-0.0f64), serde_json::json!(0));
        assert_eq!(to_wire(&vec![-0.0f64, 1.5]), serde_json::json!([0, 1.5]));
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn positional_and_named_parameters_reach_the_same_argument() {
        let positional = Params::from_json(serde_json::json!([2])).expect("a list");
        let named = Params::from_json(serde_json::json!({"by": 2})).expect("an object");

        assert_eq!(positional.arg::<i32>("by", 0).expect("decodes"), 2);
        assert_eq!(named.arg::<i32>("by", 0).expect("decodes"), 2);
    }

    #[test]
    fn a_missing_argument_is_reported_not_panicked() {
        let params = Params::from_json(serde_json::json!([])).expect("a list");

        let error = params.arg::<i32>("by", 0).expect_err("missing");

        assert!(matches!(error, LivewireError::MalformedPayload(_)));
        assert!(error.to_string().contains("[by]"));
    }

    #[test]
    fn an_optional_argument_may_be_absent() {
        let params = Params::from_json(serde_json::json!([])).expect("a list");

        assert_eq!(params.optional::<i32>("by", 0).expect("absent is fine"), None);
    }

    #[test]
    fn a_wrongly_typed_argument_is_reported() {
        let params = Params::from_json(serde_json::json!(["two"])).expect("a list");

        let error = params.arg::<i32>("by", 0).expect_err("wrong type");

        assert!(error.to_string().contains("can't be decoded"));
    }

    #[test]
    fn mixed_parameters_are_rejected() {
        let error = Params::from_json(serde_json::json!("by=2")).expect_err("neither list nor object");

        assert!(matches!(error, LivewireError::MalformedPayload(_)));
    }

    #[test]
    fn the_refresh_signals_are_not_component_methods() {
        for method in ["$refresh", "$commit", "$set", "$sync", "__dispatch", "__lazyLoad"] {
            let call = Call {
                method: method.to_owned(),
                params: Params::default(),
                metadata: Map::new(),
            };
            assert!(call.is_signal(), "{method}");
        }

        let call = Call {
            method: "increment".to_owned(),
            params: Params::default(),
            metadata: Map::new(),
        };
        assert!(!call.is_signal());
    }

    #[test]
    fn effects_collect_into_lists() {
        let mut context = ComponentContext::mounting("id", "counter", None);

        context.push_effect("dispatches", Value::from("first"));
        context.push_effect("dispatches", Value::from("second"));
        context.add_effect("xjs", Value::from("console.log(1)"));

        assert_eq!(context.effects["dispatches"], serde_json::json!(["first", "second"]));
        assert_eq!(context.effects["xjs"], serde_json::json!("console.log(1)"));
    }
}