echidnae-javascript 0.3.0__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- echidnae/javascript/__init__.py +27 -0
- echidnae/javascript/_array.py +338 -0
- echidnae/javascript/_browser/browser-host.mjs +165 -0
- echidnae/javascript/_browser/browser-protocol.mjs +111 -0
- echidnae/javascript/_browser/browser-worker.mjs +117 -0
- echidnae/javascript/_compiler_runtime.py +466 -0
- echidnae/javascript/_json.py +114 -0
- echidnae/javascript/_math.py +109 -0
- echidnae/javascript/_number.py +92 -0
- echidnae/javascript/_object.py +184 -0
- echidnae/javascript/_string.py +170 -0
- echidnae/javascript/_values.py +195 -0
- echidnae/javascript/browser.py +60 -0
- echidnae/javascript/compiler.py +473 -0
- echidnae/javascript/emitter.py +300 -0
- echidnae/javascript/modules.py +273 -0
- echidnae/javascript/py.typed +0 -0
- echidnae_javascript-0.3.0.dist-info/METADATA +144 -0
- echidnae_javascript-0.3.0.dist-info/RECORD +21 -0
- echidnae_javascript-0.3.0.dist-info/WHEEL +4 -0
- echidnae_javascript-0.3.0.dist-info/licenses/LICENSE.md +21 -0
|
@@ -0,0 +1,114 @@
|
|
|
1
|
+
"""Adapt the standalone JSON parser to runtime values and serialization rules."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import json as _json
|
|
6
|
+
import math
|
|
7
|
+
from collections.abc import Mapping
|
|
8
|
+
|
|
9
|
+
import echidnae.json as _standalone
|
|
10
|
+
|
|
11
|
+
from ._array import Array
|
|
12
|
+
from ._object import Object, own_entries
|
|
13
|
+
from ._string import String
|
|
14
|
+
from ._values import is_number, number_string, to_number, to_string, undefined
|
|
15
|
+
|
|
16
|
+
|
|
17
|
+
def _runtime(value):
|
|
18
|
+
if isinstance(value, dict):
|
|
19
|
+
return Object({key: _runtime(child) for key, child in dict.items(value)})
|
|
20
|
+
if isinstance(value, list):
|
|
21
|
+
return Array.of(*(_runtime(child) for child in value))
|
|
22
|
+
if isinstance(value, str):
|
|
23
|
+
return String(value)
|
|
24
|
+
return to_number(value) if is_number(value) else value
|
|
25
|
+
|
|
26
|
+
|
|
27
|
+
def _quote(value):
|
|
28
|
+
# Delegate escaping to the companion, preserving normal Unicode while
|
|
29
|
+
# escaping lone surrogates as required by well-formed JSON.stringify.
|
|
30
|
+
value = value.encode("utf-16-le", "surrogatepass").decode("utf-16-le", "surrogatepass")
|
|
31
|
+
quoted = _standalone.stringify(value, ensure_ascii=False)
|
|
32
|
+
return "".join(f"\\u{ord(char):04x}" if 0xD800 <= ord(char) <= 0xDFFF else char for char in quoted)
|
|
33
|
+
|
|
34
|
+
|
|
35
|
+
class _JSON:
|
|
36
|
+
JSONDecodeError = _standalone.JSONDecodeError
|
|
37
|
+
|
|
38
|
+
@staticmethod
|
|
39
|
+
def parse(text):
|
|
40
|
+
"""Parse JSON after echidnae.javascript string conversion; no reviver overload."""
|
|
41
|
+
if isinstance(text, (bytes, bytearray)):
|
|
42
|
+
raise TypeError("echidnae.javascript.JSON.parse expects text, not bytes")
|
|
43
|
+
def reject_constant(value):
|
|
44
|
+
raise ValueError(f"{value} is not a valid JSON numeric constant")
|
|
45
|
+
|
|
46
|
+
# The standalone parser preserves Python integers. Select binary64
|
|
47
|
+
# decoder hooks here so nested -0 and large integers retain JS semantics.
|
|
48
|
+
value = _json.loads(
|
|
49
|
+
to_string(text), parse_int=float, parse_float=float,
|
|
50
|
+
parse_constant=reject_constant,
|
|
51
|
+
)
|
|
52
|
+
return _runtime(value)
|
|
53
|
+
|
|
54
|
+
@staticmethod
|
|
55
|
+
def stringify(value=undefined, replacer=undefined, space=undefined):
|
|
56
|
+
"""Serialize supported values; replacers and toJSON hooks are not supported."""
|
|
57
|
+
if replacer is not undefined and replacer is not None:
|
|
58
|
+
raise NotImplementedError("JSON replacers are not supported")
|
|
59
|
+
if is_number(space):
|
|
60
|
+
number = to_number(space)
|
|
61
|
+
gap = " " * (0 if math.isnan(number) else int(max(0, min(number, 10))))
|
|
62
|
+
elif isinstance(space, str):
|
|
63
|
+
gap = String(space).slice(0, 10).valueOf()
|
|
64
|
+
else:
|
|
65
|
+
gap = ""
|
|
66
|
+
active = set()
|
|
67
|
+
|
|
68
|
+
def encode(child, depth=0):
|
|
69
|
+
if child is undefined or callable(child):
|
|
70
|
+
return undefined
|
|
71
|
+
if child is None:
|
|
72
|
+
return "null"
|
|
73
|
+
if isinstance(child, bool):
|
|
74
|
+
return "true" if child else "false"
|
|
75
|
+
if isinstance(child, str):
|
|
76
|
+
return _quote(child)
|
|
77
|
+
if is_number(child):
|
|
78
|
+
return number_string(child) if math.isfinite(to_number(child)) else "null"
|
|
79
|
+
if not isinstance(child, (Object, Array, Mapping, list, tuple)):
|
|
80
|
+
raise TypeError(f"Unsupported JSON value: {type(child).__name__}")
|
|
81
|
+
if isinstance(child, (Object, Mapping)):
|
|
82
|
+
if any(key == "toJSON" and callable(item) for key, item in own_entries(child)):
|
|
83
|
+
raise NotImplementedError("JSON toJSON hooks are not supported")
|
|
84
|
+
identity = id(child)
|
|
85
|
+
if identity in active:
|
|
86
|
+
raise TypeError("Converting circular structure to JSON")
|
|
87
|
+
active.add(identity)
|
|
88
|
+
try:
|
|
89
|
+
array = isinstance(child, (Array, list, tuple))
|
|
90
|
+
parts = []
|
|
91
|
+
if array:
|
|
92
|
+
for item in child:
|
|
93
|
+
text = encode(item, depth + 1)
|
|
94
|
+
parts.append("null" if text is undefined else text)
|
|
95
|
+
else:
|
|
96
|
+
for key, item in own_entries(child):
|
|
97
|
+
text = encode(item, depth + 1)
|
|
98
|
+
if text is not undefined:
|
|
99
|
+
parts.append(_quote(key) + (": " if gap else ":") + text)
|
|
100
|
+
left, right = ("[", "]") if array else ("{", "}")
|
|
101
|
+
if not parts:
|
|
102
|
+
return left + right
|
|
103
|
+
if not gap:
|
|
104
|
+
return left + ",".join(parts) + right
|
|
105
|
+
prefix = gap * (depth + 1)
|
|
106
|
+
return left + "\n" + prefix + (",\n" + prefix).join(parts) + "\n" + gap * depth + right
|
|
107
|
+
finally:
|
|
108
|
+
active.remove(identity)
|
|
109
|
+
|
|
110
|
+
result = encode(value)
|
|
111
|
+
return result if result is undefined else String(result)
|
|
112
|
+
|
|
113
|
+
|
|
114
|
+
JSON = _JSON()
|
|
@@ -0,0 +1,109 @@
|
|
|
1
|
+
"""Selected Math functions with ECMAScript numeric edge behavior."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import math
|
|
6
|
+
import random
|
|
7
|
+
|
|
8
|
+
from ._values import to_number, undefined
|
|
9
|
+
|
|
10
|
+
|
|
11
|
+
class _Math:
|
|
12
|
+
PI = math.pi
|
|
13
|
+
E = math.e
|
|
14
|
+
LN2 = math.log(2)
|
|
15
|
+
LN10 = math.log(10)
|
|
16
|
+
LOG2E = math.log2(math.e)
|
|
17
|
+
LOG10E = math.log10(math.e)
|
|
18
|
+
SQRT1_2 = math.sqrt(0.5)
|
|
19
|
+
SQRT2 = math.sqrt(2)
|
|
20
|
+
|
|
21
|
+
@staticmethod
|
|
22
|
+
def abs(value=undefined):
|
|
23
|
+
return abs(to_number(value))
|
|
24
|
+
|
|
25
|
+
@staticmethod
|
|
26
|
+
def floor(value=undefined):
|
|
27
|
+
number = to_number(value)
|
|
28
|
+
return float(math.floor(number)) if math.isfinite(number) and number != 0 else number
|
|
29
|
+
|
|
30
|
+
@staticmethod
|
|
31
|
+
def ceil(value=undefined):
|
|
32
|
+
number = to_number(value)
|
|
33
|
+
if not math.isfinite(number) or number == 0:
|
|
34
|
+
return number
|
|
35
|
+
return -0.0 if -1 < number < 0 else float(math.ceil(number))
|
|
36
|
+
|
|
37
|
+
@staticmethod
|
|
38
|
+
def trunc(value=undefined):
|
|
39
|
+
number = to_number(value)
|
|
40
|
+
if not math.isfinite(number) or number == 0:
|
|
41
|
+
return number
|
|
42
|
+
return math.copysign(float(math.trunc(number)), number)
|
|
43
|
+
|
|
44
|
+
@staticmethod
|
|
45
|
+
def round(value=undefined):
|
|
46
|
+
number = to_number(value)
|
|
47
|
+
if not math.isfinite(number) or number == 0:
|
|
48
|
+
return number
|
|
49
|
+
if -0.5 <= number < 0:
|
|
50
|
+
return -0.0
|
|
51
|
+
lower = math.floor(number)
|
|
52
|
+
return float(lower if number - lower < 0.5 else lower + 1)
|
|
53
|
+
|
|
54
|
+
@staticmethod
|
|
55
|
+
def sign(value=undefined):
|
|
56
|
+
number = to_number(value)
|
|
57
|
+
return number if math.isnan(number) or number == 0 else math.copysign(1.0, number)
|
|
58
|
+
|
|
59
|
+
@staticmethod
|
|
60
|
+
def min(*values):
|
|
61
|
+
result = math.inf
|
|
62
|
+
for value in values:
|
|
63
|
+
number = to_number(value)
|
|
64
|
+
if math.isnan(number):
|
|
65
|
+
return math.nan
|
|
66
|
+
if number < result or (number == result == 0 and math.copysign(1, number) < 0):
|
|
67
|
+
result = number
|
|
68
|
+
return result
|
|
69
|
+
|
|
70
|
+
@staticmethod
|
|
71
|
+
def max(*values):
|
|
72
|
+
result = -math.inf
|
|
73
|
+
for value in values:
|
|
74
|
+
number = to_number(value)
|
|
75
|
+
if math.isnan(number):
|
|
76
|
+
return math.nan
|
|
77
|
+
if number > result or (number == result == 0 and math.copysign(1, number) > 0):
|
|
78
|
+
result = number
|
|
79
|
+
return result
|
|
80
|
+
|
|
81
|
+
@staticmethod
|
|
82
|
+
def sqrt(value=undefined):
|
|
83
|
+
number = to_number(value)
|
|
84
|
+
return math.nan if number < 0 else math.sqrt(number)
|
|
85
|
+
|
|
86
|
+
@staticmethod
|
|
87
|
+
def pow(base=undefined, exponent=undefined):
|
|
88
|
+
base, exponent = to_number(base), to_number(exponent)
|
|
89
|
+
if exponent == 0:
|
|
90
|
+
return 1.0
|
|
91
|
+
if math.isnan(exponent):
|
|
92
|
+
return math.nan
|
|
93
|
+
if abs(base) == 1 and math.isinf(exponent):
|
|
94
|
+
return math.nan
|
|
95
|
+
try:
|
|
96
|
+
return math.pow(base, exponent)
|
|
97
|
+
except OverflowError:
|
|
98
|
+
return -math.inf if base < 0 and exponent.is_integer() and exponent % 2 else math.inf
|
|
99
|
+
except ValueError:
|
|
100
|
+
if base == 0 and exponent < 0:
|
|
101
|
+
return -math.inf if math.copysign(1, base) < 0 and exponent.is_integer() and exponent % 2 else math.inf
|
|
102
|
+
return math.nan
|
|
103
|
+
|
|
104
|
+
@staticmethod
|
|
105
|
+
def random():
|
|
106
|
+
return random.random()
|
|
107
|
+
|
|
108
|
+
|
|
109
|
+
Math = _Math()
|
|
@@ -0,0 +1,92 @@
|
|
|
1
|
+
"""Number conversion, predicates and prefix parsing."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import math
|
|
6
|
+
import re
|
|
7
|
+
import sys
|
|
8
|
+
|
|
9
|
+
from ._values import WHITESPACE, is_number, number_string, to_number, to_string, truthy, undefined
|
|
10
|
+
|
|
11
|
+
|
|
12
|
+
class Number(float):
|
|
13
|
+
"""Binary64 conversion with selected echidnae.javascript Number static methods."""
|
|
14
|
+
|
|
15
|
+
EPSILON = 2**-52
|
|
16
|
+
MAX_SAFE_INTEGER = 2**53 - 1
|
|
17
|
+
MIN_SAFE_INTEGER = -(2**53 - 1)
|
|
18
|
+
MAX_VALUE = sys.float_info.max
|
|
19
|
+
MIN_VALUE = float.fromhex("0x0.0000000000001p-1022")
|
|
20
|
+
NaN = math.nan
|
|
21
|
+
POSITIVE_INFINITY = math.inf
|
|
22
|
+
NEGATIVE_INFINITY = -math.inf
|
|
23
|
+
|
|
24
|
+
def __new__(cls, value=0):
|
|
25
|
+
return super().__new__(cls, to_number(value))
|
|
26
|
+
|
|
27
|
+
@staticmethod
|
|
28
|
+
def isNaN(value=undefined):
|
|
29
|
+
return is_number(value) and math.isnan(to_number(value))
|
|
30
|
+
|
|
31
|
+
@staticmethod
|
|
32
|
+
def isFinite(value=undefined):
|
|
33
|
+
return is_number(value) and math.isfinite(to_number(value))
|
|
34
|
+
|
|
35
|
+
@staticmethod
|
|
36
|
+
def isInteger(value=undefined):
|
|
37
|
+
return Number.isFinite(value) and to_number(value).is_integer()
|
|
38
|
+
|
|
39
|
+
@staticmethod
|
|
40
|
+
def isSafeInteger(value=undefined):
|
|
41
|
+
return Number.isInteger(value) and abs(to_number(value)) <= Number.MAX_SAFE_INTEGER
|
|
42
|
+
|
|
43
|
+
def toString(self):
|
|
44
|
+
from ._string import String
|
|
45
|
+
return String(number_string(self))
|
|
46
|
+
|
|
47
|
+
def valueOf(self):
|
|
48
|
+
return float(self)
|
|
49
|
+
|
|
50
|
+
|
|
51
|
+
def Boolean(value=undefined) -> bool:
|
|
52
|
+
return truthy(value)
|
|
53
|
+
|
|
54
|
+
|
|
55
|
+
def parseFloat(value=undefined):
|
|
56
|
+
text = to_string(value).lstrip(WHITESPACE)
|
|
57
|
+
match = re.match(r"[+-]?(?:Infinity|(?:[0-9]+(?:\.[0-9]*)?|\.[0-9]+)(?:[eE][+-]?[0-9]+)?)", text)
|
|
58
|
+
return float(match[0]) if match else math.nan
|
|
59
|
+
|
|
60
|
+
|
|
61
|
+
def parseInt(value=undefined, radix=undefined):
|
|
62
|
+
from ._string import uint32
|
|
63
|
+
text = to_string(value).lstrip(WHITESPACE)
|
|
64
|
+
sign = -1 if text.startswith("-") else 1
|
|
65
|
+
if text.startswith(("-", "+")):
|
|
66
|
+
text = text[1:]
|
|
67
|
+
base = uint32(radix)
|
|
68
|
+
if base >= 2**31:
|
|
69
|
+
base -= 2**32
|
|
70
|
+
if base != 0 and not 2 <= base <= 36:
|
|
71
|
+
return math.nan
|
|
72
|
+
if base in (0, 16) and text.startswith(("0x", "0X")):
|
|
73
|
+
text, base = text[2:], 16
|
|
74
|
+
if base == 0:
|
|
75
|
+
base = 10
|
|
76
|
+
digits = "0123456789abcdefghijklmnopqrstuvwxyz"[:base]
|
|
77
|
+
result = 0
|
|
78
|
+
count = 0
|
|
79
|
+
for char in text:
|
|
80
|
+
if "A" <= char <= "Z":
|
|
81
|
+
char = char.lower()
|
|
82
|
+
if char not in digits:
|
|
83
|
+
break
|
|
84
|
+
result = result * base + digits.index(char)
|
|
85
|
+
count += 1
|
|
86
|
+
if not count:
|
|
87
|
+
return math.nan
|
|
88
|
+
return to_number(result) * sign
|
|
89
|
+
|
|
90
|
+
|
|
91
|
+
Number.parseFloat = staticmethod(parseFloat)
|
|
92
|
+
Number.parseInt = staticmethod(parseInt)
|
|
@@ -0,0 +1,184 @@
|
|
|
1
|
+
"""Own enumerable data properties for the initial Object subset."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from collections.abc import Mapping
|
|
6
|
+
from reprlib import recursive_repr
|
|
7
|
+
|
|
8
|
+
from ._values import same_value, to_string, undefined
|
|
9
|
+
|
|
10
|
+
|
|
11
|
+
def array_index(key: str) -> int | None:
|
|
12
|
+
if key.isascii() and key.isdecimal() and (key == "0" or not key.startswith("0")):
|
|
13
|
+
# Avoid Python's integer-string digit limit on arbitrary property names.
|
|
14
|
+
if len(key) <= 10:
|
|
15
|
+
number = int(key)
|
|
16
|
+
if number < 2**32 - 1:
|
|
17
|
+
return number
|
|
18
|
+
return None
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
def ordered_keys(properties) -> list[str]:
|
|
22
|
+
indices = [key for key in properties if array_index(key) is not None]
|
|
23
|
+
names = [key for key in properties if array_index(key) is None]
|
|
24
|
+
return sorted(indices, key=int) + names
|
|
25
|
+
|
|
26
|
+
|
|
27
|
+
def own_entries(value):
|
|
28
|
+
if value is None or value is undefined:
|
|
29
|
+
raise TypeError("Cannot convert undefined or null to object")
|
|
30
|
+
method = getattr(type(value), "_js_entries", None)
|
|
31
|
+
if method is not None:
|
|
32
|
+
return method(value)
|
|
33
|
+
if isinstance(value, Mapping):
|
|
34
|
+
properties = {to_string(key): value[key] for key in value}
|
|
35
|
+
return [(key, properties[key]) for key in ordered_keys(properties)]
|
|
36
|
+
if isinstance(value, str):
|
|
37
|
+
data = value.encode("utf-16-le", "surrogatepass")
|
|
38
|
+
return [(str(i // 2), data[i:i + 2].decode("utf-16-le", "surrogatepass")) for i in range(0, len(data), 2)]
|
|
39
|
+
if isinstance(value, (int, float, bool)):
|
|
40
|
+
return []
|
|
41
|
+
raise TypeError("Expected Object, Array, mapping or primitive")
|
|
42
|
+
|
|
43
|
+
|
|
44
|
+
class Object:
|
|
45
|
+
"""An identity-based object containing enumerable, writable data properties.
|
|
46
|
+
|
|
47
|
+
Missing properties return undefined. Own keys shadow ordinary attributes;
|
|
48
|
+
use Object.keys(obj) rather than obj.keys() when calling static methods.
|
|
49
|
+
Special Python attributes retain their Python meaning.
|
|
50
|
+
"""
|
|
51
|
+
|
|
52
|
+
__slots__ = ("_properties",)
|
|
53
|
+
|
|
54
|
+
def __new__(cls, value=undefined):
|
|
55
|
+
if isinstance(value, cls):
|
|
56
|
+
return value
|
|
57
|
+
return super().__new__(cls)
|
|
58
|
+
|
|
59
|
+
def __init__(self, value=undefined):
|
|
60
|
+
if value is self:
|
|
61
|
+
return
|
|
62
|
+
if value is not None and value is not undefined and not isinstance(value, Mapping):
|
|
63
|
+
raise TypeError("Object() supports mappings, Object, null or undefined")
|
|
64
|
+
object.__setattr__(self, "_properties", {})
|
|
65
|
+
if value is not None and value is not undefined:
|
|
66
|
+
for key, child in own_entries(value):
|
|
67
|
+
self[key] = child
|
|
68
|
+
|
|
69
|
+
def __getattribute__(self, name):
|
|
70
|
+
if not (name.startswith("__") and name.endswith("__")):
|
|
71
|
+
properties = object.__getattribute__(self, "_properties")
|
|
72
|
+
if name in properties:
|
|
73
|
+
return properties[name]
|
|
74
|
+
return object.__getattribute__(self, name)
|
|
75
|
+
|
|
76
|
+
def __getattr__(self, name):
|
|
77
|
+
if name.startswith("__") and name.endswith("__"):
|
|
78
|
+
raise AttributeError(name)
|
|
79
|
+
return undefined
|
|
80
|
+
|
|
81
|
+
def __setattr__(self, name, value):
|
|
82
|
+
if name.startswith("__") and name.endswith("__"):
|
|
83
|
+
raise AttributeError("Use brackets for special Python names")
|
|
84
|
+
self[name] = value
|
|
85
|
+
|
|
86
|
+
def __delattr__(self, name):
|
|
87
|
+
if name.startswith("__") and name.endswith("__"):
|
|
88
|
+
raise AttributeError("Use brackets for special Python names")
|
|
89
|
+
del self[name]
|
|
90
|
+
|
|
91
|
+
def __getitem__(self, key):
|
|
92
|
+
return object.__getattribute__(self, "_properties").get(to_string(key), undefined)
|
|
93
|
+
|
|
94
|
+
def __setitem__(self, key, value):
|
|
95
|
+
object.__getattribute__(self, "_properties")[to_string(key)] = value
|
|
96
|
+
|
|
97
|
+
def __delitem__(self, key):
|
|
98
|
+
object.__getattribute__(self, "_properties").pop(to_string(key), None)
|
|
99
|
+
|
|
100
|
+
def __contains__(self, key):
|
|
101
|
+
return to_string(key) in object.__getattribute__(self, "_properties")
|
|
102
|
+
|
|
103
|
+
def __iter__(self):
|
|
104
|
+
return iter(ordered_keys(object.__getattribute__(self, "_properties")))
|
|
105
|
+
|
|
106
|
+
def __len__(self):
|
|
107
|
+
return len(object.__getattribute__(self, "_properties"))
|
|
108
|
+
|
|
109
|
+
def __bool__(self):
|
|
110
|
+
return True
|
|
111
|
+
|
|
112
|
+
def __repr__(self):
|
|
113
|
+
return _object_repr(self)
|
|
114
|
+
|
|
115
|
+
def _js_entries(self):
|
|
116
|
+
properties = object.__getattribute__(self, "_properties")
|
|
117
|
+
return [(key, properties[key]) for key in ordered_keys(properties)]
|
|
118
|
+
|
|
119
|
+
def _js_primitive(self):
|
|
120
|
+
return "[object Object]"
|
|
121
|
+
|
|
122
|
+
def toString(self):
|
|
123
|
+
return "[object Object]"
|
|
124
|
+
|
|
125
|
+
@staticmethod
|
|
126
|
+
def keys(value):
|
|
127
|
+
from ._array import Array
|
|
128
|
+
return Array.of(*(key for key, _ in own_entries(value)))
|
|
129
|
+
|
|
130
|
+
@staticmethod
|
|
131
|
+
def values(value):
|
|
132
|
+
from ._array import Array
|
|
133
|
+
return Array.of(*(child for _, child in own_entries(value)))
|
|
134
|
+
|
|
135
|
+
@staticmethod
|
|
136
|
+
def entries(value):
|
|
137
|
+
from ._array import Array
|
|
138
|
+
return Array.of(*(Array.of(key, child) for key, child in own_entries(value)))
|
|
139
|
+
|
|
140
|
+
@staticmethod
|
|
141
|
+
def assign(target, *sources):
|
|
142
|
+
if not isinstance(target, Object):
|
|
143
|
+
raise TypeError("assign target must be an Object")
|
|
144
|
+
for source in sources:
|
|
145
|
+
if source is not None and source is not undefined:
|
|
146
|
+
for key, value in own_entries(source):
|
|
147
|
+
target[key] = value
|
|
148
|
+
return target
|
|
149
|
+
|
|
150
|
+
@staticmethod
|
|
151
|
+
def fromEntries(entries):
|
|
152
|
+
from ._array import Array
|
|
153
|
+
result = Object()
|
|
154
|
+
for entry in entries:
|
|
155
|
+
if isinstance(entry, (Object, Array)):
|
|
156
|
+
key, value = entry[0], entry[1]
|
|
157
|
+
elif isinstance(entry, Mapping):
|
|
158
|
+
properties = dict(own_entries(entry))
|
|
159
|
+
key, value = properties.get("0", undefined), properties.get("1", undefined)
|
|
160
|
+
elif isinstance(entry, (list, tuple)):
|
|
161
|
+
key = entry[0] if entry else undefined
|
|
162
|
+
value = entry[1] if len(entry) > 1 else undefined
|
|
163
|
+
else:
|
|
164
|
+
raise TypeError("Iterator entry must be an object") from None
|
|
165
|
+
result[key] = value
|
|
166
|
+
return result
|
|
167
|
+
|
|
168
|
+
@staticmethod
|
|
169
|
+
def hasOwn(value, key):
|
|
170
|
+
if value is None or value is undefined:
|
|
171
|
+
raise TypeError("Cannot convert undefined or null to object")
|
|
172
|
+
if isinstance(value, str) and to_string(key) == "length":
|
|
173
|
+
return True
|
|
174
|
+
method = getattr(type(value), "_js_has_own", None)
|
|
175
|
+
if method is not None:
|
|
176
|
+
return method(value, to_string(key))
|
|
177
|
+
return to_string(key) in {name for name, _ in own_entries(value)}
|
|
178
|
+
|
|
179
|
+
is_ = staticmethod(same_value)
|
|
180
|
+
|
|
181
|
+
|
|
182
|
+
@recursive_repr("Object({...})")
|
|
183
|
+
def _object_repr(value):
|
|
184
|
+
return f"Object({object.__getattribute__(value, '_properties')!r})"
|
|
@@ -0,0 +1,170 @@
|
|
|
1
|
+
"""Selected String methods using echidnae.javascript UTF-16 code-unit indexing."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import math
|
|
6
|
+
|
|
7
|
+
from ._array import Array
|
|
8
|
+
from ._values import WHITESPACE, integer, relative_index, to_number, to_string, undefined
|
|
9
|
+
|
|
10
|
+
|
|
11
|
+
def units(value: str) -> str:
|
|
12
|
+
data = value.encode("utf-16-le", "surrogatepass")
|
|
13
|
+
return "".join(chr(int.from_bytes(data[i:i + 2], "little")) for i in range(0, len(data), 2))
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
def from_units(value: str) -> str:
|
|
17
|
+
return value.encode("utf-16-le", "surrogatepass").decode("utf-16-le", "surrogatepass")
|
|
18
|
+
|
|
19
|
+
|
|
20
|
+
def uint32(value):
|
|
21
|
+
number = to_number(value)
|
|
22
|
+
return math.trunc(number) % 2**32 if math.isfinite(number) and number else 0
|
|
23
|
+
|
|
24
|
+
|
|
25
|
+
def clamp(value, length):
|
|
26
|
+
return max(0, min(integer(value), length))
|
|
27
|
+
|
|
28
|
+
|
|
29
|
+
class String(str):
|
|
30
|
+
"""A Python string exposing selected camelCase echidnae.javascript String methods.
|
|
31
|
+
|
|
32
|
+
echidnae.javascript methods and bracket access use UTF-16 code units. Python's
|
|
33
|
+
inherited operators and methods otherwise retain their Python behavior.
|
|
34
|
+
"""
|
|
35
|
+
|
|
36
|
+
def __new__(cls, value=""):
|
|
37
|
+
return super().__new__(cls, to_string(value))
|
|
38
|
+
|
|
39
|
+
@property
|
|
40
|
+
def length(self):
|
|
41
|
+
return len(self.encode("utf-16-le", "surrogatepass")) // 2
|
|
42
|
+
|
|
43
|
+
def __getitem__(self, key):
|
|
44
|
+
key = to_string(key)
|
|
45
|
+
if key == "length":
|
|
46
|
+
return self.length
|
|
47
|
+
if not key.isascii() or not key.isdecimal() or (len(key) > 1 and key.startswith("0")) or len(key) > 10:
|
|
48
|
+
return undefined
|
|
49
|
+
return self.at(int(key))
|
|
50
|
+
|
|
51
|
+
def __iter__(self):
|
|
52
|
+
return iter(from_units(units(self)))
|
|
53
|
+
|
|
54
|
+
def at(self, index=undefined):
|
|
55
|
+
index = integer(index)
|
|
56
|
+
data = units(self)
|
|
57
|
+
if index < 0:
|
|
58
|
+
index += len(data)
|
|
59
|
+
return String(data[index]) if 0 <= index < len(data) else undefined
|
|
60
|
+
|
|
61
|
+
def charAt(self, index=undefined):
|
|
62
|
+
index = integer(index)
|
|
63
|
+
data = units(self)
|
|
64
|
+
return String(data[index]) if 0 <= index < len(data) else String()
|
|
65
|
+
|
|
66
|
+
def charCodeAt(self, index=undefined):
|
|
67
|
+
value = self.charAt(index)
|
|
68
|
+
return ord(value) if value else math.nan
|
|
69
|
+
|
|
70
|
+
def codePointAt(self, index=undefined):
|
|
71
|
+
index = integer(index)
|
|
72
|
+
data = units(self)
|
|
73
|
+
if not 0 <= index < len(data):
|
|
74
|
+
return undefined
|
|
75
|
+
first = ord(data[index])
|
|
76
|
+
if 0xD800 <= first <= 0xDBFF and index + 1 < len(data):
|
|
77
|
+
second = ord(data[index + 1])
|
|
78
|
+
if 0xDC00 <= second <= 0xDFFF:
|
|
79
|
+
return (first - 0xD800) * 0x400 + second - 0xDC00 + 0x10000
|
|
80
|
+
return first
|
|
81
|
+
|
|
82
|
+
def slice(self, start=0, end=undefined):
|
|
83
|
+
data = units(self)
|
|
84
|
+
start = relative_index(start, len(data))
|
|
85
|
+
end = len(data) if end is undefined else relative_index(end, len(data))
|
|
86
|
+
return String(from_units(data[start:end]))
|
|
87
|
+
|
|
88
|
+
def substring(self, start=0, end=undefined):
|
|
89
|
+
data = units(self)
|
|
90
|
+
start = clamp(start, len(data))
|
|
91
|
+
end = len(data) if end is undefined else clamp(end, len(data))
|
|
92
|
+
start, end = min(start, end), max(start, end)
|
|
93
|
+
return String(from_units(data[start:end]))
|
|
94
|
+
|
|
95
|
+
def indexOf(self, searchString=undefined, position=0):
|
|
96
|
+
data = units(self)
|
|
97
|
+
return data.find(units(to_string(searchString)), clamp(position, len(data)))
|
|
98
|
+
|
|
99
|
+
def lastIndexOf(self, searchString=undefined, position=undefined):
|
|
100
|
+
data, search = units(self), units(to_string(searchString))
|
|
101
|
+
number = to_number(position)
|
|
102
|
+
start = len(data) if math.isnan(number) else clamp(number, len(data))
|
|
103
|
+
return data.rfind(search, 0, min(start + len(search), len(data)))
|
|
104
|
+
|
|
105
|
+
def includes(self, searchString=undefined, position=0):
|
|
106
|
+
return self.indexOf(searchString, position) >= 0
|
|
107
|
+
|
|
108
|
+
def startsWith(self, searchString=undefined, position=0):
|
|
109
|
+
data = units(self)
|
|
110
|
+
return data.startswith(units(to_string(searchString)), clamp(position, len(data)))
|
|
111
|
+
|
|
112
|
+
def endsWith(self, searchString=undefined, endPosition=undefined):
|
|
113
|
+
data = units(self)
|
|
114
|
+
end = len(data) if endPosition is undefined else clamp(endPosition, len(data))
|
|
115
|
+
return data[:end].endswith(units(to_string(searchString)))
|
|
116
|
+
|
|
117
|
+
def split(self, separator=undefined, limit=undefined):
|
|
118
|
+
count = 2**32 - 1 if limit is undefined else uint32(limit)
|
|
119
|
+
if count == 0:
|
|
120
|
+
return Array()
|
|
121
|
+
if separator is undefined:
|
|
122
|
+
return Array.of(String(self))
|
|
123
|
+
data, separator = units(self), units(to_string(separator))
|
|
124
|
+
if separator == "":
|
|
125
|
+
return Array.of(*(String(char) for char in data[:count]))
|
|
126
|
+
return Array.of(*(String(from_units(part)) for part in data.split(separator, count)[:count]))
|
|
127
|
+
|
|
128
|
+
def concat(self, *values):
|
|
129
|
+
return String(str(self) + "".join(to_string(value) for value in values))
|
|
130
|
+
|
|
131
|
+
def repeat(self, count=0):
|
|
132
|
+
count = integer(count)
|
|
133
|
+
if count < 0 or math.isinf(count):
|
|
134
|
+
raise ValueError("Invalid repeat count")
|
|
135
|
+
return String(str(self) * count)
|
|
136
|
+
|
|
137
|
+
def trim(self):
|
|
138
|
+
return String(str(self).strip(WHITESPACE))
|
|
139
|
+
|
|
140
|
+
def trimStart(self):
|
|
141
|
+
return String(str(self).lstrip(WHITESPACE))
|
|
142
|
+
|
|
143
|
+
def trimEnd(self):
|
|
144
|
+
return String(str(self).rstrip(WHITESPACE))
|
|
145
|
+
|
|
146
|
+
def toLowerCase(self):
|
|
147
|
+
return String(str(self).lower())
|
|
148
|
+
|
|
149
|
+
def toUpperCase(self):
|
|
150
|
+
return String(str(self).upper())
|
|
151
|
+
|
|
152
|
+
def toString(self):
|
|
153
|
+
return self
|
|
154
|
+
|
|
155
|
+
def valueOf(self):
|
|
156
|
+
return str(self)
|
|
157
|
+
|
|
158
|
+
@staticmethod
|
|
159
|
+
def fromCharCode(*codes):
|
|
160
|
+
return String(from_units("".join(chr(uint32(code) % 2**16) for code in codes)))
|
|
161
|
+
|
|
162
|
+
@staticmethod
|
|
163
|
+
def fromCodePoint(*codes):
|
|
164
|
+
values = []
|
|
165
|
+
for code in codes:
|
|
166
|
+
number = to_number(code)
|
|
167
|
+
if not math.isfinite(number) or number != int(number) or not 0 <= number <= 0x10FFFF:
|
|
168
|
+
raise ValueError("Invalid code point")
|
|
169
|
+
values.append(chr(int(number)))
|
|
170
|
+
return String("".join(values))
|