leptos_hydrated 0.9.0

A component to hydrate and manage interactive hydration state in Leptos 0.8
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
use super::*;
#[cfg(feature = "ssr")]
use tower::ServiceExt;
#[cfg(feature = "ssr")]
use crate::core::{serialize_for_injection, get_injected_states, InjectedStates};
use crate::core::create_hydrated_signal;
use leptos::prelude::*;
use leptos::reactive::owner::Owner;
use serde::{Deserialize, Serialize};

// ---------------------------------------------------------------------------
// Shared fixture
// ---------------------------------------------------------------------------

static INIT: std::sync::Once = std::sync::Once::new();

fn init_test_env() {
    INIT.call_once(|| {
        let _ = any_spawner::Executor::init_tokio();
    });
}

fn use_hydrate_signal<T>() -> (RwSignal<T>, LocalResource<Option<T>>)
where
    T: Hydratable + Clone + Send + Sync + serde::Serialize + serde::de::DeserializeOwned + 'static,
{
    create_hydrated_signal(T::initial)
}

#[derive(Clone, Default, Serialize, Deserialize, PartialEq, Debug)]
pub struct DefaultState {
    pub value: i32,
}
impl Hydratable for DefaultState {
    fn initial() -> Self {
        Self::default()
    }
}

#[derive(Clone, Default, Serialize, Deserialize, PartialEq, Debug)]
pub struct ThemeState {
    pub theme: String,
}

impl Hydratable for ThemeState {
    fn initial() -> Self {
        let theme = get_cookie("theme").unwrap_or_else(|| "dark".into());
        ThemeState { theme }
    }
}

#[derive(Clone, Default, Serialize, Deserialize, PartialEq, Debug)]
pub struct FetchState {
    pub value: i32,
}
impl Hydratable for FetchState {
    fn initial() -> Self {
        FetchState { value: 100 }
    }
}

#[derive(Clone, Default, Serialize, Deserialize, PartialEq, Debug)]
#[cfg(all(feature = "hydrate", not(feature = "ssr")))]
pub struct SlowState {
    pub value: i32,
}
#[cfg(all(feature = "hydrate", not(feature = "ssr")))]
impl Hydratable for SlowState {
    fn initial() -> Self {
        SlowState { value: 2 }
    }
}

// ---------------------------------------------------------------------------
// Mechanism tests: create_hydrated_signal_internal
// ---------------------------------------------------------------------------

#[tokio::test]
async fn test_signal_initialises_from_fetch_state() {
    init_test_env();
    let local = tokio::task::LocalSet::new();
    local
        .run_until(async {
            let owner = Owner::new_root(None);
            owner.with(|| {
                let (signal, _) = use_hydrate_signal::<FetchState>();
                // In native tests, it starts with T::initial() which is 100
                assert_eq!(signal.get_untracked().value, 100);
            });
        })
        .await;
}

#[tokio::test]
async fn test_initial_sync_keeps_value() {
    init_test_env();
    let local = tokio::task::LocalSet::new();
    local
        .run_until(async {
            let owner = Owner::new_root(None);
            owner.with(|| {
                let (signal, _) = use_hydrate_signal::<DefaultState>();
                assert_eq!(signal.get_untracked().value, 0);
            });
        })
        .await;
}

// Client-only behavior: resource actually resolves
#[cfg(all(feature = "hydrate", not(feature = "ssr")))]
#[tokio::test]
async fn test_initial_updates_signal() {
    init_test_env();
    let local = tokio::task::LocalSet::new();
    local
        .run_until(async {
            let owner = Owner::new_root(None);
            let signal = owner.with(|| {
                let (signal, _) = use_hydrate_signal::<FetchState>();
                signal
            });
            assert_eq!(signal.get_untracked().value, 100);
            // It should still be 100 because it re-ran initial() which returns 100
            for _ in 0..20 {
                tokio::task::yield_now().await;
            }
            tokio::time::sleep(std::time::Duration::from_millis(50)).await;
            assert_eq!(signal.get_untracked().value, 100);
        })
        .await;
}

