farmfe_plugin_bundle 0.0.9

resource pot to bundle
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
use std::{
  collections::{HashMap, HashSet},
  mem::{self, replace},
  sync::{Arc, Mutex, RwLock},
};

use bundle_external::BundleReference;
use farmfe_core::{
  config::external::ExternalConfig,
  context::CompilationContext,
  error::{CompilationError, MapCompletionError, Result},
  farm_profile_function, farm_profile_scope,
  module::{module_graph::ModuleGraph, ModuleId, ModuleSystem},
  plugin::ResolveKind,
  rayon::iter::{IndexedParallelIterator, IntoParallelIterator, ParallelIterator},
  swc_common::{util::take::Take, DUMMY_SP},
  swc_ecma_ast::{
    self, BindingIdent, CallExpr, ClassDecl, Decl, EmptyStmt, Expr, ExprStmt, FnDecl, Ident,
    Module, ModuleDecl, ModuleItem, Stmt, VarDecl, VarDeclarator,
  },
};
use farmfe_toolkit::{script::swc_try_with::try_with, swc_ecma_visit::VisitMutWith};

pub mod bundle_analyzer;
pub mod bundle_external;
pub mod bundle_variable;
pub mod reference;
use crate::resource_pot_to_bundle::targets::{
  cjs::patch::CjsPatch, dynamic_import::replace_dynamic_import,
};

use self::reference::ReferenceMap;

use super::{
  common::OptionToResult,
  defined_idents_collector::RenameIdent,
  modules_analyzer::module_analyzer::{
    ExportSpecifierInfo, ImportSpecifierInfo, ModuleAnalyzer, StmtAction,
  },
  polyfill::SimplePolyfill,
  targets::generate::generate_namespace_by_reference_map,
  uniq_name::BundleVariable,
};
pub struct ModuleAnalyzerManager<'a> {
  pub module_map: HashMap<ModuleId, ModuleAnalyzer>,
  pub namespace_modules: HashSet<ModuleId>,

  ///
  ///
  /// TODO: dynamic generate
  ///
  /// ```js
  /// // namespace/moduleA.js
  /// export const foo = 'foo';
  /// export const bar = 'bar'
  ///
  /// // importA.js
  /// export * as moduleA from './moduleA.js';
  ///
  /// // importB.js
  /// export * as moduleB from './moduleA.js';
  /// ```
  ///
  ///
  /// {
  ///   "namespace/moduleA.js": (moduleA, {
  ///       "importA.js": "moduleA",
  ///       "importB.js": "moduleB"
  ///   })
  /// }
  ///
  ///
  pub module_global_uniq_name: ModuleGlobalUniqName,
  module_graph: &'a ModuleGraph,
}

#[derive(Debug)]
struct ModuleGlobalName {
  namespace: Option<usize>,
  default: Option<usize>,
  commonjs: Option<usize>,
}

impl ModuleGlobalName {
  fn new() -> Self {
    Self {
      namespace: None,
      default: None,
      commonjs: None,
    }
  }
}

#[derive(Debug, Default)]
pub struct ModuleGlobalUniqName {
  module_map: HashMap<ModuleId, ModuleGlobalName>,
}

impl ModuleGlobalUniqName {
  fn new() -> Self {
    Self {
      module_map: HashMap::default(),
    }
  }

  pub fn namespace_name(&self, module_id: &ModuleId) -> Option<usize> {
    self
      .module_map
      .get(module_id)
      .and_then(|item| item.namespace)
  }

  pub fn default_name(&self, module_id: &ModuleId) -> Option<usize> {
    self.module_map.get(module_id).and_then(|item| item.default)
  }

  pub fn commonjs_name(&self, module_id: &ModuleId) -> Option<usize> {
    self
      .module_map
      .get(module_id)
      .and_then(|item| item.commonjs)
  }

  pub fn default_name_result(&self, module_id: &ModuleId) -> Result<usize> {
    self
      .default_name(module_id)
      .to_result("not found module {:?} default name")
  }

  fn entry_module(&mut self, module_id: &ModuleId) -> &mut ModuleGlobalName {
    if !self.module_map.contains_key(module_id) {
      self
        .module_map
        .insert(module_id.clone(), ModuleGlobalName::new());
    }

    self.module_map.get_mut(module_id).unwrap()
  }

  fn add_namespace<F: FnOnce(&str) -> usize>(&mut self, module_id: &ModuleId, v: F) {
    let m = self.entry_module(module_id);

    if m.namespace.is_none() {
      m.namespace = Some(v("_ns"));
    }
  }

