|
| 1 | +# @file helpers.py - Python->JS helpers for PythonMonkey |
| 2 | +# - typeof operator wrapper |
| 3 | +# - new operator wrapper |
| 4 | +# |
| 5 | +# @author Wes Garland, [email protected] |
| 6 | +# @date July 2023 |
| 7 | +# |
| 8 | + |
| 9 | +from . import pythonmonkey as pm |
| 10 | +evalOpts = { 'filename': __file__, 'fromPythonFrame': True } |
| 11 | + |
| 12 | +def typeof(jsval): |
| 13 | + """ |
| 14 | + typeof function - wraps JS typeof operator |
| 15 | + """ |
| 16 | + return pm.eval("""'use strict'; ( |
| 17 | +function pmTypeof(jsval) |
| 18 | +{ |
| 19 | + return typeof jsval; |
| 20 | +} |
| 21 | + )""", evalOpts)(jsval); |
| 22 | + |
| 23 | +def new(ctor): |
| 24 | + """ |
| 25 | + new function - emits function which wraps JS new operator, emitting a lambda which constructs a new |
| 26 | + JS object upon invocation. |
| 27 | + """ |
| 28 | + if (typeof(ctor) == 'string'): |
| 29 | + ctor = pm.eval(ctor) |
| 30 | + |
| 31 | + newCtor = pm.eval("""'use strict'; ( |
| 32 | +function pmNewFactory(ctor) |
| 33 | +{ |
| 34 | + return function newCtor(args) { |
| 35 | + args = Array.from(args || []); |
| 36 | + return new ctor(...args); |
| 37 | + }; |
| 38 | +} |
| 39 | + )""", evalOpts)(ctor) |
| 40 | + return (lambda *args: newCtor(list(args))) |
| 41 | + |
| 42 | +# List which symbols are exposed to the pythonmonkey module. |
| 43 | +__all__ = [ "new", "typeof" ] |
| 44 | + |
| 45 | +# Add the non-enumerable properties of globalThis which don't collide with pythonmonkey.so as exports: |
| 46 | +globalThis = pm.eval('globalThis'); |
| 47 | +pmGlobals = vars(pm) |
| 48 | + |
| 49 | +exports = pm.eval(""" |
| 50 | +Object.getOwnPropertyNames(globalThis) |
| 51 | +.filter(prop => Object.keys(globalThis).indexOf(prop) === -1); |
| 52 | +""", evalOpts) |
| 53 | + |
| 54 | +for index in range(0, int(exports.length)): |
| 55 | + name = exports[index] |
| 56 | + if (pmGlobals.get(name) == None): |
| 57 | + globals().update({name: globalThis[name]}) |
| 58 | + __all__.append(name) |
0 commit comments