def run_js_fct(script, required=None): """ Assuming *script* contains some :epkg:`javascript` which produces :epkg:`SVG`. This functions runs the code. @param script :epkg:`javascript` @param required required libraries (does not guaranteed to work) @return :epkg:`python` function The module relies on :epkg:`js2py` and :epkg:`node.js`. Dependencies must be installed with :epkg:`npm`:. :: npm install babel-core babel-cli babel-preset-es2015 babel-polyfill babelify browserify babel-preset-env Function @see fn install_node_js_modules can be run with admin right for that. :epkg:`js2py` tries to convert a dependency into :epkg:`Python` """ from js2py import eval_js, require, node_import # To skip npm installation. node_import.DID_INIT = True if required: if not isinstance(required, list): required = [required] for r in required: require(r) fct = eval_js(script) return fct
def get_script_from_tree(tree): # 需要依赖安装 node 以及 npm 的环境 # 用以下载 escodegen.js 的文件,只会下载一次。 # 下载过后就会自动被js2py转成py代码,放在 js2py.py_node_modules 中。 # 以下是解决 win10 上面下载时可能会出现的 bug, # 有时 powershell 才可以执行 有时 command 才可以执行,这么丑的写法,我也很绝望。 try: escodegen = js2py.require('escodegen') except: import subprocess def _call(*a, **k): _a = list(a) _a[0] = 'powershell ' + a[0] return _call_bak(*a, **k) if _call_bak(*_a, **k) != 0 else 0 _call_bak = subprocess.call subprocess.call = _call escodegen = js2py.require('escodegen') return escodegen.generate(tree)
def bato_get_links(name: str, chapter: int, r) -> List[str]: text = r.text line: str = re.findall(BATO_LINK_DEF, text)[0] urls: List[str] = [] for match in re.finditer(BATO_LINK, line): url: str = match.groupdict()["url"] urls.append(url) batojs = js2py.eval_js(re.findall(BATO_BATO, text)[0]) JSON = js2py.eval_js('JSON') CryptoJS = js2py.require("crypto-js", True) server: str = re.findall(BATO_SERVER, text)[0] result: str = JSON.parse( CryptoJS.AES.decrypt(server, batojs).toString(CryptoJS.enc.Utf8)) return [result + url for url in urls]
def translate_code(code, target_language): syntax_tree = (js2py.require("esprima").parseScript( code, { "comment": True }).to_dict()) import pdb pdb.set_trace() id_list, str_lit_list = set([]), set([]) get_translatables(syntax_tree, id_list, str_lit_list) comment_list = get_comments(syntax_tree) src_target_map = get_target(id_list, str_lit_list, comment_list, target_language) translated_code = src_to_target(code, src_target_map) return translated_code
def demo(): esprima = js2py.require("esprima") with open("./data/sample.js", "r") as fin: js_code = fin.read() js_ast_origin = esprima.parse(js_code).to_dict() js_ast_modified = ConvertJsAst(js_ast_origin) print(json.dumps(js_ast_origin, indent=4)) print("-" * 128) print(json.dumps(js_ast_modified, indent=4)) print("-" * 128) DFS_traverse(js_ast_modified)
context.execute('foo.bar /= 2') assert context.foo.bar == 11.11 assert pyobj.bar == 11.11 context.execute('foo.set_bar(foo.get_bar())') assert context.foo.get_bar() == 11.11 context.execute('foo.set_bar(33)') assert context.foo.get_bar() == 33 assert context.eval('foo.bar_history.push(foo.bar_history[1].get_bar());foo.bar_history[foo.bar_history.length-1].get_bar()') == 11.11 print("Passed ECMA 5 simple tests!\n"+30*'-') print('Now harder tests - test on huge JS libraries:') # crypto-js ( https://www.npmjs.com/package/crypto-js ) print('Testing crypto-js') CryptoJS = js2py.require('crypto-js') data = [{'id': 1}, {'id': 2}] JSON = js2py.eval_js('JSON') ciphertext = CryptoJS.AES.encrypt(JSON.stringify(data), 'secret key 123') bytes = CryptoJS.AES.decrypt(ciphertext.toString(), 'secret key 123') decryptedData = JSON.parse(bytes.toString(CryptoJS.enc.Utf8)).to_list() assert decryptedData == data AES = js2py.require('crypto-js/aes') ciphertext = AES.encrypt(JSON.stringify(data), 'secret key 123') bytes = AES.decrypt(ciphertext.toString(), 'secret key 123') decryptedData = JSON.parse(bytes.toString(CryptoJS.enc.Utf8)).to_list() assert decryptedData == data # esprima ( https://www.npmjs.com/package/esprima )
# You can import any compatible node module, similar to npm install module & require(module) in node from js2py import require # This will automatically install and translate everything. Subsequent requires are fast because translation is cached. random_int = require('random-int') # https://www.npmjs.com/package/random-int print(random_int) print(random_int(10, 40))
assert pyobj.bar == 11.11 context.execute('foo.set_bar(foo.get_bar())') assert context.foo.get_bar() == 11.11 context.execute('foo.set_bar(33)') assert context.foo.get_bar() == 33 assert context.eval( 'foo.bar_history.push(foo.bar_history[1].get_bar());foo.bar_history[foo.bar_history.length-1].get_bar()' ) == 11.11 print("Passed ECMA 5 simple tests!\n" + 30 * '-') print('Now harder tests - test on huge JS libraries:') # crypto-js ( https://www.npmjs.com/package/crypto-js ) print('Testing crypto-js') CryptoJS = js2py.require('crypto-js') data = [{'id': 1}, {'id': 2}] JSON = js2py.eval_js('JSON') ciphertext = CryptoJS.AES.encrypt(JSON.stringify(data), 'secret key 123') bytes = CryptoJS.AES.decrypt(ciphertext.toString(), 'secret key 123') decryptedData = JSON.parse(bytes.toString(CryptoJS.enc.Utf8)).to_list() assert decryptedData == data AES = js2py.require('crypto-js/aes') ciphertext = AES.encrypt(JSON.stringify(data), 'secret key 123') bytes = AES.decrypt(ciphertext.toString(), 'secret key 123') decryptedData = JSON.parse(bytes.toString(CryptoJS.enc.Utf8)).to_list() assert decryptedData == data # esprima ( https://www.npmjs.com/package/esprima ) # escodegen ( https://github.com/estools/escodegen )
import js2py CryptoJS = js2py.require('crypto-js') JSON = js2py.eval_js('JSON') key = "MYeo8OZvaQR2vqn4" class Hasher: def encrypt(self, string): return CryptoJS.AES.encrypt(JSON.stringify(string), key) def decrypt(self, string): bytes = CryptoJS.AES.decrypt(string, key) decryptedString = bytes.toString(CryptoJS.enc.Utf8) return decryptedString def compareStrings(self, string1, string2): if self.decrypt(string1) == self.decrypt(string2): return True return False
from pprint import pprint import js2py Gun = js2py.require('gun') def handle_get(data, key): print(data.baz) def main(): # Grab reference to Gun #Gun = js2py.eval_js('Gun') # Init Gun & connect to our superPeer gun = Gun('http://localhost:8089/gun') # Get a reference to a node to work with baz = gun.get('baz') # Hopefully put some data to the graph baz.put({ 'foo': 'bar' }) # With luck we will get it back gun.get('baz').on(handle_get) if __name__ == "__main__": main()
def cubic_to_quad(*args, maximum_allowed_distance=1): global _cubic_to_quad if _cubic_to_quad is None: import js2py _cubic_to_quad = js2py.require('cubic2quad') return _cubic_to_quad(*args, maximum_allowed_distance)
import requests import json import re from foss_finder.config import strings, config semver = None if config.USE_SEMVER: try: import js2py # parser for npm versions semver = js2py.require('semver') except Exception as e: print(e) class NpmPackageParser(object): @classmethod def get_package_info(cls, name, version_spec, depth, npm_sections, use_semver=False): # regex to check if the package is scoped (URL is different) scope_regex = r"(?P<scope>@([.a-zA-Z0-9_-]|\[|\])+)/(?P<module>([.a-zA-Z0-9_-]|\[|\])+)$" parts = re.match(scope_regex, name) if parts: scope = parts.group('scope') module = parts.group('module')
import js2py from js2py import require res, jsfile = js2py.run_file('example.js') print(jsfile.fibonacci_series(8)) random_int = require('random-int') print(random_int) print(random_int(10, 40))