|
| 1 | +# Compiled browser target |
| 2 | + |
| 3 | +The development checkout provides `JavaScript.browser.compile_browser`. It |
| 4 | +compiles verified [local source modules](compiler-modules.md), enables the |
| 5 | +[async profile](compiler-async.md), and records the complete local worker/host |
| 6 | +asset closure. It is not included in the published 0.1.0 distribution. |
| 7 | + |
| 8 | +The target is `python-browser-modules-host-async/1`, compiler ABI |
| 9 | +`python-browser-host-esm/1`, using host protocol `pocket-python-host` version 1. |
| 10 | +Python computation executes as our emitted JavaScript and compatibility helpers |
| 11 | +inside a module worker. No interpreter, server execution or alternate engine is |
| 12 | +loaded. New-source parsing remains the independent interpreter's later milestone. |
| 13 | + |
| 14 | +## Run the example |
| 15 | + |
| 16 | +From this checkout: |
| 17 | + |
| 18 | +```sh |
| 19 | +uv sync --locked |
| 20 | +uv run --no-sync python examples/browser_text_metrics.py --output build/browser-text-metrics |
| 21 | +python -m http.server 8000 --bind 127.0.0.1 --directory build/browser-text-metrics |
| 22 | +``` |
| 23 | + |
| 24 | +Open `http://127.0.0.1:8000/`. Run counts Unicode characters, ASCII-separated |
| 25 | +words and LF-based lines. Stop terminates the worker; Restart creates a fresh |
| 26 | +session. The example enables Run after its callback is registered. Computation |
| 27 | +works offline after loading. Offline reload, service-worker caching and PWA |
| 28 | +assembly are WEB-03, not part of this example builder. |
| 29 | + |
| 30 | +The builder reads the approved text_metrics corpus, emits selected local modules, |
| 31 | +source maps/notices, the host/worker/protocol modules, a manifest and a small HTML |
| 32 | +entry. It requires a new output directory and preserves existing outputs. |
| 33 | +The same computation can be imported under CPython in a separate server entry; |
| 34 | +client entrypoints and host adapters are explicit. E2E-01 owns the complete |
| 35 | +server/client packaging demonstration. |
| 36 | + |
| 37 | +## Python namespace and entry |
| 38 | + |
| 39 | +Only named imports from the compiler's `JavaScript.browser` namespace are |
| 40 | +adopted. They belong in the client entry; they are not CPython DOM functions. |
| 41 | + |
| 42 | +```python |
| 43 | +from JavaScript.browser import on_click, read_text, write_text, fetch_text |
| 44 | +from text_metrics import metrics |
| 45 | + |
| 46 | +async def display(text): |
| 47 | + print(metrics(text)) |
| 48 | + |
| 49 | +async def main(): |
| 50 | + await on_click("run", display) |
| 51 | +``` |
| 52 | + |
| 53 | +| Function | Adopted behavior | |
| 54 | +| --- | --- | |
| 55 | +| `read_text(control)` | Await the current text/value of a named granted control; return Python str. | |
| 56 | +| `write_text(control, text)` | Await replacement with plain text; return None. | |
| 57 | +| `on_click(control, callback)` | Register a known compiled synchronous/async function taking one snapshot argument; return an opaque subscription handle. | |
| 58 | +| `unsubscribe(subscription)` | Remove the listener and release its callback; return None. Reuse raises STALE_HANDLE. | |
| 59 | +| `fetch_text(url)` | Await an allowed native GET and return `(status, final_url, text)` as a Python tuple. HTTP non-2xx statuses remain successful responses. | |
| 60 | + |
| 61 | +Every call returns an adopted Promise that source code awaits. Aliases retain |
| 62 | +binding identity. Str arguments stay explicit, and status integers remain BigInt. |
| 63 | +There is no implicit JSON/dict/Number conversion. Imports must be unconditional; |
| 64 | +module initialization contains imports, definitions, immutable constants, pass or |
| 65 | +docstrings. Browser entry requires a directly defined async `main()` without |
| 66 | +required arguments. This prevents host calls before the ready handshake. |
| 67 | + |
| 68 | +The original JavaScript Array/Promise registry keeps its own contract. |
| 69 | +`from JavaScript import fetch`, arbitrary globals/attributes, selectors, innerHTML, |
| 70 | +DOM nodes, POST/options/headers, streaming and response JSON APIs remain outside |
| 71 | +this language profile. CPython uses the published `fetch_api` companion through |
| 72 | +its server adapter; that implementation is not embedded in browser output. |
| 73 | + |
| 74 | +## Main-thread configuration |
| 75 | + |
| 76 | +Import `mountCompiledApplication` from the generated `browser-host.mjs`. Supply |
| 77 | +the verified application's manifest SHA-256, profile `compiled-javascript`/1, |
| 78 | +entrypoint `app.mjs`, and engine null. Bind grant names to trusted DOM Elements, |
| 79 | +provide a text output Element, and optionally map button names to input snapshot |
| 80 | +controls (otherwise the callback receives an empty str). The example supplies a complete configuration. Each required capability |
| 81 | +must be granted; source code cannot widen controls or URLs. |
| 82 | + |
| 83 | +The adapter supports output/1, dom-text/1, dom-events/1, handles/1 and the adopted |
| 84 | +GET text subset of fetch/1. Files/persistence and unlisted capabilities fail |
| 85 | +initialization. No arbitrary host filesystem or native object is exposed. |
| 86 | +Fetch grants use exact normalized HTTP(S) URLs without embedded credentials or |
| 87 | +fragments. Native Fetch preserves origin/CORS checks, omits credentials, rejects |
| 88 | +redirects and enforces a bounded strict-UTF-8 response and deadline. Relative |
| 89 | +requests are normalized against the page URL before the exact grant check. |
| 90 | + |
| 91 | +`ready` confirms protocol initialization, before asynchronous application setup |
| 92 | +finishes. `main()` then registers handlers. `stop()` aborts pending host work, |
| 93 | +removes listeners and terminates the worker. `restart()` stops the current |
| 94 | +session and returns a fresh controller. `stats()` exposes lifecycle and resource |
| 95 | +counts for integration tests. Optional `onError` receives bounded plain error |
| 96 | +metadata; the default output uses a text node. Application code never supplies |
| 97 | +HTML or arbitrary host properties to these operations. |
| 98 | + |
| 99 | +## Ordering, lifetime and limits |
| 100 | + |
| 101 | +The adapter implements the [HOST-01 envelope and lifecycle](https://github.com/outside-labs/pocket-python/blob/main/docs/browser-host-protocol.md) |
| 102 | +for this adopted surface: fresh 128-bit sessions, independent monotonic sequence |
| 103 | +counters, unique request IDs, bounded pending work and terminal replies. Stale |
| 104 | +sessions do not advance counters. Malformed active messages/replays close the |
| 105 | +session. Valid operation failures reject the source await with an original source |
| 106 | +location; an unhandled main/callback exception closes the application. |
| 107 | + |
| 108 | +Events are serialized in a bounded queue. Output is ordered and bounded. A |
| 109 | +subscription owns its main-thread listener and worker callback until unsubscribe |
| 110 | +or teardown; already queued events for released subscriptions are discarded. |
| 111 | +Canceled/timed-out request slots remain bounded until terminal reply or teardown. |
| 112 | +Cancellation cannot undo a committed DOM/output effect. Busy synchronous code |
| 113 | +requires worker termination; the main thread remains responsive. Worker placement |
| 114 | +provides responsiveness isolation, not a general hostile-code security sandbox. |
| 115 | + |
| 116 | +Defaults match HOST-01: 1 MiB messages/responses, value depth 64, 32 pending |
| 117 | +requests/subscriptions/events, 65,536 output code points and ten seconds per |
| 118 | +operation. Trusted configuration may lower limits. Oversized results return |
| 119 | +QUOTA. Stored Python surrogate points survive engine transport; projecting to |
| 120 | +DOM UTF-16 and reading back may combine an explicit surrogate pair. Error |
| 121 | +metadata retains its source span; full call-frame traceback construction is |
| 122 | +separately staged. |
| 123 | + |
| 124 | +The manifest records source/output hashes, maps, notices, required capabilities |
| 125 | +and every static module/worker edge. Initialization echoes identity; it does not |
| 126 | +independently authenticate files. Deployment/assembly must verify the recorded |
| 127 | +assets against a trusted manifest before use. WEB-03 implements that application |
| 128 | +profile and cache/publication boundary. |
| 129 | + |
| 130 | +## Verification |
| 131 | + |
| 132 | +```sh |
| 133 | +uv sync --locked --group browser-tests |
| 134 | +uv run --no-sync python -m playwright install chromium |
| 135 | +uv run --no-sync python scripts/compiler_browser_smoke.py --report build/compiler-browser-report.json |
| 136 | +``` |
| 137 | + |
| 138 | +Use `--channel chrome` for an installed Chrome. Playwright 1.64.0 is a declared |
| 139 | +test-only group; existing runtime dependency versions are retained. CI tests |
| 140 | +installed wheel/source compiler APIs on Linux/macOS/Windows and runs the local |
| 141 | +browser fixture on Linux. The fixture covers CPython/client parity, loaded-worker |
| 142 | +offline computation, Fetch status/CORS/credentials/grants/redirect/size/deadline, |
| 143 | +source errors, forty callback allocation/release cycles, repeated restart, |
| 144 | +pending Fetch cancellation and busy-worker stop. The user example is also run |
| 145 | +under a URL subdirectory. Reports record the actual browser and target identity. |
0 commit comments