Skip to content

Example: fill a PDF on the server ​

Sometimes the PDF already exists: a fillable form, an AcroForm with fields of its own, that the answers have to go into. In this example the server keeps that PDF, and its copy of the form definition carries a template layout for it: which of the PDF's fields takes which answer. The page delivers the envelope, and the endpoint validates it with the sandbox program, fills the PDF with the PDF program and answers with the filled file.

The page ​

There is no server behind these docs. The result under the code is answered by a stand-in in the browser that runs the same programs, from the same built files, over the same form and the same PDF. The endpoint files further down are what a real server runs.

index.html
<!doctype html>
<html lang="en">
  <head>
    <meta charset="utf-8">
    <title>Customer intake</title>
    <link rel="stylesheet" href="/datum/datum-form.css">
    <script type="module" src="/datum/datum-form.js"></script>
    <style>#record { width: 100%; height: 640px; border: 1px solid #c8ccd0; }</style>
  </head>
  <body>
    <datum-form id="intake" src="/forms/customer-intake.json" language-switcher></datum-form>

    <!-- Where the PDF the server answers with lands: offered as a file and shown in the page. -->
    <p><a id="save" hidden download="customer-intake-filled.pdf">Save the filled PDF</a></p>
    <iframe id="record" title="The existing form, filled in" hidden></iframe>

    <script type="module">
      const form = document.getElementById("intake");
      form.dataSources = {
        countries: [
          { value: "CA", label: "Canada" },
          { value: "US", label: "United States" },
          { value: "MX", label: "Mexico" }
        ]
      };

      // The endpoint validates before anything else; a 422 carries codes, which these word.
      form.messages = {
        required: {
          default: "This field is required.",
          locales: { "fr-CA": "Ce champ est requis." }
        }
      };

      form.addEventListener("datum-submit", ({ detail }) => {
        if (!detail.accepted) return; // the form shows its own validation errors
        detail.waitUntil(deliver(detail));
      });

      // Deliver the envelope. What comes back is the PDF the server already had, its fields filled
      // with the answers and left editable: the server's say, not the page's.
      async function deliver(detail) {
        try {
          const response = await fetch("/api/submissions/fill", {
            method: "POST",
            headers: { "content-type": "application/json" },
            body: JSON.stringify(detail.submission)
          });
          if (response.status === 422) {
            // { errors: [{ field, code }] }: the server's verdict, worded by the messages above.
            const { errors } = await response.json();
            form.setErrors(errors.map((e) => ({ componentId: e.field ?? undefined, code: e.code })));
            return;
          }
          if (!response.ok) throw new Error(response.statusText);
          const pdf = await response.blob();
          // The bytes as an address the page can show and offer: an iframe draws a PDF in place.
          const url = URL.createObjectURL(pdf);
          Object.assign(document.getElementById("record"), { src: url, hidden: false });
          Object.assign(document.getElementById("save"), { href: url, hidden: false });
        } catch {
          form.setErrors([{ code: "delivery.failed", message: "The form could not be sent. Try again." }]);
        }
      }
    </script>
  </body>
</html>
ResultThis page, running. Addresses under /forms//api/ are answered by the example.
What the page did

Nothing yet.

Fill in a name, pick a country and a contact method, and submit. The filled PDF appears under the form with a link to save it. Tick the newsletter box and enter an address, then submit again: the email field in the PDF is filled. Untick it and the field is cleared, because a rule hides the address and a hidden answer is not printed. The log lists the fill report, one line per mapped field.

What the server keeps ​

The PDF is the server's, at templates/customer-intake.pdf: open the blank form to see its seven fields. The page loads the plain form, and the server's copy of the definition is the same form with the template layout added: customer-intake-template.json. Its layout intake-template maps the fields this way:

PDF fieldTakes
applicant_nameThe answer to fullName, as typed
country{{country}}, template text that writes the option's label, since the PDF's list holds country names
contact_methodThe answer to contactMethod, whose values match the radio group's export values
newsletter_optinThe checkbox subscribe
newsletter_email, notesThe answers to newsletterEmail and notes
submitted_viaThe literal "Web form"

A layout like this is made in the builder's PDF workspace: add the PDF as a template layout and map its fields. See PDFs.

The endpoint ​

Each file is complete. Its first lines say what to install and how to fetch the engine, a WASM build of a JavaScript engine (qjs-wasi.wasm), from its release page. Beside it the server keeps both programs from the bundle folder, its copy of the form at forms/customer-intake.json (the one with the template layout), the PDF at templates/customer-intake.pdf and the two fonts at fonts/.

Python (FastAPI) ​

python
# main.py — the endpoint the page delivers to: the submission validated, then written into an existing PDF form.
#   pip install fastapi uvicorn wasmtime
#   curl -LO https://github.com/quickjs-ng/quickjs/releases/download/v0.16.2/qjs-wasi.wasm
#   uvicorn main:app
#
# The PDF is one this server already has (templates/customer-intake.pdf): an AcroForm whose fields the
# form's template layout maps to the answers. datum-sandbox-program.js re-validates the envelope
# (see Validate on the server) and datum-pdf-program.js fills the PDF — the kernel behind the
# browser's PDF button, in a QuickJS of this process's own: QuickJS-ng's WebAssembly build, under
# wasmtime. Nothing about PDFs is written here.
import base64
import json
import logging
import math
import tempfile
import threading
import time
import uuid
from datetime import datetime, timezone
from pathlib import Path

from fastapi import FastAPI
from fastapi.responses import JSONResponse, Response
from wasmtime import Config, Engine, ExitTrap, Linker, Module, Store, Trap, WasiConfig

FORM = json.loads(Path("forms/customer-intake.json").read_text())


# The journey the answers were given through, from this server's own copy of the form: the
# envelope names it (submission.journey.id) and nothing more. Handed to the sandbox, it has the
# kernel work the path out again from the values, as the browser did: an answer on a page the
# path skipped is judged hidden, and a form field one of the journey's own fields fills or works
# out counts as asked on that page. None named, or one the form does not have: null, and the
# answers are judged as the whole form, which asks for every required field.
def journey_of(submission: dict):
    named = (submission.get("journey") or {}).get("id")
    return next((j for j in FORM.get("journey", {}).get("journeys", []) if j["id"] == named), None)


# The engine: qjs-wasi.wasm, QuickJS-ng's own WebAssembly build from its release page, compiled
# once and shared. Every request runs it afresh in a store of its own, so requests need no lock.
config = Config()
config.epoch_interruption = True  # the time budget: a run past its deadline traps
engine = Engine(config)
QJS = Module.from_file(engine, "qjs-wasi.wasm")
linker = Linker(engine)
linker.define_wasi()

