@@ -4,6 +4,8 @@ import { isEmpty } from "lodash";
4
4
import { Editor } from "../../support/editor" ;
5
5
import { Kommand } from "../../common" ;
6
6
import { kuzzleFlags } from "../../support/kuzzle" ;
7
+ import { exec } from "child_process" ;
8
+ import fs from "fs" ;
7
9
8
10
class SdkExecute extends Kommand {
9
11
public static description = `
@@ -69,33 +71,70 @@ Other
69
71
70
72
static readStdin = true ;
71
73
74
+ async toJavascript ( filename : string ) : Promise < boolean > {
75
+ return new Promise ( ( resolve , reject ) => {
76
+ exec (
77
+ `npx tsc -t es5 ${ filename } ` ,
78
+ ( ) => {
79
+ // We do not care for TS errors, user should now if this will work or not
80
+ resolve ( true ) ;
81
+ } ) ;
82
+ } ) ;
83
+ }
84
+
72
85
async beforeConnect ( ) {
73
86
this . code = this . stdin || this . args . code || "// paste your code here" ;
87
+ try {
88
+ eval ( this . code ) ;
89
+ } catch ( e ) {
90
+ if ( e instanceof SyntaxError ) {
91
+ const tsFile = "kourou-sdk-execute-tmp.ts" ;
92
+ const jsFile = "kourou-sdk-execute-tmp.js" ;
93
+
94
+ // Write to file, transpile it and read it back
95
+ fs . writeFileSync ( tsFile , this . code ) ;
96
+ await this . toJavascript ( tsFile ) ;
97
+ const file = fs . readFileSync ( jsFile , "utf8" ) ;
98
+ this . code = file ;
99
+
100
+ // Clean up
101
+ fs . unlinkSync ( tsFile ) ;
102
+ fs . unlinkSync ( jsFile ) ;
103
+ }
104
+ }
105
+
106
+ console . log ( this . code ) ;
74
107
75
108
if ( this . haveSubscription ) {
76
109
this . sdkOptions . protocol = "ws" ;
77
110
}
78
111
}
79
112
113
+ getVariables ( ) {
114
+ return ( this . flags . var || [ ] )
115
+ . map ( ( nameValue : string ) => {
116
+ const [ name , value ] = nameValue . split ( "=" ) ;
117
+
118
+ return ` let ${ name } = ${ value } ;` ;
119
+ } )
120
+ . join ( "\n" ) ;
121
+
122
+
123
+ }
124
+
80
125
async runSafe ( ) {
81
126
if ( isEmpty ( this . code ) ) {
82
127
throw new Error ( "No code provided." ) ;
83
128
}
84
129
85
130
let userError : Error | null = null ;
86
131
87
- const variables = ( this . flags . var || [ ] )
88
- . map ( ( nameValue : string ) => {
89
- const [ name , value ] = nameValue . split ( "=" ) ;
90
132
91
- return ` let ${ name } = ${ value } ;` ;
92
- } )
93
- . join ( "\n" ) ;
94
133
95
134
this . code = `
96
135
(async () => {
97
136
try {
98
- ${ variables }
137
+ ${ this . getVariables ( ) }
99
138
${ this . code }
100
139
}
101
140
catch (error) {
@@ -137,7 +176,7 @@ ${variables}
137
176
this . logInfo ( "Keep alive for realtime notifications ..." ) ;
138
177
139
178
// eslint-disable-next-line @typescript-eslint/no-empty-function
140
- await new Promise ( ( ) => { } ) ;
179
+ await new Promise ( ( ) => { } ) ;
141
180
}
142
181
}
143
182
0 commit comments