dbg-swc 55.0.0

Debug utilities
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
use std::{
    fmt::{self, Display, Formatter},
    path::{Path, PathBuf},
    sync::Arc,
};

use anyhow::{bail, Context, Result};
use clap::Args;
use swc_common::{FileName, Mark, SourceMap};
use swc_ecma_ast::{EsVersion, Program};
use swc_ecma_codegen::{text_writer::JsWriter, Config as CodegenConfig, Emitter};
use swc_ecma_parser::{
    error::Error as ParseError, parse_file_as_program, EsSyntax, FlowSyntax, Syntax,
};
use swc_ecma_transforms_base::{fixer::fixer, resolver};
use swc_ecma_transforms_typescript::typescript;

/// Verify that Flow syntax is stripped into valid JavaScript.
#[derive(Debug, Args)]
pub struct StripCommand {
    /// The path to verify. It can be a file or directory.
    ///
    /// If this is a directory, this command recursively checks all `.js` and
    /// `.jsx` files.
    pub path: PathBuf,

    #[clap(long)]
    pub jsx: bool,

    #[clap(long)]
    pub all: bool,

    #[clap(long)]
    pub require_directive: bool,

    #[clap(long)]
    pub enums: bool,

    #[clap(long)]
    pub decorators: bool,

    #[clap(long)]
    pub components: bool,

    #[clap(long)]
    pub pattern_matching: bool,
}

impl StripCommand {
    pub fn run(self, cm: Arc<SourceMap>) -> Result<()> {
        let files = collect_flow_files(&self.path)?;
        if files.is_empty() {
            bail!(
                "No `.js` or `.jsx` files found in `{}`",
                self.path.display()
            );
        }

        let flow_syntax = self.flow_syntax();
        let mut failures = Vec::new();

        for path in files.iter() {
            if let Err(err) = verify_file(cm.clone(), path, flow_syntax) {
                failures.push(err);
            }
        }

        let total = files.len();
        let failed = failures.len();
        let passed = total - failed;

        println!("Checked {total} files: {passed} passed, {failed} failed");

        if !failures.is_empty() {
            println!("Failures:");
            for failure in failures {
                println!(
                    "{} [{}] {}",
                    failure.path.display(),
                    failure.stage,
                    failure.message
                );
            }

            bail!("flow strip verification failed");
        }

        Ok(())
    }

    fn flow_syntax(&self) -> FlowSyntax {
        FlowSyntax {
            jsx: self.jsx,
            all: self.all,
            require_directive: self.require_directive,
            enums: self.enums,
            decorators: self.decorators,
            components: self.components,
            pattern_matching: self.pattern_matching,
        }
    }
}

#[derive(Debug)]
struct FlowStripFailure {
    path: PathBuf,
    stage: FailureStage,
    message: String,
}

impl FlowStripFailure {
    fn new(path: &Path, stage: FailureStage, message: impl Into<String>) -> Self {
        Self {
            path: path.to_path_buf(),
            stage,
            message: normalize_message(message.into()),
        }
    }
}

#[derive(Debug, Clone, Copy)]
enum FailureStage {
    Parse,
    Strip,
    Reparse,
    Leak,
}

impl Display for FailureStage {
    fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
        match self {
            Self::Parse => write!(f, "parse"),
            Self::Strip => write!(f, "strip"),
            Self::Reparse => write!(f, "reparse"),
            Self::Leak => write!(f, "leak"),
        }
    }
}

fn verify_file(
    cm: Arc<SourceMap>,
    path: &Path,
    flow_syntax: FlowSyntax,
) -> std::result::Result<(), FlowStripFailure> {
    let fm = cm.load_file(path).map_err(|err| {
        FlowStripFailure::new(
            path,
            FailureStage::Parse,
            format!("failed to load file: {err:#}"),
        )
    })?;

    let mut parse_recovered_errors = Vec::new();
    let parsed = parse_file_as_program(
        &fm,
        Syntax::Flow(flow_syntax),
        EsVersion::latest(),
        None,
        &mut parse_recovered_errors,
    )
    .map_err(|err| {
        FlowStripFailure::new(
            path,
            FailureStage::Parse,
            parse_error_message(&err, &parse_recovered_errors),
        )
    })?;

    if !parse_recovered_errors.is_empty() {
        return Err(FlowStripFailure::new(
            path,
            FailureStage::Parse,
            recovered_parse_message(&parse_recovered_errors),
        ));
    }

    let unresolved_mark = Mark::new();
    let top_level_mark = Mark::new();

    let transformed = parsed
        .apply(resolver(unresolved_mark, top_level_mark, false))
        .apply(typescript::typescript(
            typescript::Config {
                flow_syntax: true,
                ..Default::default()
            },
            unresolved_mark,
            top_level_mark,
        ))
        .apply(fixer(None));

    let output = emit_program(cm.clone(), &transformed)
        .map_err(|err| FlowStripFailure::new(path, FailureStage::Strip, format!("{err:#}")))?;

    if output.contains("__flow_") {
        return Err(FlowStripFailure::new(
            path,
            FailureStage::Leak,
            "flow synthetic symbol leaked into output: `__flow_`",
        ));
    }

    let output_fm = cm.new_source_file(FileName::Anon.into(), output);
    let mut reparse_recovered_errors = Vec::new();
    parse_file_as_program(
        &output_fm,
        Syntax::Es(es_reparse_syntax(flow_syntax.jsx)),
        EsVersion::latest(),
        None,
        &mut reparse_recovered_errors,
    )
    .map_err(|err| {
        FlowStripFailure::new(
            path,
            FailureStage::Reparse,
            parse_error_message(&err, &reparse_recovered_errors),
        )
    })?;

    if !reparse_recovered_errors.is_empty() {
        return Err(FlowStripFailure::new(
            path,
            FailureStage::Reparse,
            recovered_parse_message(&reparse_recovered_errors),
        ));
    }

    Ok(())
}