# The clock every budget is kept by, one for all the runs at once: a tick every 50 ms; a run's
# deadline is its budget in ticks, plus one for the tick already under way when it started. The
# epoch it advances is the engine's, shared by every store on it, so no run may bump it for
# itself: a timer of the run's own, fired when its budget was spent, would advance the epoch under
# every other run in flight too, and cut short one that had set its deadline a tick earlier — a
# wrong verdict for a submission that was never judged. One clock, and no run can touch another.
TICK = 0.05


def clock() -> None:
    while True:
        time.sleep(TICK)
        engine.increment_epoch()


threading.Thread(target=clock, daemon=True).start()


class SandboxError(Exception):
    """A run that ended without an outcome: a limit cut it off, or a program or rule module would not load."""


def qjs(argv: list, request: str, seconds: float, memory: int) -> str:
    # One run: this directory mounted read-only as /app (the programs), the request on stdin, the
    # answer on stdout — all the run can reach; wasmtime hands it nothing else. The limits are
    # wasmtime's, at the browser's profile: the budget in seconds, the memory in bytes. Runaway
    # recursion exhausts the instance's own stack and traps, which ends the run too.
    out, err = [], []
    with tempfile.NamedTemporaryFile("w", suffix=".json") as stdin:
        stdin.write(request)
        stdin.flush()
        store = Store(engine)
        store.set_limits(memory_size=memory)
        store.set_epoch_deadline(math.ceil(seconds / TICK) + 1)
        wasi = WasiConfig()
        wasi.argv = ["qjs", "--std", *argv]  # --std: the std module, which reads stdin
        wasi.preopen_dir(".", "/app", fs_mutable=False)
        wasi.stdin_file = stdin.name
        wasi.stdout_custom = out.append
        wasi.stderr_custom = err.append
        store.set_wasi(wasi)
        try:
            linker.instantiate(store, QJS).exports(store)["_start"](store)
        except ExitTrap as exit:  # a throw: qjs printed it to stderr and exited 1
            if exit.code != 0:
                raise SandboxError(b"".join(err).decode().strip()) from exit
        except Trap as trap:  # "interrupt": the budget; "stack_overflow": the recursion
            raise SandboxError(f"{trap.trap_code}") from trap
    return b"".join(out).decode().rstrip("\n")


# The template layout, as the builder's PDF mode authored it: the PDF's fields and
# what fills each — a component's answer, an option's label through template text, a literal.
LAYOUT = next(layout for layout in FORM["pdf"]["layouts"] if layout["id"] == "intake-template")

# The PDF itself, from this server's disk. The layout's template source names it (a storage this
# server resolves, not bytes in the definition), and the bytes ride with each request, base64.
TEMPLATE = base64.b64encode(Path("templates/customer-intake.pdf").read_bytes()).decode("ascii")

# Validation first, so the PDF is filled with the sanitized values: what the form defines, nothing else.
VALIDATE = ["-I", "/app/datum-sandbox-program.js", "-e", "print(__datum_run(std.in.readAsString()));"]

# The PDF program, under the document profile; __datum_pdf's promise settles before qjs exits.
RENDER = ["-I", "/app/datum-pdf-program.js", "-e", "__datum_pdf(std.in.readAsString()).then((json) => print(json));"]


# The fonts the kernel draws the filled fields with when the standard 14 cannot show an answer.
def font(id, family, weight, file):
    data = base64.b64encode(Path("fonts", file).read_bytes()).decode("ascii")
    return {"id": id, "family": family, "weight": weight, "style": "normal", "data": data}


FONTS = [font("dejavu-sans", "sans-serif", 400, "DejaVuSans.ttf"), font("dejavu-sans-bold", "sans-serif", 700, "DejaVuSans-Bold.ttf")]

# What the Country select shows, resolved here: the layout's "{{country}}" writes the option's label.
COUNTRIES = [{"value": "CA", "label": "Canada"}, {"value": "US", "label": "United States"}, {"value": "MX", "label": "Mexico"}]

# What becomes of the filled fields. "editable" leaves them fields a reader may still change;
# "readonly" locks each one the fill touched; "flatten" burns the values into the page and drops
# the fields — an archive copy. The layout's own options are set here, per server.
FIELDS = "editable"

log = logging.getLogger("datum.fill")
logging.basicConfig(level=logging.INFO)

app = FastAPI()


@app.post("/api/submissions/fill")
def submit(envelope: dict):
    submission = envelope["submission"]
    locale = submission.get("locale", "en")
    # The journey, if the answers came through one: the path is worked out again from the values (see journey_of).
    context = {"formId": FORM["id"], "form": FORM["root"], "values": submission["values"], "locale": locale, "journey": journey_of(submission), "optionSnapshot": {"countries": COUNTRIES}}
    outcome = json.loads(qjs(VALIDATE, json.dumps(context), 0.25, 32 * 1024 * 1024))
    if outcome["errors"]:  # 422 with codes and fields, never text; the page's messages word them
        errors = [{"field": e.get("componentId"), "code": e["code"]} for e in outcome["errors"]]
        return JSONResponse(status_code=422, content={"errors": errors})
    response = render({
        "abi": "4.0.0",
        "op": "document",
        "form": FORM["root"],
        # The template layout, inline, with this server's fill options: this server's choice, so no
        # layout's "when" is tried, and the bytes below are that layout's.
        "layout": {**LAYOUT, "options": {"flatten": FIELDS == "flatten", "readOnly": FIELDS == "readonly", "appearances": "regenerate"}},
        # The PDF to fill: the bytes the layout's source names, resolved by this server.
        "template": {"data": TEMPLATE},
        "values": outcome["values"],
        "locale": locale,  # the language template texts resolve in: the country's name, here
        "optionSnapshot": {"country": COUNTRIES},
        "fonts": FONTS,
        # The only time and identity the program ever sees: the same request gives the same bytes.
        "env": {"createdAt": datetime.now(timezone.utc).strftime("%Y-%m-%dT%H:%M:%S.000Z"), "documentId": str(uuid.uuid4())},
    })
    if not response["ok"]:  # {"code": "template" | "font" | "internal", "message": ...}
        return JSONResponse(status_code=500, content={"error": response["error"]})
    # The fill report, one entry per mapped field: filled; cleared (no answer, or one a rule hid);
    # missing (the PDF has no field of that name); unsupported (a kind the kernel cannot fill).
    for field in response["fields"]:
        log.info("%s %s (%s)", field["status"], field["pdfField"], field.get("kind", "-"))
    return Response(
        content=base64.b64decode(response["bytes"]),
        media_type="application/pdf",
        headers={"Content-Disposition": 'attachment; filename="customer-intake-filled.pdf"', "X-Page-Count": str(response["pageCount"])},
    )


