1#[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#[derive(Debug, Clone)]
43pub struct StripError {
44 pub filename: String,
46 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
62pub fn strip_types(source: &str, filename: &str) -> Result<String, StripError> {
68 strip_types_with_map(source, filename, false).map(|(js, _)| js)
69}
70
71fn 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 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 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 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
139fn 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 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 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 map.set_source_contents(Vec::new());
184 Some(map.to_json_string())
185}
186
187pub 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 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 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 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 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 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 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}