#[cfg(all(feature = "hydrate", not(feature = "ssr")))]
#[tokio::test]
async fn test_two_way_binding_sync_flow() {
    init_test_env();
    let local = tokio::task::LocalSet::new();
    local
        .run_until(async {
            let owner = Owner::new_root(None);
            let (signal, resource) = owner.with(|| use_hydrate_signal::<SlowState>());

            // 1. Initial state (SlowState::initial returns 2)
            assert_eq!(signal.get_untracked().value, 2);

            // 2. Wait for hydration (it re-runs initial which returns 2)
            tokio::time::sleep(std::time::Duration::from_millis(50)).await;
            assert_eq!(signal.get_untracked().value, 2);
            assert_eq!(resource.get_untracked(), Some(Some(SlowState { value: 2 })));

            // 3. Simulated user update
            signal.set(SlowState { value: 3 });
            assert_eq!(signal.get_untracked().value, 3);
            // Wait for resource to re-evaluate
            for _ in 0..10 {
                tokio::task::yield_now().await;
            }
            assert_eq!(resource.get_untracked(), Some(Some(SlowState { value: 3 })));
        })
        .await;
}

// ---------------------------------------------------------------------------
// SSR isolation
// ---------------------------------------------------------------------------

#[tokio::test]
async fn test_ssr_resource_is_muted() {
    init_test_env();
    let local = tokio::task::LocalSet::new();
    local
        .run_until(async {
            let owner = Owner::new_root(None);
            owner.with(|| {
                let (signal, resource) = use_hydrate_signal::<DefaultState>();
                assert_eq!(signal.get_untracked().value, 0);
                // LocalResource should not resolve on the server
                assert!(resource.get_untracked().is_none());
            });
        })
        .await;
}

// ---------------------------------------------------------------------------
// Component + context tests
// ---------------------------------------------------------------------------

#[component]
fn MainContent() -> impl IntoView {
    let state = hydrated_signal(ThemeState::initial());
    view! { <p>"Theme: " {move || state.get().theme}</p> }
}

#[tokio::test]
async fn test_hydrate_context_global_provides_context() {
    init_test_env();
    let local = tokio::task::LocalSet::new();
    local
        .run_until(async {
            let owner = Owner::new_root(None);
            owner.with(|| {
                let _ = view! {
                    <HydratedContext<ThemeState> global=true />
                    <MainContent />
                };
            });
        })
        .await;
}

#[component]
fn ScopedDisplay() -> impl IntoView {
    let state = hydrated_signal(ThemeState::initial());
    view! { <p>"Scoped: " {move || state.get().theme}</p> }
}

#[tokio::test]
async fn test_hydrate_context_provides_context_to_children() {
    init_test_env();
    let local = tokio::task::LocalSet::new();
    local
        .run_until(async {
            let owner = Owner::new_root(None);
            owner.with(|| {
                let _ = view! {
                    <HydratedContext<ThemeState>>
                        <ScopedDisplay />
                    </HydratedContext<ThemeState>>
                };
            });
        })
        .await;
}

// ---------------------------------------------------------------------------
// use_hydrated_context accessors
// ---------------------------------------------------------------------------

#[tokio::test]
async fn test_use_hydrated_context_returns_some_when_context_exists() {
    init_test_env();
    let local = tokio::task::LocalSet::new();
    local.run_until(async {
        let owner = Owner::new_root(None);
        owner.with(|| {
            let signal = RwSignal::new(ThemeState {
                theme: "dark".into(),
            });
            let _resource = LocalResource::new(|| async { None::<ThemeState> });
            provide_context(signal);
            let result = use_hydrated_context::<ThemeState>();
            assert_eq!(result, signal);
            assert_eq!(result.get_untracked().theme, "dark");
        });
    }).await;
}

#[test]
#[should_panic(expected = "MISSING CONTEXT PROVIDER")]
fn test_use_hydrated_context_returns_none_when_no_context() {
    let owner = Owner::new_root(None);
    owner.with(|| {
        let _ = use_hydrated_context::<ThemeState>();
    });
}

// ---------------------------------------------------------------------------
// Isomorphic Helpers
// ---------------------------------------------------------------------------