def render(request: dict) -> dict:
    return json.loads(qjs(RENDER, json.dumps(request), 15, 256 * 1024 * 1024))

Java (Spring Boot) ​

java
// Application.java — the endpoint the page delivers to: the submission validated, then written into an existing PDF form.
//   pom.xml beside it: Spring Boot, and Endive with its Maven plugin, which compiles the engine in.
//   curl -Lo src/main/resources/qjs-wasi.wasm https://github.com/quickjs-ng/quickjs/releases/download/v0.16.2/qjs-wasi.wasm
//   mvn spring-boot:run
//
// The PDF is one this server already has (templates/customer-intake.pdf): an AcroForm whose fields the
// form's template layout maps to the answers. datum-sandbox-program.js re-validates the envelope
// (see Validate on the server) and datum-pdf-program.js fills the PDF — the kernel behind the
// browser's PDF button, in a QuickJS of this process's own: QuickJS-ng's WebAssembly build, under
// Endive. Nothing about PDFs is written here.
package datum;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.UncheckedIOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.time.Instant;
import java.time.ZoneOffset;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.Base64;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;

import com.google.common.jimfs.Configuration;
import com.google.common.jimfs.Jimfs;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;
import run.endive.runtime.ImportValues;
import run.endive.wasi.WasiExitException;
import run.endive.wasi.WasiOptions;
import run.endive.wasi.WasiPreview1;
import run.endive.wasm.types.MemoryLimits;
import tools.jackson.databind.JsonNode;
import tools.jackson.databind.json.JsonMapper;
import tools.jackson.databind.node.ObjectNode;

@SpringBootApplication
@RestController
public class Application {

    static final JsonMapper JSON = JsonMapper.shared();
    static final JsonNode FORM = JSON.readTree(text("forms/customer-intake.json"));

    // The journey the answers were given through, from this server's own copy of the form: the
    // envelope names it (submission.journey.id) and nothing more. Handed to the sandbox, it has the
    // kernel work the path out again from the values, as the browser did: an answer on a page the
    // path skipped is judged hidden, and a form field one of the journey's own fields fills or works
    // out counts as asked on that page. None named, or one the form does not have: null, and the
    // answers are judged as the whole form, which asks for every required field.
    static JsonNode journeyOf(JsonNode submission) {
        for (JsonNode journey : FORM.path("journey").path("journeys")) {
            if (journey.path("id").equals(submission.path("journey").path("id"))) {
                return journey;
            }
        }
        return null;  // set as JSON null: no journey
    }

    // The engine: qjs-wasi.wasm, QuickJS-ng's own WebAssembly build from its release page, compiled once,
    // at build time, by Endive's plugin (see pom.xml) into the class Qjs — native code where the platform
    // has it, JVM bytecode where not. Every request runs it afresh in an instance of its own, so requests
    // need no lock. The module's own initial memory, which a limit must keep.
    static final int QJS_PAGES = Qjs.load().memorySection().get().getMemory(0).limits().initialPages();

    // What a run can reach: one in-memory directory holding the two programs, and nothing else — not this
    // directory, not the disk. Endive mounts any java.nio path, and Jimfs makes one.
    static final Path APP = programs();

    static Path programs() {
        try {
            var app = Files.createDirectories(Jimfs.newFileSystem(Configuration.unix()).getPath("/app"));
            for (var name : List.of("datum-sandbox-program.js", "datum-pdf-program.js")) {
                Files.copy(Path.of(name), app.resolve(name));
            }
            return app;
        } catch (IOException e) {
            throw new UncheckedIOException(e);
        }
    }

    static {
        // A JVM's first runs are slow until its JIT has compiled the runner's own setup, several times
        // over what they settle to: pay for that at start, not on the first requests.
        for (int i = 0; i < 3; i++) {
            try {
                qjs(List.of("-e", "0"), "", 30, 32 * 1024 * 1024);
            } catch (SandboxException ignored) {
                // the budget is wide; a failure here shows on the first request instead
            }
        }
    }

    /** A run that ended without an outcome: a limit cut it off, or a program or rule module would not load. */
    static class SandboxException extends Exception {
        SandboxException(String message) {
            super(message);
        }
    }

    static String qjs(List<String> argv, String request, double seconds, int memory) throws SandboxException {
        // One run: the programs mounted as /app, the request on stdin, the answer on stdout — all the run can
        // reach; Endive hands it nothing else. The limits are Endive's, at the browser's profile: the budget in
        // seconds — past it the run is interrupted, native or bytecode — and the memory in bytes. The budget
        // is this run's alone, a Future of its own cancelled at the timeout, so a run past it interrupts no
        // other: there is no engine-wide clock here, as there is under wasmtime (see main.py). Runaway
        // recursion exhausts the instance's own stack and traps, which ends the run too.
        var out = new ByteArrayOutputStream();
        var err = new ByteArrayOutputStream();
        var args = new ArrayList<>(List.of("qjs", "--std"));  // --std: the std module, which reads stdin
        args.addAll(argv);
        var options = WasiOptions.builder()
                .withArguments(args)
                .withDirectory("/app", APP)
                .withStdin(new ByteArrayInputStream(request.getBytes(StandardCharsets.UTF_8)))
                .withStdout(out)
                .withStderr(err)
                .build();
        var worker = Executors.newSingleThreadExecutor();
        try (var wasi = WasiPreview1.builder().withOptions(options).build()) {
            var imports = ImportValues.builder().addFunction(wasi.toHostFunctions()).build();
            var run = worker.submit(() -> {
                // Building the instance runs _start: qjs's main, through to its exit.
                try (var instance = Qjs.builder()
                        .withImportValues(imports)
                        .withMemoryLimits(new MemoryLimits(QJS_PAGES, memory / 65536))
                        .build()) {
                    return null;
                }
            });
            try {
                run.get((long) (seconds * 1000), TimeUnit.MILLISECONDS);
            } catch (TimeoutException budget) {
                run.cancel(true);  // the interrupt that ends the run
                throw new SandboxException("interrupt");
            }
        } catch (ExecutionException failed) {
            var cause = failed.getCause();
            if (cause instanceof WasiExitException exit) {  // a throw: qjs printed it to stderr and exited 1
                if (exit.exitCode() != 0) {
                    throw new SandboxException(err.toString(StandardCharsets.UTF_8).strip());
                }
            } else {  // a trap: "call stack exhausted", "out of bounds memory access"
                throw new SandboxException(cause.getMessage());
            }
        } catch (InterruptedException interrupted) {
            Thread.currentThread().interrupt();
            throw new SandboxException("interrupted");
        } finally {
            worker.shutdownNow();
        }
        return out.toString(StandardCharsets.UTF_8).stripTrailing();
    }

