summaryrefslogtreecommitdiff
path: root/cli/tools/registry/graph.rs
blob: 184557e5df779760a58f86ce5f66da7be5dddc79 (plain)
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
// Copyright 2018-2024 the Deno authors. All rights reserved. MIT license.

use std::collections::HashSet;
use std::sync::Arc;

use deno_ast::swc::common::comments::CommentKind;
use deno_ast::ParsedSource;
use deno_ast::SourceRangedForSpanned;
use deno_ast::SourceTextInfo;
use deno_core::error::AnyError;
use deno_core::url::Url;
use deno_graph::ModuleEntryRef;
use deno_graph::ModuleGraph;
use deno_graph::ResolutionResolved;
use deno_graph::WalkOptions;
use deno_semver::jsr::JsrPackageReqReference;
use deno_semver::npm::NpmPackageReqReference;

use crate::cache::ParsedSourceCache;

use super::diagnostics::PublishDiagnostic;
use super::diagnostics::PublishDiagnosticsCollector;

pub struct GraphDiagnosticsCollector {
  parsed_source_cache: Arc<ParsedSourceCache>,
}

impl GraphDiagnosticsCollector {
  pub fn new(parsed_source_cache: Arc<ParsedSourceCache>) -> Self {
    Self {
      parsed_source_cache,
    }
  }

  pub fn collect_diagnostics_for_graph(
    &self,
    graph: &ModuleGraph,
    diagnostics_collector: &PublishDiagnosticsCollector,
  ) -> Result<(), AnyError> {
    let mut visited = HashSet::new();
    let mut skip_specifiers: HashSet<Url> = HashSet::new();

    let mut collect_if_invalid =
      |skip_specifiers: &mut HashSet<Url>,
       source_text: &Arc<str>,
       specifier_text: &str,
       resolution: &ResolutionResolved| {
        if visited.insert(resolution.specifier.clone()) {
          match resolution.specifier.scheme() {
            "file" | "data" | "node" => {}
            "jsr" => {
              skip_specifiers.insert(resolution.specifier.clone());

              // check for a missing version constraint
              if let Ok(jsr_req_ref) =
                JsrPackageReqReference::from_specifier(&resolution.specifier)
              {
                if jsr_req_ref.req().version_req.version_text() == "*" {
                  let maybe_version = graph
                    .packages
                    .mappings()
                    .get(jsr_req_ref.req())
                    .map(|nv| nv.version.clone());
                  diagnostics_collector.push(
                    PublishDiagnostic::MissingConstraint {
                      specifier: resolution.specifier.clone(),
                      specifier_text: specifier_text.to_string(),
                      resolved_version: maybe_version,
                      text_info: SourceTextInfo::new(source_text.clone()),
                      referrer: resolution.range.clone(),
                    },
                  );
                }
              }
            }
            "npm" => {
              skip_specifiers.insert(resolution.specifier.clone());

              // check for a missing version constraint
              if let Ok(jsr_req_ref) =
                NpmPackageReqReference::from_specifier(&resolution.specifier)
              {
                if jsr_req_ref.req().version_req.version_text() == "*" {
                  let maybe_version = graph
                    .get(&resolution.specifier)
                    .and_then(|m| m.npm())
                    .map(|n| n.nv_reference.nv().version.clone());
                  diagnostics_collector.push(
                    PublishDiagnostic::MissingConstraint {
                      specifier: resolution.specifier.clone(),
                      specifier_text: specifier_text.to_string(),
                      resolved_version: maybe_version,
                      text_info: SourceTextInfo::new(source_text.clone()),
                      referrer: resolution.range.clone(),
                    },
                  );
                }
              }
            }
            "http" | "https" => {
              skip_specifiers.insert(resolution.specifier.clone());
              diagnostics_collector.push(
                PublishDiagnostic::InvalidExternalImport {
                  kind: format!("non-JSR '{}'", resolution.specifier.scheme()),
                  text_info: SourceTextInfo::new(source_text.clone()),
                  imported: resolution.specifier.clone(),
                  referrer: resolution.range.clone(),
                },
              );
            }
            _ => {
              skip_specifiers.insert(resolution.specifier.clone());
              diagnostics_collector.push(
                PublishDiagnostic::InvalidExternalImport {
                  kind: format!("'{}'", resolution.specifier.scheme()),
                  text_info: SourceTextInfo::new(source_text.clone()),
                  imported: resolution.specifier.clone(),
                  referrer: resolution.range.clone(),
                },
              );
            }
          }
        }
      };

    let options = WalkOptions {
      check_js: true,
      follow_dynamic: true,
      // search the entire graph and not just the fast check subset
      prefer_fast_check_graph: false,
      kind: deno_graph::GraphKind::All,
    };
    let mut iter = graph.walk(graph.roots.iter(), options);
    while let Some((specifier, entry)) = iter.next() {
      if skip_specifiers.contains(specifier) {
        iter.skip_previous_dependencies();
        continue;
      }

      let ModuleEntryRef::Module(module) = entry else {
        continue;
      };
      let Some(module) = module.js() else {
        continue;
      };

      let parsed_source = self
        .parsed_source_cache
        .get_parsed_source_from_js_module(module)?;

      // surface syntax errors
      for diagnostic in parsed_source.diagnostics() {
        diagnostics_collector
          .push(PublishDiagnostic::SyntaxError(diagnostic.clone()));
      }

      check_for_banned_triple_slash_directives(
        &parsed_source,
        diagnostics_collector,
      );

      for (specifier_text, dep) in &module.dependencies {
        if let Some(resolved) = dep.maybe_code.ok() {
          collect_if_invalid(
            &mut skip_specifiers,
            &module.source,
            specifier_text,
            resolved,
          );
        }
        if let Some(resolved) = dep.maybe_type.ok() {
          collect_if_invalid(
            &mut skip_specifiers,
            &module.source,
            specifier_text,
            resolved,
          );
        }
      }
    }

    Ok(())
  }
}

fn check_for_banned_triple_slash_directives(
  parsed_source: &ParsedSource,
  diagnostics_collector: &PublishDiagnosticsCollector,
) {
  let triple_slash_re = lazy_regex::regex!(
    r#"^/\s+<reference\s+(no-default-lib\s*=\s*"true"|lib\s*=\s*("[^"]+"|'[^']+'))\s*/>\s*$"#
  );

  let Some(comments) = parsed_source.get_leading_comments() else {
    return;
  };
  for comment in comments {
    if comment.kind != CommentKind::Line {
      continue;
    }
    if triple_slash_re.is_match(&comment.text) {
      diagnostics_collector.push(
        PublishDiagnostic::BannedTripleSlashDirectives {
          specifier: parsed_source.specifier().clone(),
          range: comment.range(),
          text_info: parsed_source.text_info_lazy().clone(),
        },
      );
    }
  }
}