  fn add_default<F: FnOnce(&str) -> usize>(&mut self, module_id: &ModuleId, v: F) {
    let m = self.entry_module(module_id);

    if m.default.is_none() {
      m.default = Some(v("_default"));
    }
  }

  fn add_commonjs<F: FnOnce(&str) -> usize>(&mut self, module_id: &ModuleId, v: F) {
    let m = self.entry_module(module_id);

    if m.commonjs.is_none() {
      m.commonjs = Some(v("_cjs"));
    }
  }
}

impl Take for ModuleGlobalUniqName {
  fn dummy() -> Self {
    Default::default()
  }
}

impl<'a> ModuleAnalyzerManager<'a> {
  pub fn new(module_map: HashMap<ModuleId, ModuleAnalyzer>, module_graph: &'a ModuleGraph) -> Self {
    Self {
      module_map,
      namespace_modules: HashSet::new(),
      module_global_uniq_name: ModuleGlobalUniqName::new(),
      module_graph,
    }
  }

  pub fn extract_modules_statements(
    &mut self,
    modules: &Vec<&ModuleId>,
    context: &Arc<CompilationContext>,
    module_graph: &ModuleGraph,
    bundle_variable: &mut BundleVariable,
  ) -> Result<()> {
    farm_profile_function!();

    let data = Mutex::new(vec![]);
    // TODO: performance optimization
    let module_map = {
      mem::take(&mut self.module_map)
        .into_iter()
        .map(|(key, val)| (key, Arc::new(RwLock::new(val))))
        .collect::<HashMap<ModuleId, Arc<RwLock<ModuleAnalyzer>>>>()
    };

    modules
      .into_par_iter()
      .enumerate()
      .try_for_each(|(index, module_id)| {
        let mut module_analyzer = module_map
          .get(module_id)
          .map(|item| item.write().unwrap())
          .unwrap();
        let mut new_bundle_variable = bundle_variable.branch();
        new_bundle_variable.set_namespace(module_analyzer.resource_pot_id.clone());
        farm_profile_scope!(format!(
          "extract module statement: {:?}",
          module_id.to_string()
        ));

        module_analyzer.extract_statement(module_graph, context, &mut new_bundle_variable)?;

        data.lock().map_c_error()?.push((
          index,
          (
            module_analyzer.cjs_module_analyzer.require_modules.clone(),
            new_bundle_variable,
          ),
        ));
        Ok::<(), CompilationError>(())
      })?;

    let mut map = HashMap::new();

    for (key, val) in module_map {
      map.insert(
        key,
        Arc::try_unwrap(val).unwrap().into_inner().map_c_error()?,
      );
    }

    let _ = mem::replace(&mut self.module_map, map);

    let mut values = data.into_inner().map_c_error()?;

    values.sort_by_key(|(index, _)| *index);

    for (_, (require_modules, inner_bundle_variable)) in values {
      self.namespace_modules.extend(require_modules);

      bundle_variable.merge(inner_bundle_variable);
    }

    Ok(())
  }

  #[inline]
  pub fn is_commonjs(&self, module_id: &ModuleId) -> bool {
    self
      .module_map
      .get(module_id)
      .map(|item| item.is_commonjs())
      .unwrap_or(false)
  }

  #[inline]
  pub fn is_entry(&self, module_id: &ModuleId) -> bool {
    self
      .module_map
      .get(module_id)
      .map(|item| item.entry)
      .unwrap_or(false)
  }

  pub fn module_system(&self, module_id: &ModuleId) -> ModuleSystem {
    self
      .module_map
      .get(module_id)
      .map(|item| item.module_system.clone())
      .unwrap()
  }

  pub fn is_hybrid_or_esm(&self, module_id: &ModuleId) -> bool {
    self
      .module_map
      .get(module_id)
      .map(|item| item.is_hybrid_esm())
      .unwrap_or(false)
  }

  #[inline]
  pub fn get_export_names(&self, module_id: &ModuleId) -> Arc<ReferenceMap> {
    self
      .module_map
      .get(module_id)
      .map(|m| m.export_names())
      .unwrap_or_else(|| Arc::new(ReferenceMap::new(self.module_system(module_id))))
  }

  #[inline]
  pub fn module_analyzer(&self, module_id: &ModuleId) -> Option<&ModuleAnalyzer> {
    self.module_map.get(module_id)
  }

  #[inline]
  pub fn module_analyzer_unchecked(&self, module_id: &ModuleId) -> &ModuleAnalyzer {
    &self.module_map[module_id]
  }