#[cfg(feature = "ssr")]
#[tokio::test]
async fn test_get_cookie_ssr() {
    use axum::http::Request;
    use axum::http::header::COOKIE;

    let (parts, _) = Request::builder()
        .header(COOKIE, "test=value; other=foo")
        .body(())
        .unwrap()
        .into_parts();

    let owner = Owner::new_root(None);
    owner.with(|| {
        provide_context(parts);
        assert_eq!(get_cookie("test"), Some("value".into()));
        assert_eq!(get_cookie("other"), Some("foo".into()));
        assert_eq!(get_cookie("missing"), None);
    });
}

#[cfg(feature = "ssr")]
#[tokio::test]
async fn test_set_cookie_ssr() {
    use leptos_axum::ResponseOptions;

    let owner = Owner::new_root(None);
    owner.with(|| {
        let res_options = ResponseOptions::default();
        provide_context(res_options.clone());

        set_cookie("test_c", "val", "; Path=/");

        // Verify it was also inserted into mock state
        assert_eq!(get_cookie("test_c"), Some("val".into()));
    });
}

#[cfg(feature = "ssr")]
#[tokio::test]
async fn test_get_query_param_ssr() {
    use axum::http::Request;

    let (parts, _) = Request::builder()
        .uri("http://example.com/?foo=bar&baz=qux")
        .body(())
        .unwrap()
        .into_parts();

    let owner = Owner::new_root(None);
    owner.with(|| {
        provide_context(parts);
        assert_eq!(get_query_param("foo"), Some("bar".into()));
        assert_eq!(get_query_param("baz"), Some("qux".into()));
        assert_eq!(get_query_param("missing"), None);
    });
}


#[cfg(all(not(feature = "ssr"), not(feature = "hydrate")))]
#[test]
fn test_cookie_persistence_in_csr_mode() {
    let owner = Owner::new_root(None);
    owner.with(|| {
        // In CSR mode (native tests), we use a mock store
        set_cookie("csr_test", "works", "");
        assert_eq!(get_cookie("csr_test"), Some("works".into()));
        assert_eq!(get_cookie("missing"), None);
    });
}

// ---------------------------------------------------------------------------
// Internal Mechanisms
// ---------------------------------------------------------------------------

