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
|
// Copyright 2018-2023 the Deno authors. All rights reserved. MIT license.
use std::cell::RefCell;
use std::collections::HashMap;
use std::collections::HashSet;
use std::path::Path;
use std::path::PathBuf;
use std::sync::Arc;
use deno_ast::ModuleSpecifier;
use deno_core::anyhow::anyhow;
use deno_core::anyhow::bail;
use deno_core::error::AnyError;
use deno_core::futures;
use deno_core::futures::FutureExt;
use deno_core::serde_json;
use deno_graph::source::LoadFuture;
use deno_graph::source::LoadResponse;
use deno_graph::source::Loader;
use deno_graph::GraphKind;
use deno_graph::ModuleGraph;
use import_map::ImportMap;
use crate::args::JsxImportSourceConfig;
use crate::cache::ParsedSourceCache;
use crate::npm::CliNpmRegistryApi;
use crate::npm::NpmResolution;
use crate::resolver::CliGraphResolver;
use crate::resolver::CliGraphResolverOptions;
use super::build::VendorEnvironment;
// Utilities that help `deno vendor` get tested in memory.
type RemoteFileText = String;
type RemoteFileHeaders = Option<HashMap<String, String>>;
type RemoteFileResult = Result<(RemoteFileText, RemoteFileHeaders), String>;
#[derive(Clone, Default)]
pub struct TestLoader {
files: HashMap<ModuleSpecifier, RemoteFileResult>,
redirects: HashMap<ModuleSpecifier, ModuleSpecifier>,
}
impl TestLoader {
pub fn add(
&mut self,
path_or_specifier: impl AsRef<str>,
text: impl AsRef<str>,
) -> &mut Self {
self.add_result(path_or_specifier, Ok((text.as_ref().to_string(), None)))
}
pub fn add_failure(
&mut self,
path_or_specifier: impl AsRef<str>,
message: impl AsRef<str>,
) -> &mut Self {
self.add_result(path_or_specifier, Err(message.as_ref().to_string()))
}
fn add_result(
&mut self,
path_or_specifier: impl AsRef<str>,
result: RemoteFileResult,
) -> &mut Self {
if path_or_specifier
.as_ref()
.to_lowercase()
.starts_with("http")
{
self.files.insert(
ModuleSpecifier::parse(path_or_specifier.as_ref()).unwrap(),
result,
);
} else {
let path = make_path(path_or_specifier.as_ref());
let specifier = ModuleSpecifier::from_file_path(path).unwrap();
self.files.insert(specifier, result);
}
self
}
pub fn add_with_headers(
&mut self,
specifier: impl AsRef<str>,
text: impl AsRef<str>,
headers: &[(&str, &str)],
) -> &mut Self {
let headers = headers
.iter()
.map(|(key, value)| (key.to_string(), value.to_string()))
.collect();
self.files.insert(
ModuleSpecifier::parse(specifier.as_ref()).unwrap(),
Ok((text.as_ref().to_string(), Some(headers))),
);
self
}
pub fn add_redirect(
&mut self,
from: impl AsRef<str>,
to: impl AsRef<str>,
) -> &mut Self {
self.redirects.insert(
ModuleSpecifier::parse(from.as_ref()).unwrap(),
ModuleSpecifier::parse(to.as_ref()).unwrap(),
);
self
}
}
impl Loader for TestLoader {
fn load(
&mut self,
specifier: &ModuleSpecifier,
_is_dynamic: bool,
_cache_setting: deno_graph::source::CacheSetting,
) -> LoadFuture {
let specifier = self.redirects.get(specifier).unwrap_or(specifier);
let result = self.files.get(specifier).map(|result| match result {
Ok(result) => Ok(LoadResponse::Module {
specifier: specifier.clone(),
content: result.0.clone().into(),
maybe_headers: result.1.clone(),
}),
Err(err) => Err(err),
});
let result = match result {
Some(Ok(result)) => Ok(Some(result)),
Some(Err(err)) => Err(anyhow!("{}", err)),
None if specifier.scheme() == "data" => {
deno_graph::source::load_data_url(specifier)
}
None => Ok(None),
};
Box::pin(futures::future::ready(result))
}
}
#[derive(Default)]
struct TestVendorEnvironment {
directories: RefCell<HashSet<PathBuf>>,
files: RefCell<HashMap<PathBuf, String>>,
}
impl VendorEnvironment for TestVendorEnvironment {
fn cwd(&self) -> Result<PathBuf, AnyError> {
Ok(make_path("/"))
}
fn create_dir_all(&self, dir_path: &Path) -> Result<(), AnyError> {
let mut directories = self.directories.borrow_mut();
for path in dir_path.ancestors() {
if !directories.insert(path.to_path_buf()) {
break;
}
}
Ok(())
}
fn write_file(&self, file_path: &Path, text: &str) -> Result<(), AnyError> {
let parent = file_path.parent().unwrap();
if !self.directories.borrow().contains(parent) {
bail!("Directory not found: {}", parent.display());
}
self
.files
.borrow_mut()
.insert(file_path.to_path_buf(), text.to_string());
Ok(())
}
fn path_exists(&self, path: &Path) -> bool {
self.files.borrow().contains_key(&path.to_path_buf())
}
}
pub struct VendorOutput {
pub files: Vec<(String, String)>,
pub import_map: Option<serde_json::Value>,
}
#[derive(Default)]
pub struct VendorTestBuilder {
entry_points: Vec<ModuleSpecifier>,
loader: TestLoader,
original_import_map: Option<ImportMap>,
environment: TestVendorEnvironment,
jsx_import_source_config: Option<JsxImportSourceConfig>,
}
impl VendorTestBuilder {
pub fn with_default_setup() -> Self {
let mut builder = VendorTestBuilder::default();
builder.add_entry_point("/mod.ts");
builder
}
pub fn resolve_to_url(&self, path: &str) -> ModuleSpecifier {
ModuleSpecifier::from_file_path(make_path(path)).unwrap()
}
pub fn new_import_map(&self, base_path: &str) -> ImportMap {
let base = self.resolve_to_url(base_path);
ImportMap::new(base)
}
pub fn set_original_import_map(
&mut self,
import_map: ImportMap,
) -> &mut Self {
self.original_import_map = Some(import_map);
self
}
pub fn add_entry_point(&mut self, entry_point: impl AsRef<str>) -> &mut Self {
let entry_point = make_path(entry_point.as_ref());
self
.entry_points
.push(ModuleSpecifier::from_file_path(entry_point).unwrap());
self
}
pub fn set_jsx_import_source_config(
&mut self,
jsx_import_source_config: JsxImportSourceConfig,
) -> &mut Self {
self.jsx_import_source_config = Some(jsx_import_source_config);
self
}
pub async fn build(&mut self) -> Result<VendorOutput, AnyError> {
let output_dir = make_path("/vendor");
let entry_points = self.entry_points.clone();
let loader = self.loader.clone();
let parsed_source_cache = ParsedSourceCache::new_in_memory();
let analyzer = parsed_source_cache.as_analyzer();
let resolver = Arc::new(build_resolver(
self.jsx_import_source_config.clone(),
self.original_import_map.clone(),
));
super::build::build(super::build::BuildInput {
entry_points,
build_graph: {
let resolver = resolver.clone();
move |entry_points| {
async move {
Ok(
build_test_graph(
entry_points,
loader,
resolver.as_graph_resolver(),
&*analyzer,
)
.await,
)
}
.boxed_local()
}
},
parsed_source_cache: &parsed_source_cache,
output_dir: &output_dir,
maybe_original_import_map: self.original_import_map.as_ref(),
maybe_lockfile: None,
maybe_jsx_import_source: self.jsx_import_source_config.as_ref(),
resolver: resolver.as_graph_resolver(),
environment: &self.environment,
})
.await?;
let mut files = self.environment.files.borrow_mut();
let import_map = files.remove(&output_dir.join("import_map.json"));
let mut files = files
.iter()
.map(|(path, text)| (path_to_string(path), text.to_string()))
.collect::<Vec<_>>();
files.sort_by(|a, b| a.0.cmp(&b.0));
Ok(VendorOutput {
import_map: import_map.map(|text| serde_json::from_str(&text).unwrap()),
files,
})
}
pub fn with_loader(&mut self, action: impl Fn(&mut TestLoader)) -> &mut Self {
action(&mut self.loader);
self
}
}
fn build_resolver(
maybe_jsx_import_source_config: Option<JsxImportSourceConfig>,
original_import_map: Option<ImportMap>,
) -> CliGraphResolver {
let npm_registry_api = Arc::new(CliNpmRegistryApi::new_uninitialized());
let npm_resolution = Arc::new(NpmResolution::from_serialized(
npm_registry_api.clone(),
None,
None,
));
CliGraphResolver::new(
npm_registry_api,
npm_resolution,
Default::default(),
Default::default(),
CliGraphResolverOptions {
maybe_jsx_import_source_config,
maybe_import_map: original_import_map.map(Arc::new),
maybe_vendor_dir: None,
no_npm: false,
},
)
}
async fn build_test_graph(
roots: Vec<ModuleSpecifier>,
mut loader: TestLoader,
resolver: &dyn deno_graph::source::Resolver,
analyzer: &dyn deno_graph::ModuleAnalyzer,
) -> ModuleGraph {
let mut graph = ModuleGraph::new(GraphKind::All);
graph
.build(
roots,
&mut loader,
deno_graph::BuildOptions {
resolver: Some(resolver),
module_analyzer: Some(analyzer),
..Default::default()
},
)
.await;
graph
}
fn make_path(text: &str) -> PathBuf {
// This should work all in memory. We're waiting on
// https://github.com/servo/rust-url/issues/730 to provide
// a cross platform path here
assert!(text.starts_with('/'));
if cfg!(windows) {
PathBuf::from(format!("C:{}", text.replace('/', "\\")))
} else {
PathBuf::from(text)
}
}
fn path_to_string<P>(path: P) -> String
where
P: AsRef<Path>,
{
let path = path.as_ref();
// inverse of the function above
let path = path.to_string_lossy();
if cfg!(windows) {
path.replace("C:\\", "\\").replace('\\', "/")
} else {
path.to_string()
}
}
|