  #[inline]
  pub fn is_external(&self, module_id: &ModuleId) -> bool {
    self
      .module_graph
      .module(module_id)
      .is_some_and(|m| m.external)
  }

  #[inline]
  pub fn module_analyzer_mut(&mut self, module_id: &ModuleId) -> Option<&mut ModuleAnalyzer> {
    self.module_map.get_mut(module_id)
  }

  #[inline]
  pub fn module_analyzer_mut_unchecked(&mut self, module_id: &ModuleId) -> &mut ModuleAnalyzer {
    self.module_map.get_mut(module_id).unwrap()
  }

  #[inline]
  pub fn set_ast_body(&mut self, module_id: &ModuleId, ast_body: Vec<ModuleItem>) {
    self.module_analyzer_mut_unchecked(module_id).ast.body = ast_body;
  }

  #[inline]
  pub fn set_ast(&mut self, module_id: &ModuleId, ast_body: Module) {
    self.module_analyzer_mut_unchecked(module_id).ast = ast_body;
  }

  pub fn module_analyzer_by_source(
    &self,
    module_id: &ModuleId,
    source: &str,
  ) -> Option<&ModuleAnalyzer> {
    if let Some(m) = self.module_graph.get_dep_by_source_optional(
      module_id,
      source,
      Some(ResolveKind::DynamicImport),
    ) {
      return self.module_map.get(&m);
    }

    None
  }

  pub fn is_same_bundle(&self, a: &ModuleId, b: &ModuleId) -> bool {
    match (self.module_analyzer(a), self.module_analyzer(b)) {
      (Some(a), Some(b)) => a.resource_pot_id == b.resource_pot_id,
      _ => false,
    }
  }

  #[inline]
  pub fn is_contain_namespace(&self, module_id: &ModuleId) -> bool {
    self
      .module_global_uniq_name
      .namespace_name(module_id)
      .is_some()
  }

  /// ---
  /// 1. all export continue to search
  /// 2. named export need filter
  ///   2-1. has source continue search with filter
  ///   2-2. no source collect
  /// 3. namespace export collect and skip
  /// 4. default export skip
  ///
  /// if export all, should skip default export
  pub fn build_export_names(
    &mut self,
    module_id: &ModuleId,
    bundle_variable: &BundleVariable,
  ) -> Arc<ReferenceMap> {
    let exports_stmts = if let Some(module_analyzer) = self.module_analyzer(module_id) {
      if let Some(export_names) = &module_analyzer.export_names {
        return export_names.clone();
      }

      module_analyzer
        .exports_stmts()
        .into_iter()
        .cloned()
        .collect::<Vec<_>>()
    } else {
      vec![]
    };

    let mut map = ReferenceMap::new(self.module_system(module_id));

    // preventing circular references
    if let Some(m) = self.module_analyzer_mut(module_id) {
      m.export_names = Some(Arc::new(map.clone()));
    }

    for export in exports_stmts {
      for specify in export.specifiers.iter() {
        if let Some(ref source) = export.source {
          if self.is_external(source) {
            map.add_reference(source, specify);
            continue;
          }

          if self.is_commonjs(source) {
            map.add_commonjs(source, specify);
            continue;
          }

          match specify {
            ExportSpecifierInfo::All(_) => {
              let result = self.build_export_names(source, bundle_variable);
              map.extends(&result);
            }

            ExportSpecifierInfo::Named(export) => {
              let export_map = self.build_export_names(source, bundle_variable);
              if let Some(i) = export_map.query(export.export_from(), bundle_variable) {
                map.add_local(&ExportSpecifierInfo::Named(
                  (i, Some(export.export_as())).into(),
                ))
              };
            }

            ExportSpecifierInfo::Default(_) | ExportSpecifierInfo::Namespace(_) => {
              map.add_local(specify);
            }
          }
        } else {
          match specify {
            ExportSpecifierInfo::All(_) => {
              unreachable!("export All source should not be None")
            }

            ExportSpecifierInfo::Namespace(_) => {
              unreachable!("export namespace source should not be None")
            }

            _ => {
              map.add_local(specify);
            }
          }
        }
      }
    }

    if self.is_commonjs(module_id) && self.module_analyzer(module_id).is_some_and(|m| m.entry) {
      // map
    }

    if let Some(m) = self.module_analyzer_mut(module_id) {
      m.export_names = Some(Arc::new(map));
    }

    self.get_export_names(module_id)
  }

