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.
@@ -0,0 +1,195 @@
1
+ """Shared ECMAScript value operations for the supported runtime subset."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import inspect
6
+ import math
7
+ import re
8
+ from collections.abc import Mapping
9
+ from decimal import Decimal
10
+
11
+
12
+ class _Undefined:
13
+ __slots__ = ()
14
+ _instance = None
15
+
16
+ def __new__(cls):
17
+ if cls._instance is None:
18
+ cls._instance = super().__new__(cls)
19
+ return cls._instance
20
+
21
+ def __repr__(self) -> str:
22
+ return "undefined"
23
+
24
+ def __bool__(self) -> bool:
25
+ return False
26
+
27
+ def __reduce__(self):
28
+ return (_Undefined, ())
29
+
30
+
31
+ undefined = _Undefined()
32
+ null = None
33
+ NaN = math.nan
34
+ Infinity = math.inf
35
+
36
+ # ECMAScript WhiteSpace and LineTerminator code points, including BOM.
37
+ WHITESPACE = "\u0009\u000b\u000c\u0020\u00a0\u1680\u2000\u2001\u2002\u2003\u2004\u2005\u2006\u2007\u2008\u2009\u200a\u202f\u205f\u3000\ufeff\u000a\u000d\u2028\u2029"
38
+ _DECIMAL = re.compile(r"[+-]?(?:(?:[0-9]+(?:\.[0-9]*)?|\.[0-9]+)(?:[eE][+-]?[0-9]+)?|Infinity)\Z")
39
+
40
+
41
+ def is_number(value) -> bool:
42
+ return isinstance(value, (int, float)) and not isinstance(value, bool)
43
+
44
+
45
+ def truthy(value=undefined) -> bool:
46
+ """echidnae.javascript Boolean conversion; empty containers are true."""
47
+ if value is undefined or value is None or value is False:
48
+ return False
49
+ if is_number(value):
50
+ return value != 0 and not math.isnan(to_number(value))
51
+ if isinstance(value, str):
52
+ return len(value) != 0
53
+ return True
54
+
55
+
56
+ def primitive(value):
57
+ if value is undefined or value is None or isinstance(value, (str, bool, int, float)):
58
+ return value
59
+ method = getattr(type(value), "_js_primitive", None)
60
+ if method is not None:
61
+ result = method(value)
62
+ if result is undefined or result is None or isinstance(result, (str, bool, int, float)):
63
+ return result
64
+ raise TypeError("Cannot convert object to a primitive value")
65
+ if isinstance(value, (list, tuple)):
66
+ return ",".join("" if item is None or item is undefined else to_string(item) for item in value)
67
+ if isinstance(value, Mapping):
68
+ return "[object Object]"
69
+ raise TypeError(f"Unsupported echidnae.javascript value: {type(value).__name__}")
70
+
71
+
72
+ def to_number(value=undefined) -> float:
73
+ value = primitive(value)
74
+ if value is undefined:
75
+ return NaN
76
+ if value is None:
77
+ return 0.0
78
+ if isinstance(value, (bool, int, float)):
79
+ try:
80
+ return float(value)
81
+ except OverflowError:
82
+ return -Infinity if value < 0 else Infinity
83
+ text = value.strip(WHITESPACE)
84
+ if not text:
85
+ return 0.0
86
+ if re.fullmatch(r"0[xX][0-9a-fA-F]+|0[bB][01]+|0[oO][0-7]+", text):
87
+ return to_number(int(text, 0))
88
+ if not _DECIMAL.fullmatch(text):
89
+ return NaN
90
+ return float(text)
91
+
92
+
93
+ def number_string(value) -> str:
94
+ number = to_number(value)
95
+ if math.isnan(number):
96
+ return "NaN"
97
+ if math.isinf(number):
98
+ return "-Infinity" if number < 0 else "Infinity"
99
+ if number == 0:
100
+ return "0"
101
+ text = repr(number)
102
+ if 1e-6 <= abs(number) < 1e21:
103
+ text = format(Decimal(text), "f")
104
+ return text.rstrip("0").rstrip(".") if "." in text else text
105
+ mantissa, exponent = text.split("e")
106
+ exponent = int(exponent)
107
+ return f"{mantissa.removesuffix('.0')}e{'+' if exponent >= 0 else '-'}{abs(exponent)}"
108
+
109
+
110
+ def to_string(value=undefined) -> str:
111
+ value = primitive(value)
112
+ if value is undefined:
113
+ return "undefined"
114
+ if value is None:
115
+ return "null"
116
+ if value is True:
117
+ return "true"
118
+ if value is False:
119
+ return "false"
120
+ if isinstance(value, str):
121
+ return value.encode("utf-16-le", "surrogatepass").decode("utf-16-le", "surrogatepass")
122
+ return number_string(value)
123
+
124
+
125
+ def integer(value=undefined):
126
+ number = to_number(value)
127
+ if math.isnan(number) or number == 0:
128
+ return 0
129
+ return number if math.isinf(number) else math.trunc(number)
130
+
131
+
132
+ def relative_index(value, length: int) -> int:
133
+ index = integer(value)
134
+ if index < 0:
135
+ return max(length + index, 0)
136
+ return min(index, length)
137
+
138
+
139
+ def strictEqual(left, right) -> bool:
140
+ """ECMAScript strict equality for supported values (objects use identity)."""
141
+ if is_number(left) and is_number(right):
142
+ return to_number(left) == to_number(right)
143
+ if isinstance(left, str) and isinstance(right, str):
144
+ return left.encode("utf-16-le", "surrogatepass") == right.encode("utf-16-le", "surrogatepass")
145
+ return left is right
146
+
147
+
148
+ def same_value(left, right) -> bool:
149
+ if is_number(left) and is_number(right):
150
+ a, b = to_number(left), to_number(right)
151
+ if math.isnan(a) and math.isnan(b):
152
+ return True
153
+ if a == b == 0:
154
+ return math.copysign(1, a) == math.copysign(1, b)
155
+ return strictEqual(left, right)
156
+
157
+
158
+ def same_value_zero(left, right) -> bool:
159
+ return strictEqual(left, right) or (is_number(left) and is_number(right) and math.isnan(to_number(left)) and math.isnan(to_number(right)))
160
+
161
+
162
+ def typeof(value=undefined) -> str:
163
+ if value is undefined:
164
+ return "undefined"
165
+ if value is None:
166
+ return "object"
167
+ if isinstance(value, bool):
168
+ return "boolean"
169
+ if is_number(value):
170
+ return "number"
171
+ if isinstance(value, str):
172
+ return "string"
173
+ return "function" if callable(value) else "object"
174
+
175
+
176
+ def isNaN(value=undefined) -> bool:
177
+ return math.isnan(to_number(value))
178
+
179
+
180
+ def isFinite(value=undefined) -> bool:
181
+ return math.isfinite(to_number(value))
182
+
183
+
184
+ def callback(function):
185
+ """Adapt declared positional arity once, without retrying callback errors."""
186
+ if not callable(function):
187
+ raise TypeError("Callback must be callable")
188
+ try:
189
+ parameters = inspect.signature(function).parameters.values()
190
+ except (TypeError, ValueError):
191
+ return function
192
+ if any(p.kind == p.VAR_POSITIONAL for p in parameters):
193
+ return function
194
+ count = sum(p.kind in (p.POSITIONAL_ONLY, p.POSITIONAL_OR_KEYWORD) for p in parameters)
195
+ return lambda *args: function(*args[:count])
@@ -0,0 +1,60 @@
1
+ """Build the explicit compiled browser profile and its local host assets."""
2
+
3
+ import ast
4
+ import hashlib
5
+ from importlib.resources import files
6
+
7
+ from .compiler import CompileError, Diagnostic, SourceSpan
8
+ from .emitter import CompiledArtifact, OutputFile, _json
9
+ from .modules import SourceModule, compile_modules
10
+
11
+
12
+ def compile_browser(sources: tuple[SourceModule, ...], *, entrypoint: str,
13
+ source_map: bool = True, notices: tuple[OutputFile, ...] = ()) -> CompiledArtifact:
14
+ """Compile a verified allowlist with async main(), without executing it."""
15
+ artifact = compile_modules(sources, entrypoint=entrypoint, source_map=source_map,
16
+ async_enabled=True, browser_enabled=True, notices=notices)
17
+ entry = next(source for source in sources if source.name == entrypoint)
18
+ tree = ast.parse(entry.data.decode('utf-8'))
19
+ main = next((node for node in tree.body if isinstance(node, ast.AsyncFunctionDef) and node.name == 'main'), None)
20
+ if main is None or len(main.args.defaults) != len(main.args.posonlyargs) + len(main.args.args):
21
+ raise CompileError(Diagnostic('PJS110', 'Browser entry requires an async main() callable without required arguments.',
22
+ SourceSpan(entry.filename, 1, 1, 1, 1), 'bind'))
23
+ if any(len(source.filename) > 256 for source in sources):
24
+ raise ValueError('Browser source identities must fit the host protocol filename limit of 256.')
25
+ required = set()
26
+ if 'print' in artifact.manifest['helpers']:
27
+ required.add('output/1')
28
+ for source in sources:
29
+ if source.filename not in {record['path'] for record in artifact.manifest['sources']}:
30
+ continue
31
+ for node in ast.walk(ast.parse(source.data.decode('utf-8'))):
32
+ if isinstance(node, ast.ImportFrom) and node.module == 'echidnae.javascript.browser':
33
+ for alias in node.names:
34
+ if alias.name in {'read_text', 'write_text'}:
35
+ required.add('dom-text/1')
36
+ elif alias.name in {'on_click', 'unsubscribe'}:
37
+ required.update({'dom-events/1', 'handles/1'})
38
+ elif alias.name == 'fetch_text':
39
+ required.add('fetch/1')
40
+ output = list(artifact.files)
41
+ names = ['browser-protocol.mjs', 'browser-host.mjs', 'browser-worker.mjs']
42
+ for name in names:
43
+ data = files('echidnae.javascript').joinpath('_browser', name).read_bytes()
44
+ if name == 'browser-worker.mjs':
45
+ marker = b'/*CAPABILITIES*/[]'
46
+ if data.count(marker) != 1:
47
+ raise ValueError('Browser worker template identity mismatch.')
48
+ data = data.replace(marker, _json(sorted(required)).encode())
49
+ output.append(OutputFile(name, data, 'executable-module' if name == 'browser-worker.mjs' else 'compatibility-helper'))
50
+ output = tuple(sorted(output, key=lambda item: item.path))
51
+ manifest = artifact.manifest
52
+ manifest['browser'] = {'protocol': 'pocket-python-host', 'version': 1, 'host': 'browser-host.mjs',
53
+ 'worker': 'browser-worker.mjs', 'entrypoint_export': 'main', 'capabilities': sorted(required)}
54
+ manifest['imports'].extend([{'from': 'browser-host.mjs', 'to': 'browser-protocol.mjs'},
55
+ {'from': 'browser-host.mjs', 'to': 'browser-worker.mjs'},
56
+ {'from': 'browser-worker.mjs', 'to': 'app.mjs'},
57
+ {'from': 'browser-worker.mjs', 'to': 'browser-protocol.mjs'}])
58
+ manifest['imports'].sort(key=lambda item: (item['from'], item['to']))
59
+ manifest['files'] = [{'path': item.path, 'size': len(item.data), 'sha256': hashlib.sha256(item.data).hexdigest(), 'role': item.role} for item in output]
60
+ return CompiledArtifact(output, (_json(manifest) + '\n').encode())