rari 0.13.6

rari: Runtime Accelerated Rendering Infrastructure - A high-performance React Server Components framework powered by 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
use crate::error::RariError;
use crate::rsc::rendering::core::RscRenderer;
use crate::rsc::utils::dependency_utils::extract_dependencies;
use crate::server::utils::component_utils::{
    has_use_client_directive, has_use_server_directive, wrap_server_action_module,
};
use crate::utils::path_url::path_to_file_url;
use cow_utils::CowUtils;
use tracing::error;

const DIST_DIR: &str = "dist";

pub struct ComponentLoader;

impl ComponentLoader {
    pub async fn load_production_components(renderer: &mut RscRenderer) -> Result<(), RariError> {
        let manifest_path = std::path::Path::new("dist/server/manifest.json");
        if !manifest_path.exists() {
            return Ok(());
        }

        let manifest = Self::read_manifest(manifest_path)?;
        let components = Self::parse_manifest_components(&manifest)?;

        let mut sorted_components: Vec<_> = components.iter().collect();
        sorted_components.sort_by_key(|(id, _)| if id.starts_with("components/") { 0 } else { 1 });

        for (component_id, component_info) in sorted_components {
            if component_id == "proxy" || component_id.ends_with("/proxy") {
                continue;
            }

            let module_specifier = component_info.get("moduleSpecifier").and_then(|s| s.as_str());

            let bundle_path =
                component_info.get("bundlePath").and_then(|p| p.as_str()).ok_or_else(|| {
                    RariError::configuration(format!("Component {component_id} missing bundlePath"))
                })?;

            let component_file = std::path::Path::new(DIST_DIR).join(bundle_path);
            if !component_file.exists() {
                error!("Component file not found: {}", component_file.display());
                continue;
            }

            let component_code = std::fs::read_to_string(&component_file)
                .map_err(|_e| RariError::io("Failed to read component file".to_string()))?;

            let is_server_action = has_use_server_directive(&component_code);

            if let Some(specifier) = module_specifier {
                if let Err(e) = renderer
                    .runtime
                    .add_module_to_loader_only(specifier, component_code.clone())
                    .await
                {
                    error!("Failed to add component {} to module loader: {}", component_id, e);
                    continue;
                }

                match renderer.runtime.load_es_module(component_id).await {
                    Ok(module_id) => {
                        if let Err(e) = renderer.runtime.evaluate_module(module_id).await {
                            error!(
                                "Failed to evaluate module {} (id: {}): {}",
                                component_id, module_id, e
                            );
                            continue;
                        }

                        match renderer.runtime.get_module_namespace(module_id).await {
                            Ok(_namespace) => {
                                let specifier_json = serde_json::to_string(specifier)
                                    .unwrap_or_else(|e| {
                                        error!(
                                            "Failed to serialize module specifier for {}: {}",
                                            component_id, e
                                        );
                                        "\"\"".to_string()
                                    });
                                let component_id_json = serde_json::to_string(component_id)
                                    .unwrap_or_else(|e| {
                                        error!(
                                            "Failed to serialize component_id {}: {}",
                                            component_id, e
                                        );
                                        "\"\"".to_string()
                                    });

                                if is_server_action {
                                    let action_registration_script = format!(
                                        r#"(async function() {{
                                            try {{
                                                const moduleNamespace = await import({});
                                                if (!globalThis['~serverFunctions']) {{
                                                    globalThis['~serverFunctions'] = {{}};
                                                }}
                                                if (!globalThis['~serverFunctions'].all) {{
                                                    globalThis['~serverFunctions'].all = {{}};
                                                }}
                                                if (!globalThis['~serverFunctions'].exported) {{
                                                    globalThis['~serverFunctions'].exported = {{}};
                                                }}
                                                for (const [key, value] of Object.entries(moduleNamespace)) {{
                                                    if (typeof value === 'function') {{
                                                        const moduleKey = {} + ':' + key;
                                                        globalThis['~serverFunctions'].all[moduleKey] = value;
                                                        globalThis['~serverFunctions'].exported[moduleKey] = value;
                                                    }}
                                                }}
                                                return {{ success: true }};
                                            }} catch (error) {{
                                                console.error("Failed to register server action " + {}, error);
                                                return {{ success: false, error: error.message }};
                                            }}
                                        }})()"#,
                                        specifier_json, component_id_json, component_id_json
                                    );

                                    match renderer
                                        .runtime
                                        .execute_script(
                                            format!(
                                                "register_action_{}.js",
                                                component_id.cow_replace('/', "_")
                                            ),
                                            action_registration_script,
                                        )
                                        .await
                                    {
                                        Ok(result) => {
                                            if let Some(success) =
                                                result.get("success").and_then(|v| v.as_bool())
                                                && !success
                                            {
                                                error!(
                                                    "Failed to register server action {}: {:?}",
                                                    component_id,
                                                    result.get("error")
                                                );
                                            }
                                        }
                                        Err(e) => {
                                            error!(
                                                "Failed to register server action {}: {}",
                                                component_id, e
                                            );
                                        }
                                    }
                                }

                                if !is_server_action {
                                    let skip_global_binding = component_id.starts_with("lib/");
                                    let registration_script = format!(
                                        r#"globalThis['~rari'].componentLoader.registerComponent({}, {}, {})"#,
                                        specifier_json, component_id_json, skip_global_binding
                                    );

                                    match renderer
                                        .runtime
                                        .execute_script(
                                            format!(
                                                "register_{}.js",
                                                component_id.cow_replace('/', "_")
                                            ),
                                            registration_script,
                                        )
                                        .await
                                    {
                                        Ok(result) => {
                                            if let Some(success) =
                                                result.get("success").and_then(|v| v.as_bool())
                                                && !success
                                            {
                                                error!(
                                                    "Failed to register component {} to globalThis: {:?}",
                                                    component_id,
                                                    result.get("error")
                                                );
                                            }
                                        }
                                        Err(e) => {
                                            error!(
                                                "Failed to register component {} to globalThis: {}",
                                                component_id, e
                                            );
                                        }
                                    }
                                }
                            }
                            Err(e) => {
                                error!(
                                    "Failed to get module namespace for {}: {}",
                                    component_id, e
                                );
                            }
                        }
                    }
                    Err(e) => {
                        error!("Failed to load component {} as ESM module: {}", component_id, e);
                    }
                }
            } else {
                error!("Component {} missing moduleSpecifier in manifest.", component_id);
            }
        }

        Ok(())
    }

    pub async fn load_server_actions_from_source(
        renderer: &mut RscRenderer,
    ) -> Result<(), RariError> {
        let src_dir = std::path::Path::new("src");
        if !src_dir.exists() {
            return Ok(());
        }

        Self::scan_for_server_actions(src_dir, renderer).await?;

        Ok(())
    }

    fn scan_for_server_actions<'a>(
        dir: &'a std::path::Path,
        renderer: &'a mut RscRenderer,
    ) -> std::pin::Pin<Box<dyn std::future::Future<Output = Result<(), RariError>> + 'a>> {
        Box::pin(async move {
            let entries = std::fs::read_dir(dir).map_err(|e| {
                RariError::io(format!("Failed to read directory {}: {}", dir.display(), e))
            })?;

            for entry in entries {
                let entry = entry
                    .map_err(|e| RariError::io(format!("Failed to read directory entry: {e}")))?;
                let path = entry.path();

                if path.is_dir() {
                    Self::scan_for_server_actions(&path, renderer).await?;
                } else if path
                    .extension()
                    .and_then(|s| s.to_str())
                    .map(|s| s == "ts" || s == "tsx" || s == "js" || s == "jsx")
                    .unwrap_or(false)
                {
                    let code = match std::fs::read_to_string(&path) {
                        Ok(c) => c,
                        Err(_) => continue,
                    };

                    if has_use_server_directive(&code) {
                        let src_dir = std::path::Path::new("src");
                        let relative_path = path.strip_prefix(src_dir).unwrap_or(&path);
                        let action_id = relative_path
                            .to_str()
                            .unwrap_or("unknown")
                            .cow_replace(".ts", "")
                            .cow_replace(".tsx", "")
                            .cow_replace(".js", "")
                            .cow_replace(".jsx", "")
                            .cow_replace('\\', "/")
                            .into_owned();

                        let dist_path = std::path::Path::new("dist")
                            .join("server")
                            .join(format!("{}.js", action_id));

                        if dist_path.exists() {
                            match std::fs::read_to_string(&dist_path) {
                                Ok(dist_code) => {
                                    let canonical_path =
                                        dist_path.canonicalize().unwrap_or(dist_path.clone());
                                    let module_specifier = path_to_file_url(&canonical_path);

                                    let esm_load_result = renderer
                                        .runtime
                                        .add_module_to_loader_only(
                                            &module_specifier,
                                            dist_code.clone(),
                                        )
                                        .await;

                                    if esm_load_result.is_ok() {
                                        match renderer.runtime.load_es_module(&action_id).await {
                                            Ok(module_id) => {
                                                if let Err(e) = renderer
                                                    .runtime
                                                    .evaluate_module(module_id)
                                                    .await
                                                {
                                                    error!(
                                                        "Failed to evaluate server action module {}: {}",
                                                        action_id, e
                                                    );
                                                } else {
                                                    let module_specifier_json = serde_json::to_string(&module_specifier)
                                                        .map_err(|e| {
                                                            error!("Failed to serialize module_specifier for {}: {}", action_id, e);
                                                            RariError::internal(format!("Failed to serialize module_specifier: {}", e))
                                                        })?;
                                                    let action_id_json = serde_json::to_string(
                                                        &action_id,
                                                    )
                                                    .map_err(|e| {
                                                        error!(
                                                            "Failed to serialize action_id {}: {}",
                                                            action_id, e
                                                        );
                                                        RariError::internal(format!(
                                                            "Failed to serialize action_id: {}",
                                                            e
                                                        ))
                                                    })?;

                                                    let registration_script = format!(
                                                        r#"(async function() {{
                                                            try {{
                                                                const moduleNamespace = await import({});
                                                                if (!globalThis['~serverFunctions']) {{
                                                                    globalThis['~serverFunctions'] = {{}};
                                                                }}
                                                                if (!globalThis['~serverFunctions'].all) {{
                                                                    globalThis['~serverFunctions'].all = {{}};
                                                                }}
                                                                if (!globalThis['~serverFunctions'].exported) {{
                                                                    globalThis['~serverFunctions'].exported = {{}};
                                                                }}
                                                                for (const [key, value] of Object.entries(moduleNamespace)) {{
                                                                    if (typeof value === 'function') {{
                                                                        const moduleKey = {} + ':' + key;
                                                                        globalThis['~serverFunctions'].all[moduleKey] = value;
                                                                        globalThis['~serverFunctions'].exported[moduleKey] = value;
                                                                    }}
                                                                }}
                                                                return {{ success: true }};
                                                            }} catch (error) {{
                                                                console.error("Failed to register server action " + {}, error);
                                                                return {{ success: false, error: error.message }};
                                                            }}
                                                        }})()"#,
                                                        module_specifier_json,
                                                        action_id_json,
                                                        action_id_json
                                                    );

                                                    match renderer
                                                        .runtime
                                                        .execute_script(
                                                            format!(
                                                                "register_action_{}.js",
                                                                action_id.cow_replace('/', "_")
                                                            ),
                                                            registration_script,
                                                        )
                                                        .await
                                                    {
                                                        Ok(result) => {
                                                            if let Some(success) = result
                                                                .get("success")
                                                                .and_then(|v| v.as_bool())
                                                                && !success
                                                            {
                                                                if let Some(error_msg) = result
                                                                    .get("error")
                                                                    .and_then(|v| v.as_str())
                                                                {
                                                                    error!(
                                                                        "Failed to register server action {}: {}",
                                                                        action_id, error_msg
                                                                    );
                                                                } else {
                                                                    error!(
                                                                        "Failed to register server action {}: unknown error",
                                                                        action_id
                                                                    );
                                                                }
                                                            }
                                                        }
                                                        Err(e) => {
                                                            error!(
                                                                "Failed to register server action {}: {}",
                                                                action_id, e
                                                            );
                                                        }
                                                    }
                                                }
                                            }
                                            Err(e) => {
                                                error!(
                                                    "Failed to load server action {} as ESM module: {}",
                                                    action_id, e
                                                );
                                            }
                                        }
                                    } else {
                                        let wrapped_code =
                                            wrap_server_action_module(&dist_code, &action_id);
                                        match renderer
                                            .runtime
                                            .execute_script(
                                                format!(
                                                    "load_action_{}.js",
                                                    action_id.cow_replace('/', "_")
                                                ),
                                                wrapped_code,
                                            )
                                            .await
                                        {
                                            Ok(_) => {}
                                            Err(e) => {
                                                error!(
                                                    "Failed to load server action {}: {}",
                                                    action_id, e
                                                );
                                            }
                                        }
                                    }
                                }
                                Err(e) => {
                                    error!(
                                        "Failed to read built server action {:?}: {}",
                                        dist_path, e
                                    );
                                }
                            }
                        }
                    }
                }
            }

            Ok(())
        })
    }

    pub async fn load_app_router_components(renderer: &mut RscRenderer) -> Result<(), RariError> {
        let server_dir = std::path::Path::new(DIST_DIR).join("server");
        if !server_dir.exists() {
            return Ok(());
        }

        Self::load_server_components_recursive(&server_dir, &server_dir, renderer).await?;

        Ok(())
    }

    fn load_server_components_recursive<'a>(
        dir: &'a std::path::Path,
        base_dir: &'a std::path::Path,
        renderer: &'a mut RscRenderer,
    ) -> std::pin::Pin<Box<dyn std::future::Future<Output = Result<(), RariError>> + 'a>> {
        Box::pin(async move {
            let entries = std::fs::read_dir(dir).map_err(|e| {
                RariError::io(format!("Failed to read directory {}: {}", dir.display(), e))
            })?;

            for entry in entries {
                let entry = entry
                    .map_err(|e| RariError::io(format!("Failed to read directory entry: {e}")))?;
                let path = entry.path();

                if path.is_dir() {
                    Self::load_server_components_recursive(&path, base_dir, renderer).await?;
                } else if path.extension().and_then(|s| s.to_str()) == Some("js") {
                    let file_name = path.file_stem().and_then(|s| s.to_str()).unwrap_or("");
                    if file_name == "proxy" {
                        continue;
                    }

                    let component_code = std::fs::read_to_string(&path).map_err(|e| {
                        RariError::io(format!("Failed to read component file: {e}"))
                    })?;

                    if has_use_server_directive(&component_code) {
                        let relative_path = path.strip_prefix(base_dir).unwrap_or(&path);
                        let relative_str = relative_path
                            .to_str()
                            .unwrap_or("unknown")
                            .cow_replace(".js", "")
                            .cow_replace('\\', "/")
                            .into_owned();

                        let canonical_path = path.canonicalize().unwrap_or(path.to_path_buf());
                        let module_specifier = path_to_file_url(&canonical_path);

                        let esm_load_result = renderer
                            .runtime
                            .add_module_to_loader_only(&module_specifier, component_code.clone())
                            .await;

                        if esm_load_result.is_ok() {
                            match renderer.runtime.load_es_module(&relative_str).await {
                                Ok(module_id) => {
                                    if let Err(e) =
                                        renderer.runtime.evaluate_module(module_id).await
                                    {
                                        error!(
                                            "Failed to evaluate server action module {}: {}",
                                            relative_str, e
                                        );
                                    } else {
                                        let module_specifier_json = serde_json::to_string(
                                            &module_specifier,
                                        )
                                        .map_err(|e| {
                                            error!(
                                                "Failed to serialize module_specifier for {}: {}",
                                                relative_str, e
                                            );
                                            RariError::internal(format!(
                                                "Failed to serialize module_specifier: {}",
                                                e
                                            ))
                                        })?;
                                        let relative_str_json =
                                            serde_json::to_string(&relative_str).map_err(|e| {
                                                error!(
                                                    "Failed to serialize relative_str {}: {}",
                                                    relative_str, e
                                                );
                                                RariError::internal(format!(
                                                    "Failed to serialize relative_str: {}",
                                                    e
                                                ))
                                            })?;

                                        let registration_script = format!(
                                            r#"(async function() {{
                                                try {{
                                                    const moduleNamespace = await import({});
                                                    if (!globalThis['~serverFunctions']) {{
                                                        globalThis['~serverFunctions'] = {{}};
                                                    }}
                                                    if (!globalThis['~serverFunctions'].all) {{
                                                        globalThis['~serverFunctions'].all = {{}};
                                                    }}
                                                    if (!globalThis['~serverFunctions'].exported) {{
                                                        globalThis['~serverFunctions'].exported = {{}};
                                                    }}
                                                    for (const [key, value] of Object.entries(moduleNamespace)) {{
                                                        if (typeof value === 'function') {{
                                                            const moduleKey = {} + ':' + key;
                                                            globalThis['~serverFunctions'].all[moduleKey] = value;
                                                            globalThis['~serverFunctions'].exported[moduleKey] = value;
                                                        }}
                                                    }}
                                                    return {{ success: true }};
                                                }} catch (error) {{
                                                    console.error("Failed to register server action " + {}, error);
                                                    return {{ success: false, error: error.message }};
                                                }}
                                            }})()"#,
                                            module_specifier_json,
                                            relative_str_json,
                                            relative_str_json
                                        );

                                        match renderer
                                            .runtime
                                            .execute_script(
                                                format!(
                                                    "register_{}.js",
                                                    relative_str.cow_replace('/', "_")
                                                ),
                                                registration_script,
                                            )
                                            .await
                                        {
                                            Ok(result) => {
                                                if let Some(success) =
                                                    result.get("success").and_then(|v| v.as_bool())
                                                    && !success
                                                {
                                                    if let Some(error_msg) =
                                                        result.get("error").and_then(|v| v.as_str())
                                                    {
                                                        error!(
                                                            "Failed to register server functions from {}: {}",
                                                            relative_str, error_msg
                                                        );
                                                    } else {
                                                        error!(
                                                            "Failed to register server functions from {}: unknown error",
                                                            relative_str
                                                        );
                                                    }
                                                }
                                            }
                                            Err(e) => {
                                                error!(
                                                    "Failed to register server functions from {}: {}",
                                                    relative_str, e
                                                );
                                            }
                                        }
                                    }
                                }
                                Err(e) => {
                                    error!(
                                        "Failed to load server action {} as ESM module: {}",
                                        relative_str, e
                                    );
                                }
                            }
                        } else {
                            let wrapped_code =
                                wrap_server_action_module(&component_code, &relative_str);
                            match renderer
                                .runtime
                                .execute_script(
                                    format!("load_{}.js", relative_str.cow_replace('/', "_")),
                                    wrapped_code,
                                )
                                .await
                            {
                                Ok(_) => {}
                                Err(e) => {
                                    error!(
                                        "Failed to load server actions from {}: {}",
                                        relative_str, e
                                    );
                                }
                            }
                        }
                        continue;
                    }

                    let relative_path = path.strip_prefix(base_dir).unwrap_or(&path);
                    let relative_str = relative_path
                        .to_str()
                        .unwrap_or("unknown")
                        .cow_replace(".js", "")
                        .cow_replace('\\', "/")
                        .into_owned();

                    let component_id = relative_str.clone();

                    let is_client_component = has_use_client_directive(&component_code);

                    let transformed_module_code = component_code.clone();

                    let dependencies = extract_dependencies(&component_code);

                    {
                        let mut registry = renderer.component_registry.lock();
                        let _ = registry.register_component(
                            &component_id,
                            &component_code,
                            transformed_module_code.clone(),
                            dependencies.clone().into_iter().collect(),
                        );
                    }

                    let canonical_path = path.canonicalize().unwrap_or(path.to_path_buf());
                    let module_specifier = path_to_file_url(&canonical_path);

                    let esm_load_result = renderer
                        .runtime
                        .add_module_to_loader_only(&module_specifier, component_code.clone())
                        .await;

                    if esm_load_result.is_ok() {
                        match renderer.runtime.load_es_module(&component_id).await {
                            Ok(module_id) => {
                                if let Err(e) = renderer.runtime.evaluate_module(module_id).await {
                                    error!(
                                        "Failed to evaluate ESM module {} (id: {}): {}",
                                        component_id, module_id, e
                                    );
                                } else {
                                    let skip_global_binding = component_id.starts_with("lib/");
                                    let module_specifier_json =
                                        serde_json::to_string(&module_specifier).map_err(|e| {
                                            error!(
                                                "Failed to serialize module_specifier for {}: {}",
                                                component_id, e
                                            );
                                            RariError::internal(format!(
                                                "Failed to serialize module_specifier: {}",
                                                e
                                            ))
                                        })?;
                                    let component_id_json = serde_json::to_string(&component_id)
                                        .map_err(|e| {
                                            error!(
                                                "Failed to serialize component_id {}: {}",
                                                component_id, e
                                            );
                                            RariError::internal(format!(
                                                "Failed to serialize component_id: {}",
                                                e
                                            ))
                                        })?;
                                    let registration_script = format!(
                                        r#"globalThis['~rari'].componentLoader.registerComponent({}, {}, {})"#,
                                        module_specifier_json,
                                        component_id_json,
                                        skip_global_binding
                                    );

                                    match renderer
                                        .runtime
                                        .execute_script(
                                            format!(
                                                "register_{}.js",
                                                component_id.cow_replace('/', "_")
                                            ),
                                            registration_script,
                                        )
                                        .await
                                    {
                                        Ok(result) => {
                                            let registration_succeeded = result
                                                .get("success")
                                                .and_then(|v| v.as_bool())
                                                .unwrap_or(false);

                                            if !registration_succeeded {
                                                error!(
                                                    "Failed to register component {} to globalThis: {:?}",
                                                    component_id,
                                                    result.get("error")
                                                );
                                            }

                                            if registration_succeeded && is_client_component {
                                                let component_id_json = serde_json::to_string(
                                                    &component_id,
                                                )
                                                .unwrap_or_else(|e| {
                                                    error!(
                                                        "Failed to serialize component_id {}: {}",
                                                        component_id, e
                                                    );
                                                    "\"\"".to_string()
                                                });
                                                let mark_client_script = if skip_global_binding {
                                                    format!(
                                                        r#"(function() {{
                                                            const module = globalThis['~rsc']?.modules?.[{}];
                                                            if (module) {{
                                                                const comp = module.default || Object.values(module).find(v => typeof v === 'function');
                                                                if (comp && typeof comp === 'function') {{
                                                                    comp['~isClientComponent'] = true;
                                                                    comp['~clientComponentId'] = {};
                                                                }}
                                                            }}
                                                            return {{ componentId: {}, isClient: true }};
                                                        }})()"#,
                                                        component_id_json,
                                                        component_id_json,
                                                        component_id_json
                                                    )
                                                } else {
                                                    format!(
                                                        r#"(function() {{
                                                            const comp = globalThis[{}];
                                                            if (comp && typeof comp === 'function') {{
                                                                comp['~isClientComponent'] = true;
                                                                comp['~clientComponentId'] = {};
                                                            }}
                                                            return {{ componentId: {}, isClient: true }};
                                                        }})()"#,
                                                        component_id_json,
                                                        component_id_json,
                                                        component_id_json
                                                    )
                                                };

                                                if let Err(e) = renderer
                                                    .runtime
                                                    .execute_script(
                                                        format!(
                                                            "mark_client_{}.js",
                                                            component_id.cow_replace('/', "_")
                                                        ),
                                                        mark_client_script,
                                                    )
                                                    .await
                                                {
                                                    error!(
                                                        "Failed to mark component {} as client: {}",
                                                        component_id, e
                                                    );
                                                }
                                            }
                                        }
                                        Err(e) => {
                                            error!(
                                                "Failed to register component {}: {}",
                                                component_id, e
                                            );
                                        }
                                    }
                                }
                            }
                            Err(e) => {
                                error!(
                                    "Failed to load component {} as ESM module: {}",
                                    component_id, e
                                );
                            }
                        }
                    } else {
                        match renderer
                            .runtime
                            .execute_script(
                                format!("load_{}.js", component_id.cow_replace('/', "_")),
                                transformed_module_code,
                            )
                            .await
                        {
                            Ok(_) => {
                                if is_client_component {
                                    let skip_global_binding = component_id.starts_with("lib/");
                                    let component_id_json = serde_json::to_string(&component_id)
                                        .unwrap_or_else(|e| {
                                            error!(
                                                "Failed to serialize component_id {}: {}",
                                                component_id, e
                                            );
                                            "\"\"".to_string()
                                        });

                                    let mark_client_script = if skip_global_binding {
                                        format!(
                                            r#"(function() {{
                                                const module = globalThis['~rsc']?.modules?.[{}];
                                                if (module) {{
                                                    const comp = module.default || Object.values(module).find(v => typeof v === 'function');
                                                    if (comp && typeof comp === 'function') {{
                                                        comp['~isClientComponent'] = true;
                                                        comp['~clientComponentId'] = {};
                                                    }}
                                                }}
                                                return {{ componentId: {}, isClient: true }};
                                            }})()"#,
                                            component_id_json, component_id_json, component_id_json
                                        )
                                    } else {
                                        format!(
                                            r#"(function() {{
                                                const comp = globalThis[{}];
                                                if (comp && typeof comp === 'function') {{
                                                    comp['~isClientComponent'] = true;
                                                    comp['~clientComponentId'] = {};
                                                }}
                                                return {{ componentId: {}, isClient: true }};
                                            }})()"#,
                                            component_id_json, component_id_json, component_id_json
                                        )
                                    };

                                    if let Err(e) = renderer
                                        .runtime
                                        .execute_script(
                                            format!(
                                                "mark_client_{}.js",
                                                component_id.cow_replace('/', "_")
                                            ),
                                            mark_client_script,
                                        )
                                        .await
                                    {
                                        error!(
                                            "Failed to mark component {} as client: {}",
                                            component_id, e
                                        );
                                    }
                                }
                            }
                            Err(e) => {
                                error!("Failed to execute component {}: {}", component_id, e);
                            }
                        }
                    }
                }
            }

            Ok(())
        })
    }

    fn read_manifest(manifest_path: &std::path::Path) -> Result<serde_json::Value, RariError> {
        let manifest_content = std::fs::read_to_string(manifest_path)
            .map_err(|e| RariError::io(format!("Failed to read server manifest: {e}")))?;

        serde_json::from_str(&manifest_content)
            .map_err(|e| RariError::configuration(format!("Failed to parse server manifest: {e}")))
    }

    fn parse_manifest_components(
        manifest: &serde_json::Value,
    ) -> Result<&serde_json::Map<String, serde_json::Value>, RariError> {
        manifest.get("components").and_then(|c| c.as_object()).ok_or_else(|| {
            RariError::configuration("Invalid manifest: missing components".to_string())
        })
    }

    pub async fn load_component_from_manifest(
        component_id: &str,
        component_info: &serde_json::Value,
        renderer: &mut RscRenderer,
    ) -> Result<(), RariError> {
        let bundle_path =
            component_info.get("bundlePath").and_then(|p| p.as_str()).ok_or_else(|| {
                RariError::configuration(format!("Component {component_id} missing bundlePath"))
            })?;

        let component_file = std::path::Path::new(DIST_DIR).join(bundle_path);

        if !component_file.exists() {
            return Err(RariError::not_found(format!(
                "Component file not found: {}",
                component_file.display()
            )));
        }

        let component_code = std::fs::read_to_string(&component_file)
            .map_err(|e| RariError::io(format!("Failed to read component file: {e}")))?;

        renderer
            .register_component(component_id, &component_code)
            .await
            .map_err(|e| RariError::internal(format!("Failed to register component: {e}")))
    }
}