diff --git a/demo.html b/demo.html index 574ab06..9551532 100644 --- a/demo.html +++ b/demo.html @@ -29,6 +29,11 @@

Pytml Demos

Greeting

Use browser input and Python to build a tiny interactive page.

Open demo →

Joystick

Pointer/touch joystick controls exposed to Python.

Open demo →

Packages

Install Python packages through micropip and use them in the browser.

Open demo →
+

Game Starter

Move a player with keyboard, gamepad or on-screen D-pad using one set of controls.

Open demo →
+

Space Shooter

A complete tiny game: game loop, sound effects, touch controls, pause and saved high scores.

Open demo →
+

Gamepad Tester

Live buttons, sticks and rumble for any connected controller.

Open demo →
+

Sound Lab

Built-in retro sound effects and a tone generator. No audio files needed.

Open demo →
+

Sprite Animation

Sprite sheets, animation and crisp pixel-art rendering on a canvas.

Open demo →
diff --git a/dist/pytml.js b/dist/pytml.js index 035bd10..7d0d5df 100644 --- a/dist/pytml.js +++ b/dist/pytml.js @@ -1,14 +1,17 @@ /* - * Pytml 2.5.1 + * Pytml 2.6.0 * Python + HTML, powered by Pyodide. * - * Pytml 2.5 includes a lightweight inline UI preprocessor for blocks. + * Pytml 2.6 adds a persistent Pyodide cache (Cache Storage API) and the + * Pytml Game Kit (game loop, keyboard/gamepad/touch input, canvas, sprites, + * sound, collisions, save games). The Game Kit is loaded lazily, so pages + * that do not use it pay nothing. * The full document/language compiler remains planned for v3.0. */ (function (global) { 'use strict'; - const VERSION = '2.5.1'; + const VERSION = '2.6.0'; const PYODIDE_VERSION = '314.0.7'; const PYODIDE_INDEX = `https://cdn.jsdelivr.net/pyodide/v${PYODIDE_VERSION}/full/`; const PYODIDE_SCRIPT = `${PYODIDE_INDEX}pyodide.js`; @@ -16,6 +19,186 @@ const IS_FILE_PROTOCOL = typeof location !== 'undefined' && location.protocol === 'file:'; const PY_BLOCK = /^py(?:\d+)?$/i; + + // --- Configuration ------------------------------------------------------- + // Read from window.PytmlConfig (set before the script tag) and from data-* + // attributes on the + const SCRIPT_TAG = (typeof document !== 'undefined' && document.currentScript) || null; + const FALSE_WORDS = ['off', 'false', '0', 'no', 'none']; + + function readConfig() { + const cfg = Object.assign({}, (global.PytmlConfig && typeof global.PytmlConfig === 'object') ? global.PytmlConfig : {}); + for (const key of ['cache', 'persist', 'preload']) { + // Accept true/false as well as 'off', 'false', '0', 'no' written as strings. + if (typeof cfg[key] === 'string') cfg[key] = !FALSE_WORDS.includes(cfg[key].trim().toLowerCase()); + } + if (SCRIPT_TAG && SCRIPT_TAG.hasAttribute) { + const flag = (name) => { + if (!SCRIPT_TAG.hasAttribute(name)) return undefined; + return !FALSE_WORDS.includes(String(SCRIPT_TAG.getAttribute(name)).trim().toLowerCase()); + }; + for (const key of ['cache', 'persist', 'preload']) { + const value = flag(`data-${key}`); + if (value !== undefined) cfg[key] = value; + } + } + return cfg; + } + const CONFIG = readConfig(); + + // --- Persistent Pyodide cache --------------------------------------------- + // Pyodide's big files (pyodide.asm.wasm, python_stdlib.zip, pyodide-lock.json + // and package wheels such as NumPy) are stored in the browser's Cache Storage + // the first time a page loads them, then served from disk afterwards. + // + // Browsers partition all storage and HTTP caches by top-level site, so a copy + // cached for site A can never be reused by site B. This cache therefore works + // per site: every page and every return visit on the same origin is instant + // after the first load. (Cookies are limited to ~4 KB and cannot hold Pyodide.) + const CACHE_PREFIX = 'pytml-pyodide-'; + const CACHE_NAME = `${CACHE_PREFIX}${PYODIDE_VERSION}`; + const CORE_FILES = ['pyodide-lock.json', 'python_stdlib.zip', 'pyodide.asm.wasm']; + const cacheStats = { hits: 0, misses: 0, stored: 0, errors: 0 }; + const pendingPuts = new Set(); + let _cachePrefixes = []; + let _fetchPatched = false; + let _cacheDisabled = false; + + function cacheSupported() { + try { + return typeof caches !== 'undefined' && typeof caches.open === 'function' && typeof Response !== 'undefined'; + } catch (_) { return false; } + } + + async function openPyodideCache() { + if (_cacheDisabled || !cacheSupported()) return null; + try { return await caches.open(CACHE_NAME); } + catch (_) { _cacheDisabled = true; return null; } // file://, sandboxed iframes, private modes + } + + function requestInfo(input, init) { + try { + const url = typeof input === 'string' ? input : (input && input.href) || (input && input.url) || ''; + const method = String((init && init.method) || (input && input.method) || 'GET').toUpperCase(); + let ranged = false; + const headers = (init && init.headers) || (input && input.headers); + if (headers) { + ranged = typeof headers.has === 'function' ? headers.has('range') + : Object.keys(headers).some((k) => k.toLowerCase() === 'range'); + } + return { url: String(url), method, ranged }; + } catch (_) { return { url: '', method: '', ranged: true }; } + } + + function installPyodideCache(indexURL) { + if (_cacheDisabled || !cacheSupported() || typeof global.fetch !== 'function') return false; + for (const prefix of [indexURL, PYODIDE_INDEX]) if (prefix && !_cachePrefixes.includes(prefix)) _cachePrefixes.push(prefix); + if (_fetchPatched) return true; + _fetchPatched = true; + const nativeFetch = global.fetch.bind(global); + + global.fetch = async function pytmlCachedFetch(input, init) { + const { url, method, ranged } = requestInfo(input, init); + // Only versioned Pyodide assets, never .mjs/.js loader scripts (those are + // loaded by import()/ +const SCRIPT_TAG = (typeof document !== 'undefined' && document.currentScript) || null; +const FALSE_WORDS = ['off', 'false', '0', 'no', 'none']; +function readConfig() { +const cfg = Object.assign({}, (global.PytmlConfig && typeof global.PytmlConfig === 'object') ? global.PytmlConfig : {}); +for (const key of ['cache', 'persist', 'preload']) { +// Accept true/false as well as 'off', 'false', '0', 'no' written as strings. +if (typeof cfg[key] === 'string') cfg[key] = !FALSE_WORDS.includes(cfg[key].trim().toLowerCase()); +} +if (SCRIPT_TAG && SCRIPT_TAG.hasAttribute) { +const flag = (name) => { +if (!SCRIPT_TAG.hasAttribute(name)) return undefined; +return !FALSE_WORDS.includes(String(SCRIPT_TAG.getAttribute(name)).trim().toLowerCase()); +}; +for (const key of ['cache', 'persist', 'preload']) { +const value = flag(`data-${key}`); +if (value !== undefined) cfg[key] = value; +} +} +return cfg; +} +const CONFIG = readConfig(); +// --- Persistent Pyodide cache --------------------------------------------- +// Pyodide's big files (pyodide.asm.wasm, python_stdlib.zip, pyodide-lock.json +// and package wheels such as NumPy) are stored in the browser's Cache Storage +// the first time a page loads them, then served from disk afterwards. +// +// Browsers partition all storage and HTTP caches by top-level site, so a copy +// cached for site A can never be reused by site B. This cache therefore works +// per site: every page and every return visit on the same origin is instant +// after the first load. (Cookies are limited to ~4 KB and cannot hold Pyodide.) +const CACHE_PREFIX = 'pytml-pyodide-'; +const CACHE_NAME = `${CACHE_PREFIX}${PYODIDE_VERSION}`; +const CORE_FILES = ['pyodide-lock.json', 'python_stdlib.zip', 'pyodide.asm.wasm']; +const cacheStats = { hits: 0, misses: 0, stored: 0, errors: 0 }; +const pendingPuts = new Set(); +let _cachePrefixes = []; +let _fetchPatched = false; +let _cacheDisabled = false; +function cacheSupported() { +try { +return typeof caches !== 'undefined' && typeof caches.open === 'function' && typeof Response !== 'undefined'; +} catch (_) { return false; } +} +async function openPyodideCache() { +if (_cacheDisabled || !cacheSupported()) return null; +try { return await caches.open(CACHE_NAME); } +catch (_) { _cacheDisabled = true; return null; } // file://, sandboxed iframes, private modes +} +function requestInfo(input, init) { +try { +const url = typeof input === 'string' ? input : (input && input.href) || (input && input.url) || ''; +const method = String((init && init.method) || (input && input.method) || 'GET').toUpperCase(); +let ranged = false; +const headers = (init && init.headers) || (input && input.headers); +if (headers) { +ranged = typeof headers.has === 'function' ? headers.has('range') +: Object.keys(headers).some((k) => k.toLowerCase() === 'range'); +} +return { url: String(url), method, ranged }; +} catch (_) { return { url: '', method: '', ranged: true }; } +} +function installPyodideCache(indexURL) { +if (_cacheDisabled || !cacheSupported() || typeof global.fetch !== 'function') return false; +for (const prefix of [indexURL, PYODIDE_INDEX]) if (prefix && !_cachePrefixes.includes(prefix)) _cachePrefixes.push(prefix); +if (_fetchPatched) return true; +_fetchPatched = true; +const nativeFetch = global.fetch.bind(global); +global.fetch = async function pytmlCachedFetch(input, init) { +const { url, method, ranged } = requestInfo(input, init); +// Only versioned Pyodide assets, never .mjs/.js loader scripts (those are +// loaded by import()/ + + + +

Gamepad Tester

+
Connect a controller and press any button.
+ + + + +from pytml import Canvas, loop, gamepad, connected_gamepads, on_gamepad_connected, on_gamepad_disconnected + +screen = Canvas("screen", 520, 300, fit=True) +BUTTONS = ["a", "b", "x", "y", "lb", "rb", "lt", "rt", "back", "start", "ls", "rs", "up", "down", "left", "right", "home"] +last = {"name": None} + + +def say(pad, state): + info.text = f"{state}: {pad.id}" + + +on_gamepad_connected(lambda pad: say(pad, "Connected")) +on_gamepad_disconnected(lambda pad: say(pad, "Disconnected")) + + +def buzz(event): + pads = connected_gamepads() + if pads and not pads[0].rumble(300): + info.text = "This browser/controller does not support rumble." + + +rumble.on("click", buzz) + + +def stick(cx, cy, vec, label): + screen.circle(cx, cy, 46, "#30363d", fill=False, line_width=2) + screen.circle(cx + vec[0] * 34, cy + vec[1] * 34, 11, "#4aa8ff") + screen.text(f"{vec[0]:+.2f}, {vec[1]:+.2f}", cx, cy + 58, "#8b949e", 12, align="center") + screen.text(label, cx, cy - 72, "#c9d1d9", 13, align="center") + + +@loop +def draw(dt): + screen.clear("#111827") + pads = connected_gamepads() + if not pads: + screen.text("No controller detected", 260, 150, "#8b949e", 18, align="center", baseline="middle") + return + pad = pads[0] + for i, name in enumerate(BUTTONS): + col, row = i % 9, i // 9 + x, y = 40 + col * 56, 24 + row * 44 + v = pad.button(name) + screen.rect(x, y, 48, 32, (74 + int(v * 100), 168, 255, 0.15 + v * 0.85)) + screen.text(name, x + 24, y + 16, "#fff", 12, align="center", baseline="middle") + if pad.pressed(name): + last["name"] = name + stick(150, 200, pad.left_stick, "Left stick") + stick(370, 200, pad.right_stick, "Right stick") + screen.text(f"Last pressed: {last['name'] or '-'}", 260, 280, "#8b949e", 13, align="center") + + +

← Back to demos

+ + diff --git a/examples/game-sound.html b/examples/game-sound.html new file mode 100644 index 0000000..5822d4e --- /dev/null +++ b/examples/game-sound.html @@ -0,0 +1,72 @@ + + + + + + Pytml Sound Lab + + + + +

Sound Lab

+

Retro sound effects built into Pytml. No audio files needed.

+ +
+ + + + +
+ +

Make your own

+ + + + + + + +
+ + +

+
+
+from pytml import sfx, beep, audio
+
+for name in sfx.names:
+    elements[f"b_{name}"].on("click", lambda e, n=name: sfx.play(n))
+
+
+def show(event=None):
+    pitch_v.text, slide_v.text, dur_v.text = pitch.value, slide.value, dur.value
+    code.text = f"beep({pitch.value}, {dur.value}, '{wave.value}', slide={slide.value})"
+
+
+def tone(event):
+    show()
+    beep(int(pitch.value), int(dur.value), wave.value, slide=int(slide.value))
+
+
+pitch.on("input", show)
+slide.on("input", show)
+dur.on("input", show)
+wave.on("change", show)
+play.on("click", tone)
+vol.on("input", lambda e: setattr(audio, "volume", int(vol.value) / 100))
+show()
+
+
+

← Back to demos

+ + diff --git a/examples/game-space-shooter.html b/examples/game-space-shooter.html new file mode 100644 index 0000000..ff11918 --- /dev/null +++ b/examples/game-space-shooter.html @@ -0,0 +1,165 @@ + + + + + + Pytml Space Shooter + + + + + +
+

Arrows / WASD move  ·  Space / gamepad A fires  ·  P pauses

+ + +import math +import random +from pytml import Canvas, loop, controls, dpad, touch_button, sfx, HighScores, Vec2, clamp, circle_overlap, vibrate + +W, H = 360, 480 +screen = Canvas("screen", W, H, fit=True) +dpad("dpad") +touch_button("fire", "FIRE") + +controls.use_defaults() +controls.bind("left", "touch:dpad.left") +controls.bind("right", "touch:dpad.right") +controls.bind("fire", "space", "z", "pad:a", "pad:rt", "touch:fire") + +scores = HighScores("pytml-space-shooter", limit=5) +stars = [[random.uniform(0, W), random.uniform(0, H), random.uniform(20, 90)] for _ in range(60)] +g = {} + + +def reset(): + g.update(state="play", paused=False, x=W / 2, cooldown=0.0, spawn=0.0, score=0, lives=3, + invuln=0.0, bullets=[], enemies=[], sparks=[], rank=None, time=0.0) + + +def explode(x, y, color, n=14): + for _ in range(n): + speed = random.uniform(40, 180) + g["sparks"].append([x, y, speed * random.uniform(-1, 1), speed * random.uniform(-1, 1), random.uniform(0.3, 0.7), color]) + + +def update(dt): + for st in stars: # parallax stars never stop + st[1] = (st[1] + st[2] * dt) % H + + if g["state"] == "over": + if controls.pressed("action") or controls.pressed("fire"): + reset() + return + if controls.pressed("pause"): + g["paused"] = not g["paused"] + if g["paused"]: + return + + g["time"] += dt + g["x"] = clamp(g["x"] + controls.axis("left", "right") * 230 * dt, 18, W - 18) + g["cooldown"] -= dt + g["invuln"] = max(0.0, g["invuln"] - dt) + + if controls.down("fire") and g["cooldown"] <= 0: + g["bullets"].append([g["x"], H - 56]) + g["cooldown"] = 0.17 + sfx.play("laser", 0.12) + + g["spawn"] -= dt + if g["spawn"] <= 0: + g["enemies"].append({"x": random.uniform(20, W - 20), "y": -20.0, "phase": random.uniform(0, 6.28), "dead": False}) + g["spawn"] = max(0.25, 0.9 - g["score"] / 900) + + speed = 70 + g["score"] / 8 + for b in g["bullets"]: + b[1] -= 440 * dt + for e in g["enemies"]: + e["y"] += speed * dt + e["x"] = clamp(e["x"] + math.sin(g["time"] * 2 + e["phase"]) * 60 * dt, 14, W - 14) + + for b in g["bullets"]: + for e in g["enemies"]: + if not e["dead"] and circle_overlap(b[0], b[1], 3, e["x"], e["y"], 14): + b[1] = -100 + e["dead"] = True + g["score"] += 10 + explode(e["x"], e["y"], "#ff9f43", 8) + sfx.play("hit", 0.15) + break + g["bullets"] = [b for b in g["bullets"] if b[1] > -20] + + alive = [] + for e in g["enemies"]: + if e["dead"]: + continue + if g["invuln"] <= 0 and circle_overlap(g["x"], H - 40, 12, e["x"], e["y"], 14): + explode(g["x"], H - 40, "#4aa8ff", 24) + sfx.play("explosion", 0.3) + vibrate(120) + g["invuln"] = 1.5 + g["lives"] -= 1 + elif e["y"] > H + 20: # got past the ship + sfx.play("error", 0.15) + g["lives"] -= 1 + else: + alive.append(e) + g["enemies"] = alive + + if g["lives"] <= 0: + g["state"] = "over" + g["rank"] = scores.submit(g["score"], "YOU") + sfx.play("lose", 0.25) + + for s in g["sparks"]: + s[0] += s[2] * dt + s[1] += s[3] * dt + s[4] -= dt + g["sparks"] = [s for s in g["sparks"] if s[4] > 0] + + +def draw(): + screen.clear("#05060a") + for sx, sy, sp in stars: + v = int(80 + sp) + screen.rect(sx, sy, 2, 2, (v, v, v + 40)) + for b in g["bullets"]: + screen.rect(b[0] - 1.5, b[1] - 8, 3, 12, "#7df9ff") + for e in g["enemies"]: + screen.circle(e["x"], e["y"], 14, "#e5484d") + screen.circle(e["x"] - 5, e["y"] - 2, 3, "#fff") + screen.circle(e["x"] + 5, e["y"] - 2, 3, "#fff") + for sx, sy, _, _, life, color in g["sparks"]: + screen.rect(sx, sy, 3, 3, color) + if g["state"] == "play" and (g["invuln"] <= 0 or int(g["time"] * 14) % 2): + x, y = g["x"], H - 40 + screen.polygon([(x, y - 18), (x + 14, y + 14), (x, y + 8), (x - 14, y + 14)], "#4aa8ff") + + screen.text(f"SCORE {g['score']}", 10, 8, "#e6edf3", 15, bold=True) + screen.text(f"BEST {scores.best or 0}", W / 2, 8, "#8b949e", 13, align="center") + screen.text("♥" * max(0, g["lives"]), W - 10, 8, "#e5484d", 15, align="right") + + if g["paused"]: + screen.text("PAUSED", W / 2, H / 2, "#fff", 28, align="center", baseline="middle", bold=True) + if g["state"] == "over": + screen.text("GAME OVER", W / 2, H / 2 - 40, "#fff", 30, align="center", baseline="middle", bold=True) + if g["rank"]: + screen.text(f"New high score! Rank #{g['rank']}", W / 2, H / 2, "#ffd166", 16, align="center", baseline="middle") + screen.text("Press Space / FIRE to play again", W / 2, H / 2 + 40, "#8b949e", 14, align="center", baseline="middle") + + +reset() +loop(update, render=draw) + + +

← Back to demos

+ + diff --git a/examples/game-sprites.html b/examples/game-sprites.html new file mode 100644 index 0000000..b1f9f51 --- /dev/null +++ b/examples/game-sprites.html @@ -0,0 +1,60 @@ + + + + + + Pytml Sprites + + + + +

Sprite Animation

+ +

Left / Right to walk. This sprite sheet is drawn in code; use await load_image("hero.png") for your own art.

+ + +from pytml import Canvas, SpriteSheet, Animation, loop, controls, clamp + +# --- build a 4-frame sprite sheet in code (16x16 per frame) ------------------- +sheet_canvas = Canvas.create(64, 16, hidpi=False) +for frame in range(4): + ox = frame * 16 + bob = (0, -1, 0, -1)[frame] + leg = (0, 3, 0, -3)[frame] + sheet_canvas.rect(ox + 4, 4 + bob, 8, 8, "#f6c177") # body + sheet_canvas.rect(ox + 5, 6 + bob, 2, 2, "#191724") # eyes + sheet_canvas.rect(ox + 9, 6 + bob, 2, 2, "#191724") + sheet_canvas.rect(ox + 4 + leg // 2, 12, 3, 3, "#eb6f92") # feet + sheet_canvas.rect(ox + 9 - leg // 2, 12, 3, 3, "#eb6f92") + +sheet = SpriteSheet(sheet_canvas, 16, 16) +walk = Animation(sheet, [0, 1, 2, 3], fps=8) +idle = Animation(sheet, [0], fps=1) + +screen = Canvas("screen", 320, 160, pixelated=True, fit=True) +controls.use_defaults() +x, facing_left = 150.0, False + + +@loop +def update(dt): + global x, facing_left + move = controls.axis("left", "right") + x = clamp(x + move * 90 * dt, 0, 320 - 64) + if move: + facing_left = move < 0 + anim = walk if move else idle + anim.update(dt) + + screen.clear("#1f1d2e") + screen.rect(0, 120, 320, 40, "#26233a") + anim.draw(screen, x, 56, 64, 64, flip_x=facing_left) # 4x scale, crisp pixels + + +

← Back to demos

+ + diff --git a/examples/game-starter.html b/examples/game-starter.html new file mode 100644 index 0000000..be775c0 --- /dev/null +++ b/examples/game-starter.html @@ -0,0 +1,64 @@ + + + + + + Pytml Game Starter + + + + +

Game Starter

+ +
+

Move: arrows / WASD / gamepad stick / on-screen D-pad  ·  Action: Space / gamepad A / on-screen button

+ + +from pytml import Canvas, loop, controls, dpad, touch_button, sfx, Vec2, clamp + +screen = Canvas("screen", 480, 320, fit=True) +dpad("dpad") +touch_button("jump", "A") + +# One set of actions, three kinds of input. +controls.use_defaults() +controls.bind("left", "touch:dpad.left") +controls.bind("right", "touch:dpad.right") +controls.bind("up", "touch:dpad.up") +controls.bind("down", "touch:dpad.down") +controls.bind("action", "touch:jump") + +player = Vec2(240, 160) +SPEED = 200 +pulse = 0.0 + + +@loop +def update(dt): + global player, pulse + player += controls.vector() * SPEED * dt # diagonals are not faster + player = Vec2(clamp(player.x, 16, 464), clamp(player.y, 16, 304)) + + if controls.pressed("action"): + sfx.play("coin") + pulse = 1.0 + pulse = max(0.0, pulse - dt * 3) + + screen.clear("#111827") + screen.circle(player.x, player.y, 16 + pulse * 18, (80, 170, 255, 0.25 + pulse * 0.4)) + screen.circle(player.x, player.y, 12, "#4aa8ff") + screen.text("Pytml Game Kit", 10, 8, "#8b949e", 14) + screen.text(f"{update.fps:.0f} fps", 470, 8, "#8b949e", 14, align="right") + + +

← Back to demos

+ + diff --git a/package.json b/package.json index 89ac05b..07acfb2 100644 --- a/package.json +++ b/package.json @@ -8,5 +8,14 @@ }, "dependencies": { "@upstash/redis": "^1.34.3" + }, + "scripts": { + "build": "node tools/build.mjs", + "test": "node --test tests/runtime.test.js", + "test:integration": "node tests/integration/run.mjs" + }, + "devDependencies": { + "jsdom": "^26.1.0", + "pyodide": "314.0.7" } } diff --git a/pytml.js b/pytml.js index 035bd10..7d0d5df 100644 --- a/pytml.js +++ b/pytml.js @@ -1,14 +1,17 @@ /* - * Pytml 2.5.1 + * Pytml 2.6.0 * Python + HTML, powered by Pyodide. * - * Pytml 2.5 includes a lightweight inline UI preprocessor for blocks. + * Pytml 2.6 adds a persistent Pyodide cache (Cache Storage API) and the + * Pytml Game Kit (game loop, keyboard/gamepad/touch input, canvas, sprites, + * sound, collisions, save games). The Game Kit is loaded lazily, so pages + * that do not use it pay nothing. * The full document/language compiler remains planned for v3.0. */ (function (global) { 'use strict'; - const VERSION = '2.5.1'; + const VERSION = '2.6.0'; const PYODIDE_VERSION = '314.0.7'; const PYODIDE_INDEX = `https://cdn.jsdelivr.net/pyodide/v${PYODIDE_VERSION}/full/`; const PYODIDE_SCRIPT = `${PYODIDE_INDEX}pyodide.js`; @@ -16,6 +19,186 @@ const IS_FILE_PROTOCOL = typeof location !== 'undefined' && location.protocol === 'file:'; const PY_BLOCK = /^py(?:\d+)?$/i; + + // --- Configuration ------------------------------------------------------- + // Read from window.PytmlConfig (set before the script tag) and from data-* + // attributes on the + const SCRIPT_TAG = (typeof document !== 'undefined' && document.currentScript) || null; + const FALSE_WORDS = ['off', 'false', '0', 'no', 'none']; + + function readConfig() { + const cfg = Object.assign({}, (global.PytmlConfig && typeof global.PytmlConfig === 'object') ? global.PytmlConfig : {}); + for (const key of ['cache', 'persist', 'preload']) { + // Accept true/false as well as 'off', 'false', '0', 'no' written as strings. + if (typeof cfg[key] === 'string') cfg[key] = !FALSE_WORDS.includes(cfg[key].trim().toLowerCase()); + } + if (SCRIPT_TAG && SCRIPT_TAG.hasAttribute) { + const flag = (name) => { + if (!SCRIPT_TAG.hasAttribute(name)) return undefined; + return !FALSE_WORDS.includes(String(SCRIPT_TAG.getAttribute(name)).trim().toLowerCase()); + }; + for (const key of ['cache', 'persist', 'preload']) { + const value = flag(`data-${key}`); + if (value !== undefined) cfg[key] = value; + } + } + return cfg; + } + const CONFIG = readConfig(); + + // --- Persistent Pyodide cache --------------------------------------------- + // Pyodide's big files (pyodide.asm.wasm, python_stdlib.zip, pyodide-lock.json + // and package wheels such as NumPy) are stored in the browser's Cache Storage + // the first time a page loads them, then served from disk afterwards. + // + // Browsers partition all storage and HTTP caches by top-level site, so a copy + // cached for site A can never be reused by site B. This cache therefore works + // per site: every page and every return visit on the same origin is instant + // after the first load. (Cookies are limited to ~4 KB and cannot hold Pyodide.) + const CACHE_PREFIX = 'pytml-pyodide-'; + const CACHE_NAME = `${CACHE_PREFIX}${PYODIDE_VERSION}`; + const CORE_FILES = ['pyodide-lock.json', 'python_stdlib.zip', 'pyodide.asm.wasm']; + const cacheStats = { hits: 0, misses: 0, stored: 0, errors: 0 }; + const pendingPuts = new Set(); + let _cachePrefixes = []; + let _fetchPatched = false; + let _cacheDisabled = false; + + function cacheSupported() { + try { + return typeof caches !== 'undefined' && typeof caches.open === 'function' && typeof Response !== 'undefined'; + } catch (_) { return false; } + } + + async function openPyodideCache() { + if (_cacheDisabled || !cacheSupported()) return null; + try { return await caches.open(CACHE_NAME); } + catch (_) { _cacheDisabled = true; return null; } // file://, sandboxed iframes, private modes + } + + function requestInfo(input, init) { + try { + const url = typeof input === 'string' ? input : (input && input.href) || (input && input.url) || ''; + const method = String((init && init.method) || (input && input.method) || 'GET').toUpperCase(); + let ranged = false; + const headers = (init && init.headers) || (input && input.headers); + if (headers) { + ranged = typeof headers.has === 'function' ? headers.has('range') + : Object.keys(headers).some((k) => k.toLowerCase() === 'range'); + } + return { url: String(url), method, ranged }; + } catch (_) { return { url: '', method: '', ranged: true }; } + } + + function installPyodideCache(indexURL) { + if (_cacheDisabled || !cacheSupported() || typeof global.fetch !== 'function') return false; + for (const prefix of [indexURL, PYODIDE_INDEX]) if (prefix && !_cachePrefixes.includes(prefix)) _cachePrefixes.push(prefix); + if (_fetchPatched) return true; + _fetchPatched = true; + const nativeFetch = global.fetch.bind(global); + + global.fetch = async function pytmlCachedFetch(input, init) { + const { url, method, ranged } = requestInfo(input, init); + // Only versioned Pyodide assets, never .mjs/.js loader scripts (those are + // loaded by import()/ +const SCRIPT_TAG = (typeof document !== 'undefined' && document.currentScript) || null; +const FALSE_WORDS = ['off', 'false', '0', 'no', 'none']; +function readConfig() { +const cfg = Object.assign({}, (global.PytmlConfig && typeof global.PytmlConfig === 'object') ? global.PytmlConfig : {}); +for (const key of ['cache', 'persist', 'preload']) { +// Accept true/false as well as 'off', 'false', '0', 'no' written as strings. +if (typeof cfg[key] === 'string') cfg[key] = !FALSE_WORDS.includes(cfg[key].trim().toLowerCase()); +} +if (SCRIPT_TAG && SCRIPT_TAG.hasAttribute) { +const flag = (name) => { +if (!SCRIPT_TAG.hasAttribute(name)) return undefined; +return !FALSE_WORDS.includes(String(SCRIPT_TAG.getAttribute(name)).trim().toLowerCase()); +}; +for (const key of ['cache', 'persist', 'preload']) { +const value = flag(`data-${key}`); +if (value !== undefined) cfg[key] = value; +} +} +return cfg; +} +const CONFIG = readConfig(); +// --- Persistent Pyodide cache --------------------------------------------- +// Pyodide's big files (pyodide.asm.wasm, python_stdlib.zip, pyodide-lock.json +// and package wheels such as NumPy) are stored in the browser's Cache Storage +// the first time a page loads them, then served from disk afterwards. +// +// Browsers partition all storage and HTTP caches by top-level site, so a copy +// cached for site A can never be reused by site B. This cache therefore works +// per site: every page and every return visit on the same origin is instant +// after the first load. (Cookies are limited to ~4 KB and cannot hold Pyodide.) +const CACHE_PREFIX = 'pytml-pyodide-'; +const CACHE_NAME = `${CACHE_PREFIX}${PYODIDE_VERSION}`; +const CORE_FILES = ['pyodide-lock.json', 'python_stdlib.zip', 'pyodide.asm.wasm']; +const cacheStats = { hits: 0, misses: 0, stored: 0, errors: 0 }; +const pendingPuts = new Set(); +let _cachePrefixes = []; +let _fetchPatched = false; +let _cacheDisabled = false; +function cacheSupported() { +try { +return typeof caches !== 'undefined' && typeof caches.open === 'function' && typeof Response !== 'undefined'; +} catch (_) { return false; } +} +async function openPyodideCache() { +if (_cacheDisabled || !cacheSupported()) return null; +try { return await caches.open(CACHE_NAME); } +catch (_) { _cacheDisabled = true; return null; } // file://, sandboxed iframes, private modes +} +function requestInfo(input, init) { +try { +const url = typeof input === 'string' ? input : (input && input.href) || (input && input.url) || ''; +const method = String((init && init.method) || (input && input.method) || 'GET').toUpperCase(); +let ranged = false; +const headers = (init && init.headers) || (input && input.headers); +if (headers) { +ranged = typeof headers.has === 'function' ? headers.has('range') +: Object.keys(headers).some((k) => k.toLowerCase() === 'range'); +} +return { url: String(url), method, ranged }; +} catch (_) { return { url: '', method: '', ranged: true }; } +} +function installPyodideCache(indexURL) { +if (_cacheDisabled || !cacheSupported() || typeof global.fetch !== 'function') return false; +for (const prefix of [indexURL, PYODIDE_INDEX]) if (prefix && !_cachePrefixes.includes(prefix)) _cachePrefixes.push(prefix); +if (_fetchPatched) return true; +_fetchPatched = true; +const nativeFetch = global.fetch.bind(global); +global.fetch = async function pytmlCachedFetch(input, init) { +const { url, method, ranged } = requestInfo(input, init); +// Only versioned Pyodide assets, never .mjs/.js loader scripts (those are +// loaded by import()/ + const SCRIPT_TAG = (typeof document !== 'undefined' && document.currentScript) || null; + const FALSE_WORDS = ['off', 'false', '0', 'no', 'none']; + + function readConfig() { + const cfg = Object.assign({}, (global.PytmlConfig && typeof global.PytmlConfig === 'object') ? global.PytmlConfig : {}); + for (const key of ['cache', 'persist', 'preload']) { + // Accept true/false as well as 'off', 'false', '0', 'no' written as strings. + if (typeof cfg[key] === 'string') cfg[key] = !FALSE_WORDS.includes(cfg[key].trim().toLowerCase()); + } + if (SCRIPT_TAG && SCRIPT_TAG.hasAttribute) { + const flag = (name) => { + if (!SCRIPT_TAG.hasAttribute(name)) return undefined; + return !FALSE_WORDS.includes(String(SCRIPT_TAG.getAttribute(name)).trim().toLowerCase()); + }; + for (const key of ['cache', 'persist', 'preload']) { + const value = flag(`data-${key}`); + if (value !== undefined) cfg[key] = value; + } + } + return cfg; + } + const CONFIG = readConfig(); + + // --- Persistent Pyodide cache --------------------------------------------- + // Pyodide's big files (pyodide.asm.wasm, python_stdlib.zip, pyodide-lock.json + // and package wheels such as NumPy) are stored in the browser's Cache Storage + // the first time a page loads them, then served from disk afterwards. + // + // Browsers partition all storage and HTTP caches by top-level site, so a copy + // cached for site A can never be reused by site B. This cache therefore works + // per site: every page and every return visit on the same origin is instant + // after the first load. (Cookies are limited to ~4 KB and cannot hold Pyodide.) + const CACHE_PREFIX = 'pytml-pyodide-'; + const CACHE_NAME = `${CACHE_PREFIX}${PYODIDE_VERSION}`; + const CORE_FILES = ['pyodide-lock.json', 'python_stdlib.zip', 'pyodide.asm.wasm']; + const cacheStats = { hits: 0, misses: 0, stored: 0, errors: 0 }; + const pendingPuts = new Set(); + let _cachePrefixes = []; + let _fetchPatched = false; + let _cacheDisabled = false; + + function cacheSupported() { + try { + return typeof caches !== 'undefined' && typeof caches.open === 'function' && typeof Response !== 'undefined'; + } catch (_) { return false; } + } + + async function openPyodideCache() { + if (_cacheDisabled || !cacheSupported()) return null; + try { return await caches.open(CACHE_NAME); } + catch (_) { _cacheDisabled = true; return null; } // file://, sandboxed iframes, private modes + } + + function requestInfo(input, init) { + try { + const url = typeof input === 'string' ? input : (input && input.href) || (input && input.url) || ''; + const method = String((init && init.method) || (input && input.method) || 'GET').toUpperCase(); + let ranged = false; + const headers = (init && init.headers) || (input && input.headers); + if (headers) { + ranged = typeof headers.has === 'function' ? headers.has('range') + : Object.keys(headers).some((k) => k.toLowerCase() === 'range'); + } + return { url: String(url), method, ranged }; + } catch (_) { return { url: '', method: '', ranged: true }; } + } + + function installPyodideCache(indexURL) { + if (_cacheDisabled || !cacheSupported() || typeof global.fetch !== 'function') return false; + for (const prefix of [indexURL, PYODIDE_INDEX]) if (prefix && !_cachePrefixes.includes(prefix)) _cachePrefixes.push(prefix); + if (_fetchPatched) return true; + _fetchPatched = true; + const nativeFetch = global.fetch.bind(global); + + global.fetch = async function pytmlCachedFetch(input, init) { + const { url, method, ranged } = requestInfo(input, init); + // Only versioned Pyodide assets, never .mjs/.js loader scripts (those are + // loaded by import()/