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
// Copyright 2018-2022 the Deno authors. All rights reserved. MIT license.

use crate::normalize_path;
use std::env::current_dir;
use std::error::Error;
use std::fmt;
use std::path::PathBuf;
use url::ParseError;
use url::Url;

pub const DUMMY_SPECIFIER: &str = "<unknown>";

/// Error indicating the reason resolving a module specifier failed.
#[derive(Clone, Debug, Eq, PartialEq)]
pub enum ModuleResolutionError {
  InvalidUrl(ParseError),
  InvalidBaseUrl(ParseError),
  InvalidPath(PathBuf),
  ImportPrefixMissing(String, Option<String>),
}
use ModuleResolutionError::*;

impl Error for ModuleResolutionError {
  fn source(&self) -> Option<&(dyn Error + 'static)> {
    match self {
      InvalidUrl(ref err) | InvalidBaseUrl(ref err) => Some(err),
      _ => None,
    }
  }
}

impl fmt::Display for ModuleResolutionError {
  fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
    match self {
      InvalidUrl(ref err) => write!(f, "invalid URL: {}", err),
      InvalidBaseUrl(ref err) => {
        write!(f, "invalid base URL for relative import: {}", err)
      }
      InvalidPath(ref path) => write!(f, "invalid module path: {:?}", path),
      ImportPrefixMissing(ref specifier, ref maybe_referrer) => write!(
        f,
        "Relative import path \"{}\" not prefixed with / or ./ or ../{}",
        specifier,
        match maybe_referrer {
          Some(referrer) => format!(" from \"{}\"", referrer),
          None => String::new(),
        }
      ),
    }
  }
}

/// Resolved module specifier
pub type ModuleSpecifier = Url;

/// Resolves module using this algorithm:
/// <https://html.spec.whatwg.org/multipage/webappapis.html#resolve-a-module-specifier>
pub fn resolve_import(
  specifier: &str,
  base: &str,
) -> Result<ModuleSpecifier, ModuleResolutionError> {
  let url = match Url::parse(specifier) {
    // 1. Apply the URL parser to specifier.
    //    If the result is not failure, return he result.
    Ok(url) => url,

    // 2. If specifier does not start with the character U+002F SOLIDUS (/),
    //    the two-character sequence U+002E FULL STOP, U+002F SOLIDUS (./),
    //    or the three-character sequence U+002E FULL STOP, U+002E FULL STOP,
    //    U+002F SOLIDUS (../), return failure.
    Err(ParseError::RelativeUrlWithoutBase)
      if !(specifier.starts_with('/')
        || specifier.starts_with("./")
        || specifier.starts_with("../")) =>
    {
      let maybe_referrer = if base.is_empty() {
        None
      } else {
        Some(base.to_string())
      };
      return Err(ImportPrefixMissing(specifier.to_string(), maybe_referrer));
    }

    // 3. Return the result of applying the URL parser to specifier with base
    //    URL as the base URL.
    Err(ParseError::RelativeUrlWithoutBase) => {
      let base = if base == DUMMY_SPECIFIER {
        // Handle <unknown> case, happening under e.g. repl.
        // Use CWD for such case.

        // Forcefully join base to current dir.
        // Otherwise, later joining in Url would be interpreted in
        // the parent directory (appending trailing slash does not work)
        let path = current_dir().unwrap().join(base);
        Url::from_file_path(path).unwrap()
      } else {
        Url::parse(base).map_err(InvalidBaseUrl)?
      };
      base.join(specifier).map_err(InvalidUrl)?
    }

    // If parsing the specifier as a URL failed for a different reason than
    // it being relative, always return the original error. We don't want to
    // return `ImportPrefixMissing` or `InvalidBaseUrl` if the real
    // problem lies somewhere else.
    Err(err) => return Err(InvalidUrl(err)),
  };

  Ok(url)
}

/// Converts a string representing an absolute URL into a ModuleSpecifier.
pub fn resolve_url(
  url_str: &str,
) -> Result<ModuleSpecifier, ModuleResolutionError> {
  Url::parse(url_str).map_err(ModuleResolutionError::InvalidUrl)
}

/// Takes a string representing either an absolute URL or a file path,
/// as it may be passed to deno as a command line argument.
/// The string is interpreted as a URL if it starts with a valid URI scheme,
/// e.g. 'http:' or 'file:' or 'git+ssh:'. If not, it's interpreted as a
/// file path; if it is a relative path it's resolved relative to the current
/// working directory.
pub fn resolve_url_or_path(
  specifier: &str,
) -> Result<ModuleSpecifier, ModuleResolutionError> {
  if specifier_has_uri_scheme(specifier) {
    resolve_url(specifier)
  } else {
    resolve_path(specifier)
  }
}

