dioxus_use_js_macro/
lib.rs

1#![doc = include_str!("../README.md")]
2
3use base64::Engine;
4use core::panic;
5use indexmap::IndexMap;
6use proc_macro::TokenStream;
7use proc_macro2::{Literal, TokenStream as TokenStream2};
8use quote::{format_ident, quote};
9use std::collections::HashMap;
10use std::str::FromStr;
11use std::{fs, path::Path};
12use swc_common::comments::{CommentKind, Comments};
13use swc_common::{SourceMap, comments::SingleThreadedComments};
14use swc_common::{SourceMapper, Spanned};
15use swc_ecma_ast::{
16    ClassDecl, ClassMember, Decl, ExportDecl, ExportSpecifier, FnDecl, NamedExport, Pat, PropName,
17    TsType, TsTypeAnn, VarDeclarator,
18};
19use swc_ecma_parser::EsSyntax;
20use swc_ecma_parser::{Parser, StringInput, Syntax, lexer::Lexer};
21use swc_ecma_visit::{Visit, VisitWith};
22use syn::TypeParam;
23use syn::{
24    Ident, LitStr, Result, Token,
25    parse::{Parse, ParseStream},
26    parse_macro_input,
27};
28
29/// `JsValue<T>`
30const JSVALUE_START: &str = "JsValue";
31const JSVALUE: &str = "dioxus_use_js::JsValue";
32const DEFAULT_GENRIC_INPUT: &str = "impl dioxus_use_js::SerdeSerialize";
33const DEFAULT_GENERIC_OUTPUT: &str = "DeserializeOwned";
34const DEFAULT_OUTPUT_GENERIC_DECLARTION: &str =
35    "DeserializeOwned: dioxus_use_js::SerdeDeDeserializeOwned";
36const SERDE_VALUE: &str = "dioxus_use_js::SerdeJsonValue";
37const JSON: &str = "Json";
38/// `RustCallback<T,TT>`
39const RUST_CALLBACK_JS_START: &str = "RustCallback";
40const UNIT: &str = "()";
41const DROP_TYPE: &str = "Drop";
42const DROP_NAME: &str = "drop";
43
44#[derive(Debug, Clone)]
45enum ImportSpec {
46    /// *
47    All,
48    /// {greeting, other_func}
49    Named(Vec<Ident>),
50    /// greeting
51    Single(Ident),
52}
53
54struct UseJsInput {
55    js_bundle_path: LitStr,
56    ts_source_path: Option<LitStr>,
57    import_spec: ImportSpec,
58}
59
60impl Parse for UseJsInput {
61    fn parse(input: ParseStream) -> Result<Self> {
62        let first_str: LitStr = input.parse()?;
63
64        // Check if => follows (i.e., we have "src.ts" => "bundle.js")
65        let (ts_source_path, js_bundle_path) = if input.peek(Token![,]) {
66            input.parse::<Token![,]>()?;
67            let second_str: LitStr = input.parse()?;
68            (Some(first_str), second_str)
69        } else {
70            (None, first_str)
71        };
72
73        // Check for optional :: following bundle path
74        let import_spec = if input.peek(Token![::]) {
75            input.parse::<Token![::]>()?;
76
77            if input.peek(Token![*]) {
78                input.parse::<Token![*]>()?;
79                ImportSpec::All
80            } else if input.peek(Ident) {
81                let ident: Ident = input.parse()?;
82                ImportSpec::Single(ident)
83            } else if input.peek(syn::token::Brace) {
84                let content;
85                syn::braced!(content in input);
86                let idents: syn::punctuated::Punctuated<Ident, Token![,]> =
87                    content.parse_terminated(Ident::parse, Token![,])?;
88                ImportSpec::Named(idents.into_iter().collect())
89            } else {
90                return Err(input.error("Expected `*`, an identifier, or a brace group after `::`"));
91            }
92        } else {
93            return Err(input
94                .error("Expected `::` followed by an import spec (even for wildcard with `*`)"));
95        };
96
97        Ok(UseJsInput {
98            js_bundle_path,
99            ts_source_path,
100            import_spec,
101        })
102    }
103}
104
105#[derive(Debug, Clone)]
106struct ParamInfo {
107    name: String,
108    js_type: Option<String>,
109    rust_type: RustType,
110}
111
112impl ParamInfo {
113    fn is_drop(&self) -> bool {
114        match self.js_type.as_ref() {
115            Some(js_type) => js_type == DROP_TYPE,
116            None => self.name == DROP_NAME,
117        }
118    }
119}
120
121#[derive(Debug, Clone)]
122struct FunctionInfo {
123    name: String,
124    /// If specified in the `use_js!` declaration. Used to link the generated code to this span
125    ident: Option<Ident>,
126    /// js param types
127    params: Vec<ParamInfo>,
128    // js return type
129    js_return_type: Option<String>,
130    rust_return_type: RustType,
131    is_exported: bool,
132    is_async: bool,
133    /// The stripped lines
134    doc_comment: Vec<String>,
135}
136
137#[derive(Debug, Clone)]
138struct MethodInfo {
139    name: String,
140    /// js param types
141    params: Vec<ParamInfo>,
142    // js return type
143    js_return_type: Option<String>,
144    rust_return_type: RustType,
145    is_async: bool,
146    is_static: bool,
147    /// The stripped lines
148    doc_comment: Vec<String>,
149}
150
151#[derive(Debug, Clone)]
152#[allow(dead_code)]
153struct ClassInfo {
154    name: String,
155    /// If specified in the `use_js!` declaration. Used to link the generated code to this span
156    ident: Option<Ident>,
157    /// Class methods
158    methods: Vec<MethodInfo>,
159    is_exported: bool,
160    /// The stripped lines
161    doc_comment: Vec<String>,
162}
163
164struct JsVisitor {
165    functions: Vec<FunctionInfo>,
166    classes: Vec<ClassInfo>,
167    comments: SingleThreadedComments,
168    source_map: SourceMap,
169}
170
171impl JsVisitor {
172    fn new(comments: SingleThreadedComments, source_map: SourceMap) -> Self {
173        Self {
174            functions: Vec::new(),
175            classes: Vec::new(),
176            comments,
177            source_map,
178        }
179    }
180
181    fn extract_doc_comment(&self, span: &swc_common::Span) -> Vec<String> {
182        // Get leading comments for the span
183        let leading_comment = self.comments.get_leading(span.lo());
184
185        if let Some(comments) = leading_comment {
186            let mut doc_lines = Vec::new();
187
188            for comment in comments.iter() {
189                let comment_text = &comment.text;
190                match comment.kind {
191                    // Handle `///`. `//` is already stripped
192                    CommentKind::Line => {
193                        if let Some(content) = comment_text.strip_prefix("/") {
194                            let cleaned = content.trim_start();
195                            doc_lines.push(cleaned.to_string());
196                        }
197                    }
198                    // Handle `/*` `*/`. `/*` `*/` is already stripped
199                    CommentKind::Block => {
200                        for line in comment_text.lines() {
201                            if let Some(cleaned) = line.trim_start().strip_prefix("*") {
202                                doc_lines.push(cleaned.to_string());
203                            }
204                        }
205                    }
206                };
207            }
208
209            doc_lines
210        } else {
211            Vec::new()
212        }
213    }
214}
215
216#[derive(Debug, Clone)]
217enum RustType {
218    Regular(String),
219    Callback(RustCallback),
220    JsValue(JsValue),
221}
222
223impl ToString for RustType {
224    fn to_string(&self) -> String {
225        match self {
226            RustType::Regular(ty) => ty.clone(),
227            RustType::Callback(callback) => callback.to_string(),
228            RustType::JsValue(js_value) => js_value.to_string(),
229        }
230    }
231}
232
233impl RustType {
234    fn to_tokens(&self) -> TokenStream2 {
235        self.to_string()
236            .parse::<TokenStream2>()
237            .expect("Calculated Rust type should always be valid")
238    }
239}
240
241#[derive(Debug, Clone)]
242struct RustCallback {
243    input: Option<String>,
244    output: Option<String>,
245}
246
247impl ToString for RustCallback {
248    fn to_string(&self) -> String {
249        let input = self.input.as_deref();
250        let output = self.output.as_deref().unwrap_or(UNIT);
251        format!(
252            "dioxus::core::Callback<{}, impl Future<Output = Result<{}, dioxus_use_js::SerdeJsonValue>> + 'static>",
253            input.unwrap_or("()"),
254            output
255        )
256    }
257}
258
259#[derive(Debug, Clone)]
260struct JsValue {
261    is_option: bool,
262    is_input: bool,
263}
264
265impl ToString for JsValue {
266    fn to_string(&self) -> String {
267        if self.is_option {
268            format!(
269                "Option<{}>",
270                if self.is_input {
271                    format!("&{}", JSVALUE)
272                } else {
273                    JSVALUE.to_owned()
274                }
275            )
276        } else {
277            if self.is_input {
278                format!("&{}", JSVALUE)
279            } else {
280                JSVALUE.to_owned()
281            }
282        }
283    }
284}
285
286fn strip_parenthesis(mut ts_type: &str) -> &str {
287    while ts_type.starts_with("(") && ts_type.ends_with(")") {
288        ts_type = &ts_type[1..ts_type.len() - 1].trim();
289    }
290    return ts_type;
291}
292
293/// Splits into correct comma delimited arguments
294fn split_into_args(ts_type: &str) -> Vec<&str> {
295    let mut depth_angle: u16 = 0;
296    let mut depth_square: u16 = 0;
297    let mut depth_paren: u16 = 0;
298    let mut splits = Vec::new();
299    let mut last: usize = 0;
300    for (i, c) in ts_type.char_indices() {
301        match c {
302            '<' => depth_angle += 1,
303            '>' => depth_angle = depth_angle.saturating_sub(1),
304            '[' => depth_square += 1,
305            ']' => depth_square = depth_square.saturating_sub(1),
306            '(' => depth_paren += 1,
307            ')' => depth_paren = depth_paren.saturating_sub(1),
308            ',' if depth_angle == 0 && depth_square == 0 && depth_paren == 0 => {
309                splits.push(ts_type[last..i].trim());
310                last = i + 1;
311            }
312            _ => {}
313        }
314    }
315    let len = ts_type.len();
316    if last != len {
317        let maybe_arg = ts_type[last..len].trim();
318        if !maybe_arg.is_empty() {
319            splits.push(maybe_arg);
320        }
321    }
322    splits
323}
324
325fn ts_type_to_rust_type(ts_type: Option<&str>, is_input: bool) -> RustType {
326    let Some(mut ts_type) = ts_type else {
327        return RustType::Regular(
328            (if is_input {
329                DEFAULT_GENRIC_INPUT
330            } else {
331                DEFAULT_GENERIC_OUTPUT
332            })
333            .to_owned(),
334        );
335    };
336    ts_type = strip_parenthesis(&mut ts_type);
337    if ts_type.starts_with("Promise<") && ts_type.ends_with(">") {
338        assert!(!is_input, "Promise cannot be used as input type");
339        ts_type = &ts_type[8..ts_type.len() - 1];
340    }
341    ts_type = strip_parenthesis(&mut ts_type);
342    if ts_type.contains(JSVALUE_START) {
343        let parts = split_top_level_union(ts_type);
344        let len = parts.len();
345        if len == 1 && parts[0].starts_with(JSVALUE_START) {
346            return RustType::JsValue(JsValue {
347                is_option: false,
348                is_input,
349            });
350        }
351
352        if len == 2 && parts.contains(&"null") {
353            return RustType::JsValue(JsValue {
354                is_option: true,
355                is_input,
356            });
357        } else {
358            panic!("Invalid use of `{}` for `{}`", JSVALUE_START, ts_type);
359        }
360    }
361    if ts_type.contains(RUST_CALLBACK_JS_START) {
362        if !ts_type.starts_with(RUST_CALLBACK_JS_START) {
363            panic!("Nested RustCallback is not valid: {}", ts_type);
364        }
365        assert!(is_input, "Cannot return a RustCallback: {}", ts_type);
366        let ts_type = &ts_type[RUST_CALLBACK_JS_START.len()..];
367        if !(ts_type.starts_with("<") && ts_type.ends_with(">")) {
368            panic!("Invalid RustCallback type: {}", ts_type);
369        }
370        let inner = &ts_type[1..ts_type.len() - 1];
371        let parts = split_into_args(inner);
372        let len = parts.len();
373        if len != 2 {
374            panic!(
375                "A RustCallback type expects two parameters, got: {:?}",
376                parts
377            );
378        }
379        let ts_input = parts[0];
380        let rs_input = if ts_input == "void" {
381            None
382        } else {
383            let rs_input = ts_type_to_rust_type_helper(ts_input, false);
384            if rs_input.is_none() || rs_input.as_ref().is_some_and(|e| e == UNIT) {
385                panic!("Type `{ts_input}` is not a valid input for `{RUST_CALLBACK_JS_START}`");
386            }
387            rs_input
388        };
389        let ts_output = parts[1];
390        let rs_output = if ts_output == "void" {
391            None
392        } else {
393            let rs_output = ts_type_to_rust_type_helper(ts_output, false);
394            if rs_output.is_none() || rs_output.as_ref().is_some_and(|e| e == UNIT) {
395                panic!("Type `{ts_output}` is not a valid output for `{RUST_CALLBACK_JS_START}`");
396            }
397            rs_output
398        };
399        return RustType::Callback(RustCallback {
400            input: rs_input,
401            output: rs_output,
402        });
403    }
404    RustType::Regular(match ts_type_to_rust_type_helper(ts_type, is_input) {
405        Some(value) => {
406            if value.contains(UNIT) && (is_input || &value != UNIT) {
407                // Would cause serialization errors since `serde_json::Value::Null` or any, cannot be deserialized into `()`.
408                // We handle `()` special case to account for this if this is the root type in the output. But not input or output nested.
409                panic!("`{}` is not valid in this position", ts_type);
410            }
411            value
412        }
413        None => (if is_input {
414            DEFAULT_GENRIC_INPUT
415        } else {
416            DEFAULT_GENERIC_OUTPUT
417        })
418        .to_owned(),
419    })
420}
421
422/// Returns None if could not determine type
423fn ts_type_to_rust_type_helper(mut ts_type: &str, can_be_ref: bool) -> Option<String> {
424    ts_type = ts_type.trim();
425    ts_type = strip_parenthesis(&mut ts_type);
426
427    let parts = split_top_level_union(ts_type);
428    if parts.len() > 1 {
429        // Handle single null union: T | null or null | T
430        if parts.len() == 2 && parts.contains(&"null") {
431            let inner = parts.iter().find(|p| **p != "null")?;
432            let inner_rust = ts_type_to_rust_type_helper(inner, can_be_ref)?;
433            return Some(format!("Option<{}>", inner_rust));
434        }
435        // Unsupported union type
436        return None;
437    }
438
439    ts_type = parts[0];
440
441    if ts_type.ends_with("[]") {
442        let inner = ts_type.strip_suffix("[]").unwrap();
443        let inner_rust = ts_type_to_rust_type_helper(inner, false)?;
444        return Some(if can_be_ref {
445            format!("&[{}]", inner_rust)
446        } else {
447            format!("Vec<{}>", inner_rust)
448        });
449    }
450
451    if ts_type.starts_with("Array<") && ts_type.ends_with(">") {
452        let inner = &ts_type[6..ts_type.len() - 1];
453        let inner_rust = ts_type_to_rust_type_helper(inner, false)?;
454        return Some(if can_be_ref {
455            format!("&[{}]", inner_rust)
456        } else {
457            format!("Vec<{}>", inner_rust)
458        });
459    }
460
461    if ts_type.starts_with("Set<") && ts_type.ends_with(">") {
462        let inner = &ts_type[4..ts_type.len() - 1];
463        let inner_rust = ts_type_to_rust_type_helper(inner, false)?;
464        if can_be_ref {
465            return Some(format!("&std::collections::HashSet<{}>", inner_rust));
466        } else {
467            return Some(format!("std::collections::HashSet<{}>", inner_rust));
468        }
469    }
470
471    if ts_type.starts_with("Map<") && ts_type.ends_with(">") {
472        let inner = &ts_type[4..ts_type.len() - 1];
473        let mut depth = 0;
474        let mut split_index = None;
475        for (i, c) in inner.char_indices() {
476            match c {
477                '<' => depth += 1,
478                '>' => depth -= 1,
479                ',' if depth == 0 => {
480                    split_index = Some(i);
481                    break;
482                }
483                _ => {}
484            }
485        }
486
487        if let Some(i) = split_index {
488            let (key, value) = inner.split_at(i);
489            let value = &value[1..]; // skip comma
490            let key_rust = ts_type_to_rust_type_helper(key.trim(), false)?;
491            let value_rust = ts_type_to_rust_type_helper(value.trim(), false)?;
492            if can_be_ref {
493                return Some(format!(
494                    "&std::collections::HashMap<{}, {}>",
495                    key_rust, value_rust
496                ));
497            } else {
498                return Some(format!(
499                    "std::collections::HashMap<{}, {}>",
500                    key_rust, value_rust
501                ));
502            }
503        } else {
504            return None;
505        }
506    }
507
508    // Base types
509    let rust_type = match ts_type {
510        "string" => {
511            if can_be_ref {
512                Some("&str".to_owned())
513            } else {
514                Some("String".to_owned())
515            }
516        }
517        "number" => Some("f64".to_owned()),
518        "boolean" => Some("bool".to_owned()),
519        "void" | "undefined" | "never" | "null" => Some(UNIT.to_owned()),
520        JSON => {
521            if can_be_ref {
522                Some(format!("&{SERDE_VALUE}"))
523            } else {
524                Some(SERDE_VALUE.to_owned())
525            }
526        }
527        "Promise" => {
528            panic!("`{}` - nested promises are not valid", ts_type)
529        }
530        // "any" | "unknown" | "object" | .. etc.
531        _ => None,
532    };
533
534    rust_type
535}
536
537/// Splits e.g. `number | null | string` ignoring nesting like `(number | null)[]`
538fn split_top_level_union(s: &str) -> Vec<&str> {
539    let mut parts = vec![];
540    let mut last = 0;
541    let mut depth_angle = 0;
542    let mut depth_paren = 0;
543
544    for (i, c) in s.char_indices() {
545        match c {
546            '<' => depth_angle += 1,
547            '>' => {
548                if depth_angle > 0 {
549                    depth_angle -= 1
550                }
551            }
552            '(' => depth_paren += 1,
553            ')' => {
554                if depth_paren > 0 {
555                    depth_paren -= 1
556                }
557            }
558            '|' if depth_angle == 0 && depth_paren == 0 => {
559                parts.push(s[last..i].trim());
560                last = i + 1;
561            }
562            _ => {}
563        }
564    }
565
566    if last < s.len() {
567        parts.push(s[last..].trim());
568    }
569
570    parts
571}
572
573fn type_to_string(ty: &Box<TsType>, source_map: &SourceMap) -> String {
574    let span = ty.span();
575    source_map
576        .span_to_snippet(span)
577        .expect("Could not get snippet from span for type")
578}
579
580fn function_pat_to_param_info<'a, I>(pats: I, source_map: &SourceMap) -> Vec<ParamInfo>
581where
582    I: Iterator<Item = &'a Pat>,
583{
584    pats.enumerate()
585        .map(|(i, pat)| to_param_info_helper(i, pat, source_map))
586        .collect()
587}
588
589fn to_param_info_helper(i: usize, pat: &Pat, source_map: &SourceMap) -> ParamInfo {
590    let name = if let Some(ident) = pat.as_ident() {
591        ident.id.sym.to_string()
592    } else {
593        format!("arg{}", i)
594    };
595
596    let js_type = pat
597        .as_ident()
598        .and_then(|ident| ident.type_ann.as_ref())
599        .map(|type_ann| {
600            let ty = &type_ann.type_ann;
601            type_to_string(ty, source_map)
602        });
603    let rust_type = ts_type_to_rust_type(js_type.as_deref(), true);
604
605    ParamInfo {
606        name,
607        js_type,
608        rust_type,
609    }
610}
611
612fn function_info_helper<'a, I>(
613    visitor: &JsVisitor,
614    name: String,
615    span: &swc_common::Span,
616    params: I,
617    return_type: Option<&Box<TsTypeAnn>>,
618    is_async: bool,
619    is_exported: bool,
620) -> FunctionInfo
621where
622    I: Iterator<Item = &'a Pat>,
623{
624    let doc_comment = visitor.extract_doc_comment(span);
625
626    let params = function_pat_to_param_info(params, &visitor.source_map);
627
628    let js_return_type = return_type.as_ref().map(|type_ann| {
629        let ty = &type_ann.type_ann;
630        type_to_string(ty, &visitor.source_map)
631    });
632    if !is_async
633        && let Some(ref js_return_type) = js_return_type
634        && js_return_type.starts_with("Promise")
635    {
636        panic!(
637            "Promise return type is only supported for async functions, use `async fn` instead. For `{js_return_type}`"
638        );
639    }
640
641    let rust_return_type = ts_type_to_rust_type(js_return_type.as_deref(), false);
642
643    FunctionInfo {
644        name,
645        ident: None,
646        params,
647        js_return_type,
648        rust_return_type,
649        is_exported,
650        is_async,
651        doc_comment,
652    }
653}
654
655impl Visit for JsVisitor {
656    /// Visit function declarations: function foo() {}
657    fn visit_fn_decl(&mut self, node: &FnDecl) {
658        let name = node.ident.sym.to_string();
659        self.functions.push(function_info_helper(
660            self,
661            name,
662            &node.span(),
663            node.function.params.iter().map(|e| &e.pat),
664            node.function.return_type.as_ref(),
665            node.function.is_async,
666            false,
667        ));
668        node.visit_children_with(self);
669    }
670
671    /// Visit function expressions: const foo = function() {}
672    fn visit_var_declarator(&mut self, node: &VarDeclarator) {
673        if let swc_ecma_ast::Pat::Ident(ident) = &node.name {
674            if let Some(init) = &node.init {
675                let span = node.span();
676                let name = ident.id.sym.to_string();
677                match &**init {
678                    swc_ecma_ast::Expr::Fn(fn_expr) => {
679                        self.functions.push(function_info_helper(
680                            &self,
681                            name,
682                            &span,
683                            fn_expr.function.params.iter().map(|e| &e.pat),
684                            fn_expr.function.return_type.as_ref(),
685                            fn_expr.function.is_async,
686                            false,
687                        ));
688                    }
689                    swc_ecma_ast::Expr::Arrow(arrow_fn) => {
690                        self.functions.push(function_info_helper(
691                            &self,
692                            name,
693                            &span,
694                            arrow_fn.params.iter(),
695                            arrow_fn.return_type.as_ref(),
696                            arrow_fn.is_async,
697                            false,
698                        ));
699                    }
700                    _ => {}
701                }
702            }
703        }
704        node.visit_children_with(self);
705    }
706
707    /// Visit export declarations: export function foo() {} or export class Bar {}
708    fn visit_export_decl(&mut self, node: &ExportDecl) {
709        match &node.decl {
710            Decl::Fn(fn_decl) => {
711                let span = node.span();
712                let name = fn_decl.ident.sym.to_string();
713                self.functions.push(function_info_helper(
714                    &self,
715                    name,
716                    &span,
717                    fn_decl.function.params.iter().map(|e| &e.pat),
718                    fn_decl.function.return_type.as_ref(),
719                    fn_decl.function.is_async,
720                    true,
721                ));
722            }
723            Decl::Class(class_decl) => {
724                let name = class_decl.ident.sym.to_string();
725                let span = class_decl.class.span();
726                let doc_comment = self.extract_doc_comment(&span);
727                let mut methods = Vec::new();
728
729                for member in &class_decl.class.body {
730                    match member {
731                        ClassMember::Method(method) => {
732                            let method_name = match &method.key {
733                                PropName::Ident(ident) => ident.sym.to_string(),
734                                PropName::Str(str_lit) => str_lit.value.to_string(),
735                                _ => continue,
736                            };
737
738                            let method_span = method.span();
739                            let method_doc = self.extract_doc_comment(&method_span);
740
741                            let params = function_pat_to_param_info(
742                                method.function.params.iter().map(|p| &p.pat),
743                                &self.source_map,
744                            );
745
746                            let js_return_type =
747                                method.function.return_type.as_ref().map(|type_ann| {
748                                    let ty = &type_ann.type_ann;
749                                    type_to_string(ty, &self.source_map)
750                                });
751
752                            let is_async = method.function.is_async;
753                            if !is_async
754                                && js_return_type
755                                    .as_ref()
756                                    .is_some_and(|js_return_type: &String| {
757                                        js_return_type.starts_with("Promise")
758                                    })
759                            {
760                                panic!(
761                                    "Method `{}` in exported class `{}` returns a Promise but is not marked as async",
762                                    method_name, name
763                                );
764                            }
765
766                            let rust_return_type =
767                                ts_type_to_rust_type(js_return_type.as_deref(), false);
768
769                            methods.push(MethodInfo {
770                                name: method_name,
771                                params,
772                                js_return_type,
773                                rust_return_type,
774                                is_async,
775                                is_static: method.is_static,
776                                doc_comment: method_doc,
777                            });
778                        }
779                        _ => {}
780                    }
781                }
782
783                self.classes.push(ClassInfo {
784                    name,
785                    ident: None,
786                    methods,
787                    is_exported: true,
788                    doc_comment,
789                });
790            }
791            _ => {}
792        }
793        node.visit_children_with(self);
794    }
795
796    /// Visit named exports: export { foo }
797    fn visit_named_export(&mut self, node: &NamedExport) {
798        for spec in &node.specifiers {
799            if let ExportSpecifier::Named(named) = spec {
800                let original_name = named.orig.atom().to_string();
801                let out_name = named
802                    .exported
803                    .as_ref()
804                    .map(|e| e.atom().to_string())
805                    .unwrap_or_else(|| original_name.clone());
806
807                if let Some(func) = self.functions.iter_mut().find(|f| f.name == original_name) {
808                    let mut func = func.clone();
809                    func.name = out_name.clone();
810                    func.is_exported = true;
811                    self.functions.push(func);
812                }
813
814                if let Some(class) = self.classes.iter_mut().find(|c| c.name == original_name) {
815                    let mut class = class.clone();
816                    class.name = out_name.clone();
817                    class.is_exported = true;
818                    self.classes.push(class);
819                }
820            }
821        }
822        node.visit_children_with(self);
823    }
824
825    /// Visit class declarations: class Foo {}
826    fn visit_class_decl(&mut self, node: &ClassDecl) {
827        let name = node.ident.sym.to_string();
828        let span = node.span();
829        let doc_comment = self.extract_doc_comment(&span);
830        let mut methods = Vec::new();
831
832        for member in &node.class.body {
833            match member {
834                ClassMember::Method(method) => {
835                    let method_name = match &method.key {
836                        PropName::Ident(ident) => ident.sym.to_string(),
837                        PropName::Str(str_lit) => str_lit.value.to_string(),
838                        _ => continue,
839                    };
840
841                    let method_span = method.span();
842                    let method_doc = self.extract_doc_comment(&method_span);
843
844                    let params = function_pat_to_param_info(
845                        method.function.params.iter().map(|p| &p.pat),
846                        &self.source_map,
847                    );
848
849                    let js_return_type = method.function.return_type.as_ref().map(|type_ann| {
850                        let ty = &type_ann.type_ann;
851                        type_to_string(ty, &self.source_map)
852                    });
853
854                    let is_async = method.function.is_async;
855                    if !is_async
856                        && js_return_type
857                            .as_ref()
858                            .is_some_and(|js_return_type: &String| {
859                                js_return_type.starts_with("Promise")
860                            })
861                    {
862                        panic!(
863                            "Function `{}` in class `{}` returns a Promise but is not marked as async",
864                            method_name, name
865                        );
866                    }
867
868                    let rust_return_type = ts_type_to_rust_type(js_return_type.as_deref(), false);
869
870                    methods.push(MethodInfo {
871                        name: method_name,
872                        params,
873                        js_return_type,
874                        rust_return_type,
875                        is_async,
876                        is_static: method.is_static,
877                        doc_comment: method_doc,
878                    });
879                }
880                _ => {}
881            }
882        }
883
884        self.classes.push(ClassInfo {
885            name,
886            ident: None,
887            methods,
888            is_exported: false,
889            doc_comment,
890        });
891
892        node.visit_children_with(self);
893    }
894}
895
896fn parse_script_file(file_path: &Path, is_js: bool) -> Result<(Vec<FunctionInfo>, Vec<ClassInfo>)> {
897    let js_content = fs::read_to_string(file_path).map_err(|e| {
898        syn::Error::new(
899            proc_macro2::Span::call_site(),
900            format!("Could not read file '{}': {}", file_path.display(), e),
901        )
902    })?;
903
904    let source_map = SourceMap::default();
905    let fm = source_map.new_source_file(
906        swc_common::FileName::Custom(file_path.display().to_string()).into(),
907        js_content.clone(),
908    );
909    let comments = SingleThreadedComments::default();
910
911    // Enable TypeScript parsing to handle type annotations
912    let syntax = if is_js {
913        Syntax::Es(EsSyntax {
914            jsx: false,
915            fn_bind: false,
916            decorators: false,
917            decorators_before_export: false,
918            export_default_from: false,
919            import_attributes: false,
920            allow_super_outside_method: false,
921            allow_return_outside_function: false,
922            auto_accessors: false,
923            explicit_resource_management: false,
924        })
925    } else {
926        Syntax::Typescript(swc_ecma_parser::TsSyntax {
927            tsx: false,
928            decorators: false,
929            dts: false,
930            no_early_errors: false,
931            disallow_ambiguous_jsx_like: true,
932        })
933    };
934
935    let lexer = Lexer::new(
936        syntax,
937        Default::default(),
938        StringInput::from(&*fm),
939        Some(&comments),
940    );
941
942    let mut parser = Parser::new_from(lexer);
943
944    let module = parser.parse_module().map_err(|e| {
945        syn::Error::new(
946            proc_macro2::Span::call_site(),
947            format!(
948                "Failed to parse script file '{}': {:?}",
949                file_path.display(),
950                e
951            ),
952        )
953    })?;
954
955    let mut visitor = JsVisitor::new(comments, source_map);
956    module.visit_with(&mut visitor);
957
958    Ok((visitor.functions, visitor.classes))
959}
960
961fn get_types_to_generate(
962    classes: Vec<ClassInfo>,
963    functions: Vec<FunctionInfo>,
964    import_spec: &ImportSpec,
965    file: &Path,
966) -> Result<(Vec<ClassInfo>, Vec<FunctionInfo>)> {
967    fn named_helper(
968        names: &Vec<Ident>,
969        mut all_class_infos: Vec<ClassInfo>,
970        mut all_function_infos: Vec<FunctionInfo>,
971        file: &Path,
972    ) -> Result<(Vec<ClassInfo>, Vec<FunctionInfo>)> {
973        let mut resolved_function_infos = Vec::new();
974        let mut resolved_class_infos = Vec::new();
975        for name in names {
976            let name_str = name.to_string();
977            if let Some(pos) = all_function_infos
978                .iter()
979                .position(|f: &FunctionInfo| f.name == name_str)
980            {
981                let mut function_info = all_function_infos.remove(pos);
982                if !function_info.is_exported {
983                    return Err(syn::Error::new(
984                        proc_macro2::Span::call_site(),
985                        format!(
986                            "Function '{}' not exported in file '{}'",
987                            name,
988                            file.display()
989                        ),
990                    ));
991                }
992                function_info.ident.replace(name.clone());
993                resolved_function_infos.push(function_info);
994            } else if let Some(pos) = all_class_infos.iter().position(|c: &ClassInfo| c.name == name_str) {
995                let mut class_info = all_class_infos.remove(pos);
996                if !class_info.is_exported {
997                    return Err(syn::Error::new(
998                        proc_macro2::Span::call_site(),
999                        format!("Class '{}' not exported in file '{}'", name, file.display()),
1000                    ));
1001                }
1002                class_info.ident.replace(name.clone());
1003                resolved_class_infos.push(class_info);
1004            } else {
1005                return Err(syn::Error::new(
1006                    proc_macro2::Span::call_site(),
1007                    format!(
1008                        "Function or Class '{}' not found in file '{}'",
1009                        name,
1010                        file.display()
1011                    ),
1012                ));
1013            }
1014        }
1015        Ok((resolved_class_infos, resolved_function_infos))
1016    }
1017    match import_spec {
1018        ImportSpec::All => Ok((
1019            classes.into_iter().filter(|e| e.is_exported).collect(),
1020            functions.into_iter().filter(|e| e.is_exported).collect(),
1021        )),
1022        ImportSpec::Single(name) => named_helper(&vec![name.clone()], classes, functions, file),
1023        ImportSpec::Named(names) => named_helper(names, classes, functions, file),
1024    }
1025}
1026
1027fn generate_class_wrapper(
1028    class_info: &ClassInfo,
1029    asset_path: &LitStr,
1030    function_id_hasher: &blake3::Hasher,
1031) -> TokenStream2 {
1032    let class_ident = class_info
1033        .ident
1034        .clone()
1035        .unwrap_or_else(|| Ident::new(class_info.name.as_str(), proc_macro2::Span::call_site()));
1036
1037    let doc_comment = if class_info.doc_comment.is_empty() {
1038        quote! {}
1039    } else {
1040        let doc_lines: Vec<_> = class_info
1041            .doc_comment
1042            .iter()
1043            .map(|line| quote! { #[doc = #line] })
1044            .collect();
1045        quote! { #(#doc_lines)* }
1046    };
1047
1048    let mut parts: Vec<TokenStream2> = Vec::new();
1049    for method in &class_info.methods {
1050        let func_info = FunctionInfo {
1051            name: method.name.clone(),
1052            ident: None,
1053            params: method.params.clone(),
1054            js_return_type: method.js_return_type.clone(),
1055            rust_return_type: method.rust_return_type.clone(),
1056            is_exported: true,
1057            is_async: method.is_async,
1058            doc_comment: method.doc_comment.clone(),
1059        };
1060
1061        let inner_function = generate_invocation(
1062            Some(FunctionClassContext {
1063                class_name: class_info.name.clone(),
1064                ident: class_ident.clone(),
1065                is_static: method.is_static,
1066            }),
1067            &func_info,
1068            asset_path,
1069            function_id_hasher,
1070        );
1071
1072        let method_name = format_ident!("{}", method.name);
1073        let method_params: Vec<_> = method
1074            .params
1075            .iter()
1076            .filter_map(|param| {
1077                if param.is_drop() {
1078                    return None;
1079                }
1080                let param_name = format_ident!("{}", param.name);
1081                let type_tokens = param.rust_type.to_tokens();
1082                Some(quote! { #param_name: #type_tokens })
1083            })
1084            .collect();
1085
1086        let param_names: Vec<_> = method
1087            .params
1088            .iter()
1089            .map(|p| format_ident!("{}", p.name))
1090            .collect();
1091
1092        let method_doc = if method.doc_comment.is_empty() {
1093            quote! {}
1094        } else {
1095            let doc_lines: Vec<_> = method
1096                .doc_comment
1097                .iter()
1098                .map(|line| quote! { #[doc = #line] })
1099                .collect();
1100            quote! { #(#doc_lines)* }
1101        };
1102
1103        fn returns_self_type(func_info: &FunctionInfo, class_info: &ClassInfo) -> bool {
1104            let Some(js_return_type) = &func_info.js_return_type else {
1105                return false;
1106            };
1107            if !matches!(func_info.rust_return_type, RustType::JsValue(_)) {
1108                return false;
1109            }
1110            if js_return_type.starts_with("JsValue<") && js_return_type.ends_with('>') {
1111                let inner = js_return_type[8..js_return_type.len() - 1].trim();
1112                if inner == class_info.name {
1113                    return true;
1114                }
1115            }
1116            return false;
1117        }
1118
1119        let (invocation, return_type, generic) = if returns_self_type(&func_info, &class_info) {
1120            // Constructs this
1121            let invocation = if method.is_static {
1122                quote! {
1123                    Ok(#class_ident::new(#method_name(#(#param_names),*).await?))
1124                }
1125            } else {
1126                quote! {
1127                    Ok(#class_ident::new(#method_name(&self.0, #(#param_names),*).await?))
1128                }
1129            };
1130            let (_, generic_tokens) = return_type_tokens(
1131                &method.rust_return_type,
1132                class_info.ident.as_ref().map(|e| e.span()),
1133            );
1134            let return_type_tokens = quote! { Result<#class_ident, dioxus_use_js::JsError> };
1135            (invocation, return_type_tokens, generic_tokens)
1136        } else {
1137            let invocation = if method.is_static {
1138                quote! {
1139                    #method_name(#(#param_names),*).await
1140                }
1141            } else {
1142                quote! {
1143                    #method_name(&self.0, #(#param_names),*).await
1144                }
1145            };
1146            let (return_type_tokens, generic_tokens) = return_type_tokens(
1147                &method.rust_return_type,
1148                class_info.ident.as_ref().map(|e| e.span()),
1149            );
1150            (invocation, return_type_tokens, generic_tokens)
1151        };
1152
1153        let part = if method.is_static {
1154            quote! {
1155                #method_doc
1156                #[allow(non_snake_case)]
1157                pub async fn #method_name #generic(#(#method_params),*) -> #return_type {
1158                    #[inline]
1159                    #inner_function
1160                    #invocation
1161                }
1162            }
1163        } else {
1164            quote! {
1165                #method_doc
1166                #[allow(non_snake_case)]
1167                pub async fn #method_name #generic(&self, #(#method_params),*) -> #return_type {
1168                    #[inline]
1169                    #inner_function
1170                    #invocation
1171                }
1172            }
1173        };
1174
1175        parts.push(part);
1176    }
1177
1178    quote! {
1179        #doc_comment
1180        #[derive(Clone, Debug, PartialEq, Eq, Hash,)]
1181        pub struct #class_ident(dioxus_use_js::JsValue);
1182
1183        impl #class_ident {
1184            pub fn new(js_value: dioxus_use_js::JsValue) -> Self {
1185                Self(js_value)
1186            }
1187        }
1188
1189        impl #class_ident {
1190            #(#parts)*
1191        }
1192
1193        impl AsRef<dioxus_use_js::JsValue> for #class_ident {
1194            fn as_ref(&self) -> &dioxus_use_js::JsValue {
1195                &self.0
1196            }
1197        }
1198    }
1199}
1200
1201struct FunctionClassContext {
1202    class_name: String,
1203    ident: Ident,
1204    is_static: bool,
1205}
1206
1207fn generate_invocation(
1208    class: Option<FunctionClassContext>,
1209    func: &FunctionInfo,
1210    asset_path: &LitStr,
1211    function_id_hasher: &blake3::Hasher,
1212) -> TokenStream2 {
1213    let is_class_method = class.as_ref().is_some_and(|e| !e.is_static);
1214    let mut params = func.params.clone();
1215    if is_class_method {
1216        let new_param = ParamInfo {
1217            name: "_m_".to_owned(),
1218            js_type: None,
1219            rust_type: RustType::JsValue(JsValue {
1220                is_option: false,
1221                is_input: true,
1222            }),
1223        };
1224        params.insert(0, new_param);
1225    }
1226    // If we have callbacks, we cant do a simpl return, we have to do message passing
1227    let mut callback_name_to_index: HashMap<String, u64> = HashMap::new();
1228    let mut callback_name_to_info: IndexMap<String, &RustCallback> = IndexMap::new();
1229    let mut index: u64 = 0;
1230    let mut needs_drop = false;
1231    let mut has_callbacks = false;
1232    for param in &params {
1233        if let RustType::Callback(callback) = &param.rust_type {
1234            callback_name_to_index.insert(param.name.to_owned(), index);
1235            index += 1;
1236            callback_name_to_info.insert(param.name.to_owned(), callback);
1237            has_callbacks = true;
1238            needs_drop = true;
1239        } else if param.is_drop() {
1240            needs_drop = true;
1241        }
1242    }
1243    let func_name_str = &func.name;
1244    let func_name_static_ident = quote! { FUNC_NAME };
1245
1246    let send_calls: Vec<TokenStream2> = params
1247        .iter()
1248        .flat_map(|param| {
1249            if param.is_drop() {
1250                return None;
1251            }
1252            let param_name = format_ident!("{}", param.name);
1253            match &param.rust_type {
1254                RustType::Regular(_) => Some(quote! {
1255                    eval.send(#param_name).map_err(|e| dioxus_use_js::JsError::Eval { func: #func_name_static_ident, error: std::sync::Arc::new(e) })?;
1256                }),
1257                RustType::JsValue(js_value) => {
1258                    if js_value.is_option {
1259                        Some(quote! {
1260                            #[allow(deprecated)]
1261                            eval.send(#param_name.map(|e| e.internal_get())).map_err(|e| dioxus_use_js::JsError::Eval { func: #func_name_static_ident, error: std::sync::Arc::new(e) })?;
1262                        })
1263                    } else {
1264                        Some(quote! {
1265                            #[allow(deprecated)]
1266                            eval.send(#param_name.internal_get()).map_err(|e| dioxus_use_js::JsError::Eval { func: #func_name_static_ident, error: std::sync::Arc::new(e) })?;
1267                        })
1268                    }
1269                },
1270                RustType::Callback(_) => {
1271                    None
1272                },
1273            }
1274        })
1275        .collect();
1276
1277    // Note we use `func.params` here
1278    let call_params = &func
1279        .params
1280        .iter()
1281        .map(|p| p.name.as_str())
1282        .collect::<Vec<&str>>()
1283        .join(", ");
1284    let prepare = if has_callbacks {
1285        assert!(needs_drop);
1286        "let _i_=\"**INVOCATION_ID**\";let _l_={};window[_i_]=_l_;let _g_ = 0;let _a_=true;const _c_=(c, v)=>{if(!_a_){return Promise.reject(new Error(\"Channel already destroyed\"));}_g_+=1;if(_g_>Number.MAX_SAFE_INTEGER){_g_= 0;}let o, e;let p=new Promise((rs, rj)=>{o=rs;e=rj});_l_[_g_]=[o, e];dioxus.send([c,_g_,v]);return p;};"
1287    } else if needs_drop {
1288        "let _i_=\"**INVOCATION_ID**\";"
1289    } else {
1290        ""
1291    };
1292    let param_declarations = &params
1293        .iter()
1294        .map(|param| {
1295            if needs_drop && param.is_drop() {
1296                return format!("let {}=_dp_;", param.name);
1297            }
1298            match &param.rust_type {
1299            RustType::Regular(_) => {
1300                format!("let {}=await dioxus.recv();", param.name)
1301            }
1302            RustType::JsValue(js_value) => {
1303                let param_name = &param.name;
1304                if js_value.is_option {
1305                format!(
1306                    "let _{param_name}T_=await dioxus.recv();let {param_name}=null;if(_{param_name}T_!==null){{{param_name}=window[_{param_name}T_]}};",
1307                )
1308            }
1309            else {
1310                format!(
1311                    "let _{param_name}T_=await dioxus.recv();let {param_name}=window[_{param_name}T_];",
1312                )
1313            }
1314            },
1315            RustType::Callback(rust_callback) => {
1316                let name = &param.name;
1317                let index = callback_name_to_index.get(name).unwrap();
1318                let RustCallback { input, output } = rust_callback;
1319                match (input, output) {
1320                    (None, None) => {
1321                        // no return, but still need to await ack
1322                        format!(
1323                            "const {}=async()=>{{await _c_({},null);}};",
1324                            name, index
1325                        )
1326                    },
1327                    (None, Some(_)) => {
1328                        format!(
1329                            "const {}=async()=>{{return await _c_({},null);}};",
1330                            name, index
1331
1332                        )
1333                    },
1334                    (Some(_), None) => {
1335                        // no return, but still need to await ack
1336                        format!(
1337                            "const {}=async(v)=>{{await _c_({},v);}};",
1338                            name, index
1339                        )
1340                    },
1341                    (Some(_), Some(_)) => {
1342                        format!(
1343                            "const {}=async(v)=>{{return await _c_({},v);}};",
1344                            name, index
1345                        )
1346                    },
1347                }
1348            },
1349        }})
1350        .collect::<Vec<_>>()
1351        .join("");
1352    let mut maybe_await = String::new();
1353    if func.is_async {
1354        maybe_await.push_str("await");
1355    }
1356    let func_call_full_path = if is_class_method {
1357        let var_name = &params.first().unwrap().name;
1358        format!("{var_name}.{func_name_str}")
1359    } else if let Some(class) = &class {
1360        let class_name = &class.class_name;
1361        format!("{class_name}.{func_name_str}")
1362    } else {
1363        func_name_str.to_owned()
1364    };
1365    let call_function = match &func.rust_return_type {
1366        RustType::Regular(_) => {
1367            format!("return [true, {maybe_await} {func_call_full_path}({call_params})];")
1368        }
1369        RustType::Callback(_) => {
1370            unreachable!("This cannot be an output type, the macro should have panicked earlier.")
1371        }
1372        RustType::JsValue(js_value) => {
1373            let check = if js_value.is_option {
1374                // null or undefined is valid, since this is e.g. `Option<JsValue>`
1375                "if (_v_===null||_v_===undefined){return [true,null];}".to_owned()
1376            } else {
1377                format!(
1378                    "if (_v_===null||_v_===undefined){{console.error(\"The result of `{func_call_full_path}` was null or undefined, but a value is needed for JsValue\");return [true,null];}}"
1379                )
1380            };
1381            format!(
1382                "const _v_={maybe_await} {func_call_full_path}({call_params});{check}let _j_=\"__js-value-\"+crypto.randomUUID();window[_j_]=_v_;return [true,_j_];"
1383            )
1384        }
1385    };
1386    let drop_declare = if needs_drop {
1387        // Note the additional `d` also added by `SignalDrop`
1388        "let _d_;let _dp_=new Promise((r)=>_d_=r);window[_i_+\"d\"]=_d_;"
1389    } else {
1390        ""
1391    };
1392    let drop_handle = if needs_drop {
1393        if has_callbacks {
1394            "(async()=>{await _dp_;dioxus.close();_a_=false;let w=window[_i_];delete window[_i_];for(const[o, e] of Object.values(w)){e(new Error(\"Channel destroyed\"));}})();"
1395        } else {
1396            "(async()=>{await _dp_;dioxus.close();})();"
1397        }
1398    } else {
1399        assert!(
1400            !has_callbacks,
1401            "If this is true then needing drop should be true"
1402        );
1403        ""
1404    };
1405    let finally = if needs_drop {
1406        ""
1407    } else {
1408        "finally{dioxus.close();}"
1409    };
1410    let asset_path_string = asset_path.value();
1411    // Note: eval will fail if returning undefined. undefined happens if there is no return type
1412    let js = if is_class_method {
1413        format!(
1414            "{prepare}{drop_declare}{param_declarations}{drop_handle}try{{{call_function}}}catch(e){{console.warn(\"Executing `{func_call_full_path}` threw:\", e);return [false,null];}}{finally}"
1415        )
1416    } else if let Some(class) = &class {
1417        let class_name = &class.class_name;
1418        format!(
1419            "const{{{class_name}}}=await import(\"{asset_path_string}\");{prepare}{drop_declare}{param_declarations}{drop_handle}try{{{call_function}}}catch(e){{console.warn(\"Executing `{func_call_full_path}` threw:\", e);return [false,null];}}{finally}"
1420        )
1421    } else {
1422        assert_eq!(func_call_full_path.as_str(), func_name_str);
1423        format!(
1424            "const{{{func_name_str}}}=await import(\"{asset_path_string}\");{prepare}{drop_declare}{param_declarations}{drop_handle}try{{{call_function}}}catch(e){{console.warn(\"Executing `{func_call_full_path}` threw:\", e);return [false,null];}}{finally}"
1425        )
1426    };
1427    fn to_raw_string_literal(s: &str) -> Literal {
1428        let mut hashes = String::from("#");
1429        while s.contains(&format!("\"{}", hashes)) {
1430            hashes.push('#');
1431        }
1432
1433        let raw = format!("r{h}\"{s}\"{h}", h = hashes);
1434        Literal::from_str(&raw).unwrap()
1435    }
1436    let comment = to_raw_string_literal(&js);
1437    // Easier debugging to see what the generated js is. Will be compiled away.
1438    let js_in_comment = quote! {
1439        #[doc = #comment]
1440        fn ___above_is_the_generated_js___() {}
1441    };
1442    let js_format = js.replace("{", "{{").replace("}", "}}");
1443    let js_format = if is_class_method {
1444        assert!(!js_format.contains(&asset_path_string));
1445        js_format
1446    } else {
1447        js_format.replace(&asset_path_string, "{}")
1448    };
1449    let js_format = if needs_drop {
1450        js_format.replace("**INVOCATION_ID**", "{}")
1451    } else {
1452        js_format
1453    };
1454    let js_eval_statement = if needs_drop {
1455        let js_line = if is_class_method {
1456            quote! {
1457            let js = format!(#js_format, &invocation_id);
1458            }
1459        } else {
1460            quote! {
1461                const MODULE: Asset = asset!(#asset_path);
1462                let js = format!(#js_format, MODULE, &invocation_id);
1463            }
1464        };
1465        let function_id = {
1466            let mut hasher = function_id_hasher.clone();
1467            hasher.update(func_call_full_path.as_bytes());
1468            let mut output_reader = hasher.finalize_xof();
1469            let mut truncated_bytes = vec![0u8; 10];
1470            use std::io::Read;
1471            output_reader.read_exact(&mut truncated_bytes).unwrap();
1472            let function_id =
1473                base64::engine::general_purpose::STANDARD_NO_PAD.encode(truncated_bytes);
1474            function_id
1475        };
1476        quote! {
1477            static INVOCATION_NUM: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
1478            // Each invocation id guarentees a unique namespace for the callback invocation for requests/responses and on drop everything there can be cleaned up and outstanding promises rejected.
1479            let invocation_id = format!("__{}{}", #function_id, INVOCATION_NUM.fetch_add(1, std::sync::atomic::Ordering::Relaxed));
1480            #js_line
1481            let mut eval = dioxus::document::eval(js.as_str());
1482        }
1483    } else {
1484        if is_class_method {
1485            quote! {
1486                let js = #js_format;
1487                let mut eval = dioxus::document::eval(js);
1488            }
1489        } else {
1490            quote! {
1491                const MODULE: Asset = asset!(#asset_path);
1492                let js = format!(#js_format, MODULE);
1493                let mut eval = dioxus::document::eval(js.as_str());
1494            }
1495        }
1496    };
1497
1498    // Generate parameter types with extracted type information
1499    let param_types: Vec<_> = params
1500        .iter()
1501        .filter_map(|param| {
1502            if param.is_drop() {
1503                return None;
1504            }
1505            let param_name = format_ident!("{}", param.name);
1506            let type_tokens = param.rust_type.to_tokens();
1507            Some(quote! { #param_name: #type_tokens })
1508        })
1509        .collect();
1510
1511    let (return_type_tokens, generic_tokens) = return_type_tokens(
1512        &func.rust_return_type,
1513        func.ident.as_ref().map(|e| e.span()),
1514    );
1515
1516    // Generate documentation comment if available - preserve original JSDoc format
1517    let doc_comment = if func.doc_comment.is_empty() {
1518        quote! {}
1519    } else {
1520        let doc_lines: Vec<_> = func
1521            .doc_comment
1522            .iter()
1523            .map(|line| quote! { #[doc = #line] })
1524            .collect();
1525        quote! { #(#doc_lines)* }
1526    };
1527
1528    let func_name = func
1529        .ident
1530        .clone()
1531        // Can not exist if `::*`
1532        .unwrap_or_else(|| Ident::new(func.name.as_str(), proc_macro2::Span::call_site()));
1533
1534    // void like returns always send back "Null" as an ack
1535    let void_output_mapping = if func.rust_return_type.to_string() == UNIT {
1536        quote! {
1537            .and_then(|e| {
1538                if matches!(e, dioxus_use_js::SerdeJsonValue::Null) {
1539                    Ok(())
1540                } else {
1541                    Err(dioxus_use_js::JsError::Eval {
1542                        func: #func_name_static_ident,
1543                        error: std::sync::Arc::new(dioxus::document::EvalError::Serialization(
1544                            <dioxus_use_js::SerdeJsonError as dioxus_use_js::SerdeDeError>::custom(dioxus_use_js::__BAD_VOID_RETURN.to_owned())
1545                        ))
1546                    })
1547                }
1548            })
1549        }
1550    } else {
1551        quote! {}
1552    };
1553
1554    let callback_arms: Vec<TokenStream2> = callback_name_to_index
1555        .iter()
1556        .map(|(name, index)| {
1557            let callback_name = format_ident!("{}", name);
1558            let callback_info = callback_name_to_info.get(name).unwrap();
1559            let callback_call = match (&callback_info.input, &callback_info.output) {
1560                (None, None) => {
1561                    quote! {
1562                    dioxus::prelude::spawn({let responder = responder.clone(); async move {
1563                        let result = #callback_name(()).await;
1564
1565                        match result {
1566                            // send ack
1567                            Ok(_) => responder.respond(request_id, true, dioxus_use_js::SerdeJsonValue::Null),
1568                            Err(error) => responder.respond(request_id, false, error),
1569                        }
1570                    }});
1571                    }
1572                },
1573                (None, Some(_)) => {
1574                    quote! {
1575                    dioxus::prelude::spawn({let responder = responder.clone(); async move {
1576                        let result = #callback_name(()).await;
1577
1578                        match result {
1579                            Ok(value) => responder.respond(request_id, true, value),
1580                            Err(error) => responder.respond(request_id, false, error),
1581                        }
1582                    }});
1583                }
1584                },
1585                (Some(_), None) => {
1586                    quote! {
1587                    let value = values.next().unwrap();
1588                    let value = match dioxus_use_js::serde_json_from_value(value) {
1589                        Ok(value) => value,
1590                        Err(value) => {
1591                            responder.respond(request_id, false, dioxus_use_js::SerdeJsonValue::String(dioxus_use_js::__UNEXPECTED_CALLBACK_TYPE.to_owned()));
1592                            continue;
1593                        }
1594                    };
1595
1596                    dioxus::prelude::spawn({let responder = responder.clone(); async move {
1597                        let result = #callback_name(value).await;
1598
1599                        match result {
1600                            // send ack
1601                            Ok(_) => responder.respond(request_id, true, dioxus_use_js::SerdeJsonValue::Null),
1602                            Err(error) => responder.respond(request_id, false, error),
1603                        }
1604                    }});
1605                }
1606                },
1607                (Some(_), Some(_)) => {
1608                    quote! {
1609                    let value = values.next().unwrap();
1610                    let value = match dioxus_use_js::serde_json_from_value(value) {
1611                        Ok(value) => value,
1612                        Err(value) => {
1613                            responder.respond(request_id, false, dioxus_use_js::SerdeJsonValue::String(dioxus_use_js::__UNEXPECTED_CALLBACK_TYPE.to_owned()));
1614                            continue;
1615                        }
1616                    };
1617
1618                    dioxus::prelude::spawn({let responder = responder.clone(); async move {
1619                        let result = #callback_name(value).await;
1620
1621                        match result {
1622                            Ok(value) => responder.respond(request_id, true, value),
1623                            Err(error) => responder.respond(request_id, false, error),
1624                        }
1625                    }});
1626                }
1627                }
1628            };
1629            quote! {
1630                #index => {
1631                    #callback_call
1632                }
1633            }
1634        })
1635        .collect();
1636
1637    let callback_spawn = if !callback_arms.is_empty() {
1638        quote! {
1639            dioxus::prelude::spawn({
1640                    async move {
1641                        let responder = dioxus_use_js::CallbackResponder::new(&invocation_id);
1642                        let _signal_drop = dioxus_use_js::SignalDrop::new(invocation_id.clone());
1643                        loop {
1644                            let result = eval.recv::<dioxus_use_js::SerdeJsonValue>().await;
1645                            let value = match result {
1646                                Ok(v) => v,
1647                                Err(e) => {
1648                                    // Though we still may be able to accept more callback requests,
1649                                    // We shutdown otherwise the invocation of this callback will be awaiting forever
1650                                    // (since we don't know where the request came from so we cannot cancel it).
1651                                    dioxus::prelude::error!(
1652                                        "Callback receiver errored. Shutting down all callbacks for invocation id `{}`: {:?}",
1653                                        &invocation_id,
1654                                        e
1655                                    );
1656                                    return;
1657                                }
1658                            };
1659                            let dioxus_use_js::SerdeJsonValue::Array(values) = value else {
1660                                unreachable!("{}", dioxus_use_js::__CALLBACK_SEND_VALIDATION_MSG);
1661                            };
1662                            let len = values.len();
1663                            if len != 3 {
1664                                unreachable!("{}", dioxus_use_js::__CALLBACK_SEND_VALIDATION_MSG);
1665                            }
1666                            let mut values = values.into_iter();
1667                            let action = values.next().unwrap().as_u64().expect(dioxus_use_js::__INDEX_VALIDATION_MSG);
1668                            let request_id = values.next().unwrap().as_u64().expect(dioxus_use_js::__INDEX_VALIDATION_MSG);
1669                            match action {
1670                                #(#callback_arms,)*
1671                                _ => unreachable!("{}", dioxus_use_js::__BAD_CALL_MSG),
1672                            }
1673                        }
1674                    }
1675            });
1676        }
1677    } else if needs_drop {
1678        // We can't use `use_drop` because the rule of hooks, so like the callback case, we just
1679        // spawn a future that will never finish, but the eval will drop and fire off the signal
1680        // when the component drops.
1681        quote! {
1682            dioxus::prelude::spawn(async move {
1683                let _signal_drop = dioxus_use_js::SignalDrop::new(invocation_id);
1684                let f = dioxus_use_js::PendingFuture;
1685                f.await;
1686            });
1687        }
1688    } else {
1689        quote! {}
1690    };
1691
1692    let end_statement = quote! {
1693        let value = eval.await.map_err(|e| {
1694            dioxus_use_js::JsError::Eval {
1695                func: #func_name_static_ident,
1696                error: std::sync::Arc::new(e),
1697            }
1698        })?;
1699        let dioxus_use_js::SerdeJsonValue::Array(values) = value else {
1700            unreachable!("{}", dioxus_use_js::__RESULT_SEND_VALIDATION_MSG);
1701        };
1702        if values.len() != 2 {
1703            unreachable!("{}", dioxus_use_js::__RESULT_SEND_VALIDATION_MSG);
1704        }
1705        let mut values = values.into_iter();
1706        let success = values.next().unwrap().as_bool().expect(dioxus_use_js::__INDEX_VALIDATION_MSG);
1707        if success {
1708            let value = values.next().unwrap();
1709            return dioxus_use_js::serde_json_from_value(value).map_err(|e| {
1710                dioxus_use_js::JsError::Eval {
1711                    func: #func_name_static_ident,
1712                    error: std::sync::Arc::new(dioxus::document::EvalError::Serialization(e)),
1713                }
1714            })
1715            #void_output_mapping;
1716        } else {
1717             return Err(dioxus_use_js::JsError::Threw { func: #func_name_static_ident });
1718        }
1719    };
1720
1721    quote! {
1722        #doc_comment
1723        #[allow(non_snake_case)]
1724        pub async fn #func_name #generic_tokens(#(#param_types),*) -> #return_type_tokens {
1725            const #func_name_static_ident: &str = #func_name_str;
1726            #js_in_comment
1727            #js_eval_statement
1728            #(#send_calls)*
1729            #callback_spawn
1730            #end_statement
1731        }
1732    }
1733}
1734
1735fn return_type_tokens(
1736    return_type: &RustType,
1737    span: Option<proc_macro2::Span>,
1738) -> (proc_macro2::TokenStream, Option<proc_macro2::TokenStream>) {
1739    let span = span.unwrap_or_else(|| proc_macro2::Span::call_site());
1740    let parsed_type = return_type.to_tokens();
1741    if return_type.to_string() == DEFAULT_GENERIC_OUTPUT {
1742        let generic = Ident::new(DEFAULT_GENERIC_OUTPUT, span);
1743        let generic_decl: TypeParam = syn::parse_str(DEFAULT_OUTPUT_GENERIC_DECLARTION).unwrap();
1744        (
1745            quote! { Result<#generic, dioxus_use_js::JsError> },
1746            Some(quote! { <#generic_decl> }),
1747        )
1748    } else {
1749        (
1750            quote! { Result<#parsed_type, dioxus_use_js::JsError> },
1751            None,
1752        )
1753    }
1754}
1755
1756/// A macro to create rust bindings to javascript and typescript functions. See [README](https://github.com/mcmah309/dioxus-use-js) and [example](https://github.com/mcmah309/dioxus-use-js/blob/master/example/src/main.rs) for more.
1757#[proc_macro]
1758pub fn use_js(input: TokenStream) -> TokenStream {
1759    let input = parse_macro_input!(input as UseJsInput);
1760
1761    let manifest_dir = match std::env::var("CARGO_MANIFEST_DIR") {
1762        Ok(dir) => dir,
1763        Err(_) => {
1764            return TokenStream::from(
1765                syn::Error::new(
1766                    proc_macro2::Span::call_site(),
1767                    "CARGO_MANIFEST_DIR environment variable not found",
1768                )
1769                .to_compile_error(),
1770            );
1771        }
1772    };
1773
1774    let UseJsInput {
1775        js_bundle_path,
1776        ts_source_path,
1777        import_spec,
1778    } = input;
1779
1780    let js_file_path = std::path::Path::new(&manifest_dir).join(js_bundle_path.value());
1781
1782    let (js_all_functions, js_all_classes) = match parse_script_file(&js_file_path, true) {
1783        Ok(result) => result,
1784        Err(e) => return TokenStream::from(e.to_compile_error()),
1785    };
1786
1787    let (js_classes_to_generate, js_functions_to_generate) = match get_types_to_generate(
1788        js_all_classes,
1789        js_all_functions,
1790        &import_spec,
1791        &js_file_path,
1792    ) {
1793        Ok((classes, funcs)) => (classes, funcs),
1794        Err(e) => {
1795            return TokenStream::from(e.to_compile_error());
1796        }
1797    };
1798
1799    let (functions_to_generate, classes_to_generate) = if let Some(ts_file_path) = ts_source_path {
1800        let ts_file_path = std::path::Path::new(&manifest_dir).join(ts_file_path.value());
1801        let (ts_all_functions, ts_all_classes) = match parse_script_file(&ts_file_path, false) {
1802            Ok(result) => result,
1803            Err(e) => return TokenStream::from(e.to_compile_error()),
1804        };
1805
1806        let (ts_classes_to_generate, ts_functions_to_generate) = match get_types_to_generate(
1807            ts_all_classes,
1808            ts_all_functions,
1809            &import_spec,
1810            &ts_file_path,
1811        ) {
1812            Ok((classes, funcs)) => (classes, funcs),
1813            Err(e) => {
1814                return TokenStream::from(e.to_compile_error());
1815            }
1816        };
1817
1818        for ts_func in ts_functions_to_generate.iter() {
1819            if let Some(js_func) = js_functions_to_generate
1820                .iter()
1821                .find(|f| f.name == ts_func.name)
1822            {
1823                if ts_func.params.len() != js_func.params.len() {
1824                    return TokenStream::from(syn::Error::new(
1825                        proc_macro2::Span::call_site(),
1826                        format!(
1827                            "Function '{}' has different parameter count in JS and TS files. Bundle may be out of date",
1828                            ts_func.name
1829                        ),
1830                    )
1831                    .to_compile_error());
1832                }
1833            } else {
1834                return TokenStream::from(syn::Error::new(
1835                    proc_macro2::Span::call_site(),
1836                    format!(
1837                        "Function '{}' is defined in TS file but not in JS file. Bundle may be out of date",
1838                        ts_func.name
1839                    ),
1840                )
1841                .to_compile_error());
1842            }
1843        }
1844
1845        // Validate classes match between TS and JS
1846        for ts_class in ts_classes_to_generate.iter() {
1847            if let Some(js_class) = js_classes_to_generate
1848                .iter()
1849                .find(|c| c.name == ts_class.name)
1850            {
1851                if ts_class.methods.len() != js_class.methods.len() {
1852                    return TokenStream::from(syn::Error::new(
1853                        proc_macro2::Span::call_site(),
1854                        format!(
1855                            "Class '{}' has different method count in JS and TS files. Bundle may be out of date",
1856                            ts_class.name
1857                        ),
1858                    )
1859                    .to_compile_error());
1860                }
1861            } else {
1862                return TokenStream::from(syn::Error::new(
1863                    proc_macro2::Span::call_site(),
1864                    format!(
1865                        "Class '{}' is defined in TS file but not in JS file. Bundle may be out of date",
1866                        ts_class.name
1867                    ),
1868                )
1869                .to_compile_error());
1870            }
1871        }
1872
1873        (ts_functions_to_generate, ts_classes_to_generate)
1874    } else {
1875        (js_functions_to_generate, js_classes_to_generate)
1876    };
1877
1878    for function in functions_to_generate.iter() {
1879        for param in function.params.iter() {
1880            if param.name.starts_with("_") && param.name.ends_with("_") {
1881                panic!(
1882                    "Parameter name '{}' in function '{}' is invalid. Parameters starting and ending with underscores are reserved.",
1883                    param.name, function.name
1884                );
1885            }
1886            if param.name == "dioxus" {
1887                panic!(
1888                    "Parameter name 'dioxus' in function '{}' is invalid. This parameter name is reserved.",
1889                    function.name
1890                );
1891            }
1892            if param.name == function.name {
1893                panic!(
1894                    "Parameter name '{}' in function '{}' is invalid. Parameters cannot have the same name as the function.",
1895                    param.name, function.name
1896                );
1897            }
1898        }
1899    }
1900
1901    let call_site_span = proc_macro::Span::call_site();
1902    let file = call_site_span.file();
1903    let line_number = call_site_span.line();
1904    let column_number = call_site_span.column();
1905    let mut unhashed_id = file;
1906    unhashed_id.push_str(":");
1907    unhashed_id.push_str(&line_number.to_string());
1908    unhashed_id.push_str(":");
1909    unhashed_id.push_str(&column_number.to_string());
1910    unhashed_id.push_str(":");
1911    let mut function_id_hasher = blake3::Hasher::new();
1912    function_id_hasher.update(unhashed_id.as_bytes());
1913
1914    let function_wrappers: Vec<TokenStream2> = functions_to_generate
1915        .iter()
1916        .map(|func| generate_invocation(None, func, &js_bundle_path, &function_id_hasher))
1917        .collect();
1918
1919    let class_wrappers: Vec<TokenStream2> = classes_to_generate
1920        .iter()
1921        .map(|class| generate_class_wrapper(class, &js_bundle_path, &function_id_hasher))
1922        .collect();
1923
1924    let expanded = quote! {
1925        #(#function_wrappers)*
1926        #(#class_wrappers)*
1927    };
1928
1929    TokenStream::from(expanded)
1930}
1931
1932//************************************************************************//
1933
1934#[cfg(test)]
1935mod tests {
1936    use super::*;
1937
1938    #[test]
1939    fn test_primitives() {
1940        assert_eq!(
1941            ts_type_to_rust_type(Some("string"), false).to_string(),
1942            "String"
1943        );
1944        assert_eq!(
1945            ts_type_to_rust_type(Some("string"), true).to_string(),
1946            "&str"
1947        );
1948        assert_eq!(
1949            ts_type_to_rust_type(Some("number"), false).to_string(),
1950            "f64"
1951        );
1952        assert_eq!(
1953            ts_type_to_rust_type(Some("number"), true).to_string(),
1954            "f64"
1955        );
1956        assert_eq!(
1957            ts_type_to_rust_type(Some("boolean"), false).to_string(),
1958            "bool"
1959        );
1960        assert_eq!(
1961            ts_type_to_rust_type(Some("boolean"), true).to_string(),
1962            "bool"
1963        );
1964    }
1965
1966    #[test]
1967    fn test_nullable_primitives() {
1968        assert_eq!(
1969            ts_type_to_rust_type(Some("string | null"), true).to_string(),
1970            "Option<&str>"
1971        );
1972        assert_eq!(
1973            ts_type_to_rust_type(Some("string | null"), false).to_string(),
1974            "Option<String>"
1975        );
1976        assert_eq!(
1977            ts_type_to_rust_type(Some("number | null"), true).to_string(),
1978            "Option<f64>"
1979        );
1980        assert_eq!(
1981            ts_type_to_rust_type(Some("number | null"), false).to_string(),
1982            "Option<f64>"
1983        );
1984        assert_eq!(
1985            ts_type_to_rust_type(Some("boolean | null"), true).to_string(),
1986            "Option<bool>"
1987        );
1988        assert_eq!(
1989            ts_type_to_rust_type(Some("boolean | null"), false).to_string(),
1990            "Option<bool>"
1991        );
1992    }
1993
1994    #[test]
1995    fn test_arrays() {
1996        assert_eq!(
1997            ts_type_to_rust_type(Some("string[]"), true).to_string(),
1998            "&[String]"
1999        );
2000        assert_eq!(
2001            ts_type_to_rust_type(Some("string[]"), false).to_string(),
2002            "Vec<String>"
2003        );
2004        assert_eq!(
2005            ts_type_to_rust_type(Some("Array<number>"), true).to_string(),
2006            "&[f64]"
2007        );
2008        assert_eq!(
2009            ts_type_to_rust_type(Some("Array<number>"), false).to_string(),
2010            "Vec<f64>"
2011        );
2012    }
2013
2014    #[test]
2015    fn test_nullable_array_elements() {
2016        assert_eq!(
2017            ts_type_to_rust_type(Some("(string | null)[]"), true).to_string(),
2018            "&[Option<String>]"
2019        );
2020        assert_eq!(
2021            ts_type_to_rust_type(Some("(string | null)[]"), false).to_string(),
2022            "Vec<Option<String>>"
2023        );
2024        assert_eq!(
2025            ts_type_to_rust_type(Some("Array<number | null>"), true).to_string(),
2026            "&[Option<f64>]"
2027        );
2028        assert_eq!(
2029            ts_type_to_rust_type(Some("Array<number | null>"), false).to_string(),
2030            "Vec<Option<f64>>"
2031        );
2032    }
2033
2034    #[test]
2035    fn test_nullable_array_itself() {
2036        assert_eq!(
2037            ts_type_to_rust_type(Some("string[] | null"), true).to_string(),
2038            "Option<&[String]>"
2039        );
2040        assert_eq!(
2041            ts_type_to_rust_type(Some("string[] | null"), false).to_string(),
2042            "Option<Vec<String>>"
2043        );
2044        assert_eq!(
2045            ts_type_to_rust_type(Some("Array<number> | null"), true).to_string(),
2046            "Option<&[f64]>"
2047        );
2048        assert_eq!(
2049            ts_type_to_rust_type(Some("Array<number> | null"), false).to_string(),
2050            "Option<Vec<f64>>"
2051        );
2052    }
2053
2054    #[test]
2055    fn test_nullable_array_and_elements() {
2056        assert_eq!(
2057            ts_type_to_rust_type(Some("Array<string | null> | null"), true).to_string(),
2058            "Option<&[Option<String>]>"
2059        );
2060        assert_eq!(
2061            ts_type_to_rust_type(Some("Array<string | null> | null"), false).to_string(),
2062            "Option<Vec<Option<String>>>"
2063        );
2064    }
2065
2066    #[test]
2067    fn test_fallback_for_union() {
2068        assert_eq!(
2069            ts_type_to_rust_type(Some("string | number"), true).to_string(),
2070            "impl dioxus_use_js::SerdeSerialize"
2071        );
2072        assert_eq!(
2073            ts_type_to_rust_type(Some("string | number"), false).to_string(),
2074            "DeserializeOwned"
2075        );
2076        assert_eq!(
2077            ts_type_to_rust_type(Some("string | number | null"), true).to_string(),
2078            "impl dioxus_use_js::SerdeSerialize"
2079        );
2080        assert_eq!(
2081            ts_type_to_rust_type(Some("string | number | null"), false).to_string(),
2082            "DeserializeOwned"
2083        );
2084    }
2085
2086    #[test]
2087    fn test_unknown_types() {
2088        assert_eq!(
2089            ts_type_to_rust_type(Some("foo"), true).to_string(),
2090            "impl dioxus_use_js::SerdeSerialize"
2091        );
2092        assert_eq!(
2093            ts_type_to_rust_type(Some("foo"), false).to_string(),
2094            "DeserializeOwned"
2095        );
2096
2097        assert_eq!(
2098            ts_type_to_rust_type(Some("any"), true).to_string(),
2099            "impl dioxus_use_js::SerdeSerialize"
2100        );
2101        assert_eq!(
2102            ts_type_to_rust_type(Some("any"), false).to_string(),
2103            "DeserializeOwned"
2104        );
2105        assert_eq!(
2106            ts_type_to_rust_type(Some("object"), true).to_string(),
2107            "impl dioxus_use_js::SerdeSerialize"
2108        );
2109        assert_eq!(
2110            ts_type_to_rust_type(Some("object"), false).to_string(),
2111            "DeserializeOwned"
2112        );
2113        assert_eq!(
2114            ts_type_to_rust_type(Some("unknown"), true).to_string(),
2115            "impl dioxus_use_js::SerdeSerialize"
2116        );
2117        assert_eq!(
2118            ts_type_to_rust_type(Some("unknown"), false).to_string(),
2119            "DeserializeOwned"
2120        );
2121
2122        assert_eq!(ts_type_to_rust_type(Some("void"), false).to_string(), "()");
2123        assert_eq!(
2124            ts_type_to_rust_type(Some("undefined"), false).to_string(),
2125            "()"
2126        );
2127        assert_eq!(ts_type_to_rust_type(Some("null"), false).to_string(), "()");
2128    }
2129
2130    #[test]
2131    fn test_extra_whitespace() {
2132        assert_eq!(
2133            ts_type_to_rust_type(Some("  string | null  "), true).to_string(),
2134            "Option<&str>"
2135        );
2136        assert_eq!(
2137            ts_type_to_rust_type(Some("  string | null  "), false).to_string(),
2138            "Option<String>"
2139        );
2140        assert_eq!(
2141            ts_type_to_rust_type(Some(" Array< string > "), true).to_string(),
2142            "&[String]"
2143        );
2144        assert_eq!(
2145            ts_type_to_rust_type(Some(" Array< string > "), false).to_string(),
2146            "Vec<String>"
2147        );
2148    }
2149
2150    #[test]
2151    fn test_map_types() {
2152        assert_eq!(
2153            ts_type_to_rust_type(Some("Map<string, number>"), true).to_string(),
2154            "&std::collections::HashMap<String, f64>"
2155        );
2156        assert_eq!(
2157            ts_type_to_rust_type(Some("Map<string, number>"), false).to_string(),
2158            "std::collections::HashMap<String, f64>"
2159        );
2160        assert_eq!(
2161            ts_type_to_rust_type(Some("Map<string, boolean>"), true).to_string(),
2162            "&std::collections::HashMap<String, bool>"
2163        );
2164        assert_eq!(
2165            ts_type_to_rust_type(Some("Map<string, boolean>"), false).to_string(),
2166            "std::collections::HashMap<String, bool>"
2167        );
2168        assert_eq!(
2169            ts_type_to_rust_type(Some("Map<number, string>"), true).to_string(),
2170            "&std::collections::HashMap<f64, String>"
2171        );
2172        assert_eq!(
2173            ts_type_to_rust_type(Some("Map<number, string>"), false).to_string(),
2174            "std::collections::HashMap<f64, String>"
2175        );
2176    }
2177
2178    #[test]
2179    fn test_set_types() {
2180        assert_eq!(
2181            ts_type_to_rust_type(Some("Set<string>"), true).to_string(),
2182            "&std::collections::HashSet<String>"
2183        );
2184        assert_eq!(
2185            ts_type_to_rust_type(Some("Set<string>"), false).to_string(),
2186            "std::collections::HashSet<String>"
2187        );
2188        assert_eq!(
2189            ts_type_to_rust_type(Some("Set<number>"), true).to_string(),
2190            "&std::collections::HashSet<f64>"
2191        );
2192        assert_eq!(
2193            ts_type_to_rust_type(Some("Set<number>"), false).to_string(),
2194            "std::collections::HashSet<f64>"
2195        );
2196        assert_eq!(
2197            ts_type_to_rust_type(Some("Set<boolean>"), true).to_string(),
2198            "&std::collections::HashSet<bool>"
2199        );
2200        assert_eq!(
2201            ts_type_to_rust_type(Some("Set<boolean>"), false).to_string(),
2202            "std::collections::HashSet<bool>"
2203        );
2204    }
2205
2206    #[test]
2207    fn test_rust_callback() {
2208        assert_eq!(
2209            ts_type_to_rust_type(Some("RustCallback<number,string>"), true).to_string(),
2210            "dioxus::core::Callback<f64, impl Future<Output = Result<String, dioxus_use_js::SerdeJsonValue>> + 'static>"
2211        );
2212        assert_eq!(
2213            ts_type_to_rust_type(Some("RustCallback<void,string>"), true).to_string(),
2214            "dioxus::core::Callback<(), impl Future<Output = Result<String, dioxus_use_js::SerdeJsonValue>> + 'static>"
2215        );
2216        assert_eq!(
2217            ts_type_to_rust_type(Some("RustCallback<void,void>"), true).to_string(),
2218            "dioxus::core::Callback<(), impl Future<Output = Result<(), dioxus_use_js::SerdeJsonValue>> + 'static>"
2219        );
2220        assert_eq!(
2221            ts_type_to_rust_type(Some("RustCallback<number,void>"), true).to_string(),
2222            "dioxus::core::Callback<f64, impl Future<Output = Result<(), dioxus_use_js::SerdeJsonValue>> + 'static>"
2223        );
2224    }
2225
2226    #[test]
2227    fn test_promise_types() {
2228        assert_eq!(
2229            ts_type_to_rust_type(Some("Promise<string>"), false).to_string(),
2230            "String"
2231        );
2232        assert_eq!(
2233            ts_type_to_rust_type(Some("Promise<number>"), false).to_string(),
2234            "f64"
2235        );
2236        assert_eq!(
2237            ts_type_to_rust_type(Some("Promise<boolean>"), false).to_string(),
2238            "bool"
2239        );
2240    }
2241
2242    #[test]
2243    fn test_json_types() {
2244        assert_eq!(
2245            ts_type_to_rust_type(Some("Json"), true).to_string(),
2246            "&dioxus_use_js::SerdeJsonValue"
2247        );
2248        assert_eq!(
2249            ts_type_to_rust_type(Some("Json"), false).to_string(),
2250            "dioxus_use_js::SerdeJsonValue"
2251        );
2252    }
2253
2254    #[test]
2255    fn test_js_value() {
2256        assert_eq!(
2257            ts_type_to_rust_type(Some("JsValue"), true).to_string(),
2258            "&dioxus_use_js::JsValue"
2259        );
2260        assert_eq!(
2261            ts_type_to_rust_type(Some("JsValue"), false).to_string(),
2262            "dioxus_use_js::JsValue"
2263        );
2264        assert_eq!(
2265            ts_type_to_rust_type(Some("JsValue<CustomType>"), true).to_string(),
2266            "&dioxus_use_js::JsValue"
2267        );
2268        assert_eq!(
2269            ts_type_to_rust_type(Some("JsValue<CustomType>"), false).to_string(),
2270            "dioxus_use_js::JsValue"
2271        );
2272
2273        assert_eq!(
2274            ts_type_to_rust_type(Some("Promise<JsValue>"), false).to_string(),
2275            "dioxus_use_js::JsValue"
2276        );
2277
2278        assert_eq!(
2279            ts_type_to_rust_type(Some("Promise<JsValue | null>"), false).to_string(),
2280            "Option<dioxus_use_js::JsValue>"
2281        );
2282        assert_eq!(
2283            ts_type_to_rust_type(Some("JsValue | null"), true).to_string(),
2284            "Option<&dioxus_use_js::JsValue>"
2285        );
2286        assert_eq!(
2287            ts_type_to_rust_type(Some("JsValue | null"), false).to_string(),
2288            "Option<dioxus_use_js::JsValue>"
2289        );
2290    }
2291
2292    #[test]
2293    fn test_class_parsing() {
2294        let ts_content = r#"
2295            /**
2296             * A test class
2297             */
2298            export class MyClass {
2299                constructor(name: string, value: number) {}
2300                
2301                /**
2302                 * Instance method
2303                 */
2304                greet(greeting: string): string {
2305                    return greeting;
2306                }
2307                
2308                /**
2309                 * Async method
2310                 */
2311                async fetchData(url: string): Promise<string> {
2312                    return "data";
2313                }
2314                
2315                /**
2316                 * Static method
2317                 */
2318                static create(): MyClass {
2319                    return new MyClass("test", 0);
2320                }
2321            }
2322        "#;
2323
2324        let source_map = SourceMap::default();
2325        let fm = source_map.new_source_file(
2326            swc_common::FileName::Custom("test.ts".to_string()).into(),
2327            ts_content.to_string(),
2328        );
2329        let comments = SingleThreadedComments::default();
2330
2331        let syntax = Syntax::Typescript(swc_ecma_parser::TsSyntax {
2332            tsx: false,
2333            decorators: false,
2334            dts: false,
2335            no_early_errors: false,
2336            disallow_ambiguous_jsx_like: true,
2337        });
2338
2339        let lexer = Lexer::new(
2340            syntax,
2341            Default::default(),
2342            StringInput::from(&*fm),
2343            Some(&comments),
2344        );
2345
2346        let mut parser = Parser::new_from(lexer);
2347        let module = parser.parse_module().unwrap();
2348
2349        let mut visitor = JsVisitor::new(comments, source_map);
2350        module.visit_with(&mut visitor);
2351
2352        // Dedup classes (as done in parse_script_file)
2353        visitor
2354            .classes
2355            .dedup_by(|e1, e2| e1.name.as_str() == e2.name.as_str());
2356
2357        // Verify we parsed the class
2358        assert_eq!(visitor.classes.len(), 1);
2359        let class = &visitor.classes[0];
2360        assert_eq!(class.name, "MyClass");
2361        assert_eq!(class.is_exported, true);
2362
2363        // Verify methods
2364        assert_eq!(class.methods.len(), 3);
2365
2366        let greet = &class.methods[0];
2367        assert_eq!(greet.name, "greet");
2368        assert_eq!(greet.is_async, false);
2369        assert_eq!(greet.is_static, false);
2370        assert_eq!(greet.params.len(), 1);
2371        assert_eq!(greet.params[0].name, "greeting");
2372        assert_eq!(greet.params[0].rust_type.to_string(), "&str");
2373        assert_eq!(greet.rust_return_type.to_string(), "String");
2374
2375        let fetch_data = &class.methods[1];
2376        assert_eq!(fetch_data.name, "fetchData");
2377        assert_eq!(fetch_data.is_async, true);
2378        assert_eq!(fetch_data.is_static, false);
2379        assert_eq!(fetch_data.params.len(), 1);
2380        assert_eq!(fetch_data.rust_return_type.to_string(), "String");
2381
2382        let create = &class.methods[2];
2383        assert_eq!(create.name, "create");
2384        assert_eq!(create.is_async, false);
2385        assert_eq!(create.is_static, true);
2386        assert_eq!(create.params.len(), 0);
2387        // Note: The return type MyClass would be parsed as JsValue or unknown type
2388    }
2389}