echidnae-python 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/python/__init__.py +3 -0
- echidnae/python/__main__.py +3 -0
- echidnae/python/_compiler_lock.py +23 -0
- echidnae/python/_interpreter_lock.py +130 -0
- echidnae/python/_library_lock.py +3 -0
- echidnae/python/assets.py +149 -0
- echidnae/python/bundles.py +81 -0
- echidnae/python/cli.py +79 -0
- echidnae/python/compiled.py +236 -0
- echidnae/python/compiled_templates.py +82 -0
- echidnae/python/interpreter.py +238 -0
- echidnae/python/interpreter_templates.py +119 -0
- echidnae/python/py.typed +0 -0
- echidnae/python/templates.py +140 -0
- echidnae/python/web.py +134 -0
- echidnae_python-0.3.0.dist-info/METADATA +32 -0
- echidnae_python-0.3.0.dist-info/RECORD +20 -0
- echidnae_python-0.3.0.dist-info/WHEEL +4 -0
- echidnae_python-0.3.0.dist-info/entry_points.txt +3 -0
- echidnae_python-0.3.0.dist-info/licenses/LICENSE +21 -0
|
@@ -0,0 +1,236 @@
|
|
|
1
|
+
"""Assemble known compiler output from an explicit verified client source allowlist."""
|
|
2
|
+
|
|
3
|
+
from dataclasses import dataclass
|
|
4
|
+
import hashlib
|
|
5
|
+
import html
|
|
6
|
+
import ipaddress
|
|
7
|
+
from importlib import metadata, util
|
|
8
|
+
import json
|
|
9
|
+
from pathlib import Path
|
|
10
|
+
import re
|
|
11
|
+
from urllib.parse import unquote, urlparse
|
|
12
|
+
|
|
13
|
+
from echidnae.python import __version__
|
|
14
|
+
from echidnae.python._compiler_lock import COMPILER_FILES, COMPILER_FINGERPRINT, COMPILER_REVISION, COMPILER_VERSION
|
|
15
|
+
from echidnae.python.assets import ArtifactError, check_names, file_record, json_bytes, read_asset
|
|
16
|
+
from echidnae.python.compiled_templates import APP, PAGE, SERVICE_WORKER
|
|
17
|
+
from echidnae.python.templates import ICON
|
|
18
|
+
from echidnae.python.web import _publish
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
def _json(data):
|
|
22
|
+
def pairs(items):
|
|
23
|
+
result = {}
|
|
24
|
+
for key, value in items:
|
|
25
|
+
if key in result:
|
|
26
|
+
raise ArtifactError('Duplicate JSON field: ' + key)
|
|
27
|
+
result[key] = value
|
|
28
|
+
return result
|
|
29
|
+
try:
|
|
30
|
+
value = json.loads(data, object_pairs_hook=pairs)
|
|
31
|
+
except (ValueError, UnicodeError) as error:
|
|
32
|
+
raise ArtifactError('Invalid compiled input JSON.') from error
|
|
33
|
+
if not isinstance(value, dict):
|
|
34
|
+
raise ArtifactError('Expected a compiled input object.')
|
|
35
|
+
return value
|
|
36
|
+
|
|
37
|
+
|
|
38
|
+
@dataclass(frozen=True)
|
|
39
|
+
class ClientSources:
|
|
40
|
+
root: Path
|
|
41
|
+
manifest_bytes: bytes
|
|
42
|
+
files: tuple[tuple[str, bytes], ...]
|
|
43
|
+
|
|
44
|
+
|
|
45
|
+
@dataclass(frozen=True)
|
|
46
|
+
class CompilerOutput:
|
|
47
|
+
root: Path
|
|
48
|
+
manifest_bytes: bytes
|
|
49
|
+
files: tuple[tuple[str, bytes], ...]
|
|
50
|
+
|
|
51
|
+
|
|
52
|
+
def _client_manifest(data):
|
|
53
|
+
manifest = _json(data)
|
|
54
|
+
if set(manifest) != {'kind', 'schema_version', 'target', 'entrypoint', 'source_map', 'sources', 'notices', 'fetch_urls'} or manifest['kind'] != 'pocket-python-client' or type(manifest['schema_version']) is not int or manifest['schema_version'] != 1 or manifest['target'] != 'client':
|
|
55
|
+
raise ArtifactError('Expected an explicit schema-1 client-source allowlist.')
|
|
56
|
+
if not isinstance(manifest['entrypoint'], str) or type(manifest['source_map']) is not bool:
|
|
57
|
+
raise ArtifactError('Client entrypoint and source-map policy are required.')
|
|
58
|
+
sources, notices = manifest['sources'], manifest['notices']
|
|
59
|
+
if not isinstance(sources, list) or not 1 <= len(sources) <= 32 or not isinstance(notices, list) or len(notices) > 32:
|
|
60
|
+
raise ArtifactError('Declare 1–32 client sources and at most 32 notices.')
|
|
61
|
+
for record, source in [(item, True) for item in sources] + [(item, False) for item in notices]:
|
|
62
|
+
fields = {'path', 'sha256', 'size_bytes', 'role'} | ({'module', 'is_package'} if source else set())
|
|
63
|
+
if not isinstance(record, dict) or set(record) != fields or record['role'] != ('client-source' if source else 'notice'):
|
|
64
|
+
raise ArtifactError('Only explicit client-source and notice records are accepted.')
|
|
65
|
+
if not isinstance(record['path'], str) or not isinstance(record['sha256'], str) or not re.fullmatch('[0-9a-f]{64}', record['sha256']) or type(record['size_bytes']) is not int or not 0 <= record['size_bytes'] <= 1_048_576:
|
|
66
|
+
raise ArtifactError('Invalid client file hash, path or bounded size.')
|
|
67
|
+
if source and (not record['path'].endswith('.py') or not isinstance(record['module'], str) or type(record['is_package']) is not bool):
|
|
68
|
+
raise ArtifactError('Client sources require Python paths and explicit module identities.')
|
|
69
|
+
if not source and (not record['path'].startswith('LICENSES/') or record['size_bytes'] == 0):
|
|
70
|
+
raise ArtifactError('Notices must be nonempty files under LICENSES/.')
|
|
71
|
+
check_names(record['path'] for record in sources + notices)
|
|
72
|
+
if sum(record['size_bytes'] for record in sources + notices) > 8_388_608:
|
|
73
|
+
raise ArtifactError('Client input exceeds 8 MiB.')
|
|
74
|
+
urls = manifest['fetch_urls']
|
|
75
|
+
if not isinstance(urls, list) or len(urls) > 32 or any(not isinstance(url, str) or len(url) > 8192 for url in urls) or len(set(urls)) != len(urls):
|
|
76
|
+
raise ArtifactError('Fetch grants require at most 32 unique explicit URLs.')
|
|
77
|
+
for url in urls:
|
|
78
|
+
parsed = urlparse(url)
|
|
79
|
+
try:
|
|
80
|
+
port = parsed.port
|
|
81
|
+
if (not url.isascii() or not re.fullmatch(r'https?://[a-z0-9.-]+(?::[1-9][0-9]{0,4})?/[^\s\\#<>"`{}|^]*', url)
|
|
82
|
+
or parsed.geturl() != url or port == (80 if parsed.scheme == 'http' else 443)
|
|
83
|
+
or chr(39) in url or any(part in {'.', '..'} for part in unquote(parsed.path).split('/'))
|
|
84
|
+
or (port is not None and not 1 <= port <= 65535)
|
|
85
|
+
or re.search(r'%(?![0-9A-Fa-f]{2})', url)):
|
|
86
|
+
raise ValueError
|
|
87
|
+
if re.fullmatch(r'(?:[0-9]+|0x[0-9a-f]+)', parsed.hostname.rsplit('.', 1)[-1]):
|
|
88
|
+
if str(ipaddress.IPv4Address(parsed.hostname)) != parsed.hostname:
|
|
89
|
+
raise ValueError
|
|
90
|
+
except ValueError as error:
|
|
91
|
+
raise ArtifactError('Fetch grants require canonical ASCII HTTP(S) URLs with an explicit / path, hostname or IPv4 address, and no credentials/fragments/default port.') from error
|
|
92
|
+
return manifest
|
|
93
|
+
|
|
94
|
+
|
|
95
|
+
def _snapshot(client):
|
|
96
|
+
if not isinstance(client, ClientSources) or type(client.manifest_bytes) is not bytes or not isinstance(client.files, tuple):
|
|
97
|
+
raise ArtifactError('Expected an immutable client-source snapshot.')
|
|
98
|
+
manifest = _client_manifest(client.manifest_bytes)
|
|
99
|
+
files = dict(client.files)
|
|
100
|
+
records = manifest['sources'] + manifest['notices']
|
|
101
|
+
if len(files) != len(client.files) or set(files) != {record['path'] for record in records}:
|
|
102
|
+
raise ArtifactError('Client snapshot file set changed.')
|
|
103
|
+
for record in records:
|
|
104
|
+
content = files[record['path']]
|
|
105
|
+
if type(content) is not bytes or file_record(record['path'], content) != {key: record[key] for key in ['path', 'sha256', 'size_bytes']}:
|
|
106
|
+
raise ArtifactError('Client snapshot hash/size changed.')
|
|
107
|
+
if record['role'] == 'notice' and not content.strip():
|
|
108
|
+
raise ArtifactError('Client notice is empty.')
|
|
109
|
+
return manifest, files
|
|
110
|
+
|
|
111
|
+
|
|
112
|
+
def read_client(manifest_path: str | Path) -> ClientSources:
|
|
113
|
+
path = Path(manifest_path).absolute()
|
|
114
|
+
data = read_asset(path.parent, path.name, max_bytes=1_048_576)
|
|
115
|
+
manifest = _client_manifest(data)
|
|
116
|
+
files = tuple((record['path'], read_asset(path.parent, record['path'], max_bytes=record['size_bytes'])) for record in manifest['sources'] + manifest['notices'])
|
|
117
|
+
client = ClientSources(path.parent, data, files)
|
|
118
|
+
_snapshot(client)
|
|
119
|
+
return client
|
|
120
|
+
|
|
121
|
+
|
|
122
|
+
def _compiler():
|
|
123
|
+
spec = util.find_spec('echidnae.javascript')
|
|
124
|
+
if spec is None or not spec.submodule_search_locations:
|
|
125
|
+
raise ArtifactError('The compiled profile requires the pinned compiled-build tooling; no compiler is installed automatically.')
|
|
126
|
+
root = Path(next(iter(spec.submodule_search_locations)))
|
|
127
|
+
digest = hashlib.sha256()
|
|
128
|
+
try:
|
|
129
|
+
for name in COMPILER_FILES:
|
|
130
|
+
for data in [name.encode(), read_asset(root, name, max_bytes=1_048_576).replace(b'\r\n', b'\n')]:
|
|
131
|
+
digest.update(len(data).to_bytes(8, 'big'))
|
|
132
|
+
digest.update(data)
|
|
133
|
+
if digest.hexdigest() != COMPILER_FINGERPRINT or metadata.version('echidnae-javascript') != COMPILER_VERSION:
|
|
134
|
+
raise ArtifactError('Compiler source differs from the supported pinned build.')
|
|
135
|
+
from echidnae.javascript.browser import compile_browser
|
|
136
|
+
from echidnae.javascript.emitter import OutputFile
|
|
137
|
+
from echidnae.javascript.modules import SourceModule
|
|
138
|
+
except (ImportError, OSError, metadata.PackageNotFoundError) as error:
|
|
139
|
+
raise ArtifactError('The supported compiled-build tooling is unavailable.') from error
|
|
140
|
+
return compile_browser, OutputFile, SourceModule
|
|
141
|
+
|
|
142
|
+
|
|
143
|
+
def compile_client(client: ClientSources, *, source_map: bool | None = None):
|
|
144
|
+
manifest, files = _snapshot(client)
|
|
145
|
+
compile_browser, OutputFile, SourceModule = _compiler()
|
|
146
|
+
if source_map is not None and type(source_map) is not bool:
|
|
147
|
+
raise ArtifactError('Source-map policy must be boolean.')
|
|
148
|
+
try:
|
|
149
|
+
sources = tuple(SourceModule.from_text(record['module'], files[record['path']].decode('utf-8'), is_package=record['is_package'], filename=record['path']) for record in manifest['sources'])
|
|
150
|
+
notices = tuple(OutputFile(record['path'], files[record['path']], 'notice') for record in manifest['notices'])
|
|
151
|
+
artifact = compile_browser(sources, entrypoint=manifest['entrypoint'], source_map=manifest['source_map'] if source_map is None else source_map, notices=notices)
|
|
152
|
+
except (ValueError, UnicodeError) as error:
|
|
153
|
+
raise ArtifactError('Client compilation failed: ' + str(error)) from error
|
|
154
|
+
if len(artifact.files) > 256 or sum(len(item.data) for item in artifact.files) > 33_554_432:
|
|
155
|
+
raise ArtifactError('Compiled output exceeds the 256-file / 32-MiB limit.')
|
|
156
|
+
required = set(artifact.manifest['browser']['capabilities'])
|
|
157
|
+
available = {'output/1', 'dom-text/1', 'dom-events/1', 'handles/1'} | ({'fetch/1'} if manifest['fetch_urls'] else set())
|
|
158
|
+
if not required <= available:
|
|
159
|
+
raise ArtifactError('Compiled application requires unavailable host capabilities: ' + ', '.join(sorted(required - available)))
|
|
160
|
+
return artifact
|
|
161
|
+
|
|
162
|
+
|
|
163
|
+
def read_compiled(root: str | Path, client: ClientSources) -> CompilerOutput:
|
|
164
|
+
expected = compile_client(client)
|
|
165
|
+
root = Path(root).absolute()
|
|
166
|
+
data = read_asset(root, 'COMPILED-MANIFEST.json', max_bytes=1_048_576)
|
|
167
|
+
if data != expected.manifest_bytes:
|
|
168
|
+
raise ArtifactError('Compiler manifest differs from deterministic recompilation.')
|
|
169
|
+
files = tuple((item.path, read_asset(root, item.path, max_bytes=len(item.data))) for item in expected.files)
|
|
170
|
+
if files != tuple((item.path, item.data) for item in expected.files):
|
|
171
|
+
raise ArtifactError('Compiler output differs from deterministic recompilation.')
|
|
172
|
+
return CompilerOutput(root, data, files)
|
|
173
|
+
|
|
174
|
+
|
|
175
|
+
def build_compiled(client: ClientSources, output: str | Path, *, compiled: CompilerOutput | None = None,
|
|
176
|
+
title: str = 'Echidnae Python', omit_source_maps: bool = False) -> dict:
|
|
177
|
+
manifest, _ = _snapshot(client)
|
|
178
|
+
artifact = compile_client(client)
|
|
179
|
+
if compiled is not None and (not isinstance(compiled, CompilerOutput) or compiled.manifest_bytes != artifact.manifest_bytes or compiled.files != tuple((item.path, item.data) for item in artifact.files)):
|
|
180
|
+
raise ArtifactError('Compiler snapshot differs from deterministic recompilation.')
|
|
181
|
+
requested = Path(output).absolute()
|
|
182
|
+
if requested.exists() or requested.is_symlink():
|
|
183
|
+
raise ArtifactError('Output already exists; choose a new directory.')
|
|
184
|
+
destination = requested.resolve()
|
|
185
|
+
for root in [client.root, *([compiled.root] if compiled else [])]:
|
|
186
|
+
root = root.resolve()
|
|
187
|
+
if destination.is_relative_to(root) or root.is_relative_to(destination):
|
|
188
|
+
raise ArtifactError('Output overlaps an input root.')
|
|
189
|
+
if not isinstance(title, str) or not title.strip() or len(title) > 256 or type(omit_source_maps) is not bool:
|
|
190
|
+
raise ArtifactError('Title and source-map output policy are invalid.')
|
|
191
|
+
if omit_source_maps and manifest['source_map']:
|
|
192
|
+
artifact = compile_client(client, source_map=False)
|
|
193
|
+
compiled_manifest = artifact.manifest
|
|
194
|
+
namespace = 'application/' + hashlib.sha256(artifact.manifest_bytes).hexdigest()
|
|
195
|
+
files = {namespace + '/' + item.path: item.data for item in artifact.files}
|
|
196
|
+
roles = {namespace + '/' + item.path: item.role for item in artifact.files}
|
|
197
|
+
files[namespace + '/COMPILED-MANIFEST.json'] = artifact.manifest_bytes
|
|
198
|
+
capabilities = [{'id': 'output/1'}, {'id': 'dom-text/1', 'controls': ['input', 'result', 'status']},
|
|
199
|
+
{'id': 'dom-events/1', 'controls': ['run'], 'events': ['click']}, {'id': 'handles/1'}]
|
|
200
|
+
if manifest['fetch_urls']:
|
|
201
|
+
capabilities.append({'id': 'fetch/1', 'urls': manifest['fetch_urls']})
|
|
202
|
+
config_data = json_bytes({'application': {'manifest_sha256': hashlib.sha256(artifact.manifest_bytes).hexdigest(), 'profile': 'compiled-javascript', 'profile_version': 1, 'entrypoint': 'app.mjs', 'engine': None}, 'capabilities': capabilities})
|
|
203
|
+
config_name = 'app-config-' + hashlib.sha256(config_data).hexdigest() + '.json'
|
|
204
|
+
launcher_data = APP.replace('__APPLICATION__', namespace).replace('__CONFIG__', config_name).encode()
|
|
205
|
+
launcher_name = 'app-' + hashlib.sha256(launcher_data).hexdigest() + '.js'
|
|
206
|
+
files.update({'index.html': PAGE.replace('__LAUNCHER__', launcher_name).replace('__TITLE__', html.escape(title, quote=True)).encode(),
|
|
207
|
+
launcher_name: launcher_data, config_name: config_data, 'icon.svg': ICON.encode(),
|
|
208
|
+
'manifest.webmanifest': json_bytes({'name': title, 'short_name': title[:24], 'id': './', 'start_url': './', 'scope': './', 'display': 'standalone', 'theme_color': '#225841', 'background_color': '#f4f7f1', 'icons': [{'src': './icon.svg', 'sizes': 'any', 'type': 'image/svg+xml'}]})})
|
|
209
|
+
records = [file_record(name, data) for name, data in sorted(files.items())]
|
|
210
|
+
cache_version = hashlib.sha256(json_bytes({'profile': 'compiled-javascript/1', 'pocket_python_version': __version__, 'compiler_revision': COMPILER_REVISION, 'compiler_fingerprint': COMPILER_FINGERPRINT, 'service_worker_template': hashlib.sha256(SERVICE_WORKER.encode()).hexdigest(), 'files': records})).hexdigest()
|
|
211
|
+
files['service-worker.js'] = SERVICE_WORKER.replace('__FILES__', json.dumps([*sorted(files), 'service-worker.js', 'POCKET-PYTHON.json'])).replace('__VERSION__', cache_version).encode()
|
|
212
|
+
for name in files:
|
|
213
|
+
roles.setdefault(name, 'executable-module' if name in {launcher_name, 'service-worker.js'} else 'data')
|
|
214
|
+
receipt = {'kind': 'pocket-python-application', 'schema_version': 2, 'profile': 'compiled-javascript', 'profile_version': 1, 'target': 'client',
|
|
215
|
+
'pocket_python_version': __version__, 'title': title, 'entrypoint': {'path': namespace + '/app.mjs', 'kind': 'es-module'}, 'ui_entrypoint': 'index.html', 'launcher': launcher_name, 'configuration': config_name, 'ui_profile': 'text-input/1', 'engine': None,
|
|
216
|
+
'producer': {**compiled_manifest['compiler'], 'source_revision': COMPILER_REVISION, 'source_fingerprint': COMPILER_FINGERPRINT, 'language_profile': compiled_manifest['language_profile']},
|
|
217
|
+
'compiler_manifest': namespace + '/COMPILED-MANIFEST.json', 'source_map': not omit_source_maps and manifest['source_map'], 'sources': compiled_manifest['sources'],
|
|
218
|
+
'capabilities': capabilities, 'imports': [{'from': launcher_name, 'to': namespace + '/browser-host.mjs'}] + [{'from': namespace + '/' + edge['from'], 'to': namespace + '/' + edge['to']} for edge in compiled_manifest['imports']],
|
|
219
|
+
'licenses': [namespace + '/' + name for name in compiled_manifest['notices']], 'cache_version': cache_version,
|
|
220
|
+
'files': [{**file_record(name, data), 'role': roles[name]} for name, data in sorted(files.items())],
|
|
221
|
+
'size': {'source_bytes': sum(record['size'] for record in compiled_manifest['sources']), 'emitted_module_bytes': sum(len(item.data) for item in artifact.files if item.role == 'executable-module'),
|
|
222
|
+
'helper_bytes': sum(len(item.data) for item in artifact.files if item.role == 'compatibility-helper'), 'source_map_bytes': sum(len(item.data) for item in artifact.files if item.role == 'source-map'),
|
|
223
|
+
'notice_bytes': sum(len(item.data) for item in artifact.files if item.role == 'notice'), 'engine_bytes': 0,
|
|
224
|
+
'data_bytes': sum(len(data) for name, data in files.items() if roles[name] == 'data'),
|
|
225
|
+
'assembly_module_bytes': len(files[launcher_name]) + len(files['service-worker.js']), 'receipt_bytes': 0, 'artifact_bytes': 0}}
|
|
226
|
+
payload_size = sum(map(len, files.values()))
|
|
227
|
+
while True:
|
|
228
|
+
data = json_bytes(receipt)
|
|
229
|
+
total = payload_size + len(data)
|
|
230
|
+
if total == receipt['size']['artifact_bytes'] and len(data) == receipt['size']['receipt_bytes']:
|
|
231
|
+
break
|
|
232
|
+
receipt['size']['artifact_bytes'] = total
|
|
233
|
+
receipt['size']['receipt_bytes'] = len(data)
|
|
234
|
+
files['POCKET-PYTHON.json'] = data
|
|
235
|
+
_publish(destination, files)
|
|
236
|
+
return receipt
|
|
@@ -0,0 +1,82 @@
|
|
|
1
|
+
"""Local text-input UI for the compiled-javascript application profile."""
|
|
2
|
+
|
|
3
|
+
PAGE = '''<!doctype html><html lang="en"><meta charset="utf-8"><meta name="viewport" content="width=device-width">
|
|
4
|
+
<title>__TITLE__</title><link rel="manifest" href="./manifest.webmanifest"><link rel="icon" href="./icon.svg">
|
|
5
|
+
<style>body{font:1.1rem system-ui,sans-serif;max-width:44rem;margin:4rem auto;padding:0 1.5rem;color:#19362c;background:#f4f7f1}
|
|
6
|
+
textarea{box-sizing:border-box;width:100%;min-height:12rem;padding:1rem;font:inherit;border:1px solid #779287;border-radius:.5rem;background:white}
|
|
7
|
+
button{padding:.6rem 1rem;font:inherit;border:1px solid #779287;border-radius:.4rem;background:white;cursor:pointer}
|
|
8
|
+
#run{background:#225841;color:white}nav{display:flex;gap:.5rem;margin:1rem 0}pre{min-height:3rem;white-space:pre-wrap;padding:1rem;background:white;border-radius:.5rem}</style>
|
|
9
|
+
<main><h1>__TITLE__</h1><p>Run this application locally in your browser.</p>
|
|
10
|
+
<label for="input">Text</label><textarea id="input" placeholder="Write something…"></textarea>
|
|
11
|
+
<nav><button id="run" disabled>Run</button><button id="stop">Stop</button><button id="restart">Restart</button></nav>
|
|
12
|
+
<label for="result">Result</label><pre id="result" aria-live="polite"></pre><p id="status" role="status"></p><p id="offline" role="status">Preparing offline use…</p></main>
|
|
13
|
+
<script type="module" src="./__LAUNCHER__"></script></html>'''
|
|
14
|
+
|
|
15
|
+
APP = '''import {mountCompiledApplication} from './__APPLICATION__/browser-host.mjs';
|
|
16
|
+
const byId=name=>document.getElementById(name);
|
|
17
|
+
const config=await(await fetch('./__CONFIG__')).json();
|
|
18
|
+
let current;
|
|
19
|
+
function start(){
|
|
20
|
+
current?.stop();byId('run').disabled=true;byId('result').textContent='';byId('status').textContent='Starting…';
|
|
21
|
+
const active=mountCompiledApplication({application:config.application,capabilities:config.capabilities,
|
|
22
|
+
controls:Object.fromEntries(['input','run','result','status'].map(name=>[name,byId(name)])),
|
|
23
|
+
eventInputs:{run:'input'},output:byId('result'),onError:error=>{
|
|
24
|
+
byId('run').disabled=true;
|
|
25
|
+
const at=error.location?' ('+error.location.filename+':'+error.location.line+':'+error.location.column+')':'';
|
|
26
|
+
byId('status').textContent=error.type+': '+error.message+at;
|
|
27
|
+
}});
|
|
28
|
+
current=active;
|
|
29
|
+
active.ready.then(async()=>{
|
|
30
|
+
while(current===active&&active.stats().state==='ready'&&active.stats().subscriptions<1)await new Promise(requestAnimationFrame);
|
|
31
|
+
if(current===active&&active.stats().state==='ready'){byId('run').disabled=false;byId('status').textContent='Ready';}
|
|
32
|
+
},()=>{});
|
|
33
|
+
}
|
|
34
|
+
byId('run').addEventListener('click',()=>{byId('result').textContent='';});
|
|
35
|
+
byId('stop').addEventListener('click',()=>{current?.stop();byId('run').disabled=true;byId('status').textContent='Stopped';});
|
|
36
|
+
byId('restart').addEventListener('click',start);
|
|
37
|
+
window.addEventListener('pagehide',()=>current?.stop());
|
|
38
|
+
window.addEventListener('pageshow',event=>{if(event.persisted)start();});
|
|
39
|
+
async function prepareOffline(){
|
|
40
|
+
if(!('serviceWorker' in navigator))throw new Error('This browser does not support offline installation.');
|
|
41
|
+
const registration=await navigator.serviceWorker.register('./service-worker.js',{scope:'./',updateViaCache:'none'});
|
|
42
|
+
function describeOffline(){
|
|
43
|
+
byId('offline').textContent=registration.waiting?'Update ready. Close this app\u2019s tabs and windows, then reopen to update.':'Offline ready on this device';
|
|
44
|
+
}
|
|
45
|
+
function watchUpdate(){
|
|
46
|
+
registration.installing?.addEventListener('statechange',()=>{if(registration.active)describeOffline();});
|
|
47
|
+
}
|
|
48
|
+
registration.addEventListener('updatefound',watchUpdate);watchUpdate();
|
|
49
|
+
const installing=registration.installing||registration.waiting;
|
|
50
|
+
if(!registration.active&&installing&&installing.state!=='activated')await new Promise((resolve,reject)=>{
|
|
51
|
+
function changed(){if(installing.state==='activated')resolve();if(installing.state==='redundant')reject(new Error('Offline installation failed.'));}
|
|
52
|
+
installing.addEventListener('statechange',changed);changed();
|
|
53
|
+
});
|
|
54
|
+
await navigator.serviceWorker.ready;
|
|
55
|
+
describeOffline();
|
|
56
|
+
}
|
|
57
|
+
prepareOffline().catch(error=>{byId('offline').textContent='Offline unavailable: '+error.message;});
|
|
58
|
+
start();
|
|
59
|
+
'''
|
|
60
|
+
|
|
61
|
+
SERVICE_WORKER = '''const FILES = __FILES__;
|
|
62
|
+
const PREFIX = "pocket-python:" + self.registration.scope + ":";
|
|
63
|
+
const CACHE = PREFIX + "__VERSION__";
|
|
64
|
+
self.addEventListener("install", event => {
|
|
65
|
+
const requests=FILES.map(path=>new Request(new URL(path,self.registration.scope).href,{cache:'reload'}));
|
|
66
|
+
// Keep the current session's document and module graph together. An update
|
|
67
|
+
// activates after every client of the previous version has closed.
|
|
68
|
+
event.waitUntil(caches.open(CACHE).then(cache=>cache.addAll(requests)));
|
|
69
|
+
});
|
|
70
|
+
self.addEventListener("activate", event => {
|
|
71
|
+
event.waitUntil(caches.keys().then(keys=>Promise.all(keys.filter(key=>key.startsWith(PREFIX)&&key!==CACHE).map(key=>caches.delete(key)))).then(()=>self.clients.claim()));
|
|
72
|
+
});
|
|
73
|
+
self.addEventListener("fetch", event => {
|
|
74
|
+
const url=new URL(event.request.url),index=new URL('index.html',self.registration.scope);
|
|
75
|
+
if(event.request.method!=='GET'||url.origin!==self.location.origin||!url.href.startsWith(self.registration.scope))return;
|
|
76
|
+
event.respondWith((async()=>{
|
|
77
|
+
const cache=await caches.open(CACHE);
|
|
78
|
+
const request=event.request.mode==='navigate'&&url.pathname===new URL(self.registration.scope).pathname?index.href:event.request;
|
|
79
|
+
return(await cache.match(request))||fetch(event.request);
|
|
80
|
+
})());
|
|
81
|
+
});
|
|
82
|
+
'''
|
|
@@ -0,0 +1,238 @@
|
|
|
1
|
+
"""Assemble the pinned independent source engine and one explicit console source."""
|
|
2
|
+
|
|
3
|
+
from dataclasses import dataclass
|
|
4
|
+
import hashlib
|
|
5
|
+
import html
|
|
6
|
+
import json
|
|
7
|
+
from pathlib import Path
|
|
8
|
+
import re
|
|
9
|
+
|
|
10
|
+
from echidnae.python import __version__
|
|
11
|
+
from echidnae.python._interpreter_lock import ENGINE_FILES, ENGINE_FINGERPRINT, ENGINE_IMPORTS
|
|
12
|
+
from echidnae.python._library_lock import LIBRARY_PROFILES
|
|
13
|
+
from echidnae.python.assets import ArtifactError, check_names, file_record, json_bytes, read_asset
|
|
14
|
+
from echidnae.python.interpreter_templates import APP, PAGE, SERVICE_WORKER
|
|
15
|
+
from echidnae.python.templates import ICON
|
|
16
|
+
from echidnae.python.web import _publish
|
|
17
|
+
|
|
18
|
+
|
|
19
|
+
ENGINE = {'implementation': 'pocket-python-source', 'version': '1', 'backend': 'javascript-vm',
|
|
20
|
+
'bytecode_version': 4, 'language_profile': 'core-source/1'}
|
|
21
|
+
LANGUAGE_ENGINES = {'core-source/1': ENGINE,
|
|
22
|
+
'classes-source/1': {**ENGINE, 'bytecode_version': 5, 'language_profile': 'classes-source/1'}}
|
|
23
|
+
LIMITS = {'message_bytes': 1048576, 'value_depth': 16, 'pending_requests': 1, 'subscriptions': 0,
|
|
24
|
+
'output_codepoints': 16384, 'response_bytes': 1048576, 'deadline_ms': 10000,
|
|
25
|
+
'source_bytes': 65536, 'compile_work': 4194304, 'execution_steps': 1000000,
|
|
26
|
+
'execution_work': 100000000, 'memory_bytes': 8388608, 'memory_objects': 4096, 'memory_frames': 64}
|
|
27
|
+
|
|
28
|
+
|
|
29
|
+
@dataclass(frozen=True)
|
|
30
|
+
class InterpreterAssets:
|
|
31
|
+
root: Path
|
|
32
|
+
files: tuple[tuple[str, bytes], ...]
|
|
33
|
+
library_profile: str = 'core-only/1'
|
|
34
|
+
|
|
35
|
+
|
|
36
|
+
@dataclass(frozen=True)
|
|
37
|
+
class ConsoleSource:
|
|
38
|
+
root: Path
|
|
39
|
+
manifest_bytes: bytes
|
|
40
|
+
files: tuple[tuple[str, bytes], ...]
|
|
41
|
+
|
|
42
|
+
|
|
43
|
+
def _manifest(data):
|
|
44
|
+
def pairs(items):
|
|
45
|
+
result = {}
|
|
46
|
+
for key, value in items:
|
|
47
|
+
if key in result:
|
|
48
|
+
raise ArtifactError('Duplicate console-source field: ' + key)
|
|
49
|
+
result[key] = value
|
|
50
|
+
return result
|
|
51
|
+
try:
|
|
52
|
+
manifest = json.loads(data, object_pairs_hook=pairs)
|
|
53
|
+
except ArtifactError:
|
|
54
|
+
raise
|
|
55
|
+
except (ValueError, UnicodeError, RecursionError) as error:
|
|
56
|
+
raise ArtifactError('Invalid console-source JSON.') from error
|
|
57
|
+
fields = {'kind', 'schema_version', 'target', 'source', 'notice'}
|
|
58
|
+
if (not isinstance(manifest, dict) or set(manifest) != fields
|
|
59
|
+
or manifest['kind'] != 'pocket-python-console-source' or type(manifest['schema_version']) is not int
|
|
60
|
+
or manifest['schema_version'] != 1 or manifest['target'] != 'client'):
|
|
61
|
+
raise ArtifactError('Expected an explicit schema-1 client console-source allowlist.')
|
|
62
|
+
for key, role in [('source', 'client-source'), ('notice', 'notice')]:
|
|
63
|
+
record = manifest[key]
|
|
64
|
+
if (not isinstance(record, dict) or set(record) != {'path', 'size_bytes', 'sha256', 'role'}
|
|
65
|
+
or record['role'] != role or not isinstance(record['path'], str)
|
|
66
|
+
or type(record['size_bytes']) is not int or not 0 <= record['size_bytes'] <= 65536
|
|
67
|
+
or not isinstance(record['sha256'], str) or not re.fullmatch('[0-9a-f]{64}', record['sha256'])):
|
|
68
|
+
raise ArtifactError('Invalid bounded console source/notice record.')
|
|
69
|
+
if key == 'source' and not record['path'].endswith('.py'):
|
|
70
|
+
raise ArtifactError('Console source requires a Python file path.')
|
|
71
|
+
if key == 'notice' and (not record['path'].startswith('LICENSES/') or not record['size_bytes']):
|
|
72
|
+
raise ArtifactError('Console source requires a nonempty notice under LICENSES/.')
|
|
73
|
+
check_names(manifest[key]['path'] for key in ['source', 'notice'])
|
|
74
|
+
return manifest
|
|
75
|
+
|
|
76
|
+
|
|
77
|
+
def _source_snapshot(source):
|
|
78
|
+
if not isinstance(source, ConsoleSource) or type(source.manifest_bytes) is not bytes or not isinstance(source.files, tuple):
|
|
79
|
+
raise ArtifactError('Expected an immutable console-source snapshot.')
|
|
80
|
+
manifest, files = _manifest(source.manifest_bytes), dict(source.files)
|
|
81
|
+
if len(files) != len(source.files) or set(files) != {manifest[key]['path'] for key in ['source', 'notice']}:
|
|
82
|
+
raise ArtifactError('Console-source snapshot file set changed.')
|
|
83
|
+
for key in ['source', 'notice']:
|
|
84
|
+
record = manifest[key]
|
|
85
|
+
data = files[record['path']]
|
|
86
|
+
if type(data) is not bytes or file_record(record['path'], data) != {field: record[field] for field in ['path', 'size_bytes', 'sha256']}:
|
|
87
|
+
raise ArtifactError('Console-source snapshot hash/size differs.')
|
|
88
|
+
try:
|
|
89
|
+
text = data.decode('utf-8')
|
|
90
|
+
except UnicodeError as error:
|
|
91
|
+
raise ArtifactError('Console source and notice require UTF-8.') from error
|
|
92
|
+
if key == 'notice' and not text.strip():
|
|
93
|
+
raise ArtifactError('Console source notice is empty.')
|
|
94
|
+
if key == 'source' and text.startswith('\ufeff'):
|
|
95
|
+
raise ArtifactError('The console editor requires UTF-8 source without a BOM.')
|
|
96
|
+
return manifest, files
|
|
97
|
+
|
|
98
|
+
|
|
99
|
+
def _library_profile(identity):
|
|
100
|
+
if not isinstance(identity, str) or identity not in LIBRARY_PROFILES:
|
|
101
|
+
raise ArtifactError('Unknown library profile; no fallback is selected.')
|
|
102
|
+
return LIBRARY_PROFILES[identity]
|
|
103
|
+
|
|
104
|
+
|
|
105
|
+
def _engine_snapshot(engine):
|
|
106
|
+
if not isinstance(engine, InterpreterAssets) or not isinstance(engine.files, tuple):
|
|
107
|
+
raise ArtifactError('Expected an immutable independent-engine snapshot.')
|
|
108
|
+
files = dict(engine.files)
|
|
109
|
+
profile = _library_profile(engine.library_profile)
|
|
110
|
+
optional = {record['source']['path']: record['source'] for record in profile['modules']}
|
|
111
|
+
if len(files) != len(engine.files) or set(files) != {name for name, _, _ in ENGINE_FILES} | set(optional):
|
|
112
|
+
raise ArtifactError('Independent-engine file set differs from the pinned allowlist.')
|
|
113
|
+
digest = hashlib.sha256()
|
|
114
|
+
for name, size, sha in ENGINE_FILES:
|
|
115
|
+
data = files[name]
|
|
116
|
+
if type(data) is not bytes or len(data) != size or hashlib.sha256(data).hexdigest() != sha:
|
|
117
|
+
raise ArtifactError('Independent-engine asset differs from the supported pinned build: ' + name)
|
|
118
|
+
for part in (name.encode(), data):
|
|
119
|
+
digest.update(len(part).to_bytes(8, 'big'))
|
|
120
|
+
digest.update(part)
|
|
121
|
+
if digest.hexdigest() != ENGINE_FINGERPRINT:
|
|
122
|
+
raise ArtifactError('Independent-engine fingerprint differs.')
|
|
123
|
+
for record in [*optional.values(), *(record['notice'] for record in profile['modules'])]:
|
|
124
|
+
if record['path'] not in files or type(files[record['path']]) is not bytes or file_record(record['path'], files[record['path']]) != record:
|
|
125
|
+
raise ArtifactError('Library source/notice differs from its reviewed identity.')
|
|
126
|
+
return files
|
|
127
|
+
|
|
128
|
+
|
|
129
|
+
def read_console_source(manifest_path: str | Path) -> ConsoleSource:
|
|
130
|
+
path = Path(manifest_path).absolute()
|
|
131
|
+
data = read_asset(path.parent, path.name, max_bytes=65536)
|
|
132
|
+
manifest = _manifest(data)
|
|
133
|
+
files = tuple((record['path'], read_asset(path.parent, record['path'], max_bytes=record['size_bytes']))
|
|
134
|
+
for record in [manifest['source'], manifest['notice']])
|
|
135
|
+
result = ConsoleSource(path.parent, data, files)
|
|
136
|
+
_source_snapshot(result)
|
|
137
|
+
return result
|
|
138
|
+
|
|
139
|
+
|
|
140
|
+
def read_interpreter(root: str | Path, *, library_profile: str = 'core-only/1') -> InterpreterAssets:
|
|
141
|
+
root = Path(root).absolute()
|
|
142
|
+
profile = _library_profile(library_profile)
|
|
143
|
+
# Canonicalize checkout line endings only; source inputs retain exact bytes.
|
|
144
|
+
files = tuple((name, read_asset(root, name, max_bytes=max(2 * size, 1)).replace(b'\r\n', b'\n')) for name, size, _ in ENGINE_FILES)
|
|
145
|
+
files += tuple((record['source']['path'], read_asset(root, record['source']['path'], max_bytes=2 * record['source']['size_bytes']).replace(b'\r\n', b'\n')) for record in profile['modules'])
|
|
146
|
+
result = InterpreterAssets(root, files, library_profile)
|
|
147
|
+
_engine_snapshot(result)
|
|
148
|
+
return result
|
|
149
|
+
|
|
150
|
+
|
|
151
|
+
def build_interpreter(source: ConsoleSource, engine: InterpreterAssets, output: str | Path,
|
|
152
|
+
*, title: str = 'Echidnae Python Console', host_profile: str = 'output-only/1',
|
|
153
|
+
language_profile: str = 'core-source/1') -> dict:
|
|
154
|
+
if not isinstance(language_profile, str) or language_profile not in LANGUAGE_ENGINES:
|
|
155
|
+
raise ArtifactError('Unavailable source language profile.')
|
|
156
|
+
language = dict(LANGUAGE_ENGINES[language_profile])
|
|
157
|
+
manifest, source_files = _source_snapshot(source)
|
|
158
|
+
engine_files = _engine_snapshot(engine)
|
|
159
|
+
profile = _library_profile(engine.library_profile)
|
|
160
|
+
if host_profile != 'output-only/1':
|
|
161
|
+
raise ArtifactError('Unavailable host-module profile; async adapters require INT-10.')
|
|
162
|
+
requested = Path(output).absolute()
|
|
163
|
+
if requested.exists() or requested.is_symlink():
|
|
164
|
+
raise ArtifactError('Output already exists; choose a new directory.')
|
|
165
|
+
destination = requested.resolve()
|
|
166
|
+
for root in [source.root.resolve(), engine.root.resolve()]:
|
|
167
|
+
if destination.is_relative_to(root) or root.is_relative_to(destination):
|
|
168
|
+
raise ArtifactError('Output overlaps an input root.')
|
|
169
|
+
if not isinstance(title, str) or not title.strip() or len(title) > 256:
|
|
170
|
+
raise ArtifactError('Console title requires 1–256 characters.')
|
|
171
|
+
|
|
172
|
+
engine_root = 'engine/' + ENGINE_FINGERPRINT
|
|
173
|
+
identity = {'kind': 'pocket-python-source-console', 'schema_version': 1,
|
|
174
|
+
'profile': 'in-house-interpreter', 'profile_version': 1, 'engine': {**language, 'fingerprint': ENGINE_FINGERPRINT},
|
|
175
|
+
'library_profile': profile, 'host_profile': host_profile,
|
|
176
|
+
'source': manifest['source'], 'notice': manifest['notice'], 'capabilities': [{'id': 'output/1'}], 'limits': LIMITS}
|
|
177
|
+
identity_bytes = json_bytes(identity)
|
|
178
|
+
source_root = 'application/' + hashlib.sha256(identity_bytes).hexdigest()
|
|
179
|
+
files = {engine_root + '/' + name: data for name, data in engine_files.items()}
|
|
180
|
+
source_path = source_root + '/sources/app.py'
|
|
181
|
+
notice_path = source_root + '/' + manifest['notice']['path']
|
|
182
|
+
files.update({source_path: source_files[manifest['source']['path']], notice_path: source_files[manifest['notice']['path']],
|
|
183
|
+
source_root + '/APPLICATION.json': identity_bytes})
|
|
184
|
+
libraries = [{**{key: record[key] for key in ['name', 'package', 'imports']},
|
|
185
|
+
**{key: file_record(engine_root + '/' + record[key]['path'], engine_files[record[key]['path']]) for key in ['source', 'notice']}}
|
|
186
|
+
for record in profile['modules']]
|
|
187
|
+
config = {'application': {'manifest_sha256': hashlib.sha256(identity_bytes).hexdigest(), 'profile': 'in-house-interpreter',
|
|
188
|
+
'profile_version': 1, 'entrypoint': 'sources/app.py', 'engine': language},
|
|
189
|
+
'library_profile': profile['id'], 'libraries': libraries, 'host_profile': host_profile,
|
|
190
|
+
'source': file_record(source_path, files[source_path]), 'capabilities': identity['capabilities'], 'limits': LIMITS}
|
|
191
|
+
config_bytes = json_bytes(config)
|
|
192
|
+
config_sha = hashlib.sha256(config_bytes).hexdigest()
|
|
193
|
+
config_path = 'app-config-' + config_sha + '.json'
|
|
194
|
+
launcher = APP.replace('__ENGINE__', engine_root).replace('__CONFIG__', config_path).replace('__CONFIG_SHA__', config_sha).encode()
|
|
195
|
+
launcher_path = 'app-' + hashlib.sha256(launcher).hexdigest() + '.js'
|
|
196
|
+
files.update({config_path: config_bytes, launcher_path: launcher,
|
|
197
|
+
'index.html': PAGE.replace('__LAUNCHER__', launcher_path).replace('__TITLE__', html.escape(title, quote=True)).encode(),
|
|
198
|
+
'icon.svg': ICON.encode(), 'manifest.webmanifest': json_bytes({'name': title, 'short_name': title[:24], 'id': './',
|
|
199
|
+
'start_url': './', 'scope': './', 'display': 'standalone', 'theme_color': '#225841', 'background_color': '#f4f7f1',
|
|
200
|
+
'icons': [{'src': './icon.svg', 'sizes': 'any', 'type': 'image/svg+xml'}]})})
|
|
201
|
+
roles = {name: 'data' for name in files}
|
|
202
|
+
roles.update({engine_root + '/' + name: 'notice' if name.startswith('licenses/') else 'engine' for name in engine_files})
|
|
203
|
+
roles.update({record['source']['path']: 'library' for record in libraries})
|
|
204
|
+
roles.update({source_path: 'source', notice_path: 'notice', launcher_path: 'executable-module'})
|
|
205
|
+
records = [file_record(name, data) for name, data in sorted(files.items())]
|
|
206
|
+
cache_version = hashlib.sha256(json_bytes({'profile': 'in-house-interpreter/1', 'pocket_python_version': __version__,
|
|
207
|
+
'service_worker_template': hashlib.sha256(SERVICE_WORKER.encode()).hexdigest(), 'files': records})).hexdigest()
|
|
208
|
+
files['service-worker.js'] = SERVICE_WORKER.replace('__RECORDS__', json.dumps(records, sort_keys=True)).replace('__VERSION__', cache_version).encode()
|
|
209
|
+
roles['service-worker.js'] = 'executable-module'
|
|
210
|
+
receipt = {'kind': 'pocket-python-application', 'schema_version': 2, 'target': 'client', 'profile': 'in-house-interpreter',
|
|
211
|
+
'profile_version': 1, 'pocket_python_version': __version__, 'title': title, 'ui_profile': 'source-console/1',
|
|
212
|
+
'entrypoint': {'path': source_path, 'kind': 'python-source'}, 'ui_entrypoint': 'index.html',
|
|
213
|
+
'launcher': launcher_path, 'configuration': config_path, 'application_manifest': source_root + '/APPLICATION.json',
|
|
214
|
+
'engine': {**language, 'fingerprint': ENGINE_FINGERPRINT, 'entrypoint': engine_root + '/interpreter-worker.mjs'},
|
|
215
|
+
'producer': {'name': 'echidnae-python', 'version': __version__, 'language_profile': language_profile},
|
|
216
|
+
'source_execution': True, 'input_mode': 'source', 'capabilities': identity['capabilities'], 'limits': LIMITS,
|
|
217
|
+
'library_profile': {'id': profile['id'], 'fingerprint': profile['fingerprint']}, 'libraries': libraries, 'host_profile': host_profile,
|
|
218
|
+
'sources': [{**file_record(source_path, files[source_path]), 'original_path': manifest['source']['path'], 'logical_path': 'sources/app.py'}] +
|
|
219
|
+
[{**record['source'], 'original_path': definition['source']['path'],
|
|
220
|
+
'logical_path': 'sources/' + record['name'].replace('.', '/') + '.py'} for record, definition in zip(libraries, profile['modules'])],
|
|
221
|
+
'imports': [{'from': launcher_path, 'to': engine_root + '/interpreter-host.mjs'}] +
|
|
222
|
+
[{'from': engine_root + '/' + origin, 'to': engine_root + '/' + target} for origin, target in ENGINE_IMPORTS],
|
|
223
|
+
'licenses': sorted(name for name in files if roles[name] == 'notice'), 'cache_version': cache_version,
|
|
224
|
+
'files': [{**file_record(name, data), 'role': roles[name]} for name, data in sorted(files.items())],
|
|
225
|
+
'size': {**{role + '_bytes': sum(len(data) for name, data in files.items() if roles[name] == role)
|
|
226
|
+
for role in ['source', 'engine', 'library', 'notice', 'data']},
|
|
227
|
+
'assembly_module_bytes': sum(len(data) for name, data in files.items() if roles[name] == 'executable-module'),
|
|
228
|
+
'receipt_bytes': 0, 'artifact_bytes': 0}}
|
|
229
|
+
payload_size = sum(map(len, files.values()))
|
|
230
|
+
while True:
|
|
231
|
+
data = json_bytes(receipt)
|
|
232
|
+
total = payload_size + len(data)
|
|
233
|
+
if total == receipt['size']['artifact_bytes'] and len(data) == receipt['size']['receipt_bytes']:
|
|
234
|
+
break
|
|
235
|
+
receipt['size']['artifact_bytes'], receipt['size']['receipt_bytes'] = total, len(data)
|
|
236
|
+
files['POCKET-PYTHON.json'] = data
|
|
237
|
+
_publish(destination, files)
|
|
238
|
+
return receipt
|