Skip to main content

bynk/
logs.rs

1//! `bynk dev` worker logs (#2474): each line a `wrangler dev` prints, with the
2//! stack frames that name generated TypeScript rewritten to the `.bynk` source
3//! line they came from.
4//!
5//! The emitter writes a source-map v3 document beside every generated module
6//! (`<file>.ts.map`, ADR 0103/0569). A runtime error in a handler prints frames
7//! like `at http_GET (/…/.bynk/dev/workers/shop/handlers.ts:57:11)`; that line
8//! is useless to someone who wrote `.bynk`. [`Rewriter`] looks the position up
9//! in the module's map and puts the `.bynk` location in its place, so the
10//! terminal, and the editor's log view, can link straight to the source.
11//!
12//! The rewriting is the driver's rather than the editor's so the CLI benefits
13//! too. It is line-at-a-time and total: a line it does not understand, a module
14//! without a map, or a position the map does not cover is passed through as it
15//! came.
16
17use std::collections::HashMap;
18use std::path::{Path, PathBuf};
19use std::sync::Mutex;
20use std::time::SystemTime;
21
22/// How severe a log line is, as far as `wrangler dev`'s output tells.
23#[derive(Debug, Clone, Copy, PartialEq, Eq, serde::Serialize)]
24#[serde(rename_all = "snake_case")]
25pub enum LogLevel {
26    Info,
27    Warn,
28    Error,
29}
30
31/// Classifies a stream of log lines. Wrangler tags its own messages
32/// (`[ERROR]`, `✘`, `[WARNING]`, `▲`) and prints a thrown error as
33/// `Error: …` followed by `    at …` frames, so a frame inherits the level of
34/// the line it continues.
35#[derive(Debug)]
36pub struct Classifier {
37    last: LogLevel,
38}
39
40impl Default for Classifier {
41    fn default() -> Self {
42        Classifier {
43            last: LogLevel::Info,
44        }
45    }
46}
47
48impl Classifier {
49    pub fn classify(&mut self, line: &str) -> LogLevel {
50        let text = line.trim_start();
51        let level = if text.starts_with("at ") {
52            self.last
53        } else if text.contains("[ERROR]")
54            || text.starts_with('✘')
55            || text.starts_with("Uncaught")
56            || text.contains("Uncaught (in")
57            || is_error_headline(text)
58        {
59            LogLevel::Error
60        } else if text.contains("[WARNING]") || text.starts_with('▲') {
61            LogLevel::Warn
62        } else {
63            LogLevel::Info
64        };
65        self.last = level;
66        level
67    }
68}
69
70/// `TypeError: x is not a function` — an uncaught error's first line: a
71/// capitalised identifier ending `Error`, then a colon.
72fn is_error_headline(text: &str) -> bool {
73    let Some((name, _)) = text.split_once(':') else {
74        return false;
75    };
76    name.ends_with("Error")
77        && name.chars().next().is_some_and(|c| c.is_ascii_uppercase())
78        && name.chars().all(|c| c.is_ascii_alphanumeric() || c == '_')
79}
80
81/// A decoded source-map v3 document. Only what a frame needs: the `sources`
82/// and, per generated line, the segments that carry a source position.
83#[derive(Debug, PartialEq, Eq)]
84pub struct SourceMap {
85    sources: Vec<String>,
86    /// Per generated line (0-based), segments in column order.
87    lines: Vec<Vec<Segment>>,
88}
89
90#[derive(Debug, Clone, Copy, PartialEq, Eq)]
91struct Segment {
92    column: u32,
93    source: u32,
94    line: u32,
95    source_column: u32,
96}
97
98/// A position in an original source: 1-based line and column, as editors and
99/// stack frames count.
100#[derive(Debug, Clone, PartialEq, Eq)]
101pub struct Original {
102    pub source: String,
103    pub line: u32,
104    pub column: u32,
105}
106
107impl SourceMap {
108    /// Parse a v3 document; `None` for anything else.
109    pub fn parse(json: &str) -> Option<SourceMap> {
110        let doc: serde_json::Value = serde_json::from_str(json).ok()?;
111        if doc.get("version")?.as_u64()? != 3 {
112            return None;
113        }
114        let root = doc.get("sourceRoot").and_then(|r| r.as_str()).unwrap_or("");
115        let sources = doc
116            .get("sources")?
117            .as_array()?
118            .iter()
119            .map(|s| {
120                let s = s.as_str().unwrap_or("");
121                if root.is_empty() || Path::new(s).is_absolute() {
122                    s.to_string()
123                } else {
124                    format!("{}/{s}", root.trim_end_matches('/'))
125                }
126            })
127            .collect();
128        let lines = decode_mappings(doc.get("mappings")?.as_str()?)?;
129        Some(SourceMap { sources, lines })
130    }
131
132    /// The original position of a generated one (1-based line and column): the
133    /// last segment on that line at or before the column. A line the map has no
134    /// segment for has no original; the emitter maps every generated line a
135    /// statement spans, so that is generated glue.
136    pub fn original(&self, line: u32, column: u32) -> Option<Original> {
137        let segments = self.lines.get(line.checked_sub(1)? as usize)?;
138        let column0 = column.saturating_sub(1);
139        let seg = segments
140            .iter()
141            .take_while(|s| s.column <= column0)
142            .last()
143            .or_else(|| segments.first())?;
144        Some(Original {
145            source: self.sources.get(seg.source as usize)?.clone(),
146            line: seg.line + 1,
147            column: seg.source_column + 1,
148        })
149    }
150}
151
152fn decode_mappings(mappings: &str) -> Option<Vec<Vec<Segment>>> {
153    let (mut source, mut line, mut source_column) = (0i64, 0i64, 0i64);
154    let mut out = Vec::new();
155    for generated_line in mappings.split(';') {
156        let mut column = 0i64;
157        let mut segments = Vec::new();
158        for raw in generated_line.split(',').filter(|s| !s.is_empty()) {
159            let fields = decode_vlq(raw)?;
160            column += *fields.first()?;
161            // One field is a generated-only position: nothing to map back to.
162            if fields.len() < 4 {
163                continue;
164            }
165            source += fields[1];
166            line += fields[2];
167            source_column += fields[3];
168            segments.push(Segment {
169                column: u32::try_from(column).ok()?,
170                source: u32::try_from(source).ok()?,
171                line: u32::try_from(line).ok()?,
172                source_column: u32::try_from(source_column).ok()?,
173            });
174        }
175        out.push(segments);
176    }
177    Some(out)
178}
179
180fn decode_vlq(segment: &str) -> Option<Vec<i64>> {
181    const BASE64: &[u8] = b"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
182    let mut values = Vec::new();
183    let (mut value, mut shift) = (0i64, 0u32);
184    for byte in segment.bytes() {
185        let digit = BASE64.iter().position(|&b| b == byte)? as i64;
186        if shift > 40 {
187            return None;
188        }
189        value |= (digit & 0x1f) << shift;
190        if digit & 0x20 != 0 {
191            shift += 5;
192        } else {
193            let negative = value & 1 == 1;
194            let magnitude = value >> 1;
195            values.push(if negative { -magnitude } else { magnitude });
196            (value, shift) = (0, 0);
197        }
198    }
199    (shift == 0).then_some(values)
200}
201
202/// One stack frame's location, split out of a line.
203#[derive(Debug, PartialEq, Eq)]
204struct Frame<'a> {
205    /// The line up to the location.
206    head: &'a str,
207    path: &'a str,
208    line: u32,
209    column: u32,
210    /// The line from the end of the location: the closing `)`, if any.
211    tail: &'a str,
212}
213
214/// Split `    at fn (file:///x/y.ts:12:5)` / `    at /x/y.ts:12:5` into its
215/// location. `None` for any line that is not a stack frame.
216fn parse_frame(line: &str) -> Option<Frame<'_>> {
217    let body = line.trim_start();
218    let indent = line.len() - body.len();
219    let rest = body.strip_prefix("at ")?;
220    let (loc_start, loc_end) = if rest.ends_with(')') {
221        let open = rest.rfind(" (")? + 2;
222        (indent + 3 + open, line.len() - 1)
223    } else {
224        let skip = if rest.starts_with("async ") { 6 } else { 0 };
225        (indent + 3 + skip, line.len())
226    };
227    let loc = line.get(loc_start..loc_end)?;
228    let (rest, column) = loc.rsplit_once(':')?;
229    let (path, ln) = rest.rsplit_once(':')?;
230    Some(Frame {
231        head: &line[..loc_start],
232        path,
233        line: ln.parse().ok()?,
234        column: column.parse().ok()?,
235        tail: &line[loc_end..],
236    })
237}
238
239/// `line` without ANSI colour sequences (wrangler colours its output under
240/// `FORCE_COLOR`): an event carries text, and the editor colours it itself.
241pub fn strip_ansi(line: &str) -> String {
242    let mut out = String::with_capacity(line.len());
243    let mut chars = line.chars().peekable();
244    while let Some(c) = chars.next() {
245        if c == '\x1b' && chars.peek() == Some(&'[') {
246            chars.next();
247            for n in chars.by_ref() {
248                if ('@'..='~').contains(&n) {
249                    break;
250                }
251            }
252        } else {
253            out.push(c);
254        }
255    }
256    out
257}
258
259/// A `file://` URL's path with its `%XX` escapes decoded (a space in the
260/// project path arrives as `%20`); other text is unchanged.
261fn percent_decode(text: &str) -> String {
262    let bytes = text.as_bytes();
263    let mut out = Vec::with_capacity(bytes.len());
264    let mut i = 0;
265    while i < bytes.len() {
266        let hex = |b: u8| (b as char).to_digit(16);
267        if bytes[i] == b'%'
268            && i + 2 < bytes.len()
269            && let (Some(h), Some(l)) = (hex(bytes[i + 1]), hex(bytes[i + 2]))
270        {
271            out.push((h * 16 + l) as u8);
272            i += 3;
273        } else {
274            out.push(bytes[i]);
275            i += 1;
276        }
277    }
278    String::from_utf8_lossy(&out).into_owned()
279}
280
281/// `file:///c:/x/y.ts` and `file:///x/y.ts` to a plain path.
282fn strip_file_scheme(path: &str) -> String {
283    let Some(rest) = path.strip_prefix("file://") else {
284        return path.to_string();
285    };
286    let decoded = percent_decode(rest);
287    let rest = decoded.as_str();
288    // `file:///c:/x` carries a drive letter; `file:///x` is rooted.
289    let drive = rest.strip_prefix('/').filter(|r| {
290        let b = r.as_bytes();
291        b.len() > 2 && b[0].is_ascii_alphabetic() && b[1] == b':'
292    });
293    drive.unwrap_or(rest).to_string()
294}
295
296/// A loaded map and the mtime it was read at; `None` for a file that did not parse.
297type CachedMap = (SystemTime, Option<std::sync::Arc<SourceMap>>);
298
299/// Rewrites frames against the source maps under a build dir, loading each map
300/// on first use and again when it changes: a rebuild rewrites them in place.
301pub struct Rewriter {
302    build_dir: PathBuf,
303    cache: Mutex<HashMap<PathBuf, CachedMap>>,
304}
305
306impl Rewriter {
307    pub fn new(build_dir: &Path) -> Rewriter {
308        Rewriter {
309            // Canonical, so a map is only ever read from inside it (see
310            // `module_map`).
311            build_dir: build_dir
312                .canonicalize()
313                .unwrap_or_else(|_| build_dir.to_path_buf()),
314            cache: Mutex::new(HashMap::new()),
315        }
316    }
317
318    /// `line`, with its frame location (if it is a frame into generated code
319    /// that has a map) replaced by the `.bynk` one. `worker` is the worker dir
320    /// the line came from, to resolve a path wrangler printed relative to it.
321    pub fn rewrite(&self, worker: &str, line: &str) -> String {
322        // A colour-wrapped frame (`FORCE_COLOR`) is parsed uncoloured; if it
323        // maps, the rewritten line is the uncoloured one.
324        if line.contains('\x1b') {
325            let plain = strip_ansi(line);
326            let rewritten = self.rewrite(worker, &plain);
327            return if rewritten == plain {
328                line.to_string()
329            } else {
330                rewritten
331            };
332        }
333        let Some(frame) = parse_frame(line) else {
334            return line.to_string();
335        };
336        let Some(original) = self
337            .module_map(worker, frame.path)
338            .and_then(|m| m.original(frame.line, frame.column))
339        else {
340            return line.to_string();
341        };
342        format!(
343            "{}{}:{}:{}{}",
344            frame.head, original.source, original.line, original.column, frame.tail
345        )
346    }
347
348    /// The map for the generated module a frame names, if it has one.
349    fn module_map(&self, worker: &str, path: &str) -> Option<std::sync::Arc<SourceMap>> {
350        let path = strip_file_scheme(path);
351        let map_name = format!("{path}.map");
352        let candidates: Vec<PathBuf> = if Path::new(&path).is_absolute() {
353            vec![PathBuf::from(&map_name)]
354        } else {
355            vec![
356                self.build_dir.join("workers").join(worker).join(&map_name),
357                self.build_dir.join(&map_name),
358            ]
359        };
360        // Worker output is partly the program's own (`console.log` can print
361        // anything shaped like a frame), so only maps under the build dir,
362        // where the emitter writes them, are ever opened.
363        let found = candidates
364            .iter()
365            .filter_map(|c| c.canonicalize().ok())
366            .find(|c| c.starts_with(&self.build_dir) && c.is_file())?;
367        self.load(&found)
368    }
369
370    fn load(&self, file: &Path) -> Option<std::sync::Arc<SourceMap>> {
371        let mtime = std::fs::metadata(file).ok()?.modified().ok()?;
372        let mut cache = self.cache.lock().ok()?;
373        if let Some((seen, map)) = cache.get(file)
374            && *seen == mtime
375        {
376            return map.clone();
377        }
378        let map = std::fs::read_to_string(file)
379            .ok()
380            .and_then(|text| SourceMap::parse(&text))
381            .map(std::sync::Arc::new);
382        cache.insert(file.to_path_buf(), (mtime, map.clone()));
383        map
384    }
385}
386
387#[cfg(test)]
388mod tests {
389    use super::*;
390
391    /// A map for a four-line module whose lines 2 and 3 are `.bynk` lines 10
392    /// and 11 (0-based 9 and 10), with a first column of 4 on line 3.
393    const MAP: &str =
394        r#"{"version":3,"file":"h.ts","sources":["/p/src/a.bynk"],"mappings":";AASA;IACA"}"#;
395
396    #[test]
397    fn decodes_vlq_with_signs_and_continuations() {
398        assert_eq!(decode_vlq("A"), Some(vec![0]));
399        assert_eq!(decode_vlq("C"), Some(vec![1]));
400        assert_eq!(decode_vlq("D"), Some(vec![-1]));
401        assert_eq!(decode_vlq("gB"), Some(vec![16]));
402        assert_eq!(decode_vlq("AAMA"), Some(vec![0, 0, 6, 0]));
403        // A continuation bit with nothing after it is malformed.
404        assert_eq!(decode_vlq("g"), None);
405        assert_eq!(decode_vlq("!"), None);
406    }
407
408    #[test]
409    fn looks_up_a_generated_position() {
410        let map = SourceMap::parse(MAP).unwrap();
411        assert_eq!(
412            map.original(2, 1),
413            Some(Original {
414                source: "/p/src/a.bynk".into(),
415                line: 10,
416                column: 1
417            })
418        );
419        // Line 3's segment starts at column 5 (0-based 4): an earlier
420        // column on the line still takes it, as does a later one.
421        assert_eq!(map.original(3, 40).unwrap().line, 11);
422        assert_eq!(map.original(3, 40).unwrap().column, 1);
423        // No segment on line 1, and no line 9.
424        assert_eq!(map.original(1, 1), None);
425        assert_eq!(map.original(9, 1), None);
426        assert_eq!(map.original(0, 1), None);
427    }
428
429    #[test]
430    fn rejects_other_documents() {
431        assert!(SourceMap::parse("not json").is_none());
432        assert!(SourceMap::parse(r#"{"version":2,"sources":[],"mappings":""}"#).is_none());
433        assert!(SourceMap::parse(r#"{"version":3,"sources":[],"mappings":"!!"}"#).is_none());
434    }
435
436    #[test]
437    fn splits_frames_in_both_node_shapes() {
438        let f = parse_frame("    at http_GET (file:///w/h.ts:57:11)").unwrap();
439        assert_eq!((f.path, f.line, f.column), ("file:///w/h.ts", 57, 11));
440        assert_eq!(f.head, "    at http_GET (");
441        assert_eq!(f.tail, ")");
442        let f = parse_frame("    at async /w/h.ts:3:9").unwrap();
443        assert_eq!((f.path, f.line, f.column), ("/w/h.ts", 3, 9));
444        assert_eq!(f.tail, "");
445        // A Windows drive letter's colon is not a position.
446        let f = parse_frame("  at f (C:\\w\\h.ts:1:2)").unwrap();
447        assert_eq!(f.path, "C:\\w\\h.ts");
448        assert!(parse_frame("GET / 200 OK (5ms)").is_none());
449        assert!(parse_frame("    at native").is_none());
450        assert!(parse_frame("    at f (<anonymous>)").is_none());
451    }
452
453    #[test]
454    fn decodes_percent_escapes_in_a_file_url() {
455        assert_eq!(
456            strip_file_scheme("file:///Users/me/My%20Project/h.ts"),
457            "/Users/me/My Project/h.ts"
458        );
459        assert_eq!(strip_file_scheme("file:///x/100%/h.ts"), "/x/100%/h.ts");
460        assert_eq!(strip_file_scheme("file:///x/%e2%9c%98/h.ts"), "/x/✘/h.ts");
461    }
462
463    #[test]
464    fn strips_colour() {
465        assert_eq!(
466            strip_ansi("\x1b[31m✘ [ERROR]\x1b[0m boom"),
467            "✘ [ERROR] boom"
468        );
469        assert_eq!(strip_ansi("plain"), "plain");
470    }
471
472    #[test]
473    fn rewrites_a_colour_wrapped_frame() {
474        let build = project("colour");
475        let rw = Rewriter::new(&build);
476        assert_eq!(
477            rw.rewrite("shop", "\x1b[90m    at handlers.ts:2:1\x1b[39m"),
478            "    at /p/src/a.bynk:10:1"
479        );
480        // Unmapped, a coloured line keeps its colour.
481        let other = "\x1b[90m    at elsewhere.js:2:1\x1b[39m";
482        assert_eq!(rw.rewrite("shop", other), other);
483        let _ = std::fs::remove_dir_all(&build);
484    }
485
486    #[test]
487    fn rewrites_through_an_encoded_path_with_a_space() {
488        let build = project("space dir");
489        let rw = Rewriter::new(&build);
490        let abs = build.join("workers/shop/handlers.ts");
491        let url = format!("file://{}", abs.display()).replace(' ', "%20");
492        assert_eq!(
493            rw.rewrite("shop", &format!("    at f ({url}:3:1)")),
494            "    at f (/p/src/a.bynk:11:1)"
495        );
496        let _ = std::fs::remove_dir_all(&build);
497    }
498
499    #[test]
500    fn opens_no_map_outside_the_build_dir() {
501        let build = project("confine");
502        let outside =
503            std::env::temp_dir().join(format!("bynk-logs-outside-{}", std::process::id()));
504        std::fs::create_dir_all(&outside).unwrap();
505        std::fs::write(outside.join("x.ts.map"), MAP).unwrap();
506        let rw = Rewriter::new(&build);
507        for path in [
508            outside.join("x.ts").display().to_string(),
509            format!(
510                "{}/../../{}/x.ts",
511                build.join("workers/shop").display(),
512                outside.file_name().unwrap().to_string_lossy()
513            ),
514        ] {
515            let line = format!("    at {path}:2:1");
516            assert_eq!(rw.rewrite("shop", &line), line, "{path}");
517        }
518        let _ = std::fs::remove_dir_all(&build);
519        let _ = std::fs::remove_dir_all(&outside);
520    }
521
522    #[test]
523    fn strips_the_file_scheme() {
524        assert_eq!(strip_file_scheme("file:///w/h.ts"), "/w/h.ts");
525        assert_eq!(strip_file_scheme("file:///c:/w/h.ts"), "c:/w/h.ts");
526        assert_eq!(strip_file_scheme("/w/h.ts"), "/w/h.ts");
527    }
528
529    fn project(name: &str) -> PathBuf {
530        let dir = std::env::temp_dir().join(format!("bynk-logs-{name}-{}", std::process::id()));
531        let _ = std::fs::remove_dir_all(&dir);
532        let worker = dir.join("workers").join("shop");
533        std::fs::create_dir_all(&worker).unwrap();
534        std::fs::write(worker.join("handlers.ts.map"), MAP).unwrap();
535        dir
536    }
537
538    #[test]
539    fn rewrites_an_absolute_and_a_relative_frame() {
540        let build = project("rewrite");
541        let rw = Rewriter::new(&build);
542        let abs = build.join("workers/shop/handlers.ts");
543        let line = format!("    at http_GET (file://{}:2:7)", abs.display());
544        assert_eq!(
545            rw.rewrite("shop", &line),
546            "    at http_GET (/p/src/a.bynk:10:1)"
547        );
548        // Wrangler prints a path relative to the worker dir, too.
549        assert_eq!(
550            rw.rewrite("shop", "    at handlers.ts:3:1"),
551            "    at /p/src/a.bynk:11:1"
552        );
553        let _ = std::fs::remove_dir_all(&build);
554    }
555
556    #[test]
557    fn leaves_everything_else_alone() {
558        let build = project("alone");
559        let rw = Rewriter::new(&build);
560        for line in [
561            "GET / 200 OK (5ms)",
562            "Error: boom",
563            // No map for this module.
564            "    at f (file:///elsewhere/runtime.js:5:5)",
565            // A map, but no segment on that line.
566            "    at handlers.ts:1:1",
567            "    at handlers.ts:400:1",
568            "",
569        ] {
570            assert_eq!(rw.rewrite("shop", line), line);
571        }
572        let _ = std::fs::remove_dir_all(&build);
573    }
574
575    #[test]
576    fn reloads_a_map_that_changed() {
577        let build = project("reload");
578        let rw = Rewriter::new(&build);
579        let map = build.join("workers/shop/handlers.ts.map");
580        assert!(
581            rw.rewrite("shop", "    at handlers.ts:2:1")
582                .contains(":10:1")
583        );
584        // A rebuild rewrites the map (a later mtime, a different line).
585        std::thread::sleep(std::time::Duration::from_millis(20));
586        std::fs::write(&map, MAP.replace(";AASA;", ";AAeA;")).unwrap();
587        let later = SystemTime::now() + std::time::Duration::from_secs(5);
588        std::fs::File::options()
589            .write(true)
590            .open(&map)
591            .unwrap()
592            .set_modified(later)
593            .unwrap();
594        assert!(
595            rw.rewrite("shop", "    at handlers.ts:2:1")
596                .contains(":16:1")
597        );
598        let _ = std::fs::remove_dir_all(&build);
599    }
600
601    #[test]
602    fn classifies_levels_and_lets_frames_inherit() {
603        let mut c = Classifier::default();
604        assert_eq!(c.classify("GET / 200 OK (5ms)"), LogLevel::Info);
605        assert_eq!(
606            c.classify("✘ [ERROR] Uncaught (in response) Error: x"),
607            LogLevel::Error
608        );
609        assert_eq!(c.classify("    at f (a.ts:1:1)"), LogLevel::Error);
610        assert_eq!(c.classify("▲ [WARNING] heads up"), LogLevel::Warn);
611        assert_eq!(c.classify("    at g (a.ts:1:1)"), LogLevel::Warn);
612        assert_eq!(
613            c.classify("TypeError: x is not a function"),
614            LogLevel::Error
615        );
616        assert_eq!(c.classify("    at h (a.ts:1:1)"), LogLevel::Error);
617        assert_eq!(c.classify("hello"), LogLevel::Info);
618        // A frame with nothing before it is information.
619        assert_eq!(
620            Classifier::default().classify("    at h (a.ts:1:1)"),
621            LogLevel::Info
622        );
623    }
624}