1use std::collections::{BTreeMap, BTreeSet};
4
5use oxc_allocator::Allocator;
6use oxc_ast::ast::{
7 Argument, ArrowFunctionExpression, AwaitExpression, BinaryExpression, CallExpression, Class,
8 DoWhileStatement, ExportAllDeclaration, ExportFromDeclaration, Expression, ForInStatement,
9 ForOfStatement, ForStatement, Function, IdentifierReference, ImportDeclaration,
10 ImportExpression, NewExpression, RegExpLiteral, StaticMemberExpression, TSAnyKeyword,
11 TSFunctionType, TSMethodSignature, ThrowStatement, TryStatement, WhileStatement,
12 YieldExpression,
13};
14use oxc_ast_visit::{Visit, walk};
15use oxc_parser::Parser;
16use oxc_span::{SourceType, Span};
17use oxc_syntax::{operator::UnaryOperator, scope::ScopeFlags};
18use serde::Serialize;
19
20use crate::risks::{Risk, regex_folds_differently, regex_needs_fancy};
21
22#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize)]
24#[serde(rename_all = "kebab-case")]
25pub enum Platform {
26 Node,
27 Browser,
28 Editor,
29 Ui,
30}
31
32#[derive(Clone, Debug, Serialize)]
33pub struct Import {
34 pub specifier: String,
35 pub type_only: bool,
36 pub dynamic: bool,
37}
38
39#[derive(Debug, Default, Serialize)]
40pub struct FileFacts {
41 pub loc: usize,
42 pub imports: Vec<Import>,
43 pub risks: BTreeMap<Risk, Vec<u32>>,
45 pub platforms: BTreeSet<Platform>,
46 pub loops: usize,
47 pub parse_errors: usize,
48}
49
50const STRING_OFFSET_METHODS: &[&str] = &[
51 "slice",
52 "substring",
53 "substr",
54 "charAt",
55 "charCodeAt",
56 "codePointAt",
57 "indexOf",
58 "lastIndexOf",
59 "padStart",
60 "padEnd",
61];
62const BROWSER_GLOBALS: &[&str] = &[
63 "window",
64 "document",
65 "navigator",
66 "localStorage",
67 "sessionStorage",
68 "location",
69 "HTMLElement",
70];
71const NODE_GLOBALS: &[&str] = &["process", "Buffer", "__dirname", "__filename"];
72const NODE_BUILTINS: &[&str] = &[
73 "assert",
74 "async_hooks",
75 "buffer",
76 "child_process",
77 "cluster",
78 "console",
79 "constants",
80 "crypto",
81 "dgram",
82 "diagnostics_channel",
83 "dns",
84 "domain",
85 "events",
86 "fs",
87 "http",
88 "http2",
89 "https",
90 "inspector",
91 "module",
92 "net",
93 "os",
94 "path",
95 "perf_hooks",
96 "process",
97 "punycode",
98 "querystring",
99 "readline",
100 "repl",
101 "stream",
102 "string_decoder",
103 "sys",
104 "timers",
105 "tls",
106 "trace_events",
107 "tty",
108 "url",
109 "util",
110 "v8",
111 "vm",
112 "wasi",
113 "worker_threads",
114 "zlib",
115];
116const UI_PACKAGES: &[&str] = &[
117 "vue",
118 "react",
119 "react-dom",
120 "preact",
121 "solid-js",
122 "svelte",
123 "nuxt",
124 "#app",
125 "#imports",
126 "vue-router",
127];
128
129pub fn platform_of(specifier: &str) -> Option<Platform> {
133 let root = specifier.split('/').next().unwrap_or(specifier);
134 if specifier.starts_with("node:") || NODE_BUILTINS.contains(&root) {
135 Some(Platform::Node)
136 } else if specifier == "vscode" {
137 Some(Platform::Editor)
138 } else if UI_PACKAGES.contains(&specifier) {
139 Some(Platform::Ui)
140 } else {
141 None
142 }
143}
144
145pub fn scan(path: &str, source: &str) -> FileFacts {
147 let source_type = SourceType::from_path(path).unwrap_or_else(|_| SourceType::ts());
148 let allocator = Allocator::default();
149 let ret = Parser::new(&allocator, source, source_type).parse();
150 let mut collector = Collector {
151 line_starts: std::iter::once(0)
152 .chain(
153 source
154 .match_indices('\n')
155 .map(|(i, _)| u32::try_from(i + 1).unwrap_or(u32::MAX)),
156 )
157 .collect(),
158 facts: FileFacts {
159 loc: crate::lang::syntax::loc(source, crate::lang::Lang::Ts),
160 parse_errors: ret.diagnostics.len(),
161 ..FileFacts::default()
162 },
163 };
164 collector.visit_program(&ret.program);
165 for import in &collector.facts.imports {
166 if let Some(platform) = platform_of(&import.specifier) {
167 collector.facts.platforms.insert(platform);
168 }
169 }
170 collector.facts
171}
172
173struct Collector {
174 line_starts: Vec<u32>,
175 facts: FileFacts,
176}
177
178impl Collector {
179 fn line(&self, span: Span) -> u32 {
180 u32::try_from(self.line_starts.partition_point(|&s| s <= span.start)).unwrap_or(u32::MAX)
181 }
182
183 fn add(&mut self, risk: Risk, span: Span) {
184 let line = self.line(span);
185 self.facts.risks.entry(risk).or_default().push(line);
186 }
187
188 fn import(&mut self, specifier: String, type_only: bool, dynamic: bool) {
189 self.facts.imports.push(Import {
190 specifier,
191 type_only,
192 dynamic,
193 });
194 }
195
196 fn check_regex(&mut self, pattern: &str, flags: &str, span: Span) {
197 if regex_needs_fancy(pattern, flags) || regex_folds_differently(pattern, flags) {
198 self.add(Risk::RegexSyntax, span);
199 }
200 if flags.contains('d') {
201 self.add(Risk::StringOffsets, span);
202 }
203 }
204}
205
206fn is_intl_member(expr: &Expression<'_>) -> bool {
208 matches!(expr, Expression::StaticMemberExpression(m) if identifier(&m.object) == Some("Intl"))
209}
210
211fn identifier<'a>(expr: &Expression<'a>) -> Option<&'a str> {
212 match expr {
213 Expression::Identifier(id) => Some(id.name.as_str()),
214 _ => None,
215 }
216}
217
218fn string_arg(arg: Option<&Argument>) -> Option<String> {
219 match arg {
220 Some(Argument::StringLiteral(s)) => Some(s.value.display().to_string()),
221 _ => None,
222 }
223}
224
225fn is_number_literal(arg: Option<&Argument>) -> bool {
226 match arg {
227 Some(Argument::NumericLiteral(_)) => true,
228 Some(Argument::UnaryExpression(u)) => {
229 u.operator == UnaryOperator::UnaryNegation
230 && matches!(u.argument, Expression::NumericLiteral(_))
231 }
232 _ => false,
233 }
234}
235
236impl<'a> Visit<'a> for Collector {
237 fn visit_import_declaration(&mut self, it: &ImportDeclaration<'a>) {
238 self.import(
239 it.source.value.display().to_string(),
240 it.import_kind.is_type(),
241 false,
242 );
243 walk::walk_import_declaration(self, it);
244 }
245
246 fn visit_export_from_declaration(&mut self, it: &ExportFromDeclaration<'a>) {
247 self.import(
248 it.source.value.display().to_string(),
249 it.export_kind.is_type(),
250 false,
251 );
252 walk::walk_export_from_declaration(self, it);
253 }
254
255 fn visit_export_all_declaration(&mut self, it: &ExportAllDeclaration<'a>) {
256 self.import(
257 it.source.value.display().to_string(),
258 it.export_kind.is_type(),
259 false,
260 );
261 walk::walk_export_all_declaration(self, it);
262 }
263
264 fn visit_import_expression(&mut self, it: &ImportExpression<'a>) {
265 match &it.source {
266 Expression::StringLiteral(s) => self.import(s.value.display().to_string(), false, true),
267 _ => self.add(Risk::DynamicCode, it.span),
268 }
269 walk::walk_import_expression(self, it);
270 }
271
272 fn visit_call_expression(&mut self, it: &CallExpression<'a>) {
273 match &it.callee {
274 Expression::StaticMemberExpression(member) => {
275 let property = member.property.name.as_str();
276 match (identifier(&member.object), property) {
277 (Some("JSON"), _) => self.add(Risk::Json, it.span),
278 (Some("Object"), "keys" | "values" | "entries" | "fromEntries") => {
279 self.add(Risk::OrderedCollections, it.span);
280 }
281 (
282 Some("Object"),
283 "defineProperty" | "getPrototypeOf" | "setPrototypeOf" | "freeze",
284 )
285 | (Some("Reflect"), _) => self.add(Risk::Reflection, it.span),
286 (Some("Promise"), _) => self.add(Risk::Async, it.span),
287 (Some("Math"), "random")
288 | (Some("Date" | "performance"), "now")
289 | (Some("crypto"), "randomUUID" | "getRandomValues") => {
290 self.add(Risk::ClockAndRandom, it.span);
291 }
292 (Some("Math"), "round")
293 | (Some("Number"), "parseInt" | "parseFloat")
294 | (_, "toFixed") => {
295 self.add(Risk::NumberSemantics, it.span);
296 }
297 (Some("Intl"), _)
298 | (
299 _,
300 "localeCompare" | "toLocaleLowerCase" | "toLocaleUpperCase"
301 | "toLocaleString" | "toLocaleDateString" | "toLocaleTimeString",
302 ) => {
303 self.add(Risk::Intl, it.span);
304 }
305 (_, "normalize")
307 if it.arguments.is_empty()
308 || string_arg(it.arguments.first())
309 .is_some_and(|f| f.starts_with("NF")) =>
310 {
311 self.add(Risk::Intl, it.span);
312 }
313 (Some("Date"), "parse") => self.add(Risk::DateParsing, it.span),
314 (_, "matchAll" | "exec") => self.add(Risk::StringOffsets, it.span),
315 (_, method) if STRING_OFFSET_METHODS.contains(&method) => {
316 self.add(Risk::StringOffsets, it.span);
317 }
318 _ => {}
319 }
320 }
321 Expression::Identifier(id) => match id.name.as_str() {
322 "eval" => self.add(Risk::DynamicCode, it.span),
323 "Date" => self.add(Risk::ClockAndRandom, it.span),
324 "parseInt" | "parseFloat" => self.add(Risk::NumberSemantics, it.span),
325 "atob" | "btoa" => self.add(Risk::WebApis, it.span),
326 "require" => match string_arg(it.arguments.first()) {
327 Some(specifier) => self.import(specifier, false, true),
328 None => self.add(Risk::DynamicCode, it.span),
329 },
330 "RegExp" => {
331 self.regexp_constructor(it.arguments.first(), it.arguments.get(1), it.span)
332 }
333 _ => {}
334 },
335 _ => {}
336 }
337 walk::walk_call_expression(self, it);
338 }
339
340 fn visit_new_expression(&mut self, it: &NewExpression<'a>) {
341 match identifier(&it.callee) {
342 Some("RegExp") => {
343 self.regexp_constructor(it.arguments.first(), it.arguments.get(1), it.span);
344 }
345 Some("Map" | "Set") => self.add(Risk::OrderedCollections, it.span),
346 Some("Date") if it.arguments.is_empty() => self.add(Risk::ClockAndRandom, it.span),
347 Some("Date") if it.arguments.len() == 1 && !is_number_literal(it.arguments.first()) => {
349 self.add(Risk::DateParsing, it.span);
350 }
351 Some("URL" | "URLSearchParams" | "TextEncoder" | "TextDecoder") => {
352 self.add(Risk::WebApis, it.span);
353 }
354 Some("Function") => self.add(Risk::DynamicCode, it.span),
355 Some("Proxy" | "WeakRef" | "FinalizationRegistry") => {
356 self.add(Risk::Reflection, it.span);
357 }
358 Some("Promise") => self.add(Risk::Async, it.span),
359 _ if is_intl_member(&it.callee) => self.add(Risk::Intl, it.span),
360 _ => {}
361 }
362 walk::walk_new_expression(self, it);
363 }
364
365 fn visit_static_member_expression(&mut self, it: &StaticMemberExpression<'a>) {
366 if matches!(it.property.name.as_str(), "indices" | "lastIndex") {
367 self.add(Risk::StringOffsets, it.span);
368 }
369 walk::walk_static_member_expression(self, it);
370 }
371
372 fn visit_reg_exp_literal(&mut self, it: &RegExpLiteral<'a>) {
373 let flags = it.regex.flags.to_string();
374 self.check_regex(it.regex.pattern.text.as_str(), &flags, it.span);
375 }
376
377 fn visit_throw_statement(&mut self, it: &ThrowStatement<'a>) {
378 self.add(Risk::Exceptions, it.span);
379 walk::walk_throw_statement(self, it);
380 }
381
382 fn visit_try_statement(&mut self, it: &TryStatement<'a>) {
383 self.add(Risk::Exceptions, it.span);
384 walk::walk_try_statement(self, it);
385 }
386
387 fn visit_await_expression(&mut self, it: &AwaitExpression<'a>) {
388 self.add(Risk::Async, it.span);
389 walk::walk_await_expression(self, it);
390 }
391
392 fn visit_function(&mut self, it: &Function<'a>, flags: ScopeFlags) {
393 if it.generator {
394 self.add(Risk::Generators, it.span);
395 }
396 if it.r#async {
397 self.add(Risk::Async, it.span);
398 }
399 walk::walk_function(self, it, flags);
400 }
401
402 fn visit_arrow_function_expression(&mut self, it: &ArrowFunctionExpression<'a>) {
403 if it.r#async {
404 self.add(Risk::Async, it.span);
405 }
406 walk::walk_arrow_function_expression(self, it);
407 }
408
409 fn visit_yield_expression(&mut self, it: &YieldExpression<'a>) {
410 self.add(Risk::Generators, it.span);
411 walk::walk_yield_expression(self, it);
412 }
413
414 fn visit_class(&mut self, it: &Class<'a>) {
415 if it.heritage.is_some() {
416 self.add(Risk::ClassInheritance, it.span);
417 }
418 walk::walk_class(self, it);
419 }
420
421 fn visit_for_in_statement(&mut self, it: &ForInStatement<'a>) {
422 self.facts.loops += 1;
423 self.add(Risk::OrderedCollections, it.span);
424 walk::walk_for_in_statement(self, it);
425 }
426
427 fn visit_for_of_statement(&mut self, it: &ForOfStatement<'a>) {
428 self.facts.loops += 1;
429 walk::walk_for_of_statement(self, it);
430 }
431
432 fn visit_for_statement(&mut self, it: &ForStatement<'a>) {
433 self.facts.loops += 1;
434 walk::walk_for_statement(self, it);
435 }
436
437 fn visit_while_statement(&mut self, it: &WhileStatement<'a>) {
438 self.facts.loops += 1;
439 walk::walk_while_statement(self, it);
440 }
441
442 fn visit_do_while_statement(&mut self, it: &DoWhileStatement<'a>) {
443 self.facts.loops += 1;
444 walk::walk_do_while_statement(self, it);
445 }
446
447 fn visit_binary_expression(&mut self, it: &BinaryExpression<'a>) {
448 if it.operator.is_bitwise() {
449 self.add(Risk::NumberSemantics, it.span);
450 } else if it.operator.is_in() {
451 self.add(Risk::DynamicTyping, it.span);
452 }
453 walk::walk_binary_expression(self, it);
454 }
455
456 fn visit_ts_any_keyword(&mut self, it: &TSAnyKeyword) {
457 self.add(Risk::DynamicTyping, it.span);
458 }
459
460 fn visit_ts_function_type(&mut self, it: &TSFunctionType<'a>) {
461 self.add(Risk::Callbacks, it.span);
462 walk::walk_ts_function_type(self, it);
463 }
464
465 fn visit_ts_method_signature(&mut self, it: &TSMethodSignature<'a>) {
466 self.add(Risk::Callbacks, it.span);
467 walk::walk_ts_method_signature(self, it);
468 }
469
470 fn visit_identifier_reference(&mut self, it: &IdentifierReference<'a>) {
471 let name = it.name.as_str();
472 if BROWSER_GLOBALS.contains(&name) {
473 self.facts.platforms.insert(Platform::Browser);
474 } else if NODE_GLOBALS.contains(&name) {
475 self.facts.platforms.insert(Platform::Node);
476 } else if name == "Symbol" {
477 self.add(Risk::Reflection, it.span);
478 }
479 }
480}
481
482impl Collector {
483 fn regexp_constructor(
484 &mut self,
485 pattern: Option<&Argument>,
486 flags: Option<&Argument>,
487 span: Span,
488 ) {
489 match string_arg(pattern) {
490 Some(pattern) => {
491 let flags = string_arg(flags).unwrap_or_default();
492 self.check_regex(&pattern, &flags, span);
493 }
494 None => self.add(Risk::DynamicRegex, span),
495 }
496 }
497}
498
499#[cfg(test)]
500mod tests {
501 use super::*;
502
503 #[test]
506 fn comment_lines_are_not_lines_of_code() {
507 let source = "/**\n * Counts words.\n *\n * @param s the text\n */\n\
508 // a note\n// another\n\
509 export function f(s: string) {\n return s.length\n}\n";
510 assert_eq!(scan("src/f.ts", source).loc, 3);
511 assert_eq!(crate::lang::syntax::loc(source, crate::lang::Lang::Ts), 3);
512 }
513
514 #[test]
515 fn collects_imports_platforms_and_risks() {
516 let facts = scan(
517 "a.ts",
518 "import { readFile } from 'node:fs'\n\
519 import type { X } from './types'\n\
520 export * from './util.js'\n\
521 const re = /(?<=a)b/g\n\
522 const dyn = new RegExp(input)\n\
523 export function f(s: string) { return s.slice(1) }\n\
524 const m = new Map()\n",
525 );
526 let specifiers: Vec<_> = facts.imports.iter().map(|i| i.specifier.as_str()).collect();
527 assert_eq!(specifiers, ["node:fs", "./types", "./util.js"]);
528 assert!(facts.imports[1].type_only);
529 assert!(facts.platforms.contains(&Platform::Node));
530 assert_eq!(facts.risks[&Risk::RegexSyntax], [4]);
531 assert_eq!(facts.risks[&Risk::DynamicRegex], [5]);
532 assert_eq!(facts.risks[&Risk::StringOffsets], [6]);
533 assert_eq!(facts.risks[&Risk::OrderedCollections], [7]);
534 assert_eq!(facts.parse_errors, 0);
535 }
536
537 #[test]
538 fn flags_runtime_apis_a_port_must_reproduce() {
539 let facts = scan(
540 "t.ts",
541 "const seg = new Intl.Segmenter('und', { granularity: 'word' })\n\
542 export const same = (a: string, b: string) => a.localeCompare(b) === 0\n\
543 export const nfc = (s: string) => s.normalize('NFC')\n\
544 import * as path from 'node:path'\n\
545 export const p = (s: string) => path.normalize(s)\n\
546 export const ms = (s: string) => Date.parse(s)\n\
547 export const d = (s: string) => new Date(s)\n\
548 export const epoch = () => new Date(0)\n\
549 export const before = () => new Date(-1)\n\
550 export const host = (u: string) => new URL(u).host\n\
551 export const b = (s: string) => atob(s)\n\
552 export const t = (b: Uint8Array) => new TextDecoder().decode(b)\n\
553 export const price = (n: number) => n.toLocaleString('de-DE')\n\
554 export const day = (d: Date) => d.toLocaleDateString('en-US')\n\
555 export const hour = (d: Date) => d.toLocaleTimeString()\n",
556 );
557 assert_eq!(facts.risks[&Risk::Intl], [1, 2, 3, 13, 14, 15]);
558 assert_eq!(facts.risks[&Risk::DateParsing], [6, 7]);
559 assert_eq!(facts.risks[&Risk::WebApis], [10, 11, 12]);
560 }
561
562 #[test]
563 fn flags_rounding_and_ascii_case_folds() {
564 let facts = scan(
565 "ms.ts",
566 "const re = /^(\\d+) *(secs?|ms)$/i\n\
567 export const r = (x: number) => Math.round(x)\n\
568 export const f = (x: number) => x.toFixed(2)\n\
569 export const i = (s: string) => Number.parseInt(s, 10)\n\
570 export const p = (s: string) => Number.parseFloat(s)\n",
571 );
572 assert_eq!(facts.risks[&Risk::RegexSyntax], [1]);
573 assert_eq!(facts.risks[&Risk::NumberSemantics], [2, 3, 4, 5]);
574 }
575
576 #[test]
577 fn a_subpath_names_the_same_builtin() {
578 for spec in [
581 "stream/web",
582 "util/types",
583 "dns/promises",
584 "fs/promises",
585 "node:fs/promises",
586 "tls",
587 "http2",
588 "querystring",
589 "string_decoder",
590 "wasi",
591 ] {
592 assert_eq!(platform_of(spec), Some(Platform::Node), "{spec}");
593 }
594 assert_eq!(platform_of("react/jsx-runtime"), None);
596 assert_eq!(platform_of("@scope/pkg/sub"), None);
597 assert_eq!(platform_of("path-to-regexp"), None);
598 assert_eq!(platform_of("left-pad"), None);
599 assert_eq!(platform_of("vscode"), Some(Platform::Editor));
600 assert_eq!(platform_of("svelte/store"), None);
601 }
602}