File size: 11,166 Bytes
1e92f2d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
use anyhow::Result;
use turbo_rcstr::rcstr;
use turbo_tasks::{ResolvedVc, Vc};
use turbo_tasks_fs::{FileSystem, FileSystemPath};
use turbopack_core::resolve::{
    AliasMap, AliasPattern, ExternalTraced, ExternalType, FindContextFileResult, find_context_file,
    options::{
        ConditionValue, ImportMap, ImportMapping, ResolutionConditions, ResolveInPackage,
        ResolveIntoPackage, ResolveModules, ResolveOptions,
    },
};

use crate::{
    resolve_options_context::ResolveOptionsContext,
    typescript::{apply_tsconfig_resolve_options, tsconfig, tsconfig_resolve_options},
};

const NODE_EXTERNALS: [&str; 64] = [
    "assert",
    "assert/strict",
    "async_hooks",
    "buffer",
    "child_process",
    "cluster",
    "console",
    "constants",
    "crypto",
    "dgram",
    "diagnostics_channel",
    "dns",
    "dns/promises",
    "domain",
    "events",
    "fs",
    "fs/promises",
    "http",
    "http2",
    "https",
    "inspector",
    "module",
    "net",
    "os",
    "path",
    "path/posix",
    "path/win32",
    "perf_hooks",
    "process",
    "punycode",
    "querystring",
    "readline",
    "repl",
    "stream",
    "stream/promises",
    "stream/web",
    "string_decoder",
    "sys",
    "timers",
    "timers/promises",
    "tls",
    "trace_events",
    "tty",
    "url",
    "util",
    "util/types",
    "v8",
    "vm",
    "wasi",
    "worker_threads",
    "zlib",
    "pnpapi",
    "_http_agent",
    "_http_client",
    "_http_common",
    "_http_incoming",
    "_http_outgoing",
    "_http_server",
    "_stream_duplex",
    "_stream_passthrough",
    "_stream_readable",
    "_stream_transform",
    "_stream_wrap",
    "_stream_writable",
];

const EDGE_NODE_EXTERNALS: [&str; 5] = ["buffer", "events", "assert", "util", "async_hooks"];

#[turbo_tasks::function]
async fn base_resolve_options(
    fs: ResolvedVc<Box<dyn FileSystem>>,
    options_context: Vc<ResolveOptionsContext>,
) -> Result<Vc<ResolveOptions>> {
    let opt = options_context.await?;
    let emulating = opt.emulate_environment;
    let root = fs.root().owned().await?;
    let mut direct_mappings = AliasMap::new();
    let node_externals = if let Some(environment) = emulating {
        environment.node_externals().owned().await?
    } else {
        opt.enable_node_externals
    };
    if node_externals || opt.enable_edge_node_externals {
        let untraced_external_cell =
            ImportMapping::External(None, ExternalType::CommonJs, ExternalTraced::Untraced)
                .resolved_cell();

        if node_externals {
            for req in NODE_EXTERNALS {
                direct_mappings.insert(AliasPattern::exact(req), untraced_external_cell);
                direct_mappings.insert(
                    AliasPattern::exact(format!("node:{req}")),
                    untraced_external_cell,
                );
            }
        }
        if opt.enable_edge_node_externals {
            for req in EDGE_NODE_EXTERNALS {
                direct_mappings.insert(
                    AliasPattern::exact(req),
                    ImportMapping::External(
                        Some(format!("node:{req}").into()),
                        ExternalType::CommonJs,
                        ExternalTraced::Untraced,
                    )
                    .resolved_cell(),
                );
                direct_mappings.insert(
                    AliasPattern::exact(format!("node:{req}")),
                    untraced_external_cell,
                );
            }
        }
    }

    let mut import_map = ImportMap::new(direct_mappings);
    if let Some(additional_import_map) = opt.import_map {
        let additional_import_map = additional_import_map.await?;
        import_map.extend_ref(&additional_import_map);
    }
    let import_map = import_map.resolved_cell();

    let conditions = {
        let mut conditions: ResolutionConditions = [
            (rcstr!("import"), ConditionValue::Unknown),
            (rcstr!("require"), ConditionValue::Unknown),
        ]
        .into_iter()
        .collect();
        if opt.browser {
            conditions.insert(rcstr!("browser"), ConditionValue::Set);
        }
        if opt.module {
            conditions.insert(rcstr!("module"), ConditionValue::Set);
        }
        if let Some(environment) = emulating {
            for condition in environment.resolve_conditions().await?.iter() {
                conditions.insert(condition.clone(), ConditionValue::Set);
            }
        }
        for condition in opt.custom_conditions.iter() {
            conditions.insert(condition.clone(), ConditionValue::Set);
        }
        // Infer some well-known conditions
        let dev = conditions.get("development").cloned();
        let prod = conditions.get("production").cloned();
        if prod.is_none() {
            conditions.insert(
                rcstr!("production"),
                if matches!(dev, Some(ConditionValue::Set)) {
                    ConditionValue::Unset
                } else {
                    ConditionValue::Unknown
                },
            );
        }
        if dev.is_none() {
            conditions.insert(
                rcstr!("development"),
                if matches!(prod, Some(ConditionValue::Set)) {
                    ConditionValue::Unset
                } else {
                    ConditionValue::Unknown
                },
            );
        }
        conditions
    };

    let extensions = if let Some(custom_extension) = &opt.custom_extensions {
        custom_extension.clone()
    } else if let Some(environment) = emulating {
        environment.resolve_extensions().owned().await?
    } else {
        let mut ext = Vec::new();
        if opt.enable_typescript && opt.enable_react {
            ext.push(rcstr!(".tsx"));
        }
        if opt.enable_typescript {
            ext.push(rcstr!(".ts"));
        }
        if opt.enable_react {
            ext.push(rcstr!(".jsx"));
        }
        ext.push(rcstr!(".js"));
        if opt.enable_mjs_extension {
            ext.push(rcstr!(".mjs"));
        }
        if opt.enable_node_native_modules {
            ext.push(rcstr!(".node"));
        }
        ext.push(rcstr!(".json"));
        ext
    };
    Ok(ResolveOptions {
        extensions,
        modules: if let Some(environment) = emulating {
            if *environment.resolve_node_modules().await? {
                vec![ResolveModules::Nested(
                    root.clone(),
                    vec![rcstr!("node_modules")],
                )]
            } else {
                Vec::new()
            }
        } else {
            let mut mods = Vec::new();
            if let Some(dir) = &opt.enable_node_modules {
                mods.push(ResolveModules::Nested(
                    dir.clone(),
                    vec![rcstr!("node_modules")],
                ));
            }
            mods
        },
        into_package: {
            let mut resolve_into = vec![ResolveIntoPackage::ExportsField {
                conditions: conditions.clone(),
                unspecified_conditions: ConditionValue::Unset,
            }];
            if opt.browser {
                resolve_into.push(ResolveIntoPackage::MainField {
                    field: rcstr!("browser"),
                });
            }
            if opt.module {
                resolve_into.push(ResolveIntoPackage::MainField {
                    field: rcstr!("module"),
                });
            }
            resolve_into.push(ResolveIntoPackage::MainField {
                field: rcstr!("main"),
            });
            resolve_into
        },
        in_package: {
            let mut resolve_in = vec![ResolveInPackage::ImportsField {
                conditions,
                unspecified_conditions: ConditionValue::Unset,
            }];
            if opt.browser {
                resolve_in.push(ResolveInPackage::AliasField(rcstr!("browser")));
            }
            resolve_in
        },
        default_files: vec![rcstr!("index")],
        import_map: Some(import_map),
        resolved_map: opt.resolved_map,
        after_resolve_plugins: opt.after_resolve_plugins.clone(),
        before_resolve_plugins: opt.before_resolve_plugins.clone(),
        loose_errors: opt.loose_errors,
        ..Default::default()
    }
    .into())
}

