Skip to main content

bynk_strip/
lib.rs

1//! Strip-only TypeScript → JavaScript for Bynk's first-class JS artefact (the
2//! in-browser track, slice 1 — ADR 0137).
3//!
4//! `bynk` emits TypeScript. A JS artefact is *emit-then-strip*: the same emitter
5//! output with type annotations erased and nothing else changed. Because the
6//! emitter is **strip-only** (ADR 0136 — every emitted `.ts` is erasable by pure
7//! type-stripping), the transform here is total and lossless for runtime
8//! behaviour: it never has to lower a type-directed construct (parameter
9//! property, `enum`, `namespace`), only delete type syntax.
10//!
11//! The engine is [`oxc`] — a pure-Rust TS parser, type-erasing transform, and
12//! codegen — so neither `bynk --emit js` nor the in-browser compile path has any
13//! Node/`tsc` dependency, and the crate compiles to `wasm32` for the playground.
14//!
15//! The transform is configured for **pure type-stripping**, matching Node's
16//! `stripTypeScriptTypes` (the slice-0 strip oracle): `only_remove_type_imports`
17//! keeps every *value* import even when unused, eliding only `import type` and
18//! `type` specifiers — TypeScript's import-elision-by-usage is deliberately off,
19//! so stripping is a syntactic erase, not a semantics-aware rewrite.
20
21// The README's `rust` examples are compiled (and, unless marked `no_run`, run)
22// as doctests, so they cannot rot (#1645). `cfg(doctest)` keeps this item out of
23// every build and out of the docs.rs front page, which the `//!` docs above own.
24#[cfg(doctest)]
25#[doc = include_str!("../README.md")]
26struct ReadmeDoctests;
27
28use std::fmt;
29use std::path::{Path, PathBuf};
30
31use oxc::allocator::Allocator;
32use oxc::codegen::{Codegen, CodegenOptions};
33use oxc::parser::Parser;
34use oxc::semantic::SemanticBuilder;
35use oxc::span::SourceType;
36use oxc::transformer::{TransformOptions, Transformer, TypeScriptOptions};
37
38/// A failure to strip TypeScript to JavaScript. For input produced by the Bynk
39/// emitter this should never occur — the emitter only emits valid, strip-only
40/// TypeScript (ADR 0136) — so a `StripError` indicates an emitter or toolchain
41/// bug rather than user error.
42#[derive(Debug, Clone)]
43pub struct StripError {
44    /// The file being stripped (for diagnostics).
45    pub filename: String,
46    /// What went wrong (parse or transform diagnostics).
47    pub message: String,
48}
49
50impl fmt::Display for StripError {
51    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
52        write!(
53            f,
54            "failed to strip types from {}: {}",
55            self.filename, self.message
56        )
57    }
58}
59
60impl std::error::Error for StripError {}
61
62/// Strip TypeScript types from `source`, returning equivalent JavaScript.
63///
64/// `filename` selects the source flavour (`.ts`/`.tsx`/`.mts`) and labels
65/// diagnostics; it does not have to exist on disk. Value imports are preserved
66/// verbatim (see the module docs); only type syntax is erased.
67pub fn strip_types(source: &str, filename: &str) -> Result<String, StripError> {
68    strip_types_with_map(source, filename, false).map(|(js, _)| js)
69}
70
71/// [`strip_types`], optionally also returning the JS-to-input source map the
72/// codegen records (generated JS position -> position in `source`).
73fn strip_types_with_map(
74    source: &str,
75    filename: &str,
76    want_map: bool,
77) -> Result<(String, Option<oxc_sourcemap::SourceMap<'static>>), StripError> {
78    let allocator = Allocator::default();
79    let source_type = SourceType::from_path(filename).unwrap_or_else(|_| SourceType::ts());
80
81    let parsed = Parser::new(&allocator, source, source_type).parse();
82    if parsed.panicked || !parsed.diagnostics.is_empty() {
83        return Err(StripError {
84            filename: filename.to_string(),
85            message: format!("parse error: {}", join_diagnostics(&parsed.diagnostics)),
86        });
87    }
88
89    let mut program = parsed.program;
90    // `with_enum_eval(true)`: the transformer *panics* on an `enum` without it.
91    // Strip-only emitter output never contains one (ADR 0136), but evaluating
92    // enums keeps this a total function — graceful transform, never a panic — if
93    // a non-strip-only source is ever handed in.
94    let scoping = SemanticBuilder::new()
95        .with_enum_eval(true)
96        .build(&program)
97        .semantic
98        .into_scoping();
99
100    let options = TransformOptions {
101        typescript: TypeScriptOptions {
102            // Pure type-stripping: keep every value import (even unused),
103            // erase only `import type` / `type` specifiers. Matches Node's
104            // strip-only mode rather than TypeScript's usage-based elision.
105            only_remove_type_imports: true,
106            ..TypeScriptOptions::default()
107        },
108        ..TransformOptions::default()
109    };
110
111    let ret = Transformer::new(&allocator, Path::new(filename), &options)
112        .build_with_scoping(scoping, &mut program);
113    if !ret.diagnostics.is_empty() {
114        return Err(StripError {
115            filename: filename.to_string(),
116            message: format!("transform error: {}", join_diagnostics(&ret.diagnostics)),
117        });
118    }
119
120    if !want_map {
121        return Ok((Codegen::new().build(&program).code, None));
122    }
123    let options = CodegenOptions {
124        source_map_path: Some(PathBuf::from(filename)),
125        ..CodegenOptions::default()
126    };
127    let ret = Codegen::new().with_options(options).build(&program);
128    // `oxc_codegen` 0.146 still links `oxc_sourcemap` 8, while this crate uses 10:
129    // the two `SourceMap` types are distinct, so cross the boundary as a v3 JSON
130    // document. Drop this round trip once `oxc` is bumped to a release on 10.
131    let map = ret.map.and_then(|m| {
132        oxc_sourcemap::SourceMap::from_json_string(&m.to_json_string())
133            .ok()
134            .map(|m| m.into_owned())
135    });
136    Ok((ret.code, map))
137}
138
139/// Compose a Bynk-to-TypeScript source map (the emitter's own, line-anchored
140/// per ADR 0103) with the TypeScript-to-JavaScript map the strip codegen
141/// records, giving a Bynk-to-JavaScript v3 map. No second mapping is
142/// generated: each JS token takes the Bynk position the emitter already
143/// assigned to its TypeScript line. `sourcesContent` is dropped (the consumer
144/// holds the source). `None` when either map does not parse or nothing maps.
145fn compose_maps(bynk_to_ts: &str, ts_to_js: &oxc_sourcemap::SourceMap<'_>) -> Option<String> {
146    let first = oxc_sourcemap::SourceMap::from_json_string(bynk_to_ts).ok()?;
147    // The emitter's map has one segment per TS line; the last wins per line.
148    let mut by_line: std::collections::HashMap<u32, (u32, u32, u32)> = Default::default();
149    for t in first.get_tokens() {
150        by_line.insert(
151            t.get_dst_line(),
152            (
153                t.get_source_id().unwrap_or(0),
154                t.get_src_line(),
155                t.get_src_col(),
156            ),
157        );
158    }
159    let mut builder = oxc_sourcemap::SourceMapBuilder::default();
160    for name in first.get_sources() {
161        builder.add_source_and_content(name.unwrap_or_default(), "");
162    }
163    let mut last: Option<(u32, u32, u32, u32)> = None;
164    let mut any = false;
165    for t in ts_to_js.get_tokens() {
166        let Some(&(src, sl, sc)) = by_line.get(&t.get_src_line()) else {
167            continue;
168        };
169        // Line-level maps: one token per JS line per Bynk position is enough.
170        let key = (t.get_dst_line(), src, sl, sc);
171        if last == Some(key) {
172            continue;
173        }
174        last = Some(key);
175        builder.add_token(t.get_dst_line(), t.get_dst_col(), sl, sc, Some(src), None);
176        any = true;
177    }
178    if !any {
179        return None;
180    }
181    let mut map = builder.into_sourcemap();
182    // Without `sourcesContent`, as promised above.
183    map.set_source_contents(Vec::new());
184    Some(map.to_json_string())
185}
186
187/// [`strip_types`] for one emitted module, also composing the module's Bynk-to-JavaScript
188/// source map: `bynk_map` is the emitter's Bynk-to-TypeScript v3 map for the same module
189/// (`None` skips the map work entirely). Returns the JavaScript and, when `bynk_map` was
190/// given and the two maps compose, the composed v3 map as JSON (#2705).
191///
192/// This is the text-level seam the project-level strip in `bynk-driver` calls per module;
193/// it keeps `oxc`'s source-map types inside this crate.
194pub fn strip_types_mapped(
195    source: &str,
196    filename: &str,
197    bynk_map: Option<&str>,
198) -> Result<(String, Option<String>), StripError> {
199    let (js, ts_to_js) = strip_types_with_map(source, filename, bynk_map.is_some())?;
200    let map = match (ts_to_js, bynk_map) {
201        (Some(ts_to_js), Some(bynk)) => compose_maps(bynk, &ts_to_js),
202        _ => None,
203    };
204    Ok((js, map))
205}
206
207fn join_diagnostics(diags: &[oxc::diagnostics::OxcDiagnostic]) -> String {
208    diags
209        .iter()
210        .map(|d| d.to_string())
211        .collect::<Vec<_>>()
212        .join("; ")
213}
214
215#[cfg(test)]
216mod tests {
217    use super::*;
218
219    /// A v3 map whose one source is `a.bynk`, with the given
220    /// `(generated line, source line)` segments (all at column 0).
221    fn bynk_map(segs: &[(u32, u32)]) -> String {
222        let mut b = oxc_sourcemap::SourceMapBuilder::default();
223        b.add_source_and_content("a.bynk", "");
224        for &(gl, sl) in segs {
225            b.add_token(gl, 0, sl, 0, Some(0), None);
226        }
227        b.into_sourcemap().to_json_string()
228    }
229
230    /// A TS-to-JS map with one token per `(js line, ts line)`.
231    fn ts_to_js(toks: &[(u32, u32)]) -> oxc_sourcemap::SourceMap<'static> {
232        let mut b = oxc_sourcemap::SourceMapBuilder::default();
233        b.add_source_and_content("a.ts", "");
234        for &(jl, tl) in toks {
235            b.add_token(jl, 0, tl, 0, Some(0), None);
236        }
237        b.into_sourcemap().into_owned()
238    }
239
240    fn composed_lines(json: &str) -> Vec<(u32, u32)> {
241        let m = oxc_sourcemap::SourceMap::from_json_string(json).unwrap();
242        m.get_tokens()
243            .map(|t| (t.get_dst_line(), t.get_src_line()))
244            .collect()
245    }
246
247    #[test]
248    fn compose_drops_a_ts_line_with_no_emitter_segment() {
249        // The emitter maps TS line 1 only; the JS token for TS line 0 is dropped.
250        let out = compose_maps(&bynk_map(&[(1, 4)]), &ts_to_js(&[(0, 0), (1, 1)])).unwrap();
251        assert_eq!(composed_lines(&out), vec![(1, 4)]);
252    }
253
254    #[test]
255    fn compose_takes_the_last_segment_on_a_ts_line() {
256        let out = compose_maps(&bynk_map(&[(0, 2), (0, 7)]), &ts_to_js(&[(0, 0)])).unwrap();
257        assert_eq!(composed_lines(&out), vec![(0, 7)]);
258    }
259
260    #[test]
261    fn compose_is_none_when_nothing_maps() {
262        assert!(compose_maps(&bynk_map(&[(5, 1)]), &ts_to_js(&[(0, 0)])).is_none());
263        assert!(compose_maps("not json", &ts_to_js(&[(0, 0)])).is_none());
264    }
265
266    /// Assert the stripped JS contains `needle` and none of the `absent` strings.
267    fn strip(src: &str) -> String {
268        strip_types(src, "test.ts").expect("strip should succeed on valid strip-only TS")
269    }
270
271    #[test]
272    fn erases_annotations_and_keeps_values() {
273        let js = strip("export const add = (a: number, b: number): number => a + b;\n");
274        assert!(js.contains("export const add"));
275        assert!(!js.contains(": number"), "annotations erased:\n{js}");
276    }
277
278    #[test]
279    fn removes_type_aliases_and_interfaces() {
280        let js = strip(
281            "export type Id = string & { readonly __brand: \"x\" };\n\
282             export interface Logger { info(m: string): Promise<void>; }\n\
283             export const v = 1;\n",
284        );
285        assert!(!js.contains("interface"), "interface erased:\n{js}");
286        assert!(!js.contains("type Id"), "type alias erased:\n{js}");
287        assert!(js.contains("export const v = 1"));
288    }
289
290    #[test]
291    fn preserves_value_imports_drops_type_specifiers() {
292        // `Ok`/`Err` are value imports and must survive even though they are
293        // unused here; `type Result`/`import type` must go.
294        let js = strip(
295            "import { Ok, Err, type Result } from \"./runtime.js\";\n\
296             import type { Foo } from \"./foo.js\";\n\
297             export const x = 1;\n",
298        );
299        assert!(js.contains("Ok"), "value import Ok kept:\n{js}");
300        assert!(js.contains("Err"), "value import Err kept:\n{js}");
301        assert!(!js.contains("Result"), "type specifier dropped:\n{js}");
302        assert!(!js.contains("Foo"), "import type dropped:\n{js}");
303        assert!(
304            !js.contains("./foo.js"),
305            "type-only import line dropped:\n{js}"
306        );
307    }
308
309    #[test]
310    fn de_sugared_provider_constructor_strips() {
311        // The shape the slice-0 emitter produces for a `given` provider.
312        let js = strip(
313            "export class P {\n\
314             \x20 private deps: { Log: unknown };\n\
315             \x20 constructor(deps: { Log: unknown }) { this.deps = deps; }\n\
316             }\n",
317        );
318        assert!(js.contains("class P"));
319        assert!(
320            js.contains("constructor(deps)"),
321            "ctor param keeps name:\n{js}"
322        );
323        assert!(
324            js.contains("this.deps = deps"),
325            "assignment preserved:\n{js}"
326        );
327        assert!(!js.contains(": { Log"), "field/param types erased:\n{js}");
328    }
329
330    #[test]
331    fn as_casts_and_unique_symbol_erased() {
332        let js = strip(
333            "export const Tok: unique symbol = Symbol(\"T\");\n\
334             export const id = (v: string) => v as string;\n",
335        );
336        assert!(!js.contains("unique symbol"), "unique symbol erased:\n{js}");
337        assert!(!js.contains(" as string"), "as-cast erased:\n{js}");
338        assert!(js.contains("Symbol(\"T\")"));
339    }
340
341    #[test]
342    fn invalid_source_is_an_error_not_a_panic() {
343        let err = strip_types("const = = =;", "bad.ts");
344        assert!(err.is_err(), "malformed source is an error");
345    }
346}