File size: 10,512 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
use std::{cell::RefCell, fs, path::PathBuf, sync::Arc};

use napi::bindgen_prelude::*;
use swc_core::{
    base::{
        config::{IsModule, ParseOptions},
        try_with_handler,
    },
    common::{
        FileName, FilePathMapping, GLOBALS, Mark, SourceMap, SyntaxContext, errors::ColorConfig,
    },
    ecma::{
        ast::{Decl, EsVersion, Id},
        atoms::Atom,
        parser::{EsSyntax, Syntax, TsSyntax},
        utils::{ExprCtx, find_pat_ids},
        visit::{Visit, VisitMutWith, VisitWith},
    },
    node::MapErr,
};

use crate::next_api::utils::{NapiIssueSourceRange, NapiSourcePos};

struct Finder {
    pub named_exports: Vec<Atom>,
}

impl Visit for Finder {
    fn visit_export_decl(&mut self, node: &swc_core::ecma::ast::ExportDecl) {
        match &node.decl {
            Decl::Class(class_decl) => {
                self.named_exports.push(class_decl.ident.sym.clone());
            }
            Decl::Fn(fn_decl) => {
                self.named_exports.push(fn_decl.ident.sym.clone());
            }
            Decl::Var(var_decl) => {
                let ids: Vec<Id> = find_pat_ids(&var_decl.decls);
                for id in ids {
                    self.named_exports.push(id.0);
                }
            }
            _ => {}
        }
    }

    fn visit_export_named_specifier(&mut self, node: &swc_core::ecma::ast::ExportNamedSpecifier) {
        let named_export = if let Some(exported) = &node.exported {
            exported.atom().clone()
        } else {
            node.orig.atom().clone()
        };
        self.named_exports.push(named_export);
    }

    fn visit_export_namespace_specifier(
        &mut self,
        node: &swc_core::ecma::ast::ExportNamespaceSpecifier,
    ) {
        self.named_exports.push(node.name.atom().clone());
    }
}

pub struct FinderTask {
    pub resource_path: Option<String>,
}

impl Task for FinderTask {
    type Output = Vec<Atom>;
    type JsValue = Array;

    fn compute(&mut self) -> napi::Result<Self::Output> {
        let resource_path = PathBuf::from(self.resource_path.take().unwrap());
        let src = fs::read_to_string(&resource_path)
            .map_err(|e| napi::Error::from_reason(e.to_string()))?;

        let syntax = match resource_path
            .extension()
            .map(|os_str| os_str.to_string_lossy())
        {
            Some(ext) if matches!(ext.as_ref(), "ts" | "mts" | "cts") => {
                Syntax::Typescript(TsSyntax {
                    tsx: false,
                    decorators: true,
                    dts: false,
                    no_early_errors: true,
                    disallow_ambiguous_jsx_like: false,
                })
            }
            Some(ext) if matches!(ext.as_ref(), "tsx" | "mtsx" | "ctsx") => {
                Syntax::Typescript(TsSyntax {
                    tsx: true,
                    decorators: true,
                    dts: false,
                    no_early_errors: true,
                    disallow_ambiguous_jsx_like: false,
                })
            }
            _ => Syntax::Es(EsSyntax {
                jsx: true,
                fn_bind: true,
                decorators: true,
                decorators_before_export: true,
                export_default_from: true,
                import_attributes: true,
                allow_super_outside_method: true,
                allow_return_outside_function: true,
                auto_accessors: true,
                explicit_resource_management: true,
            }),
        };

        GLOBALS.set(&Default::default(), || {
            let c =
                swc_core::base::Compiler::new(Arc::new(SourceMap::new(FilePathMapping::empty())));

            let options = ParseOptions {
                comments: false,
                syntax,
                is_module: IsModule::Unknown,
                target: EsVersion::default(),
            };
            let fm =
                c.cm.new_source_file(Arc::new(FileName::Real(resource_path)), src);
            let program = try_with_handler(
                c.cm.clone(),
                swc_core::base::HandlerOpts {
                    color: ColorConfig::Never,
                    skip_filename: false,
                },
                |handler| {
                    c.parse_js(
                        fm,
                        handler,
                        options.target,
                        options.syntax,
                        options.is_module,
                        None,
                    )
                },
            )
            .map_err(|e| e.to_pretty_error())
            .convert_err()?;

            let mut visitor = Finder {
                named_exports: Vec::new(),
            };
            // Visit the AST to find named exports
            program.visit_with(&mut visitor);

            Ok(visitor.named_exports)
        })
    }