  pub fn patch_module_analyzer_ast(
    &mut self,
    module_id: &ModuleId,
    context: &Arc<CompilationContext>,
    module_graph: &ModuleGraph,
    bundle_variable: &mut BundleVariable,
    bundle_reference: &mut BundleReference,
    commonjs_import_executed: &mut HashSet<ModuleId>,
    order_index_map: &HashMap<ModuleId, usize>,
    polyfill: &mut SimplePolyfill,
    external_config: &ExternalConfig,
  ) -> Result<()> {
    farm_profile_function!(format!(
      "patch module analyzer ast: {}",
      module_id.to_string()
    ));

    let namespace = self.module_global_uniq_name.namespace_name(module_id);

    self.patch_module(
      module_id,
      context,
      bundle_variable,
      module_graph,
      namespace,
      bundle_reference,
      commonjs_import_executed,
      order_index_map,
      polyfill,
      external_config,
    )?;

    Ok(())
  }

  fn patch_namespace(
    &mut self,
    module_id: &ModuleId,
    namespace: Option<usize>,
    bundle_variable: &BundleVariable,
    bundle_reference: &mut BundleReference,
    patch_asts: &mut Vec<ModuleItem>,
    order_index_map: &HashMap<ModuleId, usize>,
    polyfill: &mut SimplePolyfill,
  ) -> Result<()> {
    if self.is_commonjs(module_id) {
      return Ok(());
    }

    if let Some(ns) = namespace {
      patch_asts.extend(generate_namespace_by_reference_map(
        module_id,
        ns,
        bundle_variable,
        bundle_reference,
        &self.build_export_names(module_id, bundle_variable),
        self,
        order_index_map,
        polyfill,
      )?);
    }

    Ok(())
  }

  fn strip_module_decl(
    &mut self,
    module_id: &ModuleId,
    bundle_variable: &BundleVariable,
    commonjs_import_executed: &mut HashSet<ModuleId>,
  ) {
    let module_analyzer = self.module_analyzer_mut_unchecked(module_id);
    let mut stmt_actions = module_analyzer
      .statement_actions
      .clone()
      .into_iter()
      .collect::<Vec<_>>();
    stmt_actions.sort_by_key(|a| std::cmp::Reverse(a.index()));
    let mut ast = module_analyzer.ast.take();

    stmt_actions.iter().for_each(|action| {
            let mut replace_ast_item = |index: usize| {
              replace(&mut ast.body[index], ModuleItem::Stmt(Stmt::Empty(EmptyStmt { span: DUMMY_SP })))
            };

            match action {
              StmtAction::StripExport(index) => {
                if let ModuleItem::ModuleDecl(ModuleDecl::ExportDecl(export_decl)) = replace_ast_item(*index) {
                  ast.body[*index] = ModuleItem::Stmt(Stmt::Decl(export_decl.decl))
                }
              },

              StmtAction::StripDefaultExport(index, rename) => {
                if let ModuleItem::ModuleDecl(ModuleDecl::ExportDefaultDecl(export_decl)) = replace_ast_item(*index) {
                  let rendered_name = bundle_variable.render_name(*rename);
                  ast.body[*index] = ModuleItem::Stmt(Stmt::Decl(match export_decl.decl {
                    swc_ecma_ast::DefaultDecl::Class(class) => {
                      Decl::Class(
                        ClassDecl {
                          ident: Ident::from(rendered_name.as_str()),
                          declare: false,
                          class: class.class,
                        },
                      )
                    },
                    swc_ecma_ast::DefaultDecl::Fn(f) => {
                      Decl::Fn(FnDecl {
                        ident: Ident::from(rendered_name.as_str()),
                        declare: false,
                        function: f.function,
                      })
                    },
                    _ => {
                      unreachable!(
                        "export_default_decl.decl should not be anything clone() other than a class, function"
                      )
                    },
                  }));
                }
              }

              StmtAction::DeclDefaultExpr(index, var) => {
                match replace_ast_item(*index) {
                  ModuleItem::ModuleDecl(decl) => {
                    match decl {
                        ModuleDecl::ExportDefaultDecl(export) => {
                          let default_name = bundle_variable.render_name(self.module_global_uniq_name.default_name(module_id).unwrap());
                          match export.decl {
                            swc_ecma_ast::DefaultDecl::Class(class) => {
                              ast.body[*index] = ModuleItem::Stmt(Stmt::Decl(Decl::Class(ClassDecl {
                                ident: Ident::from(default_name.as_str()),
                                declare: false,
                                class: class.class,
                              })));
                            },
                            swc_ecma_ast::DefaultDecl::Fn(f) => {
                              ast.body[*index] = ModuleItem::Stmt(Stmt::Decl(Decl::Fn(FnDecl {
                                ident: Ident::from(default_name.as_str()),
                                declare: false,
                                function: f.function,
                              })));
                            },
                            _ => {
                              unreachable!("ExportDefault should not be anything other than a class, function")
                            }
                          }
                        },
                        ModuleDecl::ExportDefaultExpr(export_default_decl) => {
                          ast.body[*index] =
                          ModuleItem::Stmt(Stmt::Decl(Decl::Var(Box::new(VarDecl {
                            span: DUMMY_SP,
                            kind: swc_ecma_ast::VarDeclKind::Var,
                            declare: false,
                            decls: vec![VarDeclarator {
                              span: DUMMY_SP,
                              name: swc_ecma_ast::Pat::Ident(BindingIdent {
                                id: Ident::from(bundle_variable.render_name(*var).as_str()),
                                type_ann: None,
                              }),
                              init: Some(export_default_decl.expr),
                              definite: false,
                            }],
                          }))));
                        },
                        _ => {}
                    }
                  },
                  _ => {
                    unreachable!("ExportDefault should not be anything other than a class, function");
                  }
                }
              }

              StmtAction::StripCjsImport(index, import_execute_module) => {
                replace_ast_item(*index);
                if let Some(source) = import_execute_module {
                  if !commonjs_import_executed.contains(source) {
                    ast.body[*index] = ModuleItem::Stmt(Stmt::Expr(
                      ExprStmt { span: DUMMY_SP, expr: Box::new(Expr::Call(
                        CallExpr { span: DUMMY_SP, callee: swc_ecma_ast::Callee::Expr(Box::new(Expr::Ident(bundle_variable.name(self.module_global_uniq_name.commonjs_name(source).unwrap()).as_str().into()))), args: vec![], type_args: None }
                      )) }
                    ));
                    commonjs_import_executed.insert(source.clone());
                  }
                }
              }

              StmtAction::RemoveImport(index) => {
                replace_ast_item(*index);
              }
            }

        });

    let module_analyzer = self.module_analyzer_mut_unchecked(module_id);
    module_analyzer.ast = ast;
  }