/// Converts a string representing a relative or absolute path into a
/// ModuleSpecifier. A relative path is considered relative to the current
/// working directory.
pub fn resolve_path(
  path_str: &str,
) -> Result<ModuleSpecifier, ModuleResolutionError> {
  let path = current_dir()
    .map_err(|_| ModuleResolutionError::InvalidPath(path_str.into()))?
    .join(path_str);
  let path = normalize_path(&path);
  Url::from_file_path(path.clone())
    .map_err(|()| ModuleResolutionError::InvalidPath(path))
}

/// Returns true if the input string starts with a sequence of characters
/// that could be a valid URI scheme, like 'https:', 'git+ssh:' or 'data:'.
///
/// According to RFC 3986 (https://tools.ietf.org/html/rfc3986#section-3.1),
/// a valid scheme has the following format:
///   scheme = ALPHA *( ALPHA / DIGIT / "+" / "-" / "." )
///
/// We additionally require the scheme to be at least 2 characters long,
/// because otherwise a windows path like c:/foo would be treated as a URL,
/// while no schemes with a one-letter name actually exist.
fn specifier_has_uri_scheme(specifier: &str) -> bool {
  let mut chars = specifier.chars();
  let mut len = 0usize;
  // THe first character must be a letter.
  match chars.next() {
    Some(c) if c.is_ascii_alphabetic() => len += 1,
    _ => return false,
  }
  // Second and following characters must be either a letter, number,
  // plus sign, minus sign, or dot.
  loop {
    match chars.next() {
      Some(c) if c.is_ascii_alphanumeric() || "+-.".contains(c) => len += 1,
      Some(':') if len >= 2 => return true,
      _ => return false,
    }
  }
}

#[cfg(test)]
mod tests {
  use super::*;
  use crate::serde_json::from_value;
  use crate::serde_json::json;
  use std::path::Path;

  #[test]
  fn test_resolve_import() {
    fn get_path(specifier: &str) -> Url {
      let base_path = current_dir().unwrap().join("<unknown>");
      let base_url = Url::from_file_path(base_path).unwrap();
      base_url.join(specifier).unwrap()
    }
    let awesome = get_path("/awesome.ts");
    let awesome_srv = get_path("/service/awesome.ts");
    let tests = vec![
      ("/awesome.ts", "<unknown>", awesome.as_str()),
      ("/service/awesome.ts", "<unknown>", awesome_srv.as_str()),
      (
        "./005_more_imports.ts",
        "http://deno.land/core/tests/006_url_imports.ts",
        "http://deno.land/core/tests/005_more_imports.ts",
      ),
      (
        "../005_more_imports.ts",
        "http://deno.land/core/tests/006_url_imports.ts",
        "http://deno.land/core/005_more_imports.ts",
      ),
      (
        "http://deno.land/core/tests/005_more_imports.ts",
        "http://deno.land/core/tests/006_url_imports.ts",
        "http://deno.land/core/tests/005_more_imports.ts",
      ),
      (
        "data:text/javascript,export default 'grapes';",
        "http://deno.land/core/tests/006_url_imports.ts",
        "data:text/javascript,export default 'grapes';",
      ),
      (
        "blob:https://whatwg.org/d0360e2f-caee-469f-9a2f-87d5b0456f6f",
        "http://deno.land/core/tests/006_url_imports.ts",
        "blob:https://whatwg.org/d0360e2f-caee-469f-9a2f-87d5b0456f6f",
      ),
      (
        "javascript:export default 'artichokes';",
        "http://deno.land/core/tests/006_url_imports.ts",
        "javascript:export default 'artichokes';",
      ),
      (
        "data:text/plain,export default 'kale';",
        "http://deno.land/core/tests/006_url_imports.ts",
        "data:text/plain,export default 'kale';",
      ),
      (
        "/dev/core/tests/005_more_imports.ts",
        "file:///home/yeti",
        "file:///dev/core/tests/005_more_imports.ts",
      ),
      (
        "//zombo.com/1999.ts",
        "https://cherry.dev/its/a/thing",
        "https://zombo.com/1999.ts",
      ),
      (
        "http://deno.land/this/url/is/valid",
        "base is clearly not a valid url",
        "http://deno.land/this/url/is/valid",
      ),
      (
        "//server/some/dir/file",
        "file:///home/yeti/deno",
        "file://server/some/dir/file",
      ),
      // This test is disabled because the url crate does not follow the spec,
      // dropping the server part from the final result.
      // (
      //   "/another/path/at/the/same/server",
      //   "file://server/some/dir/file",
      //   "file://server/another/path/at/the/same/server",
      // ),
    ];

    for (specifier, base, expected_url) in tests {
      let url = resolve_import(specifier, base).unwrap().to_string();
      assert_eq!(url, expected_url);
    }
  }

