-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbootstrap.js
More file actions
283 lines (245 loc) · 9.71 KB
/
Copy pathbootstrap.js
File metadata and controls
283 lines (245 loc) · 9.71 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
// Wybthon demo template bootstrap.
//
// Loads Pyodide from CDN, installs `wybthon` from PyPI via micropip,
// fetches the app package listed in `app/manifest.json`, writes it into
// Pyodide's virtual filesystem, and runs `app.main.main()`.
//
// Designed to work as a static site on GitHub Pages with no server and no
// build step: every request is a plain GET against files in this repo or an
// allowlisted CDN. All URLs are relative, so the site works at the domain
// root *and* under a repository subpath (https://<user>.github.io/<repo>/).
//
// The Pyodide and Wybthon versions live in `config.json`, the single source
// of truth shared with local tooling (see tests/test_config.py).
const CONFIG_URL = "./config.json";
const APP_BASE = "./app";
const MANIFEST_URL = `${APP_BASE}/manifest.json`;
const APP_ROOT = "/app"; // mount point inside Pyodide's virtual FS
// ---------- Loading overlay ----------------------------------------------
const setStatus = (msg) => {
const el = document.getElementById("loading-status");
if (el) el.textContent = msg;
};
const setProgress = (fraction) => {
const el = document.getElementById("loading-bar");
if (el) el.style.width = `${Math.round(Math.min(1, Math.max(0, fraction)) * 100)}%`;
};
const fadeOutLoader = () => {
const el = document.getElementById("loading");
if (!el) return;
el.classList.add("fade-out");
setTimeout(() => {
if (el && el.parentNode) el.parentNode.removeChild(el);
}, 420);
};
// ---------- Python stdout / stderr capture -------------------------------
// Ring buffer of recent Python output. Mirrored to the devtools console and
// appended to the error overlay so failures ship their own context.
const PY_LOG_LIMIT = 300;
const pyLog = [];
window.__wybthonPyLog = pyLog;
function recordPyOutput(stream, line) {
pyLog.push(`[${stream}] ${line}`);
if (pyLog.length > PY_LOG_LIMIT) pyLog.splice(0, pyLog.length - PY_LOG_LIMIT);
if (stream === "stderr") {
console.warn("[py]", line);
} else {
console.log("[py]", line);
}
}
function recentPyOutput(maxLines = 40) {
if (pyLog.length === 0) return "";
const tail = pyLog.slice(-maxLines);
return `\n\n--- Recent Python output (last ${tail.length} lines) ---\n${tail.join("\n")}`;
}
// ---------- Error overlay -------------------------------------------------
let __overlay = null;
function showErrorOverlay(title, details, { retryable = true } = {}) {
try {
if (__overlay) {
__overlay.remove();
__overlay = null;
}
const overlay = document.createElement("div");
overlay.id = "wyb-error-overlay";
overlay.style.cssText = `
position: fixed; inset: 0; z-index: 2147483647;
background: rgba(8, 11, 20, 0.92);
color: #e8edf7;
overflow: auto; padding: 24px;
font-family: ui-monospace, SFMono-Regular, Menlo, Consolas, monospace;
font-size: 13px; line-height: 1.6;
backdrop-filter: blur(4px);
`;
const box = document.createElement("div");
box.style.cssText = `
max-width: 960px; margin: 0 auto;
background: #101625;
border: 1px solid #ff5d7a;
border-radius: 10px;
box-shadow: 0 24px 64px rgba(0,0,0,0.5);
padding: 20px 24px;
`;
const hdr = document.createElement("div");
hdr.style.cssText = "display:flex; align-items:center; justify-content:space-between; gap:12px; flex-wrap:wrap;";
const h = document.createElement("div");
h.textContent = title || "Error";
h.style.cssText = "font-weight:700; font-size:14px; color:#ff5d7a; letter-spacing:0.04em; text-transform:uppercase;";
hdr.appendChild(h);
const actions = document.createElement("div");
actions.style.cssText = "display:flex; gap:8px;";
const buttonCss = `
background: transparent; color: #e8edf7;
border: 1px solid #3a4664;
border-radius: 6px; padding: 6px 14px; cursor: pointer;
font: inherit;
`;
if (retryable) {
const retry = document.createElement("button");
retry.textContent = "Retry";
retry.style.cssText = buttonCss + "background:#16aee3; border-color:#16aee3; color:#06121f; font-weight:700;";
retry.onclick = () => window.location.reload();
actions.appendChild(retry);
}
const dismiss = document.createElement("button");
dismiss.textContent = "Dismiss";
dismiss.style.cssText = buttonCss;
dismiss.onclick = () => { try { overlay.remove(); } catch { /* noop */ } };
actions.appendChild(dismiss);
hdr.appendChild(actions);
const pre = document.createElement("pre");
pre.style.cssText = "white-space: pre-wrap; word-break: break-word; margin-top: 14px; color: #aeb9d4;";
pre.textContent = (details || "") + recentPyOutput();
const hint = document.createElement("div");
hint.style.cssText = "margin-top: 14px; color: #66708c; font-size: 12px;";
hint.textContent =
"Retry reloads the page. If the failure persists, check your network, then the pinned " +
"versions in config.json and the file list in app/manifest.json.";
box.appendChild(hdr);
box.appendChild(pre);
box.appendChild(hint);
overlay.appendChild(box);
document.body.appendChild(overlay);
__overlay = overlay;
} catch {
// The overlay is best-effort; never let it throw further.
}
}
window.addEventListener("error", (e) => {
try {
const msg = (e?.error && (e.error.stack || String(e.error))) || String(e?.message || "");
showErrorOverlay("JavaScript Error", msg);
} catch { /* noop */ }
});
window.addEventListener("unhandledrejection", (e) => {
try {
const reason = e?.reason;
showErrorOverlay("Unhandled Promise Rejection", String(reason?.stack || reason || "Unknown rejection"));
} catch { /* noop */ }
});
// ---------- Fetch helpers -------------------------------------------------
async function fetchJsonFresh(url) {
// Small, mutable files (config, manifest) are always fetched fresh; the
// files they point at are cache-busted by content hash instead.
const r = await fetch(url, { cache: "no-store" });
if (!r.ok) throw new Error(`Failed to fetch ${url}: ${r.status} ${r.statusText}`);
return r.json();
}
async function fetchText(url) {
const r = await fetch(url);
if (!r.ok) throw new Error(`Failed to fetch ${url}: ${r.status} ${r.statusText}`);
return r.text();
}
function ensureDirs(pyodide, mountRoot, relPaths) {
const dirs = new Set([mountRoot]);
for (const rel of relPaths) {
const parts = rel.split("/");
for (let i = 1; i < parts.length; i++) {
dirs.add(`${mountRoot}/${parts.slice(0, i).join("/")}`);
}
}
for (const d of [...dirs].sort()) {
try { pyodide.FS.mkdir(d); } catch { /* already exists */ }
}
}
// ---------- Boot ----------------------------------------------------------
async function bootstrap() {
try {
setStatus("Reading configuration…");
setProgress(0.02);
const config = await fetchJsonFresh(CONFIG_URL);
const pyodideVersion = config?.pyodideVersion;
const wybthonVersion = config?.wybthonVersion;
if (!pyodideVersion || !wybthonVersion) {
throw new Error("config.json must define pyodideVersion and wybthonVersion.");
}
const pyodideBaseUrl = `https://cdn.jsdelivr.net/pyodide/v${pyodideVersion}/full/`;
const wybthonSpec = `wybthon==${wybthonVersion}`;
setStatus(`Loading Pyodide ${pyodideVersion}…`);
setProgress(0.08);
const { loadPyodide } = await import(`${pyodideBaseUrl}pyodide.mjs`);
const pyodide = await loadPyodide({
indexURL: pyodideBaseUrl,
stdout: (line) => recordPyOutput("stdout", line),
stderr: (line) => recordPyOutput("stderr", line),
});
window.__pyodide = pyodide; // handy for debugging from the devtools console
setProgress(0.5);
setStatus(`Installing ${wybthonSpec} from PyPI…`);
await pyodide.loadPackage("micropip");
await pyodide.runPythonAsync(`
import micropip
await micropip.install("${wybthonSpec}")
import wybthon # noqa: F401 (fail fast if the install went sideways)
`);
setProgress(0.72);
setStatus("Loading app modules…");
const manifest = await fetchJsonFresh(MANIFEST_URL);
const entries = manifest?.files;
if (!Array.isArray(entries) || entries.length === 0) {
throw new Error(
`App manifest at ${MANIFEST_URL} is empty or malformed. ` +
"Run `uv run python tools/build_manifest.py` and commit the result."
);
}
ensureDirs(pyodide, APP_ROOT, entries.map((e) => e.path));
let loaded = 0;
await Promise.all(entries.map(async ({ path, hash }) => {
// Content-based cache busting: the URL changes only when the file does,
// so browsers can cache aggressively yet never serve stale modules.
const url = `${APP_BASE}/${path}?v=${hash}`;
const text = await fetchText(url);
pyodide.FS.writeFile(`${APP_ROOT}/${path}`, new TextEncoder().encode(text));
loaded += 1;
setStatus(`Loading app modules… ${loaded}/${entries.length}`);
setProgress(0.72 + 0.2 * (loaded / entries.length));
}));
setStatus("Starting app…");
setProgress(0.95);
await pyodide.runPythonAsync(`
import sys
if "/" not in sys.path:
sys.path.insert(0, "/")
from app.main import main
await main()
`);
setProgress(1);
fadeOutLoader();
console.log(
`[wybthon-demo] Ready: Pyodide ${pyodideVersion}, ${wybthonSpec}, ` +
`${entries.length} app modules loaded.`
);
} catch (err) {
console.error("[wybthon-demo] Bootstrap failed:", err);
setStatus("Boot failed; see the overlay for details.");
const msg = err && (err.message || err.stack)
? `${err.message || ""}\n${err.stack || ""}`
: String(err);
showErrorOverlay("Bootstrap Failure", msg);
}
}
if (document.readyState === "loading") {
document.addEventListener("DOMContentLoaded", bootstrap);
} else {
bootstrap();
}