binding_macros 60.0.0

Macros to build customized bindings interface
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
use std::sync::Arc;

#[doc(hidden)]
pub use anyhow;
use anyhow::Error;
#[doc(hidden)]
pub use js_sys;
use once_cell::sync::Lazy;
#[doc(hidden)]
pub use serde_wasm_bindgen;
use serde_wasm_bindgen::Serializer;
#[doc(hidden)]
pub use swc::PrintArgs;
use swc::{config::ErrorFormat, Compiler, HandlerOpts};
#[doc(hidden)]
pub use swc::{
    config::{Options, ParseOptions, SourceMapsConfig},
    try_with_handler,
};
#[doc(hidden)]
pub use swc_common::{
    comments::{self, SingleThreadedComments},
    errors::Handler,
    FileName, Mark, GLOBALS,
};
use swc_common::{sync::Lrc, FilePathMapping, SourceMap};
#[doc(hidden)]
pub use swc_ecma_ast::noop_pass;
#[doc(hidden)]
pub use swc_ecma_ast::{EsVersion, Program};
#[doc(hidden)]
pub use swc_ecma_transforms::resolver;
#[doc(hidden)]
pub use swc_ecma_visit::VisitMutWith;
#[doc(hidden)]
pub use wasm_bindgen::{JsCast, JsValue};
#[doc(hidden)]
pub use wasm_bindgen_futures::future_to_promise;

// A serializer with options to provide backward compat for the input / output
// from the bindgen generated swc interfaces.
#[doc(hidden)]
pub fn compat_serializer() -> Arc<Serializer> {
    static V: Lazy<Arc<Serializer>> = Lazy::new(|| {
        let s = Serializer::new()
            .serialize_maps_as_objects(true)
            .serialize_missing_as_null(true);
        Arc::new(s)
    });

    V.clone()
}

#[doc(hidden)]
pub fn try_with_handler_globals<F, Ret>(
    cm: Lrc<SourceMap>,
    config: HandlerOpts,
    op: F,
) -> Result<Ret, Error>
where
    F: FnOnce(&Handler) -> Result<Ret, Error>,
{
    GLOBALS
        .set(&Default::default(), || {
            swc::try_with_handler(cm, config, op)
        })
        .map_err(|e| e.to_pretty_error())
}

/// Get global sourcemap
pub fn compiler() -> Arc<Compiler> {
    console_error_panic_hook::set_once();

    static C: Lazy<Arc<Compiler>> = Lazy::new(|| {
        let cm = Arc::new(SourceMap::new(FilePathMapping::empty()));

        Arc::new(Compiler::new(cm))
    });

    C.clone()
}

#[doc(hidden)]
pub fn convert_err(
    err: Error,
    error_format: Option<ErrorFormat>,
) -> wasm_bindgen::prelude::JsValue {
    error_format
        .unwrap_or(ErrorFormat::Normal)
        .format(&err)
        .into()
}

