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
mod config;
mod hook;
mod loader;
mod minify;
mod options;
mod output;
mod resolver;

use askama::Template;
use config::TsConfig;
use deno_ast::swc::{
    self,
    bundler::Bundler,
    common::{FileName, FilePathMapping, Globals, SourceMap, GLOBALS},
};
use deno_core::{anyhow::Context, error::AnyError, ModuleSpecifier};
use deno_utils::{ModuleStore, UniversalModuleLoader};
use derive_builder::Builder;
use hook::BundleHook;
use loader::BundleLoader;
use minify::minify;
use output::gen_code;
use resolver::BundleResolver;
use std::{collections::HashMap, rc::Rc, sync::Arc};

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum BundleType {
    MainModule,
    /// Return the emitted contents of the program as a single "flattened" ES
    /// module.
    Module,
    /// Return the emitted contents of the program as a single script that
    /// executes the program using an immediately invoked function execution
    /// (IIFE).
    Classic,
}

#[derive(Builder, Clone)]
#[builder(default, pattern = "owned")]
pub struct BundleOptions {
    pub bundle_type: BundleType,
    pub ts_config: TsConfig,
    pub emit_ignore_directives: bool,
    pub module_store: Option<Arc<dyn ModuleStore>>,
    pub minify: bool,
}

#[derive(Template)]
#[template(path = "layout.j2", escape = "none")]
struct BundledJs {
    body: String,
    bundle_type: BundleType,
}

/// Given a module graph, generate and return a bundle of the graph and
/// optionally its source map. Unlike emitting with `check_and_maybe_emit` and
/// `emit`, which store the emitted modules in the cache, this function simply
/// returns the output.
pub async fn bundle(
    // graph: &ModuleGraph,
    root: ModuleSpecifier,
    options: BundleOptions,
) -> Result<(String, Option<String>), AnyError> {
    let mut loader = UniversalModuleLoader::new(options.module_store, false);
    let graph_owned = deno_graph::create_graph(
        vec![(root, deno_graph::ModuleKind::Esm)],
        false,
        None,
        &mut loader,
        None,
        None,
        None,
        None,
    )
    .await;
    let graph = &graph_owned;

    let globals = Globals::new();
    GLOBALS.set(&globals, || {
        let emit_options: deno_ast::EmitOptions = options.ts_config.into();

        let cm = Rc::new(SourceMap::new(FilePathMapping::empty()));
        let loader = BundleLoader::new(cm.clone(), &emit_options, graph);
        let resolver = BundleResolver(graph);
        let config = swc::bundler::Config {
            module: options.bundle_type.into(),
            disable_fixer: options.minify,
            disable_hygiene: options.minify,
            ..Default::default()
        };
        // This hook will rewrite the `import.meta` when bundling to give a consistent
        // behavior between bundled and unbundled code.
        let hook = Box::new(BundleHook);
        let mut bundler = Bundler::new(&globals, cm.clone(), loader, resolver, config, hook);
        let mut entries = HashMap::new();
        entries.insert(
            "bundle".to_string(),
            FileName::Url(graph.roots[0].0.clone()),
        );
        let mut modules = bundler
            .bundle(entries)
            .context("Unable to output during bundling.")?;

        if options.minify {
            modules = minify(cm.clone(), modules);
        }

        let (mut code, may_map) = gen_code(
            cm,
            &modules[0],
            &emit_options,
            options.emit_ignore_directives,
            options.minify,
        )?;

        let tpl = BundledJs {
            body: code,
            bundle_type: options.bundle_type,
        };
        code = tpl.render()?;
        Ok((code, may_map))
    })
}

#[cfg(test)]
mod tests {
    use std::path::Path;

    use deno_core::resolve_url_or_path;

    use super::*;

    #[tokio::test]
    async fn bundle_code_main_module_should_work() {
        let options = BundleOptions {
            bundle_type: BundleType::MainModule,
            ..BundleOptions::default()
        };
        let f = Path::new(env!("CARGO_MANIFEST_DIR")).join("fixtures/01_main.ts");
        let f = f.to_string_lossy().to_string();
        let m = resolve_url_or_path(&f).unwrap();
        let ret = bundle(m.clone(), options.clone()).await;
        assert!(ret.is_ok());
    }

    #[tokio::test]
    async fn bundle_code_module_should_work() {
        let options = BundleOptions::default();
        let f = Path::new(env!("CARGO_MANIFEST_DIR")).join("fixtures/01_main.ts");
        let f = f.to_string_lossy().to_string();
        let m = resolve_url_or_path(&f).unwrap();
        let (_bundle, _) = bundle(m.clone(), options.clone()).await.unwrap();
        let store = options.module_store.unwrap();
        let ret = store.get(m.as_str()).await;
        assert!(ret.is_ok());
        let imported = resolve_url_or_path(
            "https://cdn.jsdelivr.net/gh/denoland/deno_std@main/http/server.ts",
        )
        .unwrap();
        let _ret = store.get(imported.as_str()).await.unwrap();
    }

    #[tokio::test]
    async fn bundle_code_classic_should_work() {
        let options = BundleOptions {
            bundle_type: BundleType::Classic,
            ..BundleOptions::default()
        };
        let f = Path::new(env!("CARGO_MANIFEST_DIR")).join("fixtures/02_global.ts");
        let f = f.to_string_lossy().to_string();
        let m = resolve_url_or_path(&f).unwrap();
        let ret = bundle(m.clone(), options.clone()).await;
        assert!(ret.is_ok());
    }
}