11use std:: io:: Cursor ;
2+ use std:: path:: { Path , PathBuf } ;
23use tracing:: instrument;
34
5+ use crate :: UsubaError ;
6+
47use super :: Bake ;
58use async_trait:: async_trait;
69use bytes:: Bytes ;
710use tempfile:: TempDir ;
811
912use tokio:: process:: Command ;
13+ use tokio:: task:: JoinSet ;
14+
15+ use wit_parser:: UnresolvedPackage ;
16+
17+ async fn write_file ( path : PathBuf , bytes : Bytes ) -> Result < ( ) , UsubaError > {
18+ let mut file = tokio:: fs:: File :: create ( & path) . await ?;
19+ let mut cursor = Cursor :: new ( bytes. as_ref ( ) ) ;
20+ tokio:: io:: copy ( & mut cursor, & mut file) . await ?;
21+ Ok ( ( ) )
22+ }
1023
1124#[ derive( Debug ) ]
1225pub struct JavaScriptBaker { }
1326
1427#[ async_trait]
1528impl Bake for JavaScriptBaker {
1629 #[ instrument]
17- async fn bake ( & self , wit : Bytes , source_code : Bytes ) -> Result < Bytes , crate :: UsubaError > {
30+ async fn bake (
31+ & self ,
32+ world : & str ,
33+ wit : Vec < Bytes > ,
34+ source_code : Bytes ,
35+ ) -> Result < Bytes , crate :: UsubaError > {
1836 let workspace = TempDir :: new ( ) ?;
1937 debug ! (
2038 "Created temporary workspace in {}" ,
@@ -23,31 +41,32 @@ impl Bake for JavaScriptBaker {
2341
2442 let wasm_path = workspace. path ( ) . join ( "module.wasm" ) ;
2543 let js_path = workspace. path ( ) . join ( "module.js" ) ;
26- let wit_path = workspace. path ( ) . join ( "module.wit" ) ;
2744
28- let ( mut wit_file, mut js_file) = tokio:: try_join!(
29- tokio:: fs:: File :: create( & wit_path) ,
30- tokio:: fs:: File :: create( & js_path) ,
31- ) ?;
45+ debug ! ( ?workspace, "Created temporary workspace" ) ;
3246
33- debug ! ( ?wit_path , ?js_path , "Created temporary input files" ) ;
47+ let mut writes = JoinSet :: new ( ) ;
3448
35- let mut wit_cursor = Cursor :: new ( wit) ;
36- let mut js_cursor = Cursor :: new ( source_code) ;
49+ wit. into_iter ( )
50+ . enumerate ( )
51+ . map ( |( i, wit) | write_file ( workspace. path ( ) . join ( format ! ( "module{}.wit" , i) ) , wit) )
52+ . chain ( [ write_file ( js_path. clone ( ) , source_code) ] )
53+ . for_each ( |fut| {
54+ writes. spawn ( fut) ;
55+ } ) ;
3756
38- tokio :: try_join! (
39- tokio :: io :: copy ( & mut wit_cursor , & mut wit_file ) ,
40- tokio :: io :: copy ( & mut js_cursor , & mut js_file ) ,
41- ) ? ;
57+ while let Some ( result ) = writes . try_join_next ( ) {
58+ result?? ;
59+ continue ;
60+ }
4261
43- debug ! ( ?wit_path , ?js_path , "Populated temporary input files" ) ;
62+ debug ! ( ?workspace , "Populated temporary input files" ) ;
4463
4564 let mut command = Command :: new ( "jco" ) ;
4665
4766 command
4867 . arg ( "componentize" )
4968 . arg ( "-w" )
50- . arg ( wit_path . display ( ) . to_string ( ) )
69+ . arg ( workspace . path ( ) )
5170 . arg ( "-o" )
5271 . arg ( wasm_path. display ( ) . to_string ( ) )
5372 . arg ( js_path. display ( ) . to_string ( ) ) ;
0 commit comments