    static String text(String file) {
        try {
            return Files.readString(Path.of(file));
        } catch (IOException e) {
            throw new UncheckedIOException(e);
        }
    }

    // The template layout, as the builder's PDF mode authored it: the PDF's fields and
    // what fills each — a component's answer, an option's label through template text, a literal.
    static final ObjectNode LAYOUT = layout("intake-template");

    static ObjectNode layout(String id) {
        for (JsonNode layout : FORM.path("pdf").path("layouts")) {
            if (id.equals(layout.path("id").asString())) {
                return (ObjectNode) layout;
            }
        }
        throw new IllegalStateException("the form has no layout " + id);
    }

    // The PDF itself, from this server's disk. The layout's template source names it (a storage this
    // server resolves, not bytes in the definition), and the bytes ride with each request, base64.
    static final String TEMPLATE = base64("templates/customer-intake.pdf");

    // Validation first, so the PDF is filled with the sanitized values: what the form defines, nothing else.
    static final List<String> VALIDATE = List.of("-I", "/app/datum-sandbox-program.js", "-e", "print(__datum_run(std.in.readAsString()));");

    // The PDF program, under the document profile; __datum_pdf's promise settles before qjs exits.
    static final List<String> RENDER = List.of("-I", "/app/datum-pdf-program.js", "-e", "__datum_pdf(std.in.readAsString()).then((json) => print(json));");

    // The fonts the kernel draws the filled fields with when the standard 14 cannot show an answer.
    static Map<String, Object> font(String id, String family, int weight, String file) {
        return Map.of("id", id, "family", family, "weight", weight, "style", "normal", "data", base64("fonts/" + file));
    }

    static final List<Map<String, Object>> FONTS = List.of(font("dejavu-sans", "sans-serif", 400, "DejaVuSans.ttf"), font("dejavu-sans-bold", "sans-serif", 700, "DejaVuSans-Bold.ttf"));

    // What the Country select shows, resolved here: the layout's "{{country}}" writes the option's label.
    static final List<Map<String, String>> COUNTRIES = List.of(
            Map.of("value", "CA", "label", "Canada"), Map.of("value", "US", "label", "United States"), Map.of("value", "MX", "label", "Mexico"));

    // The instant as the program takes it, to the second: the same request gives the same bytes.
    static final DateTimeFormatter CREATED_AT = DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss'.000Z'").withZone(ZoneOffset.UTC);

    // What becomes of the filled fields. "editable" leaves them fields a reader may still change;
    // "readonly" locks each one the fill touched; "flatten" burns the values into the page and drops
    // the fields — an archive copy. The layout's own options are set here, per server.
    static final String FIELDS = "editable";

    static final Logger log = LoggerFactory.getLogger("datum.fill");

    public static void main(String[] args) {
        SpringApplication.run(Application.class, args);
    }

    record FieldError(String field, String code) {}

    @PostMapping("/api/submissions/fill")
    public ResponseEntity<?> submit(@RequestBody JsonNode envelope) throws SandboxException {
        var submission = envelope.path("submission");
        var locale = submission.path("locale").asString("en");
        var context = JSON.createObjectNode()
                .put("formId", FORM.path("id").asString())
                .set("form", FORM.path("root"))
                .set("values", submission.path("values"))
                .put("locale", locale)
                .set("optionSnapshot", JSON.valueToTree(Map.of("countries", COUNTRIES)))  // the lists a choice's data source holds, by source id
                .set("journey", journeyOf(submission));  // the path, worked out again from the values (see journeyOf)
        var outcome = JSON.readTree(qjs(VALIDATE, JSON.writeValueAsString(context), 5, 32 * 1024 * 1024));
        if (!outcome.path("errors").isEmpty()) {  // 422 with codes and fields, never text; the page's messages word them
            var errors = new ArrayList<FieldError>();
            for (JsonNode e : outcome.path("errors")) {
                errors.add(new FieldError(e.path("componentId").asString(null), e.path("code").asString()));
            }
            return ResponseEntity.status(422).body(Map.of("errors", errors));
        }
        // The template layout, inline, with this server's fill options: this server's choice, so no
        // layout's "when" is tried, and the bytes below are that layout's.
        var layout = LAYOUT.deepCopy();
        layout.set("options", JSON.valueToTree(Map.of("flatten", FIELDS.equals("flatten"), "readOnly", FIELDS.equals("readonly"), "appearances", "regenerate")));
        var response = render(JSON.createObjectNode()
                .put("abi", "4.0.0")
                .put("op", "document")
                .set("form", FORM.path("root"))
                .set("layout", layout)
                // The PDF to fill: the bytes the layout's source names, resolved by this server.
                .set("template", JSON.valueToTree(Map.of("data", TEMPLATE)))
                .set("values", outcome.path("values"))
                .put("locale", locale)  // the language template texts resolve in: the country's name, here
                .set("optionSnapshot", JSON.valueToTree(Map.of("country", COUNTRIES)))
                .set("fonts", JSON.valueToTree(FONTS))
                // The only time and identity the program ever sees: the same request gives the same bytes.
                .set("env", JSON.valueToTree(Map.of("createdAt", CREATED_AT.format(Instant.now()), "documentId", UUID.randomUUID().toString()))));
        if (!response.path("ok").asBoolean()) {  // {"code": "template" | "font" | "internal", "message": ...}
            return ResponseEntity.status(500).body(Map.of("error", response.path("error")));
        }
        // The fill report, one entry per mapped field: filled; cleared (no answer, or one a rule hid);
        // missing (the PDF has no field of that name); unsupported (a kind the kernel cannot fill).
        for (JsonNode field : response.path("fields")) {
            log.info("{} {} ({})", field.path("status").asString(), field.path("pdfField").asString(), field.path("kind").asString("-"));
        }
        return ResponseEntity.ok()
                .contentType(MediaType.APPLICATION_PDF)
                .header(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=\"customer-intake-filled.pdf\"")
                .header("X-Page-Count", String.valueOf(response.path("pageCount").asInt()))
                .body(Base64.getDecoder().decode(response.path("bytes").asString()));
    }