  fn patch_module(
    &mut self,
    module_id: &ModuleId,
    context: &Arc<CompilationContext>,
    bundle_variable: &mut BundleVariable,
    module_graph: &ModuleGraph,
    namespace: Option<usize>,
    bundle_reference: &mut BundleReference,
    commonjs_import_executed: &mut HashSet<ModuleId>,
    order_index_map: &HashMap<ModuleId, usize>,
    polyfill: &mut SimplePolyfill,
    external_config: &ExternalConfig,
  ) -> Result<()> {
    farm_profile_function!("");

    if self.module_analyzer(module_id).is_none() {
      return Ok(());
    }

    let module_analyzer = self.module_analyzer_mut(module_id).unwrap();

    let cm = module_analyzer.cm.clone();

    try_with(cm, &context.meta.script.globals, || {
      // 1. strip/remove export
      self.strip_module_decl(module_id, bundle_variable, commonjs_import_executed);

      let mut patch_asts = vec![];

      // TODO: exact generate namespace in used
      // 2. generate namespace for module
      self
        .patch_namespace(
          module_id,
          namespace,
          bundle_variable,
          bundle_reference,
          &mut patch_asts,
          order_index_map,
          polyfill,
        )
        .unwrap();

      // 3. process hybrid module or commonjs
      CjsPatch::patch_cjs_module(
        self,
        module_id,
        module_graph,
        context,
        &mut patch_asts,
        bundle_variable,
        bundle_reference,
        polyfill,
      );

      // 1. append ast
      // 2. replace commonjs require
      // 3. rename
      {
        let module_analyzer = self.module_analyzer_mut_unchecked(module_id);
        let mut ast = module_analyzer.ast.take();

        let rename_map = module_analyzer.build_rename_map(bundle_variable);

        ast.body.extend(patch_asts);

        if matches!(
          module_analyzer.module_system,
          ModuleSystem::CommonJs | ModuleSystem::Hybrid
        ) {
          CjsPatch::replace_cjs_require(
            module_analyzer.mark,
            &mut ast,
            module_id,
            module_graph,
            &self.module_global_uniq_name,
            bundle_variable,
            &context.config,
            polyfill,
            external_config,
          )
        }

        ast.body = mem::take(&mut ast.body)
          .into_iter()
          .filter_map(|item| match item {
            ModuleItem::Stmt(Stmt::Empty(_)) => None,
            _ => Some(item),
          })
          .collect::<Vec<_>>();

        ast.visit_mut_with(&mut replace_dynamic_import(
          self,
          module_id,
          bundle_variable,
        ));

        ast.visit_mut_with(&mut RenameIdent::new(rename_map));

        self.set_ast(module_id, ast);
      }
    })
    .unwrap();

    Ok(())
  }

