# pyr.js

[![](https://data.jsdelivr.com/v1/package/gh/Techtonique/pyr.js/badge)](https://www.jsdelivr.com/package/gh/Techtonique/pyr.js)
[![test](https://github.com/Techtonique/pyr.js/actions/workflows/test.yml/badge.svg)](https://github.com/Techtonique/pyr.js/actions/workflows/test.yml)
[![License: MIT](https://img.shields.io/badge/license-MIT-blue.svg)](LICENSE)

Python and R in HTML pages, with one script tag. No server, no build step, no install.

pyr.js is a small file (one script, about 460 lines) that finds Python and R code in your page and runs it in the
visitor's browser. [Pyodide](https://pyodide.org) (Python) and [webR](https://docs.r-wasm.org/webr/latest/) (R)
do the heavy lifting; pyr.js connects them to your HTML.

```html
<script src="https://cdn.jsdelivr.net/gh/Techtonique/pyr.js@v0.1.0/pyr.js"></script>

<p id="count">count = 0</p>
<button py-click="add_one()" py-out="count">Add</button>

<script type="text/python">
count = 0

def add_one():
    global count
    count += 1
    return f"count = {count}"
</script>
```

Save that as an `.html` file and double-click it. The first visit downloads Python (several MB, cached afterwards).

## Examples

| Example | Shows |
|---|---|
| [`examples/index.html`](examples/index.html) | Python and R blocks, buttons, live input, R output and plots |
| [`examples/charts.html`](examples/charts.html) | Python and R data drawn with Observable Plot |
| [`examples/highcharts.html`](examples/highcharts.html) | Python data drawn with Highcharts |
| [`examples/watch.html`](examples/watch.html) | Editing a `.py` file and seeing changes without reloading (needs a local server) |

## Writing pages

### Code blocks

```html
<script type="text/python"> print("hello") </script>
<script type="text/r"> summary(cars) </script>
<script type="text/python" src="app.py"></script>   <!-- served pages only -->
```

Blocks run in page order and share variables with other blocks of the same language. Printed output, the value of
the last line (like Jupyter for Python, like the console for R) and R plots appear where the block is. Python
packages you import (`numpy`, `pandas`, ...) are loaded automatically.

### Events

Put `py-` or `r-` in front of any DOM event name, with the code to run:

| Attribute | Meaning |
|---|---|
| `py-click="add_one()"`, `r-input="..."`, `py-change="..."`, ... | Run this code when the event fires |
| `py-ready="..."`, `r-ready="..."` | Run once, as soon as the engines are ready |
| `py-out="id"`, `r-out="id"` | Show the result in the element with this id: text, or an R plot |
| `py-then="fn"`, `r-then="fn"` | Pass the result as JavaScript data to `window.fn(data, element, event)` |

The element's current value (an input, slider, select) is available as `_value` in Python and `.value` in R.
Errors appear in red, in the `py-out` / `r-out` element or next to the element.

### Passing data to charts

`py-then` / `r-then` hand results to your own JavaScript, so any chart library works. Python returns a list of
dicts; an R function returns a data frame. Both arrive as an array of row objects:

```html
<script src="https://cdn.jsdelivr.net/npm/d3@7.9.2/dist/d3.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/@observablehq/plot@0.6.19/dist/plot.umd.min.js"></script>
<script src="https://cdn.jsdelivr.net/gh/Techtonique/pyr.js@v0.1.0/pyr.js"></script>
<script>
  function draw(rows, el) {
    el.replaceChildren(Plot.dot(rows, { x: 'wt', y: 'mpg' }).plot());
  }
</script>

<div r-ready="mtcars[, c('wt', 'mpg')]" r-then="draw" r-out="chart"></div>
<div id="chart"></div>
```

How values convert:

| Python | R | JavaScript |
|---|---|---|
| `dict` | named list, named vector | object |
| `list`, `tuple`, numpy array | unnamed list, vector | array |
| pandas DataFrame | data frame | array of row objects |
| `None` | `NULL`, `NA` | `null` |
| `datetime` | `Date`, `POSIXct`, factor | string |

One R detail: a vector of length 1 arrives as a single value, not an array of one.

### JavaScript API

```js
document.addEventListener('pyr:ready', async () => {
  const rows = await pyr.data('python', 'walk(200)');   // result as data; throws on error
  const items = await pyr.exec('r', 'summary(cars)');    // raw output items
  await pyr.rerun();                                     // run all blocks again
});
```

`<html data-pyr="loading|ready|error">` lets your CSS style the page while engines start, for example
`html[data-pyr="loading"] button { opacity: .5; pointer-events: none; }`.

### Script tag options

| Option | Meaning |
|---|---|
| `data-watch` | Re-run `src` files when they change, in the running interpreter (development) |
| `data-langs="python r"` | Start downloading engines before the page has finished loading |
| `data-py-index="/pyodide/"` | Use a self-hosted Pyodide instead of jsDelivr |
| `data-r-base="/webr/"` | Use a self-hosted webR instead of webr.r-wasm.org |

## How fast is it?

The first visit downloads the engines; after that they come from the browser cache. Starting an interpreter still
takes a moment on each page load, except in the shared mode below. Measured locally in Chromium:

| Situation | Ready in |
|---|---|
| Python, first start | about 3 s |
| R, first start | about 2–4 s |
| Python, another tab or a page reload (same-site, shared mode) | under 0.1 s |

### Where code runs

| How the page is opened | Python | R |
|---|---|---|
| From disk (double-click) | On the page | On the page, R itself in a worker |
| Served, pyr.js from a CDN | Worker per page | Worker per page |
| Served, pyr.js from the same site | **Shared worker**: other tabs and reloads reuse it | Worker per page |

In shared mode, each tab still has its own variables, and a reload starts the page fresh; only the running
interpreter is reused. Keeping it alive across reloads relies on a recent Chromium feature; other browsers start
it again after a reload. R can't be shared because webR starts a worker of its own, which Chrome does not allow
inside a shared worker.

Pages opened from disk can't read other local files, so use inline code there rather than `src="app.py"`.

## Using it from a CDN

```html
<script src="https://cdn.jsdelivr.net/gh/Techtonique/pyr.js@v0.1.0/pyr.js"
        integrity="sha384-HASH" crossorigin="anonymous"></script>
```

Tagged versions on jsDelivr never change, so you can pin one with an `integrity` hash. Get the hash with
`openssl dgst -sha384 -binary pyr.js | openssl base64 -A`. Replace `.js` with `.min.js` for a minified copy.

For the shared, instant-reload mode, host a copy of `pyr.js` on your own site instead.

## Privacy

All code runs in the visitor's browser and pyr.js sends nothing anywhere. The CDNs that serve the engines and
packages see the usual request information (IP address, referring site, which files), never your data. Self-host
the engines to avoid even that. Code in a page is visible to its visitors, so never put secrets in it.

## Self-hosting the engines

- **Pyodide:** download a release from [GitHub](https://github.com/pyodide/pyodide/releases) and point
  `data-py-index` at its `full/` folder.
- **webR:** download the release archive from [GitHub](https://github.com/r-wasm/webr/releases) and point
  `data-r-base` at it. Use the release archive rather than the npm package: the npm build targets Node and bundlers.

## Development

```sh
npm install
npx playwright install chromium
npm test
```

The tests run every example in a real browser, with Pyodide, webR and the chart libraries served locally by
`test/server.mjs`. Run `node test/server.mjs 8080` to browse the examples at `http://localhost:8080/examples/`
without any network access.

## Credits and licenses

pyr.js is MIT-licensed, copyright (c) 2026 T. Moudiki (Techtonique). It downloads, but does not include:

- [Pyodide](https://pyodide.org), MPL-2.0
- [webR](https://github.com/r-wasm/webr), with [R](https://www.r-project.org) itself under the GPL

If you self-host these, their licenses apply to the copies you distribute.
