@@ -8,9 +8,9 @@ import app.cash.quickjs.QuickJs
88import app.cash.quickjs.QuickJsException
99import kotlinx.serialization.SerializationException
1010import kotlinx.serialization.json.Json
11- import kotlinx.serialization.json.encodeToJsonElement
11+ import kotlinx.serialization.json.JsonObject
1212
13- actual class JavaScriptEngine actual constructor(){
13+ actual class JavaScriptEngine actual constructor() {
1414 private val quickJs: QuickJs = QuickJs .create()
1515 private val json: Json = Json .Default
1616
@@ -27,7 +27,7 @@ actual class JavaScriptEngine actual constructor(){
2727 return try {
2828 internalEvaluate(context, script)
2929 } catch (exception: QuickJsException ) {
30- throw JavaScriptEvaluationException (exception)
30+ throw JavaScriptEvaluationException (exception, exception.message )
3131 }
3232 }
3333
@@ -41,22 +41,33 @@ actual class JavaScriptEngine actual constructor(){
4141 context : Map <String , JsType >,
4242 script : String
4343 ): JsType {
44- context.forEach { pair ->
45- quickJs.set(pair.key, pair.value.javaClass, pair.value)
46- }
47- val result = quickJs.evaluate(script)
44+ val scriptWithContext = convertContextMapToJsScript(context) + script
45+ val result = quickJs.evaluate(scriptWithContext)
4846 return handleQuickJsResult(result)
4947 }
5048
49+ private fun convertContextMapToJsScript (context : Map <String , JsType >): String {
50+ if (context.isEmpty()) return " "
51+
52+ return context.mapNotNull { pair ->
53+ pair.value.value?.let { " var ${pair.key} = $it ;" }
54+ }.joinToString(separator = " " )
55+ }
56+
5157 private fun handleQuickJsResult (result : Any? ): JsType {
52- return when (result) {
58+ return when {
5359 result == null -> JsType .Null
54- is Boolean -> JsType .Bool (result)
55- is Int -> JsType .IntNum (result)
56- is Double -> JsType .DoubleNum (result)
57- is Float -> JsType .DoubleNum (result.toDouble())
58- is String -> try {
59- JsType .Json (json.encodeToJsonElement(result))
60+ result is Boolean -> JsType .Bool (result)
61+ result is Int -> JsType .IntNum (result)
62+ result is Double -> JsType .DoubleNum (result)
63+ result is Float -> JsType .DoubleNum (result.toDouble())
64+ result is String -> try {
65+ val serializeResult = json.parseToJsonElement(result)
66+ if (serializeResult is JsonObject ) {
67+ JsType .Json (serializeResult)
68+ } else {
69+ JsType .Str (result)
70+ }
6071 } catch (ex: SerializationException ) {
6172 JsType .Str (result)
6273 }
0 commit comments