swc_bundler/bundler/chunk/
mod.rs

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
use std::time::Instant;

use anyhow::{Context, Error};
#[cfg(feature = "rayon")]
use rayon::iter::ParallelIterator;
use swc_common::collections::AHashMap;

use super::{load::TransformedModule, Bundler};
use crate::{
    bundler::chunk::merge::Ctx, load::Load, resolve::Resolve, util::IntoParallelIterator, Bundle,
};

mod cjs;
mod computed_key;
mod merge;
mod plan;

impl<L, R> Bundler<'_, L, R>
where
    L: Load,
    R: Resolve,
{
    /// `entries` - Entry modules (provided by user) by it's basename.
    ///
    /// # How it works
    ///
    /// For first, we load all dependencies and determine all entries.
    pub(super) fn chunk(
        &self,
        entries: AHashMap<String, TransformedModule>,
    ) -> Result<Vec<Bundle>, Error> {
        #[cfg(not(target_arch = "wasm32"))]
        let start = Instant::now();
        let (plan, graph, cycles) = self.determine_entries(entries).context("failed to plan")?;
        #[cfg(not(target_arch = "wasm32"))]
        let dur = Instant::now() - start;
        #[cfg(not(target_arch = "wasm32"))]
        tracing::debug!("Dependency analysis took {:?}", dur);

        if cfg!(debug_assertions) {
            for (i, id1) in plan.all.iter().enumerate() {
                for (j, id2) in plan.all.iter().enumerate() {
                    if i == j {
                        continue;
                    }

                    debug_assert_ne!(
                        id1, id2,
                        "Dependency analysis created duplicate entries: {:?}",
                        id1
                    )
                }
            }
        }

        let ctx = Ctx {
            graph,
            cycles,
            transitive_remap: Default::default(),
            export_stars_in_wrapped: Default::default(),
        };

        #[cfg(not(target_arch = "wasm32"))]
        let start = Instant::now();
        let mut all = (&*plan.all)
            .into_par_iter()
            .map(|id| -> Result<_, Error> {
                self.run(|| {
                    // TODO: is_entry should be false if it's dep of other entry.
                    let is_entry = plan.entries.contains_key(id);
                    let module = self.get_for_merging(&ctx, *id, is_entry)?;

                    Ok((*id, module))
                })
            })
            .collect::<Result<AHashMap<_, _>, _>>()?;

        #[cfg(not(target_arch = "wasm32"))]
        let dur = Instant::now() - start;
        #[cfg(not(target_arch = "wasm32"))]
        tracing::debug!("Module preparation took {:?}", dur);

        let entries = all
            .iter()
            .filter_map(|(id, module)| {
                if plan.entries.contains_key(id) {
                    return Some((*id, module.clone()));
                }
                None
            })
            .collect::<Vec<_>>();

        let merged: Vec<_> = if entries.len() == 1 {
            entries
                .into_iter()
                .map(|(id, mut entry)| {
                    self.merge_into_entry(&ctx, id, &mut entry, &mut all);

                    tracing::debug!("Merged `{}` and it's dep into an entry", id);

                    (id, entry)
                })
                .map(|(id, module)| {
                    let kind = plan
                        .entries
                        .get(&id)
                        .unwrap_or_else(|| {
                            unreachable!("Plan does not contain bundle kind for {:?}", id)
                        })
                        .clone();
                    Bundle {
                        kind,
                        id,
                        module: module.into(),
                    }
                })
                .collect()
        } else {
            entries
                .into_iter()
                .map(|(id, mut entry)| {
                    let mut a = all.clone();
                    self.merge_into_entry(&ctx, id, &mut entry, &mut a);

                    tracing::debug!("Merged `{}` and it's dep into an entry", id);

                    (id, entry)
                })
                .map(|(id, module)| {
                    let kind = plan
                        .entries
                        .get(&id)
                        .unwrap_or_else(|| {
                            unreachable!("Plan does not contain bundle kind for {:?}", id)
                        })
                        .clone();
                    Bundle {
                        kind,
                        id,
                        module: module.into(),
                    }
                })
                .collect()
        };

        Ok(merged)
    }
}

#[cfg(test)]
mod tests {
    use swc_common::FileName;

    use super::*;
    use crate::bundler::tests::suite;

    #[test]
    fn cjs_chunk() {
        suite()
            .file(
                "main.js",
                "
                require('./a');
                require('./b');
                ",
            )
            .file("a.js", "require('./common')")
            .file("b.js", "require('./common')")
            .file("common.js", r#"console.log('foo')"#)
            .run(|t| {
                let module = t
                    .bundler
                    .load_transformed(&FileName::Real("main.js".into()))?
                    .unwrap();
                let mut entries = AHashMap::default();
                entries.insert("main.js".to_string(), module);

                let chunked = t.bundler.chunk(entries)?;
                assert_eq!(chunked.len(), 1);

                Ok(())
            });
    }
}