code-playgrounds

What the framework is and how to put a playground on a site.

code-playgrounds

Code playgrounds that run in the reader's browser: an editor with language-server support, a Run button, and outputs such as the program's output, an intermediate form, a tree or a graph. Any language can plug in through one interface.

Status: the protocol, the sandbox, the editor and the <code-playground> element work, tested in Chromium, Firefox and WebKit (docs/plan.md §6).

Languages. This repository is the framework and holds no real language. The ready-made ones (OCaml, OxCaml, Koka, Effekt, Haskell, Python, Rust, Rocq, Agda, SQL, Typst, the logics of deduxit and more) are in playgroundkit/languages, built on this framework, with the flake module that puts them on a site (docs/plan.md D72, docs/migrating.md).

How it works

  • Language packages. A language is a directory: a manifest, a TextMate grammar, and one or more workers (WebAssembly, with a JavaScript fallback). Workers speak the Language Server Protocol for the editor, and a few playground/* methods for running code.
  • Sandboxed. Code runs in a Web Worker inside an <iframe sandbox="allow-scripts">: an opaque origin, no network, no storage. It runs only when the reader presses Run.
  • Nothing large loads early. Highlighting works at once. The engine downloads when the reader activates a playground, on a button that says how much.
  • One engine per language per page, shared by every playground on it.
  • Any site. A <code-playground> element for any page; Solid components for Solid sites; an Astro integration; response headers for Cloudflare, Netlify, nginx and Caddy, and a mode for hosts that send none, such as GitHub Pages (docs/hosts.md).

Using it on a site

In a flake built with flake-parts, import the module and choose languages:

{
  imports = [ inputs.playgrounds.flakeModules.default ];
  perSystem.playgrounds = {
    # A language from any flake: a package from `lib.mkLanguage`.
    languages.my-language.package = inputs'.my-language.packages.default;
    # An engine of a flake of ready-made languages, which fills `engines`
    # (`playgroundkit/languages` does):
    engines = inputs'.languages.engines;
    languages.ocaml.enable = true;
  };
}

engines is a registry of pkgs: args: package, empty by default; languages.<name>.engine (by default the name itself) picks one, with its arguments (id, name, aliases and whatever the engine takes). package needs no registry.

packages.playgrounds is then a directory to serve under any path, and checks.playgrounds checks it. It contains index.json, the files of every package as blobs/<sha256>.<ext>, the sandbox frames (frame/<policy>/), the element and headers.json: the response headers as data, which hold no base, so one build serves anywhere. The headers for a host come from the playgrounds command, for where the directory is served:

playgrounds headers result --base /playgrounds/ --for cloudflare   # or netlify, nginx, caddy
playgrounds verify site --base /playgrounds/ --host cloudflare     # a built site, as the host serves it
playgrounds verify site --base /playgrounds/ --host none           # a host that sends no headers
playgrounds serve result --base /playgrounds/                      # the directory with its headers

Set base (and host) to have the directory carry headers/ for that place, and set site to a built site to get checks.playgrounds-site, which runs verify on it (lib.checkSite pkgs { site; base; host; } without flake-parts). With precompress = true, each file a host would compress gets a brotli <file>.br, and the nginx (with ngx_brotli) and Caddy headers serve them. docs/hosts.md has each host's recipe. Your pages' CSP needs frame-src 'self' and connect-src 'self'. Without flake-parts, call inputs.playgrounds.lib.mkPlaygrounds pkgs { packages = [ … ]; }.

The flake keeps a consumer's lock small: its own inputs are nixpkgs and flake-parts, so a site that follows both locks one more node, playgrounds. The inputs of development (the formatter, the Rust toolchain for the template) belong to a partition with a lock of its own (nix/inputs/), which Nix reads only for this repository's own checks and dev shell.

For a site's own npm build (an Astro site, say), lib.npmOverrides pkgs and lib.mkNodeModules pkgs { npmRoot = ./.; } give node_modules that install this flake's npm package (packages.npm) from the store, as file:.playgrounds in the site's lock (docs/guide.md §6). lib.npmWorkersOverrides pkgs does the same with packages.npm-workers, the package with /protocol and /worker only, for the builds that make a language's workers.

On a page:

<script type="module" src="/playgrounds/element/define.js"></script>
<code-playground language="my-language">
  print("Hello")
</code-playground>

define.js defines the three elements and loads each one's code with its first instance; an element answers before then. It also exports addStyleSheet(), setDefaultStyles() and configure(), for a page without a bundler. Every attribute, property, method, event and state is in docs/elements.md, the look in docs/styling.md. code-playgrounds/element exports the classes without defining them, for a page with its own tag names, and code-playgrounds/core is the model without any element (createPlayground()).

A page that draws its own controls and outputs (a chat, say) uses chrome="none", the editor alone, with run(), stop() and the events; <code-playground-items for="p1" output="run"> draws the items it keeps, buttons included; itemsToMarkdown(items) gives a readable copy. highlight(language, code) from code-playgrounds/highlight colours static code as the editor does (link element/playground.css and put it in a .pg-code element), and --pg-line-height, --pg-editor-padding-block, --pg-editor-padding-inline, --pg-editor-bg, --pg-editor-border and --pg-editor-gutters make the editor sit where a static block was (docs/plan.md D65). highlightRanges(language, code) gives the same as ranges, for a page's own editor. An element that is never shown still answers from its language server (el.diagnostics(), el.hover(position), el.inlayHints(), the playground-diagnostics event); el.insertText(text) and el.focus({ at: "end" }) type and focus as the reader would, waiting for the editor (state.editor is ready); --pg-tooltip-bg, -fg, -border, -font and -radius style its tooltips (D66).

Playgrounds of one language share an engine: one download and start of the runtime and one language server, which sees every document and runs every playground's code in the same workers. A run is still a fresh program, so definitions do not carry from one run or playground to another; what code leaves in the workers themselves (a changed prototype, a global) does. Give playgrounds whose authors do not trust each other different scope attributes (any string), and each scope gets an engine of its own (docs/plan.md D63). An engine ends 30 s after its last playground leaves the page.

It fits any width down to 320 px and is sized for touch. Add keymap="vim" for Vim's key bindings, readonly, label (the editor's accessible name), start="edit" or start="focus" to start the language server on the reader's first edit or focus, not only on Run, or storage="indexeddb" or storage="local" (localStorage) to keep the reader's edits in this browser (storage-key names them; by default the page and the share name); share also names the element in share links. Its default look is native to the page (the page's font and text colour); restyle it with --pg-* custom properties, ::part(), a stylesheet added to every playground with addStyleSheet(), or unstyled and your own from nothing; colours follow the page's color-scheme (docs/styling.md). In the editor, Escape then Tab leaves it, and Ctrl/⌘+I reads the type at the cursor.

Hidden code before the reader's, such as imports or a running example's definitions, goes in a child <template data-prelude> (folded, shown on request) or <template data-setup> (never shown); the editor knows what it defines (docs/plan.md D49). In Markdown, a fence marked prelude or setup before a playground fence does the same.

An exercise adds hidden tests in <template data-tests>: the package's check output runs them after the reader's code and shows a verdict for each. In OCaml (a package of playgroundkit/languages):

<code-playground language="ocaml" share="double" storage="local" start="edit">
  <template data-setup>let square x = x * x</template>
  <template data-tests>let () = Check.equal "double 2" ~expected:4 (fun () -> double 2)</template>
  let double x = (* your code *) 0
</code-playground>

In Solid, the same are <Playground setup="…" prelude="…" context={[{ name: "tests", text, role: "tests" }]}>. lib.checkExercises checks a site's own exercises in its build (docs/guide.md).

Outputs can live anywhere on the page, each styled on its own: tabs="none" (or a list of ids) on <code-playground> limits its tabs, and <code-playground-output for="p1" output="run" controls> shows one output where it is placed (docs/plan.md D40).

A host that keeps code and outputs in a shared document listens for playground-change, playground-items and playground-state, and calls applyChanges(), seed() and run() (which, as the Run button, produces every output that runs on Run, D56) or sets code (docs/plan.md D38). A page can start the language server on a reader's action without running anything (activate(), D54), pass a run its own parameters (run(output, { args })), keep ranges marked in the editor and every output (mark(ranges)), and follow what is linked through playground-link (D52).

In an npm build (Solid, Astro)

packages.npm is the npm package code-playgrounds. Its exports: code-playgrounds/solid (<Playground>, a headless createPlayground()) and /solid/playground.css; code-playgrounds/astro (the integration); code-playgrounds/element and /element/define; code-playgrounds/highlight; code-playgrounds/items; code-playgrounds/core and /protocol; code-playgrounds/headers; code-playgrounds/serve (serveDirectory, a built directory with its headers); code-playgrounds/build (assembleSite, verifySite), /precompute and /exercises; code-playgrounds/worker (serve(), for a language's worker); code-playgrounds/testing (a server and a handle for browser tests, docs/guide.md); code-playgrounds/conformance (the engine, client and router a language's own checks drive). It also installs the playgrounds command as a bin. A site built with nixpkgs' importNpmLock installs it from the store:

  1. Link nix build .#npm to .playgrounds in the site (git-ignored), add "code-playgrounds": "file:.playgrounds" to its package.json, set install-links=true in its .npmrc, and run npm install to update the lock.

  2. Build node_modules with the store path in place of that entry:

    pkgs.importNpmLock.buildNodeModules {
      npmRoot = ./site;
      nodejs = pkgs.nodejs;
      derivationArgs = {
        npmDeps = pkgs.importNpmLock {
          npmRoot = ./site;
          packageSourceOverrides."node_modules/code-playgrounds" = inputs'.playgrounds.packages.npm;
        };
        env.npm_config_install_links = "true";
      };
    }
    
  3. In Astro, add playgrounds({ dir, base: "/playgrounds/" }) from code-playgrounds/astro, with dir the built playgrounds directory. Fences such as ```my-language playground become playgrounds, with Sätteri (Astro 7's default) or the unified processor. In a Solid island (Solid 2: solid-js, @solidjs/web and @astrojs/solid-js 8): <Playground client:visible language="my-language" code="…" />. Its base prop sets where the playgrounds are (default /playgrounds/). The props that make the playground (language, code, files) are read once.

  4. Add precompute to a fence (```my-language playground precompute), or precompute: "all" to the integration's options, and its outputs are computed when the site builds: readers see them before any engine downloads. Other static sites run node packages/build/precompute.ts <site> <playgrounds> on <code-playground precompute> elements (docs/plan.md D41).

tests/consumer is such a site, built by checks.consumer and run in three browsers. A site that uses Astro's security.csp needs nothing more: the integration adds the hash of Solid's hydration script, which Astro leaves out. It also writes the headers for the site's URL base and checks the built site (verify, an error by default). host: "none" is for a host that sends no headers, such as GitHub Pages: it writes no header file and verifies the pages' and frames' <meta> policies instead (docs/hosts.md).

Adding a language

Read docs/guide.md, then copy a template: templates/typescript/ or templates/rust/ (the λ-calculus, a complete package each). The guide names the ready-made package on each route (C by Emscripten, Rust by wasm-bindgen, GHC, JavaScript, OCaml), all in playgroundkit/languages. docs/protocol.md is the full protocol. Check a package with the conformance kit, with the playgrounds command (the dev shell has it; the npm package installs it as a bin):

playgrounds check path/to/package [options.json]

A site's own cells and exercises are checked against a built package with lib.checkExercises or playgrounds exercises <package> <dir> [--mode gaps] (docs/guide.md, "Checking a site's cells and exercises"). playgrounds compose prints the document a host sends for a playground's hidden parts, and playgrounds precompute fills a built site's <code-playground precompute> elements.

A package's workers can run on a remote the site operates instead of in the reader's browser (docs/protocol.md §3.2, §8; docs/plan.md D71). playgrounds engines <package> <dir> writes what a remote serves, and playgrounds check <package> --engines <dir> runs the kit through a remote of its own on loopback (--remote <url> through one that runs). The page's side is not built yet.

Development

Needs Nix with flakes. direnv allow (or nix develop) enters the dev shell; menu lists the commands.

tests        # unit tests
lint         # Biome and TypeScript
check        # every check, the gate before a commit

To try a site with engines on a remote, build a package, write its engines directory and serve both from the repository (the engine server is AGPL-3.0-or-later and not in the playgrounds npm package; unsafe-process contains nothing, so it listens on loopback only; --sandbox bubblewrap is the jail, for a machine set up as docs/remote.md says):

playgrounds engines <package-dir> engines                    # a built language package
playgrounds serve result --engines engines --sandbox unsafe-process --listen 127.0.0.1:8080

It serves the directory with its headers, answers the wire and GET /info on the same port, and prints a ticket secret once (secret <hex>). Without the directory it is the engine server alone. To run one for a site, with jails and limits, as a NixOS service: docs/remote.md.

The flake has two locks: flake.lock (nixpkgs and flake-parts) and nix/inputs/flake.lock (every other input, the partition's). nix flake update --flake ./nix/inputs moves the second; up updates both and commits them. checks.partition-pins fails when the partition's nixpkgs or flake-parts is not the root's revision.

A language package depends on this repository's protocol layer (packages/protocol, packages/worker) and the builder, and on nothing else: a change to the element, the Solid components or the stylesheet leaves its derivation, and its entry in a binary cache, as it was. A language's workers are built in a node_modules that holds only code-playgrounds/protocol and /worker (packages.npm-workers, lib.npmWorkersOverrides); lib.checkLanguageInputs fails a build that reaches further, and checks.language-inputs runs it on the templates (docs/plan.md D77).

Version control is Jujutsu. docs/plan.md records the architecture and its decisions; AGENTS.md is for coding agents.

Licence

Four licences, by part (REUSE 3.3: each file's SPDX header or REUSE.toml says which; the texts are in LICENSES/):

Part Licence
packages/protocol, packages/worker, schemas/: the protocol layer a worker or a server links MIT OR Apache-2.0
README.md, CONTRIBUTING.md, llms.txt, docs/*.md: the documentation, whose snippets go into sites, server configurations and language packages MIT OR Apache-2.0
templates/, the conformance kit's echo fixture: made to be copied 0BSD
packages/remote: the engine server AGPL-3.0-or-later
everything else: the core, the frame, the front ends, the build tools, the Nix library GPL-3.0-or-later (LICENSE)

A language package that bundles the protocol layer into its workers owes the GPL nothing for that part; a copy of a template owes nothing at all, but a copy that depends on the protocol package takes its licence for that dependency. The code-playgrounds npm package holds the GPL and the permissive parts, each file marked; code-playgrounds/protocol and code-playgrounds/worker are the permissive ones. See CONTRIBUTING.md to contribute.

packages/remote, the supervisor that runs a site's engines on a machine the site operates, is AGPL-3.0-or-later (packages/remote/LICENSE): a network service owes its source to its users, which the GPL's duties on distribution do not give. It combines with the rest by section 13 of both licences. The wire it speaks, stdioEndpoint(), the token signer and the ready-made workers are in the permissive layer, so a client, another remote or a worker in any language owes nothing to it. The code-playgrounds npm package does not contain it. An operator who changes it sets source, the URL its welcome gives to its users.

This page as MarkdownSource on GitHub