    static JsonNode render(ObjectNode request) throws SandboxException {
        return JSON.readTree(qjs(RENDER, JSON.writeValueAsString(request), 15, 256 * 1024 * 1024));
    }

    static String base64(String file) {
        try {
            return Base64.getEncoder().encodeToString(Files.readAllBytes(Path.of(file)));
        } catch (IOException e) {
            throw new UncheckedIOException(e);
        }
    }
}
xml
<!-- pom.xml — beside Application.java. Spring Boot for the endpoint; Endive, the Bytecode Alliance's
     WebAssembly runtime for the JVM, for the engine: its Maven plugin compiles qjs-wasi.wasm at build
     time — to native code through Redline (Cranelift, the code generator behind wasmtime) for the six
     platforms it knows, and to JVM bytecode as the fallback for any other — into the class datum.Qjs,
     packaged in the jar. No native library to install, no JNI: the jar runs wherever a JDK does. Redline
     is experimental in Endive 1.1.0; the bytecode runs the same program the same way, more slowly. -->
<project xmlns="http://maven.apache.org/POM/4.0.0">
  <modelVersion>4.0.0</modelVersion>
  <parent>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-parent</artifactId>
    <version>4.1.1</version>
  </parent>
  <groupId>example</groupId>
  <artifactId>intake</artifactId>
  <version>1.0.0</version>
  <properties>
    <!-- The native runner uses the Panama FFM API, so Java 25; on 17 to 24, redline-runner-jffi-experimental instead. -->
    <java.version>25</java.version>
    <endive.version>1.1.0</endive.version>
  </properties>
  <dependencies>
    <dependency>
      <groupId>org.springframework.boot</groupId>
      <artifactId>spring-boot-starter-webmvc</artifactId>
    </dependency>
    <!-- Endive: the WASI layer (stdin, stdout, the mount) and the runner for the native code. -->
    <dependency>
      <groupId>run.endive</groupId>
      <artifactId>wasi</artifactId>
      <version>${endive.version}</version>
    </dependency>
    <dependency>
      <groupId>run.endive</groupId>
      <artifactId>redline-runner-experimental</artifactId>
      <version>${endive.version}</version>
    </dependency>
    <!-- An in-memory file system: the one directory a run is given. -->
    <dependency>
      <groupId>com.google.jimfs</groupId>
      <artifactId>jimfs</artifactId>
      <version>1.3.2</version>
    </dependency>
  </dependencies>
  <build>
    <plugins>
      <plugin>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-maven-plugin</artifactId>
        <configuration>
          <!-- The native runner is a restricted API: without this the JDK warns at the first run. -->
          <jvmArguments>--enable-native-access=ALL-UNNAMED</jvmArguments>
        </configuration>
      </plugin>
      <plugin>
        <groupId>run.endive</groupId>
        <artifactId>endive-compiler-maven-plugin</artifactId>
        <version>${endive.version}</version>
        <executions>
          <execution>
            <goals>
              <goal>compile</goal>
            </goals>
            <configuration>
              <name>datum.Qjs</name>
              <wasmFile>src/main/resources/qjs-wasi.wasm</wasmFile>
              <redlineExperimental>true</redlineExperimental>
              <!-- QuickJS's interpreter loop, JS_CallInternal, is too big for one JVM method: the bytecode
                   fallback interprets that one function. The native code has no such limit. -->
              <interpreterFallback>WARN</interpreterFallback>
            </configuration>
          </execution>
        </executions>
      </plugin>
    </plugins>
  </build>
</project>

C# (ASP.NET Core) ​

csharp
// Program.cs — the endpoint the page delivers to: the submission validated, then written into an existing PDF form.
//   intake.csproj beside it: ASP.NET Core, and Wasmtime, the .NET embedding of wasmtime.
//   curl -LO https://github.com/quickjs-ng/quickjs/releases/download/v0.16.2/qjs-wasi.wasm
//   dotnet run
//
// The PDF is one this server already has (templates/customer-intake.pdf): an AcroForm whose fields the
// form's template layout maps to the answers. datum-sandbox-program.js re-validates the envelope
// (see Validate on the server) and datum-pdf-program.js fills the PDF — the kernel behind the
// browser's PDF button, in a QuickJS of this process's own: QuickJS-ng's WebAssembly build, under
// wasmtime. Nothing about PDFs is written here.
using System.Text.Json;
using System.Text.Json.Nodes;
using Wasmtime;

var form = JsonNode.Parse(File.ReadAllText("forms/customer-intake.json"))!;

// The journey the answers were given through, from this server's own copy of the form: the
// envelope names it (submission.journey.id) and nothing more. Handed to the sandbox, it has the
// kernel work the path out again from the values, as the browser did: an answer on a page the
// path skipped is judged hidden, and a form field one of the journey's own fields fills or works
// out counts as asked on that page. None named, or one the form does not have: null, and the
// answers are judged as the whole form, which asks for every required field.
JsonNode? JourneyOf(JsonNode submission) =>
    form["journey"]?["journeys"]?.AsArray().FirstOrDefault(journey => (string?)journey!["id"] == (string?)submission["journey"]?["id"]);

// The engine: qjs-wasi.wasm, QuickJS-ng's own WebAssembly build from its release page, compiled
// once, now, and shared (the Sandbox class below). Every request runs it afresh in a store of its
// own, so requests need no lock.
var sandbox = new Sandbox();

// The template layout, as the builder's PDF mode authored it: the PDF's fields and
// what fills each — a component's answer, an option's label through template text, a literal.
var layout = form["pdf"]!["layouts"]!.AsArray().First(layout => (string?)layout!["id"] == "intake-template")!;

// The PDF itself, from this server's disk. The layout's template source names it (a storage this
// server resolves, not bytes in the definition), and the bytes ride with each request, base64.
var template = Convert.ToBase64String(File.ReadAllBytes("templates/customer-intake.pdf"));

// Validation first, so the PDF is filled with the sanitized values: what the form defines, nothing else.
string[] validate = ["-I", "/app/datum-sandbox-program.js", "-e", "print(__datum_run(std.in.readAsString()));"];

// The PDF program, under the document profile; __datum_pdf's promise settles before qjs exits.
string[] render = ["-I", "/app/datum-pdf-program.js", "-e", "__datum_pdf(std.in.readAsString()).then((json) => print(json));"];