  pub fn link(
    &mut self,
    bundle_variable: &mut BundleVariable,
    order_index_map: &HashMap<ModuleId, usize>,
    context: &Arc<CompilationContext>,
  ) {
    farm_profile_scope!("link module analyzer");
    let root = &context.config.root;
    let mut ordered_module_ids = order_index_map.keys().collect::<Vec<_>>();

    ordered_module_ids.sort_by(|a, b| order_index_map[b].cmp(&order_index_map[a]));

    for module_id in ordered_module_ids {
      if self.module_map.contains_key(module_id) {
        self.build_export_names(module_id, bundle_variable);
      }

      let Some(module_analyzer) = self.module_map.get(module_id) else {
        continue;
      };

      farm_profile_scope!(format!(
        "link module analyzer: {}",
        module_analyzer.module_id.to_string()
      ));

      bundle_variable.set_namespace(module_analyzer.resource_pot_id.clone());

      // in this time, it import by cjs require
      if self.namespace_modules.contains(&module_analyzer.module_id)
        || self.is_external(&module_analyzer.module_id)
        || self.module_graph.is_dynamic(module_id)
      {
        self
          .module_global_uniq_name
          .add_namespace(&module_analyzer.module_id, |v| {
            bundle_variable.register_used_name_by_module_id(&module_analyzer.module_id, v, root)
          });

        if self.is_external(&module_analyzer.module_id) {
          continue;
        }
      };

      if module_analyzer.is_commonjs() {
        self
          .module_global_uniq_name
          .add_commonjs(&module_analyzer.module_id, |v| {
            bundle_variable.register_used_name_by_module_id(&module_analyzer.module_id, v, root)
          });

        if module_analyzer.entry {
          self
            .module_global_uniq_name
            .add_namespace(&module_analyzer.module_id, |v| {
              bundle_variable.register_used_name_by_module_id(&module_analyzer.module_id, v, root)
            });
        }
      }

      if matches!(module_analyzer.module_system, ModuleSystem::CommonJs) {
        continue;
      }

      let is_hybrid = matches!(module_analyzer.module_system, ModuleSystem::Hybrid);

      // hybrid | esm
      for statement in &module_analyzer.statements {
        if let Some(s) = &statement.import {
          if self.is_external(&s.source)
            || s
              .specifiers
              .iter()
              .any(|specify| matches!(specify, ImportSpecifierInfo::Namespace(_)))
          {
            self.module_global_uniq_name.add_namespace(&s.source, |v| {
              bundle_variable.register_used_name_by_module_id(&s.source, v, root)
            });
          }
        }

        if let Some(s) = &statement.export {
          if is_hybrid {
            if let Some(source) = s.source.as_ref() {
              if !self.is_commonjs(source) {
                self.module_global_uniq_name.add_namespace(source, |s| {
                  bundle_variable.register_used_name_by_module_id(source, s, root)
                });
              }
            }
          }

          if let Some(module_id) = s.source.as_ref() {
            if self.is_external(module_id) {
              self.module_global_uniq_name.add_namespace(module_id, |s| {
                bundle_variable.register_used_name_by_module_id(module_id, s, root)
              })
            }
          }

          for specify in &s.specifiers {
            match specify {
              ExportSpecifierInfo::Default(n) => {
                if bundle_variable.name(*n) == "default" {
                  self
                    .module_global_uniq_name
                    .add_default(&module_analyzer.module_id, |s| {
                      bundle_variable.register_used_name_by_module_id(&module_analyzer.module_id, s, root)
                    });
                }
              }

              ExportSpecifierInfo::Namespace(_) |
              // maybe used in namespace
              ExportSpecifierInfo::All(_) => {
                if let Some(source) = &s.source {
                  self
                    .module_global_uniq_name
                    .add_namespace(source, |s| bundle_variable.register_used_name_by_module_id(source, s, root));
                }
              }
              ExportSpecifierInfo::Named(var) => {
                if bundle_variable.name(var.local()) == "default" {
                  self
                    .module_global_uniq_name
                    .add_default(&module_analyzer.module_id, |s| {
                      bundle_variable.register_used_name_by_module_id(&module_analyzer.module_id, s, root)
                    });
                }
              }
            }
          }
        }
      }
    }
  }
}

