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,119 @@
|
|
|
1
|
+
"""Source editor and scoped offline installation for the independent interpreter."""
|
|
2
|
+
|
|
3
|
+
PAGE = '''<!doctype html><html lang="en"><meta charset="utf-8"><meta name="viewport" content="width=device-width">
|
|
4
|
+
<meta http-equiv="Content-Security-Policy" content="default-src 'self'; script-src 'self'; worker-src 'self'; connect-src 'self'; style-src 'self' 'unsafe-inline'; object-src 'none'; base-uri 'none'">
|
|
5
|
+
<title>__TITLE__</title><link rel="manifest" href="./manifest.webmanifest"><link rel="icon" href="./icon.svg">
|
|
6
|
+
<style>body{font:1rem system-ui,sans-serif;max-width:56rem;margin:3rem auto;padding:0 1.5rem;color:#19362c;background:#f4f7f1}
|
|
7
|
+
textarea{box-sizing:border-box;width:100%;min-height:20rem;padding:1rem;font:1rem/1.6 ui-monospace,monospace;tab-size:4;border:1px solid #779287;border-radius:.5rem;background:white}
|
|
8
|
+
button{padding:.6rem 1rem;font:inherit;border:1px solid #779287;border-radius:.4rem;background:white;cursor:pointer}button:disabled{opacity:.5;cursor:default}
|
|
9
|
+
#run{background:#225841;color:white}nav{display:flex;gap:.5rem;margin:1rem 0}pre{min-height:2rem;overflow-wrap:anywhere;white-space:pre-wrap;padding:1rem;background:white;border-radius:.5rem}
|
|
10
|
+
#diagnostic{color:#8b2323;min-height:0}#diagnostic:empty{display:none}.note{color:#4a6358;font-size:.9rem}label{display:block;margin-bottom:.5rem;font-weight:600}</style>
|
|
11
|
+
<main><h1>__TITLE__</h1><p>Write Python and run it on this device. Each run starts with fresh variables.</p>
|
|
12
|
+
<label for="input">Python source</label><textarea id="input" spellcheck="false" autocapitalize="off" autocomplete="off" aria-describedby="language"></textarea>
|
|
13
|
+
<p id="language" class="note">Loading the selected language profile…</p>
|
|
14
|
+
<p id="libraries" class="note"></p>
|
|
15
|
+
<nav aria-label="Execution"><button id="run" disabled>Run</button><button id="stop">Stop</button><button id="restart">Restart</button></nav>
|
|
16
|
+
<p id="status" role="status">Starting…</p><label for="result">Output</label><pre id="result" aria-live="polite"></pre><pre id="diagnostic" role="alert"></pre>
|
|
17
|
+
<p id="offline" role="status">Preparing offline use…</p><p class="note">Source stays in this tab. Reload restores the supplied example.</p></main>
|
|
18
|
+
<script type="module" src="./__LAUNCHER__"></script></html>'''
|
|
19
|
+
|
|
20
|
+
APP = '''import {mountInterpreter} from './__ENGINE__/interpreter-host.mjs';
|
|
21
|
+
const byId=name=>document.getElementById(name);
|
|
22
|
+
let current=null,generation=0;
|
|
23
|
+
async function verified(path,digest,maximum){
|
|
24
|
+
const response=await fetch(path,{cache:'no-store'});
|
|
25
|
+
if(!response.ok)throw new Error('Application asset is unavailable: '+path);
|
|
26
|
+
const reader=response.body.getReader(),chunks=[];let size=0;
|
|
27
|
+
while(true){const {done,value}=await reader.read();if(done)break;
|
|
28
|
+
if((size+=value.byteLength)>maximum){await reader.cancel();throw new Error('Application asset byte budget exceeded.');}chunks.push(value);}
|
|
29
|
+
const bytes=new Uint8Array(size);let offset=0;for(const chunk of chunks){bytes.set(chunk,offset);offset+=chunk.byteLength;}
|
|
30
|
+
const actual=Array.from(new Uint8Array(await crypto.subtle.digest('SHA-256',bytes)),b=>b.toString(16).padStart(2,'0')).join('');
|
|
31
|
+
if(actual!==digest)throw new Error('Application asset hash differs: '+path);
|
|
32
|
+
return new TextDecoder('utf-8',{fatal:true}).decode(bytes);
|
|
33
|
+
}
|
|
34
|
+
function showError(error){
|
|
35
|
+
const value=error.detail||error;
|
|
36
|
+
const at=value.location?' ('+value.location.filename+':'+value.location.line+':'+value.location.column+')':'';
|
|
37
|
+
byId('status').textContent=(value.type||error.name||'Error')+': '+value.message+at;
|
|
38
|
+
byId('diagnostic').textContent=(value.frames||[]).map(frame=>frame.function+(frame.location?' at '+frame.location.filename+':'+frame.location.line:'')).join('\\n');
|
|
39
|
+
}
|
|
40
|
+
let config;
|
|
41
|
+
function start(){
|
|
42
|
+
const turn=++generation;current?.stop('restart');current=null;
|
|
43
|
+
byId('run').disabled=true;byId('result').textContent='';byId('diagnostic').textContent='';byId('status').textContent='Starting…';
|
|
44
|
+
try{
|
|
45
|
+
const active=mountInterpreter({application:config.application,capabilities:config.capabilities,limits:config.limits,
|
|
46
|
+
libraryProfile:config.library_profile,libraries:config.library_sources,hostProfile:config.host_profile,
|
|
47
|
+
onOutput:text=>{if(turn===generation)byId('result').append(document.createTextNode(text));},
|
|
48
|
+
onError:error=>{if(turn===generation){byId('run').disabled=true;showError(error);}}});
|
|
49
|
+
current=active;
|
|
50
|
+
active.ready.then(()=>{if(turn===generation){byId('run').disabled=false;byId('status').textContent='Ready';}},error=>{if(turn===generation)showError(error);});
|
|
51
|
+
}catch(error){showError(error);}
|
|
52
|
+
}
|
|
53
|
+
byId('run').addEventListener('click',async()=>{
|
|
54
|
+
const turn=generation,active=current;if(!active)return;
|
|
55
|
+
byId('run').disabled=true;byId('result').textContent='';byId('diagnostic').textContent='';byId('status').textContent='Running…';
|
|
56
|
+
try{await active.run(byId('input').value);if(turn===generation)byId('status').textContent='Completed';}
|
|
57
|
+
catch(error){if(turn===generation)showError(error);}
|
|
58
|
+
finally{if(turn===generation)byId('run').disabled=active.stats().state!=='ready';}
|
|
59
|
+
});
|
|
60
|
+
byId('stop').addEventListener('click',()=>{generation++;current?.stop();byId('run').disabled=true;byId('status').textContent='Stopped';});
|
|
61
|
+
byId('restart').addEventListener('click',()=>{if(config)start();});
|
|
62
|
+
window.addEventListener('pagehide',()=>{generation++;current?.stop();});
|
|
63
|
+
window.addEventListener('pageshow',event=>{if(event.persisted&&config)start();});
|
|
64
|
+
async function prepareOffline(){
|
|
65
|
+
if(!('serviceWorker' in navigator))throw new Error('This browser does not support offline installation.');
|
|
66
|
+
const registration=await navigator.serviceWorker.register('./service-worker.js',{scope:'./',updateViaCache:'none'});
|
|
67
|
+
function describe(){byId('offline').textContent=registration.waiting?'Update ready. Close this app’s tabs and windows, then reopen to update.':'Offline ready on this device';}
|
|
68
|
+
function watch(){registration.installing?.addEventListener('statechange',()=>{if(registration.active)describe();});}
|
|
69
|
+
registration.addEventListener('updatefound',watch);watch();
|
|
70
|
+
const installing=registration.installing||registration.waiting;
|
|
71
|
+
if(!registration.active&&installing&&installing.state!=='activated')await new Promise((resolve,reject)=>{
|
|
72
|
+
function changed(){if(installing.state==='activated')resolve();if(installing.state==='redundant')reject(new Error('Offline installation failed.'));}
|
|
73
|
+
installing.addEventListener('statechange',changed);changed();
|
|
74
|
+
});
|
|
75
|
+
await navigator.serviceWorker.ready;describe();
|
|
76
|
+
}
|
|
77
|
+
prepareOffline().catch(error=>{byId('offline').textContent='Offline unavailable: '+error.message;});
|
|
78
|
+
try{
|
|
79
|
+
config=JSON.parse(await verified('./__CONFIG__','__CONFIG_SHA__',65536));
|
|
80
|
+
const descriptions={'classes-source/1':'Language profile: classes-source/1. Supports the core subset plus classes, inheritance, attributes, methods, private names, descriptors, properties, decorators, callable objects, length/truth, repr/str, integer indices and item/slice access and mutation, iteration and containment, equality and hashing. Ranges, list/tuple construction and all/any support adopted user protocols; user length hints are a later stage. Functions support computed/mutable defaults, global/nonlocal state, variadic parameters and starred calls. Assertions, assignment expressions, lambdas, unpacking targets and starred sequence/dictionary displays are available. Finite sets, bytes, bytearrays and memoryviews, with strict UTF-8/ASCII/Latin-1 codecs, are available in both profiles. Bytearray resizing, buffer casts and native buffers are later stages. Numeric operators, helpers and real/complex values are available in both profiles; numeric conversion and abs/round hooks use class type lookup. Generators, yield from, send/throw/close and scoped comprehensions are available. Attribute reflection and arithmetic/reflected/in-place hooks use ordinary class descriptors. Owned construction, super, expanded class headers, prepared mapping namespaces, callable metaclass factories, custom MRO and actual-metaclass special protocols are available. Type relations accept nested tuples of adopted types. Type hierarchies can be inspected with mro() and primary-base attributes; adopted native descriptors expose their declaring types. Owned instance attribute hooks and advertised class identities are available. Metaclass and ordinary checker custom instance/subclass checks use owned descriptors and truth conversion; native type defaults retain actual ancestry. Builtin instance subclasses and storage layouts are later stages. Rich ordering methods and bounded list/tuple/slice comparisons are available. Properties support accessor copies and explicit function binding is available. Bounded compile, eval and exec share execution limits; dynamic imports use only the granted module registry. Stable object IDs, optimized function and generator-expression namespace snapshots and custom vars/dir hooks are available. Custom directories support length hints and stable rich ordering. Inlined list/dict/set comprehensions expose enclosing function snapshots or isolated module/class snapshots. Live namespace mappings and default directories are later stages. Float/container/default-object formatting and async are later stages.',
|
|
81
|
+
'core-source/1':'Language profile: core-source/1. Supports values, loops, functions with computed/mutable defaults, global/nonlocal state, variadic parameters and starred calls, assertions, assignment expressions, lambdas, unpacking targets and starred sequence/dictionary displays, exceptions, primitive repr/str, ranges, primitive list/tuple construction, all/any, numeric operators/helpers and real/complex values. Finite sets, bytes, bytearrays and memoryviews, with strict UTF-8/ASCII/Latin-1 codecs, are available. Bytearray resizing, buffer casts and native buffers are later stages. Generators, yield from, send/throw/close and scoped comprehensions are available. Classes require the explicit class profile; async and external packages are later stages.'};
|
|
82
|
+
if(!Object.hasOwn(descriptions,config.application.engine.language_profile))throw new Error('Source language profile is unavailable.');
|
|
83
|
+
byId('language').textContent=descriptions[config.application.engine.language_profile];
|
|
84
|
+
config.library_sources=[];
|
|
85
|
+
for(const module of config.libraries){config.library_sources.push({name:module.name,package:module.package,imports:module.imports,
|
|
86
|
+
source:await verified('./'+module.source.path,module.source.sha256,module.source.size_bytes),
|
|
87
|
+
notice:await verified('./'+module.notice.path,module.notice.sha256,module.notice.size_bytes)});}
|
|
88
|
+
byId('libraries').textContent='Library profile: '+config.library_profile+'. Host profile: '+config.host_profile+'.';
|
|
89
|
+
byId('input').value=await verified('./'+config.source.path,config.source.sha256,65536);
|
|
90
|
+
start();
|
|
91
|
+
}catch(error){showError(error);}
|
|
92
|
+
'''
|
|
93
|
+
|
|
94
|
+
SERVICE_WORKER = '''const RECORDS=__RECORDS__;
|
|
95
|
+
const FILES=[...RECORDS.map(record=>record.path),'service-worker.js','POCKET-PYTHON.json'];
|
|
96
|
+
const PREFIX='pocket-python:'+self.registration.scope+':';
|
|
97
|
+
const CACHE=PREFIX+'__VERSION__';
|
|
98
|
+
self.addEventListener('install',event=>{
|
|
99
|
+
const requests=RECORDS.map(record=>new Request(new URL(record.path,self.registration.scope),{
|
|
100
|
+
cache:'reload',integrity:'sha256-'+btoa(String.fromCharCode(...record.sha256.match(/../g).map(hex=>parseInt(hex,16))))}));
|
|
101
|
+
requests.push(...['service-worker.js','POCKET-PYTHON.json'].map(path=>new Request(new URL(path,self.registration.scope),{cache:'reload'})));
|
|
102
|
+
// Install the complete verified graph. Keep the previous version until every
|
|
103
|
+
// old app tab/window has closed; never switch a running session mid-graph.
|
|
104
|
+
event.waitUntil(caches.open(CACHE).then(cache=>cache.addAll(requests)));
|
|
105
|
+
});
|
|
106
|
+
self.addEventListener('activate',event=>{
|
|
107
|
+
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()));
|
|
108
|
+
});
|
|
109
|
+
self.addEventListener('fetch',event=>{
|
|
110
|
+
const url=new URL(event.request.url),scope=new URL(self.registration.scope);
|
|
111
|
+
if(event.request.method!=='GET'||url.origin!==scope.origin||!url.href.startsWith(scope.href))return;
|
|
112
|
+
event.respondWith((async()=>{
|
|
113
|
+
const path=url.pathname===scope.pathname?'index.html':decodeURI(url.pathname.slice(scope.pathname.length));
|
|
114
|
+
if(url.search||!FILES.includes(path))return new Response('Not found',{status:404});
|
|
115
|
+
const cache=await caches.open(CACHE),key=new URL(path,scope).href;
|
|
116
|
+
return(await cache.match(key))||new Response('Offline asset missing; reinstall this application.',{status:503});
|
|
117
|
+
})());
|
|
118
|
+
});
|
|
119
|
+
'''
|
echidnae/python/py.typed
ADDED
|
File without changes
|
|
@@ -0,0 +1,140 @@
|
|
|
1
|
+
"""Local-asset browser shell and MicroPython worker templates."""
|
|
2
|
+
|
|
3
|
+
PAGE = '''<!doctype html>
|
|
4
|
+
<html lang="en">
|
|
5
|
+
<meta charset="utf-8">
|
|
6
|
+
<meta name="viewport" content="width=device-width,initial-scale=1">
|
|
7
|
+
<meta name="theme-color" content="#213b45">
|
|
8
|
+
<link rel="manifest" href="./manifest.webmanifest">
|
|
9
|
+
<link rel="icon" href="./icon.svg" type="image/svg+xml">
|
|
10
|
+
<title>{title}</title>
|
|
11
|
+
<style>
|
|
12
|
+
:root {{ color-scheme: light dark; font: 17px/1.6 system-ui,sans-serif; }}
|
|
13
|
+
body {{ max-width: 52rem; margin: 8vh auto; padding: 0 1.5rem; }}
|
|
14
|
+
h1 {{ line-height: 1.2; }}
|
|
15
|
+
button {{ font: inherit; padding: .35rem 1rem; margin-right: .5rem; cursor: pointer; }}
|
|
16
|
+
pre {{ min-height: 10rem; padding: 1.25rem; border: 1px solid #789; border-radius: .5rem; white-space: pre-wrap; overflow-wrap: anywhere; }}
|
|
17
|
+
small {{ display: block; margin-top: 1rem; }}
|
|
18
|
+
</style>
|
|
19
|
+
<main>
|
|
20
|
+
<h1>{title}</h1>
|
|
21
|
+
<p>Python runs on your device.</p>
|
|
22
|
+
<p id="status" role="status">Ready</p>
|
|
23
|
+
<button id="run" type="button">Run</button><button id="stop" type="button" disabled>Stop</button>
|
|
24
|
+
<pre id="output" aria-label="Python output"></pre>
|
|
25
|
+
<small id="offline" role="status">Preparing offline files…</small>
|
|
26
|
+
</main>
|
|
27
|
+
<script type="module" src="./app.js"></script>
|
|
28
|
+
</html>
|
|
29
|
+
'''
|
|
30
|
+
|
|
31
|
+
APP = '''const output = document.querySelector("#output");
|
|
32
|
+
const status = document.querySelector("#status");
|
|
33
|
+
const run = document.querySelector("#run");
|
|
34
|
+
const stop = document.querySelector("#stop");
|
|
35
|
+
const offline = document.querySelector("#offline");
|
|
36
|
+
let worker;
|
|
37
|
+
function finish(message) {
|
|
38
|
+
if (worker) worker.terminate();
|
|
39
|
+
worker = undefined;
|
|
40
|
+
run.disabled = false;
|
|
41
|
+
stop.disabled = true;
|
|
42
|
+
status.textContent = message;
|
|
43
|
+
}
|
|
44
|
+
function start() {
|
|
45
|
+
if (worker) worker.terminate();
|
|
46
|
+
output.textContent = "";
|
|
47
|
+
status.textContent = "Running…";
|
|
48
|
+
run.disabled = true;
|
|
49
|
+
stop.disabled = false;
|
|
50
|
+
worker = new Worker(new URL("./worker.js", import.meta.url), {type: "module"});
|
|
51
|
+
worker.onmessage = ({data}) => {
|
|
52
|
+
if (data.type === "stdout" || data.type === "stderr") output.textContent += data.text;
|
|
53
|
+
if (data.type === "error") { output.textContent += "\\n" + data.text; finish("Error"); }
|
|
54
|
+
if (data.type === "done") finish("Finished");
|
|
55
|
+
};
|
|
56
|
+
worker.onerror = (event) => { output.textContent += "\\n" + event.message; finish("Error"); };
|
|
57
|
+
worker.postMessage({type: "run"});
|
|
58
|
+
}
|
|
59
|
+
run.addEventListener("click", start);
|
|
60
|
+
stop.addEventListener("click", () => finish("Stopped"));
|
|
61
|
+
async function prepareOffline() {
|
|
62
|
+
if (!("serviceWorker" in navigator)) throw new Error("Service workers require HTTPS or localhost.");
|
|
63
|
+
const registration = await navigator.serviceWorker.register(new URL("./service-worker.js", import.meta.url), {scope: "./"});
|
|
64
|
+
const installing = registration.installing || registration.waiting;
|
|
65
|
+
if (installing && installing.state !== "activated") {
|
|
66
|
+
await new Promise((resolve, reject) => {
|
|
67
|
+
function changed() {
|
|
68
|
+
if (installing.state === "activated") resolve();
|
|
69
|
+
if (installing.state === "redundant") reject(new Error("Offline installation failed."));
|
|
70
|
+
}
|
|
71
|
+
installing.addEventListener("statechange", changed);
|
|
72
|
+
changed();
|
|
73
|
+
});
|
|
74
|
+
}
|
|
75
|
+
await navigator.serviceWorker.ready;
|
|
76
|
+
offline.textContent = "Offline ready on this device";
|
|
77
|
+
}
|
|
78
|
+
prepareOffline().catch(error => { offline.textContent = "Offline unavailable: " + error.message; });
|
|
79
|
+
start();
|
|
80
|
+
'''
|
|
81
|
+
|
|
82
|
+
WORKER = '''import {loadMicroPython} from "./runtime/micropython.mjs";
|
|
83
|
+
let started = false;
|
|
84
|
+
async function get(path) {
|
|
85
|
+
const url = new URL(path.split("/").map(encodeURIComponent).join("/"), import.meta.url);
|
|
86
|
+
const response = await fetch(url);
|
|
87
|
+
if (!response.ok) throw new Error("Could not load " + path + ": " + response.status);
|
|
88
|
+
return response;
|
|
89
|
+
}
|
|
90
|
+
self.onmessage = async ({data}) => {
|
|
91
|
+
if (started || data.type !== "run") return;
|
|
92
|
+
started = true;
|
|
93
|
+
const stdout = new TextDecoder();
|
|
94
|
+
const stderr = new TextDecoder();
|
|
95
|
+
try {
|
|
96
|
+
const config = await (await get("app-config.json")).json();
|
|
97
|
+
const mp = await loadMicroPython({
|
|
98
|
+
url: new URL("./runtime/micropython.wasm", import.meta.url).href,
|
|
99
|
+
linebuffer: false,
|
|
100
|
+
stdout: bytes => postMessage({type: "stdout", text: stdout.decode(bytes, {stream: true})}),
|
|
101
|
+
stderr: bytes => postMessage({type: "stderr", text: stderr.decode(bytes, {stream: true})})
|
|
102
|
+
});
|
|
103
|
+
let entry;
|
|
104
|
+
for (const source of config.sources) {
|
|
105
|
+
const bytes = new Uint8Array(await (await get(source.url)).arrayBuffer());
|
|
106
|
+
const path = "/app/" + source.path;
|
|
107
|
+
mp.FS.mkdirTree(path.slice(0, path.lastIndexOf("/")));
|
|
108
|
+
mp.FS.writeFile(path, bytes);
|
|
109
|
+
if (source.path === config.entrypoint) entry = new TextDecoder("utf-8", {fatal: true}).decode(bytes);
|
|
110
|
+
}
|
|
111
|
+
if (entry === undefined) throw new Error("Application entrypoint is missing.");
|
|
112
|
+
mp.globals.set("__file__", "/app/" + config.entrypoint);
|
|
113
|
+
mp.runPython("import sys\\nsys.path.insert(0, '/app')\\n");
|
|
114
|
+
mp.runPython(entry);
|
|
115
|
+
postMessage({type: "stdout", text: stdout.decode()});
|
|
116
|
+
postMessage({type: "stderr", text: stderr.decode()});
|
|
117
|
+
postMessage({type: "done"});
|
|
118
|
+
} catch (error) {
|
|
119
|
+
postMessage({type: "error", text: (error.type || error.name || "Error") + ": " + error.message});
|
|
120
|
+
}
|
|
121
|
+
};
|
|
122
|
+
'''
|
|
123
|
+
|
|
124
|
+
SERVICE_WORKER = '''const FILES = __FILES__;
|
|
125
|
+
const PREFIX = "pocket-python:" + self.registration.scope + ":";
|
|
126
|
+
const CACHE = PREFIX + "__VERSION__";
|
|
127
|
+
self.addEventListener("install", event => {
|
|
128
|
+
event.waitUntil(caches.open(CACHE).then(cache => cache.addAll(FILES.map(path => new URL(path, self.registration.scope).href))).then(() => self.skipWaiting()));
|
|
129
|
+
});
|
|
130
|
+
self.addEventListener("activate", event => {
|
|
131
|
+
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()));
|
|
132
|
+
});
|
|
133
|
+
self.addEventListener("fetch", event => {
|
|
134
|
+
const url = new URL(event.request.url);
|
|
135
|
+
if (event.request.method !== "GET" || url.origin !== self.location.origin || !url.href.startsWith(self.registration.scope)) return;
|
|
136
|
+
event.respondWith(caches.open(CACHE).then(async cache => (await cache.match(event.request)) || fetch(event.request)));
|
|
137
|
+
});
|
|
138
|
+
'''
|
|
139
|
+
|
|
140
|
+
ICON = '''<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 192 192"><rect width="192" height="192" rx="40" fill="#213b45"/><path d="M57 49h48a30 30 0 0 1 0 60H81v34H57zM81 73v12h24a6 6 0 0 0 0-12z" fill="#f4da8b"/></svg>'''
|
echidnae/python/web.py
ADDED
|
@@ -0,0 +1,134 @@
|
|
|
1
|
+
"""Assemble verified sources and a local MicroPython runtime as a PWA."""
|
|
2
|
+
|
|
3
|
+
import hashlib
|
|
4
|
+
import html
|
|
5
|
+
import json
|
|
6
|
+
import os
|
|
7
|
+
from pathlib import Path
|
|
8
|
+
import tempfile
|
|
9
|
+
|
|
10
|
+
from echidnae.python import __version__
|
|
11
|
+
from echidnae.python.assets import ArtifactError, RuntimeAssets, check_names, file_record, json_bytes, json_object
|
|
12
|
+
from echidnae.python.bundles import SourceBundle
|
|
13
|
+
from echidnae.python.templates import APP, ICON, PAGE, SERVICE_WORKER, WORKER
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
def _publish(destination: Path, files: dict[str, bytes]):
|
|
17
|
+
check_names(files)
|
|
18
|
+
destination.parent.mkdir(parents=True, exist_ok=True)
|
|
19
|
+
with tempfile.TemporaryDirectory(prefix=".pocket-python-", dir=destination.parent) as temporary:
|
|
20
|
+
stage = Path(temporary)
|
|
21
|
+
for name, content in files.items():
|
|
22
|
+
path = stage / name
|
|
23
|
+
path.parent.mkdir(parents=True, exist_ok=True)
|
|
24
|
+
path.write_bytes(content)
|
|
25
|
+
destination.mkdir()
|
|
26
|
+
written, directories = [], {destination}
|
|
27
|
+
try:
|
|
28
|
+
for name in sorted(files):
|
|
29
|
+
path = destination / name
|
|
30
|
+
parents = []
|
|
31
|
+
parent = path.parent
|
|
32
|
+
while parent != destination:
|
|
33
|
+
parents.append(parent)
|
|
34
|
+
parent = parent.parent
|
|
35
|
+
for parent in reversed(parents):
|
|
36
|
+
if parent not in directories:
|
|
37
|
+
parent.mkdir()
|
|
38
|
+
directories.add(parent)
|
|
39
|
+
os.link(stage / name, path)
|
|
40
|
+
written.append(path)
|
|
41
|
+
except BaseException:
|
|
42
|
+
for path in reversed(written):
|
|
43
|
+
path.unlink(missing_ok=True)
|
|
44
|
+
for path in sorted(directories, key=lambda p: len(p.parts), reverse=True):
|
|
45
|
+
try:
|
|
46
|
+
path.rmdir()
|
|
47
|
+
except OSError:
|
|
48
|
+
pass
|
|
49
|
+
raise
|
|
50
|
+
|
|
51
|
+
|
|
52
|
+
def build_web(bundle: SourceBundle, runtime: RuntimeAssets, output: str | Path, *, title: str = "Echidnae Python") -> dict:
|
|
53
|
+
if json_object(bundle.files["SHIMIFY-MANIFEST.json"]) != bundle.manifest:
|
|
54
|
+
raise ArtifactError("Source manifest snapshot changed after validation.")
|
|
55
|
+
for records, snapshot, extra in [
|
|
56
|
+
(bundle.manifest["files"], bundle.files, {"SHIMIFY-MANIFEST.json"}),
|
|
57
|
+
(runtime.lock["files"], runtime.files, set()),
|
|
58
|
+
]:
|
|
59
|
+
if set(snapshot) != {record["path"] for record in records} | extra:
|
|
60
|
+
raise ArtifactError("Snapshot files changed after validation.")
|
|
61
|
+
for record in records:
|
|
62
|
+
if file_record(record["path"], snapshot[record["path"]]) != {key: record[key] for key in ["path", "sha256", "size_bytes"]}:
|
|
63
|
+
raise ArtifactError("Snapshot hash or size changed after validation.")
|
|
64
|
+
requested = Path(output).absolute()
|
|
65
|
+
if requested.exists() or requested.is_symlink():
|
|
66
|
+
raise ArtifactError("Output already exists; choose a new directory.")
|
|
67
|
+
destination = requested.resolve()
|
|
68
|
+
for root in [bundle.root.resolve(), runtime.root.resolve()]:
|
|
69
|
+
if destination.is_relative_to(root) or root.is_relative_to(destination):
|
|
70
|
+
raise ArtifactError("Output overlaps an input root.")
|
|
71
|
+
if not isinstance(title, str) or not title.strip():
|
|
72
|
+
raise ArtifactError("Application title must be nonempty.")
|
|
73
|
+
sources = []
|
|
74
|
+
for source in bundle.manifest["sources"]:
|
|
75
|
+
name = source["output"]
|
|
76
|
+
try:
|
|
77
|
+
bundle.files[name].decode("utf-8")
|
|
78
|
+
except UnicodeError as error:
|
|
79
|
+
raise ArtifactError("The MicroPython profile requires UTF-8 application sources.") from error
|
|
80
|
+
sources.append({"path": name.removeprefix("_sources/"), "url": "application/" + name})
|
|
81
|
+
files = {"application/" + name: data for name, data in bundle.files.items()}
|
|
82
|
+
files.update({"runtime/" + name: data for name, data in runtime.files.items()})
|
|
83
|
+
files["runtime-lock.json"] = json_bytes(runtime.lock)
|
|
84
|
+
files["index.html"] = PAGE.format(title=html.escape(title, quote=True)).encode()
|
|
85
|
+
files["app.js"] = APP.encode()
|
|
86
|
+
files["worker.js"] = WORKER.encode()
|
|
87
|
+
files["icon.svg"] = ICON.encode()
|
|
88
|
+
files["app-config.json"] = json_bytes({"entrypoint": bundle.manifest["entrypoint"].removeprefix("_sources/"), "sources": sorted(sources, key=lambda s: s["path"])})
|
|
89
|
+
files["manifest.webmanifest"] = json_bytes({
|
|
90
|
+
"name": title, "short_name": title[:24], "id": "./", "start_url": "./", "scope": "./",
|
|
91
|
+
"display": "standalone", "theme_color": "#213b45", "background_color": "#213b45",
|
|
92
|
+
"icons": [{"src": "./icon.svg", "sizes": "any", "type": "image/svg+xml", "purpose": "any maskable"}],
|
|
93
|
+
})
|
|
94
|
+
records = [file_record(name, content) for name, content in sorted(files.items())]
|
|
95
|
+
cache_version = hashlib.sha256(json_bytes({"files": records})).hexdigest()
|
|
96
|
+
precache = ["./", *sorted(files), "service-worker.js", "POCKET-PYTHON.json"]
|
|
97
|
+
files["service-worker.js"] = SERVICE_WORKER.replace("__FILES__", json.dumps(precache)).replace("__VERSION__", cache_version).encode()
|
|
98
|
+
manifest = {
|
|
99
|
+
"schema_version": 1,
|
|
100
|
+
"kind": "pocket-python-web",
|
|
101
|
+
"pocket_python_version": __version__,
|
|
102
|
+
"title": title,
|
|
103
|
+
"entrypoint": "index.html",
|
|
104
|
+
"runtime": {key: runtime.lock[key] for key in ["implementation", "version", "source_url", "license_files"]},
|
|
105
|
+
"source_bundle": "application/SHIMIFY-MANIFEST.json",
|
|
106
|
+
"runtime_lock": "runtime-lock.json",
|
|
107
|
+
"cache_version": cache_version,
|
|
108
|
+
"size": {
|
|
109
|
+
"application_source_bytes": bundle.report()["source_size_bytes"],
|
|
110
|
+
"source_bundle_bytes": sum(map(len, bundle.files.values())),
|
|
111
|
+
"runtime_asset_bytes": sum(map(len, runtime.files.values())),
|
|
112
|
+
"artifact_bytes": 0,
|
|
113
|
+
},
|
|
114
|
+
"files": [file_record(name, content) for name, content in sorted(files.items())],
|
|
115
|
+
"direct_stdlib_modules": bundle.manifest["stdlib_modules"],
|
|
116
|
+
"limitations": [
|
|
117
|
+
"MicroPython compatibility must be tested for this application; CPython syntax and stdlib APIs may differ.",
|
|
118
|
+
"Supplied runtime assets are preserved, not automatically rebuilt or trimmed.",
|
|
119
|
+
"Offline use requires initial installation over HTTPS/localhost and retained browser cache.",
|
|
120
|
+
"License material is preserved; redistribution compliance is not certified.",
|
|
121
|
+
],
|
|
122
|
+
}
|
|
123
|
+
# The manifest excludes its own file hash, but its total byte count includes
|
|
124
|
+
# itself. Iterate until the decimal length of the total is stable.
|
|
125
|
+
payload_size = sum(map(len, files.values()))
|
|
126
|
+
while True:
|
|
127
|
+
content = json_bytes(manifest)
|
|
128
|
+
total = payload_size + len(content)
|
|
129
|
+
if manifest["size"]["artifact_bytes"] == total:
|
|
130
|
+
break
|
|
131
|
+
manifest["size"]["artifact_bytes"] = total
|
|
132
|
+
files["POCKET-PYTHON.json"] = content
|
|
133
|
+
_publish(destination, files)
|
|
134
|
+
return manifest
|
|
@@ -0,0 +1,32 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: echidnae-python
|
|
3
|
+
Version: 0.3.0
|
|
4
|
+
Summary: Verified offline Python application assembly and runtime interfaces
|
|
5
|
+
Author: ellainng
|
|
6
|
+
Author-email: ellainng <299958882+ellainng@users.noreply.github.com>
|
|
7
|
+
License-Expression: MIT
|
|
8
|
+
License-File: LICENSE
|
|
9
|
+
Classifier: Development Status :: 3 - Alpha
|
|
10
|
+
Classifier: Programming Language :: Python :: 3.14
|
|
11
|
+
Requires-Python: >=3.14
|
|
12
|
+
Project-URL: Repository, https://github.com/wispsy/echidnae
|
|
13
|
+
Project-URL: Issues, https://github.com/wispsy/echidnae/issues
|
|
14
|
+
Description-Content-Type: text/markdown
|
|
15
|
+
|
|
16
|
+
# echidnae-python
|
|
17
|
+
|
|
18
|
+
Python 3.14+ tooling for assembling verified offline applications from explicit source and runtime assets. This is the Python interface; the independent JavaScript Python interpreter is distributed as `@echidnae/python` on npm.
|
|
19
|
+
|
|
20
|
+
```sh
|
|
21
|
+
python -m pip install echidnae-python==0.3.0
|
|
22
|
+
echidnae-python --help
|
|
23
|
+
```
|
|
24
|
+
|
|
25
|
+
```python
|
|
26
|
+
from echidnae.python.interpreter import build_interpreter, read_interpreter
|
|
27
|
+
from echidnae.python.compiled import build_compiled, read_client
|
|
28
|
+
```
|
|
29
|
+
|
|
30
|
+
Runtime assets are supplied explicitly. Compiled applications require `echidnae-javascript==0.3.0` as build tooling. No compiler, interpreter binary or network download is installed implicitly. Existing versioned artifact identifiers are retained for compatibility. See the [application guides](https://github.com/wispsy/echidnae/tree/main/docs) and [migration guide](https://github.com/wispsy/echidnae/blob/main/docs/migration.md).
|
|
31
|
+
|
|
32
|
+
The interpreter remains an alpha implementation with explicit language and library profiles; installation does not certify unrestricted Python or third-party package compatibility. MIT license.
|
|
@@ -0,0 +1,20 @@
|
|
|
1
|
+
echidnae/python/__init__.py,sha256=9EjgaoOQ7DoInu5em-tYrOWuo8z37vwHMbTtnU7oXu4,87
|
|
2
|
+
echidnae/python/__main__.py,sha256=YcOgMZmSTvXpIKN4K64-l43m58bma7cMQggumUosqIE,63
|
|
3
|
+
echidnae/python/_compiler_lock.py,sha256=OKzbrclndbbLcmcjHrs8cNRpwNDgS4rrmhtpidBcYMw,610
|
|
4
|
+
echidnae/python/_interpreter_lock.py,sha256=WAE9tQtblqnND8jsl4SsDgj2ddIw9E860BU3L0tdVwg,8033
|
|
5
|
+
echidnae/python/_library_lock.py,sha256=VNGiBuu4Px8F6zBUwQfkjP9g2GD8lLOT81ITQkj8j_A,718
|
|
6
|
+
echidnae/python/assets.py,sha256=nZO6G9ZkawqmxgiwaWpwd_T7_UZmc0u91Vzgc5J830c,6744
|
|
7
|
+
echidnae/python/bundles.py,sha256=IlSRx4TYoIYH7Jq4OjE9QwVwCxPsrk7pS4hLsFKz1NA,5046
|
|
8
|
+
echidnae/python/cli.py,sha256=KhLfTN8gTk14ka-KIbAE3ORvKKlz-Y6BGYHkX03W3Rw,5445
|
|
9
|
+
echidnae/python/compiled.py,sha256=jMmaqbhwY9tLEpx2S2yc9HJALyQ51dsp9B_z8icBkEc,16305
|
|
10
|
+
echidnae/python/compiled_templates.py,sha256=p-Ti1FRoMaAWhUt_RBA_5AFr72-yxBJfn6EU16iLgPc,5482
|
|
11
|
+
echidnae/python/interpreter.py,sha256=bX3Elw2oJt02Gw4jSBdKL6BgW8upj8J-inkBvAuzAXw,15431
|
|
12
|
+
echidnae/python/interpreter_templates.py,sha256=kYmXy-Hn6VArqL2Y0OqfxIywAvrwqWT4gbrOSNiTK4I,12588
|
|
13
|
+
echidnae/python/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
|
|
14
|
+
echidnae/python/templates.py,sha256=MDo3LVhhEbvvoNMmIHKSyZTzpCEiHKFuc9O1tC2kVMg,6342
|
|
15
|
+
echidnae/python/web.py,sha256=geJ-YjIEZK-9iZzWEoaTUtUEJo-8Rd33K2VguaNJdXE,6865
|
|
16
|
+
echidnae_python-0.3.0.dist-info/licenses/LICENSE,sha256=MJiaArfnOql8NJRA2TI9JIYDOoiis3Rh8xQruzBRXoU,1066
|
|
17
|
+
echidnae_python-0.3.0.dist-info/WHEEL,sha256=e4_1dyBeezi8ZjfxrZ3bnVOxFDa3ksqVqH0jTHkUZ3k,81
|
|
18
|
+
echidnae_python-0.3.0.dist-info/entry_points.txt,sha256=4wRejVJpwFTPxGTVWlwvQZNcFZ57DVoQbx2JCUxpsd4,62
|
|
19
|
+
echidnae_python-0.3.0.dist-info/METADATA,sha256=6fAQvAQHIeQDLx5CM7FEVTNWVPrcMYtgd2y5bCyRdH4,1662
|
|
20
|
+
echidnae_python-0.3.0.dist-info/RECORD,,
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 Ella Inng
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|