// The fonts the kernel draws the filled fields with when the standard 14 cannot show an answer.
static object Font(string id, string family, int weight, string file) =>
    new { id, family, weight, style = "normal", data = Convert.ToBase64String(File.ReadAllBytes(Path.Combine("fonts", file))) };

object[] fonts = [Font("dejavu-sans", "sans-serif", 400, "DejaVuSans.ttf"), Font("dejavu-sans-bold", "sans-serif", 700, "DejaVuSans-Bold.ttf")];

// What the Country select shows, resolved here: the layout's "{{country}}" writes the option's label.
object[] countries = [new { value = "CA", label = "Canada" }, new { value = "US", label = "United States" }, new { value = "MX", label = "Mexico" }];

// What becomes of the filled fields. "editable" leaves them fields a reader may still change;
// "readonly" locks each one the fill touched; "flatten" burns the values into the page and drops
// the fields — an archive copy. The layout's own options are set here, per server.
var fields = "editable";

var app = WebApplication.CreateBuilder(args).Build();
var log = app.Services.GetRequiredService<ILoggerFactory>().CreateLogger("datum.fill");

app.MapPost("/api/submissions/fill", (JsonNode envelope, HttpContext http) =>
{
    var submission = envelope["submission"]!;
    var locale = (string?)submission["locale"] ?? "en";
    // The journey, if the answers came through one: the path is worked out again from the values (see JourneyOf).
    var context = JsonSerializer.Serialize(new { formId = form["id"], form = form["root"], values = submission["values"], locale, journey = JourneyOf(submission), optionSnapshot = new { countries } });
    var outcome = JsonNode.Parse(sandbox.Run(validate, context, 0.25, 32 * 1024 * 1024))!;
    if (outcome["errors"]!.AsArray().Count > 0)  // 422 with codes and fields, never text; the page's messages word them
    {
        var errors = outcome["errors"]!.AsArray().Select(e => new { field = (string?)e!["componentId"], code = (string?)e["code"] });
        return Results.Json(new { errors }, statusCode: 422);
    }
    // The template layout, inline, with this server's fill options: this server's choice, so no
    // layout's "when" is tried, and the bytes below are that layout's.
    var filled = layout.DeepClone();
    filled["options"] = new JsonObject { ["flatten"] = fields == "flatten", ["readOnly"] = fields == "readonly", ["appearances"] = "regenerate" };
    var response = Render(new Dictionary<string, object?>
    {
        ["abi"] = "4.0.0",
        ["op"] = "document",
        ["form"] = form["root"],
        ["layout"] = filled,
        // The PDF to fill: the bytes the layout's source names, resolved by this server.
        ["template"] = new { data = template },
        ["values"] = outcome["values"],
        ["locale"] = locale,  // the language template texts resolve in: the country's name, here
        ["optionSnapshot"] = new { country = countries },
        ["fonts"] = fonts,
        // The only time and identity the program ever sees: the same request gives the same bytes.
        ["env"] = new { createdAt = DateTime.UtcNow.ToString("yyyy-MM-dd'T'HH:mm:ss'.000Z'"), documentId = Guid.NewGuid().ToString() }
    });
    if (!(bool)response["ok"]!)  // {"code": "template" | "font" | "internal", "message": ...}
    {
        return Results.Json(new { error = response["error"] }, statusCode: 500);
    }
    // The fill report, one entry per mapped field: filled; cleared (no answer, or one a rule hid);
    // missing (the PDF has no field of that name); unsupported (a kind the kernel cannot fill).
    foreach (var field in response["fields"]!.AsArray())
    {
        log.LogInformation("{Status} {Field} ({Kind})", (string?)field!["status"], (string?)field["pdfField"], (string?)field["kind"] ?? "-");
    }
    http.Response.Headers["X-Page-Count"] = ((int)response["pageCount"]!).ToString();
    return Results.File(Convert.FromBase64String((string)response["bytes"]!), "application/pdf", "customer-intake-filled.pdf");
});

app.Run();

JsonNode Render(Dictionary<string, object?> request) =>
    JsonNode.Parse(sandbox.Run(render, JsonSerializer.Serialize(request), 15, 256 * 1024 * 1024))!;

/// <summary>A run that ended without an outcome: a limit cut it off, or a program or rule module would not load.</summary>
class SandboxException(string message) : Exception(message);

/// <summary>The engine, compiled once as the process starts, and one run of it per request.</summary>
class Sandbox
{
    readonly Engine engine = new(new Config().WithEpochInterruption(true));  // the time budget: a run past its deadline traps
    readonly Module qjs;
    readonly Linker linker;

    // The clock every budget is kept by, one for all the runs at once: a tick every 50 ms; a run's
    // deadline is its budget in ticks, plus one for the tick already under way when it started. The
    // epoch it advances is the engine's, shared by every store on it, so no run may bump it for
    // itself: a timer of the run's own, fired when its budget was spent, would advance the epoch under
    // every other run in flight too, and cut short one that had set its deadline a tick earlier — a
    // wrong verdict for a submission that was never judged. One clock, and no run can touch another.
    static readonly TimeSpan Tick = TimeSpan.FromSeconds(0.05);
    readonly Timer clock;

    public Sandbox()
    {
        qjs = Module.FromFile(engine, "qjs-wasi.wasm");
        linker = new Linker(engine);
        linker.DefineWasi();
        clock = new Timer(_ => engine.IncrementEpoch(), null, Tick, Tick);
    }