    fn resolve(&mut self, env: Env, result: Self::Output) -> napi::Result<Self::JsValue> {
        let mut array = env.create_array(result.len() as u32)?;
        for (i, name) in result.iter().enumerate() {
            let js_val = env.create_string(name.as_str())?;
            array.set(i as u32, js_val)?;
        }
        Ok(array)
    }
}

#[napi(ts_return_type = "Promise<string[]>")]
pub fn get_module_named_exports(resource_path: String) -> AsyncTask<FinderTask> {
    AsyncTask::new(FinderTask {
        resource_path: Some(resource_path),
    })
}

#[napi(object)]
pub struct NapiSourceDiagnostic {
    pub severity: &'static str,
    pub message: String,
    pub loc: NapiIssueSourceRange,
}

pub struct AnalyzeTask {
    pub source: Option<String>,
    pub is_production: bool,
}

impl Task for AnalyzeTask {
    type Output = Vec<NapiSourceDiagnostic>;
    type JsValue = Vec<NapiSourceDiagnostic>;

    fn compute(&mut self) -> Result<Self::Output> {
        GLOBALS.set(&Default::default(), || {
            let c =
                swc_core::base::Compiler::new(Arc::new(SourceMap::new(FilePathMapping::empty())));

            let options = ParseOptions {
                comments: false,
                syntax: Syntax::Es(EsSyntax {
                    jsx: true,
                    fn_bind: true,
                    decorators: true,
                    decorators_before_export: true,
                    export_default_from: true,
                    import_attributes: true,
                    allow_super_outside_method: true,
                    allow_return_outside_function: true,
                    auto_accessors: true,
                    explicit_resource_management: true,
                }),
                is_module: IsModule::Unknown,
                target: EsVersion::default(),
            };
            let source = self.source.take().unwrap();
            let fm =
                c.cm.new_source_file(Arc::new(FileName::Anon), source);
            let mut program = try_with_handler(
                c.cm.clone(),
                swc_core::base::HandlerOpts {
                    color: ColorConfig::Never,
                    skip_filename: false,
                },
                |handler| {
                    c.parse_js(
                        fm,
                        handler,
                        options.target,
                        options.syntax,
                        options.is_module,
                        None,
                    )
                },
            )
            .map_err(|e| e.to_pretty_error())
            .convert_err()?;

            let diagnostics = RefCell::new(Vec::new());
            let top_level_mark = Mark::fresh(Mark::root());
            let unresolved_mark = Mark::fresh(Mark::root());
            let mut resolver_visitor = swc_core::ecma::transforms::base::resolver(unresolved_mark, top_level_mark, true);
            let mut analyze_visitor = next_custom_transforms::transforms::warn_for_edge_runtime::warn_for_edge_runtime_with_handlers(
                c.cm.clone(),
                ExprCtx {
                    is_unresolved_ref_safe: true,
                    unresolved_ctxt: SyntaxContext::empty().apply_mark(unresolved_mark),
                    in_strict: false,
                    remaining_depth: 4,
                },
                false,
                self.is_production,
                |span, msg| {
                    let start = c.cm.lookup_char_pos(span.lo);
                    let end = c.cm.lookup_char_pos(span.hi);
                    diagnostics.borrow_mut().push(NapiSourceDiagnostic {
                        severity: "Warning",
                        message: msg,
                        loc: NapiIssueSourceRange {
                            start: NapiSourcePos {
                                line: start.line as u32,
                                column: start.col_display as u32,
                            },
                            end: NapiSourcePos {
                                line: end.line as u32,
                                column: end.col_display as u32,
                            }
                        }
                    });
                },
                |span, msg| {
                    let start = c.cm.lookup_char_pos(span.lo);
                    let end = c.cm.lookup_char_pos(span.hi);
                    diagnostics.borrow_mut().push(NapiSourceDiagnostic {
                        severity: "Error",
                        message: msg,
                        loc: NapiIssueSourceRange {
                            start: NapiSourcePos {
                                line: start.line as u32,
                                column: start.col_display as u32,
                            },
                            end: NapiSourcePos {
                                line: end.line as u32,
                                column: end.col_display as u32,
                            }
                        }
                    });
                });

                program.visit_mut_with(&mut resolver_visitor);
                program.visit_with(&mut analyze_visitor);

            Ok(diagnostics.take())
        })
    }

    fn resolve(&mut self, _env: Env, output: Self::Output) -> Result<Self::JsValue> {
        Ok(output)
    }
}

#[napi(ts_return_type = "Promise<NapiSourceDiagnostic[]>")]
pub fn warn_for_edge_runtime(source: String, is_production: bool) -> AsyncTask<AnalyzeTask> {
    AsyncTask::new(AnalyzeTask {
        source: Some(source),
        is_production,
    })
}