nicktaras / client-side-crypto-js-for-ios

0 stars 0 forks source link

Running with JavaScriptCore in Swift #1

Open hboon opened 3 years ago

hboon commented 3 years ago

Hi Nick,

I've run it with this bit of code:

let context = JSContext()!
let jsLib = try! String(contentsOf: URL(string: "file:///Users/hboon/p/alphawallet/client-side-crypto-js-for-ios/node/output.js")!)
_ = context.evaluateScript(jsLib)
context.evaluateScript("var morseMessage = new Morse.MorseMessage()")
NSLog("""
      xxx out: \(context.evaluateScript("morseMessage.translate('abc')"))
      """)

with the output:

xxx out: Optional(undefined)

If it's easier, you can try that in main.swift to get the same result (but we should do a final test while embedded in the app, just to be sure):

import JavaScriptCore

let context = JSContext()!
let jsLib = try! String(contentsOf: URL(string: "file:///Users/hboon/p/alphawallet/client-side-crypto-js-for-ios/node/output.js")!)
_ = context.evaluateScript(jsLib)
context.evaluateScript("var morseMessage = new Morse.MorseMessage()")
NSLog("""
xxx out: \(context.evaluateScript("morseMessage.translate('abc')"))
""")

(remember the modify the absolute path to output.js)

hboon commented 3 years ago

Just wanted to show a variation of the snippet I posted above to illustrate the issue:

import JavaScriptCore

let context = JSContext()!

//let jsLib = try! String(contentsOf: URL(string: "file:///Users/hboon/p/alphawallet/client-side-crypto-js-for-ios/node/output.js")!)
let jsLib = """
            function foo(i) {
               return `this should work + ${i * 3}`
            }
            """

_ = context.evaluateScript(jsLib)

//context.evaluateScript("var morseMessage = new Morse.MorseMessage()")
//NSLog("""
//let v = context.evaluateScript("morseMessage.translate('abc')")
//""")

let v = context.evaluateScript("foo(4)")

NSLog("""
      xxx out: \(v)
      """)

The output is (with warnings removed):

xxx out: Optional(this should work + 12)

In other words, output.js should be produced in such a way that it can be called like in the line foo(4).

hboon commented 3 years ago

Another example:

import JavaScriptCore

let context = JSContext()!

let jsLib = try! String(contentsOf: URL(string: "file:///Users/hboon/p/alphawallet/client-side-crypto-js-for-ios/node/output.js")!)
_ = context.evaluateScript(jsLib)

let v1 = context.evaluateScript("""
                               JSON.stringify(CryptoJS.HmacSHA1("Message", "Key"))
                               """)

let v2 = context.evaluateScript("""
                               JSON.stringify(1)
                               """)

NSLog("""
      xxx out: \(String(describing: v1))
      """)

NSLog("""
      xxx out: \(String(describing: v2))
      """)

Which prints:

2021-04-22 00:18:03.135 swift[80890:21850452] xxx out: Optional(undefined) 2021-04-22 00:18:03.135 swift[80890:21850452] xxx out: Optional(1)