    public string Run(string[] argv, string request, double seconds, long memory)
    {
        // One run: this directory mounted read-only as /app (the programs), the request on stdin, the
        // answer on stdout — all the run can reach; wasmtime hands it nothing else. The limits are
        // wasmtime's, at the browser's profile: the budget in seconds, the memory in bytes. Runaway
        // recursion exhausts the instance's own stack and traps, which ends the run too. WASI's
        // standard streams are files here: the request goes in as one, the answer comes back as one.
        var stdin = Path.GetTempFileName();
        var stdout = Path.GetTempFileName();
        var stderr = Path.GetTempFileName();
        try
        {
            File.WriteAllText(stdin, request);
            string[] args = ["qjs", "--std", .. argv];  // --std: the std module, which reads stdin
            using var store = new Store(engine);
            store.SetLimits(memorySize: memory);
            store.SetEpochDeadline((ulong)Math.Ceiling(seconds / Tick.TotalSeconds) + 1);
            store.SetWasiConfiguration(new WasiConfiguration()
                .WithArgs(args)
                .WithPreopenedDirectory(".", "/app", WasiDirectoryPermissions.Read, WasiFilePermissions.Read)
                .WithStandardInput(stdin)
                .WithStandardOutput(stdout)
                .WithStandardError(stderr));
            try
            {
                linker.Instantiate(store, qjs).GetFunction("_start")!.Invoke();
            }
            catch (WasmtimeException exit) when (exit.ExitCode is int code)  // a throw: qjs printed it to stderr and exited 1
            {
                if (code != 0)
                {
                    throw new SandboxException(File.ReadAllText(stderr).Trim());
                }
            }
            catch (TrapException trap)  // Interrupt: the budget; StackOverflow: the recursion
            {
                throw new SandboxException(trap.Type.ToString());
            }
            return File.ReadAllText(stdout).TrimEnd('\n');
        }
        finally
        {
            File.Delete(stdin);
            File.Delete(stdout);
            File.Delete(stderr);
        }
    }
}
xml
<!-- intake.csproj — beside Program.cs. ASP.NET Core for the endpoint; Wasmtime, the Bytecode Alliance's
     .NET embedding of wasmtime, for the engine: the runtime main.py runs under, as a NuGet package that
     carries its native library for Windows, macOS and Linux on x64 and arm64. Nothing else to install. -->
<Project Sdk="Microsoft.NET.Sdk.Web">
  <PropertyGroup>
    <TargetFramework>net10.0</TargetFramework>
    <Nullable>enable</Nullable>
    <ImplicitUsings>enable</ImplicitUsings>
  </PropertyGroup>
  <ItemGroup>
    <PackageReference Include="Wasmtime" Version="44.0.0" />
  </ItemGroup>
</Project>

Node.js (Express) ​

js
// main.mjs — the endpoint the page delivers to: the submission validated, then written into an existing PDF form.
//   qjs.mjs beside it: the engine, one process per run — Node 22 or later, nothing to install for it.
//   npm install express
//   curl -LO https://github.com/quickjs-ng/quickjs/releases/download/v0.16.2/qjs-wasi.wasm
//   node main.mjs
//
// The PDF is one this server already has (templates/customer-intake.pdf): an AcroForm whose fields the
// form's template layout maps to the answers. datum-sandbox-program.js re-validates the envelope
// (see Validate on the server) and datum-pdf-program.js fills the PDF — the kernel behind the
// browser's PDF button, in a QuickJS of this process's own: QuickJS-ng's WebAssembly build, under
// node:wasi. Nothing about PDFs is written here.
import { spawn } from "node:child_process";
import { randomUUID } from "node:crypto";
import { copyFileSync, mkdtempSync, readFileSync, rmSync } from "node:fs";
import { tmpdir } from "node:os";
import { join } from "node:path";
import { fileURLToPath } from "node:url";

import express from "express";

const FORM = JSON.parse(readFileSync("forms/customer-intake.json", "utf8"));

// The journey the answers were given through, from this server's own copy of the form: the
// envelope names it (submission.journey.id) and nothing more. Handed to the sandbox, it has the
// kernel work the path out again from the values, as the browser did: an answer on a page the
// path skipped is judged hidden, and a form field one of the journey's own fields fills or works
// out counts as asked on that page. None named, or one the form does not have: null, and the
// answers are judged as the whole form, which asks for every required field.
const journeyOf = (submission) => FORM.journey?.journeys?.find((journey) => journey.id === submission.journey?.id) ?? null;

// The engine: qjs-wasi.wasm, QuickJS-ng's own WebAssembly build from its release page, on V8 with
// node:wasi (qjs.mjs) — nothing to install. Every request runs it in a process of its own, so requests
// need no lock and share nothing: V8 has no store to hang a limit on, as wasmtime has, so the
// operating system draws the line instead, and the flag and the timeout below are that process's.
const RUNNER = fileURLToPath(new URL("qjs.mjs", import.meta.url));

// What a run can reach: one directory holding the two programs, and nothing else — not this
// directory, not the disk. Node's WASI mounts a directory read-write and does not promise the
// sandbox wasmtime's does, so a run is started in a directory of its own with nothing else in it.
const APP = programs();

function programs() {
  const app = mkdtempSync(join(tmpdir(), "datum-"));
  for (const name of ["datum-sandbox-program.js", "datum-pdf-program.js"]) {
    copyFileSync(name, join(app, name));
  }
  // Gone with the process: at its exit, and on the signals that would otherwise end it without one.
  process.on("exit", () => rmSync(app, { recursive: true, force: true }));
  for (const signal of ["SIGINT", "SIGTERM"]) process.once(signal, () => process.exit());
  return app;
}

/** A run that ended without an outcome: a limit cut it off, or a program or rule module would not load. */
class SandboxError extends Error {}

function qjs(argv, request, seconds, memory) {
  // One run: a process started in the programs' directory, which it mounts as /app, the request on
  // its stdin, the answer on its stdout — all the run can reach; the runner hands it nothing else.
  // The limits are the process's, at the browser's profile: the memory in bytes, as the pages V8
  // lets the module's memory grow to, and the budget in seconds, a timeout that ends the process —
  // this run's alone, so a run past it interrupts no other: there is no engine-wide clock here, as
  // there is under wasmtime (see main.py). The budget counts the process's own start and the
  // module's compilation, a fifth of a second: it is a bound on a runaway rule, not a latency to
  // meet. Runaway recursion ends the run too: QuickJS's own stack check throws, and V8 traps the
  // instance's stack if it does not.
  return new Promise((resolve, reject) => {
    const flags = ["--wasm-max-mem-pages=" + memory / 65536, "--disable-warning=ExperimentalWarning"];
    const run = spawn(process.execPath, [...flags, RUNNER, ...argv], { cwd: APP, timeout: seconds * 1000 });
    const out = [];
    const err = [];
    run.stdout.on("data", (chunk) => out.push(chunk));
    run.stderr.on("data", (chunk) => err.push(chunk));
    run.stdin.on("error", () => {});  // a run that ended before reading its request: what ended it is on stderr
    run.stdin.end(request);
    run.on("error", reject);
    run.on("close", (code, signal) => {
      if (signal !== null) {  // the budget: the timeout ended the process
        reject(new SandboxError("interrupt"));
      } else if (code !== 0) {  // a throw: qjs printed it to stderr and exited 1
        reject(new SandboxError(Buffer.concat(err).toString().trim()));
      } else {
        resolve(Buffer.concat(out).toString().trimEnd());
      }
    });
  });
}