#[macro_export]
macro_rules! build_minify_sync {
  ($(#[$m:meta])*) => {
    build_minify_sync!($(#[$m])*, Default::default());
  };
  ($(#[$m:meta])*, $opt: expr) => {
    $(#[$m])*
    pub fn minify_sync(s: $crate::wasm::js_sys::JsString, opts: $crate::wasm::JsValue) -> Result<$crate::wasm::JsValue, $crate::wasm::JsValue> {
      use serde::Serialize;

      let c = $crate::wasm::compiler();

      $crate::wasm::try_with_handler_globals(
          c.cm.clone(),
          $opt,
          |handler| {
              c.run(|| {
                  let opts = if opts.is_null() || opts.is_undefined() {
                      Default::default()
                  } else {
                    $crate::wasm::serde_wasm_bindgen::from_value(opts)
                      .map_err(|e| $crate::wasm::anyhow::anyhow!("failed to parse options: {}", e))?
                  };

                  let fm = c.cm.new_source_file($crate::wasm::FileName::Anon.into(), String::from(s));
                  let program = $crate::wasm::anyhow::Context::context(c.minify(fm, handler, &opts, Default::default()), "failed to minify file")?;

                  program
                    .serialize($crate::wasm::compat_serializer().as_ref())
                    .map_err(|e| $crate::wasm::anyhow::anyhow!("failed to serialize program: {}", e))
              })
          },
      )
      .map_err(|e| $crate::wasm::convert_err(e, None))
    }
  };
}

/// Currently this relies on existence of minify_sync.
#[macro_export]
macro_rules! build_minify {
  ($(#[$m:meta])*) => {
    build_minify!($(#[$m])*, Default::default());
  };
  ($(#[$m:meta])*, $opt: expr) => {
      $(#[$m])*
      pub fn minify(s: $crate::wasm::js_sys::JsString, opts: $crate::wasm::JsValue) -> $crate::wasm::js_sys::Promise {
          // TODO: This'll be properly scheduled once wasm have standard backed thread
          // support.
          $crate::wasm::future_to_promise(async { minify_sync(s, opts) })
      }
  };
}

#[macro_export]
macro_rules! build_parse_sync {
  ($(#[$m:meta])*) => {
    build_parse_sync!($(#[$m])*, Default::default());
  };
  ($(#[$m:meta])*, $opt: expr) => {
    $(#[$m])*
    pub fn parse_sync(s: $crate::wasm::js_sys::JsString, opts: $crate::wasm::JsValue) -> Result<$crate::wasm::JsValue, $crate::wasm::JsValue> {
      use serde::Serialize;
      use $crate::wasm::VisitMutWith;
      use $crate::wasm::PrintArgs;

      let c = $crate::wasm::compiler();

      $crate::wasm::try_with_handler_globals(
          c.cm.clone(),
          $opt,
          |handler| {
              c.run(|| {
                  let opts: $crate::wasm::ParseOptions = if opts.is_null() || opts.is_undefined() {
                      Default::default()
                  } else {
                      $crate::wasm::serde_wasm_bindgen::from_value(opts)
                        .map_err(|e| $crate::wasm::anyhow::anyhow!("failed to parse options: {}", e))?
                  };

                  let fm = c.cm.new_source_file($crate::wasm::FileName::Anon.into(), String::from(s));

                  let cmts = c.comments().clone();
                  let comments = if opts.comments {
                      Some(&cmts as &dyn $crate::wasm::comments::Comments)
                  } else {
                      None
                  };

                  let mut program = $crate::wasm::anyhow::Context::context(
                    c.parse_js(
                          fm,
                          handler,
                          opts.target,
                          opts.syntax,
                          opts.is_module,
                          comments,
                      ),
                      "failed to parse code"
                  )?;

                  program.visit_mut_with(&mut $crate::wasm::resolver(
                    $crate::wasm::Mark::new(),
                    $crate::wasm::Mark::new(),
                    opts.syntax.typescript(),
                  ));

                  program
                    .serialize($crate::wasm::compat_serializer().as_ref())
                    .map_err(|e| $crate::wasm::anyhow::anyhow!("failed to serialize program: {}", e))
              })
          },
      )
      .map_err(|e| $crate::wasm::convert_err(e, None))
    }
  };
}

/// Currently this relies on existence of parse_sync.
#[macro_export]
macro_rules! build_parse {
  ($(#[$m:meta])*) => {
    build_parse!($(#[$m])*, Default::default());
  };
  ($(#[$m:meta])*, $opt: expr) => {
      $(#[$m])*
      pub fn parse(s: $crate::wasm::js_sys::JsString, opts: $crate::wasm::JsValue) -> $crate::wasm::js_sys::Promise {
          // TODO: This'll be properly scheduled once wasm have standard backed thread
          // support.
          $crate::wasm::future_to_promise(async { parse_sync(s, opts) })
      }
  };
}

#[macro_export]
macro_rules! build_print_sync {
  ($(#[$m:meta])*) => {
    build_print_sync!($(#[$m])*, Default::default());
  };
  ($(#[$m:meta])*, $opt: expr) => {
    $(#[$m])*
    pub fn print_sync(s: $crate::wasm::JsValue, opts: $crate::wasm::JsValue) -> Result<$crate::wasm::JsValue, $crate::wasm::JsValue> {
      use $crate::wasm::PrintArgs;

      let c = $crate::wasm::compiler();

      $crate::wasm::try_with_handler_globals(
          c.cm.clone(),
          $opt,
          |_handler| {
              c.run(|| {
                  let opts: $crate::wasm::Options = if opts.is_null() || opts.is_undefined() {
                      Default::default()
                  } else {
                    $crate::wasm::serde_wasm_bindgen::from_value(opts)
                      .map_err(|e| $crate::wasm::anyhow::anyhow!("failed to parse options: {}", e))?
                  };

                  let program: $crate::wasm::Program = $crate::wasm::serde_wasm_bindgen::from_value(s)
                    .map_err(|e| $crate::wasm::anyhow::anyhow!("failed to deserialize program: {}", e))?;
                  let s = $crate::wasm::anyhow::Context::context(c
                    .print(
                        &program,
                        PrintArgs {
                          inline_sources_content: true,
                          source_map: opts.source_maps
                              .clone()
                              .unwrap_or($crate::wasm::SourceMapsConfig::Bool(false)),
                          emit_source_map_columns: opts.config.emit_source_map_columns.into_bool(),
                          codegen_config: swc_core::ecma::codegen::Config::default()
                              .with_target(opts.codegen_target().unwrap_or($crate::wasm::EsVersion::Es2020))
                              .with_minify(opts.config.minify.into()),
                          ..Default::default()
                        },
                    ),"failed to print code")?;

                    serde_wasm_bindgen::to_value(&s)
                    .map_err(|e| anyhow::anyhow!("failed to serialize json: {}", e))
              })
          },
      )
      .map_err(|e| $crate::wasm::convert_err(e, None))
    }
  };
}

/// Currently this relies on existence of print_sync.
#[macro_export]
macro_rules! build_print {
  ($(#[$m:meta])*) => {
    build_print!($(#[$m])*, Default::default());
  };
  ($(#[$m:meta])*, $opt: expr) => {

      $(#[$m])*
      pub fn print(s: $crate::wasm::JsValue, opts: $crate::wasm::JsValue) -> $crate::wasm::js_sys::Promise {
        // TODO: This'll be properly scheduled once wasm have standard backed thread
        // support.
        $crate::wasm::future_to_promise(async { print_sync(s, opts) })
      }
  };
}

#[macro_export]
macro_rules! build_transform_sync {
  ($(#[$m:meta])*) => {
    build_transform_sync!($(#[$m])*, |_| $crate::wasm::noop_pass(), |_| $crate::wasm::noop_pass(), Default::default());
  };
  ($(#[$m:meta])*, $before_pass: expr, $after_pass: expr) => {
    build_transform_sync!($(#[$m])*, $before_pass, $after_pass, Default::default());
  };
  ($(#[$m:meta])*, $before_pass: expr, $after_pass: expr, $opt: expr) => {
    $(#[$m])*
    #[allow(unused_variables)]
    pub fn transform_sync(
        s: $crate::wasm::JsValue,
        opts: $crate::wasm::JsValue,
        experimental_plugin_bytes_resolver: $crate::wasm::JsValue,
    ) -> Result<$crate::wasm::JsValue, $crate::wasm::JsValue> {
        use serde::Serialize;

        let c = $crate::wasm::compiler();

        //[TODO]: refer binding_core_wasm/Cargo.toml,
        //disables via renaming feature to arbitary name
        #[cfg(feature = "__plugin")]
        {
            if experimental_plugin_bytes_resolver.is_object() {
                use $crate::wasm::js_sys::{Array, Object, Uint8Array};

                // TODO: This is probably very inefficient, including each transform
                // deserializes plugin bytes.
                let plugin_bytes_resolver_object: Object = experimental_plugin_bytes_resolver
                    .try_into()
                    .expect("Resolver should be a js object");

                swc_core::plugin_runner::cache::init_plugin_module_cache_once();

                let entries = Object::entries(&plugin_bytes_resolver_object);
                for entry in entries.iter() {
                    let entry: Array = entry
                        .try_into()
                        .expect("Resolver object missing either key or value");
                    let name: String = entry
                        .get(0)
                        .as_string()
                        .expect("Resolver key should be a string");
                    let buffer = entry.get(1);

                    //https://github.com/rustwasm/wasm-bindgen/issues/2017#issue-573013044
                    //We may use https://github.com/cloudflare/serde-wasm-bindgen instead later
                    let data = if $crate::wasm::JsCast::is_instance_of::<Uint8Array>(&buffer) {
                        JsValue::from(Array::from(&buffer))
                    } else {
                        buffer
                    };

                    let bytes: Vec<u8> = $crate::wasm::serde_wasm_bindgen::from_value(data).expect("Could not read byte from plugin resolver");

                    // In here we 'inject' externally loaded bytes into the cache, so
                    // remaining plugin_runner execution path works as much as
                    // similar between embedded runtime.
                    swc_core::plugin_runner::cache::PLUGIN_MODULE_CACHE.store_once(&name, bytes);
                }
            }
        }

        let opts: $crate::wasm::Options = if opts.is_null() || opts.is_undefined() {
            Default::default()
        } else {
          $crate::wasm::serde_wasm_bindgen::from_value(opts)?
        };

        let error_format = opts.experimental.error_format.unwrap_or_default();
        $crate::wasm::try_with_handler_globals(
            c.cm.clone(),
            $opt,
            |handler| {
                c.run(|| {
                  let s = $crate::wasm::JsCast::dyn_into::<$crate::wasm::js_sys::JsString>(s);
                  let out = match s {
                      Ok(s) => {
                          let fm = c.cm.new_source_file(
                              if opts.filename.is_empty() {
                                $crate::wasm::FileName::Anon.into()
                              } else {
                                $crate::wasm::FileName::Real(opts.filename.clone().into()).into()
                              },
                              String::from(s),
                          );
                          let cm = c.cm.clone();
                          let file = fm.clone();
                          let comments = $crate::wasm::SingleThreadedComments::default();
                          $crate::wasm::anyhow::Context::context(
                            c.process_js_with_custom_pass(
                              fm,
                              None,
                              handler,
                              &opts,
                              comments,
                              $before_pass,
                              $after_pass,
                          ), "failed to process js file"
                          )?
                      }
                      Err(v) => unsafe { c.process_js(handler, $crate::wasm::serde_wasm_bindgen::from_value(v).expect(""), &opts)? },
                  };

                  out
                    .serialize($crate::wasm::compat_serializer().as_ref())
                    .map_err(|e| $crate::wasm::anyhow::anyhow!("failed to serialize transform result: {}", e))
              })
            },
        )
        .map_err(|e| $crate::wasm::convert_err(e, Some(error_format)))
    }
  };
}

/// Currently this relies on existence of transform_sync.
#[macro_export]
macro_rules! build_transform {
  ($(#[$m:meta])*) => {
    build_transform!($(#[$m])*, Default::default());
  };
  ($(#[$m:meta])*, $opt: expr) => {
      $(#[$m])*
      pub fn transform(
        s: $crate::wasm::JsValue,
        opts: $crate::wasm::JsValue,
        experimental_plugin_bytes_resolver: $crate::wasm::JsValue,
      ) -> $crate::wasm::js_sys::Promise {
          // TODO: This'll be properly scheduled once wasm have standard backed thread
          // support.
          $crate::wasm::future_to_promise(async { transform_sync(s, opts, experimental_plugin_bytes_resolver) })
      }
  };
}