#[turbo_tasks::function]
pub async fn resolve_options(
    resolve_path: FileSystemPath,
    options_context: Vc<ResolveOptionsContext>,
) -> Result<Vc<ResolveOptions>> {
    let options_context_value = options_context.await?;
    if !options_context_value.rules.is_empty() {
        for (condition, new_options_context) in options_context_value.rules.iter() {
            if condition.matches(&resolve_path) {
                return Ok(resolve_options(resolve_path, **new_options_context));
            }
        }
    }

    let resolve_options = base_resolve_options(*resolve_path.fs, options_context);

    let resolve_options = if options_context_value.enable_typescript {
        let find_tsconfig = async || {
            // Otherwise, attempt to find a tsconfig up the file tree
            let tsconfig = find_context_file(resolve_path.clone(), tsconfig()).await?;
            anyhow::Ok::<Vc<ResolveOptions>>(match &*tsconfig {
                FindContextFileResult::Found(path, _) => apply_tsconfig_resolve_options(
                    resolve_options,
                    tsconfig_resolve_options(path.clone()),
                ),
                FindContextFileResult::NotFound(_) => resolve_options,
            })
        };

        // Use a specified tsconfig path if provided. In Next.js, this is always provided by the
        // default config, at the very least.
        if let Some(tsconfig_path) = &options_context_value.tsconfig_path {
            let meta = tsconfig_path.metadata().await;
            if meta.is_ok() {
                // If the file exists, use it.
                apply_tsconfig_resolve_options(
                    resolve_options,
                    tsconfig_resolve_options(tsconfig_path.clone()),
                )
            } else {
                // Otherwise, try and find one.
                // TODO: If the user provides a tsconfig.json explicitly, this should fail
                // explicitly. Currently implemented this way for parity with webpack.
                find_tsconfig().await?
            }
        } else {
            find_tsconfig().await?
        }
    } else {
        resolve_options
    };

    // Make sure to always apply `options_context.import_map` last, so it properly
    // overwrites any other mappings.
    let resolve_options = options_context_value
        .import_map
        .map(|import_map| resolve_options.with_extended_import_map(*import_map))
        .unwrap_or(resolve_options);
    // And the same for the fallback_import_map
    let resolve_options = options_context_value
        .fallback_import_map
        .map(|fallback_import_map| {
            resolve_options.with_extended_fallback_import_map(*fallback_import_map)
        })
        .unwrap_or(resolve_options);

    Ok(resolve_options)
}