// The template layout, as the builder's PDF mode authored it: the PDF's fields and
// what fills each — a component's answer, an option's label through template text, a literal.
const LAYOUT = FORM.pdf.layouts.find((layout) => layout.id === "intake-template");

// The PDF itself, from this server's disk. The layout's template source names it (a storage this
// server resolves, not bytes in the definition), and the bytes ride with each request, base64.
const TEMPLATE = readFileSync("templates/customer-intake.pdf").toString("base64");

// Validation first, so the PDF is filled with the sanitized values: what the form defines, nothing else.
const VALIDATE = ["-I", "/app/datum-sandbox-program.js", "-e", "print(__datum_run(std.in.readAsString()));"];

// The PDF program, under the document profile; __datum_pdf's promise settles before qjs exits.
const RENDER = ["-I", "/app/datum-pdf-program.js", "-e", "__datum_pdf(std.in.readAsString()).then((json) => print(json));"];

// The fonts the kernel draws the filled fields with when the standard 14 cannot show an answer.
function font(id, family, weight, file) {
  return { id, family, weight, style: "normal", data: readFileSync(join("fonts", file)).toString("base64") };
}

const FONTS = [font("dejavu-sans", "sans-serif", 400, "DejaVuSans.ttf"), font("dejavu-sans-bold", "sans-serif", 700, "DejaVuSans-Bold.ttf")];

// What the Country select shows, resolved here: the layout's "{{country}}" writes the option's label.
const COUNTRIES = [{ value: "CA", label: "Canada" }, { value: "US", label: "United States" }, { value: "MX", label: "Mexico" }];

// What becomes of the filled fields. "editable" leaves them fields a reader may still change;
// "readonly" locks each one the fill touched; "flatten" burns the values into the page and drops
// the fields — an archive copy. The layout's own options are set here, per server.
const FIELDS = "editable";

const app = express();
app.use(express.json());

app.post("/api/submissions/fill", async (req, res) => {
  const { submission } = req.body;
  const locale = submission.locale ?? "en";
  // The journey, if the answers came through one: the path is worked out again from the values (see journeyOf).
  const context = { formId: FORM.id, form: FORM.root, values: submission.values, locale, journey: journeyOf(submission), optionSnapshot: { countries: COUNTRIES } };
  const outcome = JSON.parse(await qjs(VALIDATE, JSON.stringify(context), 5, 32 * 1024 * 1024));
  if (outcome.errors.length > 0) {  // 422 with codes and fields, never text; the page's messages word them
    const errors = outcome.errors.map((e) => ({ field: e.componentId ?? null, code: e.code }));
    return res.status(422).json({ errors });
  }
  const response = await render({
    abi: "4.0.0",
    op: "document",
    form: FORM.root,
    // The template layout, inline, with this server's fill options: this server's choice, so no
    // layout's "when" is tried, and the bytes below are that layout's.
    layout: { ...LAYOUT, options: { flatten: FIELDS === "flatten", readOnly: FIELDS === "readonly", appearances: "regenerate" } },
    // The PDF to fill: the bytes the layout's source names, resolved by this server.
    template: { data: TEMPLATE },
    values: outcome.values,
    locale,  // the language template texts resolve in: the country's name, here
    optionSnapshot: { country: COUNTRIES },
    fonts: FONTS,
    // The only time and identity the program ever sees: the same request gives the same bytes.
    env: { createdAt: new Date().toISOString(), documentId: randomUUID() }
  });
  if (!response.ok) {  // {"code": "template" | "font" | "internal", "message": ...}
    return res.status(500).json({ error: response.error });
  }
  // The fill report, one entry per mapped field: filled; cleared (no answer, or one a rule hid);
  // missing (the PDF has no field of that name); unsupported (a kind the kernel cannot fill).
  for (const field of response.fields) {
    console.info(`${field.status} ${field.pdfField} (${field.kind ?? "-"})`);
  }
  res.set({ "Content-Type": "application/pdf", "Content-Disposition": 'attachment; filename="customer-intake-filled.pdf"', "X-Page-Count": String(response.pageCount) });
  res.send(Buffer.from(response.bytes, "base64"));
});

app.listen(8000);

async function render(request) {
  return JSON.parse(await qjs(RENDER, JSON.stringify(request), 15, 256 * 1024 * 1024));
}
js
// qjs.mjs — one run of the engine, in a process of its own: qjs-wasi.wasm, QuickJS-ng's own
// WebAssembly build from its release page, on V8, with node:wasi for its system interface — nothing
// to install beside Node 22. The endpoint (main.mjs) starts one of these per request:
//   node --wasm-max-mem-pages=<pages> --disable-warning=ExperimentalWarning qjs.mjs <qjs arguments>
// The request comes in on stdin and the answer goes out on stdout; the directory the process was
// started in is mounted as /app, all the run can reach. The flag is the memory the module may grow
// to, per process. The warning silenced is node:wasi's own, that it is still marked experimental,
// so that stderr is the run's alone.
import { readFileSync } from "node:fs";
import { WASI } from "node:wasi";

const wasi = new WASI({
  version: "preview1",
  args: ["qjs", "--std", ...process.argv.slice(2)],  // --std: the std module, which reads stdin
  preopens: { "/app": "." },
  returnOnExit: true  // qjs's exit code comes back from start() below, and becomes this process's
});
const qjs = await WebAssembly.compile(readFileSync(new URL("qjs-wasi.wasm", import.meta.url)));
const instance = await WebAssembly.instantiate(qjs, wasi.getImportObject());
process.exitCode = wasi.start(instance);

What to notice ​

  • The PDF never sits in the definition. The layout's template source names a file the server resolves. The endpoint reads the bytes from its own disk and sends them with each request, base64.
  • The server picks the layout. The request carries the template layout inline, so no layout's condition is tried and the bytes are that layout's. Sending only "layoutId": "intake-template" would not select it: an id picks from the definition's pdf block, and this request carries none, so the layout has to be sent inline as here.
  • What becomes of the fields. FIELDS is the endpoint's constant: editable leaves fields a reader may still change, readonly locks each one the fill touched, and flatten draws the values into the page and drops the fields, for an archive copy. This example leaves them editable.
  • The fill report. The answer lists every mapped field with its status: filled; cleared when there is no answer or a rule hid it; missing when the PDF has no field of that name; unsupported for a kind the kernel cannot fill. The endpoint writes it to its log.
  • The options are the server's. {{country}} writes the label from the list the endpoint resolved itself ("Canada"), not the code the form stores ("CA").

Next ​

MIT licence. Your forms, your data, your keys.