fn parse_error_message(primary: &ParseError, recovered: &[ParseError]) -> String {
    let mut message = format!("{primary:?}");
    if let Some(first_recovered) = recovered.first() {
        message.push_str("; recovered: ");
        message.push_str(&format!("{first_recovered:?}"));
        if recovered.len() > 1 {
            message.push_str(&format!(" (+{} more)", recovered.len() - 1));
        }
    }
    message
}

fn recovered_parse_message(recovered: &[ParseError]) -> String {
    let first = recovered
        .first()
        .map(|err| format!("{err:?}"))
        .unwrap_or_else(|| "unknown parse error".to_string());

    if recovered.len() > 1 {
        format!("{first} (+{} more)", recovered.len() - 1)
    } else {
        first
    }
}

fn emit_program(cm: Arc<SourceMap>, program: &Program) -> Result<String> {
    let mut buf = Vec::new();
    {
        let wr = JsWriter::new(cm.clone(), "\n", &mut buf, None);
        let mut emitter = Emitter {
            cfg: CodegenConfig::default(),
            comments: None,
            cm,
            wr,
        };
        emitter
            .emit_program(program)
            .context("failed to emit transformed program")?;
    }

    String::from_utf8(buf).context("swc emitted non-utf8 output")
}

fn collect_flow_files(path: &Path) -> Result<Vec<PathBuf>> {
    if !path.exists() {
        bail!("path does not exist: `{}`", path.display());
    }

    let mut files = Vec::new();
    let mut stack = vec![path.to_path_buf()];

    while let Some(current) = stack.pop() {
        if current.is_dir() {
            let entries = current
                .read_dir()
                .with_context(|| format!("failed to read directory `{}`", current.display()))?;

            for entry in entries {
                let entry = entry.with_context(|| {
                    format!("failed to read an entry in `{}`", current.display())
                })?;
                stack.push(entry.path());
            }
            continue;
        }

        if is_flow_input_file(&current) {
            files.push(current);
        }
    }

    files.sort();
    Ok(files)
}

fn is_flow_input_file(path: &Path) -> bool {
    path.extension()
        .and_then(|ext| ext.to_str())
        .is_some_and(|ext| ext == "js" || ext == "jsx")
}

fn es_reparse_syntax(jsx: bool) -> EsSyntax {
    EsSyntax {
        jsx,
        decorators: true,
        decorators_before_export: true,
        export_default_from: true,
        import_attributes: true,
        allow_super_outside_method: true,
        auto_accessors: true,
        explicit_resource_management: true,
        ..Default::default()
    }
}

fn normalize_message(message: String) -> String {
    message.split_whitespace().collect::<Vec<_>>().join(" ")
}

#[cfg(test)]
mod tests {
    use std::{fs, sync::Arc};

    use anyhow::Result;
    use swc_common::{Globals, SourceMap, GLOBALS};
    use tempfile::TempDir;

    use super::{collect_flow_files, StripCommand};

    #[test]
    fn flow_syntax_is_mapped_from_cli_flags() {
        let cmd = StripCommand {
            path: "input.js".into(),
            jsx: true,
            all: true,
            require_directive: true,
            enums: true,
            decorators: true,
            components: true,
            pattern_matching: true,
        };

        let syntax = cmd.flow_syntax();

        assert!(syntax.jsx);
        assert!(syntax.all);
        assert!(syntax.require_directive);
        assert!(syntax.enums);
        assert!(syntax.decorators);
        assert!(syntax.components);
        assert!(syntax.pattern_matching);
    }

    #[test]
    fn collect_flow_files_only_returns_js_and_jsx() -> Result<()> {
        let tmp = TempDir::new()?;
        let root = tmp.path();

        fs::create_dir_all(root.join("nested"))?;
        fs::write(root.join("a.js"), "const a = 1;")?;
        fs::write(root.join("nested").join("b.jsx"), "const b = <div />;")?;
        fs::write(root.join("nested").join("ignored.ts"), "type T = string;")?;

        let files = collect_flow_files(root)?;
        let rel_paths = files
            .iter()
            .map(|file| {
                file.strip_prefix(root)
                    .expect("file should be inside temp dir")
                    .to_string_lossy()
                    .replace('\\', "/")
            })
            .collect::<Vec<_>>();

        assert_eq!(rel_paths, vec!["a.js", "nested/b.jsx"]);

        Ok(())
    }

    #[test]
    fn strip_command_validates_simple_flow_input() -> Result<()> {
        let tmp = TempDir::new()?;
        let input = tmp.path().join("input.js");

        fs::write(
            &input,
            r#"
type ID = string;
const value: ID = ("hello": any);
export const out: ID = value;
"#,
        )?;

        let cmd = StripCommand {
            path: input,
            jsx: false,
            all: false,
            require_directive: false,
            enums: false,
            decorators: false,
            components: false,
            pattern_matching: false,
        };

        let cm = Arc::new(SourceMap::default());
        let globals = Globals::default();

        GLOBALS.set(&globals, || cmd.run(cm))
    }
}