#[cfg(feature = "ssr")]
#[test]
fn test_serialize_for_injection_internal() {
    let state = ThemeState {
        theme: "dark".into(),
    };
    let json = serialize_for_injection(&state);
    assert_eq!(json, r#"{"theme":"dark"}"#);
}

#[tokio::test]
async fn test_hydratable_initial_is_called() {
    let result = DefaultState::initial();
    assert_eq!(result.value, 0);
}

// ---------------------------------------------------------------------------
// Panic tests
// ---------------------------------------------------------------------------

#[tokio::test]
async fn test_hydrated_signal_creates_local_when_no_context() {
    init_test_env();
    let local = tokio::task::LocalSet::new();
    local.run_until(async {
        let owner = Owner::new_root(None);
        owner.with(|| {
            let sig = hydrated_signal(DefaultState::initial());
            assert_eq!(sig.get_untracked().value, 0);
        });
    }).await;
}



// ---------------------------------------------------------------------------

// ---------------------------------------------------------------------------
// Isomorphic / Environment tests
// ---------------------------------------------------------------------------

#[test]
fn test_isomorphic_macro_branches_correctly() {
    let val = isomorphic! {
        state => "ssr",
        hydrate => "csr"
    };
    #[cfg(feature = "ssr")]
    assert_eq!(val, "ssr");
    #[cfg(not(feature = "ssr"))]
    assert_eq!(val, "csr");
}

#[cfg(not(feature = "ssr"))]

// ---------------------------------------------------------------------------
// Coverage gap: get_query_param without Parts context (falls to mock_state)
// ---------------------------------------------------------------------------

#[cfg(feature = "ssr")]
#[tokio::test]
async fn test_get_query_param_no_context_returns_none() {
    init_test_env();
    let local = tokio::task::LocalSet::new();
    local
        .run_until(async {
            let owner = Owner::new_root(None);
            owner.with(|| {
                // No Parts in context → falls to mock_state → empty → None
                assert_eq!(get_query_param("anything"), None);
            });
        })
        .await;
}

// ---------------------------------------------------------------------------
// Coverage gap: set_cookie SSR path when ResponseOptions is provided
// ---------------------------------------------------------------------------

#[cfg(feature = "ssr")]
#[tokio::test]
async fn test_set_cookie_with_response_options_appends_header() {
    use leptos_axum::ResponseOptions;

    init_test_env();
    let local = tokio::task::LocalSet::new();
    local
        .run_until(async {
            let owner = Owner::new_root(None);
            owner.with(|| {
                let res_options = ResponseOptions::default();
                provide_context(res_options.clone());

                // Triggers the ResponseOptions code path (append_header)
                // and also writes to mock_state for verification
                set_cookie("mycookie", "myvalue", "; path=/");

                // The mock_state is always written in SSR path
                assert_eq!(get_cookie("mycookie"), Some("myvalue".into()));
            });
        })
        .await;
}

// ---------------------------------------------------------------------------
// Coverage gap: LocalResource async closure — both branches
// ---------------------------------------------------------------------------

#[cfg(feature = "ssr")]
#[tokio::test]
async fn test_resource_first_run_returns_initial() {
    init_test_env();
    let local = tokio::task::LocalSet::new();
    local
        .run_until(async {
            let owner = Owner::new_root(None);
            owner.with(|| {
                // On first poll the resource re-runs initial(), which is 100 for FetchState
                let (signal, resource) = use_hydrate_signal::<FetchState>();
                assert_eq!(signal.get_untracked().value, 100);
                // Resource hasn't resolved yet (SSR LocalResource is lazy)
                assert!(resource.get_untracked().is_none());
            });
        })
        .await;
}

#[cfg(feature = "ssr")]
#[tokio::test]
async fn test_resource_subsequent_run_returns_current_signal() {
    init_test_env();
    let local = tokio::task::LocalSet::new();
    local
        .run_until(async {
            let owner = Owner::new_root(None);
            owner.with(|| {
                let (signal, _resource) = use_hydrate_signal::<DefaultState>();
                // Mutate the signal — a subsequent resource poll would return this value
                signal.set(DefaultState { value: 99 });
                assert_eq!(signal.get_untracked().value, 99);
            });
        })
        .await;
}

// ---------------------------------------------------------------------------
// Sync Opt-out tests
// ---------------------------------------------------------------------------

#[cfg(not(feature = "ssr"))]
#[derive(Clone, Default, Serialize, Deserialize, PartialEq, Debug)]
pub struct NoSyncState {
    pub value: i32,
}
#[cfg(not(feature = "ssr"))]
impl Hydratable for NoSyncState {
    fn initial() -> Self {
        NoSyncState { value: 50 }
    }
    fn should_sync_on_client() -> bool {
        false
    }
}

#[cfg(not(feature = "ssr"))]
#[tokio::test]
async fn test_should_sync_on_client_false_skips_rerun() {
    init_test_env();
    let local = tokio::task::LocalSet::new();
    local
        .run_until(async {
            let owner = Owner::new_root(None);
            let (_signal, resource) = owner.with(|| use_hydrate_signal::<NoSyncState>());

            // Wait for the resource to resolve
            tokio::time::sleep(std::time::Duration::from_millis(50)).await;

            // In non-SSR mode, the resource re-runs initial().
            // If should_sync_on_client is false, it should return None.
            assert_eq!(resource.get_untracked(), Some(None));
        })
        .await;
}

// ---------------------------------------------------------------------------
// hydrated_signal tests
// ---------------------------------------------------------------------------

#[cfg(feature = "ssr")]
#[tokio::test]
async fn test_hydrated_signal_auto_id_ssr() {
    init_test_env();
    let states = InjectedStates::default();
    let mut parts = http::request::Request::builder().body(()).unwrap().into_parts().0;
    parts.extensions.insert(states.clone());
    
    let owner = Owner::new_root(None);
    owner.with(|| {
        provide_context(parts);
        let _ = hydrated_signal(DefaultState { value: 42 });
        let _ = hydrated_signal(DefaultState { value: 100 });
    });
    
    let guard = states.0.lock().unwrap();
    assert_eq!(guard.len(), 2);
    assert_eq!(guard[0], "{\"value\":42}");
    assert_eq!(guard[1], "{\"value\":100}");
}

#[cfg(not(feature = "ssr"))]
#[tokio::test]
async fn test_hydrated_signal_client_no_panic() {
    init_test_env();
    let local = tokio::task::LocalSet::new();
    local.run_until(async {
        let owner = Owner::new_root(None);
        owner.with(|| {
            // Should not panic even if global data is missing
            let _ = hydrated_signal(DefaultState::initial());
            let _ = hydrated_signal(DefaultState::initial());
        });
    }).await;
}


// ---------------------------------------------------------------------------
// Middleware & Integration Tests
// ---------------------------------------------------------------------------

#[cfg(feature = "ssr")]
#[tokio::test]
async fn test_middleware_injects_script() {
    use axum::{body::Body, http::{Request, header}, routing::get, Router};
    use crate::ssr::HydratedRouterExt;
    use tower::ServiceExt; 
    use http_body_util::BodyExt;

    let app = Router::new()
        .route("/", get(|req: axum::extract::Request| async move {
            // Leptos would get the states from request extensions
            let states = req.extensions().get::<InjectedStates>().unwrap().clone();
            states.0.lock().unwrap().push(r#"{"test":true}"#.to_string());
            
            let mut res = axum::response::Response::new(Body::from("<html><body>Hello</body></html>"));
            res.headers_mut().insert(header::CONTENT_TYPE, header::HeaderValue::from_static("text/html"));
            res
        }))
        .hydrated();

    let response = app.oneshot(Request::builder().uri("/").body(Body::empty()).unwrap()).await.unwrap();
    
    assert_eq!(response.status(), 200);
    
    let body_bytes = response.into_body().collect().await.unwrap().to_bytes();
    let body_str = String::from_utf8_lossy(&body_bytes);
    
    assert!(body_str.contains("window.__lh_data"), "Body should contain window.__lh_data script. Got: {}", body_str);
    assert!(body_str.contains(r#"{"test":true}"#));
}

#[tokio::test]
async fn test_synchronization_equality_check() {
    let local = tokio::task::LocalSet::new();
    local.run_until(async {
        let owner = Owner::new_root(None);
        owner.with(|| {
            // 1. Create signal with initial 10
            let (signal, _resource) = create_hydrated_signal::<DefaultState, _>(|| DefaultState { value: 10 });
            assert_eq!(signal.get_untracked().value, 10);
            
            // 2. Set to 20
            signal.set(DefaultState { value: 20 });
            assert_eq!(signal.get_untracked().value, 20);
            
            // 3. Sync with SAME value 20. 
            // We verify that if we implement the logic correctly, we don't call set unnecessarily.
            let val = DefaultState { value: 20 };
            let mut set_called = false;
            if val != signal.get_untracked() {
                signal.set(val);
                set_called = true;
            }
            assert!(!set_called, "Set should not be called when values are equal");
            
            // 4. Sync with NEW value 30
            let val = DefaultState { value: 30 };
            let mut set_called = false;
            if val != signal.get_untracked() {
                signal.set(val);
                set_called = true;
            }
            assert!(set_called, "Set should be called when values are different");
            assert_eq!(signal.get_untracked().value, 30);
        });
    }).await;
}


#[cfg(feature = "ssr")]
#[tokio::test]
async fn test_hydration_store_complex_parsing() {
    use axum::http::Request;
    use axum::extract::OriginalUri;

    let mut req = Request::builder()
        .uri("/path?foo=bar&baz=qux")
        .header("Cookie", "session=123; theme=dark; pref=true")
        .body(())
        .unwrap();
    
    // Add OriginalUri extension to test fallback
    req.extensions_mut().insert(OriginalUri("/original?ref=promo".parse().unwrap()));

    let (parts, _) = req.into_parts();
    let store = HydrationStore::new_from_parts(&parts);
    
    assert_eq!(store.cookies.get_untracked().get("session").map(String::as_str), Some("123"));
    assert_eq!(store.cookies.get_untracked().get("theme").map(String::as_str), Some("dark"));
    assert_eq!(store.cookies.get_untracked().get("pref").map(String::as_str), Some("true"));
    
    // Should favor OriginalUri query
    assert_eq!(store.query.get_untracked().get("ref").map(String::as_str), Some("promo"));
}


#[tokio::test]
async fn test_use_hydrated_context_accessor() {
    init_test_env();
    let local = tokio::task::LocalSet::new();
    local.run_until(async {
        let owner = Owner::new_root(None);
        owner.with(|| {
            // Should panic now
            // assert!(use_hydrated_context::<DefaultState>().is_none());

            // Create and provide
            let (sig, _res) = create_hydrated_signal::<DefaultState, _>(|| DefaultState::initial());
            provide_context(sig);

            // Should be Some now
            assert_eq!(use_hydrated_context::<DefaultState>(), sig);
        });
    }).await;
}

#[cfg(feature = "ssr")]
#[tokio::test]
async fn test_middleware_empty_injection() {
    use axum::http::Request;
    use axum::Router;
    use axum::routing::get;
    use crate::ssr::HydratedRouterExt;

    // A route that DOES NOT use any hydrated signals
    let app = Router::new()
        .route("/", get(|| async { "no signals here" }))
        .hydrated();

    let req = Request::builder().uri("/").header("Accept", "text/html").body(axum::body::Body::empty()).unwrap();
    let res = app.oneshot(req).await.unwrap();

    assert_eq!(res.status(), http::StatusCode::OK);
    let body = axum::body::to_bytes(res.into_body(), 1024).await.unwrap();
    let body_str = String::from_utf8_lossy(&body);
    // Should NOT contain the script tag because no signals were used
    assert!(!body_str.contains("__lh_data"));
}

#[cfg(feature = "ssr")]
#[tokio::test]
async fn test_middleware_non_html_response() {
    use axum::Router;
    use axum::routing::get;
    use crate::ssr::HydratedRouterExt;

    let app = Router::new()
        .route("/", get(|parts: http::request::Parts| async move { 
            // Even if we use a signal, if the response is not HTML, it shouldn't inject
            let owner = leptos::prelude::Owner::new_root(None);
            owner.with(|| {
                provide_context(parts);
                let _ = hydrated_signal(DefaultState::initial());
            });
            axum::response::Json(serde_json::json!({"status": "ok"}))
        }))
        .hydrated();

    let req = http::Request::builder().uri("/").body(axum::body::Body::empty()).unwrap();
    let res = app.oneshot(req).await.unwrap();

    assert_eq!(res.headers().get(http::header::CONTENT_TYPE).unwrap(), "application/json");
    let body = axum::body::to_bytes(res.into_body(), 1024).await.unwrap();
    let body_str = String::from_utf8_lossy(&body);
    assert!(!body_str.contains("__lh_data"));
}

#[tokio::test]
async fn test_resource_closure_coverage() {
    init_test_env();
    let local = tokio::task::LocalSet::new();
    local.run_until(async {
        let owner = Owner::new_root(None);
        owner.with(|| {
            let (sig, res) = create_hydrated_signal::<DefaultState, _>(|| DefaultState { value: 10 });
            
            // Trigger first run
            let _ = res.get(); // Triggers the closure
            
            // Set a new value and trigger second run
            sig.set(DefaultState { value: 20 });
            let _ = res.get();
        });
    }).await;
}

#[cfg(feature = "ssr")]
#[tokio::test]
async fn test_get_injected_states_fallback() {
    init_test_env();
    // Case: Parts present, but NO InjectedStates and NO MatchedPath/MockMatchedPath
    let req = http::Request::builder().body(()).unwrap();
    let (parts, _) = req.into_parts();
    
    let owner = Owner::new_root(None);
    owner.with(|| {
        provide_context(parts);
        let states = get_injected_states();
        // Should return a default InjectedStates without panicking
        assert!(states.0.lock().unwrap().is_empty());
    });
}