  #[test]
  fn test_resolve_import_error() {
    use url::ParseError::*;
    use ModuleResolutionError::*;

    let tests = vec![
      (
        "awesome.ts",
        "<unknown>",
        ImportPrefixMissing(
          "awesome.ts".to_string(),
          Some("<unknown>".to_string()),
        ),
      ),
      (
        "005_more_imports.ts",
        "http://deno.land/core/tests/006_url_imports.ts",
        ImportPrefixMissing(
          "005_more_imports.ts".to_string(),
          Some("http://deno.land/core/tests/006_url_imports.ts".to_string()),
        ),
      ),
      (
        ".tomato",
        "http://deno.land/core/tests/006_url_imports.ts",
        ImportPrefixMissing(
          ".tomato".to_string(),
          Some("http://deno.land/core/tests/006_url_imports.ts".to_string()),
        ),
      ),
      (
        "..zucchini.mjs",
        "http://deno.land/core/tests/006_url_imports.ts",
        ImportPrefixMissing(
          "..zucchini.mjs".to_string(),
          Some("http://deno.land/core/tests/006_url_imports.ts".to_string()),
        ),
      ),
      (
        r".\yam.es",
        "http://deno.land/core/tests/006_url_imports.ts",
        ImportPrefixMissing(
          r".\yam.es".to_string(),
          Some("http://deno.land/core/tests/006_url_imports.ts".to_string()),
        ),
      ),
      (
        r"..\yam.es",
        "http://deno.land/core/tests/006_url_imports.ts",
        ImportPrefixMissing(
          r"..\yam.es".to_string(),
          Some("http://deno.land/core/tests/006_url_imports.ts".to_string()),
        ),
      ),
      (
        "https://eggplant:b/c",
        "http://deno.land/core/tests/006_url_imports.ts",
        InvalidUrl(InvalidPort),
      ),
      (
        "https://eggplant@/c",
        "http://deno.land/core/tests/006_url_imports.ts",
        InvalidUrl(EmptyHost),
      ),
      (
        "./foo.ts",
        "/relative/base/url",
        InvalidBaseUrl(RelativeUrlWithoutBase),
      ),
    ];

    for (specifier, base, expected_err) in tests {
      let err = resolve_import(specifier, base).unwrap_err();
      assert_eq!(err, expected_err);
    }
  }

