@@ -30,6 +30,7 @@ namespace js2c {
3030int Main (int argc, char * argv[]);
3131
3232static bool is_verbose = false ;
33+ static std::string output_transpiled_dir;
3334
3435void Debug (const char * format, ...) {
3536 va_list arguments;
@@ -327,6 +328,25 @@ int WriteIfChanged(const Fragment& out, const std::string& dest) {
327328 return WriteFileSync (out, dest.c_str ());
328329}
329330
331+ int MkdirpSync (const std::string& path) {
332+ uv_fs_t req;
333+ int r = uv_fs_mkdir (nullptr , &req, path.c_str (), 0755 , nullptr );
334+ uv_fs_req_cleanup (&req);
335+ if (r == 0 || r == UV_EEXIST) return 0 ;
336+ if (r == UV_ENOENT) {
337+ // Parent doesn't exist, create it first.
338+ size_t pos = path.find_last_of (' /' );
339+ if (pos == std::string::npos || pos == 0 ) return r;
340+ int pr = MkdirpSync (path.substr (0 , pos));
341+ if (pr != 0 ) return pr;
342+ r = uv_fs_mkdir (nullptr , &req, path.c_str (), 0755 , nullptr );
343+ uv_fs_req_cleanup (&req);
344+ if (r == UV_EEXIST) return 0 ;
345+ return r;
346+ }
347+ return r;
348+ }
349+
330350std::string GetFileId (const std::string& filename) {
331351 size_t end = filename.size ();
332352 size_t start = 0 ;
@@ -705,6 +725,26 @@ int AddModule(const std::string& filename,
705725 }
706726 code.assign (result.code , result.code + result.code_len );
707727 swc_transform_free_result (&result);
728+
729+ if (!output_transpiled_dir.empty ()) {
730+ // Write transpiled output as .js for debuggability.
731+ std::string out_path = output_transpiled_dir + " /" +
732+ filename.substr (0 , filename.size () - kTsSuffix .size ()) + " .js" ;
733+ size_t last_slash = out_path.find_last_of (' /' );
734+ if (last_slash != std::string::npos) {
735+ int mr = MkdirpSync (out_path.substr (0 , last_slash));
736+ if (mr != 0 ) {
737+ PrintUvError (" mkdir" , out_path.c_str (), mr);
738+ return mr;
739+ }
740+ }
741+ int wr = WriteFileSync (code, out_path.c_str ());
742+ if (wr != 0 ) {
743+ PrintUvError (" write" , out_path.c_str (), wr);
744+ return wr;
745+ }
746+ Debug (" Wrote transpiled output to %s\n " , out_path.c_str ());
747+ }
708748 }
709749
710750 std::string file_id = GetFileId (filename);
@@ -891,6 +931,7 @@ int JS2C(const FileList& js_files,
891931int PrintUsage (const char * argv0) {
892932 fprintf (stderr,
893933 " Usage: %s [--verbose] [--root /path/to/project/root] "
934+ " [--output-transpiled-ts path/to/dir] "
894935 " path/to/output.cc path/to/directory "
895936 " [extra-files ...]\n " ,
896937 argv0);
@@ -915,6 +956,12 @@ int Main(int argc, char* argv[]) {
915956 return 1 ;
916957 }
917958 root_dir = argv[++i];
959+ } else if (arg == " --output-transpiled-ts" ) {
960+ if (i == argc - 1 ) {
961+ fprintf (stderr, " --output-transpiled-ts must be followed by a path\n " );
962+ return 1 ;
963+ }
964+ output_transpiled_dir = argv[++i];
918965 } else {
919966 args.emplace_back (argv[i]);
920967 }
0 commit comments