#[cfg(test)]
mod tests {
  use std::{
    collections::{HashMap, HashSet},
    sync::Arc,
  };

  use farmfe_core::{
    context::CompilationContext,
    module::{
      module_graph::ModuleGraph, Module, ModuleId, ModuleMetaData, ModuleSystem, ModuleType,
      ScriptModuleMetaData,
    },
    swc_common::{Globals, Mark, SourceMap, DUMMY_SP},
    swc_ecma_ast::{Ident, Module as EcmaAstModule},
  };
  use farmfe_toolkit::script::swc_try_with::try_with;

  use crate::resource_pot_to_bundle::{
    modules_analyzer::module_analyzer::{
      ExportInfo, ExportSpecifierInfo, ModuleAnalyzer, Statement, Variable,
    },
    uniq_name::BundleVariable,
  };

  use super::ModuleAnalyzerManager;

  #[test]
  fn test() {
    let mut map = HashMap::new();

    let module_index_id: ModuleId = "index".into();
    let module_a_id: ModuleId = "moduleA".into();
    let module_b_id: ModuleId = "moduleB".into();
    let module_c_id: ModuleId = "moduleC".into();
    let module_d_id: ModuleId = "moduleD".into();

    let context = Arc::new(CompilationContext::default());

    let resource_pot_id = "index";

    let globals = Globals::default();
    let cm = Arc::new(SourceMap::default());
    let create_script_module = |module_id: &ModuleId| -> Module {
      let mut module = Module::new(module_id.clone());
      try_with(cm.clone(), &globals, || {
        module.module_type = ModuleType::Js;
        module.meta = Box::new(ModuleMetaData::Script(ScriptModuleMetaData {
          ast: EcmaAstModule {
            span: DUMMY_SP,
            body: vec![],
            shebang: None,
          },
          top_level_mark: Default::default(),
          unresolved_mark: Mark::default().as_u32(),
          module_system: ModuleSystem::EsModule,
          hmr_self_accepted: false,
          hmr_accepted_deps: HashSet::default(),
          comments: Default::default(),
          custom: Default::default(),
        }));
      })
      .unwrap();

      module
    };

    let module_index = create_script_module(&module_index_id);
    let module_a = create_script_module(&module_a_id);
    let module_b = create_script_module(&module_b_id);
    let module_c = create_script_module(&module_c_id);
    let module_d = create_script_module(&module_d_id);

    let create_module_analyzer = |module: &Module| {
      ModuleAnalyzer::new(
        &module,
        &context,
        resource_pot_id.to_string(),
        false,
        false,
        false,
      )
      .unwrap()
    };

    // ModuleAnalyzer::new()
    let mut module_analyzer_index = create_module_analyzer(&module_index);
    let mut module_analyzer_a = create_module_analyzer(&module_a);
    let mut module_analyzer_b = create_module_analyzer(&module_b);
    let mut module_analyzer_c = create_module_analyzer(&module_c);
    let mut module_analyzer_d = create_module_analyzer(&module_d);
    // index.js   export { foo as bar } from './moduleA.js';
    // moduleA.js export { foo } from './moduleB.js';
    // moduleB.js export { a1 as foo } from './moduleC.js';
    // moduleC.js export { a2 as a1 } from './moduleD.js';
    // moduleD.js export { a2 };
    let mut bundle_variables = BundleVariable::new();
    let module_graph = ModuleGraph::new();

    // index.js bar -> a2
    // moduleA.js foo -> a2
    // moduleB.js foo -> a2
    // moduleC.js a1 -> a2
    // moduleD.js a2
    let module_index_foo_export_origin =
      bundle_variables.register_var(&module_index_id, &Ident::from("foo"), false);
    let module_index_bar_export_as =
      bundle_variables.register_var(&module_index_id, &Ident::from("bar"), false);

    module_analyzer_index.statements.push(Statement {
      id: 0,
      import: None,
      export: Some(ExportInfo {
        source: Some(module_a_id.clone()),
        specifiers: vec![ExportSpecifierInfo::Named(Variable(
          module_index_foo_export_origin,
          Some(module_index_bar_export_as),
        ))],
        stmt_id: 0,
      }),
      defined: vec![],
    });

    let module_a_foo_export_origin =
      bundle_variables.register_var(&module_a_id, &Ident::from("foo"), false);
    module_analyzer_a.statements.push(Statement {
      id: 0,
      import: None,
      export: Some(ExportInfo {
        source: Some(module_b_id.clone()),
        specifiers: vec![ExportSpecifierInfo::Named(Variable(
          module_a_foo_export_origin,
          None,
        ))],
        stmt_id: 0,
      }),
      defined: vec![],
    });

    let module_b_a1_export_origin =
      bundle_variables.register_var(&module_b_id, &Ident::from("a1"), false);
    let module_b_foo_export_as =
      bundle_variables.register_var(&module_b_id, &Ident::from("foo"), false);
    module_analyzer_b.statements.push(Statement {
      id: 0,
      import: None,
      export: Some(ExportInfo {
        source: Some(module_c_id.clone()),
        specifiers: vec![ExportSpecifierInfo::Named(Variable(
          module_b_a1_export_origin,
          Some(module_b_foo_export_as),
        ))],
        stmt_id: 0,
      }),
      defined: vec![],
    });

    let module_c_a2_export_origin =
      bundle_variables.register_var(&module_c_id, &Ident::from("a2"), false);
    let module_c_a1_export_as =
      bundle_variables.register_var(&module_c_id, &Ident::from("a1"), false);
    let module_c_d3_export_namespace =
      bundle_variables.register_var(&module_c_id, &Ident::from("d3"), false);

    module_analyzer_c.statements.push(Statement {
      id: 0,
      import: None,
      export: Some(ExportInfo {
        source: Some(module_d_id.clone()),
        specifiers: vec![
          ExportSpecifierInfo::Named(Variable(
            module_c_a2_export_origin,
            Some(module_c_a1_export_as),
          )),
          ExportSpecifierInfo::Namespace(module_c_d3_export_namespace),
        ],
        stmt_id: 0,
      }),
      defined: vec![],
    });

    let module_d_a2_export_origin =
      bundle_variables.register_var(&module_d_id, &Ident::from("a2"), false);
    module_analyzer_d.statements.push(Statement {
      id: 0,
      import: None,
      export: Some(ExportInfo {
        source: None,
        specifiers: vec![ExportSpecifierInfo::Named(Variable(
          module_d_a2_export_origin,
          None,
        ))],
        stmt_id: 0,
      }),
      defined: vec![],
    });

    map.insert(module_index_id.clone(), module_analyzer_index);
    map.insert(module_a_id.clone(), module_analyzer_a);
    map.insert(module_b_id.clone(), module_analyzer_b);
    map.insert(module_c_id.clone(), module_analyzer_c);
    map.insert(module_d_id.clone(), module_analyzer_d);

    let mut module_analyzer_manager = ModuleAnalyzerManager::new(map, &module_graph);

    {
      let exports = module_analyzer_manager.build_export_names(&module_d_id, &bundle_variables);

      assert_eq!(exports.export.named.len(), 1);

      let v = exports.export.named.iter().collect::<Vec<_>>();

      assert_eq!(
        v,
        vec![(&module_d_a2_export_origin, &module_d_a2_export_origin)]
      );
    }

    {
      // c
      let exports = module_analyzer_manager.build_export_names(&module_c_id, &bundle_variables);

      assert_eq!(exports.export.named.len(), 1);
      assert_eq!(exports.export.namespace, Some(module_c_d3_export_namespace));

      let v = exports.export.named.iter().collect::<Vec<_>>();

      assert_eq!(
        v,
        vec![(&module_c_a1_export_as, &module_d_a2_export_origin)]
      );
    }

    {
      // b
      let exports = module_analyzer_manager.build_export_names(&module_b_id, &bundle_variables);

      assert_eq!(exports.export.named.len(), 1);

      let v = exports.export.named.iter().collect::<Vec<_>>();

      assert_eq!(
        v,
        vec![(&module_b_foo_export_as, &module_d_a2_export_origin)]
      );
    }

    {
      // a
      let exports = module_analyzer_manager.build_export_names(&module_a_id, &bundle_variables);

      assert_eq!(exports.export.named.len(), 1);

      let v = exports.export.named.iter().collect::<Vec<_>>();

      assert_eq!(
        v,
        vec![(&module_a_foo_export_origin, &module_d_a2_export_origin)]
      );
    }

    {
      // index
      let exports = module_analyzer_manager.build_export_names(&module_index_id, &bundle_variables);

      assert_eq!(exports.export.named.len(), 1);

      let v = exports.export.named.iter().collect::<Vec<_>>();

      assert_eq!(
        v,
        vec![(&module_index_bar_export_as, &module_d_a2_export_origin)]
      );
    }
  }
}