  #[test]
  fn test_resolve_url_or_path() {
    // Absolute URL.
    let mut tests: Vec<(&str, String)> = vec![
      (
        "http://deno.land/core/tests/006_url_imports.ts",
        "http://deno.land/core/tests/006_url_imports.ts".to_string(),
      ),
      (
        "https://deno.land/core/tests/006_url_imports.ts",
        "https://deno.land/core/tests/006_url_imports.ts".to_string(),
      ),
    ];

    // The local path tests assume that the cwd is the deno repo root.
    let cwd = current_dir().unwrap();
    let cwd_str = cwd.to_str().unwrap();

    if cfg!(target_os = "windows") {
      // Absolute local path.
      let expected_url = "file:///C:/deno/tests/006_url_imports.ts";
      tests.extend(vec![
        (
          r"C:/deno/tests/006_url_imports.ts",
          expected_url.to_string(),
        ),
        (
          r"C:\deno\tests\006_url_imports.ts",
          expected_url.to_string(),
        ),
        (
          r"\\?\C:\deno\tests\006_url_imports.ts",
          expected_url.to_string(),
        ),
        // Not supported: `Url::from_file_path()` fails.
        // (r"\\.\C:\deno\tests\006_url_imports.ts", expected_url.to_string()),
        // Not supported: `Url::from_file_path()` performs the wrong conversion.
        // (r"//./C:/deno/tests/006_url_imports.ts", expected_url.to_string()),
      ]);

      // Rooted local path without drive letter.
      let expected_url = format!(
        "file:///{}:/deno/tests/006_url_imports.ts",
        cwd_str.get(..1).unwrap(),
      );
      tests.extend(vec![
        (r"/deno/tests/006_url_imports.ts", expected_url.to_string()),
        (r"\deno\tests\006_url_imports.ts", expected_url.to_string()),
        (
          r"\deno\..\deno\tests\006_url_imports.ts",
          expected_url.to_string(),
        ),
        (r"\deno\.\tests\006_url_imports.ts", expected_url),
      ]);

      // Relative local path.
      let expected_url = format!(
        "file:///{}/tests/006_url_imports.ts",
        cwd_str.replace('\\', "/")
      );
      tests.extend(vec![
        (r"tests/006_url_imports.ts", expected_url.to_string()),
        (r"tests\006_url_imports.ts", expected_url.to_string()),
        (r"./tests/006_url_imports.ts", (*expected_url).to_string()),
        (r".\tests\006_url_imports.ts", (*expected_url).to_string()),
      ]);

      // UNC network path.
      let expected_url = "file://server/share/deno/cool";
      tests.extend(vec![
        (r"\\server\share\deno\cool", expected_url.to_string()),
        (r"\\server/share/deno/cool", expected_url.to_string()),
        // Not supported: `Url::from_file_path()` performs the wrong conversion.
        // (r"//server/share/deno/cool", expected_url.to_string()),
      ]);
    } else {
      // Absolute local path.
      let expected_url = "file:///deno/tests/006_url_imports.ts";
      tests.extend(vec![
        ("/deno/tests/006_url_imports.ts", expected_url.to_string()),
        ("//deno/tests/006_url_imports.ts", expected_url.to_string()),
      ]);

      // Relative local path.
      let expected_url = format!("file://{}/tests/006_url_imports.ts", cwd_str);
      tests.extend(vec![
        ("tests/006_url_imports.ts", expected_url.to_string()),
        ("./tests/006_url_imports.ts", expected_url.to_string()),
        (
          "tests/../tests/006_url_imports.ts",
          expected_url.to_string(),
        ),
        ("tests/./006_url_imports.ts", expected_url),
      ]);
    }

    for (specifier, expected_url) in tests {
      let url = resolve_url_or_path(specifier).unwrap().to_string();
      assert_eq!(url, expected_url);
    }
  }

  #[test]
  fn test_resolve_url_or_path_error() {
    use url::ParseError::*;
    use ModuleResolutionError::*;

    let mut tests = vec![
      ("https://eggplant:b/c", InvalidUrl(InvalidPort)),
      ("https://:8080/a/b/c", InvalidUrl(EmptyHost)),
    ];
    if cfg!(target_os = "windows") {
      let p = r"\\.\c:/stuff/deno/script.ts";
      tests.push((p, InvalidPath(PathBuf::from(p))));
    }

    for (specifier, expected_err) in tests {
      let err = resolve_url_or_path(specifier).unwrap_err();
      assert_eq!(err, expected_err);
    }
  }

  #[test]
  fn test_specifier_has_uri_scheme() {
    let tests = vec![
      ("http://foo.bar/etc", true),
      ("HTTP://foo.bar/etc", true),
      ("http:ftp:", true),
      ("http:", true),
      ("hTtP:", true),
      ("ftp:", true),
      ("mailto:spam@please.me", true),
      ("git+ssh://git@github.com/denoland/deno", true),
      ("blob:https://whatwg.org/mumbojumbo", true),
      ("abc.123+DEF-ghi:", true),
      ("abc.123+def-ghi:@", true),
      ("", false),
      (":not", false),
      ("http", false),
      ("c:dir", false),
      ("X:", false),
      ("./http://not", false),
      ("1abc://kinda/but/no", false),
      ("schluẞ://no/more", false),
    ];

    for (specifier, expected) in tests {
      let result = specifier_has_uri_scheme(specifier);
      assert_eq!(result, expected);
    }
  }

  #[test]
  fn test_normalize_path() {
    assert_eq!(normalize_path(Path::new("a/../b")), PathBuf::from("b"));
    assert_eq!(normalize_path(Path::new("a/./b/")), PathBuf::from("a/b/"));
    assert_eq!(
      normalize_path(Path::new("a/./b/../c")),
      PathBuf::from("a/c")
    );

    if cfg!(windows) {
      assert_eq!(
        normalize_path(Path::new("C:\\a\\.\\b\\..\\c")),
        PathBuf::from("C:\\a\\c")
      );
    }
  }

  #[test]
  fn test_deserialize_module_specifier() {
    let actual: ModuleSpecifier =
      from_value(json!("http://deno.land/x/mod.ts")).unwrap();
    let expected = resolve_url("http://deno.land/x/mod.ts").unwrap();
    assert_eq!(actual, expected);
  }
}