diff --git a/.github/workflows/compiler.yml b/.github/workflows/compiler.yml index 0faa5d842..1672c499a 100644 --- a/.github/workflows/compiler.yml +++ b/.github/workflows/compiler.yml @@ -10,12 +10,52 @@ name: compiler on: push: branches: [main] - paths: ["compiler/**", ".github/workflows/compiler.yml"] + paths: ["compiler/**", "ref/**", "spec/**", "scenarios/**", "examples/**", ".github/workflows/compiler.yml"] pull_request: - paths: ["compiler/**", ".github/workflows/compiler.yml"] + paths: ["compiler/**", "ref/**", "spec/**", "scenarios/**", "examples/**", ".github/workflows/compiler.yml"] workflow_dispatch: jobs: + parity: + runs-on: ubuntu-latest + strategy: + fail-fast: false + matrix: + include: + - { name: checker, flags: "" } + - { name: lowering, flags: "--lower" } + - { name: dev lowering, flags: "--lower --dev" } + name: parity (${{ matrix.name }}) + steps: + - uses: actions/checkout@v5 + - uses: dtolnay/rust-toolchain@master + with: + toolchain: 1.99.1 + - uses: Swatinem/rust-cache@v2 + with: + workspaces: compiler + - uses: actions/setup-node@v5 + with: + node-version: 24 + - uses: pnpm/action-setup@v4 + with: + version: 11.1.1 + - run: sh ref/scripts/solid-next.sh + - run: npm ci --prefix ref + - if: matrix.flags == '' + run: npm --prefix ref run crate + - if: matrix.flags != '' + # Keep local lowering strict. In CI, tolerate only the named, existing + # mismatches until they are fixed; a crash or a different set fails. + run: | + log=$(mktemp) + status=0 + npm --prefix ref run crate -- ${{ matrix.flags }} >"$log" 2>&1 || status=$? + cat "$log" + test "$status" -le 1 + grep -Eq '^[0-9]+/[0-9]+ programs lowered alike' "$log" + diff -u ref/lowering-baseline.txt <(grep '^FAIL ' "$log" || true) + build: strategy: fail-fast: false diff --git a/.github/workflows/rx-map.yml b/.github/workflows/rx-map.yml new file mode 100644 index 000000000..77b691edf --- /dev/null +++ b/.github/workflows/rx-map.yml @@ -0,0 +1,71 @@ +# The map and its live bridge (tooling/rx-map/): the whole `npm test`, including the real-host suite (time travel, HMR, +# read-only viewing, per-instance values) against a running .rx app in headless Chromium. That suite needs a Solid +# with openView, built from the commit pinned in tooling/rx-map/solid-view.json; under CI it fails rather than skips +# when that build is missing (review 1, finding 5). +name: rx-map + +on: + push: + branches: [main] + paths: ["tooling/rx-map/**", "ref/compile/rt-web.ts", "ref/compile/emit.ts", "runtime/**", "compiler/**", ".github/workflows/rx-map.yml"] + pull_request: + paths: ["tooling/rx-map/**", "ref/compile/rt-web.ts", "ref/compile/emit.ts", "runtime/**", "compiler/**", ".github/workflows/rx-map.yml"] + workflow_dispatch: + +jobs: + test: + runs-on: ubuntu-latest + timeout-minutes: 45 + env: + CI: "true" + steps: + - uses: actions/checkout@v5 + - uses: dtolnay/rust-toolchain@master + with: + toolchain: 1.99.1 + - uses: Swatinem/rust-cache@v2 + with: + workspaces: compiler + - uses: actions/setup-node@v5 + with: + node-version: 24 + - uses: pnpm/action-setup@v4 + with: + version: 11 + - name: Build the published map page against the stock Solid pin + run: | + sh ref/scripts/solid-next.sh + npm ci --prefix ref + - name: The compiler (rxc and the Node-API build the Vite front end loads) + working-directory: compiler + run: | + npm ci + npx napi build --platform --release --features node --manifest-path ./Cargo.toml -- --lib + cargo build --release --bin rxc + - name: The runtime + working-directory: runtime + run: | + npm ci + npm run build + - name: Solid with openView, at the pinned commit + run: | + repo=$(node -p 'require("./tooling/rx-map/solid-view.json").repo') + commit=$(node -p 'require("./tooling/rx-map/solid-view.json").commit') + branch=$(node -p 'require("./tooling/rx-map/solid-view.json").branch') + git clone --filter=blob:none --branch "$branch" "https://github.com/$repo" "$RUNNER_TEMP/solid-view" + git -C "$RUNNER_TEMP/solid-view" checkout "$commit" + cd "$RUNNER_TEMP/solid-view" + pnpm install --frozen-lockfile + for p in signals solid web; do (cd "packages/$p" && pnpm run build); done + - name: Playwright's Chromium + working-directory: tooling/rx-map + run: | + npm install --no-save playwright + npx playwright install --with-deps chromium + - name: npm test (the real-host suite is required here) + working-directory: tooling/rx-map + env: + SOLID_VIEW: ${{ runner.temp }}/solid-view + SOLID_PACKAGES: ${{ runner.temp }}/solid-view/packages + RXC: ${{ github.workspace }}/compiler/target/release/rxc + run: npm test diff --git a/CHANGELOG.md b/CHANGELOG.md index e4b64a8b2..2732700b7 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,6 +2,18 @@ ## Unreleased +**Breaking** + +- MO-8c: a real `./api` implementation beside the importing module wins over the injected test API, even if + `createApp({ api })` is set. A test API call with no injected implementation now throws `MISSING_TEST_API`. +- `DEAD_TYPED_BOUNDARY` rejects a typed error boundary proven shadowed by an inner catch-all. Put the typed + boundary inside the catch-all. +- `STYLE_SCOPE` rejects a style block outside a supported style scope; move it into the component that owns the view. +- String and template escapes are cooked in the compiler; programs relying on the previous literal backslashes + must escape those backslashes explicitly. +- Multiline JSX whitespace follows the view whitespace rules (07 §4). Use an explicit `{" "}` where spacing + between pieces must survive. + **Changed** - `catch` follows only an `await`: `await f(x) catch (e) => alt` makes a matching rejection the answer. A `catch` after @@ -30,6 +42,9 @@ - `guide/async.md`: "One store over the server"; the `GUESS_WHILE_LOADING` advice says what holds when a selection changes while a guess is out (05 DV-22). +- `@reactivescript/map` adds static and live app maps, read-only MCP queries, time travel, and dev hot replacement. + The latter two have requirements listed in the map package README. + ## 0.3.1 **New** diff --git a/compiler/Cargo.lock b/compiler/Cargo.lock index 3b4082923..e0593468e 100644 --- a/compiler/Cargo.lock +++ b/compiler/Cargo.lock @@ -990,6 +990,8 @@ dependencies = [ name = "reactivescript" version = "0.3.1" dependencies = [ + "dragonbox_ecma", + "htmlize", "indexmap", "napi", "napi-build", diff --git a/compiler/Cargo.toml b/compiler/Cargo.toml index 8ac3e98ad..26d871011 100644 --- a/compiler/Cargo.toml +++ b/compiler/Cargo.toml @@ -23,6 +23,8 @@ node = ["dep:napi", "dep:napi-derive"] [dependencies] indexmap = "2" regex = "1" +htmlize = { version = "1", features = ["unescape"] } +dragonbox_ecma = "0.1" serde_json = { version = "1", features = ["preserve_order"] } # CP-1b: Solid's compiler, at the commit ref/ runs on (ref/SOLID_NEXT), and the Oxc release it is built against (CP-1c: # the program crosses the seam, so the versions must match) diff --git a/compiler/README.md b/compiler/README.md index 17769fb84..9169cf2a1 100644 --- a/compiler/README.md +++ b/compiler/README.md @@ -29,16 +29,18 @@ cargo build --release target/release/rxc check ../examples/todo.rx # diagnostics target/release/rxc check --json ../examples/todo.rx # … with ranges, for an editor or an agent (CP-8d) target/release/rxc project ../examples/todo.rx # the TSX projection, with mappings onto .rx (CP-8c) -target/release/rxc model ../examples/todo.rx # the resolved model, as JSON +target/release/rxc model ../examples/todo.rx # the resolved model, as JSON (keys relative to the cwd, CP-6f) target/release/rxc serve # a language server's requests, a JSON line each (CP-8e) cargo build --lib --release --target wasm32-unknown-unknown # … the same requests as WebAssembly (src/wasm.rs), what the server loads target/release/rxc compile ../examples/todo.rx --out out # modules (dom; --target ssr|universal), source maps onto .rx, style.css target/release/rxc app ../examples/todo.rx # the same as JSON, imports by .rx path: what the Vite front end gets +target/release/rxc app ../examples/todo.rx --dev # a dev build: creating calls under __rt.key (CP-4b; --root dir, else the cwd); also compile target/release/rxc check --spa ../examples/todo.rx # a client-only build: a first load nothing holds is an error (08 CN-3d); also compile, app npm --prefix ../ref run crate # CP-5: the crate against ref/ on every program npm --prefix ../ref run crate -- --project # … and the TSX projection, text for text, every mapping checked RX_CRATE=1 npm --prefix ../ref run types # the types scenarios, on the crate's projection npm --prefix ../ref run crate -- --lower # … and the lowered JavaScript, for every target, and its source maps +npm --prefix ../ref run crate -- --lower --dev # … the same for dev builds RX_CRATE=1 npm --prefix ../ref run compiled # the scenarios, run on the crate's output RX_CRATE=1 npm --prefix ../ref run ssr # … served and hydrated from the crate's output ``` diff --git a/compiler/graph.mjs b/compiler/graph.mjs new file mode 100644 index 000000000..41c6b0f3f --- /dev/null +++ b/compiler/graph.mjs @@ -0,0 +1,252 @@ +// Turns `rxc model`'s resolved model (spec/11 CP-6) into the graph used by HMR and the map: one node per named thing (a source, an +// equation, an action, a function, a server function, a context, an error class, a JS import) and one per unnamed site (a +// markup read, a handler, a prop, an effect), regions as nested frames, and an edge per read, write and call. Imports of +// another .rx module are folded into the symbol they name, so a module's state is drawn once, where it lives. +import { readFileSync } from "node:fs"; +import { dirname, resolve, relative } from "node:path"; + +/** Computations that are a named symbol's own body: they draw as that symbol, not as a separate site. */ +const OWNED = new Set(["seed", "memo", "question", "keyed", "deferred", "action", "fn", "server", "default"]); + +export function buildGraph(model, { root = process.cwd(), source = f => readFileSync(f, "utf8") } = {}) { + const files = model.map(m => resolve(root, m.file)); + const rel = f => relative(root, f) || f; + const nodes = [], edges = [], regions = [], lines = {}; + const symNode = new Map(); // `${mi}:${symId}` → node id (after import folding) + const byName = new Map(); // `${abs}:${name}` → node id, for import folding + + const src = files.map(f => { try { return source(f).split("\n"); } catch { return []; } }); + // every line of every module: the map labels control flow (`if …`, `for …`, `loading on(…)`) from the source + src.forEach((ls, mi) => { const m = (lines[rel(files[mi])] = {}); ls.forEach((t, i) => { if (t.trim()) m[i + 1] = t; }); }); + const keepLine = () => {}; + + // The model marks an imported source with `from`; other imported names (actions, equations, components, error + // classes) carry no `from`, so read it off their import line. + const importFrom = (mi, s) => { + if (s.from) return s.from; + const text = src[mi][s.line - 1] ?? ""; + const m = /^\s*import\b[^"']*["']([^"']+)["']/.exec(text); + if (!m || !/\.rx$/.test(m[1])) return null; + return new RegExp(`[{,\\s]${s.name}[\\s,}]`).test(text) ? m[1] : null; + }; + model.forEach((m, mi) => { for (const s of m.symbols) { const f = importFrom(mi, s); if (f) s.from = f; } }); + + // 1. regions and own symbols + model.forEach((m, mi) => { + const file = rel(files[mi]); + for (const r of m.regions) { + regions.push({ id: `${mi}:r${r.id}`, mod: mi, kind: r.kind, name: r.name ?? null, + parent: r.parent == null ? null : `${mi}:r${r.parent}`, + ...(r.shadowed != null ? { shadowed: `${mi}:r${r.shadowed}` } : {}), + // a typed `errored (e: X)` an inner catch-all already catches for (the model says so): it never shows + ...(r.deadTyped || r.dead_typed ? { deadTyped: true } : {}), + ...(r.outline ? { outline: r.outline.map(p => "site" in p ? { ...p, site: `${mi}:c${p.site}` } + : "region" in p ? { ...p, region: `${mi}:r${p.region}` } : { ...p }) } : {}) }); + for (const p of r.outline ?? []) if (p.line != null) keepLine(mi, p.line); + } + for (const s of m.symbols) { + if (s.from) continue; // folded below + const id = `${mi}:s${s.id}`; + const spec = /^\s*import\b[^"']*?\bfrom\s+["']([^"']+)["']/.exec(src[mi].slice(s.line - 1, s.line + 20).join("\n"))?.[1]; + nodes.push({ id, mod: mi, file, kind: s.kind, name: s.name, line: s.line, region: `${mi}:r${s.region}`, + io: !!s.io, question: !!s.question, async: !!s.question, world: s.kind === "import", + ...(spec && !spec.endsWith(".rx") ? { jsFrom: spec } : {}), + ...(s.key ? { rxKey: s.key } : {}) }); + symNode.set(`${mi}:${s.id}`, id); + byName.set(`${files[mi]}:${s.name}`, id); + keepLine(mi, s.line); + } + }); + + // 2. fold `.rx` imports into the symbol they name; props resolve to their component + model.forEach((m, mi) => { + for (const s of m.symbols) { + if (!s.from) continue; + const target = resolve(dirname(files[mi]), s.from); + const id = byName.get(`${target}:${s.name}`) ?? byName.get(`${target.replace(/\.rx$/, "")}.rx:${s.name}`); + if (id) symNode.set(`${mi}:${s.id}`, id); + else { + const nid = `${mi}:s${s.id}`; + nodes.push({ id: nid, mod: mi, file: rel(files[mi]), kind: s.kind, name: s.name, line: s.line, + region: `${mi}:r${s.region}`, io: !!s.io, question: !!s.question, async: !!s.question, world: true, from: s.from }); + symNode.set(`${mi}:${s.id}`, nid); + keepLine(mi, s.line); + } + } + }); + + // 3. computations: owned ones merge into their symbol, the rest become sites + const nodeById = new Map(nodes.map(n => [n.id, n])); + model.forEach((m, mi) => { + const file = rel(files[mi]); + const compOwner = new Map(); // computation id → node id + const ownerOf = c => { + if (OWNED.has(c.kind) && c.name) { + const s = m.symbols.find(s => s.name === c.name && !s.from && s.kind !== "props" + && (s.region === c.region || s.line === c.line)) ?? m.symbols.find(s => s.name === c.name && !s.from); + if (s) return symNode.get(`${mi}:${s.id}`); + } + return null; + }; + for (const c of m.computations) { + let owner = c.kind === "apply" && c.in != null ? compOwner.get(c.in) : ownerOf(c); + if (!owner) { + owner = `${mi}:c${c.id}`; + const name = c.kind === "provide" ? `provide ${c.name}` : c.at ?? c.name ?? c.kind; + nodes.push({ id: owner, mod: mi, file, kind: c.kind, site: true, name, line: c.line, region: `${mi}:r${c.region}` }); + keepLine(mi, c.line); + if (c.kind === "prop" && c.at) { + // ``: the value flows into Row's props + const comp = c.at.split(" ")[0]; + const props = model.flatMap((mm, mj) => mm.symbols.filter(s => s.kind === "props" && mm.regions.find(r => r.id === s.region)?.name === comp).map(s => symNode.get(`${mj}:${s.id}`)))[0]; + if (props) edges.push({ from: owner, to: props, type: "passes", field: c.at.split(" ")[1] ?? null }); + } + if (c.kind === "provide") { + const ctx = m.symbols.find(s => s.kind === "context" && s.name === c.name); + if (ctx) edges.push({ from: owner, to: symNode.get(`${mi}:${ctx.id}`), type: "write", op: "provide" }); + } + } else { + const n = nodeById.get(owner); + if (n && c.kind === "question") n.async = true; + if (n && (c.kind === "keyed" || c.kind === "deferred")) { n.async = n.async || c.calls.length > 0; n.flavor = c.kind; } + } + compOwner.set(c.id, owner); + for (const r of c.reads) { + const from = symNode.get(`${mi}:${r.sym}`); + if (from && from !== owner) edges.push({ from, to: owner, type: "read", mode: r.mode, probe: r.probe ?? null, field: r.field ?? null, line: c.line }); + } + for (const w of c.writes) { + const to = symNode.get(`${mi}:${w.sym}`); + if (to) edges.push({ from: owner, to, type: "write", op: w.op, path: !!w.path, ...(w.field ? { field: w.field } : {}), line: c.line }); + } + for (const k of c.calls) { + const to = symNode.get(`${mi}:${k}`); + if (to && to !== owner) edges.push({ from: owner, to, type: "call", line: c.line }); + } + } + // a component rendered somewhere: the region that holds it points at the component + for (const r of m.regions) { + if (r.kind !== "children" || !r.name) continue; + const s = m.symbols.find(s => s.kind === "comp" && s.name === r.name); + const to = s && symNode.get(`${mi}:${s.id}`); + if (to) edges.push({ from: `${mi}:r${r.id}`, to, type: "renders" }); + } + }); + + // "can be pending" is "awaits": the model marks a source with a standing question as a question even when it never + // awaits (`source editing = null`), and an equation whose await sits inside `?:` as a plain memo. The declaration's + // own line says which. + for (const n of nodes) { + if (n.site || (n.kind !== "source" && n.kind !== "eq") || n.world) continue; + const mi = n.mod, text = src[mi]?.[n.line - 1] ?? ""; + const awaits = /\bawait\b/.test(text); + if (n.kind === "source") n.async = awaits; + else n.async = n.async || awaits; + } + + // dedupe identical edges (a handler that reads the same thing twice) + const seen = new Set(); + const uniq = edges.filter(e => { const k = JSON.stringify([e.from, e.to, e.type, e.mode, e.op, e.probe, e.field]); return seen.has(k) ? false : (seen.add(k), true); }); + const graph = { modules: files.map(rel), absModules: files, nodes, edges: uniq, regions, lines }; + controlHeads(graph, mi => src[mi] ?? []); + addKeys(graph); + return graph; +} + +/** How each control-flow construct reads in source: the pattern of its header line, and its label. */ +export const CONTROL = { + then: [/(?:^|[{\s])if\s+(.+?)\s*\{/, m => `if ${m[1]}`], + else: [/\belse\s+if\s+(.+?)\s*\{|\belse\b/, m => (m[1] ? `else if ${m[1]}` : "else")], + for: [/\{\s*for\s+(.+?)\s*\{/, m => `for ${m[1]}`], + loading: [/\bloading\b\s*(on\s*\([^)]*\))?/, m => (m[1] ? `loading ${m[1].replace(/\s+/g, "")}` : "loading")], + errored: [/\berrored\b(?:\s+fallback\s*\(([^)]*)\))?/, m => (m[1] ? `errored (${m[1].trim()})` : "errored")], +}; + +/** + * Gives each `if` / `else` / `for` / `loading` / `errored` region its own header: `head = { line, text }`, e.g. + * `errored (e: NotFound)`. The model has no line for a region, so it is read off the source: the nearest header line + * above the region's first line. Nested constructs are placed first, and a region's search starts above the headers of + * the constructs inside it, so an outer `errored (e)` is not labelled with an inner `errored (e: NotFound)`. + */ +export function controlHeads(graph, sourceOf) { + const kids = new Map(), own = new Map(); + for (const r of graph.regions) if (r.parent) (kids.get(r.parent) ?? kids.set(r.parent, []).get(r.parent)).push(r); + for (const n of graph.nodes) if (n.region && n.line) (own.get(n.region) ?? own.set(n.region, []).get(n.region)).push(n.line); + const firstMemo = new Map(), headMemo = new Map(); + const first = r => { + if (!firstMemo.has(r.id)) { firstMemo.set(r.id, 1e9); firstMemo.set(r.id, Math.min(...(own.get(r.id) ?? []), ...(kids.get(r.id) ?? []).map(first), 1e9)); } + return firstMemo.get(r.id); + }; + const head = r => { + if (headMemo.has(r.id)) return headMemo.get(r.id); + headMemo.set(r.id, null); + let bound = first(r); + const below = rr => { for (const k of kids.get(rr.id) ?? []) { const h = CONTROL[k.kind] && head(k); if (h?.line) bound = Math.min(bound, h.line - 1); else below(k); } }; + below(r); + const pat = CONTROL[r.kind], ls = sourceOf(r.mod); + let h = null; + if (pat && bound < 1e9) for (let i = bound; i >= Math.max(1, bound - 40); i--) { + const m = ls[i - 1] && pat[0].exec(ls[i - 1]); + if (m) { h = { line: i, text: pat[1](m) }; break; } + } + headMemo.set(r.id, h); + return h; + }; + for (const r of graph.regions) if (CONTROL[r.kind]) { const h = head(r); if (h) r.head = h; } + return graph; +} + +/** + * Stable keys, so two versions of one program can be lined up (`--diff`) and a running program's nodes can be found on + * the map (live mode). Ids are positions in the model and lines move; a key is what a reader would call the same thing. + * + * - A named node: `||[#n]`, the key a dev build gives the Solid nodes it creates (as `rx:`). + * `scope` is the enclosing component's name, or empty at module scope. `#n` tells apart the 2nd, 3rd… declaration of + * one name in one scope of a module, in source order (two `if` branches). When the model carries the key (`key` on a + * symbol), that one is used, so the map and the build cannot disagree. + * - A view site has no name: it is keyed by its module, the chain of regions it sits in, and what it is, with an ordinal + * for look-alikes (and `sig`, what it reads, to pair look-alikes in a diff). + */ +export function addKeys(g) { + const regionById = new Map(g.regions.map(r => [r.id, r])); + const kidsOf = new Map(); + for (const r of g.regions) (kidsOf.get(r.parent) ?? kidsOf.set(r.parent, []).get(r.parent)).push(r); + const nodeLine = new Map(); + for (const n of g.nodes) nodeLine.set(n.region, Math.min(nodeLine.get(n.region) ?? 1e9, n.line ?? 1e9)); + const firstLine = r => Math.min(nodeLine.get(r.id) ?? 1e9, ...(kidsOf.get(r.id) ?? []).map(firstLine)); + const path = new Map(); + const walk = (parentId, prefix) => { + const kids = (kidsOf.get(parentId) ?? []).slice().sort((a, b) => firstLine(a) - firstLine(b)); + const count = {}; + for (const r of kids) { + const base = r.kind + (r.name ? `:${r.name}` : ""); + const i = (count[base] = (count[base] ?? -1) + 1); + const p = `${prefix}/${base}${i ? `#${i}` : ""}`; + path.set(r.id, p); + walk(r.id, p); + } + }; + for (const r of g.regions) if (r.parent == null) { + const base = r.kind === "program" ? "" : `/${r.kind}${r.name ? `:${r.name}` : ""}`; + path.set(r.id, base); walk(r.id, base); + } + for (const r of g.regions) r.key = `${g.modules[r.mod]}|${path.get(r.id)}`; + const reads = new Map(); + for (const e of g.edges) if (e.type === "read") (reads.get(e.to) ?? reads.set(e.to, []).get(e.to)).push(e.from); + const nodeById = new Map(g.nodes.map(n => [n.id, n])); + // the scope of a named node: the nearest component region up its chain + const scopeOf = id => { + for (let r = regionById.get(id); r; r = regionById.get(r.parent)) if (r.kind === "component") return r.name ?? ""; + return ""; + }; + const taken = {}; + for (const n of g.nodes.slice().sort((a, b) => a.line - b.line)) { + if (n.site) { + const where = `${g.modules[n.mod]}|${path.get(n.region) ?? ""}`; + n.base = `${where}|${n.kind}:${n.name}`; + n.sig = (reads.get(n.id) ?? []).map(id => nodeById.get(id)?.name).sort().join(","); + } else n.base = `${g.modules[n.mod]}|${scopeOf(n.region)}|${n.name}`; + const i = (taken[n.base] = (taken[n.base] ?? -1) + 1); + n.key = n.rxKey ?? (i ? `${n.base}#${i}` : n.base); + } +} diff --git a/compiler/hmr.mjs b/compiler/hmr.mjs new file mode 100644 index 000000000..a36db99c3 --- /dev/null +++ b/compiler/hmr.mjs @@ -0,0 +1,385 @@ +// HMR planner for the trace protocol (TRACE-CONTRACT §2). The real host calls this with the old and new graphs +// from the compiler; the fake calls the same function. Pure ESM, no dependencies, Node and browser. +// +// A plan partitions every source, equation, effect and action of old ∪ new. State (source / equation / effect) is +// kept, reset, rerun, added, removed, or a move. Actions have no state: rerun if the body changed, else kept. +// Identity is the key. A rename or a `#n` shift is a move when the declaration (minus the name, for a rename) matches. + +const PLAN_KINDS = new Set(["source", "eq", "effect", "action"]); + +const sites = (graph, name) => graph.regions.filter(r => r.kind === "children" && r.name === name) + .map(r => r.key).sort().join("\n"); +const paths = items => items.map(item => (item.ownerPath ?? []).join("/")); + +/** Only primary source accessors enter this app-local registry; auxiliaries + * for a hoisted await/catch share a trace key but do not consume a seed. */ +export function prepareCarry(before, after, plan, sources, changedModules) { + const carry = new Map(), fallback = new Set(), expected = new Map(), reasons = new Map(); + const moved = new Map(plan.moved.map(({ from, to }) => [to, from])); + const nodes = new Map(after.nodes.map(n => [n.key, n])); + const kept = new Set(plan.kept); + for (const key of [...plan.kept, ...plan.rerun]) { + const n = nodes.get(key); + if (n?.kind !== "source" || (!kept.has(key) && !n.question)) continue; + const { scope, module } = keyParts(key); + if (!scope && !changedModules.has(module)) continue; // live module root was not replaced + const reads = [...(sources.get(moved.get(key) ?? key) ?? [])]; + if (!reads.length) continue; + const shown = reads.map(read => read.hmrValue?.()); + const ownerPaths = paths(reads); + // More than one render site or a static shape edit makes mount order + // ambiguous. One unchanged site (including a keyed list) pairs in order. + const site = sites(after, scope); + if (sites(before, scope) !== site || (reads.length > 1 && (!site || site.includes("\n") || new Set(ownerPaths).size !== 1))) { + reasons.set(key, "ambiguous-instance"); + fallback.add(key); + continue; + } + if (shown.some(v => !v || !Object.hasOwn(v, "value") || v.held)) { + reasons.set(key, "value-unavailable"); + fallback.add(key); + continue; + } + const keepAnswer = n.question && kept.has(key) && !after.edges.some(e => e.to === n.id && e.type === "read" && e.mode === "tracked"); + expected.set(key, ownerPaths); + carry.set(key, { entries: shown.map((v, i) => ({ value: v.value, keepAnswer, instance: reads[i].instance })), used: 0, question: !!n.question }); + } + return { carry, fallback, expected, reasons }; +} + +// Registry values of stores are detached record/array snapshots. Compare their +// contents, but keep identity semantics for opaque values. +function equalCarryValue(a, b, seen = new WeakMap()) { + if (Object.is(a, b)) return true; + if (a === null || b === null || typeof a !== "object" || typeof b !== "object") return false; + const p = Object.getPrototypeOf(a); + if (p !== Object.getPrototypeOf(b) || ![Object.prototype, Array.prototype, null].includes(p)) return false; + if (seen.has(a)) return seen.get(a) === b; + seen.set(a, b); + const keys = Object.keys(a); + return keys.length === Object.keys(b).length && keys.every(k => Object.hasOwn(b, k) && equalCarryValue(a[k], b[k], seen)); +} + +export function finishCarry({ carry, fallback, expected, reasons }, sources, select = () => true) { + for (const [key, group] of carry) { + if (!select(group)) continue; + const readers = [...(sources.get(key) ?? [])]; + const actual = paths(readers); + const reason = !actual.length ? "instance-not-mounted" + : group.used !== group.entries.length || actual.length !== group.entries.length + || actual.some((path, i) => path !== expected.get(key)[i]) ? "instance-mismatch" + : readers.some((read, i) => { + const shown = read.hmrValue?.(); + return !shown || !Object.hasOwn(shown, "value") || !equalCarryValue(group.entries[i].value, shown.value); + }) ? "value-mismatch" : undefined; + if (reason) { fallback.add(key); reasons.set(key, reason); } + } + return [...fallback]; +} + +// An entry replaced above Loading can have no new owner at its first flush. +// Only a singleton can be matched later without guessing order. It can be +// absent or, during a pending replacement, an already mounted candidate. +export function deferredCarry({ carry, expected }, sources, includeMounted = false) { + return new Map([...carry].flatMap(([key, group]) => { + const [path] = expected.get(key); + return group.entries.length === 1 && path && (includeMounted || (!group.used && !sources.has(key))) + ? [[key, { path, value: group.entries[0] }]] : []; + })); +} + +/** Source lines for a node: `lines[file]`, keys are 1-based line numbers (strings after JSON). */ +function lineMap(graph, node) { + if (!graph?.lines || !node) return null; + return graph.lines[node.file] ?? graph.lines[graph.modules?.[node.mod]] ?? null; +} + +function braceDelta(line) { + const s = String(line).replace(/\/\/.*$/, "").replace(/"(?:\\.|[^"\\])*"|'(?:\\.|[^'\\])*'|`(?:\\.|[^`\\])*`/g, ""); + let d = 0; + for (const c of s) if (c === "{") d++; else if (c === "}") d--; + return d; +} + +/** + * Declaration text. A node may carry `decl` or `text` (preferred when a future graph has them); otherwise the + * source line, extended through the closing brace when the first line opens one. + */ +export function declText(graph, node) { + if (node?.decl != null) return String(node.decl); + if (node?.text != null) return String(node.text); + const lines = lineMap(graph, node); + if (!lines || node.line == null) return ""; + const start = lines[node.line]; + if (start == null) return ""; + const keys = Object.keys(lines).map(Number).filter(n => Number.isFinite(n)).sort((a, b) => a - b); + const i0 = keys.indexOf(Number(node.line)); + if (i0 < 0) return start; + let depth = braceDelta(start); + if (depth <= 0) return start; + const out = [start]; + for (let i = i0 + 1; i < keys.length && out.length < 120; i++) { + const t = lines[keys[i]]; + out.push(t); + depth += braceDelta(t); + if (depth <= 0) break; + } + return out.join("\n"); +} + +// Keep literal text intact, including // and spaces inside quotes. +const LITERAL_OR_COMMENT = /("(?:\\.|[^"\\])*"|'(?:\\.|[^'\\])*'|`(?:\\[\s\S]|[^`\\])*`)|\/\/[^\n]*|\/\*[\s\S]*?\*\//g; +/** Comments stripped, blank lines dropped, trailing space dropped. A comment-only edit is not a change. */ +export function normDecl(text) { + return String(text ?? "").replace(LITERAL_OR_COMMENT, (_match, literal) => literal ?? " ").trim(); +} +const comparable = text => (normDecl(text).match(/"(?:\\.|[^"\\])*"|'(?:\\.|[^'\\])*'|`(?:\\[\s\S]|[^`\\])*`|[\p{ID_Continue}$]+|[^\s]/gu) ?? []).join("\0"); + +function normType(t) { + if (!t) return ""; + return String(t).replace(/\s+/g, " ").replace(/\s*\|\s*/g, " | ").trim(); +} + +function escapeReg(s) { + return String(s).replace(/[.*+?^${}()|[\]\\]/g, "\\$&"); +} + +/** Declaration with the binding name blanked, so a rename still matches. First occurrence only. */ +export function blankName(text, name) { + if (!name) return text; + return String(text).replace(new RegExp(`\\b${escapeReg(name)}\\b`), "□"); +} + +/** + * Pull type, operator and rhs out of a declaration. `:=` is an initialiser; `=` on a source is the seed or the + * question expression. `key id` between the type and `=` is not part of the type. + */ +export function parseDecl(kind, _name, text) { + const raw = String(text ?? "").trim(); + if (kind === "source") { + const m = /^(?:export\s+)?source\s+\w+\s*(?::\s*([^=]+?))?(?:\s+key\s+\w+)?\s*(:=|=)\s*([\s\S]*)$/.exec(raw); + if (!m) return { type: null, op: null, rhs: raw }; + let type = m[1]?.trim() || null; + if (type) type = type.replace(/\s+key\s+[\s\S]+$/, "").trim() || null; + return { type, op: m[2], rhs: m[3].trim() }; + } + if (kind === "action" || kind === "fn" || kind === "server" || kind === "effect") { + return { type: null, op: null, rhs: raw }; + } + const m = /^(?:export\s+)?\w+\s*(?::\s*([^=]+?))?\s*=\s*([\s\S]*)$/.exec(raw); + if (!m) return { type: null, op: "=", rhs: raw }; + return { type: m[1]?.trim() || null, op: "=", rhs: m[2].trim() }; +} + +/** `||[#n]`. Module paths have no `|`. */ +export function keyParts(key) { + const a = String(key).indexOf("|"); + const b = a < 0 ? -1 : String(key).indexOf("|", a + 1); + if (a < 0 || b < 0) return { module: "", scope: "", name: String(key), index: "" }; + const rest = String(key).slice(b + 1); + const m = /^(.*?)(?:#(\d+))?$/.exec(rest); + return { module: key.slice(0, a), scope: key.slice(a + 1, b), name: m?.[1] ?? rest, index: m?.[2] ?? "" }; +} + +function baseKey(key) { + const p = keyParts(key); + return `${p.module}|${p.scope}|${p.name}`; +} + +function planNodes(g) { + return (g?.nodes ?? []).filter(n => n && n.key && PLAN_KINDS.has(n.kind)); +} + +function readKeys(graph, node) { + const byId = new Map((graph.nodes ?? []).map(n => [n.id, n])); + const keys = []; + for (const e of graph.edges ?? []) { + if (e.type === "read" && e.to === node.id) { + const s = byId.get(e.from); + if (s?.key) keys.push(s.key); + } + } + return keys.sort(); +} + +function mapMoved(key, moved) { + const m = moved.find(x => x.from === key); + return m ? m.to : key; +} + +/** + * @param {object} oldGraph graph from `buildGraph` + * @param {object} newGraph graph from `buildGraph` + * @param {{ renamed?: {from: string, to: string}[], reindexed?: {from: string, to: string}[] }} [edits] + * Optional identity hints from a host that already knows the edit. Heuristics run for everything else. + * @returns {import("./hmr.mjs").Plan} + */ +export function planHmr(oldGraph, newGraph, edits) { + const oldN = planNodes(oldGraph); + const newN = planNodes(newGraph); + const oldByKey = new Map(oldN.map(n => [n.key, n])); + const newByKey = new Map(newN.map(n => [n.key, n])); + const usedO = new Set(); + const usedN = new Set(); + /** @type {{ o: any, n: any, move: null | "renamed" | "reindexed" | "scope" }[]} */ + const paired = []; + + const take = (o, n, move) => { + if (!o || !n || usedO.has(o.key) || usedN.has(n.key)) return false; + if (o.kind !== n.kind && move) return false; + // The wire partitions keys (not declaration instances). When a move's + // old key is still present, prefer the exact key over an overlapping move. + if (move && (o.key === n.key || newByKey.has(o.key))) return false; + usedO.add(o.key); + usedN.add(n.key); + paired.push({ o, n, move }); + return true; + }; + + for (const h of edits?.renamed ?? []) take(oldByKey.get(h.from), newByKey.get(h.to), "renamed"); + for (const h of edits?.reindexed ?? []) take(oldByKey.get(h.from), newByKey.get(h.to), "reindexed"); + + // `#n` shift: same module, scope, name and kind. Match by declaration text, not by the old index. + const group = nodes => { + const m = new Map(); + for (const n of nodes) { + const k = `${n.kind}|${baseKey(n.key)}`; + (m.get(k) ?? m.set(k, []).get(k)).push(n); + } + return m; + }; + const gOld = group(oldN); + const gNew = group(newN); + for (const [k, os] of gOld) { + const ns = gNew.get(k); + if (!ns) continue; + for (const o of os) { + if (usedO.has(o.key)) continue; + const ot = comparable(declText(oldGraph, o)); + const n = ns.find(x => !usedN.has(x.key) && comparable(declText(newGraph, x)) === ot); + if (n) take(o, n, o.key === n.key ? null : "reindexed"); + } + } + + // Same key: an edit of one declaration, or a kind change (source became an equation, and so on). + for (const o of oldN) { + if (usedO.has(o.key)) continue; + const n = newByKey.get(o.key); + if (n && !usedN.has(n.key)) take(o, n, null); + } + + // Rename: same kind, module and scope, declaration equal once the binding name is blanked. + const byDist = (o, list) => { + const ob = comparable(blankName(normDecl(declText(oldGraph, o)), o.name)); + const op = keyParts(o.key); + let best = null, bestDist = Infinity; + for (const n of list) { + if (usedN.has(n.key) || n.kind !== o.kind || n.name === o.name) continue; + const np = keyParts(n.key); + if (np.module !== op.module || np.scope !== op.scope) continue; + if (comparable(blankName(normDecl(declText(newGraph, n)), n.name)) !== ob) continue; + const dist = Math.abs((n.line ?? 0) - (o.line ?? 0)); + if (dist < bestDist) { best = n; bestDist = dist; } + } + return best; + }; + for (const o of oldN) { + if (usedO.has(o.key)) continue; + const n = byDist(o, newN); + if (n) take(o, n, "renamed"); + } + + // Same declaration moved into another component: the key's scope changed. That resets state. + for (const o of oldN) { + if (usedO.has(o.key)) continue; + const ob = comparable(blankName(normDecl(declText(oldGraph, o)), o.name)); + const op = keyParts(o.key); + let best = null, bestDist = Infinity; + for (const n of newN) { + if (usedN.has(n.key) || n.kind !== o.kind) continue; + const np = keyParts(n.key); + if (np.module !== op.module || np.name !== op.name || np.scope === op.scope) continue; + if (comparable(blankName(normDecl(declText(newGraph, n)), n.name)) !== ob) continue; + const dist = Math.abs((n.line ?? 0) - (o.line ?? 0)); + if (dist < bestDist) { best = n; bestDist = dist; } + } + if (best) take(o, best, "scope"); + } + + const plan = { kept: [], reset: [], rerun: [], added: [], removed: [], moved: [], reasons: {} }; + const pending = []; + + const ownChange = (o, n) => { + const ot = normDecl(declText(oldGraph, o)); + const nt = normDecl(declText(newGraph, n)); + const op = parseDecl(o.kind, o.name, ot); + const np = parseDecl(n.kind, n.name, nt); + if (o.kind !== n.kind) return { bucket: "reset", reason: "kind-changed" }; + if (keyParts(o.key).scope !== keyParts(n.key).scope) return { bucket: "reset", reason: "scope-changed" }; + if (normType(o.type ?? op.type) !== normType(n.type ?? np.type) && n.kind !== "action") return { bucket: "reset", reason: "type-changed" }; + const rhsChanged = comparable(op.rhs) !== comparable(np.rhs); + // The binding name is part of the text. Blank it, or a rename looks like an expression edit. + const bodyChanged = comparable(blankName(ot, o.name)) !== comparable(blankName(nt, n.name)); + if (n.kind === "source" && (rhsChanged || bodyChanged)) { + if (np.op === "=" && (n.question || /\bawait\b/.test(np.rhs))) return { bucket: "rerun", reason: "expr-changed" }; + return { bucket: "kept", reason: "init-changed" }; + } + if ((n.kind === "eq" || n.kind === "effect" || n.kind === "action") && (rhsChanged || bodyChanged)) + return { bucket: "rerun", reason: "expr-changed" }; + return { bucket: "pending", reason: null }; + }; + + for (const p of paired) { + const c = ownChange(p.o, p.n); + if (p.move) { + plan.moved.push({ from: p.o.key, to: p.n.key }); + plan.reasons[p.o.key] = p.move === "reindexed" ? "reindexed" : p.move === "scope" ? "scope-changed" : "renamed"; + } + if (c.bucket === "pending") pending.push(p); + else { + plan[c.bucket].push(p.n.key); + plan.reasons[p.n.key] = c.reason; + } + } + for (const o of oldN) if (!usedO.has(o.key) && !newByKey.has(o.key)) { + plan.removed.push(o.key); + plan.reasons[o.key] = "gone"; + } + for (const n of newN) if (!usedN.has(n.key)) { + plan.added.push(n.key); + plan.reasons[n.key] = "new"; + } + + const dirty = new Set([...plan.reset, ...plan.rerun, ...plan.added, ...plan.removed, ...plan.moved.map(m => m.from)]); + let left = pending; + for (let guard = 0; guard < left.length + 2 && left.length; guard++) { + const next = []; + let progressed = false; + for (const p of left) { + if (p.n.kind !== "eq" && p.n.kind !== "effect") { next.push(p); continue; } + const oldReads = readKeys(oldGraph, p.o).map(k => mapMoved(k, plan.moved)).sort(); + const newReads = readKeys(newGraph, p.n); + const readsChanged = oldReads.join("\0") !== newReads.join("\0"); + const readsDirty = newReads.some(k => dirty.has(k)); + if (readsChanged || readsDirty) { + plan.rerun.push(p.n.key); + plan.reasons[p.n.key] = "upstream-changed"; + dirty.add(p.n.key); + progressed = true; + } else next.push(p); + } + left = next; + if (!progressed) break; + } + for (const p of left) { + plan.kept.push(p.n.key); + plan.reasons[p.n.key] = "unchanged"; + } + + for (const k of ["kept", "reset", "rerun", "added", "removed"]) plan[k].sort(); + plan.moved.sort((a, b) => a.from < b.from ? -1 : a.from > b.from ? 1 : 0); + const reasons = {}; + for (const k of Object.keys(plan.reasons).sort()) reasons[k] = plan.reasons[k]; + plan.reasons = reasons; + return plan; +} diff --git a/compiler/hot.mjs b/compiler/hot.mjs new file mode 100644 index 000000000..6c3c355ae --- /dev/null +++ b/compiler/hot.mjs @@ -0,0 +1,110 @@ +import { createMemo, createSignal, flush, getOwner, onCleanup, untrack } from "solid-js"; +import { planHmr, prepareCarry, finishCarry, deferredCarry } from "./hmr.mjs"; + +const entries = new Map(); +let localId = 0; + +// Only Vite's hot client imports this. The map is a subscriber, not the owner +// of a replacement or its carried state. +export function hotEntry(payload, factory, hot, observer) { + const replacement = { ...payload, factory, hot, observer }; + const graph = payload.graph ?? payload.update.graph; + const entry = graph.modules.at(-1); + let state = entries.get(entry); + if (!state) { + const [code, replace] = createSignal({ factory }); + const mounts = new Map(); + state = { current: replacement, mounts, replace, queue: Promise.resolve(), + main: rt => () => { + if (rt.hotRuntime && getOwner()) { + rt.hotRuntime.activate(); + mounts.set(rt, (mounts.get(rt) ?? 0) + 1); + onCleanup(() => { + const count = mounts.get(rt); + if (count === 1) mounts.delete(rt); + else mounts.set(rt, count - 1); + }); + } + return createMemo(() => { + const current = code().factory; + return untrack(() => current(rt)()); + }, { transparent: true, _plumbing: true }); + } }; + entries.set(entry, state); + observer?.register(graph, { hot }); + } + function accept(next) { + state.queue = state.queue.then(async () => { + const old = state.current; + if (!next) { + if (state.announced) old.observer?.hmr({ phase: "failed", id: state.announced, error: "replacement module did not load", fallback: "none" }); + state.announced = undefined; + return; + } + const previous = old.graph ?? old.update.graph; + const graph = next.graph ?? next.update.graph; + const update = next.update; + const sameBase = update && update.from === old.revision; + const changedModules = new Set(sameBase ? update.changedModules : [...previous.modules, ...graph.modules]); + const edit = { + phase: "plan", id: update?.id ?? `client-${++localId}`, modules: update?.modules ?? [entry], + graph, plan: sameBase ? update.plan : planHmr(previous, graph), + }; + const observer = next.observer; + if (!sameBase || state.announced !== edit.id) observer?.hmr(edit); + state.announced = undefined; + const apply = (commit = flush) => { + // A comment/formatting save can update source positions without replacing a + // single reactive owner (including an in-flight module's state). + if (sameBase && update.metadataOnly) { commit(); return new Map(); } + const frames = [...state.mounts.keys()].map(rt => { + const runtime = rt.hotRuntime; + const frame = prepareCarry(previous, graph, edit.plan, runtime.sources, changedModules); + return { runtime, ...frame }; + }); + try { + for (const { runtime, carry } of frames) runtime.begin(carry, changedModules); + state.replace({ factory: next.factory }); + commit(); + } finally { + for (const { runtime } of frames) runtime.end(); + } + const settling = Promise.all(frames.map(frame => { + const { runtime } = frame; + // A re-asked question may legitimately land a different answer. + // Verify its seed before that answer lands, not at the end of the wait. + finishCarry(frame, runtime.sources, group => group.question); + const seeds = deferredCarry(frame, runtime.sources, true); + for (const [key, seed] of seeds) seed.used = () => { + const group = frame.carry.get(key); + if (!group.used) group.used = 1; + }; + return runtime.defer(seeds); + })); + return settling.then(() => new Map(frames.flatMap(frame => { + finishCarry(frame, frame.runtime.sources, group => !group.question); + return [...frame.reasons]; + }))); + }; + const installed = () => { + state.current = next; + observer?.register(graph, { hot: next.hot, replacement: true }); + }; + if (observer) await observer.replace(edit, apply, installed); + else { + try { flush(); await apply(); installed(); } + catch (e) { console.error("[rx] replacement failed:", e); location.reload(); } + } + }).catch(e => console.error("[rx] replacement failed:", e)); + } + // Vite replaces these listeners on the next evaluation of this module. + hot?.on("rx:hmr:plan", ({ from, to, type, changedModules, metadataOnly, ...edit }) => { + if (edit.graph.modules.at(-1) !== entry || state.current.revision !== from || state.announced === edit.id) return; + state.announced = edit.id; + observer?.hmr(edit); + }); + hot?.on("rx:hmr:error", error => { + if (error.entry === entry) observer?.hmr({ phase: "failed", id: error.id, error: error.error, fallback: "none" }); + }); + return { main: state.main, replacement, accept }; +} diff --git a/compiler/index.d.ts b/compiler/index.d.ts index 8acd2a594..40a52e9cb 100644 --- a/compiler/index.d.ts +++ b/compiler/index.d.ts @@ -12,6 +12,13 @@ export declare const __napiBindingTarget: 'native' | 'wasm32-wasi' | 'wasm32-was /** * `rxc app`'s answer, as JSON text: the program `entry` (an absolute path) starts, for `target` (dom, ssr or * universal; dom by default) over `module_name` (`@solidjs/web` by default). `spa`: a client-only build (dom, not - * hydratable), checked under 08 CN-3d. + * hydratable), checked under 08 CN-3d. `dev`: a dev build — each source's and equation's creating calls run under its + * key (`__rt.key`), its module relative to `root` (the process's cwd by default). */ -export declare function app(entry: string, target?: string | undefined | null, moduleName?: string | undefined | null, spa?: boolean | undefined | null): string +export declare function app(entry: string, target?: string | undefined | null, moduleName?: string | undefined | null, spa?: boolean | undefined | null, dev?: boolean | undefined | null, root?: string | undefined | null, hot?: boolean | undefined | null): string + +/** + * `rxc model`'s answer, as JSON text: the resolved model (CP-6) of every module the programs `entries` (absolute paths) + * start, each once, with module paths and keys relative to `root` (the process's cwd by default). + */ +export declare function model(entries: Array, root?: string | undefined | null): string diff --git a/compiler/index.js b/compiler/index.js index c1c473a7b..72ee78d87 100644 --- a/compiler/index.js +++ b/compiler/index.js @@ -836,3 +836,4 @@ function __napiStampBindingTarget(exportsObject, target) { module.exports.__napiBindingTarget = __napiStampBindingTarget(nativeBinding, __napiLoadedBindingTarget) module.exports = nativeBinding module.exports.app = nativeBinding.app +module.exports.model = nativeBinding.model diff --git a/compiler/package.json b/compiler/package.json index fb156d97c..022d64dc5 100644 --- a/compiler/package.json +++ b/compiler/package.json @@ -11,6 +11,9 @@ "main": "index.js", "types": "index.d.ts", "exports": { + "./hot": "./hot.mjs", + "./hmr": "./hmr.mjs", + "./graph": "./graph.mjs", ".": { "types": "./index.d.ts", "default": "./index.js" @@ -21,6 +24,9 @@ } }, "files": [ + "hot.mjs", + "hmr.mjs", + "graph.mjs", "index.js", "index.d.ts", "vite.mjs", @@ -35,7 +41,7 @@ "create-npm-dirs": "napi create-npm-dirs", "version": "napi version && node scripts/sync-optional-deps.mjs", "prepack": "node scripts/guide.mjs", - "test": "node test/node.mjs" + "test": "node test/node.mjs && node --test test/hmr.mjs" }, "napi": { "binaryName": "compiler", diff --git a/compiler/src/app.rs b/compiler/src/app.rs index f014d014d..3e932a798 100644 --- a/compiler/src/app.rs +++ b/compiler/src/app.rs @@ -1,8 +1,9 @@ //! A program compiled for a bundler (spec/11 CP-4b): every module of the program `entry` starts, through Solid's //! compiler for `target`, each importing its dependencies by `.rx` path, with the program's stylesheet. What `rxc app` //! prints and the Node-API build (`src/node.rs`) returns to `@reactivescript/compiler/vite`. -use crate::check::check_modules; -use crate::emit::{compile_linked, lower_view, Target}; +use crate::check::{check_modules, check_modules_in}; +use crate::emit::{lower_view, Target}; +use crate::model::module_key; use crate::modules::load_modules; use serde_json::{json, Map, Value}; use std::path::Path; @@ -26,6 +27,17 @@ pub fn target(name: &str) -> Target { /// `{entry, css, modules: {path: {code, map, css}}}` (the program's stylesheet, and each module's own), or `{diagnostics: [...]}` / `{error}`. `entry` is an absolute path. /// `spa`: a client-only build, checked under 08 CN-3d. pub fn app(entry: &str, target: Target, module_name: &str, spa: bool) -> Value { + app_dev(entry, target, module_name, spa, None) +} + +/// `app`, for a dev build when `dev` is set: each source's and equation's creating calls run under its key +/// (`emit::compile_dev`); `dev` is the project root the keys' modules are relative to. +pub fn app_dev(entry: &str, target: Target, module_name: &str, spa: bool, dev: Option<&str>) -> Value { + app_hot(entry, target, module_name, spa, dev, false) +} + +pub(crate) fn app_hot(entry: &str, target: Target, module_name: &str, spa: bool, dev: Option<&str>, hot: bool) -> Value { + let hot = hot && dev.is_some(); // module keys are POSIX paths (`modules::join_path`); Windows takes `D:/a/b.rx` as it takes `D:\a\b.rx` let entry = &entry.replace('\\', "/"); (|| { @@ -43,15 +55,51 @@ pub fn app(entry: &str, target: Target, module_name: &str, spa: bool) -> Value { if !checked.diags.is_empty() { return Err(json!({ "diagnostics": checked.diags.iter().map(|d| { let mut j = d.to_json(); if j["file"].is_null() { j["file"] = json!(set.entry); } j }).collect::>() })); } - let out = compile_linked(&set, &[], true).map_err(|e| json!({ "error": format!("{entry}: not compiled: {}", e.0) }))?; + let out = crate::emit::compile_with_hot(&set, &[], true, dev, None, hot).map_err(|e| json!({ "error": format!("{entry}: not compiled: {}", e.0) }))?; let mut modules = Map::new(); for (name, module) in &out.files { let path = &out.paths[name]; let text = read_disk(path).unwrap_or_default(); - let l = lower_view(module, path, target, module_name, Some((path, &text))).map_err(|e| json!({ "error": e }))?; + let mut l = lower_view(module, path, target, module_name, Some((path, &text))).map_err(|e| json!({ "error": e }))?; + if hot && path == &set.entry { + // The frontend supplies the serialized plan and optional observer, not the entry's implementation. + l.code.push_str("\nimport { hotEntry as __rxHot } from \"@reactivescript/compiler/hot\";\n\ + const __rxEntry = __rxHot(__rxPayload, main, import.meta.hot, __rxObserver);\n\ + export default __rxEntry.main;\n\ + export const __rxReplacement = __rxEntry.replacement;\n\ + if (import.meta.hot) import.meta.hot.accept(next => __rxEntry.accept(next?.__rxReplacement));\n"); + } modules.insert(path.clone(), json!({ "code": l.code, "map": l.map, "css": out.module_css[name] })); } - Ok(json!({ "entry": set.entry, "css": out.css, "modules": modules })) + let mut result = json!({ "entry": set.entry, "css": out.css, "modules": modules }); + if dev.is_some() { + result["declarations"] = json!(set.declarations.keys().collect::>()); + } + Ok(result) })() .unwrap_or_else(|e| e) } + +/// `rxc model`'s answer for the programs `entries` start (absolute paths): each module's resolved model (CP-6) once, in +/// load order, its `file` and its symbols' keys relative to `root`. `{error}` when an entry does not load. +pub fn model(entries: &[String], root: &str) -> Value { + let mut out: Vec = vec![]; + let mut seen = std::collections::HashSet::new(); + for entry in entries { + let entry = entry.replace('\\', "/"); + let set = match load_modules(&entry, &read_disk) { + Ok(s) => s, + Err(e) => return json!({ "error": e.0 }), + }; + let checked = check_modules_in(&set, false, Some(root)); + for p in &set.order { + if !seen.insert(p.clone()) { + continue; + } + let mut m = checked.models[p].clone(); + m["file"] = json!(module_key(p, Some(root))); + out.push(m); + } + } + Value::Array(out) +} diff --git a/compiler/src/ast.rs b/compiler/src/ast.rs index 79e82bb78..e7c719e1b 100644 --- a/compiler/src/ast.rs +++ b/compiler/src/ast.rs @@ -22,6 +22,7 @@ pub enum TplPart { #[derive(Debug, Clone)] pub enum Field { Kv { key: String, v: Expr }, + Computed { key: Expr, v: Expr }, Spread(Expr), } @@ -83,6 +84,7 @@ pub enum ExprKind { Call { f: Box, args: Vec }, Arr(Vec), Rec(Vec), + As { e: Box, ty: String }, /// `stmts`: a statement-bodied arrow (imperative scope, 07 §5) Fn { params: Vec, body: Box, stmts: Option> }, /// ST-3 @@ -420,6 +422,7 @@ impl Expr { ExprKind::Call { .. } => "call", ExprKind::Arr(_) => "arr", ExprKind::Rec(_) => "rec", + ExprKind::As { .. } => "as", ExprKind::Fn { .. } => "fn", ExprKind::Draft { .. } => "draft", ExprKind::Use(_) => "use", @@ -443,6 +446,7 @@ impl Expr { ExprKind::Pre { name, init } => obj(vec![("k", k), ("name", s(name)), ("init", ob(init))]), ExprKind::Peek(e) | ExprKind::Latest(e) | ExprKind::Pending(e) | ExprKind::Spread(e) | ExprKind::Throw(e) => obj(vec![("k", k), ("e", b(e))]), ExprKind::Omit { e, keys } => obj(vec![("k", k), ("e", b(e)), ("keys", Some(strs(keys)))]), + ExprKind::As { e, ty } => obj(vec![("k", k), ("e", b(e)), ("ty", s(ty))]), ExprKind::Await { e, init, stream } => obj(vec![("k", k), ("e", b(e)), ("init", ob(init)), ("stream", Some(Value::Bool(*stream)))]), ExprKind::If { c, t, f } => obj(vec![("k", k), ("c", b(c)), ("t", b(t)), ("f", b(f))]), ExprKind::Tpl(parts) => obj(vec![ @@ -462,6 +466,7 @@ impl Expr { .iter() .map(|f| match f { Field::Kv { key, v } => obj(vec![("key", s(key)), ("v", Some(v.to_json()))]), + Field::Computed { key, v } => obj(vec![("computed", Some(key.to_json())), ("v", Some(v.to_json()))]), Field::Spread(e) => obj(vec![("spread", Some(e.to_json()))]), }) .collect(), diff --git a/compiler/src/check.rs b/compiler/src/check.rs index ef628f7b7..8d4935c41 100644 --- a/compiler/src/check.rs +++ b/compiler/src/check.rs @@ -9,7 +9,7 @@ use crate::ast::*; use crate::content::{misnested, misnested_inside, Shape, P_CLOSERS, P_SCOPE}; use crate::infer::{inferred_action, run_findings, scalar_type, trigger_text, Code, RunOpts}; -use crate::model::{ModelBuilder, ModelSymbol}; +use crate::model::{decl_keys, module_key, ModelBuilder, ModelSymbol}; use crate::modules::ModuleSet; use crate::parse::{js_trim, JsDecl, Part, Shape as FShape}; use crate::signature::{Catch, CompSig, ExportSig, ModSig, Own, PropSig, SigParam, HOLD}; @@ -42,6 +42,11 @@ impl Diagnostic { } const BUILTINS: &[&str] = &["len", "str", "map", "filter", "sum", "fail", "fetch", "every", "indexOf"]; +pub(crate) fn pure_global(name: &str, member: Option<&str>) -> bool { + static GLOBALS: std::sync::OnceLock>> = std::sync::OnceLock::new(); + GLOBALS.get_or_init(|| serde_json::from_str(include_str!("../../spec/pure-globals.json")).expect("pure globals")) + .get(name).is_some_and(|ms| member.is_none_or(|m| ms.iter().any(|x| x == m))) +} /// EF-5's cleanup shapes: a `return` of a closure anywhere in the body, a closure as its last expression, or an expression body that is one. fn returns_closure(f: &Expr) -> bool { fn in_stmts(ss: &[Stmt]) -> bool { @@ -247,6 +252,8 @@ struct Sym<'a> { arity: Option, /// RG-4b: the props of `component C()`, which declares none — C's name: reading them is UNBOUND no_props: Option, + /// CP-6: a source's or an equation's identity (model.rs `decl_keys`) + key: Option, } impl<'a> Sym<'a> { fn new(kind: SymKind, name: &str, region: RId, line: i64) -> Self { @@ -284,6 +291,7 @@ impl<'a> Sym<'a> { reader: false, arity: None, no_props: None, + key: None, } } } @@ -356,6 +364,13 @@ fn snapshot_reads<'a>(n: Node<'a>, caught: bool, locals: &mut HashSet, o fn field_of(name: &str) -> String { if name == "..." { "*".into() } else { name.to_string() } } +fn index_field(e: &Expr) -> String { + match &e.k { + ExprKind::Lit(Lit::Str(s)) => s.clone(), + ExprKind::Lit(Lit::Num(n)) => if *n == 0.0 { "0".into() } else { dragonbox_ecma::Buffer::new().format(*n).into() }, + _ => "*".into(), + } +} /// an argument as a message shows it: `x={…}`, or `{...…}` for a spread fn arg_show(field: &str) -> String { @@ -395,7 +410,7 @@ pub(crate) fn children<'a>(n: Node<'a>, paths: bool) -> Vec> { Node::E(e) => match &e.k { ExprKind::Lit(_) | ExprKind::Id(_) | ExprKind::Use(_) | ExprKind::StyleMap { .. } => {} ExprKind::Bin { l, r, .. } => out.extend([Node::E(l), Node::E(r)]), - ExprKind::Un { e, .. } | ExprKind::Peek(e) | ExprKind::Latest(e) | ExprKind::Pending(e) | ExprKind::Spread(e) | ExprKind::Omit { e, .. } | ExprKind::Throw(e) => out.push(Node::E(e)), + ExprKind::Un { e, .. } | ExprKind::As { e, .. } | ExprKind::Peek(e) | ExprKind::Latest(e) | ExprKind::Pending(e) | ExprKind::Spread(e) | ExprKind::Omit { e, .. } | ExprKind::Throw(e) => out.push(Node::E(e)), ExprKind::Pre { init, .. } => out.extend(init.iter().map(|x| Node::E(x))), ExprKind::Await { e, init, .. } => { out.push(Node::E(e)); @@ -410,10 +425,12 @@ pub(crate) fn children<'a>(n: Node<'a>, paths: bool) -> Vec> { out.extend(args.iter().map(Node::E)); } ExprKind::Arr(items) => out.extend(items.iter().map(Node::E)), - ExprKind::Rec(fields) => out.extend(fields.iter().map(|f| match f { - Field::Kv { v, .. } => Node::E(v), - Field::Spread(e) => Node::E(e), - })), + ExprKind::Rec(fields) => for f in fields { + match f { + Field::Kv { v, .. } | Field::Spread(v) => out.push(Node::E(v)), + Field::Computed { key, v } => out.extend([Node::E(key), Node::E(v)]), + } + }, ExprKind::Fn { body, stmts, .. } => { out.push(Node::E(body)); if let Some(s) = stmts { @@ -480,7 +497,7 @@ pub(crate) fn free_names(e: &Expr, bound: &HashSet, out: &mut IndexSet go(x, out), + ExprKind::Latest(x) | ExprKind::Pending(x) | ExprKind::Un { e: x, .. } | ExprKind::As { e: x, .. } | ExprKind::Spread(x) | ExprKind::Omit { e: x, .. } => go(x, out), ExprKind::Bin { l, r, .. } => { go(l, out); go(r, out); @@ -517,6 +534,7 @@ pub(crate) fn free_names(e: &Expr, bound: &HashSet, out: &mut IndexSet go(v, out), + Field::Computed { key, v } => { go(key, out); go(v, out); } Field::Spread(x) => go(x, out), } } @@ -854,6 +872,8 @@ pub struct Opts<'a> { /// CN-3d: a client-only build (no SSR): a first load nothing holds shows nothing, so every reader that can have /// no value yet needs a `loading` region above it, as a client question's reader does (SV-7b). pub spa: bool, + /// the project root a key's module is relative to (`decl_keys`); None: the path as the loader has it + pub root: Option<&'a str>, } pub struct Checker<'a> { @@ -901,6 +921,8 @@ pub struct Checker<'a> { reader_f: Vec<(RId, &'a Expr, i64, Fails)>, arg_r: Vec<(usize, String)>, arg_f: Vec<(usize, String, Fails)>, + keys: HashMap<*const Decl, String>, + boundaries: HashMap<*const Markup, usize>, } pub struct CheckResult { @@ -923,13 +945,32 @@ pub struct Checked { pub sigs: IndexMap, pub models: IndexMap, } + +/// AST sites and the matching resolved region IDs. Only the dev emitter consumes these. +pub fn boundary_regions(set: &ModuleSet) -> HashMap<*const Markup, usize> { + let mut sigs = set.signatures.clone(); + let mut sites = HashMap::new(); + for path in &set.order { + let p = &set.programs[path]; + let mut c = Checker::new(Opts { sigs: &sigs, file: Some(path.clone()), declarations: &set.declarations, spa: false, root: None }); + c.run(p); + let sig = c.signature(p); + sites.extend(c.boundaries); + sigs.insert(path.clone(), sig); + } + sites +} /// CN-4b / MO-3: check every module of a program, dependencies first, each against its imports' signatures only. pub fn check_modules(set: &ModuleSet, spa: bool) -> Checked { + check_modules_in(set, spa, None) +} +/// `check_modules`, each symbol's key naming its module relative to `root` (the project root). +pub fn check_modules_in(set: &ModuleSet, spa: bool, root: Option<&str>) -> Checked { let mut sigs: IndexMap = set.signatures.clone(); let mut diags = set.diags.clone(); let mut models = IndexMap::new(); for path in &set.order { - let r = check_with_signature(&set.programs[path], Opts { sigs: &sigs, file: Some(path.clone()), declarations: &set.declarations, spa }); + let r = check_with_signature(&set.programs[path], Opts { sigs: &sigs, file: Some(path.clone()), declarations: &set.declarations, spa, root }); diags.extend(r.diags); sigs.insert(path.clone(), r.sig); models.insert(path.clone(), r.model); @@ -978,6 +1019,8 @@ impl<'a> Checker<'a> { reader_f: vec![], arg_r: vec![], arg_f: vec![], + keys: HashMap::new(), + boundaries: HashMap::new(), } } @@ -1054,11 +1097,13 @@ impl<'a> Checker<'a> { question: if s.kind == SymKind::Source { Some(s.question) } else { None }, io: s.io, from: s.imported.clone(), + key: s.key.clone(), } }) } pub fn run(&mut self, p: &'a Program) { + self.keys = decl_keys(p, &module_key(self.opts.file.as_deref().unwrap_or("main.rx"), self.opts.root)); let r = self.region(None, "program", false, None); let root = self.env(None, r); self.root_env = Some(root); @@ -1079,6 +1124,72 @@ impl<'a> Checker<'a> { self.loading_on_outside(); self.snapshot_guards(); self.guess_while_loading(); + self.style_scope(p); + } + /// CSS-2: a component's ` { open(props.note.id) }}>{props.note.title} {props.note.updated} @@ -14,8 +18,6 @@ component Row(props: { note: Note }) { export component NoteList(props: { notes: Note[] }) { if len(props.notes) == 0 { diff --git a/guide/async.md b/guide/async.md index b67be29ec..37e28d3dd 100644 --- a/guide/async.md +++ b/guide/async.md @@ -5,6 +5,10 @@ don't need them to follow it. ## Rule zero: don't track requests yourself +Pure calculations can use the [fixed JS prelude](../spec/pure-globals.json) +directly, for example `Math.round(n)` and `Object.keys(record)`. Clocks, +randomness, browser APIs and timers still belong in imported JS. + Don't write sequence numbers, request ids, "latest token" checks, `if (stillCurrent)` guards, cancellation flags, or lists of pending requests. In .rx those are bugs waiting to happen, and they are never needed. The language already knows which question is current and which change a write belongs to. If you're reaching for a counter, you @@ -30,6 +34,32 @@ onFlush(() => { text := "" }) addTodo(t) ``` +### Which flight is holding this write? + +Start with the run that wrote the value, not the component that displays +it. Include its other writes, what their readers compute, and every +question the run opens that a display is waiting for (H-2). Two changes +can join: a new reader pass triggered by one change consumes a derivation +of the other's held value, or both write the same held slot (H-2, H-3, +H-3a). Merely having two outstanding requests doesn't join them. + +For example, a move waits for `moveCard`, writes the returned card and +undo entry, and does `refresh activity`. If a reader awaits that refreshed +activity, the undo entry can stay held after `moveCard` resolves and the +action reports `run end`. The activity flight lands, then the frame with +the card and undo entry commits. A timer polling presence or chat in a +separate run can still land independently, provided its readers don't +join the move's change. But a new badge pass computing from both the held +history and the fresh presence may join them; separate components alone +are not a guarantee. + +When debugging, compare the action end, the pending readers and flights, +and the write's `held`/`released` in the trace. Keep reads in the UI that +needs them. Use a separate run for independent UI state and `deferred` +when it's acceptable for an already loaded answer to lag (H-1). Don't +split the card and undo entry into separate writes just to make the button +appear faster. + ## 1. Reading from the server: an equation ```rx @@ -79,10 +109,30 @@ client's own state: a plain source the action's `catch` writes, shown beside the `found(await fetchUser(id), id)` with `fn found(it, id) => it == null ? throw NotFound(id) : it`. - Retry is `refresh x`. It is quiet (AC-4): the failure stays on screen until the new answer replaces it (H-12). +An `errored` region does not watch equations just because they are in scope. +Equations are lazy (E-3, E-8): if `shown` is false, `if shown { … }` skips +the body, and no `details` read there can trip the boundary. If the region +should report missing details even when their view is hidden, read them +first, inside the region: + +```rx +errored fallback(e) {

{e.message}

} { + loading fallback {

Loading…

} { + if details && shown {

{details.title}

} + } +} +``` + +This also demands the question while `shown` is false. If hiding the pane +should avoid the request, keep `shown` first. The MCP live model's +`failedUntripped` means the inspector saw an error but no instrumented +boundary currently reports that same error. It doesn't prove why no +boundary tripped, and inspecting a lazy equation can evaluate it. + ## 3. Writing to the server: an action ```rx -export source profile: Profile = await loadProfile() // a source with a question: it can take a guess +export source profile: Profile = await loadProfile() // a question source: the server answer can replace the guess export source saveError: string := "" export action save(next: Profile) { @@ -122,6 +172,9 @@ by what the screen should do: To guess a value a component gets as a prop, guess its own equation of it: `shown = props.title`, then `guess shown := t` in the action. A prop itself is read-only (O-4), and the guess shows wherever the child reads `shown`. +A writable `source x := seed` can take a guess too. Its plain writes land when the action commits; if nothing +writes it, the guess ends and the previous value shows again. No question or `refresh` is needed (AC-3). + ### Guesses go on the answer There is one shape for a write on server data. The server's answers are the stores the screen reads, and a write @@ -232,6 +285,23 @@ errors and guesses of the last visit then show on the next. ## 4. Things that look like bugs and aren't +### Progress and independent row saves + +One action groups its writes across its awaits. If a batch should commit +all at once, keep it in one action. If rows should settle separately, run +one action per row. Launch the row actions in separate runs, not by +calling them all synchronously from one handler (that can join their +changes). For a bulk control, an imported JS dispatcher can schedule each +row callback in a separate task. + +For progress on a single long operation, keep a separate progress source. +Publish progress from independent callbacks, or use `onFlush` to schedule +a separate write at a known milestone. Don't write progress into the +answer the operation already holds. A reader that derives from both +progress and the held answer can join the changes; render progress on its +own if it must stay responsive. The final result still belongs in the +action that awaited it. + - **A plain write in an action doesn't show until the server answers.** That's the hold. Use `guess` or `onFlush` (the table above). Don't move the code into a plain handler to escape it. - **A declined row guess stays until another action's re-ask lands.** While an action's `refresh` of the list is @@ -276,7 +346,78 @@ a value; an effect is for sending a value somewhere else (a parent's `on…` han a page belongs in a component that stays (pass it down, report changes up with an `on…` handler). - **Order**: two effects that fire in the same change run in no promised order (EF-6). -## 7. Forms +## 7. Polling, a log, and a sound per message + +A timer is a JS primitive (MO-10), declared once: + +```rx +export pure fn createTicker(ms: number): ref number +``` + +`tick = createTicker(2000)` is an instantiation. It is a number that moves. Nothing else about time is in the language. + +**Poll every n seconds.** An effect on the tick calls an action. The action does the fetch. The effect does not. + +```rx +tick = createTicker(2000) +action poll() { + try { status := await loadStatus() } + catch (e) { status := e.message } +} +effect (tick) { poll() } +``` + +**Re-ask a question without a dummy argument.** A question re-asks when its inputs change (ST-5). Passing the tick into `whoIsHere(id, tick)` so the call changes is a dummy. `refresh` re-runs an `await` equation for the same inputs, quietly (AC-4): the last answer stays up. + +```rx +tick = createTicker(5000) +here = await whoIsHere(boardId) +effect (tick) { refresh here } +``` + +**An append-only log with a cursor.** The log is a keyed source. This example +assumes the server returns all rows newer than the cursor, with a stable `seq` +and `id` on each row. Merge by id and sort by server sequence so overlapping +responses don't duplicate or reorder messages. Advance the cursor only forward. + +```rx +source log: Message[] key id := [] +source cursor := 0 +action poll() { + try { + let r = await messagesSince(boardId, cursor) + log := old => [...old.filter(m => !r.messages.some(n => n.id == m.id)), ...r.messages] + .sort((a, b) => a.seq - b.seq) + cursor := prev => prev > r.cursor ? prev : r.cursor + } catch (e) { err := e.message } +} +effect (tick) { poll() } +``` + +**A sound, or any other effect, for each message in a burst.** Several messages handled in one turn are one change (W-3): the functional writes compose, and an effect runs once, after that change has settled (EF-2). `onFlush` and `onSettled` also run once for the change, not once per updater. Leave a record in the state as you reduce, and play the new records from an effect on the counter. The effect runs after the commit, against the store that is on screen. + +In the `.rx` module: + +```rx +import { fresh, reduce, play } from "./live" +source live := fresh() +action dispatch(m) { + live := s => reduce(s, m) +} +effect (live.fxSeq) { play(live) } +``` + +In the JS module, `fresh` returns `{ fxSeq: 0, fx: [] }`. `reduce` applies the +message and appends `{ seq: ++s.fxSeq, message: m }` to `s.fx` in the same write. +`play` walks the committed records in sequence order and plays only those +after its last-played sequence. Keep that cursor per consumer, not in a JS +singleton shared by multiple instances. For a long-lived queue, drop records +only after they have been consumed. + +In `live.d.rx`, declare the reducer as `export fn reduce(s: LiveState, m: Message): void`. +`reduce` mutates the draft it is given and nothing else. Declare it `fn`, not `pure fn`: a pure function must not mutate, and this one does. `fn` is io, so call it from the action, which is imperative. A `pure fn` here would be a lie so the call would type-check from reactive scope. It does not need to. + +## 8. Forms A draft seeded once from loaded data is a source in the form's component, seeded with `peek`: `source name := peek(props.initial.name)`. It belongs to the user from then on; a save never resets it. diff --git a/guide/diagnostics.md b/guide/diagnostics.md index f2ddad76d..7743a23f9 100644 --- a/guide/diagnostics.md +++ b/guide/diagnostics.md @@ -97,6 +97,42 @@ export default component App() { } ``` +### JSX_TERNARY + +`c ? a : b` is an expression, and markup is not an expression. A branch of elements is `{if c { … } else { … }}`. + +```rx before +export default component App() { + source c := true +

{c ? : ""}

+} +``` + +```rx after +export default component App() { + source c := true +

{if c { } else { }}

+} +``` + +### FOR_INDEX + +`for` binds one name. The index is `xs.indexOf(x)` in the body, or map the list to pairs first. + +```rx before +export default component App() { + source xs := [1] + {for x, i in xs {

{x}

}} +} +``` + +```rx after +export default component App() { + source xs := [1] + {for x in xs {

{x} {xs.indexOf(x)}

}} +} +``` + ### ASSIGNMENT A source is written with `:=` as a statement, in a handler or an action (W-1). There is no `=`, `+=` or `++` on state. @@ -249,6 +285,12 @@ by then it may have changed (a rename accepted), be somewhere else (an earlier m action still holds, so the screen loses the edit or shows the row twice. When the answer doesn't say where a row is now (a move answers only where it went), re-ask the answers it left and joined with `refresh`. +Even `let id = entry.id` inside the action is still a projection of the row under AC-1g. If the id +identifies what the user asked for, pass just that primitive from the handler: change +`finish(entry)` to `finish(entry.id)` and `action finish(entry: Entry)` to `action finish(id: string)` +(or `number`, if that's the id type). Use `id` to find the current row inside the functional write; +don't carry the displayed row or its fields into the answer. + ```rx before type Card = { id: number; title: string } export default component App() { @@ -296,8 +338,9 @@ export default component App() { ### SNAPSHOT_ARGUMENT -A `fn` that declares state (an effect, a source) reads its value parameters once. Declare the parameter `ref` to pass -the reactive value itself, or pass `peek(…)` to say a snapshot is meant (E-10). +A block `fn` with declarations (including equations) reads its value parameters once. Declare the parameter `ref` +to pass the reactive value itself, or pass `peek(…)` to say a snapshot is meant (E-10). For a value-only calculation, +inline the equation: `fn size(xs) { n = xs.length; n }` becomes `fn size(xs) => xs.length`. ```rx before export default component App() { @@ -768,6 +811,44 @@ export default component App() { } ``` +### TYPE_IMPORT + +A `.d.rx` imports types only (MO-8e): `import { T, U as V } from "./x"`, from another `.d.rx` or an `.rx` `export type`. A function is a value. Copying the type into the file was the workaround; import the type instead. + +```rx +-- module: ./fns.d.rx +export pure fn fetch(): string + +-- module: ./api.d.rx +import { fetch } from "./fns" +export pure fn g(x: number): number +``` + +Import `Card`, not `fetch`. + +### DEAD_TYPED_BOUNDARY + +A typed `errored fallback(e: X)` wraps a catch-all with a static fallback. The catch-all takes `X` first and its static +fallback cannot fail into the typed region (R-f-4). Put the typed boundary inside the catch-all. + +```rx before +error NotFound +export default component App() { + errored fallback(e: NotFound) {

{e.message}

} { + errored fallback {

failed

} {

x

} + } +} +``` + +```rx after +error NotFound +export default component App() { + errored fallback(e) {

{e.message}

} { + errored fallback(e: NotFound) {

{e.message}

} {

x

} + } +} +``` + ### CATCH_NOT_ON_AWAIT A `catch` follows something other than an `await` (R-f-4). A value that failed is shown where it is read, by an @@ -962,6 +1043,11 @@ export default component App() { The name is not declared where it is read. A component sees its declaration site, not its caller (RG-7a): pass the value as a prop, provide it in a context, or import it. +JavaScript globals are not in scope (SV-7a). For example, put `export const Number = globalThis.Number` in +`js-globals.js` and write `import pure { Number } from "./js-globals.js"` in `.rx` +to convert values in reactive scope. For `Math`, prefer exporting the operation you +need, e.g. `export const floor = Math.floor`, then `import pure { floor } from "./js-globals.js"`. + ```rx before component Row(props) {

{caption}

} component List(props) { @@ -1231,6 +1317,34 @@ the await, `await viewport() -> 0` (SV-7b). The browser's HTML parser rewrites some nestings (a `` outside a table, a `
` inside a `

`), so the page the server sends is not the tree the client builds and hydration fails (SV-7d). Nest the elements the way HTML allows. +### STYLE_SCOPE + +A component's ``, CSS-5). + +```rx before +component Row() { +

  • x
  • +} +export default component App() { + + +} +``` + +```rx after +component Row() { + +
  • x
  • +} +export default component App() { + +} +``` + ### STYLE_PLACEMENT A view has one `;`, { filename: "class-map.tsrx", generate: "dom" }) as { code: string }; const m = /export const __s = (\{[\s\S]*?\});/.exec(r.code); return `(${m ? m[1].replace(/\n\s*/g, " ").replace(/: "[^"]*"/g, ': "" as string') : "{}"} as const)`; } // 07 CSS-5: TSRX's class map, as its typecheck projection writes it case "call": return `${go(e.f)}(${e.args.map(go).join(", ")})`; case "arr": return `[${e.items.map(go).join(", ")}]`; - case "rec": return `({ ${e.fields.map(f => "spread" in f ? `...${go(f.spread)}` : `${J(f.key)}: ${go(f.v)}`).join(", ")} })`; + case "as": return `(${go(e.e)} as ${e.ty})`; + case "rec": return `({ ${e.fields.map(f => "spread" in f ? `...${go(f.spread)}` : `${"computed" in f ? `[${go(f.computed)}]` : J(f.key)}: ${go(f.v)}`).join(", ")} })`; case "spread": return `...${go(e.e)}`; case "omit": return `__.omit(${[go(e.e), ...e.keys.map(k => J(k))].join(", ")})`; case "fn": { const ps = e.params.join(", "); - if (!e.stmts) return `((${ps}) => ${this.expr(e.body, imp, self)})`; - const w = new W(); const saved = this.w; this.w = w; this.stmts(e.stmts, " "); this.w = saved; - return `(${hasAwait(e.stmts) ? "async " : ""}(${ps}) => {\n${w.out.join("\n")}\n})`; + const names = imp ? this.handlerSnaps(e) : []; // TY-2: a handler's reads are snapshots, so a view branch does not narrow them + const saved = this.rename; + if (names.length) { this.rename = new Map(saved); for (const n of names) this.rename.set(n, `__s_${n}`); } + let inner: string; let async = false; + if (!e.stmts) inner = this.expr(e.body, imp, self); + else { async = hasAwait(e.stmts); const w = new W(); const sw = this.w; this.w = w; this.stmts(e.stmts, " "); this.w = sw; inner = w.out.join("\n"); } + this.rename = saved; + if (!names.length) return e.stmts ? `(${async ? "async " : ""}(${ps}) => {\n${inner}\n})` : `((${ps}) => ${inner})`; + const params = names.map(n => `__s_${n}: __W_${n}`).join(", "); + const args = names.join(", "); + return e.stmts ? `((${ps}) => ((${params}) => {\n${inner}\n})(${args}))` : `((${ps}) => ((${params}) => ${inner})(${args}))`; } case "serverfn": { // SF-1d: an async function, its wire checked (TY-5a) const ps = e.params.map((n, i) => `${n}${e.ptypes?.[i] ? `: ${e.ptypes[i]}` : ""}`).join(", "); diff --git a/ref/types/run.ts b/ref/types/run.ts index e06ac25c1..f9bf6f32e 100644 --- a/ref/types/run.ts +++ b/ref/types/run.ts @@ -11,14 +11,14 @@ import { parseScenario, moduleSet, type Scenario } from "../src/scenario.ts"; import { checkModules } from "../src/check.ts"; import { projectModules, PRELUDE, type Projected } from "./project.ts"; import { execFileSync } from "node:child_process"; -import { existsSync } from "node:fs"; +import { existsSync, statSync } from "node:fs"; import { loadModules } from "../src/modules.ts"; const rxc = fileURLToPath(new URL("../../compiler/target/release/rxc", import.meta.url)); /** RX_CRATE=1: the crate's projection of the program, read from the same files ref/ reads. */ function crateProjection(sc: Scenario, src: string): Projected[] { const files: Record = {}; - const read = (p: string) => { const s = p === sc.entry ? src : sc.modules.get(p) ?? (existsSync(p) ? readFileSync(p, "utf8") : undefined); if (s !== undefined) files[p] = s; return s; }; + const read = (p: string) => { const s = p === sc.entry ? src : sc.modules.get(p) ?? (existsSync(p) && statSync(p).isFile() ? readFileSync(p, "utf8") : undefined); if (s !== undefined) files[p] = s; return s; }; loadModules(sc.entry, read); const out = JSON.parse(execFileSync(rxc, ["project"], { input: JSON.stringify([{ id: 0, entry: sc.entry, files }]), maxBuffer: 1 << 28 }).toString()); return out.programs[0].files; diff --git a/runtime/build.mjs b/runtime/build.mjs index f771654ce..7bdebe0a9 100644 --- a/runtime/build.mjs +++ b/runtime/build.mjs @@ -2,7 +2,7 @@ // runs what the scenarios run: each is transpiled to dist/ as it is (Solid stays external, a peer of the app's), with // its declarations. import { execFileSync } from "node:child_process"; -import { mkdirSync, rmSync, writeFileSync } from "node:fs"; +import { mkdirSync, readFileSync, rmSync, writeFileSync } from "node:fs"; import { createRequire } from "node:module"; import { fileURLToPath } from "node:url"; import path from "node:path"; @@ -12,8 +12,17 @@ const here = path.dirname(fileURLToPath(import.meta.url)); const src = path.resolve(here, "../ref/compile"); const dist = path.join(here, "dist"); rmSync(dist, { recursive: true, force: true }); mkdirSync(dist); -for (const [from, to] of [["rt-web.ts", "web"], ["rt-server.ts", "server"]]) { - await build({ entryPoints: [path.join(src, from)], outfile: path.join(dist, `${to}.js`), format: "esm", platform: "neutral", target: "es2022", bundle: true, packages: "external", logLevel: "warning" }); +for (const [from, to] of [["rt-web.ts", "web"], ["rt-server.ts", "server"]]) for (const dev of [false, true]) { + await build({ entryPoints: [path.join(src, from)], outfile: path.join(dist, `${to}${dev ? ".dev" : ""}.js`), format: "esm", platform: "neutral", target: "es2022", bundle: true, packages: "external", logLevel: "warning", minifySyntax: true, + plugins: [{ name: "rx-runtime-tier", setup(build) { + build.onLoad({ filter: /rt-(web|server)\.ts$/ }, ({ path }) => ({ + loader: "ts", contents: readFileSync(path, "utf8") + .replace(/^const RX_(?:INSTRUMENT|HARNESS) = .*;\n/gm, "") + .replace(/\bRX_INSTRUMENT\b/g, dev ? "!!DEV" : "false") + .replace(/\bRX_HARNESS\b/g, String(dev)), + })); + } }], + }); } // declarations, unchecked: the runtime uses Solid internals its types leave out (createErrorBoundary, sharedConfig, // runInServerComponentScope); Solid's types resolve from this package's node_modules diff --git a/runtime/package.json b/runtime/package.json index 20af7113c..80a88bb94 100644 --- a/runtime/package.json +++ b/runtime/package.json @@ -14,29 +14,43 @@ ".": { "worker": { "types": "./dist/server.d.ts", + "production": "./dist/server.js", + "development": "./dist/server.dev.js", "default": "./dist/server.js" }, "browser": { "types": "./dist/web.d.ts", + "production": "./dist/web.js", + "development": "./dist/web.dev.js", "default": "./dist/web.js" }, "deno": { "types": "./dist/server.d.ts", + "production": "./dist/server.js", + "development": "./dist/server.dev.js", "default": "./dist/server.js" }, "node": { "types": "./dist/server.d.ts", + "production": "./dist/server.js", + "development": "./dist/server.dev.js", "default": "./dist/server.js" }, "types": "./dist/web.d.ts", + "production": "./dist/web.js", + "development": "./dist/web.dev.js", "default": "./dist/web.js" }, "./web": { "types": "./dist/web.d.ts", + "production": "./dist/web.js", + "development": "./dist/web.dev.js", "default": "./dist/web.js" }, "./server": { "types": "./dist/server.d.ts", + "production": "./dist/server.js", + "development": "./dist/server.dev.js", "default": "./dist/server.js" } }, diff --git a/runtime/test.mjs b/runtime/test.mjs index f9e8a480f..3768a7953 100644 --- a/runtime/test.mjs +++ b/runtime/test.mjs @@ -19,6 +19,16 @@ try { for (const [cond, build] of [["browser", "web"], ["node", "server"]]) { const keys = execFileSync(process.execPath, ["--conditions=" + cond, "--input-type=module", "-e", probe], { cwd: tmp }).toString().trim(); check(`${build} build (${cond})`, keys.includes("createApp"), keys); + const api = `import assert from "node:assert/strict"; import { createApp } from "@reactivescript/runtime"; + assert.throws(() => createApp({ root: null }).api("load"), /cannot bind load.*createApp/); + assert.equal(createApp({ root: null }).jsError, undefined); + assert.equal(createApp({ root: null, api: { load: () => "loaded" } }).api("load")(), "loaded");`; + execFileSync(process.execPath, ["--conditions=" + cond, "--input-type=module", "-e", api], { cwd: tmp }); + execFileSync(process.execPath, ["--conditions=" + cond, "--conditions=development", "--input-type=module", "-e", ` + import assert from "node:assert/strict"; import { createApp } from "@reactivescript/runtime"; + assert.throws(() => createApp({ root: null }).api("load"), /MISSING_TEST_API/); + assert.equal(typeof createApp({ root: null }).jsError, "function");`], { cwd: tmp }); + check(`${build} gates the reference API behind development`, true); } const { app: compile } = createRequire(import.meta.url)("../compiler/index.js"); const out = JSON.parse(compile(path.resolve(here, "../examples/todo.rx"), "ssr")); diff --git a/scenarios/S-action-input.md b/scenarios/S-action-input.md new file mode 100644 index 000000000..27f6d981e --- /dev/null +++ b/scenarios/S-action-input.md @@ -0,0 +1,28 @@ +# S-action-input — action arguments survive selection reset + +Rules: AC-1, W-4. An action retains the input values from its call, including +arrays and records nested inside an argument. + +## Program + +```rx +export default component App() { + source selected := ["a", "b"] + source packet := { nested: [["c"]] } + source sent := "" + action bulk(ids: string[], payload: { nested: string[][] }) { + await fetch("ready") catch (e) => "" + sent := ids.join(",") + ":" + (payload.nested[0]?.join(",") ?? "") + } +

    {selected.length}:{sent}

    +} +``` + +## Frames + +| instant | action | frame | +| --- | --- | --- | +| 0 | mount | `2:` | +| 1 | handler `bulk(selected, packet)` | `2:` | +| 2 | handler `selected := []; packet.nested[0] := []` | `0:` | +| 3 | resolve `"ready"` `"ok"` | `0:a,b:c` | diff --git a/scenarios/S-cast-1.md b/scenarios/S-cast-1.md new file mode 100644 index 000000000..86393da04 --- /dev/null +++ b/scenarios/S-cast-1.md @@ -0,0 +1,40 @@ +# S-cast-1 — A type assertion is TypeScript's, and a handler error stays on its line + +Rules exercised: 07 §3 (`e as T`), 13 TY-2. + +## Program + +```rx +type Status = "open" | "done" +export default component App() { + source s: string := "open" + source out: Status := "open" + +} +``` + +`as` is an assertion, erased where the program runs: the click writes `s`. The +projection keeps it, so `s as Status` is a `Status` and the write checks. + +## Frames + +| instant | action | frame | +| ------- | ----------------------------------- | ------ | +| 0 | mount | `open` | +| 1 | handler `out := s as Status` | `open` | + +## Rejected variants + +```rx +-- reject: PARSE +export default component App() { + source n := 1 + +} +``` + +A syntax error in a handler is that error, on its line. It is not `JS_LOCAL` +on the `let` above it: that `let` is a handler local. diff --git a/scenarios/S-check-1.md b/scenarios/S-check-1.md index 96450977d..71b7b1944 100644 --- a/scenarios/S-check-1.md +++ b/scenarios/S-check-1.md @@ -368,3 +368,11 @@ export default component App() { The second `` is rendered on a path with no provision (RG-7b): one path without it is enough. +## Rejected: action defaults + +```rx +-- reject: ACTION_PARAMETER_DEFAULT +type Intent = "edit" | "add" +export action save(operation: Intent = "edit") {} +export default component App() { } +``` diff --git a/scenarios/S-fail-5.md b/scenarios/S-fail-5.md new file mode 100644 index 000000000..d0e0cf9a9 --- /dev/null +++ b/scenarios/S-fail-5.md @@ -0,0 +1,57 @@ +# S-fail-5 — a typed error boundary wrapped by an inner catch-all is dead + +Rules: R-f-4. The catch-all takes `NotFound` first, so the typed fallback +never shows. + +## Program + +```rx +error NotFound +export default component App() { + errored fallback(e) {

    {e.message}

    } { + errored fallback(e: NotFound) {

    missing

    } {

    ok

    } + } +} +``` + +The typed boundary is inside the catch-all, which is where it can still see +`NotFound`. + +## Frames + +| instant | action | frame | +| --- | --- | --- | +| 0 | mount | `ok` | + +## Variant: a failure in the inner fallback reaches the outer region + +```rx +error NotFound +error Offline +export default component App() { + failed = throw Offline() + fallbackFailed = throw NotFound() + errored fallback(e: NotFound) {

    missing

    } { + errored fallback(e) {

    {fallbackFailed}

    } {

    {failed}

    } + } +} +``` + +| instant | action | frame | +| --- | --- | --- | +| 0 | mount | `missing` | + +## Rejected + +```rx +-- reject: DEAD_TYPED_BOUNDARY +error NotFound +export default component App() { + errored fallback(e: NotFound) {

    missing

    } { + errored fallback {

    failed

    } {

    x

    } + } +} +``` + +The inner catch-all wraps the children. `NotFound` never reaches the typed +fallback. diff --git a/scenarios/S-fail-6.md b/scenarios/S-fail-6.md new file mode 100644 index 000000000..1dce73877 --- /dev/null +++ b/scenarios/S-fail-6.md @@ -0,0 +1,24 @@ +# S-fail-6 — read order controls which failure is shown + +Rules: E-3, E-8, R-f-4. The guard can skip the `details` read entirely, +or demand it before deciding whether to show the title. + +## Program + +```rx +error Missing +export default component App() { + source shown := false + details = throw Missing() + errored fallback(e: Missing) {

    missing

    } { + if shown && details {

    title

    } + } +} +``` + +## Frames + +| instant | action | frame | +| --- | --- | --- | +| 0 | mount | | +| 1 | handler `shown := true` | `missing` | diff --git a/scenarios/S-fn-block.md b/scenarios/S-fn-block.md new file mode 100644 index 000000000..60088d434 --- /dev/null +++ b/scenarios/S-fn-block.md @@ -0,0 +1,49 @@ +# S-fn-block — declarations in a block fn instantiate + +Rules: E-9, E-10. Declarations in a block `fn` belong to the +instantiation. An arrow with a value expression needs no snapshot. + +## Program + +```rx +fn size(xs: number[]) => xs.length +export default component App() { + source xs := [1, 2] +

    {size(xs)}

    +} +``` + +## Frames + +| instant | action | frame | +| --- | --- | --- | +| 0 | mount | `2` | + +## Rejected + +```rx +-- reject: SNAPSHOT_ARGUMENT +fn total(xs: number[], k: number) { + fn twice(n: number) => n * 2 + base = xs.length + twice(base) + k +} +export default component App() { + source xs := [1, 2] + n = total(xs, 1) +

    {n}

    +} +``` + +```rx +-- reject: SNAPSHOT_ARGUMENT +fn first(id: number) { + rows = await fetch(id) catch (e) => "" + rows +} +export default component App() { + source id := 1 + row = first(id) +

    {row}

    +} +``` diff --git a/scenarios/S-handler-narrow-1.md b/scenarios/S-handler-narrow-1.md new file mode 100644 index 000000000..1ce6041ed --- /dev/null +++ b/scenarios/S-handler-narrow-1.md @@ -0,0 +1,48 @@ +# S-handler-narrow-1 — A handler reads a snapshot, so a view branch does not narrow it + +Rules exercised: 13 TY-2. A read in a handler is taken when the handler runs, +not when the view branch was chosen. The branch may no longer hold, so +narrowing the handler's read would be unsound. Snapshot it and narrow the +local. + +## Program + +```rx +type Item = { id: number } +export default component App() { + source detail: Item | null := null + {if detail != null { + + }} +} +``` + +`{detail.id}` is a read of the branch, re-checked while the branch is live, so +it is narrowed. The handler snapshots `detail` into `d` and narrows that: `d` +does not change before the read. + +## Frames + +| instant | action | frame | +| ------- | ------ | ----- | +| 0 | mount | `` | + +## Rejected variants + +```rx +-- types: TS18047 +type Item = { id: number } +export default component App() { + source detail: Item | null := null + {if detail != null { + } ``` + +``` +-- reject: JSX_TERNARY +export default component App() { + source c := true +

    {c ? : ""}

    +} +``` + +``` +-- reject: FOR_INDEX +export default component App() { + source xs := [1] + {for x, i in xs {

    {x}

    }} +} +``` diff --git a/scenarios/S-pure-globals.md b/scenarios/S-pure-globals.md new file mode 100644 index 000000000..9bd564762 --- /dev/null +++ b/scenarios/S-pure-globals.md @@ -0,0 +1,40 @@ +# S-pure-globals — pure JS operations without an import + +Rule: SV-7a. Native conversions and selected static members are value calculations. + +## Program + +```rx +export default component App() { + data = JSON.parse(JSON.stringify({ a: 2 })) + copy = Object.fromEntries(Object.entries(data)) + names = Object.keys(copy) + values = Object.values(copy) + count = Math.round(Number("2.1")) + Number.parseInt("3") + text = String(count) + String.fromCharCode(33) +

    {Array.isArray(values)}:{names[0]}:{values[0]}:{text}

    +} +``` + +## Frames + +| instant | action | frame | +| --- | --- | --- | +| 0 | mount | `true:a:2:5!` | + +## Rejected + +```rx +-- reject: UNBOUND +export default component App() {

    {Math.random()}

    } +``` + +```rx +-- reject: UNBOUND +export default component App() {

    {Date.now()}

    } +``` + +```rx +-- reject: UNBOUND +export default component App() {

    {Object.assign({}, {})}

    } +``` diff --git a/scenarios/S-source-write-1.md b/scenarios/S-source-write-1.md new file mode 100644 index 000000000..5079060ee --- /dev/null +++ b/scenarios/S-source-write-1.md @@ -0,0 +1,27 @@ +# S-source-write-1 — A source's type is its widened type, and a write checks that + +Rules exercised: 13 TY-2. A source is written later, so its initializer's +literal is not its type, and a branch that narrows a read does not narrow +what a write may store. + +## Program + +```rx +export default component App() { + source open := false + {if open { }} + +} +``` + +`open` is a boolean: `false` says what it starts as, not what it may become. +Inside `{if open}` the read is `true`, and `open := false` is still a boolean +write — the branch does not change the source's type. + +## Frames + +| instant | action | frame | +| ------- | ---------------------- | ----- | +| 0 | mount | `n` | +| 1 | handler `open := true` | `closey` | +| 2 | handler `open := false` | `n` | diff --git a/scenarios/S-surface-2.md b/scenarios/S-surface-2.md index fa3197d88..22b06c835 100644 --- a/scenarios/S-surface-2.md +++ b/scenarios/S-surface-2.md @@ -88,3 +88,18 @@ export default component App() { ``` One stylesheet per view (TSRX: "fragments can only have one style tag"). + +```rx +-- reject: STYLE_SCOPE +component Row() { +
  • x
  • +} +export default component App() { + + +} +``` + +`Row` is its own view (CSS-2). `App`'s `.row` does not style it. Give `Row` its own ` + + +
    + + + + diff --git a/tooling/rx-map/app/state.rx b/tooling/rx-map/app/state.rx new file mode 100644 index 000000000..9743f86a7 --- /dev/null +++ b/tooling/rx-map/app/state.rx @@ -0,0 +1,59 @@ +// The map's state: the graph and its model, what is selected, hovered, traced and hidden, and the layout the edges +// are drawn on. Every view reads it; only the actions here write it. +import { isDiff, loadJSON, saveJSON } from "./js/env.js" +import { graphSignal } from "./js/graphs.js" +import { toSet } from "./js/util.js" +import { buildModel, neighbourhood, downstream, upstream } from "./js/model.js" +import { boardView, detailLevel, overviewLevel } from "./js/layout.js" + +// ---- the graph ----------------------------------------------------------------------------------------------- +// the graph comes through a host signal (graphs.js, MO-10 `ref`): a source holding it would be a store over all of it +[graph, setGraph] = graphSignal() +export model = buildModel(graph) +export board = boardView(model) +export diff = isDiff() + +// ---- what is looked at --------------------------------------------------------------------------------------- +// selected: the pinned name or region; focus: the trace lit on the map (a selection's neighbourhood, a hover's, or +// what a trace button asked for); null when nothing is lit +export source selected: string | null := null +export source focus: { ids: string[]; edges: number[] } | null := null +export source hoverId: string | null := null +// the before / after view of a diff +export source diffView: string := "both" +// every edge, not just the lit ones +export source allEdges := false +// legend toggles: `k:`, `e:`, `d:changes`; remembered +export source hidden: string[] := loadJSON("rx-map:hidden", []) +effect (hidden) { saveJSON("rx-map:hidden", $0) } +// a diff summary item marks its first name as if selected, without selecting it +export source marked: string | null := null +export action mark(id: string | null) { marked := id } + +// what is lit, as a lookup: a view asks `lit[id]` +export lit = toSet(focus == null ? [] : focus.ids) + +export source level := detailLevel() +export overview = level == overviewLevel() +export action showLevel(l: number) { level := l } + +// ---- selection and traces -------------------------------------------------------------------------------------- +export action hover(id: string | null) { + hoverId := id + if (selected == null) { focus := id == null ? null : neighbourhood(model, id, diffView) } +} +export action select(id: string | null) { + selected := id + marked := null + focus := id == null ? null : neighbourhood(model, id, diffView) +} +export action traceFrom(dir: string) { + if (selected != null) { focus := dir == "down" ? downstream(model, selected, diffView) : upstream(model, selected, diffView) } +} +export action showTrace(t: { ids: string[]; edges: number[] } | null) { focus := t } +export action setDiffView(v: string) { diffView := v } +export action setAllEdges(on: boolean) { allEdges := on } +export action toggleHidden(k: string) { hidden := hidden.includes(k) ? hidden.filter(x => x != k) : [...hidden, k] } +export action showKinds(ks: string[]) { hidden := hidden.filter(x => !ks.includes(x)) } +export action hideKinds(ks: string[]) { hidden := [...hidden.filter(x => !ks.includes(x)), ...ks] } +export action swapGraph(g: any) { setGraph(g) } diff --git a/tooling/rx-map/app/tip.rx b/tooling/rx-map/app/tip.rx new file mode 100644 index 000000000..bfe678af0 --- /dev/null +++ b/tooling/rx-map/app/tip.rx @@ -0,0 +1,32 @@ +// The tooltip: a token's role in words, its line, where it is, and (live) its value; a region's construct. +import { roleIcon } from "./js/vocab.js" +import { tipInfo } from "./js/model.js" +import { hl } from "./js/hl.js" +import { placeTipNow } from "./js/tip.js" +import { model, hoverId } from "./state.rx" +import { TipLive, PlanReason } from "./live.rx" + +export component Tip() { + t = hoverId == null ? null : tipInfo(model, hoverId) + effect (hoverId) { placeTipNow() } + +} diff --git a/tooling/rx-map/app/ui.rx b/tooling/rx-map/app/ui.rx new file mode 100644 index 000000000..281b6ea7e --- /dev/null +++ b/tooling/rx-map/app/ui.rx @@ -0,0 +1,119 @@ +// The HUD's own state: the side panel (open, which tab, the tab to give back when a selection is cleared) and search. +// Selecting from anywhere goes through `pick` here, which opens the panel on the selected name. +import { isDiff, isLive, loadJSON, saveJSON } from "./js/env.js" +import { flyToId } from "./js/camera.js" +import { sfx } from "./js/sound.js" +import { toSet } from "./js/util.js" +import { searchHits } from "./js/model.js" +import { model, hidden, selected, select } from "./state.rx" + +// ---- the side panel ------------------------------------------------------------------------------------------- +// tabs: "changes" (a diff), "help", "legend", "plan" (a module replacement's), "node" (the selected name) +export panelKey = isDiff() ? "rx-map:panel:diff" : "rx-map:panel" +// the panel's own tabs (the plan and the selected name's come and go) +// live: the calls across the trust boundary (live.rx CallsPanel) +export tabs = [...(isDiff() ? [{ id: "changes", label: "Changes" }] : []), { id: "help", label: "Guide" }, { id: "legend", label: "Legend" }, + ...(isLive() ? [{ id: "calls", label: "Calls" }] : [])] +export firstTab = isDiff() ? "changes" : "help" +saved = loadJSON(panelKey, null) +export source tab: string := peek(saved) != null && peek(tabs).some(t => t.id == peek(saved).tab) ? peek(saved).tab : peek(firstTab) +export source open: boolean := peek(saved) != null ? peek(saved).open == true : isDiff() +// the tab and openness a selection took over, given back when it is cleared +export source before: { tab: string; open: boolean } | null := null + +// remembered: a transient tab (a name, a plan) is remembered as the tab it took over +effect (tab, open, before) { + let transient = $0 == "node" || $0 == "plan" + saveJSON(panelKey, { tab: transient ? ($2 != null ? $2.tab : firstTab) : $0, open: transient ? ($2 != null ? $2.open : false) : $1 }) +} + +// ---- select ----------------------------------------------------------------------------------------------------- +/** Select a name or region (or clear with null); `scroll` flies the camera to it. */ +export action pick(id: string | null, scroll: boolean) { + if (id == null) { + if (selected != null) { sfx("deselect") } + if (selected != null && tab == "node") { + tab := before != null ? before.tab : firstTab + open := before != null ? before.open : false + before := null + } + select(null) + } else { + if (selected == null && tab != "node" && tab != "plan") { before := { tab: tab, open: open } } + select(id) + sfx("select") + tab := "node" + open := true + if (scroll) { flyToId(id, "select") } + } +} + +// ---- search: every match lights; ↑ / ↓ go from one to the next, Enter selects ------------------------------------- +export source query: string := "" +q = query.trim().toLowerCase() +export hits = q == "" ? [] : searchHits(model, q, hidden) +export hitSet = toSet(hits) +export source hitAt: number := 0 +export action setQuery(text: string) { + query := text + hitAt := 0 +} +export action searchGo(i: number) { + if (hits.length > 0) { + let n = (i + hits.length) % hits.length + hitAt := n + flyToId(hits[n], "search") + } +} + +// ---- the panel's tabs -------------------------------------------------------------------------------------------- +/** Open the panel on a tab; a selection is cleared first, keeping the tab given (unless the tab is the name's own). */ +export action openTab(t: string) { + if (selected != null && t != "node") { + before := null + select(null) + } + tab := t + open := true +} + +/** The Calls tab, filtered to one import's calls (its key; "" for all). */ +export source callFilter: string := "" +export action showCalls(fnKey: string) { + callFilter := fnKey + openTab("calls") +} + +/** A tab opened for the user, not by them (a module replacement's plan): remembers what it took over. */ +export action openFor(t: string) { + if (selected == null && tab != "node" && tab != "plan") { before := { tab: tab, open: open } } + openTab(t) +} +/** That tab went away (the app reloaded, the plan with it): give back what it took over, if it is still shown. */ +export action closeFor(t: string) { + if (tab == t) { + tab := before != null ? before.tab : firstTab + open := before != null ? before.open : false + before := null + } +} + +/** Close the panel; a selection is cleared with it, and the tab it took over comes back (closed). */ +export action closePanel() { + if (selected != null) { + sfx("deselect") + if (tab == "node") { + tab := before != null ? before.tab : firstTab + before := null + } else { + before := { tab: before != null ? before.tab : firstTab, open: false } + } + select(null) + } + open := false +} +/** The header button: close the panel, or open it on the last tab that isn't a name's or a plan's. */ +export action togglePanel() { + if (open) { closePanel() } + else { openTab(tab == "node" || tab == "plan" ? firstTab : tab) } +} diff --git a/tooling/rx-map/build.mjs b/tooling/rx-map/build.mjs new file mode 100644 index 000000000..f8230fc90 --- /dev/null +++ b/tooling/rx-map/build.mjs @@ -0,0 +1,127 @@ +#!/usr/bin/env node +// Builds the map page from its .rx program (app/): compiles app/main.rx with this repository's compiler (Node-API +// `app()`), bundles it with its own copy of Solid 2 and @reactivescript/runtime (esbuild, a dev-only dependency) and +// the CSS into one self-contained HTML page, and writes it as a string in page.mjs, which exports +// `pageHTML(graph, opts)`. page.mjs is generated and committed: the package ships it and has no runtime dependencies. +// +// node build.mjs # write page.mjs +// node build.mjs --check # fail if page.mjs is not what the sources give +// node build.mjs --html [--live] [--fake ] # also write one page, for a look +// +// Where things come from: the compiler's binding (compiler/index.js), esbuild and Solid from ref/node_modules (Solid's +// built dists, pinned below: the packages' own exports would pull Solid's TypeScript sources in), the runtime from +// runtime/dist. `RX_SOLID` overrides the Solid packages dir (a checkout's `packages`). +import { readFileSync, writeFileSync, existsSync, realpathSync } from "node:fs"; +import { createRequire } from "node:module"; +import path from "node:path"; +import { fileURLToPath } from "node:url"; + +const here = path.dirname(fileURLToPath(import.meta.url)); // the package +const src = path.join(here, "app"); // the program +const repo = path.resolve(here, "../.."); +const refReq = createRequire(path.join(repo, "ref/package.json")); +const esbuild = refReq("esbuild"); +const { app } = createRequire(path.join(repo, "compiler/package.json"))("./index.js"); +const solidPkgs = process.env.RX_SOLID ?? path.dirname(realpathSync(path.join(repo, "ref/node_modules/solid-js"))); +const PIN = { + "solid-js": "solid/dist/solid.js", + "solid-js/internal": "solid/dist/internal.js", + "@solidjs/web": "web/dist/web.js", + "@solidjs/signals": "signals/dist/prod/index.js", +}; +for (const f of Object.values(PIN)) if (!existsSync(path.join(solidPkgs, f))) throw new Error(`no Solid build at ${path.join(solidPkgs, f)} (set RX_SOLID to a Solid checkout's packages dir)`); + +const entry = path.join(src, "main.rx"); +const out = JSON.parse(app(entry, "dom", null, true, false)); +if (out.diagnostics) { + for (const d of out.diagnostics) console.error(`${d.file}:${d.range ? `${d.range.start.line}:${d.range.start.column + 1}` : d.line}: error ${d.code} [${d.rule}] ${d.msg}`); + process.exit(1); +} +if (out.error) { console.error(out.error); process.exit(1); } +const mods = Object.fromEntries(Object.entries(out.modules).map(([p, m]) => [path.resolve(p), m])); + +// fake.mjs (the fake host, without its Node-only CLI) and hmr.mjs, as one module the page imports +const fakeSrc = (() => { + const s = readFileSync(path.join(here, "fake.mjs"), "utf8"); + const cli = s.indexOf("\nfunction isCli()"); + if (cli < 0) throw new Error("fake.mjs: cannot find where its CLI starts (function isCli)"); + return s.slice(0, cli); +})(); + +const res = await esbuild.build({ + stdin: { contents: readFileSync(path.join(src, "boot.js"), "utf8"), resolveDir: src, sourcefile: "boot.js", loader: "js" }, + bundle: true, write: false, format: "iife", platform: "browser", target: "es2022", + minify: !process.argv.includes("--no-minify"), legalComments: "none", charset: "utf8", + alias: { "@reactivescript/runtime": path.join(repo, "runtime/dist/web.js") }, + logLevel: "error", + plugins: [{ + name: "rx-map", + setup(b) { + b.onResolve({ filter: /^(solid-js|solid-js\/internal|@solidjs\/web|@solidjs\/signals)$/ }, a => ({ path: path.join(solidPkgs, PIN[a.path]) })); + b.onResolve({ filter: /\.rx$/ }, a => ({ path: path.resolve(a.resolveDir, a.path), namespace: "rx" })); + b.onLoad({ filter: /.*/, namespace: "rx" }, a => { + const m = mods[a.path]; + if (!m) throw new Error(`${a.path}: not in the compiled program`); + return { contents: m.code, loader: "js", resolveDir: path.dirname(a.path) }; + }); + b.onResolve({ filter: /^rx-map:fake$/ }, () => ({ path: path.join(here, "fake.mjs"), namespace: "fake" })); + b.onLoad({ filter: /.*/, namespace: "fake" }, () => ({ contents: fakeSrc, loader: "js", resolveDir: here })); + }, + }], +}); +const js = res.outputFiles[0].text; +const css = readFileSync(path.join(src, "map.css"), "utf8") + Object.values(mods).map(m => m.css ?? "").join("\n"); +if (/<\/script/i.test(js)) throw new Error("the bundle contains css).replace("/*__JS__*/", () => js); +for (const p of ["/*__GRAPH__*/null", "/*__LIVE__*/false", "/*__FAKE__*/null", ""]) + if (!html.includes(p)) throw new Error(`shell.html lost its ${p} placeholder`); + +// what the page was built from: a change to any of these makes page.mjs stale (`--check` fails), so rebuild +const version = p => JSON.parse(readFileSync(p, "utf8")).version; +const inputs = [ + `@reactivescript/compiler ${version(path.join(repo, "compiler/package.json"))} (Node-API binding)`, + `@reactivescript/runtime ${version(path.join(repo, "runtime/package.json"))} (runtime/dist)`, + `solid-js ${version(path.join(solidPkgs, "solid/package.json"))}, @solidjs/web ${version(path.join(solidPkgs, "web/package.json"))}, @solidjs/signals ${version(path.join(solidPkgs, "signals/package.json"))} (dists)`, + `esbuild ${version(refReq.resolve("esbuild/package.json"))}`, +].join("; "); +const page = `// Generated from app/ (main.rx and its modules) by build.mjs (npm run build). Edit the sources, not this file. +// Built with: ${inputs}. +const HTML = ${JSON.stringify(html)}; + +const esc = s => String(s).replace(/[<&]/g, c => (c === "<" ? "<" : "&")); + +/** + * The map page for \`graph\` (from \`buildGraph\`, or \`diffGraphs\` for a diff), one self-contained HTML document. + * \`live: true\` makes it listen for the messages \`@reactivescript/map/live\` posts (\`source: "rx-map"\`). + * \`fake: seed\` runs the fake host (\`@reactivescript/map/fake\`) inside the page, with a dev HUD to drive it. + */ +export function pageHTML(graph, { live = false, fake = null } = {}) { + const title = graph.title ?? (graph.modules ?? []).map(m => m.split("/").pop()).join(", "); + return HTML + .replace("/*__LIVE__*/false", () => String(!!live || fake != null)) + .replace("/*__FAKE__*/null", () => (fake == null ? "null" : String(Number(fake) || 1))) + .replaceAll("", () => esc(title)) + .replace("/*__GRAPH__*/null", () => JSON.stringify(graph).replace(/= 0) { + const { pageHTML } = await import(`${target}?t=${Date.now()}`); + const graph = JSON.parse(readFileSync(args[h + 1], "utf8")); + const f = args.indexOf("--fake"); + writeFileSync(args[h + 2], pageHTML(graph, { live: args.includes("--live"), fake: f >= 0 ? args[f + 1] : null })); + console.log(`wrote ${args[h + 2]}`); +} diff --git a/tooling/rx-map/conformance.mjs b/tooling/rx-map/conformance.mjs new file mode 100644 index 000000000..cc61888de --- /dev/null +++ b/tooling/rx-map/conformance.mjs @@ -0,0 +1,641 @@ +// Conformance suite for a trace host (TRACE-CONTRACT §5). `runConformance(makeHost, graphs)` drives each graph +// and returns a readable result list. The fake must pass; the real host must pass before it replaces the fake. +// Pure ESM, no dependencies. + +const KNOWN = new Set(["flush", "flight", "reset", "timeline", "step", "resume", "travel-denied", "travel-pending", "hmr"]); +const REASONS = new Set(["unchanged", "init-changed", "type-changed", "kind-changed", "scope-changed", "expr-changed", "upstream-changed", "new", "gone", "renamed", "reindexed"]); +const PLAN_KINDS = new Set(["source", "eq", "effect", "action"]); + +/** + * A view ignores a message whose type it doesn't know. This is the page's rule, checked here against a reference + * reducer so a host suite still has the check when the page isn't loaded. + */ +export function viewReduce(state, msg) { + if (!msg || typeof msg.type !== "string" || !KNOWN.has(msg.type)) return state; + if (msg.type === "reset") return { values: new Map(), seq: 0 }; + if (msg.type === "flush") { + const values = new Map(state.values); + for (const c of msg.changes ?? []) { + if (c.preview === undefined) values.delete(c.key); + else values.set(c.key, c.preview); + } + return { values, seq: msg.seq }; + } + return state; +} + +function graphLabel(graph) { + return graph?.title || graph?.modules?.[0] || "graph"; +} + +function keysOf(graph) { + return new Set((graph?.nodes ?? []).map(n => n.key).filter(Boolean)); +} + +function planNodeKeys(graph) { + return new Set((graph?.nodes ?? []).filter(n => n.key && PLAN_KINDS.has(n.kind)).map(n => n.key)); +} + +/** Errors in an HMR plan, or an empty list. Exported so a caller can check a plan it built itself. */ +export function partitionErrors(plan, oldGraph, newGraph) { + const errors = []; + if (!plan || typeof plan !== "object") return ["plan missing"]; + const buckets = ["kept", "reset", "rerun", "added", "removed"]; + for (const name of buckets) if (!Array.isArray(plan[name])) errors.push(`${name} is not a list`); + if (!Array.isArray(plan.moved)) errors.push("moved is not a list"); + if (!plan.reasons || typeof plan.reasons !== "object") errors.push("reasons missing"); + if (errors.length) return errors; + + const universe = new Set([...planNodeKeys(oldGraph), ...planNodeKeys(newGraph)]); + const seen = new Map(); + for (const name of buckets) { + for (const k of plan[name]) { + if (seen.has(k)) errors.push(`${k} is in ${seen.get(k)} and ${name}`); + else seen.set(k, name); + } + } + const froms = new Set(); + for (const m of plan.moved) { + if (!m || typeof m.from !== "string" || typeof m.to !== "string") { errors.push("moved entry is not { from, to }"); continue; } + if (froms.has(m.from)) errors.push(`${m.from} moved twice`); + froms.add(m.from); + if (seen.has(m.from)) errors.push(`${m.from} is moved.from and also in ${seen.get(m.from)}`); + const bucket = seen.get(m.to); + if (bucket !== "kept" && bucket !== "reset" && bucket !== "rerun") errors.push(`moved.to ${m.to} is ${bucket ?? "missing"}, want kept, reset or rerun`); + } + for (const k of universe) { + if (!seen.has(k) && !froms.has(k)) errors.push(`${k} missing from the plan`); + } + for (const k of seen.keys()) if (!universe.has(k)) errors.push(`${k} is in the plan but is not a source, equation, effect or action`); + for (const k of froms) if (!universe.has(k)) errors.push(`moved.from ${k} is not in the old graph`); + + const need = new Set([...seen.keys(), ...froms]); + for (const k of need) { + if (!(k in plan.reasons)) errors.push(`no reason for ${k}`); + else if (!REASONS.has(plan.reasons[k])) errors.push(`reason ${plan.reasons[k]} for ${k} is not a known code`); + } + for (const k of Object.keys(plan.reasons)) if (!need.has(k)) errors.push(`reason for ${k} but that key is not in the plan`); + + const expect = { kept: new Set(["unchanged", "init-changed"]), reset: new Set(["type-changed", "kind-changed", "scope-changed"]), rerun: new Set(["expr-changed", "upstream-changed"]), added: new Set(["new"]), removed: new Set(["gone"]) }; + for (const [bucket, ok] of Object.entries(expect)) { + for (const k of plan[bucket]) if (plan.reasons[k] && !ok.has(plan.reasons[k])) errors.push(`${k} is ${bucket} but reason is ${plan.reasons[k]}`); + } + for (const k of froms) { + const r = plan.reasons[k]; + if (r && r !== "renamed" && r !== "reindexed" && r !== "scope-changed") errors.push(`moved.from ${k} has reason ${r}`); + } + return errors; +} + +// A key's state: its preview, or its error (v0.6: an error is a shown state, not an absence). +const ERR = "\u0000error\u0000"; +const stateOf = c => c.error !== undefined ? ERR + c.error : c.preview; +const prevStateOf = c => c.prevError !== undefined ? ERR + c.prevError : c.prev; + +function reconstruct(steps, n) { + // Before a key's first change, its value is that change's `prev` (§4b). + const m = new Map(), seen = new Set(); + for (const s of steps) for (const c of s.changes ?? []) { + if (c.key == null || seen.has(c.key)) continue; + seen.add(c.key); + if (c.prev !== undefined) m.set(c.key, c.prev); + } + for (const s of steps) { + if (s.seq > n) break; + for (const c of s.changes ?? []) { + // keyed nodes only: a change with no key is shown in the flush but is no state travel restores (§1, §2 step) + if (c.key == null) continue; + if (stateOf(c) === undefined) m.delete(c.key); + else m.set(c.key, stateOf(c)); + } + } + return m; +} + +function applyChanges(map, changes) { + const next = new Map(map); + for (const c of changes ?? []) { + if (c.key == null) continue; + if (stateOf(c) === undefined) next.delete(c.key); + else next.set(c.key, stateOf(c)); + } + return next; +} + +function mapsEqual(a, b) { + if (a.size !== b.size) return false; + for (const [k, v] of a) if (b.get(k) !== v) return false; + return true; +} + +function diffKeys(a, b) { + const keys = new Set([...a.keys(), ...b.keys()]); + const out = []; + for (const k of keys) if (a.get(k) !== b.get(k) || a.has(k) !== b.has(k)) out.push(k); + return out.sort(); +} + +/** + * @param {(graph: object, opts?: { seed?: number, rate?: number, capacity?: number }) => object} makeHost + * @param {object[]} graphs + * @param {{ seed?: number }} [opts] + * @returns {{ ok: boolean, check: string, graph?: string, detail?: string }[]} + */ +export function runConformance(makeHost, graphs, opts = {}) { + return drive(makeHost, graphs, opts, run => { + for (let it = run.next(); !it.done; it = run.next(it.value)); + }); +} + +/** + * The same suite for a host whose calls take time (a real app in a browser): `makeHost` and the host's `post`, + * `act`, `tick`, `editModule` and `dispose` may return promises, and messages a call caused must have reached + * `subscribe`'s listeners by the time its promise settles. + * @returns {Promise<{ ok: boolean, check: string, graph?: string, detail?: string }[]>} + */ +export async function runConformanceAsync(makeHost, graphs, opts = {}) { + const runs = []; + const results = drive(makeHost, graphs, opts, run => runs.push(run)); + for (const run of runs) { + // a rejected call throws where the suite made it, so the check that made it reports it + for (let it = run.next(); !it.done;) { + let value, error, failed = false; + try { value = await it.value; } catch (e) { error = e; failed = true; } + it = failed ? run.throw(error) : run.next(value); + } + } + return results; +} + +function drive(makeHost, graphs, opts, start) { + const results = []; + const seed = opts.seed ?? 1; + const push = (ok, check, graph, detail) => results.push(detail ? { ok, check, graph, detail } : { ok, check, graph }); + + const withUnknown = [ + { type: "flush", seq: 1, at: 1, changes: [{ key: "k", name: "k", preview: "1" }] }, + { type: "not-a-real-type", surprise: true }, + { type: "flush", seq: 2, at: 2, changes: [{ key: "k", name: "k", preview: "2" }] }, + ]; + const without = [withUnknown[0], withUnknown[2]]; + const a = withUnknown.reduce(viewReduce, { values: new Map(), seq: 0 }); + const b = without.reduce(viewReduce, { values: new Map(), seq: 0 }); + const ignored = a.seq === b.seq && a.values.get("k") === b.values.get("k"); + push(ignored, "unknown types ignored", undefined, ignored ? "reference view" : "reference view applied an unknown type"); + + for (const graph of graphs ?? []) { + const label = graphLabel(graph); + start((function* () { + try { yield* checkOne(makeHost, graph, label, seed, push); } + catch (e) { push(false, "host threw", label, e?.message ?? String(e)); } + })()); + } + return results; +} + +// What the app displays (§5: the arbiter for a real host). `host.shown(keys)` returns `{ [key]: {preview}|{error} }` +// for the keys it displays now (absent: shows none). Compared with the replay of the host's own messages, over the +// replay's keys, except those a step marks inexact. +const toStates = shown => { + const m = new Map(); + for (const [k, v] of shown instanceof Map ? shown : Object.entries(shown ?? {})) { + const st = v == null ? undefined : typeof v === "string" ? v : stateOf(v); + if (st !== undefined) m.set(k, st); + } + return m; +}; +const fmtState = v => v === undefined ? "nothing" : v.startsWith(ERR) ? `error ${v.slice(ERR.length)}` : v; +function* shownVs(h, want, skip = []) { + if (typeof h.shown !== "function") return null; + const keys = [...want.keys()].filter(k => !skip.includes(k)); + const got = toStates(yield h.shown(keys)); + return keys.filter(k => got.get(k) !== want.get(k)).map(k => `${k}: shows ${fmtState(got.get(k))}, replay ${fmtState(want.get(k))}`); +} + +function* checkOne(makeHost, graph, label, seed, push) { + const hostOpts = { seed, rate: 0, capacity: 2000 }; + const host = yield makeHost(graph, hostOpts); + const msgs = []; + host.subscribe(m => msgs.push(m)); + try { + yield host.post({ type: "hello", want: ["live", "timeline", "travel", "hmr"] }); + const beforeUnknown = msgs.length; + yield host.post({ type: "definitely-unknown", want: [] }); + if (msgs.length !== beforeUnknown) push(false, "unknown types ignored", label, "host emitted a message for an unknown view message"); + else push(true, "unknown types ignored", label, "host ignored an unknown view message"); + + for (let i = 0; i < 5; i++) { + yield host.act(); + yield host.tick(8); + } + } catch (e) { + push(false, "host threw", label, e?.message ?? String(e)); + yield host.dispose?.(); + return; + } + + const flushes = msgs.filter(m => m.type === "flush"); + const envelopeOk = msgs.every(m => m && m.source === "rx-map" && m.v === 1); + push(envelopeOk, "messages carry v and source", label, envelopeOk ? undefined : "a message lacked source or v: 1"); + + let seqOk = true, seqDetail = ""; + let prevSeq = 0; + for (const f of flushes) { + if (typeof f.seq !== "number" || f.seq <= prevSeq) { seqOk = false; seqDetail = `seq ${f.seq} after ${prevSeq}`; break; } + prevSeq = f.seq; + } + push(seqOk, "seq strictly increasing", label, seqDetail || undefined); + + let atOk = true, atDetail = ""; + let prevAt = -Infinity; + for (const m of msgs) { + if (typeof m.at !== "number") continue; + if (m.at < prevAt) { atOk = false; atDetail = `at ${m.at} after ${prevAt} (${m.type})`; break; } + prevAt = m.at; + } + push(atOk, "at non-decreasing", label, atDetail || undefined); + + let currentKeys = keysOf(graph); + const allKeys = new Set(currentKeys); + let keyOk = true, keyDetail = ""; + for (const m of msgs) { + if (m.type === "hmr" && m.phase === "plan" && m.graph) { + currentKeys = keysOf(m.graph); + for (const k of currentKeys) allKeys.add(k); + } + const changes = m.type === "flush" ? m.changes : m.type === "step" || m.type === "resume" || (m.type === "hmr" && m.phase === "done") ? m.changes : null; + if (!changes) continue; + const bag = m.type === "flush" || (m.type === "hmr" && m.phase === "done") ? currentKeys : allKeys; + for (const c of changes) { + if (c.key != null && !bag.has(c.key)) { keyOk = false; keyDetail = `${c.key} on ${m.type}`; break; } + } + if (!keyOk) break; + } + push(keyOk, "change keys exist", label, keyDetail || undefined); + + const open = new Map(); + let flightOrder = true, flightOrderDetail = ""; + let flightDouble = true, flightDoubleDetail = ""; + for (const m of msgs) { + if (m.type !== "flight") continue; + if (m.state === "start") { + if (open.has(m.key)) { flightDouble = false; flightDoubleDetail = m.key; } + open.set(m.key, true); + } else if (m.state === "land" || m.state === "abandon") { + if (!open.has(m.key)) { flightOrder = false; flightOrderDetail = `${m.state} of ${m.key} without start`; } + open.delete(m.key); + } else { flightOrder = false; flightOrderDetail = `bad state ${m.state}`; } + } + push(flightOrder, "flight start before end", label, flightOrderDetail || (msgs.some(m => m.type === "flight") ? undefined : "no flights")); + push(flightDouble, "no double flight start", label, flightDoubleDetail || undefined); + + // v0.9: a flight start's `cause` says what re-asked it (well formed, known keys), a rejected ask's `abandon` its error; + // and a question asked again names what changed at least once (the map's call history rests on it) + let causeOk = true, causeDetail = ""; + const asked = new Map(); + let reasks = 0, reasksWithCause = 0; + for (const m of msgs) { + if (m.type !== "flight") continue; + if (m.state === "abandon" && m.error !== undefined && typeof m.error !== "string") { causeOk = false; causeDetail = `abandon of ${m.key}: error is not a string`; } + if (m.state !== "start") continue; + if (m.cause !== undefined) { + const bad = !Array.isArray(m.cause) ? "not a list" : m.cause.find(c => typeof c?.name !== "string" || (c.key != null && !allKeys.has(c.key))); + if (bad) { causeOk = false; causeDetail = `cause of ${m.key}: ${typeof bad === "string" ? bad : JSON.stringify(bad)}`; } + } + if (asked.has(m.key)) { reasks++; if (m.cause?.length) reasksWithCause++; } + asked.set(m.key, true); + } + push(causeOk, "flight causes are well formed (v0.9)", label, causeDetail || undefined); + push(!reasks || reasksWithCause > 0, "a re-asked question says what re-asked it (v0.9)", label, + reasks ? (reasksWithCause ? undefined : `${reasks} re-asks, none with a cause`) : "no re-asks"); + + // Two hosts that see the same calls. Travel must not depend on which path you took. + const script = function* (h) { + yield h.post({ type: "hello", want: ["live", "timeline", "travel", "hmr"] }); + for (let i = 0; i < 4; i++) { yield h.act(); yield h.tick(8); } + yield h.tick(12); + }; + const everything = [msgs]; + const collect = h => { + const box = []; + h.subscribe(m => box.push(m)); + everything.push(box); + return box; + }; + + // Pending: travel asked for while a flight is open never shows a step before it lands. A v0.5 host denies it + // (`pending`); a v0.6 host answers `travel-pending` and travels once the flight has landed (§4b). + try { + const pHost = yield makeHost(graph, hostOpts); + const pMsgs = collect(pHost); + yield pHost.act(); + const opened = pMsgs.some(m => m.type === "flight" && m.state === "start"); + const nPending = pMsgs.length; + yield pHost.post({ type: "travel", to: 1 }); + const pendingReply = pMsgs.slice(nPending).find(m => m.type === "step" || m.type === "travel-denied" || m.type === "travel-pending"); + if (opened) { + let ok = pendingReply?.type === "travel-denied" && pendingReply.reason === "pending"; + let detail = `got ${pendingReply?.type ?? "nothing"} ${pendingReply?.reason ?? ""}`; + if (pendingReply?.type === "travel-pending") { + const nWait = pMsgs.length; + for (let i = 0; i < 8; i++) yield pHost.tick(4); + const after = pMsgs.slice(nWait); + const landed = after.findIndex(m => m.type === "flight" && m.state !== "start"); + const step = after.findIndex(m => m.type === "step" || m.type === "travel-denied"); + // it goes once the flight lands, or (bounded wait, v0.8) is denied "pending" with what it waits on + ok = step >= 0 && (after[step].type === "travel-denied" + ? after[step].reason === "evicted" || (after[step].reason === "pending" && Array.isArray(after[step].keys)) + : after[step].to === 1 && (landed < 0 || landed < step)); + detail = step < 0 ? "travel-pending, then no step after the flight landed" : `travel-pending, then ${after[step].type} ${after[step].to ?? ""}`; + } + push(ok, "travel pending while a flight is open", label, ok ? undefined : detail); + } else push(true, "travel pending while a flight is open", label, "no flight opened"); + yield pHost.dispose?.(); + } catch (e) { + push(false, "travel pending while a flight is open", label, e?.message ?? String(e)); + } + + let travelHost, travelMsgs; + try { + travelHost = yield makeHost(graph, hostOpts); + travelMsgs = collect(travelHost); + yield* script(travelHost); + } catch (e) { + push(false, "travel matches replay", label, e?.message ?? String(e)); + yield host.dispose?.(); + return; + } + const liveFlushes = () => travelMsgs.filter(m => m.type === "flush"); + const headOf = () => liveFlushes().reduce((h, f) => Math.max(h, f.seq), 0); + const stepsNow = () => liveFlushes().slice().sort((a, b) => a.seq - b.seq); + const head = headOf(); + if (head < 1) { + push(true, "travel matches replay", label, "no flushes"); + push(true, "step changes exact", label, "no flushes"); + push(true, "travel commutative", label, "no flushes"); + push(true, "resume matches live", label, "no flushes"); + push(true, "flushes during viewing kept", label, "no flushes"); + } else { + const mid = Math.max(1, Math.ceil(head / 2)); + const fromBefore = head; + const n = travelMsgs.length; + yield travelHost.post({ type: "travel", to: mid }); + const step = travelMsgs.slice(n).find(m => m.type === "step" || m.type === "travel-denied"); + if (!step || step.type !== "step") { + push(false, "travel matches replay", label, step ? `denied: ${step.reason}` : "no step"); + push(false, "step changes exact", label, "no step"); + } else { + const atFrom = reconstruct(stepsNow(), step.from); + const atTo = reconstruct(stepsNow(), step.to); + const shown = applyChanges(atFrom, step.changes); + const match = mapsEqual(shown, atTo); + push(match, "travel matches replay", label, match ? undefined : `travel(${step.to}) diverges`); + const want = diffKeys(atFrom, atTo); + const got = (step.changes ?? []).map(c => c.key).sort(); + let exact = want.length === got.length && want.every((k, i) => k === got[i]); + let exactDetail = ""; + if (exact) { + for (const c of step.changes) { + const prev = atFrom.has(c.key) ? atFrom.get(c.key) : undefined; + const next = atTo.has(c.key) ? atTo.get(c.key) : undefined; + if ((prevStateOf(c) ?? undefined) !== prev || (stateOf(c) ?? undefined) !== next) { + exact = false; + exactDetail = `${c.key} prev/preview`; + break; + } + } + } else exactDetail = `keys ${got.join(",")} want ${want.join(",")}`; + push(exact, "step changes exact", label, exactDetail || undefined); + const off = yield* shownVs(travelHost, atTo, step.inexact ?? []); + push(off === null || off.length === 0, "app shows the travelled state", label, + off === null ? "host has no shown(): not checked" : off.slice(0, 3).join("; ") || undefined); + if (step.from !== fromBefore && step.from !== head) { + // from should be the live head we travelled from + } + void fromBefore; + } + + // travel(n) then travel(m) equals travel(m) directly. A fresh host, so `from` is live, not a previous view. + const n2 = Math.max(1, head); + const n1 = Math.max(1, Math.min(mid, n2)); + let directOk = false, directDetail = ""; + try { + const path = yield makeHost(graph, hostOpts); + const pathMsgs = collect(path); + yield* script(path); + const pathSteps = pathMsgs.filter(m => m.type === "flush").sort((a, b) => a.seq - b.seq); + const pathHead = pathSteps.reduce((h, f) => Math.max(h, f.seq), 0); + const p1 = pathMsgs.length; + yield path.post({ type: "travel", to: n1 }); + const s1 = pathMsgs.slice(p1).find(m => m.type === "step"); + const p2 = pathMsgs.length; + yield path.post({ type: "travel", to: n2 }); + const s2 = pathMsgs.slice(p2).find(m => m.type === "step"); + let shownA = reconstruct(pathSteps, pathHead); + if (s1?.type === "step") shownA = applyChanges(shownA, s1.changes); + if (s2?.type === "step") shownA = applyChanges(shownA, s2.changes); + + const other = yield makeHost(graph, hostOpts); + const otherMsgs = collect(other); + yield* script(other); + const otherSteps = otherMsgs.filter(m => m.type === "flush").sort((a, b) => a.seq - b.seq); + const otherHead = otherSteps.reduce((h, f) => Math.max(h, f.seq), 0); + const oN = otherMsgs.length; + yield other.post({ type: "travel", to: n2 }); + const direct = otherMsgs.slice(oN).find(m => m.type === "step"); + let shownB = reconstruct(otherSteps, otherHead); + if (direct?.type === "step") shownB = applyChanges(shownB, direct.changes); + directOk = s1?.type === "step" && s2?.type === "step" && direct?.type === "step" + && mapsEqual(shownA, shownB) && mapsEqual(shownB, reconstruct(otherSteps, n2)); + if (!directOk) directDetail = !direct ? "no step" : !s1 || !s2 ? "path missing a step" : "shown state differs"; + const offA = yield* shownVs(path, reconstruct(pathSteps, n2), s2?.inexact ?? []); + const offB = yield* shownVs(other, reconstruct(otherSteps, n2), direct?.inexact ?? []); + if (directOk && ((offA && offA.length) || (offB && offB.length))) { + directOk = false; + directDetail = `the app shows another state: ${[...(offA ?? []), ...(offB ?? [])].slice(0, 2).join("; ")}`; + } + yield path.dispose?.(); + yield other.dispose?.(); + } catch (e) { directDetail = e?.message ?? String(e); } + push(directOk, "travel commutative", label, directDetail || undefined); + + // Viewing buffers live flushes; resume catches up; nothing is lost. + const viewTo = 1; + yield travelHost.post({ type: "travel", to: viewTo }); + const mark = travelMsgs.length; + yield travelHost.act(); + yield travelHost.tick(8); + const during = travelMsgs.slice(mark); + const leaked = during.some(m => m.type === "flush"); + const nResume = travelMsgs.length; + yield travelHost.post({ type: "resume" }); + const resumed = travelMsgs.slice(nResume).find(m => m.type === "resume" || m.type === "travel-denied"); + const nHello = travelMsgs.length; + yield travelHost.post({ type: "hello", want: ["timeline"] }); + const tl = travelMsgs.slice(nHello).find(m => m.type === "timeline"); + // Nothing done while viewing is lost: after resume the app shows the replay of the timeline at its head (an act() + // that ran beneath the view and whose step went missing shows in the app but not in the replay). + const liveOff = tl && resumed?.type === "resume" ? yield* shownVs(travelHost, reconstruct(tl.steps ?? [], resumed.head)) : null; + const kept = !leaked && tl && (tl.steps?.length ?? 0) >= stepsNow().length && (!liveOff || liveOff.length === 0); + push(kept, "flushes during viewing kept", label, leaked ? "a flush was shown while viewing" : !tl ? "no timeline after resume" + : liveOff?.length ? `work done while viewing is not in the timeline: ${liveOff.slice(0, 2).join("; ")}` : liveOff ? undefined : "host has no shown(): timeline length only"); + push(!liveOff || liveOff.length === 0, "app shows the live state after resume", label, + liveOff === null ? "host has no shown(): not checked" : liveOff.slice(0, 3).join("; ") || undefined); + + // Current state (v0.3, v0.4 per instance): a snapshot is what the app shows now, and agrees with the timeline at + // its head (the newest live instance of each key). + const nSnap = travelMsgs.length; + yield travelHost.post({ type: "snapshot?" }); + const snap = travelMsgs.slice(nSnap).find(m => m.type === "snapshot"); + if (!snap) push(false, "snapshot on request", label, "no snapshot for snapshot?"); + else { + push(true, "snapshot on request", label); + const snapStates = toStates(new Map((snap.values ?? []).map(v => [v.key, v]))); + const head = tl ? reconstruct(tl.steps ?? [], tl.head) : new Map(); + const stale = [...head].filter(([k, v]) => snapStates.get(k) !== v).map(([k, v]) => `${k}: snapshot ${fmtState(snapStates.get(k))}, timeline ${fmtState(v)}`); + push(stale.length === 0, "values per live instance: snapshot agrees with the timeline head", label, stale.slice(0, 3).join("; ") || undefined); + const snapOff = yield* shownVs(travelHost, snapStates); + push(!snapOff || snapOff.length === 0, "snapshot shows what the app shows", label, + snapOff === null ? "host has no shown(): not checked" : snapOff.slice(0, 3).join("; ") || undefined); + } + + let resumeOk = false, resumeDetail = ""; + if (resumed?.type === "resume" && tl) { + const viewed = reconstruct(tl.steps ?? [], viewTo); + const after = applyChanges(viewed, resumed.changes); + const live = reconstruct(tl.steps ?? [], resumed.head); + resumeOk = mapsEqual(after, live) && resumed.head === tl.head; + if (!resumeOk) resumeDetail = "resume changes do not reach live"; + } else resumeDetail = resumed ? resumed.type : "no resume"; + push(resumeOk, "resume matches live", label, resumeDetail || undefined); + yield travelHost.dispose?.(); + } + + // `step.inexact` (§4b): a list of graph keys when present. + const badInexact = [...msgs, ...(travelMsgs ?? [])].filter(m => m.type === "step" && m.inexact !== undefined) + .flatMap(m => Array.isArray(m.inexact) ? m.inexact.filter(k => !allKeys.has(k)) : ["not a list"]); + push(!badInexact.length, "step inexact keys exist", label, badInexact.slice(0, 3).join(", ") || undefined); + + // The v0.3–v0.7 messages, over every host's messages. + const every = everything.flat(); + { + const hello = msgs.findIndex(m => m.type === "timeline"), snapAt = msgs.findIndex(m => m.type === "snapshot"); + push(snapAt >= 0 && snapAt < hello, "snapshot answers hello, before timeline", label, snapAt < 0 ? "no snapshot" : snapAt > hello ? "after timeline" : undefined); + const bad = []; + const STATES = new Set(["ok", "fallback", "error"]); + for (const m of every.filter(m => m.type === "snapshot")) { + for (const v of m.values ?? []) { + if (!allKeys.has(v.key)) bad.push(`value key ${v.key}`); + if (v.preview !== undefined && (typeof v.preview !== "string" || v.preview.length > 80)) bad.push(`preview of ${v.key}`); + if (v.preview === undefined && v.error === undefined && !v.pending) bad.push(`${v.key} has no preview, error or pending`); + } + for (const f of m.flights ?? []) if (!allKeys.has(f.key) || typeof f.since !== "number") bad.push(`flight ${f.key}`); + for (const b of m.boundaries ?? []) if (typeof b.region !== "string" || !STATES.has(b.state)) bad.push(`boundary ${b.region} ${b.state}`); + for (const r of m.runs ?? []) if (!allKeys.has(r.key) || r.id === undefined) bad.push(`run ${r.key}`); + for (const h of m.held ?? []) if (!allKeys.has(h.key) || !Array.isArray(h.by)) bad.push(`held ${h.key}`); + if (!Array.isArray(m.values) || !Array.isArray(m.flights) || !Array.isArray(m.boundaries) || !Array.isArray(m.runs)) bad.push("a list is missing"); + } + push(bad.length === 0, "snapshot well formed", label, bad.slice(0, 3).join("; ") || undefined); + + const bounds = every.filter(m => m.type === "boundary"); + const badB = bounds.filter(b => typeof b.region !== "string" || !STATES.has(b.state) || (b.error !== undefined && b.state !== "error")); + push(badB.length === 0, "boundary messages well formed", label, badB.length ? JSON.stringify(badB[0]) : bounds.length ? undefined : "none seen"); + + for (const box of everything) { + const open = new Map(); + for (const m of box) { + if (m.type !== "run") continue; + if (!allKeys.has(m.key)) { bad.push(`run of unknown ${m.key}`); continue; } + if (m.state === "start") { if (open.has(m.id)) bad.push(`run ${m.id} started twice`); open.set(m.id, m.key); } + else if (m.state === "end" || m.state === "error") { if (!open.has(m.id)) bad.push(`run ${m.id} ${m.state} without start`); open.delete(m.id); } + else bad.push(`run state ${m.state}`); + } + } + const runs = every.filter(m => m.type === "run"); + push(!bad.some(b => b.startsWith("run")), "runs pair start with end or error", label, bad.filter(b => b.startsWith("run")).slice(0, 3).join("; ") || (runs.length ? undefined : "none seen")); + + const heldBad = []; + for (const box of everything) { + const held = new Set(); + for (const m of box) { + if (m.type === "held") { if (!allKeys.has(m.key) || !Array.isArray(m.by)) heldBad.push(`held ${m.key}`); held.add(m.key); } + else if (m.type === "released") { if (!held.has(m.key)) heldBad.push(`released ${m.key} without held`); held.delete(m.key); } + } + } + push(heldBad.length === 0, "held before released", label, heldBad.slice(0, 3).join("; ") || (every.some(m => m.type === "held") ? undefined : "none seen")); + + const reverts = every.filter(m => m.type === "revert"); + const badR = reverts.filter(m => !allKeys.has(m.key)); + push(badR.length === 0, "revert keys exist", label, badR.length ? badR[0].key : reverts.length ? undefined : "none seen"); + + // v0.4/v0.6: an error is a state of its own: a change carrying one has no preview + const both = every.filter(m => m.type === "flush" || m.type === "step" || m.type === "resume") + .flatMap(m => m.changes ?? []).filter(c => c.error !== undefined && c.preview !== undefined); + push(both.length === 0, "an error change carries no preview", label, both.length ? both[0].key : undefined); + + } + + // Eviction: a small ring drops early seqs. + try { + const small = yield makeHost(graph, { seed, rate: 0, capacity: 3 }); + const box = []; + small.subscribe(m => box.push(m)); + let guard = 0; + while (box.filter(m => m.type === "flush").length < 6 && guard++ < 40) { + yield small.act(); + yield small.tick(6); + } + // settle flights so travel isn't pending + yield small.tick(12); + const got = box.filter(m => m.type === "flush").length; + const n = box.length; + yield small.post({ type: "travel", to: 1 }); + const denied = box.slice(n).find(m => m.type === "travel-denied" || m.type === "step"); + if (got >= 6) { + const ok = denied?.type === "travel-denied" && denied.reason === "evicted"; + push(ok, "travel evicted outside capacity", label, ok ? undefined : `got ${denied?.type ?? "nothing"} ${denied?.reason ?? ""} after ${got} flushes`); + } else push(true, "travel evicted outside capacity", label, `only ${got} flushes, skipped`); + yield small.dispose?.(); + } catch (e) { + push(false, "travel evicted outside capacity", label, e?.message ?? String(e)); + } + + // HMR plan. + try { + const h = yield makeHost(graph, hostOpts); + const box = []; + h.subscribe(m => box.push(m)); + yield h.post({ type: "hello", want: ["hmr"] }); + yield h.tick(4); + const module = graph.modules?.[0]; + yield h.editModule(module); + const planMsg = box.find(m => m.type === "hmr" && m.phase === "plan"); + const doneMsg = box.find(m => m.type === "hmr" && m.phase === "done"); + const failed = box.find(m => m.type === "hmr" && m.phase === "failed"); + if (!planMsg) { + push(false, "hmr partition", label, failed ? `failed: ${failed.error}` : "no plan"); + push(false, "hmr reasons cover plan", label, "no plan"); + push(false, "hmr done changes subset", label, "no done"); + } else { + const errors = partitionErrors(planMsg.plan, graph, planMsg.graph ?? graph); + const part = errors.filter(e => !e.startsWith("no reason") && !e.startsWith("reason for") && !e.includes("has reason") && !e.includes("but reason is")); + const reasons = errors.filter(e => e.startsWith("no reason") || e.startsWith("reason for") || e.includes("not a known code")); + push(part.length === 0, "hmr partition", label, part.slice(0, 3).join("; ") || undefined); + push(reasons.length === 0 && errors.filter(e => e.includes("but reason is") || e.includes("has reason")).length === 0, "hmr reasons cover plan", label, [...reasons, ...errors.filter(e => e.includes("reason"))].slice(0, 3).join("; ") || undefined); + const allow = new Set([...(planMsg.plan.rerun ?? []), ...(planMsg.plan.reset ?? []), ...(planMsg.plan.added ?? [])]); + const bad = (doneMsg?.changes ?? []).filter(c => c.key != null && !allow.has(c.key)).map(c => c.key); + push(!!doneMsg && bad.length === 0, "hmr done changes subset", label, !doneMsg ? "no done" : bad.length ? bad.join(", ") : undefined); + // v0.7: keys whose state could not be carried come with fallback "refresh", and exist + const known = new Set([...keysOf(graph), ...keysOf(planMsg.graph ?? graph)]); + const unc = doneMsg?.uncarried; + const uncOk = !doneMsg || (unc === undefined ? doneMsg.fallback !== "refresh" + : Array.isArray(unc) && doneMsg.fallback === "refresh" && unc.every(k => known.has(k))); + push(uncOk, "hmr uncarried keys reported with refresh", label, uncOk ? (unc ? undefined : "none uncarried") : JSON.stringify({ fallback: doneMsg.fallback, uncarried: unc })); + } + yield h.dispose?.(); + } catch (e) { + push(false, "hmr partition", label, e?.message ?? String(e)); + } + + yield host.dispose?.(); +} diff --git a/tooling/rx-map/diff.mjs b/tooling/rx-map/diff.mjs new file mode 100644 index 000000000..8ad497f61 --- /dev/null +++ b/tooling/rx-map/diff.mjs @@ -0,0 +1,183 @@ +// Two versions of one program as one map: every node and edge of both, each marked same, added, removed or changed, and +// a summary that leads with what changes behaviour (what an action can now reach, what became async or touches the +// world) rather than with how many lines moved. +import { addKeys } from "./graph.mjs"; + +const PROPS = ["kind", "async", "io", "question", "flavor", "world"]; + +export function diffGraphs(A, B) { + if (!A.nodes.every(n => n.key)) addKeys(A); + if (!B.nodes.every(n => n.key)) addKeys(B); + + // ---- modules: the after side's order, then any module only the before side has + const modules = [...B.modules]; + const modA = A.modules.map(m => { const i = modules.indexOf(m); return i >= 0 ? i : modules.push(m) - 1; }); + + // ---- regions by key + const regB = new Map(B.regions.map(r => [r.key, r])); + const regMap = new Map(); // A region id → union region id + for (const r of A.regions) regMap.set(r.id, regB.get(r.key)?.id ?? `a:${r.id}`); + const regKeysA = new Set(A.regions.map(r => r.key)); + const regA = new Map(A.regions.map(r => [r.key, r])); + const outlineText = r => JSON.stringify(r.outline?.filter(p => "text" in p).map(p => [p.attr ?? "", p.text])); + const regions = B.regions.map(r => { + const old = regA.get(r.key); + const textChanged = old?.outline && r.outline && outlineText(old) !== outlineText(r); + return { ...r, status: textChanged ? "changed" : regKeysA.has(r.key) ? "same" : "added", ...(textChanged ? { reason: "text changed" } : {}) }; + }); + for (const r of A.regions) if (!regB.has(r.key)) regions.push({ ...r, id: `a:${r.id}`, mod: modA[r.mod], parent: r.parent == null ? null : regMap.get(r.parent), status: "removed" }); + + // ---- nodes: named ones by key; sites by place, then by what they read, then in line order + const match = new Map(); // A node id → B node id + const bByKey = new Map(B.nodes.filter(n => !n.site).map(n => [n.key, n])); + for (const a of A.nodes) if (!a.site && bByKey.has(a.key)) match.set(a.id, bByKey.get(a.key).id); + const group = (g) => { const m = new Map(); for (const n of g.nodes) if (n.site) (m.get(n.base) ?? m.set(n.base, []).get(n.base)).push(n); return m; }; + const sitesA = group(A), sitesB = group(B); + for (const [base, as] of sitesA) { + const bs = (sitesB.get(base) ?? []).slice(); + const left = []; + for (const a of as) { const i = bs.findIndex(b => b.sig === a.sig); if (i >= 0) match.set(a.id, bs.splice(i, 1)[0].id); else left.push(a); } + left.sort((x, y) => x.line - y.line); bs.sort((x, y) => x.line - y.line); + left.forEach((a, i) => { if (bs[i]) match.set(a.id, bs[i].id); }); + } + const back = new Map([...match].map(([a, b]) => [b, a])); + for (const r of regions) if (r.status === "removed" && r.outline) { + r.outline = r.outline.map(p => "region" in p ? { ...p, region: regMap.get(p.region) } + : "site" in p ? { ...p, site: match.get(p.site) ?? `a:${p.site}` } : p); + } + const nodeA = new Map(A.nodes.map(n => [n.id, n])); + const textA = n => A.lines[n.file]?.[n.line]?.trim() ?? ""; + const textB = n => B.lines[n.file]?.[n.line]?.trim() ?? ""; + + const nodes = B.nodes.map(n => { + const aId = back.get(n.id); + if (!aId) return { ...n, status: "added" }; + const a = nodeA.get(aId); + const was = {}; + for (const p of PROPS) if ((a[p] ?? false) !== (n[p] ?? false)) was[p] = a[p] ?? false; + const before = { line: a.line, text: textA(a) }; + const edited = before.text !== textB(n); + return { ...n, status: Object.keys(was).length ? "changed" : "same", was, before, edited }; + }); + const uid = id => match.get(id) ?? (regMap.has(id) ? regMap.get(id) : `a:${id}`); + for (const a of A.nodes) if (!match.has(a.id)) { + nodes.push({ ...a, id: `a:${a.id}`, mod: modA[a.mod], region: regMap.get(a.region) ?? a.region, status: "removed", before: { line: a.line, text: textA(a) } }); + } + + // ---- edges + const ek = e => [e.from, e.to, e.type, e.mode ?? "", e.probe ?? "", e.op ?? "", e.field ?? "", e.path ? 1 : 0].join("|"); + const loose = e => [e.from, e.to, e.type, e.field ?? ""].join("|"); + const eA = A.edges.map(e => ({ ...e, from: uid(e.from), to: uid(e.to) })); + const aExact = new Map(), aLoose = new Map(); + for (const e of eA) { aExact.set(ek(e), e); (aLoose.get(loose(e)) ?? aLoose.set(loose(e), []).get(loose(e))).push(e); } + const used = new Set(); + const edges = []; + const pending = []; + for (const e of B.edges) { + const a = aExact.get(ek(e)); + if (a && !used.has(a)) { used.add(a); edges.push({ ...e, status: "same" }); } else pending.push(e); + } + for (const e of pending) { + const a = (aLoose.get(loose(e)) ?? []).find(x => !used.has(x)); + if (a) { used.add(a); edges.push({ ...e, status: "changed", was: { mode: a.mode, probe: a.probe, op: a.op, path: a.path } }); } + else edges.push({ ...e, status: "added" }); + } + for (const e of eA) if (!used.has(e)) edges.push({ ...e, status: "removed" }); + + const union = { + modules, absModules: B.absModules, nodes, edges, regions, lines: B.lines, linesBefore: A.lines, + diff: { before: A.label ?? "before", after: B.label ?? "after" }, + }; + union.diff.summary = summarize(A, B, union, match); + return union; +} + +// ---- summary ------------------------------------------------------------------------------------------------------- +const NOUN = { source: "source", eq: "equation", action: "action", fn: "function", server: "server function", context: "context", + errclass: "error class", comp: "component", import: "JS import", props: "props", handler: "handler", reader: "view read", + effect: "effect", prop: "prop", provide: "provide" }; +const opWord = { write: ":=", optimistic: "guess", refresh: "refresh", affects: "affects", provide: "provide" }; +const readWord = e => e.probe ? (e.probe === "pending" ? "pending?" : e.probe) : e.mode; + +/** + * What a change at `id` can reach. The action itself (and what it calls) writes and calls; data reached that way + * travels on only by tracked reads and props. An equation's own calls are how it computes, not part of the change. + */ +export function reach(g, id) { + const out = new Map(); + for (const e of g.edges) (out.get(e.from) ?? out.set(e.from, []).get(e.from)).push(e); + const seen = new Set([id]), imp = new Set([id]), todo = [[id, true]]; + while (todo.length) { + const [x, imperative] = todo.pop(); + for (const e of out.get(x) ?? []) { + const data = e.type === "passes" || e.type === "renders" || (e.type === "read" && (e.mode === "tracked" || e.probe)); + const act = imperative && (e.type === "write" || e.type === "call"); + if (!data && !act) continue; + const nextImp = e.type === "call"; + if (!seen.has(e.to) || (nextImp && !imp.has(e.to))) { seen.add(e.to); if (nextImp) imp.add(e.to); todo.push([e.to, nextImp]); } + } + } + seen.delete(id); + return seen; +} + +function summarize(A, B, U, match) { + const items = []; + const byId = new Map(U.nodes.map(n => [n.id, n])); + const name = id => { const n = byId.get(id); return n ? (n.site ? `${n.name} (L${n.line})` : n.name) : id; }; + const add = (weight, text, ids) => items.push({ weight, text, ids }); + + // what each action or handler can reach, before and after, compared by key + const nodeB = new Map(B.nodes.map(n => [n.id, n])), nodeA = new Map(A.nodes.map(n => [n.id, n])); + for (const [aId, bId] of match) { + const n = nodeB.get(bId); + if (!(n.kind === "action" || n.kind === "handler")) continue; + // a handler that only calls an action says nothing the action's own line does not + if (n.kind === "handler" && !U.edges.some(e => e.from === bId && e.status !== "same")) continue; + const before = new Set([...reach(A, aId)].map(x => nodeA.get(x)?.key).filter(Boolean)); + const after = new Set([...reach(B, bId)].map(x => nodeB.get(x)?.key).filter(Boolean)); + const keyName = k => { const m = B.nodes.find(x => x.key === k) ?? A.nodes.find(x => x.key === k); return m && !m.site ? m.name : null; }; + const gained = [...after].filter(k => !before.has(k)).map(keyName).filter(Boolean); + const lost = [...before].filter(k => !after.has(k)).map(keyName).filter(Boolean); + if (gained.length || lost.length) { + const who = n.kind === "action" ? `\`${n.name}\`` : `${n.name} (L${n.line})`; + add(n.kind === "action" ? 0 : 1, + `${who} now reaches ${[...gained.map(x => `+\`${x}\``), ...lost.map(x => `−\`${x}\``)].join(" ")}`, [bId]); + } + } + + for (const n of U.nodes) { + if (n.status === "changed") { + const bits = []; + if ("kind" in n.was) bits.push(`was ${NOUN[n.was.kind] ?? n.was.kind}, now ${NOUN[n.kind] ?? n.kind}`); + if ("async" in n.was) bits.push(n.async ? "became async: can be pending, a reader under no `loading` holds the page" : "no longer async"); + if ("io" in n.was) bits.push(n.io ? "now touches the world (io)" : "no longer touches the world"); + if ("question" in n.was) bits.push(n.question ? "now a source with a standing question" : "no longer re-asks"); + if (bits.length) add(1, `\`${n.name}\` ${bits.join("; ")}`, [n.id]); + } + if ((n.status === "added" || n.status === "removed") && !n.site) + add(2, `${n.status === "added" ? "added" : "removed"} ${NOUN[n.kind] ?? n.kind} \`${n.name}\``, [n.id]); + } + + for (const e of U.edges) { + const from = byId.get(e.from), to = byId.get(e.to); + if (!from || !to || e.status === "same") continue; + const gone = x => x.status === "added" || x.status === "removed"; + // an edge of a node that is itself new or gone is said by that node's own item + if (e.type === "write" && gone(from)) continue; + if (e.type === "call" && (gone(from) || to.status === "removed")) continue; + if (e.type === "read" && gone(to)) continue; + const sym = s => (s === "added" ? "now" : s === "removed" ? "no longer" : ""); + if (e.type === "write") { + if (e.status === "changed") add(1, `\`${name(e.from)}\` writes \`${name(e.to)}\` with ${opWord[e.op] ?? e.op} (was ${opWord[e.was.op] ?? e.was.op})`, [e.from, e.to]); + else add(1, `\`${name(e.from)}\` ${sym(e.status)} ${e.op === "optimistic" ? "guesses" : e.op === "refresh" ? "refreshes" : e.op === "affects" ? "affects" : "writes"} \`${name(e.to)}\``, [e.from, e.to]); + } else if (e.type === "call" && (to.io || to.kind === "server" || (to.world && e.status === "added"))) { + add(1, `\`${name(e.from)}\` ${sym(e.status)} calls \`${name(e.to)}\`${to.io ? " (io)" : ""}`, [e.from, e.to]); + } else if (e.type === "read") { + if (e.status === "changed") add(2, `\`${name(e.to)}\` reads \`${name(e.from)}\` as ${readWord(e)} (was ${readWord(e.was)})`, [e.from, e.to]); + else if (!to.site || from.async || gone(from)) add(3, `\`${name(e.to)}\` ${sym(e.status)} reads \`${name(e.from)}\`${from.async ? " (can be pending)" : ""}`, [e.from, e.to]); + } + } + const seen = new Set(); + return items.sort((a, b) => a.weight - b.weight).filter(i => (seen.has(i.text) ? false : (seen.add(i.text), true))); +} diff --git a/tooling/rx-map/fake.mjs b/tooling/rx-map/fake.mjs new file mode 100644 index 000000000..c853bc188 --- /dev/null +++ b/tooling/rx-map/fake.mjs @@ -0,0 +1,1483 @@ +// Fake host for the trace protocol (TRACE-CONTRACT §4). Deterministic from `seed`. Speaks the same messages the +// real `./live` bridge will, so the map, the conformance suite and a recording can all sit on one contract. +// Pure ESM, no dependencies, Node and the browser. The CLI at the bottom is Node-only and loaded on demand. +import { declText, keyParts, parseDecl, planHmr } from "./hmr.mjs"; + +const SOURCE = "rx-map"; +const V = 1; + +function mulberry32(seed) { + let a = seed >>> 0; + return function rng() { + a |= 0; + a = a + 0x6D2B79F5 | 0; + let t = Math.imul(a ^ a >>> 15, 1 | a); + t = t + Math.imul(t ^ t >>> 7, 61 | t) ^ t; + return ((t ^ t >>> 14) >>> 0) / 4294967296; + }; +} + +function hash(s) { + let h = 2166136261; + const str = String(s); + for (let i = 0; i < str.length; i++) h = Math.imul(h ^ str.charCodeAt(i), 16777619); + return h >>> 0; +} + +/** A short string of a value, at most 80 characters. Same shape as `@reactivescript/map/live`'s preview. */ +export function preview(v) { + let s; + try { s = show(v, 2); } catch { s = "?"; } + return s.length > 80 ? s.slice(0, 79) + "…" : s; +} +function show(v, depth) { + switch (typeof v) { + case "string": return JSON.stringify(v.length > 60 ? v.slice(0, 60) + "…" : v); + case "undefined": return "undefined"; + case "function": return `ƒ ${v.name || "anonymous"}`; + case "bigint": return `${v}n`; + case "symbol": return v.toString(); + case "object": break; + default: return String(v); + } + if (v === null) return "null"; + if (v instanceof Date) return Number.isNaN(v.getTime()) ? "Invalid Date" : v.toISOString(); + if (v instanceof Error) return `${v.name}: ${v.message}`; + if (typeof v.then === "function") return "Promise"; + const arr = Array.isArray(v); + if (depth <= 0) return arr ? `Array(${v.length})` : "{…}"; + let out = arr ? "[" : "{", n = 0; + const keys = arr ? null : Object.keys(v); + const len = arr ? v.length : keys.length; + for (; n < len && out.length < 80; n++) out += (n ? ", " : "") + (arr ? "" : `${keys[n]}: `) + show(arr ? v[n] : v[keys[n]], depth - 1); + if (n < len) out += `, …${len - n}`; + return out + (arr ? "]" : "}"); +} + +// ---- a small expression evaluator ------------------------------------------------------------------------------- +// Enough of RX's expression language that writes and equations in the examples come out as real values: literals, +// arithmetic, comparisons, ternary, templates, calls like `len`, member access, arrows, map/filter/reduce, `pending?` +// and `latest`. Anything else fails and the host invents a typed preview instead. + +class Flight extends Error {} +class Fail extends Error {} + +function evaluate(expr, ctx) { + try { + const src = String(expr ?? "").replace(/\/\/.*$/gm, "").trim(); + if (!src) throw new Fail(); + const p = new Parser(src, ctx); + const value = p.parseExpr(); + p.skip(); + if (p.i < p.s.length) throw new Fail(); + return { ok: true, value }; + } catch (e) { + if (e instanceof Flight) return { ok: false, flight: true }; + return { ok: false }; + } +} + +class Parser { + constructor(s, ctx) { this.s = s; this.i = 0; this.ctx = ctx; } + skip() { while (this.i < this.s.length && /\s/.test(this.s[this.i])) this.i++; } + peek() { return this.s[this.i]; } + starts(w) { return this.s.startsWith(w, this.i); } + identChar(c) { return c != null && /[A-Za-z0-9_$]/.test(c); } + eat(w) { + this.skip(); + if (!this.starts(w)) return false; + const next = this.s[this.i + w.length]; + if (this.identChar(w[w.length - 1]) && this.identChar(next)) return false; + this.i += w.length; + return true; + } + parseExpr() { + const c = this.parseOr(); + this.skip(); + // Only the taken branch runs, so `cond ? await x : null` does not open a flight when cond is false. + if (this.peek() === "?" && this.s[this.i + 1] !== "." && this.s[this.i + 1] !== "?") { + this.i++; + const truth = this.cutBranch(); + if (!this.eat(":")) throw new Fail(); + const falsy = this.cutBranch(); + const v = evaluate(c ? truth : falsy, this.ctx); + if (v.flight) throw new Flight(); + if (!v.ok) throw new Fail(); + return v.value; + } + return c; + } + /** One ternary branch: stop at the matching `:`, or at a comma / closer, nesting counted. */ + cutBranch() { + const start = this.i; + let depth = 0, tern = 0, quote = null; + for (let i = this.i; i < this.s.length; i++) { + const c = this.s[i]; + if (quote) { + if (c === "\\") { i++; continue; } + if (c === quote) quote = null; + continue; + } + if (c === '"' || c === "'" || c === "`") { quote = c; continue; } + if (c === "(" || c === "[" || c === "{") depth++; + else if (c === ")" || c === "]" || c === "}") { + if (depth === 0) { this.i = i; return this.s.slice(start, i).trim(); } + depth--; + } else if (depth === 0 && (c === "," || c === ";")) { + this.i = i; + return this.s.slice(start, i).trim(); + } else if (depth === 0 && c === "?" && this.s[i + 1] !== "." && this.s[i + 1] !== "?") tern++; + else if (depth === 0 && c === ":" && this.s[i + 1] !== "=") { + if (tern > 0) tern--; + else { this.i = i; return this.s.slice(start, i).trim(); } + } + } + this.i = this.s.length; + return this.s.slice(start).trim(); + } + parseOr() { + let v = this.parseAnd(); + while (this.eat("||")) { const r = this.parseAnd(); v = v || r; } + return v; + } + parseAnd() { + let v = this.parseCmp(); + while (this.eat("&&")) { const r = this.parseCmp(); v = v && r; } + return v; + } + parseCmp() { + let v = this.parseSum(); + for (;;) { + let op = null; + if (this.eat("===")) op = "==="; + else if (this.eat("!==")) op = "!=="; + else if (this.eat("==")) op = "=="; + else if (this.eat("!=")) op = "!="; + else if (this.eat("<=")) op = "<="; + else if (this.eat(">=")) op = ">="; + else if (this.eat("<")) op = "<"; + else if (this.eat(">")) op = ">"; + else break; + const r = this.parseSum(); + if (op === "===" || op === "==") v = v === r; + else if (op === "!==" || op === "!=") v = v !== r; + else if (op === "<") v = v < r; + else if (op === "<=") v = v <= r; + else if (op === ">") v = v > r; + else v = v >= r; + } + return v; + } + parseSum() { + let v = this.parseProd(); + for (;;) { + let op = null; + if (this.eat("+")) op = "+"; + else if (this.eat("-")) op = "-"; + else break; + const r = this.parseProd(); + v = op === "+" ? v + r : v - r; + } + return v; + } + parseProd() { + let v = this.parseUnary(); + for (;;) { + let op = null; + if (this.eat("*")) op = "*"; + else if (this.eat("/")) op = "/"; + else if (this.eat("%")) op = "%"; + else break; + const r = this.parseUnary(); + v = op === "*" ? v * r : op === "/" ? (r === 0 ? 0 : v / r) : (r === 0 ? 0 : v % r); + } + return v; + } + parseUnary() { + this.skip(); + if (this.eat("!")) return !this.parseUnary(); + if (this.eat("typeof")) return typeof this.parseUnary(); + if (this.peek() === "-" && this.s[this.i + 1] !== "=" && this.s[this.i + 1] !== ">") { this.i++; return -this.parseUnary(); } + if (this.eat("await")) { + if (this.ctx.mode !== "land") throw new Flight(); + this.skip(); + const body = this.sliceBody(); + this.i += body.length; + return this.ctx.awaitValue(body); + } + return this.parsePostfix(); + } + parsePostfix() { + let v = this.parsePrimary(); + for (;;) { + this.skip(); + if (this.eat("?.")) { + const name = this.parseIdent(); + this.skip(); + if (v == null) { if (this.peek() === "(") { this.i++; this.parseArgs(); } continue; } + if (this.peek() === "(") { this.i++; v = this.callMethod(v, name, this.parseArgs()); } + else v = v[name]; + } else if (this.eat(".")) { + const name = this.parseIdent(); + this.skip(); + if (this.peek() === "(") { this.i++; v = this.callMethod(v, name, this.parseArgs()); } + else if (name === "length") v = v == null ? 0 : v.length ?? 0; + else if (v != null && typeof v === "object") v = v[name]; + else throw new Fail(); + } else if (this.peek() === "(" && typeof v === "function") { + this.i++; + v = v(...this.parseArgs()); + } else if (this.peek() === "[") { + this.i++; + const k = this.parseExpr(); + if (!this.eat("]")) throw new Fail(); + v = v == null ? undefined : v[k]; + } else break; + } + return v; + } + parsePrimary() { + this.skip(); + const c = this.peek(); + if (c == null) throw new Fail(); + if (this.eat("(")) { + if (this.looksLikeParams()) return this.finishArrow(this.takeParams()); + const v = this.parseExpr(); + if (!this.eat(")")) throw new Fail(); + return v; + } + if (c === '"' || c === "'") return this.parseString(); + if (c === "`") return this.parseTemplate(); + if (c === "[") return this.parseArray(); + if (c === "{") return this.parseObject(); + if (c >= "0" && c <= "9") return this.parseNumber(); + if (this.eat("true")) return true; + if (this.eat("false")) return false; + if (this.eat("null")) return null; + if (this.eat("undefined")) return undefined; + if (this.starts("pending?") && !this.identChar(this.s[this.i + 8])) { + this.i += 8; + this.skip(); + return this.ctx.pending(this.parseIdent()); + } + if (this.eat("latest")) return this.ctx.get(this.parseIdent()); + if (this.identChar(c) && /[A-Za-z_$]/.test(c)) { + const name = this.parseIdent(); + this.skip(); + if (this.eat("=>")) return this.finishArrow([name]); + if (this.peek() === "(") { this.i++; return this.callNamed(name, this.parseArgs()); } + return this.ctx.get(name); + } + throw new Fail(); + } + parseIdent() { + this.skip(); + const start = this.i; + if (!/[A-Za-z_$]/.test(this.peek() ?? "")) throw new Fail(); + this.i++; + while (this.identChar(this.peek())) this.i++; + return this.s.slice(start, this.i); + } + parseNumber() { + const start = this.i; + while (/[0-9.]/.test(this.peek() ?? "")) this.i++; + const n = Number(this.s.slice(start, this.i)); + if (Number.isNaN(n)) throw new Fail(); + return n; + } + parseString() { + const q = this.s[this.i++]; + let out = ""; + while (this.i < this.s.length && this.s[this.i] !== q) { + if (this.s[this.i] === "\\") { out += this.s[this.i + 1] ?? ""; this.i += 2; continue; } + out += this.s[this.i++]; + } + if (this.s[this.i] !== q) throw new Fail(); + this.i++; + return out; + } + parseTemplate() { + this.i++; + let out = ""; + while (this.i < this.s.length && this.s[this.i] !== "`") { + if (this.s[this.i] === "$" && this.s[this.i + 1] === "{") { + this.i += 2; + const v = this.parseExpr(); + if (!this.eat("}")) throw new Fail(); + out += v == null ? "" : String(v); + } else if (this.s[this.i] === "\\") { out += this.s[this.i + 1] ?? ""; this.i += 2; } + else out += this.s[this.i++]; + } + if (this.s[this.i] !== "`") throw new Fail(); + this.i++; + return out; + } + parseArray() { + this.i++; + const out = []; + for (;;) { + this.skip(); + if (this.peek() === "]") { this.i++; break; } + if (this.eat("...")) { + const v = this.parseOr(); + if (!Array.isArray(v)) throw new Fail(); + out.push(...v); + } else out.push(this.parseExpr()); + this.skip(); + if (this.peek() === ",") this.i++; + } + return out; + } + parseObject() { + this.i++; + const out = {}; + for (;;) { + this.skip(); + if (this.peek() === "}") { this.i++; break; } + if (this.eat("...")) { + const v = this.parseExpr(); + if (v == null || typeof v !== "object") throw new Fail(); + Object.assign(out, v); + } else if (this.peek() === '"' || this.peek() === "'") { + const k = this.parseString(); + if (!this.eat(":")) throw new Fail(); + out[k] = this.parseExpr(); + } else { + const k = this.parseIdent(); + if (this.eat(":")) out[k] = this.parseExpr(); + else out[k] = this.ctx.get(k); + } + this.skip(); + if (this.peek() === ",") this.i++; + } + return out; + } + parseArgs() { + const args = []; + for (;;) { + this.skip(); + if (this.peek() === ")") { this.i++; break; } + args.push(this.parseExpr()); + this.skip(); + if (this.peek() === ",") this.i++; + } + return args; + } + looksLikeParams() { + const save = this.i; + try { + this.takeParams(); + this.skip(); + const ok = this.starts("=>"); + this.i = save; + return ok; + } catch { this.i = save; return false; } + } + takeParams() { + const params = []; + for (;;) { + this.skip(); + if (this.peek() === ")") { this.i++; break; } + if (!/[A-Za-z_$]/.test(this.peek() ?? "")) throw new Fail(); + params.push(this.parseIdent()); + this.skip(); + if (this.peek() === ":") { this.i++; this.skipType(); this.skip(); } + if (this.peek() === ",") { this.i++; continue; } + if (this.peek() === ")") { this.i++; break; } + throw new Fail(); + } + return params; + } + skipType() { + let depth = 0; + while (this.i < this.s.length) { + const c = this.s[this.i]; + if (depth === 0 && (c === "," || c === ")" || c === "=")) break; + if (c === "(" || c === "[" || c === "{") depth++; + else if (c === ")" || c === "]" || c === "}") { if (depth === 0) break; depth--; } + this.i++; + } + } + finishArrow(params) { + this.skip(); + const body = this.sliceBody(); + this.i += body.length; + const ctx = this.ctx; + return (...args) => { + const env = new Map(params.map((p, i) => [p, args[i]])); + const v = evaluate(body, ctx.withEnv(env)); + if (v.flight) throw new Flight(); + if (!v.ok) throw new Fail(); + return v.value; + }; + } + /** Body of an arrow or an `await`, cut at a comma or closer that isn't nested. */ + sliceBody() { + const start = this.i; + let depth = 0, quote = null; + for (let i = this.i; i < this.s.length; i++) { + const c = this.s[i]; + if (quote) { + if (c === "\\") { i++; continue; } + if (c === quote) quote = null; + continue; + } + if (c === '"' || c === "'" || c === "`") { quote = c; continue; } + if (c === "(" || c === "[" || c === "{") depth++; + else if (c === ")" || c === "]" || c === "}") { if (depth === 0) return this.s.slice(start, i); depth--; } + else if (depth === 0 && (c === "," || c === ";")) return this.s.slice(start, i); + } + return this.s.slice(start); + } + callNamed(name, args) { + if (name === "len" || name === "length") return args[0] == null ? 0 : (args[0].length ?? 0); + if (name === "peek") return args[0]; + if (name === "str" || name === "String") return args[0] == null ? "" : String(args[0]); + if (this.ctx.mode === "land") return this.ctx.awaitValue(name); + throw new Fail(); + } + callMethod(recv, name, args) { + if (typeof recv === "string" && typeof String.prototype[name] === "function" && name !== "constructor") { + return recv[name](...args); + } + if (!Array.isArray(recv)) throw new Fail(); + const fn = args[0]; + if (name === "map") return recv.map((x, i) => (typeof fn === "function" ? fn(x, i) : x)); + if (name === "filter") return recv.filter((x, i) => (typeof fn === "function" ? fn(x, i) : true)); + if (name === "some") return recv.some((x, i) => (typeof fn === "function" ? fn(x, i) : false)); + if (name === "every") return recv.every((x, i) => (typeof fn === "function" ? fn(x, i) : false)); + if (name === "find") return recv.find((x, i) => (typeof fn === "function" ? fn(x, i) : false)) ?? null; + if (name === "findIndex") return recv.findIndex((x, i) => (typeof fn === "function" ? fn(x, i) : false)); + if (name === "reduce") return recv.reduce((a, x) => (typeof fn === "function" ? fn(a, x) : a), args[1]); + if (name === "slice") return recv.slice(args[0], args[1]); + if (name === "concat") return recv.concat(...args); + if (name === "includes") return recv.includes(args[0]); + throw new Fail(); + } +} + +// ---- values ------------------------------------------------------------------------------------------------------ + +const POOLS = { + query: ["", "a", "note", "rx", "hello"], + q: ["note", "a", "rx", "hello", ""], + search: ["", "a", "note", "rx"], + name: ["Ada", "Bea", "Cam", "Dee"], + title: ["Groceries", "Ideas", "Later", "Ship"], + body: ["hello", "more text", "ship it"], + saveError: ["", "could not save", "conflict"], + orderError: ["", "declined", "network"], + email: ["ada@ex.com", "bea@ex.com", "cam@ex.com"], + layout: ["wide", "narrow"], + filter: ["all", "active", "done"], +}; + +function poolFor(name) { + return POOLS[name] ?? POOLS[name?.replace(/Error$/, "") && name.endsWith("Error") ? "saveError" : ""] ?? ["", "updated", "next", "other"]; +} + +function splitUnion(t) { + const parts = []; + let depth = 0, cur = ""; + for (const c of t) { + if (c === "(" || c === "[" || c === "{") depth++; + else if (c === ")" || c === "]" || c === "}") depth--; + if (c === "|" && depth === 0) { parts.push(cur.trim()); cur = ""; } + else cur += c; + } + if (cur.trim()) parts.push(cur.trim()); + return parts; +} + +function loadAliases(graph) { + const map = new Map(); + for (const file of Object.keys(graph.lines ?? {})) { + const lines = graph.lines[file]; + const keys = Object.keys(lines).map(Number).filter(Number.isFinite).sort((a, b) => a - b); + for (let i = 0; i < keys.length; i++) { + const m = /^(?:export\s+)?type\s+(\w+)\s*=\s*(.*)$/.exec(String(lines[keys[i]]).trim()); + if (!m) continue; + let body = m[2]; + while (body.includes("{") && !body.includes("}") && i + 1 < keys.length) body += " " + String(lines[keys[++i]]).trim(); + map.set(m[1], body.trim()); + } + } + return map; +} + +function sampleOf(type, name, salt, aliases) { + let t = String(type ?? "").trim(); + if (aliases?.has(t)) t = aliases.get(t); + if (!t) return (poolFor(name)[salt % poolFor(name).length]) || "item"; + if (t === "number") return name === "id" ? 1 + (salt % 5) : 1 + (salt % 97); + if (t === "string") { + const pool = poolFor(name); + return pool[salt % pool.length] || `item ${salt % 9}`; + } + if (t === "boolean") return salt % 2 === 0; + if (t.endsWith("[]")) { + const elem = t.slice(0, -2).trim(); + const n = 1 + (salt % 3); + return Array.from({ length: n }, (_, i) => sampleOf(elem, name, salt + i + 1, aliases)); + } + if (t.startsWith("{")) return sampleObject(t, salt, aliases); + if ((t.startsWith('"') && t.endsWith('"')) || (t.startsWith("'") && t.endsWith("'"))) return t.slice(1, -1); + if (t.includes("|")) { + const parts = splitUnion(t).map(p => p.trim()).filter(p => p && p !== "null" && p !== t); + if (!parts.length) return null; + return sampleOf(parts[salt % parts.length], name, salt, aliases); + } + return (poolFor(name)[salt % poolFor(name).length]) || "value"; +} + +function sampleObject(type, salt, aliases) { + const body = type.replace(/^\{/, "").replace(/\}$/, ""); + const fields = []; + let depth = 0, cur = ""; + for (const c of body) { + if (c === "(" || c === "[" || c === "{") depth++; + else if (c === ")" || c === "]" || c === "}") depth--; + if (c === ";" && depth === 0 || c === "," && depth === 0) { if (cur.trim()) fields.push(cur.trim()); cur = ""; } + else cur += c; + } + if (cur.trim()) fields.push(cur.trim()); + const obj = {}; + fields.forEach((f, i) => { + const m = /^(\w+)\??\s*:\s*([\s\S]+)$/.exec(f); + if (!m) return; + obj[m[1]] = sampleOf(m[2].trim(), m[1], salt + i + 1, aliases); + }); + return obj; +} + +function zeroOf(type, name, aliases) { + const t = String(type ?? "").trim(); + if (!t) return null; + if (t === "number") return 0; + if (t === "string") return ""; + if (t === "boolean") return false; + if (t.endsWith("[]")) return []; + if (t.includes("null")) return null; + if (t.includes("|")) return zeroOf(splitUnion(t).find(p => p !== "null") ?? "", name, aliases); + if (t.startsWith("{") || aliases?.has(t)) return sampleOf(t, name, hash(name), aliases); + if ((t.startsWith('"') && t.endsWith('"')) || (t.startsWith("'") && t.endsWith("'"))) return t.slice(1, -1); + return null; +} + +function rhsExpr(node, graph) { + const parsed = parseDecl(node.kind, node.name, declText(graph, node)); + return String(parsed.rhs ?? "").replace(/\s+->[\s\S]*$/, "").trim(); +} + +function fallbackLiteral(rhs) { + const m = /->\s*([\s\S]+?)(?:\s+catch\b|$)/.exec(rhs ?? ""); + return m ? m[1].trim() : null; +} + +function nodeType(node, graph) { + if (node.type) return String(node.type); + return parseDecl(node.kind, node.name, declText(graph, node)).type; +} + +function isAsyncNode(node, graph) { + if (node.async) return true; + return /\bawait\b/.test(declText(graph, node)); +} + +function isQuestion(node, graph) { + return (node.kind === "source" || node.kind === "eq") && (node.question || node.async || /\bawait\b/.test(rhsExpr(node, graph))); +} + +// ---- host -------------------------------------------------------------------------------------------------------- + +function clone(v) { return v == null ? v : JSON.parse(JSON.stringify(v)); } + +/** + * @param {object} graph a `buildGraph` result (keys already applied) + * @param {{ seed?: number, rate?: number, capacity?: number, failRate?: number }} [opts] + * `rate` is ticks between automatic actions (default 0: only `act` fires one). `capacity` is the timeline + * ring (default 2000). Same seed and the same calls produce the same messages. + * @returns {{ post: Function, subscribe: Function, tick: Function, act: Function, editModule: Function, dispose: Function }} + */ +export function createFakeHost(graph, opts = {}) { + if (!graph || !Array.isArray(graph.nodes)) throw new TypeError("createFakeHost: expected a graph"); + const seed = opts.seed ?? 1; + const rate = opts.rate ?? 0; + const capacity = opts.capacity ?? 2000; + // v0.4: a share of answers fail (`failRate`, default 0, so seeds and the suite are unchanged): the node's flush change + // carries `error` and no `preview` + const failRate = opts.failRate ?? 0; + const rng = mulberry32(seed); + + let g = clone(graph); + let disposed = false; + let clock = 0; + let tickCount = 0; + let seq = 0; + let head = 0; + let floor = 0; + let viewing = null; + let selected = null; + let booted = false; + let editCount = 0; + let hmrN = 0; + let landN = 0; + let runN = 0; + + const subs = new Set(); + const values = new Map(); + const shown = new Map(); + const base = new Map(); + /** @type {object[]} */ + const steps = []; + /** @type {Map} */ + const inFlight = new Map(); + /** @type {{ landTick: number, writes: any[], refresh: any[], affects: any[], cause: string, origin: string }[]} */ + let holds = []; + + let byId = new Map(); + let byKey = new Map(); + let aliases = new Map(); + + const rebuild = () => { + byId = new Map(g.nodes.map(n => [n.id, n])); + byKey = new Map(g.nodes.filter(n => n.key).map(n => [n.key, n])); + aliases = loadAliases(g); + }; + rebuild(); + + const scopeOf = node => keyParts(node.key ?? "").scope; + const resolve = (name, from) => { + const all = g.nodes.filter(n => n.name === name && !n.site && n.key); + if (!all.length) return null; + if (!from) return all[0]; + const sameMod = all.filter(n => n.mod === from.mod); + return sameMod.find(n => scopeOf(n) === scopeOf(from)) + ?? sameMod.find(n => scopeOf(n) === "") + ?? sameMod[0] + ?? all[0]; + }; + + const makeCtx = (node, mode, env) => { + const ctx = { + mode, + withEnv(extra) { + const merged = new Map(env ?? []); + for (const [k, v] of extra) merged.set(k, v); + return makeCtx(node, mode, merged); + }, + get(name) { + if (env?.has(name)) return env.get(name); + const hit = resolve(name, node); + if (!hit || !values.has(hit.key)) throw new Fail(); + return values.get(hit.key); + }, + pending(name) { + const hit = resolve(name, node); + return !!(hit && inFlight.has(hit.key)); + }, + awaitValue(body) { + const hint = String(body ?? ""); + let type = node ? nodeType(node, g) : null; + if (!type) { + if (/getNote|\bNote\b/.test(hint)) type = "Note"; + else if (/fetchUsers|\bUser\b/.test(hint)) type = "User[]"; + else if (/loadTodos|\bTodo\b/.test(hint)) type = "Todo[]"; + else if (/fetchProducts|\bProduct\b/.test(hint)) type = "Product[]"; + else if (/listNotes/.test(hint)) type = "Note[]"; + } + const reads = node ? readPreviews(node) : []; + const salt = hash(`${node?.key ?? ""}:${reads.join("|")}:${hint}:${landN}`); + if (type) return sampleOf(type, node?.name ?? "value", salt, aliases); + if (node && /width|count|total|page|id|discount/.test(node.name)) return 800 + (salt % 400); + return sampleOf("string", node?.name ?? "value", salt, aliases); + }, + }; + return ctx; + }; + + function readPreviews(node) { + const out = []; + for (const e of g.edges) { + if (e.type !== "read" || e.to !== node.id) continue; + const s = byId.get(e.from); + if (s?.key && values.has(s.key)) out.push(preview(values.get(s.key))); + } + return out; + } + + function evalNode(node, mode) { + const expr = rhsExpr(node, g); + if (!expr) return { ok: false }; + return evaluate(expr, makeCtx(node, mode, null)); + } + + function initialOf(node) { + const text = declText(g, node); + const parsed = parseDecl(node.kind, node.name, text); + const fb = fallbackLiteral(parsed.rhs); + if (fb != null) { + const v = evaluate(fb, makeCtx(node, "sync", null)); + if (v.ok) return v.value; + } + if (node.kind === "source" && parsed.op === ":=") { + const v = evaluate(parsed.rhs, makeCtx(node, "sync", null)); + if (v.ok) return v.value; + } + if (parsed.rhs && !/\bawait\b/.test(parsed.rhs)) { + const v = evaluate(rhsExpr(node, g), makeCtx(node, "sync", null)); + if (v.ok) return v.value; + } + const type = parsed.type; + if (type) return zeroOf(type, node.name, aliases); + if (node.kind === "source" || node.kind === "eq") return null; + return undefined; + } + + function topo(list) { + const ids = new Set(list.map(n => n.id)); + const indeg = new Map(list.map(n => [n.id, 0])); + const kids = new Map(); + for (const n of list) { + for (const e of g.edges) { + if (e.type !== "read" || e.to !== n.id || e.probe || e.mode === "snapshot") continue; + if (!ids.has(e.from)) continue; + indeg.set(n.id, indeg.get(n.id) + 1); + (kids.get(e.from) ?? kids.set(e.from, []).get(e.from)).push(n.id); + } + } + const ready = list.filter(n => indeg.get(n.id) === 0).sort(byKeySort); + const out = []; + while (ready.length) { + ready.sort(byKeySort); + const n = ready.shift(); + out.push(n); + for (const id of kids.get(n.id) ?? []) { + indeg.set(id, indeg.get(id) - 1); + if (indeg.get(id) === 0) ready.push(byId.get(id)); + } + } + for (const n of list.slice().sort(byKeySort)) if (!out.includes(n)) out.push(n); + return out; + } + const byKeySort = (a, b) => (a?.key ?? "") < (b?.key ?? "") ? -1 : (a?.key ?? "") > (b?.key ?? "") ? 1 : 0; + + function initAll() { + for (const n of g.nodes) { + if (n.kind !== "source") continue; + const v = initialOf(n); + if (v !== undefined) values.set(n.key, v); + } + const eqs = g.nodes.filter(n => n.kind === "eq" || n.kind === "effect"); + for (const n of eqs) { + const parsed = parseDecl(n.kind, n.name, declText(g, n)); + const fb = fallbackLiteral(parsed.rhs); + if (fb != null) { + const v = evaluate(fb, makeCtx(n, "sync", null)); + if (v.ok) values.set(n.key, v.value); + } + } + for (const n of topo(eqs)) { + if (values.has(n.key) && isAsyncNode(n, g)) continue; + const v = evalNode(n, "sync"); + if (v.ok) values.set(n.key, v.value); + else if (!values.has(n.key)) { + const z = zeroOf(nodeType(n, g), n.name, aliases); + values.set(n.key, z === undefined ? null : z); + } + } + } + initAll(); + + function emit(msg) { + if (disposed) return; + const full = { source: SOURCE, v: V, ...msg }; + if (viewing != null && full.type === "flush") return; + for (const fn of subs) fn(full); + } + + function record(step) { + steps.push(step); + head = step.seq; + for (const c of step.changes) { + if (c.preview === undefined) shown.delete(c.key); + else shown.set(c.key, c.preview); + } + while (steps.length > capacity) { + const old = steps.shift(); + for (const c of old.changes) { + if (c.preview === undefined) base.delete(c.key); + else base.set(c.key, c.preview); + } + floor = old.seq; + } + } + + function valuesAt(seqN) { + // before a key's first recorded change, its value is that change's `prev` (TRACE-CONTRACT §4b) + const m = new Map(base), seen = new Set(base.keys()); + for (const s of steps) for (const c of s.changes) { + if (c.key == null || seen.has(c.key)) continue; + seen.add(c.key); + if (c.prev !== undefined) m.set(c.key, c.prev); + } + for (const s of steps) { + if (s.seq > seqN) break; + for (const c of s.changes) { + if (c.preview === undefined) m.delete(c.key); + else m.set(c.key, c.preview); + } + } + return m; + } + + function diffMaps(from, to) { + const keys = [...new Set([...from.keys(), ...to.keys()])].sort(); + const changes = []; + for (const key of keys) { + const hasA = from.has(key), hasB = to.has(key); + if (hasA && hasB && from.get(key) === to.get(key)) continue; + const node = byKeyGet(key); + const c = { key, name: node?.name ?? keyParts(key).name }; + if (hasA) c.prev = from.get(key); + if (hasB) c.preview = to.get(key); + changes.push(c); + } + return changes; + } + function byKeyGet(key) { return g.nodes.find(n => n.key === key) ?? null; } + + function commitFlush(changes, ctx) { + if (!changes.length) return; + seq += 1; + const step = { seq, at: clock, changes, order: changes.map(c => c.key) }; + if (ctx.origin) step.origin = ctx.origin; + if (ctx.cause) step.cause = ctx.cause; + record(step); + emit({ type: "flush", ...step }); + } + + function changeFor(node, prevInternal) { + const p = preview(values.get(node.key)); + if (prevInternal !== undefined && prevInternal === p) return null; + const shownP = shown.has(node.key) ? shown.get(node.key) : undefined; + if (shownP === p) return null; + const c = { key: node.key, name: node.name, preview: p }; + if (prevInternal !== undefined) c.prev = prevInternal; + return c; + } + + function assign(node, next) { + const prev = values.has(node.key) ? preview(values.get(node.key)) : undefined; + values.set(node.key, next); + return { node, prev }; + } + + function scheduleFlight(node, ctx) { + if (!node?.key) return; + if (inFlight.has(node.key)) { + emit({ type: "flight", key: node.key, state: "abandon", at: clock }); + inFlight.delete(node.key); + } + const delay = 2 + Math.floor(rng() * 3); + const abandon = rng() < 0.1; + inFlight.set(node.key, { node, landTick: tickCount + delay, abandon, cause: ctx.cause ?? node.key, origin: ctx.origin }); + // v0.9: what re-asked it (the change this propagation started from), and the interaction + const by = ctx.cause && ctx.cause !== node.key ? [{ key: ctx.cause, name: `rx:${ctx.cause}` }] : []; + emit({ type: "flight", key: node.key, state: "start", at: clock, ...(by.length ? { cause: by } : {}), ...(ctx.origin ? { origin: ctx.origin } : {}) }); + } + + function probeUpdates(nodes) { + const out = []; + const seen = new Set(); + for (const n of nodes) { + for (const e of g.edges) { + if (e.type !== "read" || !e.probe || e.from !== n.id) continue; + const r = byId.get(e.to); + if (!r || (r.kind !== "eq" && r.kind !== "effect") || seen.has(r.id)) continue; + seen.add(r.id); + const v = evalNode(r, "sync"); + if (!v.ok) continue; + out.push(assign(r, v.value)); + } + } + return out; + } + + function invent(node) { + const cur = values.get(node.key); + const type = nodeType(node, g); + const salt = hash(`${node.key}:${readPreviews(node).join("|")}:${tickCount}`); + if (typeof cur === "number") return cur + 1; + if (typeof cur === "string") { + const pool = poolFor(node.name); + const i = pool.indexOf(cur); + return i >= 0 ? pool[(i + 1) % pool.length] : pool[salt % pool.length]; + } + if (typeof cur === "boolean") return !cur; + if (Array.isArray(cur)) { + const elem = type?.replace(/\[\]\s*$/, "").trim(); + if (cur.length && salt % 5 === 0) return cur.slice(0, -1); + const item = elem ? sampleOf(elem, node.name, salt, aliases) : { id: cur.length + 1 }; + return [...cur, item]; + } + if (cur && typeof cur === "object") { + const copy = { ...cur }; + const keys = Object.keys(copy); + if (!keys.length) return copy; + const k = keys[salt % keys.length]; + if (typeof copy[k] === "number") copy[k] = copy[k] + 1; + else if (typeof copy[k] === "string") copy[k] = poolFor(k)[(salt + 1) % poolFor(k).length]; + else if (typeof copy[k] === "boolean") copy[k] = !copy[k]; + return copy; + } + if (type) return sampleOf(type, node.name, salt, aliases); + return sampleOf("string", node.name, salt, aliases); + } + + function propagateWithPrev(seeds, ctx, prevs) { + const prevMap = prevs ?? new Map(); + const written = new Set(seeds.map(n => n.id)); + const reach = new Set(); + const stack = [...seeds]; + while (stack.length) { + const n = stack.pop(); + for (const e of g.edges) { + if (e.type !== "read" || e.from !== n.id || e.probe || e.mode === "snapshot") continue; + const r = byId.get(e.to); + if (!r) continue; + const live = r.kind === "eq" || r.kind === "effect" || (r.kind === "source" && (r.question || r.async)); + if (!live || reach.has(r.id)) continue; + reach.add(r.id); + stack.push(r); + } + } + const ordered = topo([...reach].map(id => byId.get(id)).filter(Boolean)); + const assigned = []; + const started = []; + for (const n of ordered) { + if (written.has(n.id)) continue; + const asyncQ = isQuestion(n, g) && (n.async || /\bawait\b/.test(rhsExpr(n, g))); + if (asyncQ) { + const trial = evalNode(n, "sync"); + if (trial.ok && !trial.flight) { assigned.push(assign(n, trial.value)); continue; } + started.push(n); + continue; + } + const trial = evalNode(n, "sync"); + if (trial.flight) { started.push(n); continue; } + if (trial.ok) assigned.push(assign(n, trial.value)); + else assigned.push(assign(n, invent(n))); + } + for (const n of started) scheduleFlight(n, ctx); + const probes = probeUpdates([...seeds, ...started]); + const changes = []; + const seen = new Set(); + const push = (node, prev) => { + if (!node?.key || seen.has(node.key)) return; + seen.add(node.key); + const c = changeFor(node, prev); + if (!c) return; + if (ctx.origin) c.origin = ctx.origin; + changes.push(c); + }; + for (const n of seeds) push(n, prevMap.get(n.key)); + for (const a of [...assigned, ...probes]) push(a.node, a.prev); + commitFlush(changes, ctx); + } + + function scanExpr(text, start) { + let depth = 0, quote = null; + let i = start; + for (; i < text.length; i++) { + const c = text[i]; + if (quote) { + if (c === "\\") { i++; continue; } + if (c === quote) quote = null; + continue; + } + if (c === '"' || c === "'" || c === "`") { quote = c; continue; } + if (c === "(" || c === "[" || c === "{") depth++; + else if (c === ")" || c === "]" || c === "}") { if (depth > 0) depth--; } + else if (depth === 0 && (c === ";" || c === "\n")) break; + } + return trimExpr(text.slice(start, i)); + } + function extractAssign(text, name, guess) { + const re = guess + ? new RegExp(`guess\\s+${name}\\s*:=\\s*`) + : new RegExp(`(? xs.map(...)` is a functional write: apply it to the current value. + if (typeof v.value === "function") { + try { + const cur = node && values.has(node.key) ? values.get(node.key) : undefined; + return v.value(cur); + } catch { return null; } + } + return v.value; + } + function trimExpr(expr) { + let s = String(expr).trim().replace(/;+\s*$/, ""); + const balance = t => { + let d = 0; + for (const c of t) if (c === "{") d++; else if (c === "}") d--; + return d; + }; + while (s.endsWith("}") && balance(s) < 0) s = s.slice(0, -1).trim(); + return s; + } + + function parseParams(text) { + const m = /\(([^)]*)\)/.exec(String(text).split("\n")[0]); + if (!m || !m[1].trim()) return []; + return m[1].split(",").map(p => { + const [name, type] = p.split(":").map(s => s?.trim()); + return name ? { name, type: type ?? "" } : null; + }).filter(Boolean); + } + + function sampleArg(param) { + const name = param.name; + const type = param.type ?? ""; + const pool = poolFor(name); + if (name === "q" || name === "query") return pool[Math.floor(rng() * pool.length)]; + if (name === "name" || name === "title" || name === "body") return pool[Math.floor(rng() * pool.length)]; + if (name === "done" || type === "boolean") return rng() < 0.5; + if (type.includes("[]")) return []; + if (name === "id" || type.includes("number") || !type) return 1 + Math.floor(rng() * 5); + if (type.includes("string")) return pool[Math.floor(rng() * pool.length)] || "x"; + return 1 + Math.floor(rng() * 4); + } + + function fmtArg(v) { + if (typeof v === "string") return /^[\w ]*$/.test(v) ? v : JSON.stringify(v); + if (typeof v === "number" || typeof v === "boolean" || v == null) return String(v); + return preview(v); + } + + function runAction(action) { + const text = declText(g, action); + const params = parseParams(text); + const args = params.map(sampleArg); + const origin = `action ${action.name}(${args.map(fmtArg).join(", ")})`; + const argEnv = new Map(params.map((p, i) => [p.name, args[i]])); + const run = ++runN; + emit({ type: "run", key: action.key, id: run, state: "start", at: clock, args: preview(args) }); + const awaitAt = text.search(/\bawait\b/); + const edges = g.edges.filter(e => e.from === action.id && e.type === "write").slice().sort((a, b) => String(a.op).localeCompare(String(b.op))); + const sync = []; + const held = []; + const refreshNow = []; + const refreshHeld = []; + const affects = []; + for (const e of edges) { + const node = byId.get(e.to); + if (!node || node.kind !== "source") continue; + if (e.op === "refresh") { + const off = text.search(new RegExp(`refresh\\s+${node.name}\\b`)); + (awaitAt >= 0 && off > awaitAt ? refreshHeld : refreshNow).push(node); + continue; + } + if (e.op === "affects") { affects.push(node); continue; } + const guess = e.op === "optimistic"; + const expr = extractAssign(text, node.name, guess); + const off = assignAt(text, node.name, guess); + const isHeld = !guess && awaitAt >= 0 && off > awaitAt; + (isHeld ? held : sync).push({ node, expr, argEnv, from: action }); + } + const ctx = { cause: action.key, origin }; + const concrete = list => list.map(w => ({ node: w.node, value: evalWrite(w.expr, w.argEnv, w.from, w.node) ?? invent(w.node) })); + const syncWrites = concrete(sync); + const prevs = new Map(); + for (const w of syncWrites) { + if (inFlight.has(w.node.key)) { + emit({ type: "flight", key: w.node.key, state: "abandon", at: clock }); + inFlight.delete(w.node.key); + } + prevs.set(w.node.key, values.has(w.node.key) ? preview(values.get(w.node.key)) : undefined); + values.set(w.node.key, w.value); + } + for (const n of affects) scheduleFlight(n, ctx); + for (const n of refreshNow) scheduleFlight(n, ctx); + propagateWithPrev(syncWrites.map(w => w.node), ctx, prevs); + if (held.length || refreshHeld.length) { + const delay = 2 + Math.floor(rng() * 3); + holds.push({ landTick: tickCount + delay, writes: held, refresh: refreshHeld, cause: action.key, origin, run }); + // v0.4: the written-but-held sources, and what they wait on (what the action awaits: its calls, else itself) + const by = g.edges.filter(e => e.from === action.id && e.type === "call").map(e => byId.get(e.to)?.key).filter(Boolean); + for (const w of held) emit({ type: "held", key: w.node.key, by: by.length ? [...new Set(by)] : [action.key], at: clock }); + } else emit({ type: "run", key: action.key, id: run, state: "end", at: clock }); + } + + function landFlight(f) { + if (inFlight.get(f.node.key) !== f) return; + inFlight.delete(f.node.key); + landN++; + if (f.abandon) { + emit({ type: "flight", key: f.node.key, state: "abandon", at: clock }); + const probes = probeUpdates([f.node]); + const changes = []; + for (const a of probes) { + const c = changeFor(a.node, a.prev); + if (c) changes.push(c); + } + commitFlush(changes, { cause: f.node.key, origin: `flight ${f.node.name}` }); + return; + } + if (failRate > 0 && rng() < failRate) { + emit({ type: "flight", key: f.node.key, state: "land", at: clock }); + const c = { key: f.node.key, name: f.node.name, error: `ServerError: ${f.node.name} failed (503)` }; + if (shown.has(f.node.key)) c.prev = shown.get(f.node.key); + commitFlush([c], { cause: f.node.key, origin: `flight ${f.node.name}` }); + return; + } + const trial = evalNode(f.node, "land"); + const next = trial.ok ? trial.value : invent(f.node); + const prev = values.has(f.node.key) ? preview(values.get(f.node.key)) : undefined; + values.set(f.node.key, next); + emit({ type: "flight", key: f.node.key, state: "land", at: clock }); + propagateWithPrev([f.node], { cause: f.node.key, origin: `flight ${f.node.name}` }, new Map([[f.node.key, prev]])); + } + + function landDue() { + const dueH = holds.filter(h => h.landTick <= tickCount).sort((a, b) => a.landTick - b.landTick || (a.cause < b.cause ? -1 : 1)); + holds = holds.filter(h => h.landTick > tickCount); + for (const h of dueH) { + const writes = h.writes.map(w => ({ node: w.node, value: evalWrite(w.expr, w.argEnv, w.from, w.node) ?? invent(w.node) })); + const prevs = new Map(); + for (const w of writes) { + if (inFlight.has(w.node.key)) { + emit({ type: "flight", key: w.node.key, state: "abandon", at: clock }); + inFlight.delete(w.node.key); + } + prevs.set(w.node.key, values.has(w.node.key) ? preview(values.get(w.node.key)) : undefined); + values.set(w.node.key, w.value); + } + propagateWithPrev(writes.map(w => w.node), { cause: h.cause, origin: h.origin }, prevs); + for (const w of writes) emit({ type: "released", key: w.node.key, at: clock }); + if (h.run) emit({ type: "run", key: h.cause, id: h.run, state: "end", at: clock }); + for (const n of h.refresh) scheduleFlight(n, { cause: h.cause, origin: h.origin }); + } + const dueF = [...inFlight.values()].filter(f => f.landTick <= tickCount).sort((a, b) => a.node.key < b.node.key ? -1 : 1); + for (const f of dueF) landFlight(f); + } + + function bootFlights() { + if (booted) return; + booted = true; + const nodes = g.nodes.filter(n => (n.kind === "source" || n.kind === "eq") && isAsyncNode(n, g)).sort(byKeySort); + for (const n of nodes) { + const trial = evalNode(n, "sync"); + if (trial.flight) scheduleFlight(n, { cause: n.key, origin: `flight ${n.name}` }); + } + } + + function act(actionKey) { + if (disposed) return; + clock += 1; + const actions = g.nodes.filter(n => n.kind === "action").sort(byKeySort); + if (!actions.length) return; + const action = actionKey ? actions.find(a => a.key === actionKey) : actions[Math.floor(rng() * actions.length)]; + if (!action) return; + runAction(action); + } + + function tick(n) { + if (disposed) return; + const count = n == null ? 1 : n; + for (let i = 0; i < count; i++) { + clock += 16; + tickCount += 1; + if (!booted) bootFlights(); + landDue(); + if (queued != null && !inFlight.size && !holds.length) { const to = queued; queued = null; travel(to); } + else if (queued != null && tickCount - queuedSince >= PENDING_TICKS) { + const to = queued; + queued = null; + emit({ type: "travel-denied", to, reason: "pending", keys: waitingOn() }); + } + if (rate > 0 && tickCount % rate === 0) act(); + } + } + + function timeline() { + return { + type: "timeline", + head, + viewing, + steps: steps.map(s => ({ ...s, changes: s.changes.map(c => ({ ...c })), order: s.order ? [...s.order] : undefined })), + capacity, + }; + } + + // Travel asked for while a flight or a hold is open waits for it (TRACE-CONTRACT v0.6 `travel-pending`): the newest + // target wins and goes once everything has landed; `resume` drops it. + // It waits PENDING_TICKS at most, then is denied "pending" with the keys still in the air (finding 9: no wait forever). + const PENDING_TICKS = 12; + let queued = null, queuedSince = 0; + const waitingOn = () => [...new Set([...inFlight.keys(), ...holds.flatMap(h => [...h.writes.map(w => w.node.key), ...h.refresh.map(n => n.key)])])].sort(); + function travel(to) { + if (inFlight.size || holds.length) { + if (queued == null) queuedSince = tickCount; + queued = to; // checked when it goes: the seq may be recorded by then + emit({ type: "travel-pending", to }); + return; + } + queued = null; + if (typeof to !== "number" || !Number.isInteger(to) || to < 1 || to > head || to <= floor) { + emit({ type: "travel-denied", to, reason: "evicted" }); + return; + } + const from = viewing ?? head; + const changes = diffMaps(valuesAt(from), valuesAt(to)); + viewing = to; + emit({ type: "step", from, to, direction: to < from ? "back" : "forward", changes }); + } + + function resume() { + queued = null; + if (viewing == null) { + emit({ type: "resume", head, changes: [] }); + return; + } + const from = viewing; + const changes = diffMaps(valuesAt(from), valuesAt(head)); + viewing = null; + emit({ type: "resume", head, changes }); + } + + function post(msg) { + if (disposed || !msg || typeof msg !== "object") return; + if (msg.type === "hello") { emit(snapshot()); emit(timeline()); } + else if (msg.type === "snapshot?") emit(snapshot()); + else if (msg.type === "travel") travel(msg.to); + else if (msg.type === "resume") resume(); + else if (msg.type === "select") selected = msg.key ?? null; + } + + function subscribe(fn) { + subs.add(fn); + return () => subs.delete(fn); + } + + // What the app displays now (TRACE-CONTRACT §5, the arbiter): while viewing, the state as of the viewed seq; live, + // the fake's true values, not what its timeline says. + function displayed() { + if (viewing != null) return valuesAt(viewing); + const m = new Map(); + for (const [k, v] of values) if (v !== undefined) m.set(k, preview(v)); + return m; + } + function shownKeys(keys) { + const m = displayed(), out = {}; + for (const k of keys ?? m.keys()) if (m.has(k)) out[k] = { preview: m.get(k) }; + return out; + } + function snapshot() { + const m = displayed(); + return { type: "snapshot", at: clock, values: [...m].map(([key, p]) => ({ key, preview: p })), + flights: [...inFlight.values()].map(f => ({ key: f.node.key, since: clock })), boundaries: [], + runs: holds.filter(h => h.run).map(h => ({ key: h.cause, id: h.run, since: clock })) }; + } + + function freshId(mod) { + const ids = new Set(g.nodes.map(n => n.id)); + let i = 1; + while (ids.has(`${mod}:sx${i}`)) i++; + return `${mod}:sx${i}`; + } + + function mutateGraph(next, mod, file, op) { + const inMod = kind => next.nodes.filter(n => n.mod === mod && n.kind === kind).sort(byKeySort); + const pick = list => list.length ? list[Math.floor(rng() * list.length)] : null; + const lines = next.lines[file] ?? (next.lines[file] = {}); + if (op === "rename") { + const n = pick(inMod("eq")); + if (!n) return false; + let name = `${n.name}Renamed`; + let i = 2; + while (next.nodes.some(x => x.mod === mod && x.name === name)) name = `${n.name}Renamed${i++}`; + if (lines[n.line] != null) lines[n.line] = String(lines[n.line]).replace(new RegExp(`\\b${n.name.replace(/[.*+?^${}()|[\]\\]/g, "\\$&")}\\b`), name); + const p = keyParts(n.key); + n.name = name; + n.key = `${p.module}|${p.scope}|${name}${p.index ? "#" + p.index : ""}`; + if (n.base) n.base = `${p.module}|${p.scope}|${name}`; + return true; + } + if (op === "expr") { + const n = pick(inMod("eq")); + if (!n || lines[n.line] == null) return false; + const line = String(lines[n.line]); + const cut = line.indexOf("//"); + const head = cut >= 0 ? line.slice(0, cut).replace(/\s*$/, "") : line.replace(/\s*$/, ""); + const tail = cut >= 0 ? " " + line.slice(cut) : ""; + lines[n.line] = `${head} + 0${tail}`; + return true; + } + if (op === "type") { + const sources = inMod("source").filter(n => parseDecl("source", n.name, declText(next, n)).type); + const n = pick(sources.length ? sources : inMod("source")); + if (!n || lines[n.line] == null) return false; + const line = String(lines[n.line]); + if (/:\s*[^=]+?(:=|=)/.test(line)) lines[n.line] = line.replace(/(\s*)(:=|=)/, " | null$1$2"); + else lines[n.line] = line.replace(/^((?:export\s+)?source\s+\w+)/, "$1: string"); + return true; + } + if (op === "add") { + let name = "extra"; + let i = 2; + while (next.nodes.some(n => n.mod === mod && n.name === name)) name = `extra${i++}`; + const max = Math.max(0, ...Object.keys(lines).map(Number).filter(Number.isFinite)); + const line = max + 1; + lines[line] = `source ${name}: number := 0`; + const region = next.regions.find(r => r.mod === mod && r.parent == null)?.id ?? `${mod}:r0`; + const key = `${file}||${name}`; + next.nodes.push({ + id: freshId(mod), mod, file, kind: "source", name, line, region, + io: false, question: false, async: false, key, base: key, + }); + return true; + } + if (op === "remove") { + const n = pick([...inMod("eq"), ...inMod("source")]); + if (!n) return false; + next.nodes = next.nodes.filter(x => x.id !== n.id); + next.edges = next.edges.filter(e => e.from !== n.id && e.to !== n.id); + delete lines[n.line]; + return true; + } + return false; + } + + function applyPlan(plan) { + const allow = new Set([...plan.rerun, ...plan.reset, ...plan.added]); + for (const m of plan.moved) { + if (values.has(m.from)) { + values.set(m.to, values.get(m.from)); + values.delete(m.from); + } + } + for (const k of plan.removed) values.delete(k); + const changes = []; + const touch = node => { + if (!node || node.kind === "action" || !allow.has(node.key)) return; + const p = preview(values.get(node.key)); + const prevShown = shown.has(node.key) ? shown.get(node.key) : undefined; + if (prevShown === p) return; + const c = { key: node.key, name: node.name, preview: p, origin: `hmr h${hmrN}` }; + if (prevShown !== undefined) c.prev = prevShown; + changes.push(c); + }; + for (const k of plan.reset) { + const node = byKeyGet(k); + if (!node || node.kind === "action") continue; + values.set(node.key, initialOf(node)); + touch(node); + } + for (const k of plan.added) { + const node = byKeyGet(k); + if (!node || node.kind === "action") continue; + const v = initialOf(node); + values.set(node.key, v === undefined ? 0 : v); + touch(node); + } + const rerun = plan.rerun.map(byKeyGet).filter(n => n && n.kind !== "action"); + for (const node of topo(rerun)) { + const trial = evalNode(node, "land"); + const next = trial.ok ? trial.value : (values.has(node.key) ? invent(node) : zeroOf(nodeType(node, g), node.name, aliases)); + values.set(node.key, next); + touch(node); + } + return changes; + } + + function editModule(module, mutation) { + if (disposed) return null; + clock += 1; + const mod = g.modules.indexOf(module); + const id = `h${++hmrN}`; + if (mod < 0) { + emit({ type: "hmr", phase: "failed", id, error: `unknown module ${module}`, fallback: "none" }); + return null; + } + const ops = ["rename", "expr", "type", "add", "remove"]; + const asked = typeof mutation === "string" ? mutation : mutation?.op; + const start = asked ? ops.indexOf(asked) : editCount % ops.length; + editCount++; + const order = start >= 0 ? [...ops.slice(start), ...ops.slice(0, start)] : ["add"]; + const next = clone(g); + let applied = null; + for (const op of order) { + if (mutateGraph(next, mod, module, op)) { applied = op; break; } + } + if (!applied) { + emit({ type: "hmr", phase: "failed", id, error: `could not edit ${module}`, fallback: "none" }); + return null; + } + const plan = planHmr(g, next); + emit({ type: "hmr", phase: "plan", id, modules: [module], graph: next, plan }); + emit({ type: "hmr", phase: "apply", id }); + g = next; + rebuild(); + const changes = applyPlan(plan); + emit({ type: "hmr", phase: "done", id, changes: changes.map(c => ({ ...c })) }); + if (changes.length) commitFlush(changes, { origin: `hmr ${id}` }); + return plan; + } + + function dispose() { + disposed = true; + subs.clear(); + inFlight.clear(); + holds = []; + } + + + return { post, subscribe, tick, act, editModule, dispose, shown: shownKeys }; +} + +function isCli() { + return typeof process !== "undefined" && !!process.argv?.[1] && /(?:^|\/)fake\.mjs$/.test(process.argv[1]); +} + +if (isCli()) { + const args = process.argv.slice(2); + let file = null, seed = 1, steps = 20, edit = false, rate = 4; + const usage = () => { + console.error("usage: node tooling/rx-map/fake.mjs --seed 3 --steps 20 [--edit]"); + process.exit(1); + }; + for (let i = 0; i < args.length; i++) { + if (args[i] === "--seed") seed = Number(args[++i]); + else if (args[i] === "--steps") steps = Number(args[++i]); + else if (args[i] === "--rate") rate = Number(args[++i]); + else if (args[i] === "--edit") edit = true; + else if (args[i] === "-h" || args[i] === "--help") usage(); + else if (!file) file = args[i]; + else usage(); + } + if (!file) usage(); + const { readFileSync } = await import("node:fs"); + const graph = JSON.parse(readFileSync(file, "utf8")); + const host = createFakeHost(graph, { seed, rate }); + host.subscribe(m => console.log(JSON.stringify(m))); + host.post({ type: "hello", want: ["live", "timeline", "travel", "hmr"] }); + host.tick(steps); + if (edit) host.editModule(graph.modules[0]); + host.dispose(); +} diff --git a/tooling/rx-map/graph.mjs b/tooling/rx-map/graph.mjs new file mode 100644 index 000000000..715fb98d5 --- /dev/null +++ b/tooling/rx-map/graph.mjs @@ -0,0 +1 @@ +export * from "@reactivescript/compiler/graph"; diff --git a/tooling/rx-map/hmr.mjs b/tooling/rx-map/hmr.mjs new file mode 100644 index 000000000..88abc8fc9 --- /dev/null +++ b/tooling/rx-map/hmr.mjs @@ -0,0 +1 @@ +export * from "@reactivescript/compiler/hmr"; diff --git a/tooling/rx-map/layout.mjs b/tooling/rx-map/layout.mjs new file mode 100644 index 000000000..79ea5b61e --- /dev/null +++ b/tooling/rx-map/layout.mjs @@ -0,0 +1,645 @@ +// The map's layout, as a pure function of the graph: where every module plate, region frame, token, cluster, view-text +// strip and reserved area goes, in board pixels. Computed once per graph and never changed by zoom: the two detail +// levels (overview, detail) draw different things inside the same boxes, so moving between them shifts +// nothing. No DOM: sizes come from a fixed monospace metric, so the layout doesn't depend on fonts loading, and the same +// module serves the page (map.html, embedded by build.mjs), Node tools and tests. +// +// import { analyze, layoutWorld, planTrunks } from "./layout.mjs"; +// const A = analyze(graph); // derived model: regions tree, ranks, control-flow labels, boundaries… +// const L = layoutWorld(A, { aspect: 1.6 }); // the boxes +// const routes = planTrunks(["3>0|read:tracked"], L); +// +// Rules kept by the layout: modules top to bottom in dependency order (a module sits in a lower band than everything +// it needs, so every arrow between modules points up); inside a frame, a token sits in a lower row than the tokens of +// its group it needs; nothing overlaps; the result is deterministic for a graph and options. + +/** @typedef {{ x: number, y: number, w: number, h: number }} Box */ +/** + * @typedef {object} Layout + * @property {number} width board width + * @property {number} height board height + * @property {Map} plates a module's plate + * (key = module index) or the "world" strip of JS imports + * @property {{ top: number, bottom: number, keys: (number|"world")[] }[]} rows plate rows, top to bottom + * @property {Map} frames + * region frames (module roots included, kind "program"), with their header box + * @property {Map} tokens + * every token (node id; a control region's tag under its region id, role "label"); `level` is the first detail level + * that shows it + * @property {(Box & { mod: number, unit: string, label: string, what: string })[]} clusters groups of a dense module's names + * @property {Map} strips a region's view-text strip (detail level) + * @property {(Box & { region: string, kind: "sites"|"strip" })[]} reserved areas view sites and view text fill + * (kept apart so nothing in them overlaps the names) + * @property {(Box & { file: string, label: Box })[]} worldGroups JS imports grouped by file, in the world strip + * @property {{ x: number, y: number }} gaps between plates in a row, between rows + */ + +export const CTL = { then: "if", else: "else", for: "for", loading: "loading", errored: "errored" }; +export const ORDER = ["props", "context", "source", "asource", "eq", "aeq", "action", "fn", "server", "errclass", "comp", "import"]; +export const SHAPE = { source: "well", asource: "well", eq: "flow", aeq: "flow", props: "flow", reader: "flow", action: "act", handler: "act", effect: "ring", apply: "ring", + import: "plug", server: "plug", fn: "plug", comp: "frm", context: "frm", prop: "frm", provide: "frm", errclass: "fail" }; +export const kindOf = n => (n.kind === "source" && n.question ? "asource" : n.kind === "eq" && n.async ? "aeq" : n.kind); +const FRAME_WORD = { component: "component", for: "for each", then: "if · then", else: "else", loading: "loading", errored: "errored", children: "renders", imported: "renders (imported)" }; +const REACTIVE = new Set(["reader", "prop", "effect", "provide"]); +/** Attributes whose value is words on the screen (or read aloud). */ +export const HUMAN_ATTR = /^(placeholder|title|alt|aria-label|aria-description|aria-placeholder|label|value)$/i; +/** A view site that puts text on the screen: a `{ expr }` child, or a human-text attribute (`input placeholder`). */ +export const textHole = n => /^\{(…|\.\.\.)\}$/.test(n.name) || HUMAN_ATTR.test(String(n.name).split(/\s+/).pop()); + +// ---- analysis: what the map derives from a graph --------------------------------------------------------------------- +/** + * The derived model the map draws from: the regions tree with each region's own nodes, edge indexes, dependency ranks, + * component and module levels, control-flow labels, boundary notifier edges. Does not change `graph`. + * @param {object} graph a `buildGraph` (or `diffGraphs`) result + * @param {{ diff?: boolean }} [opts] + */ +export function analyze(graph, { diff = !!graph.diff } = {}) { + const G = { ...graph, edges: [...graph.edges] }; + const nodes = new Map(G.nodes.map(n => [n.id, n])); + const out = new Map(), inc = new Map(); + const link = e => { (out.get(e.from) ?? out.set(e.from, []).get(e.from)).push(e); (inc.get(e.to) ?? inc.set(e.to, []).get(e.to)).push(e); }; + for (const e of G.edges) link(e); + const regions = new Map(G.regions.map(r => [r.id, { ...r, kids: [], nodes: [] }])); + for (const r of regions.values()) if (r.parent && regions.has(r.parent)) regions.get(r.parent).kids.push(r); + const compRegion = new Map(); + for (const n of G.nodes) { + const r = regions.get(n.region); + if (n.kind === "comp") { + const cr = [...regions.values()].find(x => x.mod === n.mod && x.kind === "component" && x.name === n.name); + if (cr) { compRegion.set(n.id, cr.id); continue; } + } + if (n.world && !n.from) continue; + (r ?? regions.get(`${n.mod}:r0`))?.nodes.push(n); + } + const compOfRegion = new Map([...compRegion].map(([n, r]) => [r, n])); + // depends(x): what x needs (reads, writes, calls, props it passes into): x sits below it + const deps = new Map(); + for (const e of G.edges) { + const [a, b] = e.type === "read" ? [e.to, e.from] : [e.from, e.to]; + if (!nodes.has(a) || !nodes.has(b) || a === b) continue; + (deps.get(a) ?? deps.set(a, new Set()).get(a)).add(b); + } + const memo = (fn) => { const m = new Map(), path = new Set(); return id => { if (m.has(id)) return m.get(id); if (path.has(id)) return 0; path.add(id); const v = fn(id); path.delete(id); m.set(id, v); return v; }; }; + const rank = memo(id => { let r = 0; for (const d of deps.get(id) ?? []) r = Math.max(r, rank(d) + 1); return r; }); + const rendered = (r, acc = new Set()) => { + for (const k of r.kids) { + if (k.kind === "children" || k.kind === "imported") { + const c = G.nodes.find(n => n.kind === "comp" && n.name === k.name && (n.mod === k.mod || !G.nodes.some(m => m.kind === "comp" && m.name === k.name && m.mod === k.mod))); + if (c) acc.add(c.id); + } + rendered(k, acc); + } + return acc; + }; + const compLevel = memo(compId => { const r = regions.get(compRegion.get(compId)); let l = 0; if (r) for (const c of rendered(r)) if (c !== compId) l = Math.max(l, compLevel(c) + 1); return l; }); + const modDeps = new Map(G.modules.map((_, i) => [i, new Set()])); + for (const [a, ds] of deps) for (const b of ds) { + const ma = nodes.get(a).mod, mb = nodes.get(b).mod; + if (ma !== mb && !nodes.get(b).world) modDeps.get(ma)?.add(mb); + } + for (const n of G.nodes) if (n.kind === "comp") for (const c of rendered(regions.get(compRegion.get(n.id)) ?? { kids: [] })) { + const mc = nodes.get(c).mod; if (mc !== n.mod) modDeps.get(n.mod)?.add(mc); + } + const modLevel = memo(m => { let l = 0; for (const d of modDeps.get(m) ?? []) l = Math.max(l, modLevel(d) + 1); return l; }); + const firstLine = r => Math.min(...r.nodes.map(n => n.line), ...r.kids.map(firstLine), 1e9); + const empty = r => r.kind !== "component" && !r.nodes.length && r.kids.every(empty) && r.kind !== "children"; + const lineOf = n => ((n.status === "removed" ? G.linesBefore : G.lines)?.[n.file]?.[n.line] ?? "").trim(); + const ctlInfo = new Map(); + const controlInfo = r => { + if (ctlInfo.has(r.id)) return ctlInfo.get(r.id); + const L = firstLine(r), ls = (r.status === "removed" ? G.linesBefore : G.lines)?.[G.modules[r.mod]] ?? {}; + const pat = { + then: [/(?:^|[{\s])if\s+(.+?)\s*\{/, m => `if ${m[1]}`], + else: [/\belse\s+if\s+(.+?)\s*\{|\belse\b/, m => (m[1] ? `else if ${m[1]}` : "else")], + for: [/\{\s*for\s+(.+?)\s*\{/, m => `for ${m[1]}`], + loading: [/\bloading\b\s*(on\s*\([^)]*\))?/, m => (m[1] ? `loading ${m[1].replace(/\s+/g, "")}` : "loading")], + errored: [/\berrored\b(?:\s+fallback\s*\(([^)]*)\))?/, m => (m[1] ? `errored (${m[1].trim()})` : "errored")], + }[r.kind]; + let info = { text: CTL[r.kind] ?? r.kind, line: null, site: null }; + if (r.head) info = { text: r.head.text, line: r.head.line, site: null }; + else { + let bound = L; + const below = rr => { for (const k of rr.kids ?? []) { const h = CTL[k.kind] && controlInfo(k); if (h?.line) bound = Math.min(bound, h.line - 1); else below(k); } }; + below(r); + if (pat && bound < 1e9) for (let i = bound; i >= Math.max(1, bound - 40); i--) { + const m = ls[i] && pat[0].exec(ls[i]); + if (m) { info = { text: pat[1](m), line: i, site: null }; break; } + } + } + const kw = { then: "if", for: "for", loading: "loading on" }[r.kind]; + if (kw && info.line) info.site = regions.get(r.parent)?.nodes.find(n => n.site && n.name === kw && n.line === info.line) ?? null; + ctlInfo.set(r.id, info); + return info; + }; + const ctlSites = new Set(); + for (const r of regions.values()) if (CTL[r.kind] && !empty(r)) { const i = controlInfo(r); if (i.site) ctlSites.add(i.site.id); } + // boundaries: which names can make each show its fallback (see map.html's guide) + const covered = (r, kind, acc = { sites: new Set(), seen: new Set() }) => { + for (const n of r.nodes) if (n.site && REACTIVE.has(n.kind)) acc.sites.add(n.id); + for (const k of r.kids) { + const typed = k.kind === "errored" && /\(\s*\w+\s*:/.test(controlInfo(k).text); + if (k.kind === "component" || (k.kind === kind && !typed)) continue; + if ((k.kind === "children" || k.kind === "imported") && k.name) + for (const c of G.nodes) if (c.kind === "comp" && c.name === k.name) { + const cr = regions.get(compRegion.get(c.id)); + if (cr && !acc.seen.has(cr.id)) { acc.seen.add(cr.id); covered(cr, kind, acc); } + } + covered(k, kind, acc); + } + return acc; + }; + const pendingRoots = siteIds => { + const roots = new Map(); + for (const sid of siteIds) { + const seen = new Set([sid]), todo = [sid]; + while (todo.length) for (const e of inc.get(todo.pop()) ?? []) { + if (!((e.type === "read" && e.mode === "tracked" && !e.probe) || e.type === "passes") || seen.has(e.from)) continue; + seen.add(e.from); + const n = nodes.get(e.from); + if (!n) continue; + if (n.async && !n.site && !roots.has(n.id)) roots.set(n.id, sid); + todo.push(e.from); + } + } + return roots; + }; + const boundaryCover = new Map(); + for (const r of regions.values()) { + if ((r.kind !== "loading" && r.kind !== "errored") || empty(r)) continue; + const { sites } = covered(r, r.kind); + boundaryCover.set(r.id, sites); + for (const [root, via] of pendingRoots(sites)) { + const e = { from: root, to: r.id, type: "notifies", boundary: r.kind, via, status: diff ? "same" : undefined }; + G.edges.push(e); link(e); + } + } + const keyIds = new Map(); + for (const n of G.nodes) if (n.key) (keyIds.get(n.key) ?? keyIds.set(n.key, []).get(n.key)).push(n.id); + const label = id => nodes.get(id)?.name ?? (regions.get(id) ? (CTL[regions.get(id).kind] ? controlInfo(regions.get(id)).text : `<${regions.get(id).name}/>`) : id); + const shorten = s => { const m = s.match(/\{([^{}]{1,40})\}/); return (m ? m[1].trim() : s).slice(0, 28); }; + // a markup hole is named by what it reads: `{ total }`, `{ pending? users }` + const readsOf = n => [...new Set((inc.get(n.id) ?? []).filter(e => e.type === "read").map(e => (e.probe === "pending" ? "pending? " : e.probe ? `${e.probe} ` : "") + label(e.from) + (e.field ? `.${e.field}` : "")))].join(", ").slice(0, 34); + /** the text a token shows for its name */ + const chipLabel = n => (n.site && n.name === "{…}" ? `{ ${readsOf(n) || shorten(lineOf(n))} }` : n.name); + const modName = mi => (G.modules[mi] ?? "").split("/").pop().replace(/\.rx$/, ""); + // a dense module's names, by who uses them (another module, or a component of this one) + const clusterNames = (list, mi) => { + const ids = new Set(list.map(n => n.id)); + const unitOf = id => { + const n = nodes.get(id); + if (!n) { const rg = regions.get(id); return rg && rg.mod !== mi ? `m${rg.mod}` : null; } + if (n.world && !n.from) return null; + if (n.mod !== mi) return `m${n.mod}`; + let r = regions.get(n.region); + while (r && r.kind !== "component") r = regions.get(r.parent); + return r ? `c${r.name}` : null; + }; + const primary = new Map(); + const vote = (n, pick) => { + const votes = new Map(); + for (const e of [...(out.get(n.id) ?? []), ...(inc.get(n.id) ?? [])]) { const o = e.from === n.id ? e.to : e.from; const u = pick(o); if (u) votes.set(u, (votes.get(u) ?? 0) + 1); } + let best = null, bv = 0; for (const [u, v] of [...votes].sort((a, b) => (a[0] < b[0] ? -1 : 1))) if (v > bv) { best = u; bv = v; } + return best; + }; + for (const n of list) { const u = vote(n, o => (ids.has(o) ? null : unitOf(o))); if (u) primary.set(n.id, u); } + for (let it = 0; it < 3; it++) for (const n of list) if (!primary.has(n.id)) { const u = vote(n, o => ids.has(o) && primary.get(o)); if (u) primary.set(n.id, u); } + const groups = new Map(); + for (const n of list) { const u = primary.get(n.id) ?? "core"; (groups.get(u) ?? groups.set(u, []).get(u)).push(n); } + const small = [...groups].filter(([u, ns]) => ns.length < 2 && u !== "core"); + if (small.length > 1) for (const [u, ns] of small) { groups.delete(u); (groups.get("other") ?? groups.set("other", []).get("other")).push(...ns); } + if (groups.size < 2) return null; + return [...groups].map(([unit, ns]) => ({ + unit, nodes: ns, + label: unit === "core" ? "inside" : unit === "other" ? "used by one each" : unit[0] === "m" ? "used by" : "used in", + what: unit === "core" || unit === "other" ? `${ns.length}` : unit[0] === "m" ? modName(+unit.slice(1)) : `<${unit.slice(1)} />`, + })); + }; + const moduleLinks = () => { + const w = new Map(), add = (a, b) => { if (a === b || a == null || b == null) return; const k = a < b ? `${a},${b}` : `${b},${a}`; w.set(k, (w.get(k) ?? 0) + 1); }; + const modOf = id => { const n = nodes.get(id); if (n) return n.world && !n.from ? null : n.mod; return regions.get(id)?.mod ?? null; }; + for (const e of G.edges) add(modOf(e.from), modOf(e.to)); + return w; + }; + // a region's view text as the screen says it: its words, holes only where the view puts text (a `{ expr }` child, a + // human-text attribute: placeholder, title, alt, aria-label, value), child regions where there are words around + // them. Classes, styles, data-*, handlers, boolean attributes stay site tokens only. Null when nothing is left to read. + const stripMemo = new Map(); + const stripParts = r => { + if (stripMemo.has(r.id)) return stripMemo.get(r.id); + const parts = []; + for (const p of r.outline ?? []) { + if ("site" in p) { const n = nodes.get(p.site); if (n && !ctlSites.has(p.site) && textHole(n)) parts.push(p); } + else if ("region" in p) { const k = regions.get(p.region); if (k && !empty(k)) parts.push(p); } + else if ("attr" in p) { if (HUMAN_ATTR.test(p.attr) && String(p.text).trim()) parts.push(p); } + else if ("text" in p) { if (String(p.text).trim()) parts.push(p); } + else if (p.br) { if (parts.length && !parts.at(-1).br) parts.push(p); } + } + while (parts.at(-1)?.br) parts.pop(); + const v = parts.some(p => "text" in p || "site" in p) ? parts : null; + stripMemo.set(r.id, v); + return v; + }; + return { G, nodes, out, inc, regions, compRegion, compOfRegion, deps, ctlSites, boundaryCover, keyIds, stripParts, + rank, rendered, compLevel, modLevel, firstLine, empty, lineOf, controlInfo, label, readsOf, chipLabel, modName, clusterNames, moduleLinks }; +} + +// ---- sizes: a fixed monospace metric, so the layout is the same before and after fonts load ------------------------- +/** Sizes of things, in px; `mono` is a monospace character's width in ems. */ +export const METRICS = { + // a monospace glyph is .6em; .64 leaves slack for hinting at small sizes + mono: .64, sans: .56, nameFont: 13.5, siteFont: 12.5, badgeFont: 10, tagFont: 12.5, stripFont: 12, labelFont: 12, + // the detail level is drawn at this scale (the page zooms its things by it): big enough that its smallest text reads + // at 11px on screen from about half zoom, where the overview hands over to it + zoom: 1.85, + // base sizes, before the zoom + namedH: 34, siteH: 28, labelH: 30, stripH: 30, + gapX: 16, siteGapX: 14, rowGap: 56, lineGap: 30, + frame: { t: 12, x: 16, b: 18 }, plate: { t: 20, x: 24, b: 28 }, cluster: { t: 10, x: 14, b: 16, gapX: 26, gapY: 24 }, + kidsGap: 20, sitesSep: 44, stripGap: 16, compMin: 560, viewMin: 400, plateScale: 1.7, + plates: { gapX: 90, gapY: 120, pad: 70 }, +}; +const monoW = (text, font, M) => String(text).length * font * M.mono; +/** A token's box size, at its level's zoom (`zoom: false` for the unzoomed size). */ +export function tokenSize(n, A, M = METRICS, zoom = true) { + const s = baseTokenSize(n, A, M), k = zoom ? M.zoom : 1; + return { w: Math.ceil(s.w * k), h: s.h * k }; +} +/** A token's unzoomed size: its icon, name, marks and badges, in the page's chip paddings. */ +export function baseTokenSize(n, A, M = METRICS) { + const kk = kindOf(n), shape = SHAPE[kk] ?? "plug", site = !!n.site; + const pad = shape === "act" ? (site ? [13, 19] : [15, 22]) : shape === "ring" ? [15, 17] : site ? [8, 11] : [10, 14]; + let w = pad[0] + pad[1] + 14 + 6 + monoW(A.chipLabel(n), site ? M.siteFont : M.nameFont, M); + if (n.async) w += 13 + 6; + if (n.kind === "source" && n.question) w += 15 + 6; + const badges = [n.flavor, n.from, site ? `L${n.line}` : null].filter(Boolean); + for (const b of badges) w += 6 + 10 + monoW(b, M.badgeFont, M); + return { w: Math.ceil(Math.min(w, 420)), h: site ? M.siteH : M.namedH }; +} + +// ---- inside a frame: tokens in rows of dependency, wrapped to the width ----------------------------------------------- +// A row per step of dependency within the group (a token sits below the tokens of its group it needs), sorted by role +// then line; a row wider than the frame wraps onto more lines; lines are centred. +function rankRows(list, A) { + const inSet = new Set(list.map(n => n.id)), memo = new Map(), path = new Set(); + const local = id => { + if (memo.has(id)) return memo.get(id); + if (path.has(id)) return 0; + path.add(id); + let r = 0; + for (const d of A.deps.get(id) ?? []) if (inSet.has(d) && d !== id) r = Math.max(r, local(d) + 1); + path.delete(id); memo.set(id, r); + return r; + }; + const byRank = new Map(); + for (const n of list) { const k = local(n.id); (byRank.get(k) ?? byRank.set(k, []).get(k)).push(n); } + return [...byRank.keys()].sort((a, b) => a - b).map(k => byRank.get(k).sort((a, b) => ORDER.indexOf(kindOf(a)) - ORDER.indexOf(kindOf(b)) || a.line - b.line || (a.id < b.id ? -1 : 1))); +} +function flowTokens(groups, x, y, w, gapX0, ctx, extra) { + const M = ctx.M; + let cy = y; + groups.forEach((g, gi) => { + const k = M.zoom, gapX = gapX0 * k; + if (gi) cy += g[0]?.site ? (M.rowGap - 12) * k : M.rowGap * Math.sqrt(k); // between steps of dependency: room for the arrows + const lines = [[]]; let lw = 0; + for (const n of g) { + const s0 = ctx.size(n), s = s0.w > w ? { ...s0, w } : s0; // never wider than its frame (the page cuts the name) + if (lines.at(-1).length && lw + gapX + s.w > w) { lines.push([]); lw = 0; } + lw += (lines.at(-1).length ? gapX : 0) + s.w; lines.at(-1).push([n, s]); + } + lines.forEach((line, li) => { + if (li) cy += M.lineGap * k; // a wrapped line: room for value badges under tokens + const lineW = line.reduce((a, [, s]) => a + s.w, 0) + gapX * (line.length - 1); + const h = Math.max(...line.map(([, s]) => s.h)); + let cx = x + Math.max(0, (w - lineW) / 2); + for (const [n, s] of line) { ctx.token(n, cx, cy + (h - s.h) / 2, s, extra); cx += s.w + gapX; } + cy += h; + }); + }); + return cy - y; +} +// the natural width of token rows: the widest row, unwrapped +const rowsWidth = (groups, gapX, ctx) => Math.max(0, ...groups.map(g => g.reduce((a, n) => a + ctx.size(n).w, 0) + gapX * ctx.M.zoom * (g.length - 1))); + +// estimate of a region's view-text strip width (one line), at the detail level's zoom +function stripWidth(r, A, M) { + let chars = 0; + for (const p of A.stripParts(r) ?? []) { + if (p.br) chars += 3; + else if ("attr" in p) chars += p.attr.length + p.text.length + 4; + else if ("text" in p) chars += p.text.length; + else if ("site" in p) { const n = A.nodes.get(p.site); if (n && !A.ctlSites.has(p.site)) chars += Math.min(22, A.chipLabel(n).length) + 3; } + else if ("region" in p) { const k = A.regions.get(p.region); if (k && !A.empty(k)) chars += (CTL[k.kind] ? A.controlInfo(k).text.length : (k.name ?? k.kind).length + 4) + 3; } + } + return (60 + chars * M.stripFont * M.mono) * M.zoom; +} +const hasStrip = (r, A) => !!A.stripParts(r); + +// ---- a region's frame: header, names, sites, view text, then the regions inside --------------------------------------- +function layRegion(r, x, y, w, ctx, depth, parent) { + const { A, M } = ctx; + const isRoot = r.kind === "program"; + const pad = isRoot ? M.plate : M.frame; + const inner = w - 2 * pad.x; + const top = y; + // the header (a plate's module label too) is detail text: at its zoom + const KN = M.zoom, LH = M.labelH * KN; + ctx.frames.set(r.id, { id: r.id, kind: r.kind, x, y, w, h: 0, depth, parent, label: { x: x + pad.x, y: y + (isRoot ? 12 : pad.t), w: inner, h: isRoot ? 18 * KN : LH } }); + let cy = y + pad.t + (isRoot ? 12 + 18 * KN : LH + 12); + // the header's own tokens: a component's name, a control construct's tag (and what it reads) + if (!isRoot) { + const comp = r.kind === "component" ? A.G.nodes.find(n => A.compRegion.get(n.id) === r.id) : null; + const lx = x + pad.x, ly = y + pad.t; + if (comp) { const s = ctx.size(comp); ctx.token(comp, lx, ly + KN, { w: Math.min(inner, s.w), h: LH - 2 * KN }, { role: "label", region: r.id, level: 2 }); } + else if (CTL[r.kind]) { + const info = A.controlInfo(r); + // the tag, and what it reads beside it; in a narrow frame both shrink (the page cuts their text) to fit the header + // (what it reads sits in the header too, so at the header's zoom) + const sw0 = info.site ? tokenSize(info.site, A, M, false).w * KN : 0; + let tw = Math.min(inner, (70 + monoW(info.text, M.tagFont, M) + 24) * KN); + if (info.site) tw = Math.min(tw, Math.max(80 * KN, inner - sw0 - 8 * KN)); + ctx.tokens.set(r.id, { id: r.id, x: lx, y: ly, w: tw, h: LH, role: "label", region: r.id, level: 2 }); + if (info.site) ctx.token(info.site, lx + tw + 8 * KN, ly + 2 * KN, { w: Math.max(24 * KN, Math.min(sw0, inner - tw - 8 * KN)), h: LH - 4 * KN }, { role: "label", region: r.id, level: 2 }); + } + } + const named = r.nodes.filter(n => !n.site), sites = r.nodes.filter(n => n.site && !A.ctlSites.has(n.id)); + const groups = isRoot && named.length > 10 ? A.clusterNames(named, r.mod) : null; + if (groups) { + // clusters, in the order of the plates that use them (ctx.clusterOrder), flowed in lines + const C = { ...M.cluster, t: M.cluster.t + 16 * KN }; // the label, at the detail zoom + const order = ctx.clusterOrder?.(r.mod) ?? (u => (u === "core" ? -1 : 0)); + groups.sort((a, b) => order(a.unit) - order(b.unit) || (a.unit < b.unit ? -1 : 1)); + const boxes = groups.map(g => { const rr = rankRows(g.nodes, A); return { g, rr, w: Math.min(inner, Math.max(160, rowsWidth(rr, M.gapX, ctx) + 2 * C.x, (30 + monoW(`${g.label} ${g.what}`, 10, M)) * KN)) }; }); + let lines = [[]], lw = 0; + for (const b of boxes) { if (lines.at(-1).length && lw + C.gapX + b.w > inner) { lines.push([]); lw = 0; } lw += (lines.at(-1).length ? C.gapX : 0) + b.w; lines.at(-1).push(b); } + for (const line of lines) { + const lineW = line.reduce((a, b) => a + b.w, 0) + C.gapX * (line.length - 1); + let cx = x + pad.x + (inner - lineW) / 2, lh = 0; + for (const b of line) { + const h = C.t + flowTokens(b.rr, cx + C.x, cy + C.t, b.w - 2 * C.x, M.gapX, ctx, { region: r.id }) + C.b; + ctx.clusters.push({ mod: r.mod, unit: b.g.unit, label: b.g.label, what: b.g.what, x: cx, y: cy, w: b.w, h }); + lh = Math.max(lh, h); cx += b.w + C.gapX; + } + cy += lh + C.gapY; + } + cy -= C.gapY; + } else if (named.length) cy += flowTokens(rankRows(named, A), x + pad.x, cy, inner, M.gapX, ctx, { region: r.id }); + // view sites: the detail level's; reserved + if (sites.length) { + if (cy > y + pad.t + (isRoot ? 12 + 18 * KN : LH + 12)) cy += M.sitesSep; + const sy = cy; + cy += flowTokens(rankRows(sites, A), x + pad.x, cy, inner, M.siteGapX, ctx, { region: r.id }); + ctx.reserved.push({ region: r.id, kind: "sites", x: x + pad.x, y: sy, w: inner, h: cy - sy }); + } + // the view text strip: one line, reserved + if (hasStrip(r, A)) { + cy += M.stripGap; + const sw = Math.min(inner, stripWidth(r, A, M)); + const box = { x: x + pad.x + (inner - sw) / 2, y: cy, w: sw, h: M.stripH * M.zoom }; + ctx.strips.set(r.id, box); + ctx.reserved.push({ region: r.id, kind: "strip", ...box }); + cy += box.h; + } + // regions inside: components by what renders what, then the view's regions side by side, then the mounts + const kids = r.kids.filter(k => !A.empty(k)); + const extra = isRoot ? [...A.regions.values()].filter(k => k.mod === r.mod && !k.parent && k.id !== r.id && !A.empty(k)) : []; + const comps = kids.filter(k => k.kind === "component"); + const byLevel = new Map(); + for (const k of comps) { const l = A.compLevel(A.compOfRegion.get(k.id)); (byLevel.get(l) ?? byLevel.set(l, []).get(l)).push(k); } + const gridOf = (list, min) => { + const n = list.length, cols = Math.max(1, Math.min(n, Math.floor((inner + M.kidsGap) / (min + M.kidsGap)))); + const cw = (inner - M.kidsGap * (cols - 1)) / cols; + for (let i = 0; i < n; i += cols) { + cy += M.kidsGap; + let rh = 0; + list.slice(i, i + cols).forEach((k, j) => { rh = Math.max(rh, layRegion(k, x + pad.x + j * (cw + M.kidsGap), cy, cw, ctx, depth + 1, r.id)); }); + cy += rh; + } + }; + for (const l of [...byLevel.keys()].sort((a, b) => a - b)) gridOf(byLevel.get(l).sort((a, b) => A.firstLine(a) - A.firstLine(b) || (a.id < b.id ? -1 : 1)), M.compMin); + const rest = kids.filter(k => k.kind !== "component").sort((a, b) => A.firstLine(a) - A.firstLine(b) || (a.id < b.id ? -1 : 1)); + const mounts = rest.filter(k => k.kind === "children" || k.kind === "imported"); + const view = rest.filter(k => !mounts.includes(k)); + if (view.length) gridOf(view, M.viewMin); + if (mounts.length) { + cy += 12; + let cx = x + pad.x, lh = 0; + for (const k of mounts) { + const mw = Math.min(inner, (24 + monoW(`${FRAME_WORD[k.kind]} <${k.name ?? ""} />`, M.labelFont, M)) * KN), mh = 28 * KN; + if (cx > x + pad.x && cx + mw > x + pad.x + inner) { cx = x + pad.x; cy += lh + 8; lh = 0; } + ctx.frames.set(k.id, { id: k.id, kind: k.kind, x: cx, y: cy, w: mw, h: mh, depth: depth + 1, parent: r.id, label: { x: cx + 8 * KN, y: cy, w: mw - 16 * KN, h: mh } }); + ctx.tokens.set(k.id, { id: k.id, x: cx, y: cy, w: mw, h: mh, role: "label", region: k.id, level: 2 }); + cx += mw + 8; lh = Math.max(lh, mh); + } + cy += lh; + } + for (const k of extra) { cy += M.kidsGap; cy += layRegion(k, x + pad.x, cy, inner, ctx, depth + 1, r.id); } + const h = cy - top + pad.b; + ctx.frames.get(r.id).h = h; + return h; +} + +// ---- the world: plates in bands ---------------------------------------------------------------------------------- +/** + * Orders the modules within each band to cut crossings (barycenters of the modules they share edges with, swept down + * and up). `bands`: arrays of module ids, sorted in place; `weight(a, b)`: edges between two modules. + */ +export function orderBands(bands, weight) { + const pos = new Map(); + const setPos = () => bands.forEach(b => b.forEach((mi, i) => pos.set(mi, (i + .5) / b.length))); + setPos(); + const bary = (mi, others) => { let s = 0, n = 0; for (const o of others) { const w = weight(mi, o); if (w) { s += w * pos.get(o); n += w; } } return n ? s / n : pos.get(mi); }; + for (let sweep = 0; sweep < 4; sweep++) { + const order = sweep % 2 ? [...bands.keys()].reverse() : [...bands.keys()]; + for (const k of order) { + const others = bands.filter((_, j) => j !== k).flat(); + const bc = new Map(bands[k].map(mi => [mi, bary(mi, others)])); + bands[k].sort((a, b) => bc.get(a) - bc.get(b) || a - b); + setPos(); + } + } + return bands; +} + +/** + * The layout of the whole world, sized for the detail level (everything every level can show has its place). + * @param {ReturnType} A + * @param {{ aspect?: number, metrics?: Partial, size?: (node: object) => { w: number, h: number } }} [opts] + * `aspect`: the screen's width / height the world should roughly take (bands wrap to it); `size` overrides token sizes + * @returns {Layout} + */ +export function layoutWorld(A, { aspect = 1.6, metrics = {}, size } = {}) { + const M = { ...METRICS, ...metrics }; + const sizeMemo = new Map(); + const sizeOf = n => { if (!sizeMemo.has(n.id)) sizeMemo.set(n.id, size?.(n) ?? tokenSize(n, A, M)); return sizeMemo.get(n.id); }; + const P = M.plates; + const mods = A.G.modules.map((_, mi) => mi).filter(mi => A.regions.get(`${mi}:r0`)); + const tokenCount = mi => A.G.nodes.filter(n => n.mod === mi && !(n.world && !n.from)).length; + const baseW = mi => Math.round(M.plateScale * Math.min(1250, Math.max(360, 128 * Math.sqrt(tokenCount(mi) + 2)))); + const links = A.moduleLinks(), weight = (a, b) => links.get(a < b ? `${a},${b}` : `${b},${a}`) ?? 0; + const bandsMap = new Map(); + for (const mi of mods) { const l = A.modLevel(mi); (bandsMap.get(l) ?? bandsMap.set(l, []).get(l)).push(mi); } + const bands = [...bandsMap.keys()].sort((a, b) => a - b).map(l => bandsMap.get(l)); + orderBands(bands, weight); + // a plate laid out alone at a width, at the origin: its height + const measure = (mi, w, clusterOrder) => { + const ctx = { A, M, size: sizeOf, frames: new Map(), tokens: new Map(), clusters: [], strips: new Map(), reserved: [], clusterOrder, + token(n, x, y, s, extra) { this.tokens.set(n.id, { id: n.id, x, y, w: s.w, h: s.h, role: extra?.role ?? (n.site ? "site" : "named"), region: extra?.region ?? n.region ?? null, level: extra?.level ?? 2 }); } }; + const h = layRegion(A.regions.get(`${mi}:r0`), 0, 0, w, ctx, 0, null); + return { h, ctx }; + }; + const widths = new Map(mods.map(mi => [mi, baseW(mi)])); + let heights = new Map(mods.map(mi => [mi, measure(mi, widths.get(mi)).h])); + const area = mods.reduce((a, mi) => a + (widths.get(mi) + P.gapX) * (heights.get(mi) + P.gapY), 0); + const maxRow = Math.max(...mods.map(mi => widths.get(mi)), Math.sqrt(area * aspect) * 1.05); + const rows = []; + for (const band of bands) { + let row = [], w = 0; + for (const mi of band) { + const sw = widths.get(mi); + if (row.length && w + P.gapX + sw > maxRow) { rows.push(row); row = []; w = 0; } + w += (row.length ? P.gapX : 0) + sw; row.push(mi); + } + if (row.length) rows.push(row); + } + const widthOf = r => r.reduce((a, mi) => a + widths.get(mi), 0) + P.gapX * (r.length - 1); + let contentW = Math.max(...rows.map(widthOf), 400); + // a row narrower than the world gives its spare width to its plates, the tallest the most + for (const r of rows) { + const slack = contentW - widthOf(r); if (slack < 120) continue; + const hs = r.reduce((a, mi) => a + heights.get(mi), 0); + for (const mi of r) { const w0 = widths.get(mi); widths.set(mi, Math.round(Math.min(w0 + slack * heights.get(mi) / hs, w0 * 3, 2600))); } + } + contentW = Math.max(...rows.map(widthOf), 400); + // the world strip of JS imports, on top: groups by file, flowed + const world = A.G.nodes.filter(n => n.world && !n.from); + const place = clusterOrder => { + const L = { width: 0, height: 0, plates: new Map(), rows: [], frames: new Map(), tokens: new Map(), clusters: [], strips: new Map(), reserved: [], worldGroups: [], gaps: { x: P.gapX, y: P.gapY } }; + let y = P.pad; + if (world.length) { + const byFile = new Map(); + for (const n of [...world].sort((a, b) => (a.file < b.file ? -1 : a.file > b.file ? 1 : a.line - b.line))) (byFile.get(n.file) ?? byFile.set(n.file, []).get(n.file)).push(n); + // at the detail zoom: the title, each file's label, its tokens + const KN = M.zoom, NH = M.namedH * KN, GX = M.gapX * KN, FL = 16 * KN; + const x0 = P.pad + 18, inner = contentW - 36; + let cx = x0, cy = y + 16 + 22 * KN, lh = 0; + for (const [file, ns] of byFile) { + const tw = ns.reduce((a, n) => a + sizeOf(n).w, 0) + GX * (ns.length - 1); + const gw = Math.min(inner, Math.max(tw, monoW(`from ${file}`, 11, M) * KN)); + if (cx > x0 && cx + gw > x0 + inner) { cx = x0; cy += lh + 18; lh = 0; } + let tx = cx, ty = cy + FL + 4, rowH = NH; + for (const n of ns) { const s = sizeOf(n); if (tx > cx && tx + s.w > cx + gw) { tx = cx; ty += NH + 12; rowH += NH + 12; } L.tokens.set(n.id, { id: n.id, x: tx, y: ty, w: Math.min(s.w, gw), h: s.h, role: "world", region: null, level: 2 }); tx += s.w + GX; } + L.worldGroups.push({ file, x: cx, y: cy, w: gw, h: FL + 4 + rowH, label: { x: cx, y: cy, w: gw, h: FL } }); + lh = Math.max(lh, FL + 4 + rowH); cx += gw + 30 * KN; + } + const h = cy + lh + 18 - y; + L.plates.set("world", { key: "world", x: P.pad, y, w: contentW, h, row: 0, band: -1 }); + L.rows.push({ top: y, bottom: y + h, keys: ["world"] }); + y += h + P.gapY; + } + for (const r of rows) { + const ms = r.map(mi => [mi, measure(mi, widths.get(mi), clusterOrder)]); + const h = Math.max(...ms.map(([, m]) => m.h)); + let x = P.pad + (contentW - widthOf(r)) / 2; + const ri = L.rows.length; + L.rows.push({ top: y, bottom: y + h, keys: r }); + for (const [mi, m] of ms) { + const w = widths.get(mi); + L.plates.set(mi, { key: mi, x, y, w, h: m.h, row: ri, band: A.modLevel(mi) }); + const sh = b => ({ ...b, x: b.x + x, y: b.y + y }); + for (const [id, f] of m.ctx.frames) L.frames.set(id, { ...sh(f), label: sh(f.label) }); + for (const [id, t] of m.ctx.tokens) L.tokens.set(id, sh(t)); + for (const c of m.ctx.clusters) L.clusters.push(sh(c)); + for (const [id, s] of m.ctx.strips) L.strips.set(id, sh(s)); + for (const v of m.ctx.reserved) L.reserved.push(sh(v)); + x += w + P.gapX; + } + y += h + P.gapY; + } + L.width = contentW + 2 * P.pad; + L.height = y - P.gapY + P.pad; + return L; + }; + // clusters face their consumers: a second pass orders each dense plate's clusters by where the plates using them are + const first = place(null); + const cx = mi => { const p = first.plates.get(mi); return p ? p.x + p.w / 2 : 1e6; }; + return place(() => u => (u === "core" ? -1e6 : u[0] === "m" ? cx(+u.slice(1)) : 1e6 - 1)); +} + +// ---- routes between plates ------------------------------------------------------------------------------------------ +// the x of each gap a route can climb through in a row: left of the first plate, between plates, right of the last +export function channels(row, L, g = L.gaps.x) { + const ps = row.keys.map(k => L.plates.get(k)).sort((a, b) => a.x - b.x); + const xs = [ps[0].x - g / 2]; + for (let i = 1; i < ps.length; i++) xs.push((ps[i - 1].x + ps[i - 1].w + ps[i].x) / 2); + xs.push(ps.at(-1).x + ps.at(-1).w + g / 2); + return xs; +} +/** + * Plans bundles between plates. `pairs`: keys `a>b` or `a>b|kind` (plate keys; a below b). Every bundle gets a port on + * a's top and one on b's bottom, spread so bundles don't share them, the gaps it climbs through in the rows between, + * and a lane in each gutter and gap it uses. Returns key → points [[x, y], …] from a's top to b's bottom. + * @param {Iterable} pairs + * @param {Layout} L + */ +export function planTrunks(pairs, L) { + const plan = new Map(); + const pk = k => (k === "world" ? "world" : +k); + const P = k => { const p = L.plates.get(k); return p && { l: p.x, r: p.x + p.w, t: p.y, b: p.y + p.h, row: p.row }; }; + const cx = p => (p.l + p.r) / 2, clamp = (v, a, b) => Math.max(a, Math.min(b, v)); + const ok = [...pairs].map(key => { const [a, b] = key.split("|")[0].split(">"); return { key, a, b }; }).filter(({ a, b }) => { const A = P(pk(a)), B = P(pk(b)); return A && B && A.row > B.row; }); + const outs = new Map(), ins = new Map(); + for (const r of ok) { (outs.get(r.a) ?? outs.set(r.a, []).get(r.a)).push(r); (ins.get(r.b) ?? ins.set(r.b, []).get(r.b)).push(r); } + const spread = (p, list, end) => { + const xs = new Map(), sorted = [...list].sort((x, y) => cx(P(pk(x[end]))) - cx(P(pk(y[end]))) || (x.key < y.key ? -1 : 1)); + const w = p.r - p.l, span = Math.min(w * .7, 22 * (sorted.length - 1)), x0 = cx(p) - span / 2; + sorted.forEach((r, i) => xs.set(r.key, sorted.length === 1 ? clamp(cx(P(pk(r[end]))), p.l + w * .25, p.r - w * .25) : x0 + (span * i) / (sorted.length - 1))); + return xs; + }; + const outX = new Map([...outs].map(([a, l]) => [a, spread(P(pk(a)), l, "b")])), inX = new Map([...ins].map(([b, l]) => [b, spread(P(pk(b)), l, "a")])); + const routes = ok.map(({ key, a, b }) => { + const A = P(pk(a)), B = P(pk(b)), xa = outX.get(a).get(key), xb = inX.get(b).get(key); + const steps = []; let x = xa; + for (let i = A.row - 1; i > B.row; i--) { + const ch = channels(L.rows[i], L); + let c = 0, cost = Infinity; + ch.forEach((cxv, j) => { const k = Math.abs(cxv - xb) + Math.abs(cxv - x) * .6; if (k < cost) { cost = k; c = j; } }); + steps.push({ row: i, ch: c, x: ch[c] }); x = ch[c]; + } + return { key, A, B, xa, xb, steps }; + }); + const lanes = new Map(), take = (slot, r) => (lanes.get(slot) ?? lanes.set(slot, []).get(slot)).push(r); + for (const r of routes) { take(`g${r.A.row}`, r); for (const s of r.steps) { take(`g${s.row}`, r); take(`c${s.row}:${s.ch}`, r); } } + const laneOf = new Map(); + for (const [slot, rs] of lanes) { rs.sort((p, q) => p.xb - q.xb || p.xa - q.xa || (p.key < q.key ? -1 : 1)); rs.forEach((r, i) => laneOf.set(`${slot}|${r.key}`, i - (rs.length - 1) / 2)); } + const lg = slot => clamp(L.gaps.y * .7 / Math.max(1, lanes.get(slot).length), 4, 12), lc = slot => clamp(L.gaps.x * .6 / Math.max(1, lanes.get(slot).length), 4, 12); + const gy = (i, r) => (L.rows[i - 1].bottom + L.rows[i].top) / 2 + laneOf.get(`g${i}|${r.key}`) * lg(`g${i}`); + for (const r of routes) { + const pts = [[r.xa, r.A.t], [r.xa, gy(r.A.row, r)]]; + for (const s of r.steps) { + const x = s.x + laneOf.get(`c${s.row}:${s.ch}|${r.key}`) * lc(`c${s.row}:${s.ch}`); + pts.push([x, gy(s.row + 1, r)], [x, gy(s.row, r)]); + } + pts.push([r.xb, pts.at(-1)[1]], [r.xb, r.B.b]); + plan.set(r.key, pts); + } + return plan; +} + +/** + * The zoom threshold between the two levels: the overview (1, module cards) and the detail (2, everything, drawn at + * `METRICS.zoom`). The detail comes in only once its smallest reading text (names, tags, view sites, view text) is + * `minText` px on screen or more; going back to the overview waits `hysteresis` lower, so a zoom resting near the + * threshold doesn't flicker. + */ +export function levelThresholds({ minText = 11, hysteresis = .05, metrics = METRICS } = {}) { + const at = px => Math.ceil((minText / px) * 100) / 100; + const up = { 1: at(Math.min(metrics.nameFont, metrics.tagFont, metrics.siteFont, metrics.stripFont) * metrics.zoom) }; + return { up, down: { 2: +(up[1] - hysteresis).toFixed(2) }, minText }; +} +/** The thresholds the page uses: overview → detail at .50; back below .45. */ +export const LEVELS = levelThresholds(); +/** The detail level for a zoom, with hysteresis: `prev` is the current level. */ +export function levelFor(s, prev = 2, LV = LEVELS) { + if (prev === 1) return s >= LV.up[1] ? 2 : 1; + return s < LV.down[2] ? 1 : 2; +} diff --git a/tooling/rx-map/live-protocol.mjs b/tooling/rx-map/live-protocol.mjs new file mode 100644 index 000000000..06de92d5a --- /dev/null +++ b/tooling/rx-map/live-protocol.mjs @@ -0,0 +1,16 @@ +export const LIVE_PATH = "/__rx/live"; +export const LIVE_READY = "rx:live:ready"; +export const LIVE_REQUEST = "rx:live:request"; +export const LIVE_RESPONSE = "rx:live:response"; +export const LIVE_TRACE = "rx:live:trace"; +export const MCP_PATH = "/__rx/mcp"; +export const LIVE_METHODS = ["status", "tail", "record", "state", "value", "why", "pending", "boundary_history"]; +export const ACT_METHODS = ["travel", "resume", "timeline"]; +export function matchesKey(record, key) { + const root = record.key ?? record.region; + if (key === undefined || key === root) return true; + if (!root || !key.startsWith(`${root}.`)) return false; + if (!record.path) return true; + const parts = key.slice(root.length + 1).split("."); + return record.path.split(".").slice(0, parts.length).every((p, i) => p === "*" || parts[i] === "*" || p === parts[i]); +} diff --git a/tooling/rx-map/live.d.ts b/tooling/rx-map/live.d.ts new file mode 100644 index 000000000..d372e8912 --- /dev/null +++ b/tooling/rx-map/live.d.ts @@ -0,0 +1,18 @@ +/** Registers a program's map graph (injected into dev entries by the RX Vite front end). */ +export function register(graph: unknown, options?: { hot?: unknown }): void; +/** Mounts the live map into `el`; returns a dispose function. */ +export function mount(el: HTMLElement): () => void; +/** + * A view without the map page (tests, other tools in the app's window): `listener` gets every host message and + * `post` takes view messages (`hello`, `snapshot?`, `travel`, `resume`). TRACE-CONTRACT §2–3. + */ +export function attach(listener: (msg: { source: "rx-map"; v: 1; type: string; [k: string]: unknown }) => void): { + post(msg: { type: string; [k: string]: unknown }): void; + detach(): void; + /** What the app displays now for each key (its newest live instance): TRACE-CONTRACT §5. */ + shown(keys?: string[]): Record; +}; +export function preview(value: unknown, max?: number, depth?: number): string; +export function mergeGraphs(list: unknown[]): unknown; +/** Attaches a view (a pop-out map window) to the bridge directly; `post` receives host → view messages. */ +export function connectView(post: (msg: unknown) => void): { send(msg: unknown): void; graph(): unknown; close(): void }; diff --git a/tooling/rx-map/live.mjs b/tooling/rx-map/live.mjs new file mode 100644 index 000000000..1a29904ea --- /dev/null +++ b/tooling/rx-map/live.mjs @@ -0,0 +1,1546 @@ +// @reactivescript/map/live: the map beside a running dev build. Browser only. +// +// A dev build's entry module calls `register(graph)` (the Vite front end adds the call). That sets +// `globalThis.__RX__ = { graphs, mount }`; a host (the devtools' Map view) calls `mount(el)` to draw the map of every +// registered program in an iframe and light it as Solid's flushes change the nodes the build named `rx:`. +// +// The recorder belongs to the app session, not to a particular map iframe. +import { pageHTML } from "./page.mjs"; +import { LIVE_READY, LIVE_REQUEST, LIVE_RESPONSE, LIVE_TRACE, matchesKey } from "./live-protocol.mjs"; + +const SOURCE = "rx-map"; +const RX = "rx:"; +// ---- what this Solid supports ------------------------------------------------------------------------------------- +// The bridge reads a few engine internals the attribution records don't carry yet (rx-vision/solid-asks.md lists them +// with the record each should become). Each read is feature-detected: the first time one is missing, the feature it +// serves is marked unsupported here (`globalThis.__RX__.solid`), said once in the console, and the bridge goes on +// without it. `true` = seen working, `false` = unsupported on this Solid, absent = not exercised yet. +const support = {}; +function supports(feature, ok, what) { + if (support[feature] !== undefined) return support[feature]; + support[feature] = !!ok; + (globalThis.__RX__ ??= {}).solid = support; + if (!ok) console.info(`[rx-map] ${what}: unsupported on this Solid`); + return support[feature]; +} +const probeOwners = new WeakSet(); +// Probe nodes are found by their owner (`_owner`/`_parent`, solid-asks #4); without it the list probes don't run. +const probeNode = node => !!node && (probeOwners.has(node._owner) || probeOwners.has(node._parent)); +const message = msg => ({ source: SOURCE, v: 1, ...msg }); +const graphs = []; +const mounts = new Set(); +const bridges = new Map(); +const hmrFlights = new WeakMap(); +let recording; +// Resolve before the entry calls register: its first render can start flights +// in the same turn, before a lazy attribution import would finish. +const engine = await Promise.all([import("solid-js"), import("solid-js/attribution")]).catch(() => []); +// Previews read app state from wherever the bridge runs (an action's click handler, a flush record): untrack, so +// Solid's strict-read check (STRICT_READ_UNTRACKED) doesn't count the bridge's reads as the app's; no owner, so +// nothing the read makes is owned by the app's scope. +const untracked = fn => { + const solid = engine[0]; + const run = solid?.untrack ? () => solid.untrack(fn) : fn; + return solid?.runWithOwner ? solid.runWithOwner(null, run) : run(); +}; +const errorPreview = error => untracked(() => preview(error, 200)); +function previews(value) { + const out = { preview: preview(value) }; + if (value !== null && typeof value === "object" && !(value instanceof Error)) { + const full = preview(value, 2000, 4); + if (full.length > out.preview.length) out.full = full; + } + return out; +} +function inspect(key, format = previews, instance) { + const entries = globalThis.__RX_NODES__?.get(key); + if (!entries?.size) return; + const read = instance === undefined ? [...entries].at(-1) : [...entries].find(r => r.instance === instance); + try { if (read) return { ...read(format), instance: read.instance, ownerPath: read.ownerPath }; } catch { /* instrumentation is best effort */ } +} +const identity = ({ key, instance }) => instance === undefined ? key : `${key}~i${instance}`; +const runtimeNodes = new Map(); +function observeNode(name, node) { + const key = keyOf(name); + if (key && node) { + const id = identity({ key, instance: instanceOf(name) }); + const refs = runtimeNodes.get(id) ?? new Set(); + for (const ref of refs) if (!ref.deref()) refs.delete(ref); else if (ref.deref() === node) return; + refs.add(new WeakRef(node)); + runtimeNodes.set(id, refs); + } +} +const engineNodes = id => [...(runtimeNodes.get(id) ?? [])].map(r => r.deref()).filter(Boolean); + +export const liveHmr = { + register, + hmr: edit => getRecorder().hmr(edit), + replace: (...args) => getRecorder().replaceModule(...args), +}; + +/** Adds a program's graph (from `@reactivescript/map/graph`'s `buildGraph`). Re-registering its entry replaces it. */ +export function register(graph, { hot, replacement = false } = {}) { + getRecorder(); + if (hot) connect(hot); + // Models are dependency-first: shared imports do not identify the entry. + const entry = graph?.modules?.at(-1); + const i = graphs.findIndex(g => g.modules?.at(-1) === entry); + if (i >= 0) { + graphs[i] = graph; + } else graphs.push(graph); + const rx = (globalThis.__RX__ ??= {}); + rx.graphs = graphs; + rx.mount = mount; + rx.attach = attach; + // Attached maps get the graph from the plan/apply messages. Don't reload + // their iframe between apply and done. + if (!replacement) for (const m of mounts) m.load(); +} + +// A view's message (TRACE-CONTRACT §3). Answers to `hello` and `snapshot?` go to the asker; `step`, `resume` and +// `travel-denied` go to every view, since they all show the one app. +function receiveFromView(data, reply) { + const recorder = getRecorder(); + if (data.type === "hello") { + reply(recorder.snapshot()); + reply(recorder.timeline(wantsInternals(data))); + } else if (data.type === "snapshot?") reply(recorder.snapshot()); + else if (data.type === "travel") recorder.travel(data.to); + else if (data.type === "resume") recorder.resume(); +} +const wantsInternals = data => Array.isArray(data.want) && data.want.includes("internals"); + +/** + * A view without the map page: `listener` gets every host message (`{source: "rx-map", v: 1, ...}`) and `post` takes + * view messages, as the map's iframe would send them. For tests and other tools in the app's window. + */ +export function attach(listener) { + const recorder = getRecorder(); + let internals = false; + const deliver = (msg, raw) => listener(internals && raw ? raw : msg); + recorder.listeners.add(deliver); + return { + post(msg) { + if (!msg || typeof msg !== "object") return; + if (msg.type === "hello") internals = wantsInternals(msg); + receiveFromView(msg, deliver); + }, + detach() { recorder.listeners.delete(deliver); }, + /** What the app displays now: `{ [key]: {preview} | {error} }` (TRACE-CONTRACT §5). */ + shown(keys) { return recorder.shown(keys); }, + }; +} + +/** Draws the map into `el`, live. Returns the dispose. */ +export function mount(el) { + const iframe = document.createElement("iframe"); + iframe.title = "rx-map"; + iframe.style.cssText = "display:block;width:100%;height:100%;border:0"; + el.setAttribute("data-rx-map", ""); // input here stays live while the app is read-only (viewing) + let ready = false, internals = false; + const post = msg => { + if (msg && ready && iframe.contentWindow) iframe.contentWindow.postMessage(msg, "*"); + }; + const forward = (msg, raw) => post(internals && raw ? raw : msg); + const receive = ({ source, data }) => { + if (source !== iframe.contentWindow || data?.source !== SOURCE || data.v !== 1) return; + if (data.type === "hello") { + ready = true; + internals = wantsInternals(data); + } + receiveFromView(data, post); + }; + window.addEventListener("message", receive); + const m = { + load() { + ready = false; + iframe.srcdoc = pageHTML(mergeGraphs(graphs), { live: true }); + }, + }; + m.load(); + el.append(iframe); + mounts.add(m); + getRecorder().listeners.add(forward); + return () => { + if (!mounts.delete(m)) return; + recording?.listeners.delete(forward); + window.removeEventListener("message", receive); + iframe.remove(); + }; +} + +function connect(hot) { + if (bridges.has(hot)) return; + const recorder = getRecorder(); + const request = ({ id, method, params } = {}) => { + try { + const result = recorder.query(method, params); + if (result instanceof Promise) result.then( + result => hot.send(LIVE_RESPONSE, { id, result }), + e => hot.send(LIVE_RESPONSE, { id, error: e.message })); + else hot.send(LIVE_RESPONSE, { id, result }); + } + catch (e) { hot.send(LIVE_RESPONSE, { id, error: e.message }); } + }; + const ready = () => hot.send(LIVE_READY); + bridges.set(hot, request); + hot.on(LIVE_REQUEST, request); + const trace = record => hot.send(LIVE_TRACE, record); + recorder.traces.add(trace); + hot.on("vite:ws:connect", ready); + const stop = () => { + if (!bridges.delete(hot)) return; + hot.off?.(LIVE_REQUEST, request); + recorder.traces.delete(trace); + hot.off?.("vite:ws:connect", ready); + }; + hot.dispose?.(stop); + hot.prune?.(stop); + ready(); +} + +function getRecorder() { + if (recording) return recording; + const size = 2000, ring = new Array(size), listeners = new Set(), traces = new Set(); + // The timeline: one step per flush, `capacity` of them (TRACE-CONTRACT §4). Beside each step, the engine nodes it + // changed and what each showed before, which is what travel pins (Solid's openView). + const capacity = Math.max(1, Math.floor(globalThis.__RX_TIMELINE_CAPACITY__ ?? 2000)); + let guessesNamed = false; // this Solid's records name the store properties a guess moved + const steps = new Array(capacity), raws = new Array(capacity), guesses = new Array(capacity), internals = new Array(capacity); + const carrierOnly = new Array(capacity), rewrites = new Array(capacity), carrierKeys = new Array(capacity); + // Does this Solid's view read a list's unnoded keys (mapArray rows) through the pinned container (solid-view + // 980f5b4c5)? Probed once, at the first travel; until then, and on an older Solid, wholesale rewrites are inexact. + let listsThroughPin = null, guessedListsThroughPin = null, probing = false; + let probingGuess = false; + // A private list, prepended once and read through mapArray, then shown under a view at its first frame: with the + // fix the view shows "a", without it the present "b". Synchronous, outside any flush (travel is called from a + // message handler); its flushes are not history. + function probeListPins(openView) { + const s = engine[0], records = s?.OBSERVE?.records; + if (!s?.createStore || !s.mapArray || !s.createRoot || !s.createRenderEffect || !records?.subscribe) return false; + probing = true; + let dispose, shown, off; + const pins = new Map(); + try { + off = records.subscribe("flush", (_e, live) => { + for (const c of live?.changes ?? []) if (c.node && !pins.has(c.node)) pins.set(c.node, c.prev); + }, { bodies: true }); + const [list, setList] = s.createStore([{ l: "a" }]); + s.createRoot(d => { + dispose = d; + const rows = s.mapArray(() => list, r => () => (typeof r === "function" ? r() : r).l); + s.createRenderEffect(() => rows().map(f => f()).join(","), v => { shown = v; }); + }); + s.flush(); + pins.clear(); + setList(l => [{ l: "b" }, ...l]); + s.flush(); + if (shown !== "b,a") return false; + const v = openView(); + try { + v.show(pins); + return shown === "a"; + } finally { v.resume(); } + } catch { return false; } + finally { + off?.(); + try { dispose?.(); s.flush(); } catch {} + probing = false; + } + } + // 49b25a45c also rewinds a list an optimistic layer guessed over across an + // await. Probe that separately: the plain-list fix shipped first. + async function probeGuessedListPins(openView) { + const s = engine[0]; + if (!s?.createOptimisticStore || !s.action) return false; + let dispose, off, shown; + const pins = new Map(); + try { + let guess, write, release; + const gate = new Promise(resolve => { release = resolve; }); + s.createRoot(d => { + dispose = d; + probeOwners.add(s.getOwner()); + const [truth, setTruth] = s.createStore([{ id: "a" }]); + const [slot] = s.createSignal(truth); + const [list, setList] = s.createOptimisticStore(() => slot(), []); + const rows = s.mapArray(() => list, row => () => (typeof row === "function" ? row() : row).id); + s.createRenderEffect(() => rows().map(f => f()).join(","), v => { shown = v; }); + write = () => setTruth(r => [{ id: "b" }, ...r]); + guess = s.action(function* () { + setList(r => r.filter(x => x.id !== "b")); + yield gate; + setTruth(r => r.filter(x => x.id !== "b")); + }); + }); + s.flush(); + write(); + s.flush(); + if (shown !== "b,a") return false; + off = s.OBSERVE.records.subscribe("flush", (_e, live) => { + for (const c of live?.changes ?? []) + if (probeNode(c.node) && !pins.has(c.node)) pins.set(c.node, c.prev); + }, { bodies: true }); + const done = guess(); + s.flush(); + const guessed = shown === "a"; + release(); + await done; + s.flush(); + if (!guessed || shown !== "a" || !pins.size) return false; + const v = openView(); + try { + v.show(pins); + return shown === "b,a"; + } finally { v.resume(); } + } catch { return false; } + finally { + off?.(); + try { dispose?.(); s.flush(); } catch {} + } + } + const base = new Map(); // previews as of just before the oldest step kept + const latest = new Map(), last = new Map(), flights = new Map(), runs = new Map(), boundaries = new Map(); + const held = new Map(), writes = new Map(), dirty = new Set(), wroteSinceFlush = new Set(); + const callbackWrites = new Map(); + const start = performance.now(); + let seq = 0, flushes = 0; + // Travel: the open view, the seq it shows, and a resume whose landing waits on async work. + let view = null, viewing = null, landing = null; + let replacing = null; + const hmrAnswers = new Map(); + const continuity = new WeakMap(); + const instanceFrame = keys => new Map([...keys].map(key => [key, [...(globalThis.__RX_NODES__?.get(key) ?? [])]])); + const reincarnations = new WeakMap(); + const sourceAt = key => { + const entries = globalThis.__RX_NODES__?.get(key); + return [...(entries ?? [])].at(-1); + }; + function valueFrame(keys) { + const out = new Map(); + for (const key of keys) { + const entry = sourceAt(key); + const shown = inspect(key); + if (!shown) continue; + const value = entry?.hmrValue?.(); + out.set(key, { + entry, value, + state: shown.error != null ? ERR + errorPreview(shown.error) : shown.value?.preview, + }); + } + return out; + } + const hmr = edit => send({ ...edit, type: "hmr", at: performance.now() }); + async function replaceModule(edit, swap, installed) { + const { id, graph, plan } = edit; + const openView = engine[1]?.openView; + if (!supports("openView", typeof openView === "function", "keyed replacement (openView)")) { + hmr({ phase: "failed", id, error: "Keyed replacement is unsupported on this Solid build", fallback: "reload" }); + globalThis.location.reload(); + return; + } + const previous = graphs.find(g => g.modules.at(-1) === graph.modules.at(-1)); + const keys = new Set([...previous.nodes, ...graph.nodes].filter(n => n.key).map(n => n.key)); + // Don't seed from a historical view or a proposal currently hidden by a hold. + if (view || queued !== null) resume(); + const deadline = performance.now() + 3000; + while (landing && performance.now() < deadline) await new Promise(resolve => setTimeout(resolve, 16)); + if (landing) { + hmr({ phase: "failed", id, error: "Timed out waiting for the time-travel landing", fallback: "none" }); + return; + } + const solid = engine[0]; + solid.flush(); + const before = valueFrame(keys); + const oldInstances = instanceFrame(keys); + const moved = new Map(plan.moved.map(({ from, to }) => [to, from])); + const nodeByKey = new Map(graph.nodes.map(n => [n.key, n])); + replacing = { id }; + hmr({ phase: "apply", id }); + let transaction; + let fallback; + try { + // Same Solid seam as travel. There are no historical pins here: branch + // closes the replacement hold and commits its new owners to live. + transaction = openView({ effects: true }); + fallback = swap(() => { + transaction?.branch(); + solid.flush(); + }); + installed(); + } catch (e) { + try { transaction?.resume(); } catch { /* the reload recovers the root */ } + replacing = null; + hmr({ phase: "failed", id, error: errorPreview(e), fallback: "reload" }); + globalThis.location.reload(); + return; + } + // New flights will be recorded separately; give their landings the HMR origin. + const after = valueFrame(keys); + for (const key of [...plan.rerun, ...plan.reset, ...plan.added]) + if ([...flights.values()].some(f => f.key === key) || inspect(key)?.pending) hmrAnswers.set(key, `hmr ${id}`); + const changes = [], raw = [], inexact = new Set(); + for (const key of keys) { + const old = before.get(key), next = after.get(key); + const predecessor = before.get(moved.get(key) ?? key); + if (predecessor?.entry?.node && next?.entry?.node && predecessor.entry.node !== next.entry.node) { + reincarnations.set(predecessor.entry.node, next.entry.node); + if (predecessor.value && Object.hasOwn(predecessor.value, "value") && (!next.entry.node._fn || next.entry.node._x?._q)) + raw.push({ node: next.entry.node, prev: predecessor.value.value }); + } + // openView cannot pin a synchronous computation. A changed expression + // can make new code disagree with an old step even with every input pinned. + if ((nodeByKey.get(key)?.kind === "eq" && plan.reasons[key] === "expr-changed") + || (old?.entry && !next?.entry?.node) || (!next?.entry && old?.state !== next?.state)) + inexact.add(key); + if (old?.state === next?.state) continue; + const change = { key, name: RX + key, ...locate(key), origin: `hmr ${id}` }; + if (old?.state !== undefined) old.state.startsWith(ERR) ? change.prevError = old.state.slice(ERR.length) : change.prev = old.state; + if (next?.state !== undefined) next.state.startsWith(ERR) ? change.error = next.state.slice(ERR.length) : Object.assign(change, inspect(key)?.value); + changes.push(change); + } + dirty.clear(); + replacing = null; + // Start a timeline seam even if the edit only changed the view, not its values. + addStep(performance.now(), changes, raw, [], false, `hmr ${id}`, [...inexact]); + // Async remounts record their own flushes while the carry result settles. + try { + fallback = await fallback; + } catch (e) { + hmr({ phase: "failed", id, error: errorPreview(e), fallback: "none" }); + queueReconcile(); + return; + } + for (const [key, all] of instanceFrame(keys)) { + const old = oldInstances.get(moved.get(key) ?? key) ?? []; + const gone = old.filter(read => !all.includes(read)); + const born = all.filter(read => !old.includes(read)); + for (const read of born) { + // Carry provides the exact predecessor. For resets, only infer a + // replacement when there is one candidate in this owner path. + const candidates = gone.filter(r => JSON.stringify(r.ownerPath) === JSON.stringify(read.ownerPath)); + const from = read.replaces ?? (born.length === 1 && candidates.length === 1 ? candidates[0].instance : undefined); + if (!from) continue; + const status = fallback.has(key) ? "reset" : read.carryStatus ?? (nodeByKey.get(key)?.question ? "re-asked" : "reset"); + continuity.set(read, { from, to: read.instance, status }); + } + } + const changed = new Set([...plan.reset, ...plan.rerun, ...plan.added]); + hmr({ phase: "done", id, changes: changes.filter(c => changed.has(c.key)), + ...(fallback.size ? { fallback: "refresh", uncarried: [...fallback.keys()].sort(), uncarriedReasons: Object.fromEntries(fallback) } : {}) }); + queueReconcile(); + } + const shownLast = new WeakMap(); // engine node → the value last recorded for it (a landing's records say "pin") + const locate = key => { + for (const graph of graphs) { + const n = graph.nodes.find(n => n.key === key); + if (n) return { file: n.file, line: n.line }; + } + return {}; + }; + const importOrigin = key => { + for (const g of graphs) { + const target = g.nodes.find(n => n.key === key); + if (!target) continue; + const seen = new Set(); + const find = id => { + if (seen.has(id)) return; + seen.add(id); + for (const e of g.edges) { + if (e.type === "call" && e.from === id) { + const js = g.nodes.find(n => n.id === e.to && (n.jsFrom || n.from)); + if (js) return `JS call ${js.name} from ${js.jsFrom ?? js.from}`; + } + if (e.type === "read" && e.to === id && e.field) { + const origin = find(e.from); + if (origin) return origin; + } + } + }; + const origin = find(target.id); + if (origin) return origin; + } + }; + const recent = (limit = size, since = 0) => { + const records = []; + for (let i = Math.max(0, since, seq - limit); i < seq; i++) records.push(ring[i % size]); + return records; + }; + const addRecord = (msg, internal) => { + const { source, v, ...record } = msg; + for (const trace of traces) trace(internal?.length ? { ...record, changes: [...record.changes, ...internal] } : { ...record }); + if (record.type === "flush" && !record.changes.length && !record.origin) return; + record.seq = ++seq; + ring[(seq - 1) % size] = record; + return record; + }; + const publish = (msg, raw) => { for (const post of listeners) post(msg && message(msg), raw && message(raw)); }; + const flightKeys = () => { + const keys = new Map(); + for (const r of flights.values()) if (!keys.has(r.key) || keys.get(r.key).since > r.since) keys.set(r.key, r); + return keys; + }; + function blockersFor(write) { + const solid = engine[0], dev = solid?.DEV; + const found = new Map(); + const action = runs.get(write.run); + if (action) found.set(action, { ...action, type: "action" }); + if (!dev?.getObservers || !dev.getSources) return [...found.values()]; + const byNode = new Map([...flights.values()].map(f => [f.node, f])); + const label = node => keyOf(node?._name) ?? node?._name ?? solid.OBSERVE?.ownerPath?.(node)?.at(-1) ?? "live reader"; + const roots = engineNodes(identity(write)); + // A reader can hold a write if it also reads an in-flight value. + const readers = new Set(roots); + for (const reader of readers) { + if (readers.size > 256) break; + for (const next of dev.getObservers(reader)) readers.add(next); + if (roots.includes(reader)) continue; + const via = [...(solid.OBSERVE?.ownerPath?.(reader) ?? []), label(reader)]; + const upstream = new Set([reader]); + for (const source of upstream) { + if (upstream.size > 256) break; + const f = byNode.get(source); + if (f && !found.has(f)) { + const { node: _node, ...flight } = f; + found.set(f, { ...flight, type: "flight", via }); + } + for (const dep of dev.getSources(source)) upstream.add(dep); + } + } + return [...found.values()]; + } + function reconcileWrites(at) { + for (const [id, write] of writes) { + const { key, instance } = write; + const now = inspect(key, () => undefined, instance); + const old = held.get(id); + if (now?.held) { + const blockers = blockersFor(write), by = [...new Set(blockers.map(b => b.key))]; + if (!old || JSON.stringify(blockers) !== JSON.stringify(old.blockers)) { + const item = { key, instance, ownerPath: now.ownerPath, by, blockers, since: old?.since ?? at }; + held.set(id, item); + send({ type: "held", ...item, at }); + } + } else { + if (held.delete(id)) send({ type: "released", key, instance, at }); + } + } + } + // A key touched by an instance being made or disposed, a flight, a write or an error: the timeline's state for it + // must be the state of the instance alive now (a component-scoped key outlives its instances: a remounted + // component's first answer is no engine change, and a disposed one's last value or error is not the app's). + const headState = new Map(), registered = new Set(); + function reconcileErrors(changes) { + const expected = new Map(); + for (const c of changes) if (c.key) expected.set(identity(c), stateOf(c)); + for (const key of dirty) { + // a name the RX registry never had (a named Solid node, an older runtime) is the engine record's alone + if (!globalThis.__RX_NODES__?.has(key) && !registered.has(key)) continue; + const instances = instanceList(key); + for (const instance of instances.length ? instances : [undefined]) { + const id = identity({ key, instance }), read = inspect(key, previews, instance); + const now = read?.error != null ? ERR + errorPreview(read.error) : read?.value?.preview; + const was = expected.has(id) ? expected.get(id) : liveHead.get(id); + liveHead.set(id, now); + if (now === was) continue; + changes.push({ key, instance, ownerPath: read?.ownerPath, name: RX + id, + ...(read?.error != null ? { error: errorPreview(read.error) } : read?.value) }); + } + } + dirty.clear(); + return changes; + } + const withInternals = (step, internal) => internal.length ? { ...step, changes: [...step.changes, ...internal] } : step; + const publishStep = (step, internal) => publish({ type: "flush", ...step }, { type: "flush", ...withInternals(step, internal) }); + const addStep = (at, changes, raw, internal, quiet = false, origin, inexact = []) => { + const i = flushes % capacity; + // the step falling out of the ring folds into the base the others replay from + if (flushes >= capacity) applyPreviews(base, steps[i].changes); + const step = { seq: ++flushes, at, changes, ...(origin ? { origin } : {}) }; + steps[i] = step; + raws[i] = raw; + if (flushes % 100 === 0) sweepDisposed(); + internals[i] = internal; + // A store guess shows through the store's guess carrier (`.$guess`). Solid with the store-guess record + // (f9ee22ade) also lists the property and presence nodes it moved, which travel pins like any other; an older + // Solid lists only the carrier, and pins can't take the store back past that guess. + const carriers = changes.filter(c => c.key && c.name?.endsWith(".$guess")).map(c => c.key); + const wasNamed = guessesNamed; + for (const k of carriers) if (changes.some(c => c.key === k && c.path !== undefined && !c.name?.endsWith(".$guess"))) guessesNamed = true; + // A list whose length changed with no index entry beside it was rewritten wholesale (`list := [x, ...list]`): Solid + // lists only its container and length, and under a view a list's items still come from the store's backing + // (openView known gap), so its rows can't be taken back past this step. + const rowless = changes.filter(c => c.key && c.path === "length" && !changes.some(d => d.key === c.key && /^\d+(\.|$)/.test(d.path ?? ""))).map(c => c.key); + guesses[i] = [...(guessesNamed ? [] : carriers), ...inexact]; + rewrites[i] = rowless; + carrierKeys[i] = carriers; + if (!wasNamed && guessesNamed) for (let s = oldest(); s < flushes; s++) { + // (the first named guess tells this Solid apart: earlier carrier-only entries were not gaps) + const j = (s - 1) % capacity; + guesses[j] = (guesses[j] ?? []).filter(k => !carrierOnly[j]?.includes(k)); + } + carrierOnly[i] = guessesNamed ? [] : carriers; + applyPreviews(headState, changes); + const record = addRecord({ type: "flush", at, changes, ...(origin ? { origin } : {}) }, internal); + for (const c of changes) if (c.key) { + if (c.preview !== undefined) latest.set(c.key, c); + last.set(c.key, { change: c, record }); + if (c.instance !== undefined) last.set(identity(c), { change: c, record }); + } + if (!quiet) publishStep(step, internal); + return step; + }; + const send = (msg, flightId, since, origin) => { + if (msg.type === "flush") { + // Under a view nothing the program does shows, and the view's own pins are not history. + if (view || probing || replacing) return; + if (landing) return void landing.records.push(msg); + const raw = recordRaw(msg.raw); + const all = reconcileErrors(msg.changes); + const errors = new Map(all.filter(c => c.key && c.error !== undefined).map(c => [identity(c), c])); + const internal = all.filter(c => !c.key); + const changes = all.filter(c => c.key && (!errors.has(identity(c)) || errors.get(identity(c)) === c)).map(({ before, ...c }) => { + const prev = last.get(identity(c))?.change.preview ?? before; + const id = identity(c); + // a value written in this flush (an action's :=, a guess) came from that write, not from an answer: no "JS call" + const js = wroteSinceFlush.has(id) ? undefined : importOrigin(c.key); + const callback = callbackWrites.get(id); + const cause = callback ? `RX callback from ${callback}` : c.origin; + const origin = hmrAnswers.get(c.key) ?? (js ? cause ? `${js} ← ${cause}` : js : cause); + return { ...c, ...(origin ? { origin } : {}), ...locate(c.key), ...(prev !== undefined ? { prev } : {}) }; + }); + for (const c of changes) callbackWrites.delete(identity(c)); + wroteSinceFlush.clear(); + // Keyless engine nodes are still part of the app frame, even when + // hidden from the map. Keep their raw bodies for openView. + for (const c of changes) if (!inspect(c.key)?.pending && ![...flights.values()].some(f => f.key === c.key)) hmrAnswers.delete(c.key); + if (changes.length || internal.length || raw.length) addStep(msg.at, changes, raw, internal, false, + msg.origin ?? changes.find(c => c.origin?.startsWith("hmr "))?.origin); + } else if (msg.type === "flight") { + const at = performance.now(); + const before = [...flights.values()].some(r => r.key === msg.key); + if (msg.state === "start") flights.set(flightId, { key: msg.key, id: flightId, instance: msg.instance, ownerPath: msg.ownerPath, + since: since ?? at, origin, node: msg.node, ...locate(msg.key) }); + else if (!flights.delete(flightId)) return; + dirty.add(msg.key); + const after = [...flights.values()].some(r => r.key === msg.key); + const { node: _node, ...event } = msg; + if (msg.instance !== undefined || before !== after) addRecord({ ...event, id: flightId, at, origin, ...locate(msg.key) }); + if (before !== after) publish({ ...event, at, ...(origin ? { origin } : {}) }); + } else { + addRecord({ ...msg, ...locate(msg.key) }); + publish(msg); + } + }; + listen((msg, ...args) => { + send(msg, ...args); + queueReconcile(); + }, key => dirty.add(key), () => replacing && `hmr ${replacing.id}`); + // The compiler supplies the resolved region ID. Keep graph path numbering (including #n) + // in the graph builder, rather than deriving a second path by walking the JSX. + const regionRefs = () => new Map(graphs.flatMap(g => g.regions + .filter(r => r.kind === "loading" || r.kind === "errored") + .map(r => [`${g.modules[r.mod]}|${r.id.split(":r").at(-1)}`, r.key]))); + function boundaryState(ref, region) { + const instances = [...(globalThis.__RX_BOUNDARIES__?.get(ref) ?? [])]; + const active = instances.findLast(b => b.state !== "ok"); + return { region, state: active?.state ?? "ok", ...(active?.state === "error" ? { error: errorPreview(active.error) } : {}) }; + } + function allBoundaries() { + const states = [], hiddenBy = []; + for (const [ref, key] of regionRefs()) { + const b = boundaryState(ref, key); + states.push(b); + if (b.state !== "ok" && [...globalThis.__RX_BOUNDARIES__.get(ref)].every(x => x.state !== "ok")) + hiddenBy.push(`${key}/`); + } + // Regions denote the boundary's content; its own fallback is outside + // that region. A retained inner fallback is not displayed while an + // enclosing boundary has swapped the content out. + return states.map(b => hiddenBy.some(prefix => b.region.startsWith(prefix)) ? { region: b.region, state: "ok" } : b); + } + // Fallback cleanup can happen in the same turn as a replacement fallback mounts. + let boundariesQueued = false; + let reconcileQueued = false; + const queueReconcile = () => { + if (reconcileQueued) return; + reconcileQueued = true; + queueMicrotask(() => { + reconcileQueued = false; + const at = performance.now(); + if (!view && !landing) reconcileWrites(at); + send({ type: "flush", at, changes: [] }); + }); + }; + const liveHead = new Map(); + const trace = event => { + if (event.type === "node") registered.add(event.key); + if (event.type === "write" || event.type === "node") { + if (event.type === "write") { + writes.set(identity(event), event); + wroteSinceFlush.add(identity(event)); + if (event.origin) callbackWrites.set(identity(event), event.origin); + else callbackWrites.delete(identity(event)); + } + dirty.add(event.key); + queueReconcile(); + return; + } + if (event.type === "dispose") { + queueSweep(); + const id = identity(event); + runtimeNodes.delete(id); + last.delete(id); + liveHead.delete(id); + writes.delete(id); + callbackWrites.delete(id); + if (held.delete(id)) send({ type: "released", key: event.key, instance: event.instance, at: performance.now() }); + for (const [id, f] of flights) if (f.key === event.key && f.instance === event.instance) + send({ type: "flight", key: event.key, instance: event.instance, state: "abandon" }, id); + if (globalThis.__RX_NODES__?.has(event.key)) { dirty.add(event.key); queueReconcile(); return; } + latest.delete(event.key); + queueReconcile(); + return; + } + if (event.type === "boundary") { + if (boundariesQueued) return; + boundariesQueued = true; + queueMicrotask(() => { + boundariesQueued = false; + if (globalThis.__RX_TRACE__ !== trace) return; + for (const b of allBoundaries()) { + const prev = boundaries.get(b.region); + if ((prev?.state ?? "ok") === b.state && prev?.error === b.error) continue; + boundaries.set(b.region, b); + send({ type: "boundary", ...b, at: performance.now() }); + } + }); + return; + } + const { type, key, id, state, args, error, ownerPath } = event; + const at = performance.now(); + const msg = { type, key, id, state, at, ownerPath }; + if (state === "start") { + msg.args = untracked(() => preview(args)); + runs.set(id, { key, id, ownerPath, since: at }); + } else { + runs.delete(id); + if (state === "error") msg.error = errorPreview(error); + } + send(msg); + queueReconcile(); + }; + globalThis.__RX_TRACE__ = trace; + // Compare the observed cause, not the error text: another instance can fail + // with an identical message. This describes the current instrumented view, + // not whether the error ever reached a boundary. + function tripsBoundary(error) { + for (const instances of globalThis.__RX_BOUNDARIES__?.values() ?? []) { + for (const b of instances) if (b.state === "error" && b.error === error) return true; + } + return false; + } + function current(key, flight, instance, field) { + const format = field ? value => previews(field.split(".").reduce((v, part) => v?.[part], value)) : previews; + const now = inspect(key, format, instance); + const read = [...(globalThis.__RX_NODES__?.get(key) ?? [])].find(r => r.instance === now?.instance); + if (now) return { key: field ? `${key}.${field}` : key, ...(field ? { root: key, field } : {}), + instance: now.instance, continuity: read && continuity.get(read), ownerPath: now.ownerPath, ...now.value, + ...(now.error ? { error: errorPreview(now.error), + ...(globalThis.__RX_BOUNDARIES__ && !tripsBoundary(now.error) ? { failedUntripped: true } : {}) } : {}), + pending: !!(!now.error && (now.pending || (now.instance === undefined && flight))), + ...(!now.error && flight && (now.instance === undefined || flight.instance === now.instance) ? { since: flight.since } : {}), ...locate(key) }; + const old = latest.get(key); + // Support named Solid nodes (and older RX runtimes), but never resurrect disposed registry nodes. + const legacy = !globalThis.__RX_NODES__ && old; + return { key: field ? `${key}.${field}` : key, instance, ...((!legacy || field) && !flight ? { observation: "unobserved" } : {}), ...(legacy && !field ? { preview: old.preview, full: old.full } : {}), pending: !!flight, + ...(flight ? { since: flight.since } : {}), ...locate(key) }; + } + const instanceList = key => [...(globalThis.__RX_NODES__?.get(key) ?? [])].map(inspect => inspect.instance).filter(i => i !== undefined); + function untripped(key) { + const active = new Map(allBoundaries().map(b => [b.region, b.state])); + for (const g of graphs) { + const source = g.nodes.find(n => n.key === key); + if (!source) continue; + const nodes = new Map(g.nodes.map(n => [n.id, n])); + const regions = new Map(g.regions.map(r => [r.id, r])); + const parents = function* (id) { + for (let r = regions.get(id); r; r = regions.get(r.parent)) yield r; + }; + const readers = g.edges.filter(e => e.from === source.id && e.type === "read" && e.mode === "tracked" && !e.probe); + const guarded = new Map(); + for (const e of readers) { + const reader = nodes.get(e.to); + const ancestors = [...parents(reader?.region)]; + const boundary = ancestors.find(r => r.kind === "errored"); + if (!boundary || active.get(boundary.key) !== "ok") continue; + const guards = guarded.get(boundary.key) ?? []; + guarded.set(boundary.key, guards); + const closed = ancestors.slice(0, ancestors.indexOf(boundary)).find(r => { + const name = /^if ([\w$]+)$/.exec(r.head?.text)?.[1]; + if (r.kind !== "then" || !name) return false; + const scope = [...parents(r.parent)].map(p => p.id); + const candidates = g.nodes.filter(n => n.name === name && scope.includes(n.region)); + if (candidates.length !== 1) return false; + const entries = [...(globalThis.__RX_NODES__?.get(candidates[0].key) ?? [])]; + return entries.length > 0 && entries.every(read => { + try { return read(Boolean).value === false; } catch { return false; } + }); + }); + guards.push(closed?.head.text.slice(3)); + } + for (const [boundary, guards] of guarded) if (guards.length && guards.every(Boolean)) { + return { boundary, guards: [...new Set(guards)] }; + } + } + } + const flightFor = (key, instance) => instance === undefined ? flightKeys().get(key) + : [...flights.values()].find(f => f.key === key && f.instance === instance); + function pending() { + return states().filter(s => s.pending).map(({ key, since, file, line }) => ({ key, since, file, line })); + } + function states() { + const flying = flightKeys(), keys = new Set([...flying.keys(), ...(globalThis.__RX_NODES__?.keys() ?? latest.keys())]); + return [...keys].flatMap(key => { + const instances = instanceList(key); + return instances.length ? instances.map(i => current(key, flightFor(key, i), i)) : [current(key, flying.get(key))]; + }); + } + function snapshot() { + const all = states(), at = performance.now(); + return message({ type: "snapshot", at, + values: all.filter(s => s.preview !== undefined || s.error || s.pending).map(({ key, preview, full, error, pending }) => ({ + key, preview, full, ...(error ? { error } : {}), ...(pending ? { pending: true } : {}) })), + flights: all.filter(s => s.pending && s.since !== undefined).map(({ key, since }) => ({ key, since })), + boundaries: allBoundaries(), runs: [...runs.values()], held: [...held.values()] }); + } + function timeline(showInternals = false) { + const history = []; + for (let i = Math.max(0, flushes - capacity); i < flushes; i++) { + const slot = i % capacity; + history.push(showInternals ? withInternals(steps[slot], internals[slot]) : steps[slot]); + } + return message({ type: "timeline", head: flushes, viewing, steps: history, capacity }); + } + + // ---- time travel (TRACE-CONTRACT §2 "Time travel") ---------------------------------------------------------------- + // A step's raw changes are the engine's own (`flush` records with bodies): the node and what it showed before. + // Showing seq n pins every node changed after n at what it showed before its first change after n; sync + // derivations, render effects and the DOM re-derive from the pins (Solid's openView, #5089). + function recordRaw(raw) { + const out = []; + for (const { node, prev, value } of raw ?? []) { + out.push({ node, prev }); + shownLast.set(node, value); + } + return out; + } + const oldest = () => Math.max(1, flushes - capacity + 1); + // Before a key's first recorded change, its value is that change's `prev` (TRACE-CONTRACT §4b). + function valuesAt(n) { + const m = new Map(base), seen = new Set(base.keys()); + for (let s = oldest(); s <= flushes; s++) + for (const c of steps[(s - 1) % capacity].changes) { + if (!c.key || seen.has(c.key)) continue; + seen.add(c.key); + if (c.prev !== undefined) m.set(c.key, c.prev); + } + for (let s = oldest(); s <= n; s++) applyPreviews(m, steps[(s - 1) % capacity].changes); + return m; + } + // Keys travel can't show exactly at n: on a Solid whose records name only a store guess's carrier, a store guessed + // after n (and what reads it). Once a guess's record has named its properties, this Solid has none. + function inexactAt(n) { + const roots = new Set(); + const guessedAfter = new Set(); + for (let s = n + 1; s <= flushes; s++) for (const k of carrierKeys[(s - 1) % capacity] ?? []) guessedAfter.add(k); + for (let s = n + 1; s <= flushes; s++) { + const i = (s - 1) % capacity; + for (const k of guesses[i] ?? []) roots.add(k); + if (!listsThroughPin) for (const k of rewrites[i] ?? []) roots.add(k); + } + // A Solid whose view reads a list's rows through the pinned container rewinds a list rewritten wholesale, except + // one an optimistic layer guessed over after n (a guess held across an await, then landed): its rows still read + // wrong or `undefined` under the view (solid-view 980f5b4c5; reported). + if (listsThroughPin && !guessedListsThroughPin && guessedAfter.size) { + const rewritten = new Set(); + for (let s = oldest(); s <= flushes; s++) for (const k of rewrites[(s - 1) % capacity] ?? []) rewritten.add(k); + for (const k of guessedAfter) if (rewritten.has(k)) roots.add(k); + } + if (!roots.size) return []; + const out = new Set(roots); + for (const g of graphs) { + const byId = new Map(g.nodes.map(x => [x.id, x])), next = new Map(); + for (const e of g.edges) if (e.type === "read") (next.get(e.from) ?? next.set(e.from, []).get(e.from)).push(e.to); + const todo = g.nodes.filter(x => roots.has(x.key)).map(x => x.id), seen = new Set(todo); + while (todo.length) for (const to of next.get(todo.pop()) ?? []) if (!seen.has(to)) { + seen.add(to); todo.push(to); + if (byId.get(to)?.key) out.add(byId.get(to).key); + } + } + return [...out].sort(); + } + // The ring keeps, per step, the engine nodes it changed: a disposed component's nodes (and the values they showed) + // would stay reachable for up to `capacity` steps. openView skips disposed nodes, so their entries go; the steps' + // keyed previews stay (finding 12). Without a readable disposed flag (solid-asks #2) nothing is swept. + const isDisposed = node => typeof node?._flags === "number" && (node._flags & (1 << 6)) !== 0; + function sweepDisposed() { + if (support.disposed === false) return; + for (let s = oldest(); s <= flushes; s++) { + const i = (s - 1) % capacity, list = raws[i]; + if (list?.some(c => isDisposed(c.node))) raws[i] = list.filter(c => !isDisposed(c.node)); + } + } + let sweepQueued = false; + const queueSweep = () => { + if (sweepQueued) return; + sweepQueued = true; + setTimeout(() => { sweepQueued = false; sweepDisposed(); }, 0); + }; + // dev only, for tests: engine nodes the ring still holds, and how many of them are disposed + const retained = () => { + const nodes = new Set(); + for (let s = oldest(); s <= flushes; s++) for (const c of raws[(s - 1) % capacity] ?? []) nodes.add(c.node); + return { nodes: nodes.size, disposed: [...nodes].filter(isDisposed).length }; + }; + (globalThis.__RX__ ??= {}).retained = retained; + function pinsFor(n) { + const pins = new Map(); + for (let s = flushes; s > n; s--) for (const c of raws[(s - 1) % capacity]) { + let node = c.node; + while (reincarnations.has(node)) node = reincarnations.get(node); + pins.set(node, c.prev); + } + return pins; + } + const nameOf = key => { + for (const graph of graphs) { const n = graph.nodes.find(n => n.key === key); if (n) return n.name; } + return latest.get(key)?.name ?? key.split("|").at(-1); + }; + function diffValues(from, to) { + const changes = []; + for (const key of [...new Set([...from.keys(), ...to.keys()])].sort()) { + if (from.has(key) === to.has(key) && from.get(key) === to.get(key)) continue; + const c = { key, name: nameOf(key), ...locate(key) }; + const a = from.get(key), b = to.get(key); + if (a !== undefined) a.startsWith(ERR) ? (c.prevError = a.slice(ERR.length)) : (c.prev = a); + if (b !== undefined) b.startsWith(ERR) ? (c.error = b.slice(ERR.length)) : (c.preview = b); + changes.push(c); + } + return changes; + } + // While viewing the app is read-only (TRACE-CONTRACT §4b): input on it would write beneath the view, unseen. + let blocker = null; + function readOnly(n) { + if (typeof document === "undefined") return; + if (n == null) { + blocker?.off(); + blocker = null; + document.documentElement.removeAttribute("data-rx-viewing"); + return; + } + document.documentElement.setAttribute("data-rx-viewing", String(n)); + (blocker ??= blockInput(() => resume())).show(n); + } + const deny = (to, reason) => publish({ type: "travel-denied", to, reason }); + // A question in the air or an action still running is a hold that has not landed: opening a view now, its landing + // would come beneath the view and could not be told apart from what the view shows. Moving between seqs once + // viewing is fine (the app is read-only, and what lands stays beneath). + const holding = () => !!landing || probingGuess || (!view && (flightKeys().size > 0 || runs.size > 0 || held.size > 0 + || [...writes.values()].some(({ key, instance }) => inspect(key, () => undefined, instance)?.held))); + // Travel asked for while holding waits (TRACE-CONTRACT v0.6 `travel-pending`): the newest target wins, and goes + // when the hold has landed. `resume` drops it. + // It waits PENDING_MS at most (an app that polls may always have a question in the air), then is denied "pending" + // with the keys it still waits on, so the view can say what. + const PENDING_MS = 3000; + let queued = null, queueTimer = 0, queuedSince = 0; + const waitingOn = () => [...new Set([...flightKeys().keys(), ...[...runs.values()].map(r => r.key), ...held.keys(), + ...[...writes.values()].filter(({ key, instance }) => inspect(key, () => undefined, instance)?.held).map(w => w.key)])].sort(); + function tryQueued() { + if (queued === null || queueTimer) return; + // never from inside a flush or an action body: openView throws there + queueTimer = setTimeout(() => { + queueTimer = 0; + if (queued === null) return; + if (holding()) { + if (performance.now() - queuedSince < PENDING_MS) return void setTimeout(tryQueued, 50); + const to = queued; + queued = null; + return publish({ type: "travel-denied", to, reason: "pending", keys: waitingOn() }); + } + const to = queued; + queued = null; + travel(to); + }, 0); + } + function travel(to) { + const openView = engine[1]?.openView; + // solid-asks #7: openView (solidjs/solid#5089) + if (!supports("openView", typeof openView === "function", "time travel (openView)")) return deny(to, "unsupported"); + if (holding()) { + if (queued === null) queuedSince = performance.now(); + queued = to; // checked when it goes: the seq may be recorded by then + publish({ type: "travel-pending", to }); + return tryQueued(); + } + queued = null; + if (!Number.isInteger(to) || to < oldest() || to > flushes) return deny(to, "evicted"); + try { + if (!view) { + if (listsThroughPin === null) { + listsThroughPin = probeListPins(openView); + // dev-only, for tests and tools: not part of the trace protocol + (globalThis.__RX__ ??= {}).travel = { listsThroughPin }; + } + if (listsThroughPin && guessedListsThroughPin === null && guessesNamed + && rewrites.flat().some(k => carrierKeys.some(keys => keys?.includes(k)))) { + queued = to; + publish({ type: "travel-pending", to }); + probingGuess = true; + void probeGuessedListPins(openView).then(supported => { + probingGuess = false; + guessedListsThroughPin = supported; + globalThis.__RX__.travel.guessedListsThroughPin = supported; + tryQueued(); + }); + return; + } + const v = openView(); + view = v; // set after openView: its own flush of what was staged is live history + } + const from = viewing ?? flushes; + view.show(pinsFor(to)); + viewing = to; + readOnly(to); + const inexact = inexactAt(to); + publish({ type: "step", from, to, direction: to < from ? "back" : "forward", changes: diffValues(valuesAt(from), valuesAt(to)), + ...(inexact.length ? { inexact } : {}) }); + } catch (e) { + // openView throws inside a flush, an effect or an action body (and while another view is open) + if (view && viewing === null) { const v = view; view = null; readOnly(null); try { v.resume(); } catch {} } + deny(to, "unsupported"); + console.warn("[rx-map] travel failed:", e); + } + } + function resume() { + queued = null; + if (landing) return; // its resume is on the way + if (!view) return publish({ type: "resume", head: flushes, changes: [] }); + const v = view, from = viewing; + view = null; + viewing = null; + landing = { view: v, from, records: [] }; + readOnly(null); + let done = false; + try { done = v.resume(); } catch (e) { console.warn("[rx-map] resume failed:", e); done = true; } + if (done) land(); + else waitForLanding(); + } + function waitForLanding() { + const check = () => { + if (!landing) return; + let busy = false; + try { busy = landing.view.landing(); } catch {} + if (busy) setTimeout(check, 16); + else land(); + }; + setTimeout(check, 16); + } + // Everything the program did beneath the view lands as one transition: one step, measured against what the + // timeline last recorded (the engine's landing record measures against the pins, which were never history). + function land() { + const { from, records } = landing; + landing = null; + const head = valuesAt(flushes); + const now = new Map(), nodes = new Map(); + let at = performance.now(); + for (const r of records) { + at = r.at ?? at; + for (const { before, ...c } of r.changes) if (c.key) now.set(c.key, c); + for (const { node, name, prev, value } of r.raw ?? []) { + if (!nodes.has(node)) nodes.set(node, { node, name, prev: shownLast.has(node) ? shownLast.get(node) : prev }); + nodes.get(node).value = value; + } + } + const raw = []; + for (const { node, prev, value } of nodes.values()) { + shownLast.set(node, value); + if (!Object.is(prev, value)) raw.push({ node, prev }); + } + // A node the view pinned whose truth beneath ended where the pin was shows no change in the landing record; + // its current value comes from the node itself. + for (const key of head.keys()) if (!now.has(key)) { + const cur = inspect(key); + if (cur?.value && cur.error == null && cur.value.preview !== head.get(key)) now.set(key, { key, name: nameOf(key), ...cur.value }); + } + const changes = []; + const landed = new Map(reconcileErrors([...now.values()]).map(c => [c.key, c])); + for (const [key, c] of landed) { + if (head.has(key) && head.get(key) === stateOf(c)) continue; + const out = { ...c, ...locate(key) }; + delete out.prev; + if (head.has(key)) { if (!head.get(key).startsWith(ERR)) out.prev = head.get(key); } + else { + // a first change: the node's own value before, as the timeline last recorded it + const own = [...nodes.values()].find(x => keyOf(x.name) === key && !x.name.slice(x.name.lastIndexOf("|") + 1).includes(".")); + if (own && own.prev !== undefined) out.prev = untracked(() => preview(own.prev)); + } + changes.push(out); + } + // The landing is one new step when something keyed moved; otherwise its records are only the pins coming off. + // The view hears the step after the resume, as the flush that brings it live again. + const internal = records.flatMap(r => r.changes.filter(c => !c.key)); + const step = changes.length ? addStep(at, changes, raw, internal, true) : null; + publish({ type: "resume", head: flushes, changes: diffValues(valuesAt(from), valuesAt(flushes)) }); + if (step) publishStep(step, internal); + queueReconcile(); + } + let acting; + function control(method, to) { + if (acting) throw new Error("another timeline request is in progress"); + return new Promise((resolve, reject) => { + const finish = (result, error) => { + clearTimeout(timer); + listeners.delete(receive); + acting = undefined; + if (error) reject(error); else resolve(result); + }; + const receive = msg => { + if (method === "resume" && msg?.type === "resume" || + method === "travel" && msg?.to === to && ["step", "travel-denied"].includes(msg.type)) finish(msg); + }; + const timer = setTimeout(() => { + if (method === "travel" && queued === to) queued = null; + finish(undefined, new Error(`${method} timed out waiting for the host`)); + }, 4000); + acting = method; + listeners.add(receive); + try { if (method === "travel") travel(to); else resume(); } + catch (e) { finish(undefined, e); } + }); + } + function query(method, { key, keys = [], instance, since = 0, limit = 20, seq: to } = {}) { + const requested = key; + const knownKeys = new Set([...graphs.flatMap(g => g.nodes.map(n => n.key)), ...(globalThis.__RX_NODES__?.keys() ?? []), ...last.keys()]); + let field; + if (key && !knownKeys.has(key)) { + const root = [...knownKeys].filter(k => key.startsWith(`${k}.`)).sort((a, b) => b.length - a.length)[0]; + if (root) { field = key.slice(root.length + 1); key = root; } + } + const known = () => { + if (typeof key !== "string" || !key) throw new Error("provide a key from find"); + if (!knownKeys.has(key)) { + const name = key.split("|").at(-1).toLowerCase(); + const similar = [...knownKeys].filter(k => k.toLowerCase().includes(name)).slice(0, 3); + throw new Error(`unknown key ${key}; ${similar.length ? `did you mean: ${similar.join(", ")}? ` : ""}Use find for keys.`); + } + }; + if (key && ["state", "value", "why"].includes(method)) { + const instances = instanceList(key); + if (instance === undefined && instances.length > 1) { + return { key: requested, instances: instances.map(i => query(method, { key: requested, instance: i })) }; + } + if (instance !== undefined && !instances.includes(instance)) throw new Error(`no live instance ${instance} for ${key}`); + instance ??= instances[0]; + } + switch (method) { + case "travel": return control("travel", to); + case "resume": return control("resume"); + case "timeline": { + const frame = timeline(); + return { ...frame, steps: frame.steps.slice(-limit) }; + } + case "status": return { flushes, uptime: performance.now() - start }; + case "tail": { + if (!Number.isSafeInteger(since) || since < 0 || !Number.isSafeInteger(limit) || limit < 1 || limit > size) + throw new Error("tail takes a nonnegative since and a limit from 1 to 2000"); + return recent(limit, since); + } + case "value": { + known(); + return current(key, flightFor(key, instance), instance, field); + } + case "boundary_history": { + const ref = [...regionRefs()].find(([, region]) => region === key)?.[0]; + const state = allBoundaries().find(b => b.region === key); + if (!state) throw new Error(`unknown boundary ${key}`); + const notifiers = new Set(Array.isArray(keys) ? keys : []); + let origin; + const history = recent().filter(r => r.region === key || (r.type === "flight" && notifiers.has(r.key))).slice(-16).map(r => { + if (r.type === "flight") { origin = r.origin; return r; } + const result = origin ? { ...r, origin } : r; + origin = undefined; + return result; + }); + return { ...state, ...(!globalThis.__RX_BOUNDARIES__?.has(ref) ? { observation: "not created yet" } : {}), history }; + } + case "state": + if (key !== undefined) { + const boundary = allBoundaries().find(b => b.region === key); + if (boundary) return query("boundary_history", { key }); + known(); + return { ...current(key, flightFor(key, instance), instance, field), held: held.get(identity({ key, instance })), runs: [...runs.values()].filter(r => r.key === key) }; + } + return { values: states(), flights: pending(), boundaries: allBoundaries().filter(b => b.state !== "ok"), + held: [...held.values()], runs: [...runs.values()], reverts: recent().filter(r => r.type === "revert").slice(-10) }; + case "why": { + known(); + const hit = field ? recent().findLast(r => r.changes?.some(c => c.key === key && c.instance === instance && matchesKey(c, requested))) + : last.get(identity({ key, instance }))?.record; + const related = new Set([key]); + const chain = []; + const changed = new Map(hit?.changes.map(c => [c.key, c])); + const upstream = new Set([key]); + for (const g of graphs) { + const byId = new Map(g.nodes.map(n => [n.id, n.key])); + const walk = (to, depth) => { + if (depth > 5 || chain.length >= 24) return; + for (const e of g.edges) { + const from = byId.get(e.from); + if (!from || byId.get(e.to) !== to) continue; + if (e.type === "write") related.add(from); + if (e.type !== "read" && e.type !== "passes") continue; + if (upstream.has(from)) continue; + upstream.add(from); + if (changed.has(from)) chain.push({ ...changed.get(from), depth }); + walk(from, depth + 1); + } + }; + walk(key, 1); + } + const events = recent().filter(r => (r.key !== key || r.instance === instance || r.instance === undefined) && + ((["run", "revert", "held", "released"].includes(r.type) && related.has(r.key)) || + (r.type === "flight" && upstream.has(r.key)))).slice(-16); + const readers = [...held.values()].filter(h => h.by.some(k => upstream.has(k))).map(h => ({ ...h, ...locate(h.key) })); + const state = current(key, flightFor(key, instance), instance, field); + state.held = held.get(identity({ key, instance })); + if (state.error) state.untripped = untripped(key); + if (!hit) return { ...state, others: [], events, chain, readers }; + const record = hit, change = hit.changes.findLast(c => c.key === key && c.instance === instance && matchesKey(c, requested)); + const others = [...new Map(record.changes.filter(c => c.key && c.key !== key).map(c => [c.key, c])).values()]; + return { ...change, seq: record.seq, at: record.at, others, events, chain, readers, current: state }; + } + case "pending": return pending(); + default: throw new Error("unknown live method; use status, tail, state, value, why, or pending"); + } + } + // What the app displays now for each key (its newest live instance): TRACE-CONTRACT §5's arbiter for this host. + function shown(keys) { + const out = {}; + for (const key of keys ?? [...(globalThis.__RX_NODES__?.keys() ?? [])]) { + const read = inspect(key); + if (!read) continue; + if (read.error != null) out[key] = { error: errorPreview(read.error) }; + else if (read.value?.preview !== undefined) out[key] = { preview: read.value.preview }; + } + return out; + } + return recording = { listeners, traces, query, snapshot, timeline, travel, resume, hmr, replaceModule, shown }; +} + +// ---- read-only while viewing ---------------------------------------------------------------------------------------- +// Capture-phase listeners on the window stop pointer and keyboard input before the app (or Solid's delegated +// handlers) sees it, except in the map, the devtools and the badge, which says why and offers a way back. +const BLOCKED = ["pointerdown", "pointerup", "mousedown", "mouseup", "click", "dblclick", "auxclick", "contextmenu", + "touchstart", "touchend", "keydown", "keyup", "keypress", "beforeinput", "input", "change", "submit", "paste", "cut", + "drop", "dragstart"]; +const ALLOWED = "[data-rx-map], [data-rx-viewing-badge], [data-solid-dev-toolbar-root], [data-solid-dev-toolbar]"; +function blockInput(onResume) { + const badge = document.createElement("div"); + badge.setAttribute("data-rx-viewing-badge", ""); + const shadow = badge.attachShadow({ mode: "open" }); + shadow.innerHTML = `
    `; + const box = shadow.querySelector(".b"), label = shadow.querySelector("span"); + shadow.querySelector("button").addEventListener("click", () => onResume()); + const allowed = ev => ev.composedPath().some(n => n instanceof Element && n.matches(ALLOWED)); + let nudged = 0; + const stop = ev => { + if (allowed(ev)) return; + ev.preventDefault(); + ev.stopImmediatePropagation(); + if (ev.type === "pointerdown" || ev.type === "keydown") { + box.classList.add("nudge"); + clearTimeout(nudged); + nudged = setTimeout(() => box.classList.remove("nudge"), 160); + } + }; + for (const t of BLOCKED) window.addEventListener(t, stop, true); + // a caret left in an app field would suggest typing works + const active = document.activeElement; + if (active && active !== document.body && !active.closest?.(ALLOWED)) active.blur?.(); + document.body.append(badge); + return { + show(n) { label.textContent = `viewing #${n} — resume to interact`; }, + off() { + for (const t of BLOCKED) window.removeEventListener(t, stop, true); + clearTimeout(nudged); + badge.remove(); + }, + }; +} + +// A key's shown state in the timeline: its preview, or its error (TRACE-CONTRACT v0.6: an error is a state, not an +// absence). Absent = no value shown (never answered, or no live instance). +const ERR = "\u0000error\u0000"; +const stateOf = c => c.error !== undefined ? ERR + c.error : c.preview; +function applyPreviews(map, changes) { + for (const c of changes ?? []) if (c.key) { + const v = stateOf(c); + if (v === undefined) map.delete(c.key); + else map.set(c.key, v); + } +} +// ---- the engine's records --------------------------------------------------------------------------------------- +// Without a dev Solid (no records channel), the map is drawn and stays still. +function listen(post, dirty, replacingOrigin) { + const [solid, attr] = engine; + const records = solid?.OBSERVE?.records; + const attribution = attr?.attribution; + if (!records || typeof attribution?.enable !== "function") return () => {}; + const formatOrigin = typeof attr.formatOrigin === "function" ? attr.formatOrigin : o => o.kind + (o.name ? ` ${o.name}` : ""); + + // A flush lists every node whose shown value it changed; with `bodies`, the values beside them (live, so they are + // previewed now). + const onFlush = (event, live) => { + const hmr = (live?.changes ?? []).map(c => hmrFlights.get(c.node)).find(Boolean); + const roots = new Map(); + const changes = (event.changes ?? []).flatMap((c, i) => { + if (probeNode(live?.changes?.[i]?.node)) return []; + const out = { name: c.nodeName, key: keyOf(c.nodeName), instance: instanceOf(c.nodeName) }; + const body = live?.changes?.[i]; + if (out.key) { + observeNode(c.nodeName, body?.node); + dirty(out.key); + const id = identity(out); + if (!roots.has(id)) roots.set(id, inspect(out.key, previews, out.instance)); + const root = roots.get(id); + out.ownerPath = root?.ownerPath; + if (c.key !== undefined && c.key !== "$guess") out.path = storePath(body?.node, c.key); + if (root?.error != null) out.error = errorPreview(root.error); + else if (root?.value) Object.assign(out, root.value); + else if (!root && !out.path && body && "value" in body) Object.assign(out, untracked(() => previews(body.value))); + // the node's own value before (not a store property's): the prev of a key's first change + if (c.nodeName === RX + id && body?.prev !== undefined) out.before = untracked(() => preview(body.prev)); + } else if (body && "value" in body) out.preview = untracked(() => preview(body.value)); + const origin = c.origin ?? event.interaction; + if (origin) { + try { out.origin = formatOrigin(origin); } catch {} + } + if (hmr && out.key) out.origin = hmr; + return out; + }); + // The engine's own nodes and what each showed before: what time travel pins. + const raw = []; + for (let i = 0; i < (live?.changes?.length ?? 0); i++) { + const body = live.changes[i]; + if (!body?.node || probeNode(body.node) || solid.OBSERVE.isExcluded?.(body.node)) continue; + raw.push({ node: body.node, name: event.changes[i]?.nodeName, prev: body.prev, value: body.value }); + } + post({ source: SOURCE, type: "flush", at: event.at, changes, raw, ...(hmr ? { origin: hmr } : {}) }); + }; + + // The engine's flight record comes when a flight ends: landed, or abandoned because the node started another. A + // start has no record, so it is read off the node a run just finished: a new promise in `_x._inFlight` (dev builds + // keep the field's name). + const announced = new WeakMap(); + const onRun = (event, node) => { + const key = keyOf(event.nodeName); + if (!key || !node) return; + observeNode(event.nodeName, node); + dirty(key); + // solid-asks #1: a flight's start (`_x._inFlight`, read off a computation that just ran) + if (typeof node._fn === "function" && !supports("flightStart", "_x" in node, "flight starts (amber orbits, pending travel)")) return; + const flight = node._x?._inFlight; + if (flight && announced.get(node) !== flight) { + const hmr = replacingOrigin(); + if (hmr) hmrFlights.set(node, hmr); + announced.set(node, flight); + const instance = instanceOf(event.nodeName), ownerPath = inspect(key, () => undefined, instance)?.ownerPath; + // v0.9: what re-asked it, from the run's causes (the inputs that changed; none on a first ask) + const cause = (event.causes ?? []).slice(0, 8).map(c => { + const k = keyOf(c.name); + return { ...(k ? { key: k } : {}), name: c.name, ...(c.prev !== undefined ? { prev: c.prev } : {}), ...(c.value !== undefined ? { value: c.value } : {}) }; + }); + post({ source: SOURCE, type: "flight", key, instance, ownerPath, node, state: "start", ...(cause.length ? { cause } : {}) }, event.nodeId, event.at, + event.interaction && formatOrigin(event.interaction)); + // Solid's flight record covers successful landings and supersession, not + // rejection. Observe native promise rejection without replacing the promise. + if (flight instanceof Promise) flight.then(() => { + // Nor does it cover a node disposed while asking (a component a route or a view remounted): its answer lands + // nowhere, and an open flight would hold travel forever. (`_flags` bit 6 is REACTIVE_DISPOSED.) + setTimeout(() => { + // solid-asks #2: disposed (`_flags` bit 6, REACTIVE_DISPOSED) + if (announced.get(node) !== flight || !supports("disposed", typeof node._flags === "number", "ending flights of disposed nodes") + || !(node._flags & (1 << 6))) return; + announced.delete(node); + post({ type: "flight", key, instance, state: "abandon" }, event.nodeId); + }, 0); + }, error => { + if (announced.get(node) !== flight) return; + announced.delete(node); + // v0.9: rejected, not superseded: the abandon carries the error + post({ type: "flight", key, instance, state: "abandon", error: errorPreview(error) }, event.nodeId); + }); + } + }; + const onFlight = (event, node) => { + const key = keyOf(event.nodeName); + if (!key) return; + if (node) announced.delete(node); + // The flight's end and flush arrive in the same turn, in engine order. + if (node && hmrFlights.has(node)) queueMicrotask(() => hmrFlights.delete(node)); + post({ source: SOURCE, type: "flight", key, instance: instanceOf(event.nodeName), state: event.outcome === "landed" ? "land" : "abandon" }, event.nodeId, + undefined, event.interaction && formatOrigin(event.interaction)); + }; + + const offs = [ + records.subscribe("flush", onFlush, { bodies: true }), + records.subscribe("flight", onFlight), + records.subscribe("rerun", onRun), + records.subscribe("create", onRun), + solid.OBSERVE.diagnostics?.subscribe(event => { + if (event.code !== "OPTIMISTIC_REVERTED") return; + const key = keyOf(event.nodeName ?? event.data?.source); + if (!key) return; + const origin = event.interaction ?? event.origin; + post({ type: "revert", key, instance: instanceOf(event.nodeName ?? event.data?.source), at: performance.now(), reason: event.data?.how, + ...(origin ? { origin: formatOrigin(origin) } : {}) }); + }), + ]; + const release = attribution.enable({ log: false, values: "full" }); + return () => { + release(); + for (const off of offs) off?.(); + }; +} + +// FlushChange.key is only the leaf. Walk the same target links Solid uses +// for attribution's own store paths. Older engines can only give the leaf. +function storePath(node, leaf) { + const parts = [leaf]; + // solid-asks #3: the leaf's parents (`_host`, `pk`, `u`) + if (!supports("storePath", node && "_host" in node, "store paths beyond the leaf")) return leaf; + for (let t = node?._host; t?.pk != null && parts.length < 128; t = t.u) parts.push(String(t.pk)); + return parts.reverse().join("."); +} + +// Solid names property nodes `.`; the part before the dot is the declaration. +const keyOf = name => { + if (typeof name !== "string" || !name.startsWith(RX)) return null; + const k = name.slice(RX.length), bar = k.lastIndexOf("|"), dot = k.indexOf(".", bar + 1); + return (dot < 0 ? k : k.slice(0, dot)).replace(/~i\d+$/, ""); +}; +const instanceOf = name => typeof name === "string" ? /~i(\d+)(?:\.|$)/.exec(name.slice(name.lastIndexOf("|") + 1))?.[1] : undefined; + +/** A short string of a value, at most 80 characters. */ +export function preview(v, max = 80, depth = 2) { + let s; + try { s = show(v, depth, max); } catch (e) { + // Store reads can throw during inspection; let the accessor report those as state. + if (max === 2000) throw e; + s = "?"; + } + return s.length > max ? s.slice(0, max - 1) + "…" : s; +} +function show(v, depth, max) { + switch (typeof v) { + case "string": return JSON.stringify(v.length > 60 ? v.slice(0, 60) + "…" : v); + case "undefined": return "undefined"; + case "function": return `ƒ ${v.name || "anonymous"}`; + case "bigint": return `${v}n`; + case "symbol": return v.toString(); + case "object": break; + default: return String(v); + } + if (v === null) return "null"; + if (v instanceof Date) return isNaN(v) ? "Invalid Date" : v.toISOString(); + if (v instanceof Error) return `${v.name === "Error" && v.constructor?.name ? v.constructor.name : v.name}: ${v.message}`; + if (typeof v.then === "function") return "Promise"; + const arr = Array.isArray(v); + if (depth <= 0) return arr ? `Array(${v.length})` : "{…}"; + let out = arr ? "[" : "{", n = 0; + const keys = arr ? null : Object.keys(v); + const len = arr ? v.length : keys.length; + for (; n < len && out.length < max; n++) out += (n ? ", " : "") + (arr ? "" : `${keys[n]}: `) + show(arr ? v[n] : v[keys[n]], depth - 1, max - out.length); + if (n < len) out += `, …${len - n}`; + return out + (arr ? "]" : "}"); +} + +/** + * Several programs as one map: their modules side by side. A module two programs share is drawn once, its nodes and + * regions matched by key. + */ +export function mergeGraphs(list) { + if (list.length === 1) return list[0]; + const out = { modules: [], absModules: [], nodes: [], edges: [], regions: [], lines: {} }; + if (list.every(g => g.title)) out.title = list.map(g => g.title).join(", "); + // ids are `:`, and the page finds a module's root region as `:r0`: a module new + // to the merge keeps its local ids under its new index; a shared one maps to what the earlier program drew + const byKey = new Map(), edgeSeen = new Set(); + list.forEach(g => { + const mod = g.modules.map((m, i) => { + const at = out.modules.indexOf(m); + if (at >= 0) return { i: at, shared: true }; + out.absModules.push(g.absModules?.[i] ?? null); + return { i: out.modules.push(m) - 1, shared: false }; + }); + const local = id => { const c = id.indexOf(":"); return { m: mod[+id.slice(0, c)], rest: id.slice(c + 1) }; }; + const re = id => { const { m, rest } = local(id); return `${m.i}:${rest}`; }; + const map = new Map(); + for (const x of [...g.regions, ...g.nodes]) { + const { m } = local(x.id); + map.set(x.id, (m.shared && x.key && byKey.get(x.key)) || re(x.id)); + } + for (const r of g.regions) { + if (mod[r.mod].shared) continue; + if (r.key) byKey.set(r.key, map.get(r.id)); + out.regions.push({ ...r, id: map.get(r.id), mod: mod[r.mod].i, parent: r.parent == null ? null : map.get(r.parent) ?? re(r.parent), + ...(r.outline ? { outline: r.outline.map(p => "site" in p ? { ...p, site: map.get(p.site) } + : "region" in p ? { ...p, region: map.get(p.region) } : p) } : {}) }); + } + for (const n of g.nodes) { + if (mod[n.mod].shared) continue; + if (n.key) byKey.set(n.key, map.get(n.id)); + out.nodes.push({ ...n, id: map.get(n.id), mod: mod[n.mod].i, region: map.get(n.region) ?? re(n.region) }); + } + for (const e of g.edges) { + const ne = { ...e, from: map.get(e.from) ?? re(e.from), to: map.get(e.to) ?? re(e.to) }; + const k = JSON.stringify(ne); + if (!edgeSeen.has(k)) { edgeSeen.add(k); out.edges.push(ne); } + } + Object.assign(out.lines, g.lines); + }); + return out; +} + +// ---- pop-outs: a map window attaches to the bridge itself ------------------------------------------------------------ +// A pop-out is opened by the map in the dock's iframe, but it must outlive that iframe (the dock leaves the Map tab) and +// the app's reloads. `__RX__.connect(post)` gives it the same stream a mounted map gets, straight from this page: +// `post(msg)` receives host → view messages; `send(msg)` takes the view's (hello, snapshot?, travel, resume); `graph()` +// is the merged graph; `close()` detaches. A post that throws (its window is gone) detaches it. +export function connectView(post) { + const recorder = getRecorder(); + let ready = false, closed = false, internals = false; + const deliver = (msg, raw) => { + if (!ready || closed) return; + try { post(internals && raw ? raw : msg); } catch { close(); } + }; + const close = () => { closed = true; recorder.listeners.delete(deliver); }; + recorder.listeners.add(deliver); + return { + send(data) { + if (closed || data?.source !== SOURCE || data.v !== 1) return; + if (data.type === "hello") { ready = true; internals = wantsInternals(data); } + receiveFromView(data, deliver); // the same handling a mounted map's messages get (hello, snapshot?, travel, resume) + }, + graph: () => mergeGraphs(graphs), + close, + }; +} +if (typeof globalThis !== "undefined") (globalThis.__RX__ ??= {}).connect = connectView; diff --git a/tooling/rx-map/mcp.mjs b/tooling/rx-map/mcp.mjs new file mode 100644 index 000000000..f188ec04a --- /dev/null +++ b/tooling/rx-map/mcp.mjs @@ -0,0 +1,182 @@ +import { createInterface } from "node:readline"; +import { plain, project } from "./project.mjs"; +import { liveText, queryDiff, queryGraph } from "./query.mjs"; +import { ACT_METHODS, LIVE_METHODS, LIVE_PATH } from "./live-protocol.mjs"; + +const str = { type: "string", minLength: 1, maxLength: 1024 }; +const integer = minimum => ({ type: "integer", minimum }); +const imports = { type: "boolean", default: false }; +const selection = { key: str, instance: str, whole: { type: "boolean", default: false }, kinds: { type: "array", minItems: 1, maxItems: 16, + items: { type: "string", enum: ["flush", "flight", "run", "boundary", "held", "released", "revert"] } } }; +const tool = (name, description, properties = {}, required = []) => ({ + name, description, annotations: { readOnlyHint: true }, + inputSchema: { type: "object", properties: { ...properties, format: { type: "string", enum: ["text", "json"] } }, + required, additionalProperties: false }, +}); +const tools = [ + tool("check", "Check the program for compiler diagnostics."), + tool("overview", "List modules in dependency order; omit JS imports unless imports is true.", { imports }), + tool("find", "Find nodes or field paths by name or stable key (case-insensitive).", { query: { type: "string" }, imports }, ["query"]), + tool("node", "Describe a node or key.field.path and its static relationships.", { key: str }, ["key"]), + tool("reach", "Trace what a change can affect (down) or what can change a node (up).", + { key: str, direction: { type: "string", enum: ["down", "up"], default: "down" }, depth: integer(0) }, ["key"]), + tool("boundary", "List loading and errored boundaries, or show what can notify one.", { key: str }), + tool("diff", "Compare behavior in the working tree against a Git ref (default HEAD).", { ref: str }), + tool("live_status", "Show connected pages, flush count, and uptime."), + tool("tail", "Read recent flushes, flights, boundaries, runs and reverts. since is an exclusive record sequence number.", + { ...selection, since: integer(0), limit: { ...integer(1), maximum: 5000 }, filter: { type: "string", enum: ["semantic", "all"] } }), + { ...tool("record", "Mark and retrieve a trace recording.", { action: { type: "string", enum: ["start", "stop", "status"] }, + ...selection, filter: { type: "string", enum: ["semantic", "all"] } }, ["action"]), annotations: { readOnlyHint: false } }, + tool("value", "Read live previews for a key, optionally narrowed to one instance.", { key: str, instance: str }, ["key"]), + tool("state", "Read live value, pending and error, optionally narrowed to one instance.", { key: str, instance: str }), + tool("why", "Show current state, the last change, other keys in that flush, and related actions and reverts.", { key: str, instance: str }, ["key"]), + tool("pending", "List nodes waiting for a request to finish."), +]; +const resources = ["graph", "model"].map(name => ({ uri: `rx://${name}`, name, mimeType: "application/json" })); +const acting = [ + { ...tool("travel", "Seek to a timeline step in the newest connected page.", { seq: integer(1) }, ["seq"]), annotations: { readOnlyHint: false } }, + { ...tool("resume", "Resume the newest connected page from time travel."), annotations: { readOnlyHint: false } }, + tool("timeline", "Read the latest timeline steps and their changes.", { limit: { ...integer(1), maximum: 2000 } }), +]; +const liveMethods = new Map(LIVE_METHODS.map(k => [k === "status" ? "live_status" : k, k])); +const versions = ["2025-11-25", "2025-06-18", "2025-03-26", "2024-11-05"]; +const object = x => x !== null && typeof x === "object" && !Array.isArray(x); +const errorMessage = e => plain(e?.message ?? e); +const textContent = text => ({ type: "text", text: plain(text) }); +const invalid = (code, message) => Object.assign(new Error(message), { rpcCode: code }); + +function validate({ name, inputSchema: s }, args) { + if (!object(args)) throw new Error(`arguments must be an object; see tools/list for ${name}`); + for (const k of s.required) if (!Object.hasOwn(args, k)) throw new Error(`missing ${k}; see tools/list for ${name}`); + for (const [k, v] of Object.entries(args)) { + const p = Object.hasOwn(s.properties, k) && s.properties[k]; + const valid = p && (p.type === "array" ? Array.isArray(v) && v.length >= p.minItems && v.length <= p.maxItems && v.every(x => p.items.enum.includes(x)) + : p.type === "boolean" ? typeof v === "boolean" + : p.type === "integer" ? Number.isSafeInteger(v) && v >= p.minimum && !(v > p.maximum) + : typeof v === "string" && !(v.length < p.minLength || v.length > p.maxLength) && (!p.enum || p.enum.includes(v))); + if (!valid) throw new Error(`invalid argument ${k}; see tools/list for ${name}`); + } +} + +async function liveCall(dev, method, params) { + const signal = AbortSignal.timeout(5000); + const candidates = dev ? [dev] : ["http://localhost:3000", "http://localhost:5173"]; + const outcomes = await Promise.all(candidates.map(async url => { + try { + const res = await fetch(new URL(LIVE_PATH, url), { + method: "POST", signal, redirect: "error", headers: { "content-type": "application/json" }, + body: JSON.stringify({ method, params }), + }); + const body = await res.json(); + return res.ok && Object.hasOwn(body, "result") ? { result: body.result } + : typeof body.error === "string" ? { error: body.error } : null; + } catch { return null; } + })); + const hit = outcomes.find(x => x && Object.hasOwn(x, "result")); + if (hit) return hit.result; + throw new Error(outcomes.find(Boolean)?.error ?? "no dev server / no page connected; start Vite with rxMap(), open the app, and set --dev if needed"); +} + +/** Serve newline-delimited JSON-RPC over stdio (or supplied Node streams). */ +export function createMcp({ dev = process.env.RX_DEV_URL, getProject, live = (method, p) => liveCall(dev, method, p), act = false, ...options } = {}) { + const catalog = act ? [...tools, ...acting] : tools; + const local = getProject ? null : project(options); + const projectFor = getProject ?? (() => local); + const call = async ({ name, arguments: args = {} } = {}) => { + try { + const t = catalog.find(t => t.name === name); + if (!t) throw new Error(`unknown tool ${JSON.stringify(name)}; use tools/list`); + validate(t, args); + const { format, ...p } = args; + let answer; + let warning; + let freshness; + if (liveMethods.has(name) || ACT_METHODS.includes(name)) { + const method = liveMethods.get(name) ?? name; + const data = await live(method, p).catch(e => { + if (["state", "value"].includes(method) && /no (dev server|page)/.test(e.message)) return { key: p.key, observation: "unobserved" }; + throw e; + }); + answer = { data, text: ACT_METHODS.includes(method) ? JSON.stringify(data, null, 2) : liveText(method, data) }; + } else if (name === "check") { + const app = projectFor(); + const data = app.check(true); + const stale = app.staleTransforms(); + warning = stale.map(s => `stale entry transform: ${s.file} (changed: ${s.files.join(", ")}). ${s.fix}`).join("\n"); + answer = { data, text: data.map(d => `${d.file}:${d.line}:${d.column} ${d.code} ${d.message}`).join("\n") || "ok" }; + } else if (name === "diff") { + try { const graph = projectFor().diff(p.ref ?? "HEAD"); warning = graph.warning; freshness = graph.freshness; answer = queryDiff(graph); } + catch (e) { throw new Error(`${errorMessage(e)}\nUse an existing Git ref and check that both versions compile.`); } + } else { + const { graph, warning: stale } = projectFor().load(); + warning = stale; + freshness = graph.freshness; + answer = queryGraph(graph, name, p); + if (name === "boundary" && p.key && (dev || getProject)) { + answer.data.live = await live("boundary_history", { key: p.key, keys: answer.data.notifiers.map(n => n.key) }) + .catch(() => ({ observation: "unobserved" })); + answer.text += `\n${liveText("boundary_history", answer.data.live)}`; + } + } + const entries = freshness?.map(e => `${e.entry}: ${e.status}${e.at ? ` at ${e.at}` : ""} (${e.modules.join(", ") || "no modules"})`).join("\n"); + return { content: format === "json" + ? [textContent(JSON.stringify(answer.data, null, 2)), ...(warning ? [textContent(warning)] : []), + ...(freshness ? [textContent(JSON.stringify({ freshness }))] : [])] + : [textContent([warning, entries, answer.text].filter(Boolean).join("\n"))] }; + } catch (e) { return { isError: true, content: [textContent(errorMessage(e))] }; } + }; + async function dispatch(method, params) { + const app = { load: () => projectFor().load() }; + switch (method) { + case "initialize": { + const v = params?.protocolVersion; + if (typeof v !== "string") throw invalid(-32602, "initialize requires protocolVersion"); + return { protocolVersion: versions.includes(v) ? v : versions[0], + capabilities: { tools: {}, resources: {} }, serverInfo: { name: "rx-map", version: "0.1.0" } }; + } + case "ping": case "notifications/initialized": return {}; + case "tools/list": return { tools: catalog }; + case "tools/call": return call(params); + case "resources/list": return { resources }; + case "resources/read": { + const r = resources.find(r => r.uri === params?.uri); + if (!r) throw invalid(-32602, "unknown resource URI; use resources/list"); + return { contents: [{ uri: r.uri, mimeType: r.mimeType, text: JSON.stringify(app.load()[r.name]) }] }; + } + default: throw invalid(-32601, `method not found: ${method}`); + } + } + return async function receive(msg) { + const failure = (id, code, message) => ({ jsonrpc: "2.0", id, error: { code, message } }); + const id = msg?.id; + const validId = typeof id === "string" || Number.isSafeInteger(id); + if (!object(msg) || msg.jsonrpc !== "2.0" || typeof msg.method !== "string" || (Object.hasOwn(msg, "id") && !validId)) { + return failure(validId ? id : null, -32600, "invalid request"); + } + if (!validId) return; // Client notifications require no response. + if (msg.params !== undefined && !object(msg.params)) return failure(id, -32602, "params must be an object"); + try { return { jsonrpc: "2.0", id, result: await dispatch(msg.method, msg.params) }; } + catch (e) { return failure(id, e.rpcCode ?? -32603, errorMessage(e)); } + }; +} + +export async function serveMcp({ input = process.stdin, output = process.stdout, ...options } = {}) { + const receive = createMcp(options); + const active = new Set(); + async function receiveLine(line) { + let msg; + try { msg = JSON.parse(line); } catch { + output.write('{"jsonrpc":"2.0","id":null,"error":{"code":-32700,"message":"parse error"}}\n'); + return; + } + const reply = await receive(msg); + if (reply) output.write(JSON.stringify(reply) + "\n"); + } + for await (const line of createInterface({ input, crlfDelay: Infinity, terminal: false })) { + if (!line.trim()) continue; + const task = receiveLine(line); + active.add(task); + void task.finally(() => active.delete(task)); + } + await Promise.all(active); +} diff --git a/tooling/rx-map/package.json b/tooling/rx-map/package.json new file mode 100644 index 000000000..3a935d9bf --- /dev/null +++ b/tooling/rx-map/package.json @@ -0,0 +1,70 @@ +{ + "name": "@reactivescript/map", + "description": "rx-map: a .rx program drawn from the checker's resolved model, as a static page or live beside a dev build", + "version": "0.1.0", + "license": "MIT", + "repository": { + "type": "git", + "url": "git+https://github.com/solidjs/reactivescript.git", + "directory": "tooling/rx-map" + }, + "type": "module", + "sideEffects": false, + "dependencies": { + "@reactivescript/compiler": "^0.3.1" + }, + "bin": { + "rx-map": "./rx-map.mjs" + }, + "exports": { + "./graph": "./graph.mjs", + "./page": "./page.mjs", + "./live": { + "types": "./live.d.ts", + "default": "./live.mjs" + }, + "./diff": "./diff.mjs", + "./mcp": "./mcp.mjs", + "./vite": { + "types": "./vite.d.ts", + "default": "./vite.mjs" + }, + "./fake": "./fake.mjs", + "./hmr": "./hmr.mjs", + "./layout": "./layout.mjs", + "./conformance": "./conformance.mjs", + "./package.json": "./package.json" + }, + "files": [ + "graph.mjs", + "page.mjs", + "live.mjs", + "diff.mjs", + "mcp.mjs", + "project.mjs", + "query.mjs", + "live-protocol.mjs", + "vite.mjs", + "fake.mjs", + "hmr.mjs", + "layout.mjs", + "conformance.mjs", + "rx-map.mjs", + "README.md", + "vite.d.ts", + "live.d.ts" + ], + "peerDependencies": { + "solid-js": "^2.0.0-rc.23" + }, + "peerDependenciesMeta": { + "solid-js": { + "optional": true + } + }, + "scripts": { + "build": "node build.mjs", + "prepack": "node build.mjs", + "test": "node build.mjs --check && node --test test/mcp.mjs test/graph.test.mjs test/layout.test.mjs && node test/conformance.test.mjs && node test/run.mjs && node test/real-host.mjs" + } +} diff --git a/tooling/rx-map/page.mjs b/tooling/rx-map/page.mjs new file mode 100644 index 000000000..44cd45386 --- /dev/null +++ b/tooling/rx-map/page.mjs @@ -0,0 +1,19 @@ +// Generated from app/ (main.rx and its modules) by build.mjs (npm run build). Edit the sources, not this file. +// Built with: @reactivescript/compiler 0.3.1 (Node-API binding); @reactivescript/runtime 0.3.1 (runtime/dist); solid-js 2.0.3, @solidjs/web 2.0.3, @solidjs/signals 2.0.3 (dists); esbuild 0.28.2. +const HTML = "\n\n\n\n\nrx-map · <!--__TITLE__-->\n\n\n\n
    \n\n\n\n\n"; + +const esc = s => String(s).replace(/[<&]/g, c => (c === "<" ? "<" : "&")); + +/** + * The map page for `graph` (from `buildGraph`, or `diffGraphs` for a diff), one self-contained HTML document. + * `live: true` makes it listen for the messages `@reactivescript/map/live` posts (`source: "rx-map"`). + * `fake: seed` runs the fake host (`@reactivescript/map/fake`) inside the page, with a dev HUD to drive it. + */ +export function pageHTML(graph, { live = false, fake = null } = {}) { + const title = graph.title ?? (graph.modules ?? []).map(m => m.split("/").pop()).join(", "); + return HTML + .replace("/*__LIVE__*/false", () => String(!!live || fake != null)) + .replace("/*__FAKE__*/null", () => (fake == null ? "null" : String(Number(fake) || 1))) + .replaceAll("", () => esc(title)) + .replace("/*__GRAPH__*/null", () => JSON.stringify(graph).replace(/ execFileSync(cmd, args, { + cwd, encoding: "utf8", maxBuffer: 1 << 28, stdio: ["ignore", "pipe", "pipe"], timeout: 30000, ...options, +}); +export const plain = s => stripVTControlCharacters(String(s)); +const where = (root, f) => relative(root, f).split("\\").join("/"); +export const isEntry = f => f.endsWith(".rx") && !f.endsWith(".d.rx") && !!statSync(f, { throwIfNoEntry: false })?.isFile(); + +function scan(root, ignored = new Set(["node_modules", "dist", ".git"])) { + const files = []; + function walk(dir) { + for (const e of readdirSync(dir, { withFileTypes: true })) { + const path = join(dir, e.name); + if (e.isDirectory() && !ignored.has(e.name)) walk(path); + else if (e.name.endsWith(".rx") && (e.isFile() || e.isSymbolicLink())) files.push(path); + } + } + walk(root); + return files.sort(); +} + +// Read import specifiers without mistaking strings or comments for imports. A .d.rx +// is a JS import's declaration (MO-8), not a program entry, but counts for invalidation. +const tokens = /\/\/[^\n]*|\/\*[\s\S]*?\*\/|"(?:\\[\s\S]|[^"\\])*"|'(?:\\[\s\S]|[^'\\])*'|`(?:\\[\s\S]|[^`\\])*`|[\w$]+|[^\s]/g; +function discover(files) { + const modules = files.filter(f => !f.endsWith(".d.rx")); + const imported = new Set(); + for (const f of modules) { + const ts = (readFileSync(f, "utf8").match(tokens) ?? []).filter(t => !t.startsWith("//") && !t.startsWith("/*")); + for (let i = 0; i < ts.length; i++) if (ts[i] === "import") { + for (let j = i + 1, nesting = 0; j < ts.length; j++) { + const t = ts[j]; + if (t === "{" || t === "(") nesting++; + if (t === "}" || t === ")") nesting--; + if (t === "from" && nesting === 0) { + const spec = ts[j + 1]; + if (/^["'].*\.rx["']$/.test(spec ?? "")) { + const target = resolve(dirname(f), spec.slice(1, -1)); + if (target !== f) imported.add(target); + } + break; + } + if (nesting < 0 || (!nesting && !/^[\w$,]+$|^[})]$/.test(t))) break; + if (t === "import") break; + } + } + } + return modules.filter(f => !imported.has(f)); +} + +export function project({ root = process.cwd(), entries = [], rxc = process.env.RXC, spa = true, managed = false, lastGood = new Map(), frontends = new Map() } = {}) { + root = resolve(root); + entries = [...new Set(entries.map(f => resolve(root, f)))]; + const binary = rxc && /[\\/]/.test(rxc) ? resolve(rxc) : rxc || "rxc"; + const require = createRequire(join(root, "package.json")); + let napi; + const compiler = (cwd, args, allowDiagnostics = false) => { + try { return run(cwd, binary, args); } + catch (e) { + if (allowDiagnostics && e.status === 1 && e.stdout) return e.stdout; + if (e.code === "ENOENT") throw new Error(`cannot run ${binary}; set RXC to the compiler binary`); + throw new Error(`${plain(e.stderr?.trim() || e.message)}\nRun check for diagnostics or verify --entry and RXC.`); + } + }; + function nativeCompiler() { + if (!rxc) { + if (napi === undefined) { + let id; + try { id = require.resolve("@reactivescript/compiler"); } + catch (e) { if (e.code !== "MODULE_NOT_FOUND") throw e; } + napi = id ? require(id) : null; + } + return napi; + } + } + function modelOf(files, cwd, current = false) { + if (!files.length) return []; + const native = nativeCompiler(); + if (native?.model) { + const model = JSON.parse(native.model(files, cwd)); + if (!Array.isArray(model)) throw new Error(model.error ?? "compiler returned no model"); + return model; + } + // The CLI prints one JSON array per entry. Merge shared dependencies once, + // preserving each entry's dependency order. + const modules = new Map(); + for (const f of files) { + for (const m of JSON.parse(compiler(cwd, ["model", ...(current && spa ? ["--spa"] : []), f]))) modules.set(resolve(cwd, m.file), m); + } + return [...modules.values()]; + } + let cached; + const stampOf = (files, deps = []) => JSON.stringify([...new Set([...files, ...entries, ...deps])].sort() + .map(f => [f, statSync(f, { throwIfNoEntry: false })?.mtimeMs])); + function snapshot() { + if (managed) { + const selected = entries.filter(isEntry); + for (const f of entries) if (!selected.includes(f)) { lastGood.delete(f); frontends.delete(f); } + if (!cached || cached.entries.length !== selected.length) cached = { entries: selected, hasPrograms: false }; + return cached; + } + const files = scan(root); + const stamp = stampOf(files, cached?.graph?.absModules); + if (stamp !== cached?.stamp) { + const selected = entries.length ? entries.filter(isEntry) : discover(files.filter(isEntry)); + for (const f of lastGood.keys()) if (!isEntry(f)) lastGood.delete(f); + cached = { stamp, files, entries: selected, hasPrograms: files.some(f => !f.endsWith(".d.rx")) }; + } + return cached; + } + function requireEntries(s) { + if (!s.entries.length) throw new Error(s.hasPrograms + ? "no entry found (imports may form a cycle); pass --entry to check a module" + : `no .rx program found under ${root}; set --root or pass --entry`); + return s.entries; + } + function buildDiagnostics(s, entry) { + const builds = s.builds ??= new Map(); + if (!builds.has(entry)) { + const frontend = frontends.get(entry); + const native = frontend ? undefined : nativeCompiler(); + const out = frontend ? frontend.check() : JSON.parse(native?.app ? native.app(entry, "dom", null, spa) + : compiler(root, ["app", entry, ...(spa ? ["--spa"] : [])])); + builds.set(entry, out.diagnostics?.length ? out.diagnostics : out.error + ? [{ file: entry, code: "BUILD", message: out.error }] : []); + } + return builds.get(entry); + } + function load() { + const s = snapshot(); + if (!s.graph) { + if (!s.entries.length) requireEntries(s); + const modules = new Map(), stale = [], failures = [], freshness = []; + const files = s.files ?? scan(root); + const stamps = new Map(JSON.parse(stampOf(files, s.entries))); + for (const entry of s.entries) { + let saved; + let fresh = false; + try { + const diagnostics = buildDiagnostics(s, entry); + if (diagnostics.length) throw Object.assign(new Error(diagnostics.map(d => d.msg ?? d.message).join("\n")), { diagnostics }); + const model = frontends.get(entry)?.model() ?? modelOf([entry], root, true); + const texts = new Map(model.map(m => { + const f = resolve(root, m.file); + let text; try { text = readFileSync(f, "utf8"); } catch { text = ""; } + return [f, text]; + })); + saved = { model, texts, stamps: entryStamps(stamps, texts), at: new Date().toISOString() }; + lastGood.set(entry, saved); + fresh = true; + } catch (e) { + failures.push(e); + saved = lastGood.get(entry); + if (!saved) { freshness.push({ entry: where(root, entry), status: "no good build", modules: [] }); continue; } + const now = entryStamps(stamps, saved.texts); + const changed = [...new Set([...now.keys(), ...saved.stamps.keys()])] + .filter(f => now.get(f) !== saved.stamps.get(f)).map(f => where(root, f)); + stale.push({ at: saved.at, changed }); + } + freshness.push({ entry: where(root, entry), status: fresh ? "current" : "last good build", + ...(!fresh ? { at: saved.at } : {}), modules: [...saved.texts.keys()].map(f => where(root, f)) }); + for (const m of saved.model) { + const path = resolve(root, m.file); + const prev = modules.get(path); + if (!prev || fresh && !prev.fresh) modules.set(path, { model: m, text: saved.texts.get(path), fresh }); + } + } + if (failures.length && !modules.size) throw failures[0]; + if (failures.length) { + let count; + try { count = check().filter(d => d.severity === "error").length; } catch {} + count ||= failures.reduce((n, e) => n + (e.diagnostics?.length || 1), 0); + const changed = [...new Set(stale.flatMap(x => x.changed))].sort().join(", ") || "(unknown)"; + const at = stale.map(x => x.at).sort()[0]; + s.warning = `program has ${count} error${count === 1 ? "" : "s"}; ${at + ? `answers from the last good build at ${at}; changed since: ${changed}` : "answers omit entries with no good build"}`; + } + s.model = [...modules.values()].map(m => m.model); + s.graph = buildGraph(structuredClone(s.model), { root, source: path => modules.get(path)?.text ?? "" }); + s.graph.freshness = freshness; + s.graph.moduleFreshness = [...modules].map(([file, m]) => ({ file: where(root, file), current: m.fresh })); + // Imported modules outside the scanned tree must also invalidate the snapshot. + if (!managed) s.stamp = stampOf(s.files, s.graph.absModules); + } + return s; + } + function entryStamps(stamps, texts) { + const out = new Map(stamps); + for (const file of texts.keys()) if (!out.has(file)) out.set(file, statSync(file, { throwIfNoEntry: false })?.mtimeMs ?? null); + return out; + } + function check(force = false) { + const s = snapshot(); + if (force && frontends.size) { delete s.builds; delete s.diagnostics; } + if (!s.diagnostics) { + const entries = requireEntries(s); + const data = frontends.size ? null : JSON.parse(compiler(root, ["check", "--json", ...(spa ? ["--spa"] : []), ...entries], true)); + const unique = new Map(); + const diagnostics = data?.diagnostics.length ? data.diagnostics : entries.flatMap(f => buildDiagnostics(s, f)); + for (const d of diagnostics) { + const diag = { file: isAbsolute(d.file) ? where(root, d.file) : d.file, + line: d.range?.start?.line ?? d.line ?? 1, column: (d.range?.start?.column ?? 0) + 1, + severity: d.severity ?? "error", code: d.code, message: plain(d.message ?? d.msg) }; + if (diag.code === "ASYNC_OUTSIDE_LOADING_BOUNDARY" && /a reader of …/.test(diag.message)) { + try { + const line = readFileSync(resolve(root, diag.file), "utf8").split(/\r?\n/)[diag.line - 1]; + const reader = line?.match(/\bpending\?\s+[\w$.]+/)?.[0] ?? line?.trim(); + if (reader) diag.message = diag.message.replace("a reader of …", `\`${reader}\` at ${diag.file}:${diag.line}`); + } catch {} + } + unique.set(JSON.stringify(diag), diag); + } + if (frontends.size) return s.diagnostics = [...unique.values()]; + // Run the project's own Volar/TypeScript projection, when installed. + let tsc; + try { tsc = require.resolve("@reactivescript/language-server/bin/tsc.js"); } catch {} + if (tsc && statSync(join(root, "tsconfig.json"), { throwIfNoEntry: false })?.isFile()) { + let output; + try { output = run(root, process.execPath, [tsc, "--noEmit", "--pretty", "false"]); } + catch (e) { output = e.stdout || e.stderr; if (!output) throw e; } + for (const text of plain(output).split(/\r?\n/)) { + const match = text.match(/^(.*)\((\d+),(\d+)\): (error|warning) (TS\d+): (.*)$/) + ?? text.match(/^(.*):(\d+):(\d+) - (error|warning) ([A-Z][A-Z_0-9]+): (.*)$/); + if (!match) continue; + const [, file, line, column, severity, code, message] = match; + const rel = isAbsolute(file) ? where(root, file) : file; + const diag = { file: rel, line: +line, column: +column, severity, code, message }; + if (![...unique.values()].some(d => d.file === rel && d.line === +line && d.code === code)) unique.set(JSON.stringify(diag), diag); + } + } + s.diagnostics = [...unique.values()]; + } + return s.diagnostics; + } + function staleTransforms() { + return [...frontends].flatMap(([entry, frontend]) => { + const files = frontend.transformed?.(); + if (!files?.length) return []; + const file = where(root, entry); + return [{ file, files: files.map(f => where(root, f)), + fix: `Touch ${file} and reload the page. If it is still stale, restart the Vite dev server and reload.` }]; + }); + } + function diff(ref) { + const s = load(); + const top = run(root, "git", ["rev-parse", "--show-toplevel"]).trim(); + const sha = run(top, "git", ["rev-parse", "--verify", "--end-of-options", `${ref}^{commit}`]).trim(); + const scratch = mkdtempSync(join(tmpdir(), "rx-map-")); + try { + const archive = run(top, "git", ["archive", sha], { encoding: null }); + run(scratch, "tar", ["-xf", "-"], { input: archive, stdio: ["pipe", "pipe", "pipe"] }); + const beforeRoot = resolve(scratch, relative(top, root)); + mkdirSync(beforeRoot, { recursive: true }); + const files = s.entries.map(f => { + const p = relative(top, f); + if (p === ".." || p.startsWith("../") || isAbsolute(p)) throw new Error(`entry ${f} is outside the Git checkout`); + return resolve(scratch, p); + }).filter(isEntry); + const before = buildGraph(modelOf(files, beforeRoot), { root: beforeRoot }); + before.label = `${ref} (${sha.slice(0, 7)})`; + const graph = diffGraphs(before, { ...s.graph, label: s.warning ? "last good build" : "working tree" }); + if (s.warning) graph.warning = s.warning; + graph.freshness = s.graph.freshness; + return graph; + } finally { + rmSync(scratch, { recursive: true, force: true }); + } + } + return { load, check, diff, staleTransforms }; +} diff --git a/tooling/rx-map/query.mjs b/tooling/rx-map/query.mjs new file mode 100644 index 000000000..58600e400 --- /dev/null +++ b/tooling/rx-map/query.mjs @@ -0,0 +1,292 @@ +const roles = { + source: "state", eq: "derived", props: "derived", reader: "derived", + action: "imperative", handler: "imperative", effect: "imperative", apply: "imperative", + fn: "outside", server: "outside", import: "outside", comp: "structure", context: "structure", + prop: "structure", provide: "structure", errclass: "failure", +}; +const isBoundary = r => r.kind === "loading" || r.kind === "errored"; +const ref = n => ({ key: n.key, kind: n.kind, file: n.file, line: n.line }); +export const location = n => n?.file ? ` ${n.file}:${n.line ?? "?"}` : ""; +const describe = n => `${n.key} ${n.kind}${location(n)}`; +const result = (data, lines, empty) => ({ data, text: lines.join("\n") || empty }); +const append = (m, k, v) => { if (!m.has(k)) m.set(k, []); m.get(k).push(v); }; +// A parent/root access can affect its descendants and vice versa. An unknown +// computed segment matches any single segment at that position. +const overlaps = (a, b) => { + if (!a || !b) return true; + const as = a.split("."), bs = b.split("."); + return as.slice(0, bs.length).every((p, i) => p === "*" || bs[i] === "*" || p === bs[i]); +}; +const quoteOutline = (region, nodes, incoming, site) => { + const parts = region?.outline; + if (!parts?.some(p => "text" in p)) return; + const i = site == null ? 0 : parts.findIndex(p => p.site === site); + if (i < 0) return; + const start = Math.max(0, i - 2), end = Math.min(parts.length, i + 4); + if (!parts.slice(start, end).some(p => "text" in p)) return; + const text = parts.slice(start, end).map(p => "text" in p ? (p.attr ? `${p.attr}: ${p.text}` : p.text) + : p.site ? `[${(incoming.get(p.site) ?? []).filter(e => e.type === "read").map(e => nodes.get(e.from)?.name).filter(Boolean).join(", ") || nodes.get(p.site)?.name || "…"}]` + : " ").join("").replace(/\s+/g, " ").trim(); + return `${start ? "… " : ""}${text.slice(0, 140)}${end < parts.length || text.length > 140 ? " …" : ""}`; +}; + +export function unknownKey(key, choices, search = "find") { + const distance = k => { + const a = key.toLowerCase(), b = k.toLowerCase(); + if (b.includes(a)) return 0; + let row = Array.from({ length: b.length + 1 }, (_, i) => i); + for (let i = 0; i < a.length; i++) { + const next = [i + 1]; + for (let j = 0; j < b.length; j++) next.push(Math.min(next[j] + 1, row[j + 1] + 1, row[j] + (a[i] !== b[j]))); + row = next; + } + return row[b.length]; + }; + const near = choices.map(k => [k, distance(k)]).sort((a, b) => a[1] - b[1]).slice(0, 3); + return new Error(`unknown key ${key}; ${near.length ? `did you mean: ${near.map(([k]) => k).join(", ")}? ` : ""}Use ${search} to list keys.`); +} + +export function queryGraph(g, method, p) { + const nodes = new Map(g.nodes.map(n => [n.id, n])); + const regions = new Map(g.regions.map(r => [r.id, r])); + const byKey = new Map(g.nodes.map(n => [n.key, n])); + const inc = new Map(), out = new Map(), kids = new Map(), members = new Map(); + for (const e of g.edges) { append(inc, e.to, e); append(out, e.from, e); } + const readsBy = id => (out.get(id) ?? []).filter(e => e.type === "read"); + const writesBy = id => (inc.get(id) ?? []).filter(e => e.type === "write"); + const fields = n => [...new Set([...readsBy(n.id), ...writesBy(n.id)].flatMap(e => { + if (!e.field) return []; + const parts = e.field.split("."); + return parts.map((_, i) => parts.slice(0, i + 1).join(".")); + }))].sort(); + for (const n of g.nodes) append(members, n.region, n); + for (const r of g.regions) append(kids, r.parent, r); + const componentRegion = n => n && g.regions.find(r => r.mod === n.mod && r.kind === "component" && r.name === n.name); + const firsts = new Map(); + function first(r) { + if (!firsts.has(r.id)) firsts.set(r.id, Math.min(Infinity, ...(members.get(r.id) ?? []).map(n => n.line), ...(kids.get(r.id) ?? []).map(first))); + return firsts.get(r.id); + } + function regionRef(r) { + const file = g.modules[r.mod]; + let line = first(r); + if (isBoundary(r)) { + const ls = g.lines[file] ?? {}; + const pattern = new RegExp(`\\{\\s*${r.kind}\\b|^\\s*${r.kind}\\s+(?:on|fallback)\\b`); + const hits = Object.keys(ls).map(Number).filter(i => pattern.test(ls[i])); + const siblings = g.regions.filter(x => x.mod === r.mod && x.kind === r.kind); + line = (hits.length === siblings.length ? hits[siblings.indexOf(r)] : hits.findLast(i => i <= line)) ?? line; + } + return { key: r.key, kind: r.kind, file, line: Number.isFinite(line) ? line : null }; + } + function notifiers(r) { + const visited = new Set(), sites = new Set(), roots = new Map(); + function cover(region, nested = false) { + if (visited.has(region.id)) return; + if (nested && region.kind === r.kind) { + const line = regionRef(region).line; + if (r.kind !== "errored" || !/fallback\s*\(\s*\w+\s*:/.test(g.lines[g.modules[region.mod]]?.[line] ?? "")) return; + } + visited.add(region.id); + for (const n of members.get(region.id) ?? []) if (n.site && ["reader", "prop", "effect", "provide"].includes(n.kind)) sites.add(n.id); + for (const e of out.get(region.id) ?? []) if (e.type === "renders") { + const comp = componentRegion(nodes.get(e.to)); + if (comp) cover(comp, true); + } + for (const child of kids.get(region.id) ?? []) if (child.kind !== "component") cover(child, true); + } + cover(r); + for (const site of sites) { + const todo = [site], seen = new Set(todo); + for (const id of todo) for (const e of inc.get(id) ?? []) { + if (seen.has(e.from) || !(e.type === "passes" || (e.type === "read" && e.mode === "tracked" && !e.probe))) continue; + seen.add(e.from); + const n = nodes.get(e.from); + if (!n) continue; + if (n.async && !n.site && !roots.has(n.id)) roots.set(n.id, { ...ref(n), via: ref(nodes.get(site)) }); + todo.push(e.from); + } + } + return [...roots.values()]; + } + const boundaries = g.regions.filter(isBoundary); + if (method === "find") { + const q = p.query.toLowerCase(); + const rank = ({ name, key }) => { + name = name.toLowerCase(); key = key.toLowerCase(); + const label = key.slice(key.lastIndexOf("|") + 1); + if (q === name || q === key) return 0; + if (name.startsWith(q) || label.startsWith(q)) return 1; + if (q.includes("|") && key.startsWith(q)) return 1; + if (name.includes(q) || label.includes(q)) return 2; + if (!q.includes("|") && key.startsWith(q)) return 3; + return key.includes(q) ? 4 : Infinity; + }; + const candidates = g.nodes.filter(n => p.imports || n.kind !== "import").flatMap(n => [n, ...fields(n).map(field => ({ + ...n, name: `${n.name}.${field}`, key: `${n.key}.${field}`, field, store: n.key, + }))]); + const ranked = candidates.map(n => ({ n, rank: rank(n) })); + // A bare search that hits a symbol needn't also list every node in a + // matching filename. An explicit filename still works as a module filter. + const named = !q.includes(".") && !q.includes("/") && ranked.some(x => x.rank < 3); + const found = ranked.filter(x => x.rank < (named ? 3 : Infinity) && (!x.n.field || x.rank < 3)) + .sort((a, b) => a.rank - b.rank || Number(!!a.n.field) - Number(!!b.n.field)) + .map(({ n }) => ({ ...ref(n), ...(n.field ? { field: n.field, store: n.store } : {}) })); + return result(found, found.map(describe), "no matching nodes"); + } + if (method === "overview") { + const data = g.modules.map((file, mod) => { + const all = g.nodes.filter(n => n.mod === mod), counts = {}; + const ns = p.imports ? all : all.filter(n => n.kind !== "import"); + for (const n of ns) { const role = roles[n.kind] ?? "other"; counts[role] = (counts[role] ?? 0) + 1; } + return { file, counts, ...(!p.imports ? { importsHidden: all.length - ns.length } : {}), components: ns.filter(n => n.kind === "comp").map(ref), + boundaries: boundaries.filter(r => r.mod === mod).map(regionRef), + topLevel: ns.filter(n => !n.site && regions.get(n.region)?.kind === "program").map(ref) }; + }); + return result(data, data.flatMap(m => [ + `${m.file} ${Object.entries(m.counts).map(([k, v]) => `${k}=${v}`).join(" ")}${m.importsHidden ? ` (${m.importsHidden} JS imports hidden)` : ""}`, + ...m.components.map(n => ` component ${describe(n)}`), + ...m.boundaries.map(n => ` boundary ${describe(n)}`), + ...m.topLevel.filter(n => n.kind !== "comp").map(n => ` top-level ${describe(n)}`), + ])); + } + if (method === "boundary") { + if (p.key === undefined) { + const data = boundaries.map(regionRef); + return result(data, data.map(describe), "no loading or errored boundaries"); + } + const r = boundaries.find(r => r.key === p.key); + if (!r) throw unknownKey(p.key, boundaries.map(r => r.key), "boundary"); + const outline = quoteOutline(r, nodes, inc); + const data = { ...regionRef(r), notifiers: notifiers(r), ...(outline ? { outline } : {}) }; + return result(data, [describe(data), ...data.notifiers.map(n => ` ${describe(n)} via ${describe(n.via)}`), + ...(!data.notifiers.length ? [" no known notifiers"] : []), ...(outline ? [` view: ${outline}`] : [])]); + } + const root = byKey.has(p.key) ? p.key : [...byKey.keys()].filter(k => p.key.startsWith(`${k}.`)).sort((a, b) => b.length - a.length)[0]; + const n = byKey.get(root); + const field = root && root !== p.key ? p.key.slice(root.length + 1) : undefined; + if (!n) throw unknownKey(p.key, [...byKey.keys()]); + if (method === "node") { + function linked(type, dir) { + const incoming = dir === "in"; + return ((incoming ? inc : out).get(n.id) ?? []).filter(e => e.type === type && + (!field || ((type === "read" && !incoming || type === "write" && incoming) && overlaps(field, e.field)))) + .map(e => ({ ...ref(nodes.get(incoming ? e.from : e.to)), mode: e.mode, probe: e.probe, op: e.op, field: e.field, at: e.line })); + } + const data = { ...ref(n), ...(field ? { key: p.key, field, store: root } : {}), role: roles[n.kind] ?? "other", + marks: { pending: !!n.async, question: !!n.question, io: !!n.io, trust: !!n.world }, + declaration: g.lines[n.file]?.[n.line] ?? "", component: null, boundaries: [], + reads: linked("read", "in"), writes: linked("write", "out"), calls: linked("call", "out"), + readBy: linked("read", "out"), writtenBy: linked("write", "in") }; + if (!field && ["source", "eq"].includes(n.kind)) data.fields = fields(n).map(field => ({ + key: `${root}.${field}`, field, + readBy: data.readBy.filter(r => overlaps(field, r.field)), writtenBy: data.writtenBy.filter(w => overlaps(field, w.field)), + })); + const sites = n.site ? [n] : data.readBy.map(r => byKey.get(r.key)).filter(x => x?.site); + const outline = sites.map(s => quoteOutline(regions.get(s.region), nodes, inc, s.id)).find(Boolean); + if (outline) data.outline = outline; + for (let r = regions.get(n.region); r; r = regions.get(r.parent)) { + if (r.kind === "component" && !data.component) { + const comp = g.nodes.find(n => n.mod === r.mod && n.kind === "comp" && n.name === r.name); + data.component = comp ? ref(comp) : regionRef(r); + } + if (isBoundary(r)) data.boundaries.push(regionRef(r)); + } + const marks = Object.keys(data.marks).filter(k => data.marks[k]); + return result(data, [ + `${describe(data)} role=${data.role} marks=${marks.join(",") || "none"}`, ` declaration: ${data.declaration.trim()}`, + ...(outline ? [` view: ${outline}`] : []), + ...(data.component ? [` component ${describe(data.component)}`] : []), + ...data.boundaries.map(b => ` boundary ${describe(b)}`), + ...Object.entries({ "read-by": data.readBy, "written-by": data.writtenBy, reads: data.reads, writes: data.writes, calls: data.calls }) + .flatMap(([k, list]) => list.map(x => ` ${k} ${describe(x)}${[x.mode, x.probe, x.op, x.field].filter(Boolean).map(v => ` ${v}`).join("")}`)), + ...(data.fields ?? []).map(f => ` field ${f.field}: read-by ${[...new Set(f.readBy.map(r => r.key))].join(", ") || "none"}; written-by ${[...new Set(f.writtenBy.map(w => w.key))].join(", ") || "none"}`), + ]); + } + const down = p.direction !== "up"; + const todo = [[n.id, !down || !["source", "eq", "props", "reader", "prop"].includes(n.kind), 0]]; + const seen = new Set(), found = new Map(); + if (!down) todo.push([n.id, false, 0]); + for (const [id, imperative, depth, path = id === n.id ? field : undefined] of todo) { + const state = JSON.stringify([id, imperative, path]); + if (seen.has(state)) continue; + seen.add(state); + if (id !== n.id && !found.has(id)) { + const other = nodes.get(id); + found.set(id, { ...(other ? ref(other) : regionRef(regions.get(id))), depth }); + } + if (depth === p.depth) continue; + for (const e of (down ? out : inc).get(id) ?? []) { + if (path) { + // An equation's inbound reads may contribute to any output field. + // The known target/source paths constrain only writes, passes and + // downstream reads at the starting node. + if (down && e.type !== "read") continue; + if ((down || e.type === "write" || e.type === "passes") && !overlaps(path, e.field)) continue; + } + const data = e.type === "passes" || e.type === "renders" || (e.type === "read" && (e.mode === "tracked" || e.probe)); + const next = down ? e.to : e.from; + if (down) { + if (data || (imperative && (e.type === "write" || e.type === "call"))) todo.push([next, e.type === "call", depth + 1, e.type === "passes" ? e.field : undefined]); + } else if (imperative ? e.type === "call" : (data || e.type === "write")) { + const nextPath = e.type === "read" && nodes.get(next)?.kind === "props" ? e.field : undefined; + todo.push([next, !data, depth + 1, nextPath]); + if (data) todo.push([next, true, depth + 1, nextPath]); + } + } + } + const data = [...found.values()]; + return result(data, data.map(x => `${x.depth} ${describe(x)}`), `no ${down ? "downstream" : "upstream"} nodes`); +} + +export function queryDiff(g) { + const byId = new Map(g.nodes.map(n => [n.id, n])); + const changes = g.diff.summary.map(i => ({ ...i, nodes: i.ids.map(id => ref(byId.get(id))) })); + const boundaries = g.regions.filter(r => isBoundary(r) && ["added", "removed"].includes(r.status)) + .map(r => ({ key: r.key, file: g.modules[r.mod], line: r.head?.line, kind: r.kind, status: r.status })); + const textChanges = g.regions.filter(r => r.reason === "text changed").map(r => ({ key: r.key, file: g.modules[r.mod], line: r.head?.line, kind: r.kind })); + return result({ before: g.diff.before, after: g.diff.after, changes, boundaries, textChanges }, + [`${g.diff.before} → ${g.diff.after}`, ...(changes.length ? changes.map(i => + `${i.text.replaceAll("`", "")} [${i.nodes.map(n => `${n.key}${location(n)}`).join("; ")}]`) : boundaries.length || textChanges.length ? [] : ["no notable behavior changes"]), + ...boundaries.map(b => `${b.status} boundary ${describe(b)}`), ...textChanges.map(r => `text changed ${describe(r)}`)]); +} +/** Text rendering of the live recorder's read-only queries. */ +export function liveText(method, data) { + const at = t => `${Math.round(t)}ms`; + const since = r => r.since === undefined ? "" : ` since ${at(r.since)}`; + const who = r => `${r.key ?? r.name}${r.instance === undefined ? "" : ` [instance ${r.continuity ? `${r.continuity.from}→${r.instance} (${r.continuity.status})` : r.instance}${r.ownerPath?.length ? ` · ${r.ownerPath.join(" › ")}` : ""}]`}`; + const val = r => `${who(r)}=${String(r.preview ?? "(no value)").replace(/\r?\n/g, "\\n")}${r.path ? ` [${r.path}]` : ""}${location(r)}`; + const waiting = r => `${who(r)} held${since(r)}${r.blockers?.length ? `: waiting on ${r.blockers.map(b => `${who(b)} ${b.type} #${b.id}${since(b)}${b.via?.length ? ` via ${b.via.join(" → ")}` : ""}`).join(", ")}` : " (no blocker observed)"}`; + const value = r => `${r.error || r.observation || (r.pending && r.preview === undefined) + ? `${who(r)} ${r.observation ?? (r.error ? `${r.failedUntripped ? "failed, untripped" : "error"}: ${r.error}` : "pending (no value yet)")}${location(r)}` + : `${val(r)}${r.pending ? ` pending${since(r)}` : ""}`}${r.held ? `\n${waiting(r.held)}` : ""}${r.untripped + ? `\nfailed but not tripped: no live reader under ${r.untripped.boundary} because ${r.untripped.guards.join(", ")} ${r.untripped.guards.length === 1 ? "is" : "are"} false` : ""}`; + const boundary = r => `${r.region} ${r.state}${r.error ? `: ${r.error}` : ""}`; + const running = r => `${r.key} running #${r.id}${since(r)}`; + const event = r => { + const label = r.type === "boundary" ? `${boundary(r)}${r.origin ? ` ← ${r.origin}` : ""}` + : r.type === "held" ? waiting(r) + : `${who(r)} ${[r.type, r.state, r.id === undefined ? "" : `#${r.id}`, r.args, r.error, r.reason, + r.type === "revert" && r.reason === "superseded" ? "(replaced by the answer, not a failure)" : "", r.origin].filter(Boolean).join(" ")}${location(r)}`; + return `${r.seq} ${at(r.at)} ${label}`; + }; + const change = r => `${r.error ? `${who(r)} error: ${r.error}` : val(r)} ${r.origin ?? "unknown origin"}`; + if (data.instances) return data.instances.map(r => liveText(method, r)).join("\n"); + switch (method) { + case "status": return `connected pages: ${data.pages}\nflushes: ${data.flushes}\nuptime: ${at(data.uptime)}`; + case "tail": return data.flatMap(r => r.type === "flush" ? r.changes.map(c => `${r.seq} ${at(r.at)} ${change(c)}`) : event(r)).join("\n") || "no records"; + case "record": return data.records ? `${data.truncated ? "recording truncated\n" : ""}${liveText("tail", data.records)}` + : data.recording ? `recording since #${data.since} (${data.filter})` : "not recording"; + case "boundary_history": return [data.observation ?? `current: ${boundary(data)}`, ...(data.history ?? []).map(event)].join("\n"); + case "value": return value(data); + case "state": + if (data.observation && !data.key) return data.observation; + if (data.region) return data.observation ?? boundary(data); + if (data.key) return [value(data), ...(data.runs ?? []).map(running)].join("\n"); + return [...data.values.map(value), ...data.boundaries.map(boundary), ...(data.held ?? []).map(waiting), ...data.runs.map(running), ...data.reverts.map(event)].join("\n") || "no live state"; + case "why": return [value(data.current ?? data), ...(data.seq ? [`${data.seq} ${at(data.at)} ${change(data)}`, + ...(data.chain ?? []).map(c => `${" ".repeat(c.depth)}← ${change(c)}`)] : ["no change recorded"]), + ...data.events.map(event), ...(data.readers ?? []).map(r => `${waiting(r)}${location(r)}`)].join("\n"); + case "pending": return data.map(r => `${r.key}${since(r)}${location(r)}`).join("\n") || "no pending requests"; + } +} diff --git a/tooling/rx-map/rx-map.mjs b/tooling/rx-map/rx-map.mjs new file mode 100755 index 000000000..c764eaf99 --- /dev/null +++ b/tooling/rx-map/rx-map.mjs @@ -0,0 +1,112 @@ +#!/usr/bin/env node +// rx-map: draw a .rx program as a static map, straight from the checker's resolved model (`rxc model`, spec/11 CP-6). +// No runtime, no build: where every source, equation, action and view site lives, and how they read, write and call +// each other and the world outside the program. +// +// node tooling/rx-map/rx-map.mjs examples/notes/main.rx -o notes-map.html +// node tooling/rx-map/rx-map.mjs examples/notes/main.rx --diff main # what changed since `main` +// node tooling/rx-map/rx-map.mjs examples/notes/main.rx --diff before.json # against a saved --json graph +// +// `rxc` is found as $RXC, then compiler/target/{release,debug}/rxc in this repo, then `rxc` on PATH. +import { execFileSync } from "node:child_process"; +import { existsSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs"; +import { tmpdir } from "node:os"; +import { basename, dirname, join, relative, resolve } from "node:path"; +import { fileURLToPath } from "node:url"; +import { buildGraph } from "./graph.mjs"; +import { diffGraphs } from "./diff.mjs"; +import { pageHTML } from "./page.mjs"; + +const here = dirname(fileURLToPath(import.meta.url)); +const repo = resolve(here, "../.."); + +function usage(code = 1) { + console.error("usage: rx-map ... [-o out.html] [--json] [--diff ]"); + console.error(" rx-map mcp [--root ] [--entry ...] [--dev ]"); + process.exit(code); +} + +const args = process.argv.slice(2); +if (!args.length || args.includes("-h") || args.includes("--help")) usage(args.length ? 0 : 1); +if (args[0] === "mcp") { + const options = { entries: [] }; + for (let i = 1; i < args.length; i++) { + const flag = args[i], value = args[++i]; + if (!value || value.startsWith("--")) usage(); + if (flag === "--entry") options.entries.push(value); + else if (flag === "--root") options.root = value; + else if (flag === "--dev") options.dev = value; + else usage(); + } + const { serveMcp } = await import("./mcp.mjs"); + await serveMcp(options); +} else runMap(); + +function runMap() { +let out = null, json = false, diff = null; +const entries = []; +for (let i = 0; i < args.length; i++) { + if (args[i] === "-o") out = args[++i]; + else if (args[i] === "--json") json = true; + else if (args[i] === "--diff") diff = args[++i] ?? usage(); + else entries.push(args[i]); +} +if (!entries.length) usage(); + +const rxc = (process.env.RXC && (/[\\/]/.test(process.env.RXC) ? resolve(process.env.RXC) : process.env.RXC)) + ?? [resolve(repo, "compiler/target/release/rxc"), resolve(repo, "compiler/target/debug/rxc")].find(existsSync) + ?? "rxc"; + +/** The graph of `files` (relative to `cwd`), with module paths relative to `cwd` so two checkouts key alike. */ +function graphOf(files, cwd) { + const model = JSON.parse(execFileSync(rxc, ["model", ...files], { cwd, encoding: "utf8", maxBuffer: 1 << 28, stdio: ["ignore", "pipe", "pipe"] })); + return buildGraph(model, { root: cwd }); +} +function fail(e) { process.stderr.write(e.stderr || e.stdout || `${e.message}\n`); process.exit(1); } +const git = (cwd, ...a) => execFileSync("git", a, { cwd, encoding: "utf8", maxBuffer: 1 << 30, stdio: ["ignore", "pipe", "pipe"] }); + +let graph; +if (!diff) { + try { graph = graphOf(entries.map(e => resolve(e)), process.cwd()); } catch (e) { fail(e); } + graph.title = entries.map(e => basename(e)).join(", "); +} else { + // the after side is the working tree; the before side is a git ref, extracted to a scratch dir, or a saved graph + let top; + try { top = git(dirname(resolve(entries[0])), "rev-parse", "--show-toplevel").trim(); } catch { top = process.cwd(); } + const rel = entries.map(e => relative(top, resolve(e))); + let before, after; + try { after = graphOf(rel, top); } catch (e) { fail(e); } + after.label = "working tree"; + if (diff.endsWith(".json") && existsSync(diff)) { + before = JSON.parse(readFileSync(diff, "utf8")); + before.label = basename(diff); + } else { + const scratch = mkdtempSync(join(tmpdir(), "rx-map-")); + try { + const sha = git(top, "rev-parse", "--short", diff).trim(); + // the entries' top-level folders first (fast); the whole tree if an import reaches outside them + const roots = [...new Set(rel.map(r => r.split(/[\\/]/)[0]))]; + const extract = paths => execFileSync("sh", ["-c", `git archive "$0" -- "$@" | tar -x -C "${scratch}"`, sha, ...paths], { cwd: top, stdio: ["ignore", "ignore", "pipe"] }); + extract(roots); + try { before = graphOf(rel, scratch); } + catch { extract(["."]); before = graphOf(rel, scratch); } + before.label = `${diff} (${sha})`; + before.absModules = null; + } catch (e) { rmSync(scratch, { recursive: true, force: true }); fail(e); } + rmSync(scratch, { recursive: true, force: true }); + } + graph = diffGraphs(before, after); + graph.title = `${entries.map(e => basename(e)).join(", ")} · ${before.label} → ${after.label}`; +} + +if (json) { + const text = JSON.stringify(graph, null, 2); + // writeFileSync on fd 1, not process.stdout.write: exiting right after an async write to a pipe cuts it at 64 KB + writeFileSync(out ?? 1, out ? text : text + "\n"); + process.exit(0); +} +out ??= entries[0].replace(/\.rx$/, "") + (diff ? ".diff" : "") + ".map.html"; +writeFileSync(out, pageHTML(graph)); +const s = graph.diff ? ` · ${graph.diff.summary.length} notable changes` : ""; +console.log(`${out}: ${graph.modules.length} module(s), ${graph.nodes.length} nodes, ${graph.edges.length} edges${s}`); +} diff --git a/tooling/rx-map/solid-view.json b/tooling/rx-map/solid-view.json new file mode 100644 index 000000000..34f8776a5 --- /dev/null +++ b/tooling/rx-map/solid-view.json @@ -0,0 +1,6 @@ +{ + "//": "The Solid build the real-host travel/HMR suite runs against (README: Supported Solid builds). openView (solidjs/solid#5089) on the pin in ref/SOLID_NEXT, plus the local openView fixes. CI checks this commit out; the branch must be pushed to the repo below for CI to find it.", + "repo": "devagrawal09/solid", + "branch": "rx/view-on-30e7805", + "commit": "49b25a45c" +} diff --git a/tooling/rx-map/test/conformance.test.mjs b/tooling/rx-map/test/conformance.test.mjs new file mode 100644 index 000000000..0f377d646 --- /dev/null +++ b/tooling/rx-map/test/conformance.test.mjs @@ -0,0 +1,414 @@ +#!/usr/bin/env node +// Fake host against the fixtures, several seeds, plus a host built to fail specific checks. +// Also checks planHmr on synthetic graphs and on five real edits of examples/users.rx. +import { execFileSync } from "node:child_process"; +import { existsSync, readFileSync, readdirSync, writeFileSync } from "node:fs"; +import { dirname, resolve } from "node:path"; +import { fileURLToPath } from "node:url"; +import { runConformance, runConformanceAsync } from "../conformance.mjs"; +import { createFakeHost } from "../fake.mjs"; +import { planHmr } from "../hmr.mjs"; + +const here = dirname(fileURLToPath(import.meta.url)); +const pkg = resolve(here, ".."); +const repo = resolve(pkg, "../.."); +const rxc = process.env.RXC + ?? [resolve(repo, "compiler/target/release/rxc"), "/home/lucifer/work/solidjs/reactivescript/compiler/target/release/rxc"].find(existsSync); + +const fixtures = readdirSync(resolve(here, "fixtures")).filter(f => f.endsWith(".json")).sort().map(f => { + const g = JSON.parse(readFileSync(resolve(here, "fixtures", f), "utf8")); + g.title = f.replace(/\.json$/, ""); + return g; +}); + +let failed = 0; +const check = (name, ok, detail) => { + console.log(`${ok ? "ok " : "FAIL"} ${name}${!ok && detail ? `\n ${detail}` : ""}`); + if (!ok) failed++; +}; + +function drive(seed, graph) { + const host = createFakeHost(graph, { seed, rate: 0 }); + const msgs = []; + host.subscribe(m => msgs.push(m)); + host.post({ type: "hello", want: ["live", "timeline", "travel", "hmr"] }); + for (let i = 0; i < 4; i++) { host.act(); host.tick(6); } + host.editModule(graph.modules[0], "rename"); + host.dispose(); + return msgs; +} + +const notes = fixtures.find(g => g.title === "notes"); +const users = fixtures.find(g => g.title === "users"); + +for (const seed of [1, 3, 7]) { + const a = JSON.stringify(drive(seed, notes)); + const b = JSON.stringify(drive(seed, notes)); + check(`deterministic seed ${seed}`, a === b, a === b ? "" : "two hosts diverged"); +} +check("seeds differ", JSON.stringify(drive(1, notes)) !== JSON.stringify(drive(2, notes))); + +for (const seed of [1, 3, 9, 42]) { + const results = runConformance((g, o) => createFakeHost(g, o), fixtures, { seed }); + for (const r of results) { + const where = r.graph ? `${r.graph}: ` : ""; + check(`${where}${r.check} (seed ${seed})`, r.ok, r.detail); + } +} + +// The fake actually flies, and a flush from an action carries cause, order and origin. +{ + const host = createFakeHost(notes, { seed: 3, rate: 4 }); + const msgs = []; + host.subscribe(m => msgs.push(m)); + host.post({ type: "hello", want: ["live"] }); + host.tick(20); + host.dispose(); + const flights = msgs.filter(m => m.type === "flight"); + const starts = flights.filter(m => m.state === "start"); + const ends = flights.filter(m => m.state === "land" || m.state === "abandon"); + check("notes opens and closes flights", starts.length > 0 && ends.length > 0, `${starts.length} starts, ${ends.length} ends`); + const acted = msgs.filter(m => m.type === "flush" && typeof m.origin === "string" && m.origin.startsWith("action ")); + const meta = acted.length > 0 && acted.every(m => m.cause && Array.isArray(m.order) && m.origin); + check("action flushes carry cause, order, origin", meta, acted.length ? "" : "no action flush"); +} + +// nextPage really ticks the number. +{ + const host = createFakeHost(users, { seed: 1, rate: 0 }); + const msgs = []; + host.subscribe(m => msgs.push(m)); + host.act("examples/users.rx||nextPage"); + host.tick(8); + host.dispose(); + const page = msgs.filter(m => m.type === "flush").flatMap(m => m.changes).find(c => c.name === "page"); + check("nextPage ticks page", page?.preview === "2" && page?.prev === "1", JSON.stringify(page)); +} + +// ---- synthetic plans --------------------------------------------------------------------------------------------- +function mini(nodes, lines, edges = []) { + return { + modules: ["m.rx"], + nodes: nodes.map(n => ({ mod: 0, file: "m.rx", region: "0:r0", line: n.line ?? 1, ...n })), + edges, + regions: [{ id: "0:r0", mod: 0, kind: "program", parent: null }], + lines: { "m.rx": lines }, + }; +} +const read = (from, to) => ({ from, to, type: "read", mode: "tracked", probe: null }); + +{ + const old = mini( + [{ id: "a", kind: "source", name: "a", key: "m.rx||a", line: 1 }, { id: "b", kind: "eq", name: "b", key: "m.rx||b", line: 2 }, { id: "c", kind: "eq", name: "c", key: "m.rx||c", line: 3 }, { id: "go", kind: "action", name: "go", key: "m.rx||go", line: 4 }], + { 1: "source a: number := 1", 2: "b = a", 3: "c = b", 4: "action go() { a := a + 1 }" }, + [read("a", "b"), read("b", "c")], + ); + const same = planHmr(old, old); + check("plan unchanged", same.reasons["m.rx||a"] === "unchanged" && same.reasons["m.rx||go"] === "unchanged" && same.kept.includes("m.rx||b"), JSON.stringify(same.reasons)); + + const init = mini(old.nodes, { ...old.lines["m.rx"], 1: "source a: number := 2" }, old.edges); + init.lines = { "m.rx": { 1: "source a: number := 2", 2: "b = a", 3: "c = b", 4: "action go() { a := a + 1 }" } }; + const initPlan = planHmr(old, init); + check("plan init-changed keeps downstream", initPlan.reasons["m.rx||a"] === "init-changed" && initPlan.kept.includes("m.rx||a") && initPlan.reasons["m.rx||b"] === "unchanged", JSON.stringify(initPlan.reasons)); + + const typed = mini(old.nodes, {}, old.edges); + typed.lines = { "m.rx": { 1: "source a: string := 1", 2: "b = a", 3: "c = b", 4: "action go() { a := a + 1 }" } }; + const typePlan = planHmr(old, typed); + check("plan type-changed resets and reruns downstream", typePlan.reasons["m.rx||a"] === "type-changed" && typePlan.reset.includes("m.rx||a") && typePlan.reasons["m.rx||b"] === "upstream-changed" && typePlan.reasons["m.rx||c"] === "upstream-changed", JSON.stringify(typePlan.reasons)); + + const expr = mini(old.nodes, {}, old.edges); + expr.lines = { "m.rx": { 1: "source a: number := 1", 2: "b = a + 1", 3: "c = b", 4: "action go() { a := a + 1 }" } }; + const exprPlan = planHmr(old, expr); + check("plan expr-changed reruns upstream", exprPlan.reasons["m.rx||b"] === "expr-changed" && exprPlan.reasons["m.rx||c"] === "upstream-changed", JSON.stringify(exprPlan.reasons)); + + const renamed = mini( + [{ id: "b", kind: "eq", name: "bee", key: "m.rx||bee", line: 2 }, { id: "a", kind: "source", name: "a", key: "m.rx||a", line: 1 }], + {}, + [read("a", "b")], + ); + renamed.lines = { "m.rx": { 1: "source a: number := 1", 2: "bee = a" } }; + const renPlan = planHmr( + mini([{ id: "b", kind: "eq", name: "b", key: "m.rx||b", line: 2 }, { id: "a", kind: "source", name: "a", key: "m.rx||a", line: 1 }], { 1: "source a: number := 1", 2: "b = a" }, [read("a", "b")]), + renamed, + ); + check("plan rename is a move", renPlan.moved.some(m => m.from === "m.rx||b" && m.to === "m.rx||bee") && renPlan.reasons["m.rx||b"] === "renamed" && renPlan.reasons["m.rx||bee"] === "unchanged" && renPlan.kept.includes("m.rx||bee"), JSON.stringify(renPlan)); + + const reOld = mini( + [{ id: "x1", kind: "eq", name: "x", key: "m.rx||x", line: 1 }, { id: "x2", kind: "eq", name: "x", key: "m.rx||x#1", line: 2 }], + { 1: "x = 1", 2: "x = 2" }, + ); + const reNew = mini([{ id: "x2", kind: "eq", name: "x", key: "m.rx||x", line: 1 }], { 1: "x = 2" }); + const rePlan = planHmr(reOld, reNew); + check("plan reindex shifts #n without reporting its reused destination twice", rePlan.moved.some(m => m.from === "m.rx||x#1" && m.to === "m.rx||x") && rePlan.reasons["m.rx||x#1"] === "reindexed" && rePlan.kept.includes("m.rx||x") && !rePlan.removed.includes("m.rx||x"), JSON.stringify(rePlan)); + + const scoped = mini([{ id: "x", kind: "eq", name: "x", key: "m.rx|App|x", line: 4 }], { 4: "x = 1" }); + const scopePlan = planHmr(mini([{ id: "x", kind: "eq", name: "x", key: "m.rx||x", line: 1 }], { 1: "x = 1" }), scoped); + check("plan scope-changed resets", scopePlan.moved.some(m => m.from === "m.rx||x" && m.to === "m.rx|App|x") && scopePlan.reset.includes("m.rx|App|x") && scopePlan.reasons["m.rx|App|x"] === "scope-changed", JSON.stringify(scopePlan.reasons)); + + const kindNew = mini([{ id: "a", kind: "eq", name: "a", key: "m.rx||a", line: 1 }], { 1: "a = 1" }); + const kindPlan = planHmr(mini([{ id: "a", kind: "source", name: "a", key: "m.rx||a", line: 1 }], { 1: "source a: number := 1" }), kindNew); + check("plan kind-changed resets", kindPlan.reasons["m.rx||a"] === "kind-changed" && kindPlan.reset.includes("m.rx||a"), JSON.stringify(kindPlan.reasons)); + + const added = mini( + [{ id: "a", kind: "source", name: "a", key: "m.rx||a", line: 1 }, { id: "e", kind: "source", name: "extra", key: "m.rx||extra", line: 2 }], + { 1: "source a: number := 1", 2: "source extra: number := 0" }, + ); + const addPlan = planHmr(mini([{ id: "a", kind: "source", name: "a", key: "m.rx||a", line: 1 }], { 1: "source a: number := 1" }), added); + check("plan add and the complement", addPlan.added.includes("m.rx||extra") && addPlan.reasons["m.rx||extra"] === "new" && addPlan.reasons["m.rx||a"] === "unchanged"); + + const gone = planHmr(added, mini([{ id: "a", kind: "source", name: "a", key: "m.rx||a", line: 1 }], { 1: "source a: number := 1" })); + check("plan remove", gone.removed.includes("m.rx||extra") && gone.reasons["m.rx||extra"] === "gone"); + + const actNew = mini([{ id: "go", kind: "action", name: "go", key: "m.rx||go", line: 1 }], { 1: "action go() { a := 2 }" }); + const actPlan = planHmr(mini([{ id: "go", kind: "action", name: "go", key: "m.rx||go", line: 1 }], { 1: "action go() { a := 1 }" }), actNew); + check("plan action body reruns", actPlan.rerun.includes("m.rx||go") && actPlan.reasons["m.rx||go"] === "expr-changed"); + + const hinted = planHmr( + mini([{ id: "b", kind: "eq", name: "b", key: "m.rx||b", line: 1 }], { 1: "b = 1" }), + mini([{ id: "b", kind: "eq", name: "bee", key: "m.rx||bee", line: 1 }], { 1: "bee = 1" }), + { renamed: [{ from: "m.rx||b", to: "m.rx||bee" }] }, + ); + check("plan honors a rename hint", hinted.moved.some(m => m.from === "m.rx||b" && m.to === "m.rx||bee")); +} + +// ---- real edits of users.rx -------------------------------------------------------------------------------------- +function graphOf(file) { + const out = execFileSync(process.execPath, [resolve(pkg, "rx-map.mjs"), file, "--json"], { + cwd: repo, + env: { ...process.env, RXC: rxc }, + encoding: "utf8", + maxBuffer: 1 << 26, + }); + return JSON.parse(out); +} +function suffix(graph, name) { + return graph.nodes.find(n => n.name === name && (n.kind === "source" || n.kind === "eq" || n.kind === "action"))?.key; +} + +if (!rxc) { + check("real edits", false, "rxc not found"); +} else { + const file = "/tmp/rx-trace-users.rx"; + const src = readFileSync(resolve(repo, "examples/users.rx"), "utf8"); + const variants = { + rename: src.replace("status = ", "label = ").replace("{status}", "{label}"), + expr: src.replace("total = len(users)", "total = len(users) + 1"), + init: src.replace("source page: number := 1", "source page: number := 2"), + type: src.replace('source saveError: string := ""', 'source saveError: string | null := ""'), + addremove: src + .replace("total = len(users)\n", "") + .replace('status = pending? users ? "loading…" : `${total} users`', 'status = pending? users ? "loading…" : "ready"') + .replace('source saveError: string := ""\n', 'source saveError: string := ""\nsource extra: number := 0\n'), + }; + writeFileSync(file, src); + const before = graphOf(file); + const line = (title, plan, ok) => { + check(title, ok, JSON.stringify({ kept: plan.kept.length, reset: plan.reset, rerun: plan.rerun, added: plan.added, removed: plan.removed, moved: plan.moved })); + if (ok) console.log(` ${title}`); + }; + for (const [name, text] of Object.entries(variants)) { + writeFileSync(file, text); + const after = graphOf(file); + const plan = planHmr(before, after); + const reason = (n) => plan.reasons[suffix(after, n) ?? suffix(before, n)]; + if (name === "rename") { + const from = suffix(before, "status"); + const to = suffix(after, "label"); + line("real edit rename status → label", plan, plan.moved.some(m => m.from === from && m.to === to) && plan.reasons[from] === "renamed" && plan.kept.includes(to)); + } else if (name === "expr") { + line("real edit equation expression", plan, reason("total") === "expr-changed" && reason("status") === "upstream-changed"); + } else if (name === "init") { + line("real edit source initialiser", plan, reason("page") === "init-changed" && plan.kept.includes(suffix(after, "page")) && reason("users") === "unchanged"); + } else if (name === "type") { + line("real edit source type", plan, reason("saveError") === "type-changed" && plan.reset.includes(suffix(after, "saveError"))); + } else if (name === "addremove") { + line("real edit add and remove", plan, plan.added.some(k => k.endsWith("|extra")) && plan.removed.some(k => k.endsWith("|total")) && reason("status") === "expr-changed"); + } + } +} + +// A host that corrupts the protocol must fail these checks, and not pass them. +const MUST_FAIL = [ + "seq strictly increasing", + "at non-decreasing", + "change keys exist", + "flight start before end", + "no double flight start", + "step changes exact", + "hmr partition", + "hmr reasons cover plan", + "hmr done changes subset", +]; +function makeBroken(graph, opts) { + const real = createFakeHost(graph, opts); + return { + post: real.post, + tick: real.tick, + act: real.act, + editModule: real.editModule, + dispose: real.dispose, + subscribe(fn) { + return real.subscribe(m => { + if (m.type === "flush") fn({ ...m, seq: 1, at: m.seq > 1 ? 0 : m.at, changes: [...(m.changes ?? []), { key: "missing", name: "missing", preview: "1" }] }); + else if (m.type === "flight" && m.state === "start") { fn({ ...m, state: "land" }); fn(m); fn(m); } + else if (m.type === "step") fn({ ...m, changes: [{ key: "bogus", name: "bogus", preview: "no" }] }); + else if (m.type === "hmr" && m.phase === "plan") { + const plan = { ...m.plan, kept: [...(m.plan.kept ?? []), "dup"], removed: [...(m.plan.removed ?? []), "dup"], reasons: {} }; + fn({ ...m, plan }); + } else if (m.type === "hmr" && m.phase === "done") { + fn({ ...m, changes: [...(m.changes ?? []), { key: "not-in-plan", name: "x", preview: "1" }] }); + } else fn(m); + }); + }, + }; +} +{ + const bad = runConformance(makeBroken, [users], { seed: 1 }); + const failedChecks = new Set(bad.filter(r => !r.ok && r.graph).map(r => r.check)); + for (const name of MUST_FAIL) check(`broken host fails ${name}`, failedChecks.has(name), [...failedChecks].join(", ") || "nothing failed"); + const passed = MUST_FAIL.filter(name => !failedChecks.has(name)); + if (passed.length) { + for (const r of bad.filter(r => !r.ok)) console.log(` broken: ${r.check}: ${r.detail ?? ""}`); + } +} + +// First-change prev (§4b): a key first changed at seq 3 had its `prev` at seqs 1-2. A host that replays without that +// rule (the key absent before its first change) fails the travel checks; one that follows it passes. +{ + const [k1, k2, k3] = users.nodes.filter(n => n.key && n.kind === "source").map(n => n.key); + const ERR = "\u0000error\u0000"; + // `errors`: k3 shows an error at seq 2 and a value from seq 4; `errorState`: the host keeps the error as k3's state + const scripted = (firstPrev, { errors = false, errorState = true } = {}) => () => { + const subs = new Set(), steps = []; + let viewing = null; + const emit = m => { for (const f of subs) f({ source: "rx-map", v: 1, ...m }); }; + const valuesAt = n => { + const m = new Map(), seen = new Set(); + if (firstPrev) for (const s of steps) for (const c of s.changes) if (!seen.has(c.key)) { seen.add(c.key); if (c.prev !== undefined) m.set(c.key, c.prev); } + for (const s of steps) if (s.seq <= n) for (const c of s.changes) { + const v = c.error !== undefined ? (errorState ? ERR + c.error : undefined) : c.preview; + if (v === undefined) m.delete(c.key); else m.set(c.key, v); + } + return m; + }; + const side = (v, value, error) => v === undefined ? {} : v.startsWith(ERR) ? { [error]: v.slice(ERR.length) } : { [value]: v }; + const diff = (a, b) => [...new Set([...a.keys(), ...b.keys()])].filter(k => a.get(k) !== b.get(k)) + .map(k => ({ key: k, name: k, ...side(a.get(k), "prev", "prevError"), ...side(b.get(k), "preview", "error") })); + return { + subscribe: f => (subs.add(f), () => subs.delete(f)), + act() { + const seq = steps.length + 1; + const changes = [{ key: k1, name: "a", prev: String(seq - 1), preview: String(seq) }]; + if (seq === 3) changes.push({ key: k2, name: "b", prev: "\"before\"", preview: "\"after\"" }); + if (errors && seq === 2) changes.push({ key: k3, name: "c", error: "NotFound" }); + if (errors && seq === 4) changes.push({ key: k3, name: "c", preview: "1" }); + steps.push({ seq, at: seq, changes }); + if (viewing == null) emit({ type: "flush", seq, at: seq, changes }); + }, + tick() {}, + post(m) { + const head = steps.length; + if (m.type === "hello") emit({ type: "timeline", head, viewing, steps, capacity: 2000 }); + else if (m.type === "travel") { + if (m.to < 1 || m.to > head) return emit({ type: "travel-denied", to: m.to, reason: "evicted" }); + const from = viewing ?? head; + viewing = m.to; + emit({ type: "step", from, to: m.to, direction: "back", changes: diff(valuesAt(from), valuesAt(m.to)) }); + } else if (m.type === "resume") { + const from = viewing ?? head; + viewing = null; + emit({ type: "resume", head, changes: diff(valuesAt(from), valuesAt(head)) }); + } + }, + editModule() { throw new Error("no hmr"); }, + }; + }; + const travelChecks = ["travel matches replay", "step changes exact", "travel commutative", "resume matches live"]; + const okOf = r => travelChecks.map(c => r.find(x => x.check === c && x.graph)?.ok); + check("a host following first-change prev passes the travel checks", okOf(runConformance(scripted(true), [users])).every(Boolean)); + check("a host ignoring it fails them", !okOf(runConformance(scripted(false), [users]))[1]); + // v0.6: an error is a shown state; step/resume changes carry `error`/`prevError` for it + check("a host keeping errors as states passes the travel checks", okOf(runConformance(scripted(true, { errors: true }), [users])).every(Boolean)); + check("a host dropping them fails", !okOf(runConformance(scripted(true, { errors: true, errorState: false }), [users])).every(Boolean)); +} + +// The arbiter (§5): hosts that send self-consistent messages but whose app shows something else must fail. +{ + const wrap = (mutate) => (g, o) => { + const h = createFakeHost(g, o); + const subs = new Set(); + const st = { viewing: null, frozen: null, head: 0, cut: null }; + h.subscribe(m => { + if (m.type === "flush") st.head = Math.max(st.head, m.seq); + for (const out of mutate.message?.(m, st, h) ?? [m]) for (const f of subs) f(out); + }); + return { ...h, subscribe: f => (subs.add(f), () => subs.delete(f)), + post: m => { mutate.post?.(m, st, h); return h.post(m); }, + act: k => { const r = h.act(k); mutate.act?.(st, f => subs.forEach(x => x(f))); return r; }, + editModule: (m, x) => h.editModule(m, x), + shown: keys => mutate.shown ? mutate.shown(keys, st, h) : h.shown(keys) }; + }; + const msg = m => ({ source: "rx-map", v: 1, ...m }); + const cases = { + // the app doesn't rewind: it keeps showing what it showed when travel was asked for + "app shows the travelled state": wrap({ + post: (m, st, h) => { if (m.type === "travel" && st.frozen === null) st.frozen = h.shown(); if (m.type === "resume") st.frozen = null; }, + shown: (keys, st, h) => st.frozen ?? h.shown(keys), + }), + // work done while viewing runs in the app, but its step never reaches the timeline + "flushes during viewing kept": wrap({ + message: (m, st) => { + if (m.type === "step" && st.cut === null) st.cut = st.head; + if (st.cut !== null && m.type === "resume") return [{ ...m, head: st.cut }]; + if (st.cut !== null && m.type === "timeline") return [{ ...m, head: st.cut, steps: m.steps.filter(x => x.seq <= st.cut) }]; + if (st.cut !== null && m.type === "flush" && m.seq > st.cut) return []; + return [m]; + }, + }), + // the snapshot reports values the app doesn't show + "snapshot shows what the app shows": wrap({ + message: m => [m.type === "snapshot" ? { ...m, values: m.values.map(v => ({ ...v, preview: "\"stale\"" })) } : m], + }), + // malformed v0.3-v0.7 messages + "runs pair start with end or error": wrap({ act: (st, send) => send(msg({ type: "run", key: users.nodes.find(n => n.kind === "action").key, id: 9999, state: "end", at: 1e9 })) }), + "held before released": wrap({ act: (st, send) => send(msg({ type: "released", key: users.nodes.find(n => n.kind === "source").key, at: 1e9 })) }), + "an error change carries no preview": wrap({ + message: m => [m.type === "flush" && m.changes[0] ? { ...m, changes: [{ ...m.changes[0], error: "boom" }, ...m.changes.slice(1)] } : m], + }), + "hmr uncarried keys reported with refresh": wrap({ + message: m => [m.type === "hmr" && m.phase === "done" ? { ...m, uncarried: [users.nodes.find(n => n.key).key] } : m], + }), + }; + for (const [name, make] of Object.entries(cases)) { + const r = runConformance(make, [users], { seed: 1 }); + const hit = r.find(x => x.check === name && x.graph); + check(`a broken host fails "${name}": ${hit?.detail ?? ""}`.slice(0, 160), hit && !hit.ok, hit ? hit.detail ?? "passed" : "check not run"); + } + const lying = runConformance(cases["snapshot shows what the app shows"], [users], { seed: 1 }); + check("…and its snapshot also disagrees with the timeline head", lying.some(x => x.check === "values per live instance: snapshot agrees with the timeline head" && !x.ok)); +} + +// The async runner (a host whose calls take time, e.g. a real app in a browser) reports what the sync one does, and +// a rejected call lands on the check that made it. +{ + const later = v => new Promise(r => setTimeout(() => r(v), 0)); + const slow = (g, o) => { + const h = createFakeHost(g, o); + return later({ ...h, post: m => later(h.post(m)), act: k => later(h.act(k)), tick: n => later(h.tick(n)), + editModule: (m, x) => later(h.editModule(m, x)), dispose: () => later(h.dispose()) }); + }; + const sync = runConformance((g, o) => createFakeHost(g, o), fixtures, { seed: 1 }); + const async = await runConformanceAsync(slow, fixtures, { seed: 1 }); + check("async runner matches the sync runner", JSON.stringify(async) === JSON.stringify(sync), + async.filter((r, i) => JSON.stringify(r) !== JSON.stringify(sync[i])).slice(0, 2).map(r => JSON.stringify(r)).join("; ")); + const rejecting = (g, o) => { const h = createFakeHost(g, o); return { ...h, editModule: () => Promise.reject(new Error("no hmr here")) }; }; + const r = await runConformanceAsync(rejecting, fixtures.slice(0, 1), { seed: 1 }); + check("async runner: a rejected call fails its check", r.some(x => !x.ok && x.check === "hmr partition" && x.detail === "no hmr here") + && r.filter(x => x.check === "travel matches replay").every(x => x.ok), JSON.stringify(r.filter(x => !x.ok))); +} + +if (failed) { + console.log(`${failed} failed`); + process.exit(1); +} +console.log("all passed"); diff --git a/tooling/rx-map/test/engine.html b/tooling/rx-map/test/engine.html new file mode 100644 index 000000000..9f01b4c5a --- /dev/null +++ b/tooling/rx-map/test/engine.html @@ -0,0 +1,350 @@ + + +rx-map live: engine harness + + + +
    + + diff --git a/tooling/rx-map/test/fake.html b/tooling/rx-map/test/fake.html new file mode 100644 index 000000000..1aed926e2 --- /dev/null +++ b/tooling/rx-map/test/fake.html @@ -0,0 +1,105 @@ + + +rx-map fake: the page runs the fake host itself + + + + diff --git a/tooling/rx-map/test/fixtures/api.d.rx b/tooling/rx-map/test/fixtures/api.d.rx new file mode 100644 index 000000000..06ad5ff97 --- /dev/null +++ b/tooling/rx-map/test/fixtures/api.d.rx @@ -0,0 +1,3 @@ +export error NotFound +export error ServerError +export pure fn fetchIssue(id: number): Promise rejects(NotFound | ServerError) diff --git a/tooling/rx-map/test/fixtures/boundaries.rx b/tooling/rx-map/test/fixtures/boundaries.rx new file mode 100644 index 000000000..735d64bea --- /dev/null +++ b/tooling/rx-map/test/fixtures/boundaries.rx @@ -0,0 +1,23 @@ +// Nested boundaries: each one is labelled with its own catch, not the one inside it. +import pure { fetchIssue, NotFound } from "./api" + +source issueId: number := 1 +title = await fetchIssue(issueId) + +export component IssueDetail() { +
    + {errored fallback(e) { +

    Something failed: {e.message}

    + } { +
    + {errored fallback(e: NotFound) { +

    No such issue

    + } { + {loading on(issueId) fallback {

    Loading issue…

    } { +

    {title}

    + }} + }} +
    + }} +
    +} diff --git a/tooling/rx-map/test/fixtures/cart.json b/tooling/rx-map/test/fixtures/cart.json new file mode 100644 index 000000000..81ba2e6d9 --- /dev/null +++ b/tooling/rx-map/test/fixtures/cart.json @@ -0,0 +1,1083 @@ +{ + "modules": [ + "examples/cart.rx" + ], + "nodes": [ + { + "id": "0:s0", + "mod": 0, + "file": "examples/cart.rx", + "kind": "import", + "name": "fetchProducts", + "line": 6, + "region": "0:r0", + "io": false, + "question": false, + "async": false, + "world": true, + "base": "examples/cart.rx||fetchProducts", + "key": "examples/cart.rx||fetchProducts" + }, + { + "id": "0:s1", + "mod": 0, + "file": "examples/cart.rx", + "kind": "import", + "name": "validateCoupon", + "line": 6, + "region": "0:r0", + "io": false, + "question": false, + "async": false, + "world": true, + "base": "examples/cart.rx||validateCoupon", + "key": "examples/cart.rx||validateCoupon" + }, + { + "id": "0:s2", + "mod": 0, + "file": "examples/cart.rx", + "kind": "import", + "name": "checkout", + "line": 6, + "region": "0:r0", + "io": false, + "question": false, + "async": false, + "world": true, + "base": "examples/cart.rx||checkout", + "key": "examples/cart.rx||checkout" + }, + { + "id": "0:s3", + "mod": 0, + "file": "examples/cart.rx", + "kind": "source", + "name": "products", + "line": 11, + "region": "0:r0", + "io": false, + "question": true, + "async": true, + "world": false, + "base": "examples/cart.rx||products", + "key": "examples/cart.rx||products" + }, + { + "id": "0:s4", + "mod": 0, + "file": "examples/cart.rx", + "kind": "source", + "name": "cart", + "line": 12, + "region": "0:r0", + "io": false, + "question": true, + "async": false, + "world": false, + "base": "examples/cart.rx||cart", + "key": "examples/cart.rx||cart" + }, + { + "id": "0:s5", + "mod": 0, + "file": "examples/cart.rx", + "kind": "source", + "name": "coupon", + "line": 13, + "region": "0:r0", + "io": false, + "question": false, + "async": false, + "world": false, + "base": "examples/cart.rx||coupon", + "key": "examples/cart.rx||coupon" + }, + { + "id": "0:s6", + "mod": 0, + "file": "examples/cart.rx", + "kind": "source", + "name": "lastOrder", + "line": 14, + "region": "0:r0", + "io": false, + "question": false, + "async": false, + "world": false, + "base": "examples/cart.rx||lastOrder", + "key": "examples/cart.rx||lastOrder" + }, + { + "id": "0:s7", + "mod": 0, + "file": "examples/cart.rx", + "kind": "fn", + "name": "qtyOf", + "line": 16, + "region": "0:r0", + "io": false, + "question": false, + "async": false, + "world": false, + "base": "examples/cart.rx||qtyOf", + "key": "examples/cart.rx||qtyOf" + }, + { + "id": "0:s8", + "mod": 0, + "file": "examples/cart.rx", + "kind": "eq", + "name": "count", + "line": 18, + "region": "0:r0", + "io": false, + "question": false, + "async": false, + "world": false, + "base": "examples/cart.rx||count", + "key": "examples/cart.rx||count" + }, + { + "id": "0:s9", + "mod": 0, + "file": "examples/cart.rx", + "kind": "eq", + "name": "subtotal", + "line": 19, + "region": "0:r0", + "io": false, + "question": false, + "async": false, + "world": false, + "base": "examples/cart.rx||subtotal", + "key": "examples/cart.rx||subtotal" + }, + { + "id": "0:s10", + "mod": 0, + "file": "examples/cart.rx", + "kind": "eq", + "name": "discount", + "line": 20, + "region": "0:r0", + "io": false, + "question": false, + "async": true, + "world": false, + "base": "examples/cart.rx||discount", + "key": "examples/cart.rx||discount" + }, + { + "id": "0:s11", + "mod": 0, + "file": "examples/cart.rx", + "kind": "eq", + "name": "total", + "line": 21, + "region": "0:r0", + "io": false, + "question": false, + "async": false, + "world": false, + "base": "examples/cart.rx||total", + "key": "examples/cart.rx||total" + }, + { + "id": "0:s12", + "mod": 0, + "file": "examples/cart.rx", + "kind": "action", + "name": "setQty", + "line": 23, + "region": "0:r0", + "io": true, + "question": false, + "async": false, + "world": false, + "base": "examples/cart.rx||setQty", + "key": "examples/cart.rx||setQty" + }, + { + "id": "0:s13", + "mod": 0, + "file": "examples/cart.rx", + "kind": "source", + "name": "orderError", + "line": 31, + "region": "0:r0", + "io": false, + "question": false, + "async": false, + "world": false, + "base": "examples/cart.rx||orderError", + "key": "examples/cart.rx||orderError" + }, + { + "id": "0:s14", + "mod": 0, + "file": "examples/cart.rx", + "kind": "action", + "name": "placeOrder", + "line": 33, + "region": "0:r0", + "io": true, + "question": false, + "async": false, + "world": false, + "base": "examples/cart.rx||placeOrder", + "key": "examples/cart.rx||placeOrder" + }, + { + "id": "0:s15", + "mod": 0, + "file": "examples/cart.rx", + "kind": "comp", + "name": "Row", + "line": 48, + "region": "0:r0", + "io": false, + "question": false, + "async": false, + "world": false, + "base": "examples/cart.rx||Row", + "key": "examples/cart.rx||Row" + }, + { + "id": "0:s16", + "mod": 0, + "file": "examples/cart.rx", + "kind": "comp", + "name": "App", + "line": 59, + "region": "0:r0", + "io": false, + "question": false, + "async": false, + "world": false, + "base": "examples/cart.rx||App", + "key": "examples/cart.rx||App" + }, + { + "id": "0:s17", + "mod": 0, + "file": "examples/cart.rx", + "kind": "props", + "name": "props", + "line": 48, + "region": "0:r1", + "io": false, + "question": false, + "async": false, + "world": false, + "base": "examples/cart.rx|Row|props", + "key": "examples/cart.rx|Row|props" + }, + { + "id": "0:s18", + "mod": 0, + "file": "examples/cart.rx", + "kind": "eq", + "name": "qty", + "line": 49, + "region": "0:r1", + "io": false, + "question": false, + "async": false, + "world": false, + "base": "examples/cart.rx|Row|qty", + "key": "examples/cart.rx|Row|qty" + }, + { + "id": "0:s19", + "mod": 0, + "file": "examples/cart.rx", + "kind": "props", + "name": "props", + "line": 59, + "region": "0:r2", + "io": false, + "question": false, + "async": false, + "world": false, + "base": "examples/cart.rx|App|props", + "key": "examples/cart.rx|App|props" + }, + { + "id": "0:c13", + "mod": 0, + "file": "examples/cart.rx", + "kind": "reader", + "site": true, + "name": "{…}", + "line": 51, + "region": "0:r1", + "base": "examples/cart.rx|/component:Row|reader:{…}", + "sig": "props", + "key": "examples/cart.rx|/component:Row|reader:{…}" + }, + { + "id": "0:c14", + "mod": 0, + "file": "examples/cart.rx", + "kind": "reader", + "site": true, + "name": "{…}", + "line": 52, + "region": "0:r1", + "base": "examples/cart.rx|/component:Row|reader:{…}", + "sig": "props", + "key": "examples/cart.rx|/component:Row|reader:{…}#1" + }, + { + "id": "0:c15", + "mod": 0, + "file": "examples/cart.rx", + "kind": "handler", + "site": true, + "name": "button onClick", + "line": 53, + "region": "0:r1", + "base": "examples/cart.rx|/component:Row|handler:button onClick", + "sig": "props,qty", + "key": "examples/cart.rx|/component:Row|handler:button onClick" + }, + { + "id": "0:c16", + "mod": 0, + "file": "examples/cart.rx", + "kind": "reader", + "site": true, + "name": "button disabled", + "line": 53, + "region": "0:r1", + "base": "examples/cart.rx|/component:Row|reader:button disabled", + "sig": "qty", + "key": "examples/cart.rx|/component:Row|reader:button disabled" + }, + { + "id": "0:c17", + "mod": 0, + "file": "examples/cart.rx", + "kind": "reader", + "site": true, + "name": "{…}", + "line": 54, + "region": "0:r1", + "base": "examples/cart.rx|/component:Row|reader:{…}", + "sig": "qty", + "key": "examples/cart.rx|/component:Row|reader:{…}#2" + }, + { + "id": "0:c18", + "mod": 0, + "file": "examples/cart.rx", + "kind": "handler", + "site": true, + "name": "button onClick", + "line": 55, + "region": "0:r1", + "base": "examples/cart.rx|/component:Row|handler:button onClick", + "sig": "props,qty", + "key": "examples/cart.rx|/component:Row|handler:button onClick#1" + }, + { + "id": "0:c19", + "mod": 0, + "file": "examples/cart.rx", + "kind": "reader", + "site": true, + "name": "p class", + "line": 60, + "region": "0:r2", + "base": "examples/cart.rx|/component:App|reader:p class", + "sig": "", + "key": "examples/cart.rx|/component:App|reader:p class" + }, + { + "id": "0:c20", + "mod": 0, + "file": "examples/cart.rx", + "kind": "reader", + "site": true, + "name": "{…}", + "line": 60, + "region": "0:r2", + "base": "examples/cart.rx|/component:App|reader:{…}", + "sig": "", + "key": "examples/cart.rx|/component:App|reader:{…}" + }, + { + "id": "0:c21", + "mod": 0, + "file": "examples/cart.rx", + "kind": "reader", + "site": true, + "name": "{…}", + "line": 62, + "region": "0:r3", + "base": "examples/cart.rx|/component:App/errored|reader:{…}", + "sig": "count", + "key": "examples/cart.rx|/component:App/errored|reader:{…}" + }, + { + "id": "0:c22", + "mod": 0, + "file": "examples/cart.rx", + "kind": "reader", + "site": true, + "name": "for", + "line": 63, + "region": "0:r3", + "base": "examples/cart.rx|/component:App/errored|reader:for", + "sig": "products", + "key": "examples/cart.rx|/component:App/errored|reader:for" + }, + { + "id": "0:c23", + "mod": 0, + "file": "examples/cart.rx", + "kind": "prop", + "site": true, + "name": "Row product", + "line": 63, + "region": "0:r4", + "base": "examples/cart.rx|/component:App/errored/for|prop:Row product", + "sig": "", + "key": "examples/cart.rx|/component:App/errored/for|prop:Row product" + }, + { + "id": "0:c24", + "mod": 0, + "file": "examples/cart.rx", + "kind": "reader", + "site": true, + "name": "input value", + "line": 65, + "region": "0:r3", + "base": "examples/cart.rx|/component:App/errored|reader:input value", + "sig": "coupon", + "key": "examples/cart.rx|/component:App/errored|reader:input value" + }, + { + "id": "0:c25", + "mod": 0, + "file": "examples/cart.rx", + "kind": "handler", + "site": true, + "name": "input onInput", + "line": 65, + "region": "0:r3", + "base": "examples/cart.rx|/component:App/errored|handler:input onInput", + "sig": "", + "key": "examples/cart.rx|/component:App/errored|handler:input onInput" + }, + { + "id": "0:c26", + "mod": 0, + "file": "examples/cart.rx", + "kind": "reader", + "site": true, + "name": "{…}", + "line": 66, + "region": "0:r3", + "base": "examples/cart.rx|/component:App/errored|reader:{…}", + "sig": "coupon,discount,discount", + "key": "examples/cart.rx|/component:App/errored|reader:{…}#1" + }, + { + "id": "0:c27", + "mod": 0, + "file": "examples/cart.rx", + "kind": "reader", + "site": true, + "name": "{…}", + "line": 68, + "region": "0:r3", + "base": "examples/cart.rx|/component:App/errored|reader:{…}", + "sig": "subtotal", + "key": "examples/cart.rx|/component:App/errored|reader:{…}#2" + }, + { + "id": "0:c28", + "mod": 0, + "file": "examples/cart.rx", + "kind": "reader", + "site": true, + "name": "{…}", + "line": 69, + "region": "0:r3", + "base": "examples/cart.rx|/component:App/errored|reader:{…}", + "sig": "total", + "key": "examples/cart.rx|/component:App/errored|reader:{…}#3" + }, + { + "id": "0:c29", + "mod": 0, + "file": "examples/cart.rx", + "kind": "handler", + "site": true, + "name": "button onClick", + "line": 70, + "region": "0:r3", + "base": "examples/cart.rx|/component:App/errored|handler:button onClick", + "sig": "", + "key": "examples/cart.rx|/component:App/errored|handler:button onClick" + }, + { + "id": "0:c30", + "mod": 0, + "file": "examples/cart.rx", + "kind": "reader", + "site": true, + "name": "button disabled", + "line": 70, + "region": "0:r3", + "base": "examples/cart.rx|/component:App/errored|reader:button disabled", + "sig": "cart,count", + "key": "examples/cart.rx|/component:App/errored|reader:button disabled" + }, + { + "id": "0:c31", + "mod": 0, + "file": "examples/cart.rx", + "kind": "reader", + "site": true, + "name": "{…}", + "line": 71, + "region": "0:r3", + "base": "examples/cart.rx|/component:App/errored|reader:{…}", + "sig": "cart,lastOrder,orderError", + "key": "examples/cart.rx|/component:App/errored|reader:{…}#4" + } + ], + "edges": [ + { + "from": "0:s3", + "to": "0:s0", + "type": "call", + "line": 11 + }, + { + "from": "0:s4", + "to": "0:s7", + "type": "read", + "mode": "tracked", + "probe": null, + "field": "find", + "line": 16 + }, + { + "from": "0:s4", + "to": "0:s8", + "type": "read", + "mode": "tracked", + "probe": null, + "field": "reduce", + "line": 18 + }, + { + "from": "0:s3", + "to": "0:s9", + "type": "read", + "mode": "tracked", + "probe": null, + "field": "reduce", + "line": 19 + }, + { + "from": "0:s9", + "to": "0:s7", + "type": "call", + "line": 19 + }, + { + "from": "0:s5", + "to": "0:s10", + "type": "read", + "mode": "tracked", + "probe": null, + "field": null, + "line": 20 + }, + { + "from": "0:s10", + "to": "0:s1", + "type": "call", + "line": 20 + }, + { + "from": "0:s9", + "to": "0:s11", + "type": "read", + "mode": "tracked", + "probe": null, + "field": null, + "line": 21 + }, + { + "from": "0:s10", + "to": "0:s11", + "type": "read", + "mode": "tracked", + "probe": "latest", + "field": null, + "line": 21 + }, + { + "from": "0:s12", + "to": "0:s4", + "type": "write", + "op": "write", + "path": false, + "line": 23 + }, + { + "from": "0:s8", + "to": "0:s14", + "type": "read", + "mode": "snapshot", + "probe": null, + "field": null, + "line": 33 + }, + { + "from": "0:s4", + "to": "0:s14", + "type": "read", + "mode": "snapshot", + "probe": null, + "field": null, + "line": 33 + }, + { + "from": "0:s5", + "to": "0:s14", + "type": "read", + "mode": "snapshot", + "probe": null, + "field": null, + "line": 33 + }, + { + "from": "0:s14", + "to": "0:s4", + "type": "write", + "op": "optimistic", + "path": false, + "line": 33 + }, + { + "from": "0:s14", + "to": "0:s4", + "type": "write", + "op": "affects", + "path": false, + "line": 33 + }, + { + "from": "0:s14", + "to": "0:s13", + "type": "write", + "op": "write", + "path": false, + "line": 33 + }, + { + "from": "0:s14", + "to": "0:s4", + "type": "write", + "op": "write", + "path": false, + "line": 33 + }, + { + "from": "0:s14", + "to": "0:s6", + "type": "write", + "op": "write", + "path": false, + "line": 33 + }, + { + "from": "0:s14", + "to": "0:s2", + "type": "call", + "line": 33 + }, + { + "from": "0:s17", + "to": "0:s18", + "type": "read", + "mode": "tracked", + "probe": null, + "field": "product", + "line": 49 + }, + { + "from": "0:s18", + "to": "0:s7", + "type": "call", + "line": 49 + }, + { + "from": "0:s17", + "to": "0:c13", + "type": "read", + "mode": "tracked", + "probe": null, + "field": "product", + "line": 51 + }, + { + "from": "0:s17", + "to": "0:c14", + "type": "read", + "mode": "tracked", + "probe": null, + "field": "product", + "line": 52 + }, + { + "from": "0:s17", + "to": "0:c15", + "type": "read", + "mode": "snapshot", + "probe": null, + "field": "product", + "line": 53 + }, + { + "from": "0:s18", + "to": "0:c15", + "type": "read", + "mode": "snapshot", + "probe": null, + "field": null, + "line": 53 + }, + { + "from": "0:c15", + "to": "0:s12", + "type": "call", + "line": 53 + }, + { + "from": "0:s18", + "to": "0:c16", + "type": "read", + "mode": "tracked", + "probe": null, + "field": null, + "line": 53 + }, + { + "from": "0:s18", + "to": "0:c17", + "type": "read", + "mode": "tracked", + "probe": null, + "field": null, + "line": 54 + }, + { + "from": "0:s17", + "to": "0:c18", + "type": "read", + "mode": "snapshot", + "probe": null, + "field": "product", + "line": 55 + }, + { + "from": "0:s18", + "to": "0:c18", + "type": "read", + "mode": "snapshot", + "probe": null, + "field": null, + "line": 55 + }, + { + "from": "0:c18", + "to": "0:s12", + "type": "call", + "line": 55 + }, + { + "from": "0:s8", + "to": "0:c21", + "type": "read", + "mode": "tracked", + "probe": null, + "field": null, + "line": 62 + }, + { + "from": "0:s3", + "to": "0:c22", + "type": "read", + "mode": "tracked", + "probe": null, + "field": null, + "line": 63 + }, + { + "from": "0:c23", + "to": "0:s17", + "type": "passes", + "field": "product" + }, + { + "from": "0:s5", + "to": "0:c24", + "type": "read", + "mode": "tracked", + "probe": null, + "field": null, + "line": 65 + }, + { + "from": "0:c25", + "to": "0:s5", + "type": "write", + "op": "write", + "path": false, + "line": 65 + }, + { + "from": "0:s10", + "to": "0:c26", + "type": "read", + "mode": "tracked", + "probe": "pending", + "field": null, + "line": 66 + }, + { + "from": "0:s10", + "to": "0:c26", + "type": "read", + "mode": "tracked", + "probe": "latest", + "field": null, + "line": 66 + }, + { + "from": "0:s5", + "to": "0:c26", + "type": "read", + "mode": "tracked", + "probe": null, + "field": null, + "line": 66 + }, + { + "from": "0:s9", + "to": "0:c27", + "type": "read", + "mode": "tracked", + "probe": null, + "field": null, + "line": 68 + }, + { + "from": "0:s11", + "to": "0:c28", + "type": "read", + "mode": "tracked", + "probe": null, + "field": null, + "line": 69 + }, + { + "from": "0:c29", + "to": "0:s14", + "type": "call", + "line": 70 + }, + { + "from": "0:s4", + "to": "0:c30", + "type": "read", + "mode": "tracked", + "probe": "pending", + "field": null, + "line": 70 + }, + { + "from": "0:s8", + "to": "0:c30", + "type": "read", + "mode": "tracked", + "probe": null, + "field": null, + "line": 70 + }, + { + "from": "0:s4", + "to": "0:c31", + "type": "read", + "mode": "tracked", + "probe": "pending", + "field": null, + "line": 71 + }, + { + "from": "0:s13", + "to": "0:c31", + "type": "read", + "mode": "tracked", + "probe": null, + "field": null, + "line": 71 + }, + { + "from": "0:s6", + "to": "0:c31", + "type": "read", + "mode": "tracked", + "probe": null, + "field": null, + "line": 71 + }, + { + "from": "0:r5", + "to": "0:s15", + "type": "renders" + }, + { + "from": "0:r6", + "to": "0:s16", + "type": "renders" + } + ], + "regions": [ + { + "id": "0:r0", + "mod": 0, + "kind": "program", + "name": null, + "parent": null, + "key": "examples/cart.rx|" + }, + { + "id": "0:r1", + "mod": 0, + "kind": "component", + "name": "Row", + "parent": "0:r0", + "key": "examples/cart.rx|/component:Row" + }, + { + "id": "0:r2", + "mod": 0, + "kind": "component", + "name": "App", + "parent": "0:r0", + "key": "examples/cart.rx|/component:App" + }, + { + "id": "0:r3", + "mod": 0, + "kind": "errored", + "name": null, + "parent": "0:r2", + "key": "examples/cart.rx|/component:App/errored" + }, + { + "id": "0:r4", + "mod": 0, + "kind": "for", + "name": null, + "parent": "0:r3", + "key": "examples/cart.rx|/component:App/errored/for" + }, + { + "id": "0:r5", + "mod": 0, + "kind": "children", + "name": "Row", + "parent": "0:r4", + "key": "examples/cart.rx|/component:App/errored/for/children:Row" + }, + { + "id": "0:r6", + "mod": 0, + "kind": "children", + "name": "App", + "parent": "0:r0", + "key": "examples/cart.rx|/children:App" + } + ], + "lines": { + "examples/cart.rx": { + "1": "// A shopping cart: the catalogue is a question with an empty first paint; the cart is", + "2": "// a source with a question whose truth is \"empty\", written functionally; totals are", + "3": "// equations; the coupon is a question on its code, shown display-ahead with `latest`;", + "4": "// checkout is an action that clears the cart optimistically and reverts when the order", + "5": "// is declined.", + "6": "import pure { fetchProducts, validateCoupon, checkout } from \"./api\"", + "8": "type Product = { id: number; name: string; price: number }", + "9": "type Line = { id: number; qty: number }", + "11": "source products: Product[] = await fetchProducts() -> [] // ST-5 + R-7: `[]` until the catalogue lands", + "12": "source cart: Line[] = [] // a question whose truth is `[]`: the target of the optimistic clear (ST-5c)", + "13": "source coupon: string := \"\"", + "14": "source lastOrder: number | null := null", + "16": "fn qtyOf(id: number): number => cart.find(l => l.id === id)?.qty || 0", + "18": "count = cart.reduce((n, l) => n + l.qty, 0)", + "19": "subtotal = products.reduce((s, p) => s + p.price * qtyOf(p.id), 0)", + "20": "discount = coupon === \"\" ? 0 : await validateCoupon(coupon) -> 0 // a question on the code; R-7: no discount until it answers", + "21": "total = subtotal - subtotal * (latest discount) / 100 // `latest`: the total keeps moving while the code is checked (H-7)", + "23": "action setQty(id: number, n: number) {", + "24": " if (n < 0) return", + "25": " cart := ls => // W-6: a functional write composes with others in the instant", + "26": " n === 0 ? ls.filter(l => l.id !== id) :", + "27": " ls.some(l => l.id === id) ? ls.map(l => l.id === id ? { ...l, qty: n } : l) :", + "28": " [...ls, { id, qty: n }]", + "29": "}", + "31": "source orderError: string := \"\"", + "33": "action placeOrder() {", + "34": " if (count === 0) return", + "35": " let items = cart // SC-2: a snapshot of the lines being ordered", + "36": " guess cart := [] // AC-3: the cart empties now, display-ahead", + "37": " affects cart // AC-5: `pending? cart` while the order is in flight", + "38": " orderError := \"\"", + "39": " try {", + "40": " let receipt = await checkout(items, coupon) // AC-7: a declined order is thrown here", + "41": " cart := [] // the truth: equal to the guess, confirms silently", + "42": " lastOrder := receipt.id", + "43": " } catch (e) {", + "44": " orderError := e.message // still the action's change: lands with the reverted guess, one frame", + "45": " }", + "46": "}", + "48": "component Row(props: { product: Product }) {", + "49": " qty = qtyOf(props.product.id)", + "50": "
  • ", + "51": " {props.product.name}", + "52": " {props.product.price}", + "53": " ", + "54": " {qty}", + "55": " ", + "56": "
  • ", + "57": "}", + "59": "export default component App() {", + "60": " errored fallback(e) {

    The shop is unavailable: {e.message}

    } { // R-f-5: the fetches can fail; one boundary at the root discharges them", + "61": "
    ", + "62": "

    Cart ({count})

    ", + "63": "
      {for p in products { }}
    ", + "64": " ", + "68": "

    Subtotal {subtotal}

    ", + "69": "

    Total {total}

    ", + "70": " ", + "71": "

    {pending? cart ? \"Placing order…\" : orderError !== \"\" ? `Failed: ${orderError}` : lastOrder ? `Order #${lastOrder} placed` : \"\"}

    ", + "72": "
    ", + "73": " }", + "74": "}" + } + }, + "title": "cart.rx" +} diff --git a/tooling/rx-map/test/fixtures/notes.json b/tooling/rx-map/test/fixtures/notes.json new file mode 100644 index 000000000..83b1e76d1 --- /dev/null +++ b/tooling/rx-map/test/fixtures/notes.json @@ -0,0 +1,1849 @@ +{ + "modules": [ + "examples/notes/data.rx", + "examples/notes/ui.rx", + "examples/notes/main.rx" + ], + "nodes": [ + { + "id": "0:s0", + "mod": 0, + "file": "examples/notes/data.rx", + "kind": "import", + "name": "dbNotes", + "line": 2, + "region": "0:r0", + "io": false, + "question": false, + "async": false, + "world": true, + "base": "examples/notes/data.rx||dbNotes", + "key": "examples/notes/data.rx||dbNotes" + }, + { + "id": "0:s1", + "mod": 0, + "file": "examples/notes/data.rx", + "kind": "import", + "name": "dbNote", + "line": 2, + "region": "0:r0", + "io": false, + "question": false, + "async": false, + "world": true, + "base": "examples/notes/data.rx||dbNote", + "key": "examples/notes/data.rx||dbNote" + }, + { + "id": "0:s2", + "mod": 0, + "file": "examples/notes/data.rx", + "kind": "import", + "name": "dbSave", + "line": 2, + "region": "0:r0", + "io": true, + "question": false, + "async": false, + "world": true, + "base": "examples/notes/data.rx||dbSave", + "key": "examples/notes/data.rx||dbSave" + }, + { + "id": "0:s3", + "mod": 0, + "file": "examples/notes/data.rx", + "kind": "errclass", + "name": "Conflict", + "line": 2, + "region": "0:r0", + "io": false, + "question": false, + "async": false, + "world": false, + "base": "examples/notes/data.rx||Conflict", + "key": "examples/notes/data.rx||Conflict" + }, + { + "id": "0:s4", + "mod": 0, + "file": "examples/notes/data.rx", + "kind": "errclass", + "name": "NotFound", + "line": 7, + "region": "0:r0", + "io": false, + "question": false, + "async": false, + "world": false, + "base": "examples/notes/data.rx||NotFound", + "key": "examples/notes/data.rx||NotFound" + }, + { + "id": "0:s5", + "mod": 0, + "file": "examples/notes/data.rx", + "kind": "fn", + "name": "note", + "line": 10, + "region": "0:r0", + "io": false, + "question": false, + "async": false, + "world": false, + "base": "examples/notes/data.rx||note", + "key": "examples/notes/data.rx||note" + }, + { + "id": "0:s6", + "mod": 0, + "file": "examples/notes/data.rx", + "kind": "server", + "name": "listNotes", + "line": 11, + "region": "0:r0", + "io": false, + "question": false, + "async": false, + "world": false, + "base": "examples/notes/data.rx||listNotes", + "key": "examples/notes/data.rx||listNotes" + }, + { + "id": "0:s7", + "mod": 0, + "file": "examples/notes/data.rx", + "kind": "server", + "name": "getNote", + "line": 15, + "region": "0:r0", + "io": false, + "question": false, + "async": false, + "world": false, + "base": "examples/notes/data.rx||getNote", + "key": "examples/notes/data.rx||getNote" + }, + { + "id": "0:s8", + "mod": 0, + "file": "examples/notes/data.rx", + "kind": "server", + "name": "saveNote", + "line": 20, + "region": "0:r0", + "io": true, + "question": false, + "async": false, + "world": false, + "base": "examples/notes/data.rx||saveNote", + "key": "examples/notes/data.rx||saveNote" + }, + { + "id": "0:s9", + "mod": 0, + "file": "examples/notes/data.rx", + "kind": "source", + "name": "query", + "line": 26, + "region": "0:r0", + "io": false, + "question": false, + "async": false, + "world": false, + "base": "examples/notes/data.rx||query", + "key": "examples/notes/data.rx||query" + }, + { + "id": "0:s10", + "mod": 0, + "file": "examples/notes/data.rx", + "kind": "source", + "name": "route", + "line": 27, + "region": "0:r0", + "io": false, + "question": false, + "async": false, + "world": false, + "base": "examples/notes/data.rx||route", + "key": "examples/notes/data.rx||route" + }, + { + "id": "0:s11", + "mod": 0, + "file": "examples/notes/data.rx", + "kind": "source", + "name": "notes", + "line": 28, + "region": "0:r0", + "io": false, + "question": true, + "async": true, + "world": false, + "base": "examples/notes/data.rx||notes", + "key": "examples/notes/data.rx||notes" + }, + { + "id": "0:s12", + "mod": 0, + "file": "examples/notes/data.rx", + "kind": "eq", + "name": "current", + "line": 29, + "region": "0:r0", + "io": false, + "question": false, + "async": true, + "world": false, + "base": "examples/notes/data.rx||current", + "key": "examples/notes/data.rx||current" + }, + { + "id": "0:s13", + "mod": 0, + "file": "examples/notes/data.rx", + "kind": "source", + "name": "saveError", + "line": 30, + "region": "0:r0", + "io": false, + "question": false, + "async": false, + "world": false, + "base": "examples/notes/data.rx||saveError", + "key": "examples/notes/data.rx||saveError" + }, + { + "id": "0:s14", + "mod": 0, + "file": "examples/notes/data.rx", + "kind": "action", + "name": "search", + "line": 32, + "region": "0:r0", + "io": true, + "question": false, + "async": false, + "world": false, + "base": "examples/notes/data.rx||search", + "key": "examples/notes/data.rx||search" + }, + { + "id": "0:s15", + "mod": 0, + "file": "examples/notes/data.rx", + "kind": "action", + "name": "open", + "line": 33, + "region": "0:r0", + "io": true, + "question": false, + "async": false, + "world": false, + "base": "examples/notes/data.rx||open", + "key": "examples/notes/data.rx||open" + }, + { + "id": "0:s16", + "mod": 0, + "file": "examples/notes/data.rx", + "kind": "action", + "name": "back", + "line": 34, + "region": "0:r0", + "io": true, + "question": false, + "async": false, + "world": false, + "base": "examples/notes/data.rx||back", + "key": "examples/notes/data.rx||back" + }, + { + "id": "0:s17", + "mod": 0, + "file": "examples/notes/data.rx", + "kind": "action", + "name": "save", + "line": 35, + "region": "0:r0", + "io": true, + "question": false, + "async": false, + "world": false, + "base": "examples/notes/data.rx||save", + "key": "examples/notes/data.rx||save" + }, + { + "id": "1:s3", + "mod": 1, + "file": "examples/notes/ui.rx", + "kind": "errclass", + "name": "TitleRequired", + "line": 5, + "region": "1:r0", + "io": false, + "question": false, + "async": false, + "world": false, + "base": "examples/notes/ui.rx||TitleRequired", + "key": "examples/notes/ui.rx||TitleRequired" + }, + { + "id": "1:s4", + "mod": 1, + "file": "examples/notes/ui.rx", + "kind": "comp", + "name": "Row", + "line": 7, + "region": "1:r0", + "io": false, + "question": false, + "async": false, + "world": false, + "base": "examples/notes/ui.rx||Row", + "key": "examples/notes/ui.rx||Row" + }, + { + "id": "1:s5", + "mod": 1, + "file": "examples/notes/ui.rx", + "kind": "comp", + "name": "NoteList", + "line": 14, + "region": "1:r0", + "io": false, + "question": false, + "async": false, + "world": false, + "base": "examples/notes/ui.rx||NoteList", + "key": "examples/notes/ui.rx||NoteList" + }, + { + "id": "1:s6", + "mod": 1, + "file": "examples/notes/ui.rx", + "kind": "comp", + "name": "NoteEditor", + "line": 29, + "region": "1:r0", + "io": false, + "question": false, + "async": false, + "world": false, + "base": "examples/notes/ui.rx||NoteEditor", + "key": "examples/notes/ui.rx||NoteEditor" + }, + { + "id": "1:s7", + "mod": 1, + "file": "examples/notes/ui.rx", + "kind": "props", + "name": "props", + "line": 7, + "region": "1:r1", + "io": false, + "question": false, + "async": false, + "world": false, + "base": "examples/notes/ui.rx|Row|props", + "key": "examples/notes/ui.rx|Row|props" + }, + { + "id": "1:s8", + "mod": 1, + "file": "examples/notes/ui.rx", + "kind": "props", + "name": "props", + "line": 14, + "region": "1:r2", + "io": false, + "question": false, + "async": false, + "world": false, + "base": "examples/notes/ui.rx|NoteList|props", + "key": "examples/notes/ui.rx|NoteList|props" + }, + { + "id": "1:s9", + "mod": 1, + "file": "examples/notes/ui.rx", + "kind": "props", + "name": "props", + "line": 29, + "region": "1:r3", + "io": false, + "question": false, + "async": false, + "world": false, + "base": "examples/notes/ui.rx|NoteEditor|props", + "key": "examples/notes/ui.rx|NoteEditor|props" + }, + { + "id": "1:s10", + "mod": 1, + "file": "examples/notes/ui.rx", + "kind": "source", + "name": "title", + "line": 30, + "region": "1:r3", + "io": false, + "question": false, + "async": false, + "world": false, + "base": "examples/notes/ui.rx|NoteEditor|title", + "key": "examples/notes/ui.rx|NoteEditor|title" + }, + { + "id": "1:s11", + "mod": 1, + "file": "examples/notes/ui.rx", + "kind": "source", + "name": "body", + "line": 31, + "region": "1:r3", + "io": false, + "question": false, + "async": false, + "world": false, + "base": "examples/notes/ui.rx|NoteEditor|body", + "key": "examples/notes/ui.rx|NoteEditor|body" + }, + { + "id": "1:s12", + "mod": 1, + "file": "examples/notes/ui.rx", + "kind": "eq", + "name": "problem", + "line": 32, + "region": "1:r3", + "io": false, + "question": false, + "async": false, + "world": false, + "base": "examples/notes/ui.rx|NoteEditor|problem", + "key": "examples/notes/ui.rx|NoteEditor|problem" + }, + { + "id": "1:s13", + "mod": 1, + "file": "examples/notes/ui.rx", + "kind": "eq", + "name": "dirty", + "line": 33, + "region": "1:r3", + "io": false, + "question": false, + "async": false, + "world": false, + "base": "examples/notes/ui.rx|NoteEditor|dirty", + "key": "examples/notes/ui.rx|NoteEditor|dirty" + }, + { + "id": "2:s9", + "mod": 2, + "file": "examples/notes/main.rx", + "kind": "import", + "name": "viewport", + "line": 5, + "region": "2:r0", + "io": false, + "question": false, + "async": false, + "world": true, + "base": "examples/notes/main.rx||viewport", + "key": "examples/notes/main.rx||viewport" + }, + { + "id": "2:s10", + "mod": 2, + "file": "examples/notes/main.rx", + "kind": "comp", + "name": "App", + "line": 7, + "region": "2:r0", + "io": false, + "question": false, + "async": false, + "world": false, + "base": "examples/notes/main.rx||App", + "key": "examples/notes/main.rx||App" + }, + { + "id": "2:s11", + "mod": 2, + "file": "examples/notes/main.rx", + "kind": "props", + "name": "props", + "line": 7, + "region": "2:r3", + "io": false, + "question": false, + "async": false, + "world": false, + "base": "examples/notes/main.rx|App|props", + "key": "examples/notes/main.rx|App|props" + }, + { + "id": "2:s12", + "mod": 2, + "file": "examples/notes/main.rx", + "kind": "eq", + "name": "width", + "line": 8, + "region": "2:r3", + "io": false, + "question": false, + "async": true, + "world": false, + "base": "examples/notes/main.rx|App|width", + "key": "examples/notes/main.rx|App|width" + }, + { + "id": "2:s13", + "mod": 2, + "file": "examples/notes/main.rx", + "kind": "eq", + "name": "layout", + "line": 9, + "region": "2:r3", + "io": false, + "question": false, + "async": false, + "world": false, + "base": "examples/notes/main.rx|App|layout", + "key": "examples/notes/main.rx|App|layout" + }, + { + "id": "1:c0", + "mod": 1, + "file": "examples/notes/ui.rx", + "kind": "handler", + "site": true, + "name": "a onClick", + "line": 9, + "region": "1:r1", + "base": "examples/notes/ui.rx|/component:Row|handler:a onClick", + "sig": "props", + "key": "examples/notes/ui.rx|/component:Row|handler:a onClick" + }, + { + "id": "1:c1", + "mod": 1, + "file": "examples/notes/ui.rx", + "kind": "reader", + "site": true, + "name": "{…}", + "line": 9, + "region": "1:r1", + "base": "examples/notes/ui.rx|/component:Row|reader:{…}", + "sig": "props", + "key": "examples/notes/ui.rx|/component:Row|reader:{…}" + }, + { + "id": "1:c2", + "mod": 1, + "file": "examples/notes/ui.rx", + "kind": "reader", + "site": true, + "name": "td class", + "line": 10, + "region": "1:r1", + "base": "examples/notes/ui.rx|/component:Row|reader:td class", + "sig": "", + "key": "examples/notes/ui.rx|/component:Row|reader:td class" + }, + { + "id": "1:c3", + "mod": 1, + "file": "examples/notes/ui.rx", + "kind": "reader", + "site": true, + "name": "{…}", + "line": 10, + "region": "1:r1", + "base": "examples/notes/ui.rx|/component:Row|reader:{…}", + "sig": "props", + "key": "examples/notes/ui.rx|/component:Row|reader:{…}#1" + }, + { + "id": "1:c4", + "mod": 1, + "file": "examples/notes/ui.rx", + "kind": "reader", + "site": true, + "name": "if", + "line": 21, + "region": "1:r2", + "base": "examples/notes/ui.rx|/component:NoteList|reader:if", + "sig": "props", + "key": "examples/notes/ui.rx|/component:NoteList|reader:if" + }, + { + "id": "1:c5", + "mod": 1, + "file": "examples/notes/ui.rx", + "kind": "reader", + "site": true, + "name": "p class", + "line": 22, + "region": "1:r4", + "base": "examples/notes/ui.rx|/component:NoteList/then|reader:p class", + "sig": "", + "key": "examples/notes/ui.rx|/component:NoteList/then|reader:p class" + }, + { + "id": "1:c6", + "mod": 1, + "file": "examples/notes/ui.rx", + "kind": "reader", + "site": true, + "name": "for", + "line": 24, + "region": "1:r5", + "base": "examples/notes/ui.rx|/component:NoteList/else|reader:for", + "sig": "props", + "key": "examples/notes/ui.rx|/component:NoteList/else|reader:for" + }, + { + "id": "1:c7", + "mod": 1, + "file": "examples/notes/ui.rx", + "kind": "prop", + "site": true, + "name": "Row note", + "line": 24, + "region": "1:r6", + "base": "examples/notes/ui.rx|/component:NoteList/else/for|prop:Row note", + "sig": "", + "key": "examples/notes/ui.rx|/component:NoteList/else/for|prop:Row note" + }, + { + "id": "1:c12", + "mod": 1, + "file": "examples/notes/ui.rx", + "kind": "reader", + "site": true, + "name": "input value", + "line": 40, + "region": "1:r3", + "base": "examples/notes/ui.rx|/component:NoteEditor|reader:input value", + "sig": "title", + "key": "examples/notes/ui.rx|/component:NoteEditor|reader:input value" + }, + { + "id": "1:c13", + "mod": 1, + "file": "examples/notes/ui.rx", + "kind": "handler", + "site": true, + "name": "input onInput", + "line": 40, + "region": "1:r3", + "base": "examples/notes/ui.rx|/component:NoteEditor|handler:input onInput", + "sig": "", + "key": "examples/notes/ui.rx|/component:NoteEditor|handler:input onInput" + }, + { + "id": "1:c14", + "mod": 1, + "file": "examples/notes/ui.rx", + "kind": "reader", + "site": true, + "name": "textarea value", + "line": 41, + "region": "1:r3", + "base": "examples/notes/ui.rx|/component:NoteEditor|reader:textarea value", + "sig": "body", + "key": "examples/notes/ui.rx|/component:NoteEditor|reader:textarea value" + }, + { + "id": "1:c15", + "mod": 1, + "file": "examples/notes/ui.rx", + "kind": "handler", + "site": true, + "name": "textarea onInput", + "line": 41, + "region": "1:r3", + "base": "examples/notes/ui.rx|/component:NoteEditor|handler:textarea onInput", + "sig": "", + "key": "examples/notes/ui.rx|/component:NoteEditor|handler:textarea onInput" + }, + { + "id": "1:c16", + "mod": 1, + "file": "examples/notes/ui.rx", + "kind": "reader", + "site": true, + "name": "if", + "line": 42, + "region": "1:r3", + "base": "examples/notes/ui.rx|/component:NoteEditor|reader:if", + "sig": "problem", + "key": "examples/notes/ui.rx|/component:NoteEditor|reader:if" + }, + { + "id": "1:c17", + "mod": 1, + "file": "examples/notes/ui.rx", + "kind": "reader", + "site": true, + "name": "p class", + "line": 42, + "region": "1:r8", + "base": "examples/notes/ui.rx|/component:NoteEditor/then|reader:p class", + "sig": "", + "key": "examples/notes/ui.rx|/component:NoteEditor/then|reader:p class" + }, + { + "id": "1:c18", + "mod": 1, + "file": "examples/notes/ui.rx", + "kind": "reader", + "site": true, + "name": "{…}", + "line": 42, + "region": "1:r8", + "base": "examples/notes/ui.rx|/component:NoteEditor/then|reader:{…}", + "sig": "problem", + "key": "examples/notes/ui.rx|/component:NoteEditor/then|reader:{…}" + }, + { + "id": "1:c19", + "mod": 1, + "file": "examples/notes/ui.rx", + "kind": "reader", + "site": true, + "name": "if", + "line": 43, + "region": "1:r3", + "base": "examples/notes/ui.rx|/component:NoteEditor|reader:if", + "sig": "saveError", + "key": "examples/notes/ui.rx|/component:NoteEditor|reader:if#1" + }, + { + "id": "1:c20", + "mod": 1, + "file": "examples/notes/ui.rx", + "kind": "reader", + "site": true, + "name": "p class", + "line": 43, + "region": "1:r10", + "base": "examples/notes/ui.rx|/component:NoteEditor/then#1|reader:p class", + "sig": "", + "key": "examples/notes/ui.rx|/component:NoteEditor/then#1|reader:p class" + }, + { + "id": "1:c21", + "mod": 1, + "file": "examples/notes/ui.rx", + "kind": "reader", + "site": true, + "name": "{…}", + "line": 43, + "region": "1:r10", + "base": "examples/notes/ui.rx|/component:NoteEditor/then#1|reader:{…}", + "sig": "saveError", + "key": "examples/notes/ui.rx|/component:NoteEditor/then#1|reader:{…}" + }, + { + "id": "1:c22", + "mod": 1, + "file": "examples/notes/ui.rx", + "kind": "reader", + "site": true, + "name": "button disabled", + "line": 44, + "region": "1:r3", + "base": "examples/notes/ui.rx|/component:NoteEditor|reader:button disabled", + "sig": "dirty,problem", + "key": "examples/notes/ui.rx|/component:NoteEditor|reader:button disabled" + }, + { + "id": "1:c23", + "mod": 1, + "file": "examples/notes/ui.rx", + "kind": "handler", + "site": true, + "name": "button onClick", + "line": 44, + "region": "1:r3", + "base": "examples/notes/ui.rx|/component:NoteEditor|handler:button onClick", + "sig": "body,props,title", + "key": "examples/notes/ui.rx|/component:NoteEditor|handler:button onClick" + }, + { + "id": "2:c2", + "mod": 2, + "file": "examples/notes/main.rx", + "kind": "reader", + "site": true, + "name": "main class", + "line": 16, + "region": "2:r3", + "base": "examples/notes/main.rx|/component:App|reader:main class", + "sig": "layout", + "key": "examples/notes/main.rx|/component:App|reader:main class" + }, + { + "id": "2:c3", + "mod": 2, + "file": "examples/notes/main.rx", + "kind": "reader", + "site": true, + "name": "input placeholder", + "line": 18, + "region": "2:r3", + "base": "examples/notes/main.rx|/component:App|reader:input placeholder", + "sig": "", + "key": "examples/notes/main.rx|/component:App|reader:input placeholder" + }, + { + "id": "2:c4", + "mod": 2, + "file": "examples/notes/main.rx", + "kind": "reader", + "site": true, + "name": "input value", + "line": 18, + "region": "2:r3", + "base": "examples/notes/main.rx|/component:App|reader:input value", + "sig": "query", + "key": "examples/notes/main.rx|/component:App|reader:input value" + }, + { + "id": "2:c5", + "mod": 2, + "file": "examples/notes/main.rx", + "kind": "handler", + "site": true, + "name": "input onInput", + "line": 18, + "region": "2:r3", + "base": "examples/notes/main.rx|/component:App|handler:input onInput", + "sig": "", + "key": "examples/notes/main.rx|/component:App|handler:input onInput" + }, + { + "id": "2:c6", + "mod": 2, + "file": "examples/notes/main.rx", + "kind": "reader", + "site": true, + "name": "if", + "line": 19, + "region": "2:r3", + "base": "examples/notes/main.rx|/component:App|reader:if", + "sig": "route", + "key": "examples/notes/main.rx|/component:App|reader:if" + }, + { + "id": "2:c7", + "mod": 2, + "file": "examples/notes/main.rx", + "kind": "handler", + "site": true, + "name": "button onClick", + "line": 19, + "region": "2:r4", + "base": "examples/notes/main.rx|/component:App/then|handler:button onClick", + "sig": "", + "key": "examples/notes/main.rx|/component:App/then|handler:button onClick" + }, + { + "id": "2:c8", + "mod": 2, + "file": "examples/notes/main.rx", + "kind": "reader", + "site": true, + "name": "{…}", + "line": 20, + "region": "2:r3", + "base": "examples/notes/main.rx|/component:App|reader:{…}", + "sig": "layout", + "key": "examples/notes/main.rx|/component:App|reader:{…}" + }, + { + "id": "2:c9", + "mod": 2, + "file": "examples/notes/main.rx", + "kind": "reader", + "site": true, + "name": "{…}", + "line": 22, + "region": "2:r3", + "base": "examples/notes/main.rx|/component:App|reader:{…}", + "sig": "", + "key": "examples/notes/main.rx|/component:App|reader:{…}#1" + }, + { + "id": "2:c10", + "mod": 2, + "file": "examples/notes/main.rx", + "kind": "reader", + "site": true, + "name": "if", + "line": 23, + "region": "2:r6", + "base": "examples/notes/main.rx|/component:App/errored|reader:if", + "sig": "route", + "key": "examples/notes/main.rx|/component:App/errored|reader:if" + }, + { + "id": "2:c11", + "mod": 2, + "file": "examples/notes/main.rx", + "kind": "reader", + "site": true, + "name": "loading on", + "line": 24, + "region": "2:r7", + "base": "examples/notes/main.rx|/component:App/errored/then|reader:loading on", + "sig": "query", + "key": "examples/notes/main.rx|/component:App/errored/then|reader:loading on" + }, + { + "id": "2:c12", + "mod": 2, + "file": "examples/notes/main.rx", + "kind": "prop", + "site": true, + "name": "NoteList notes", + "line": 24, + "region": "2:r8", + "base": "examples/notes/main.rx|/component:App/errored/then/loading|prop:NoteList notes", + "sig": "notes", + "key": "examples/notes/main.rx|/component:App/errored/then/loading|prop:NoteList notes" + }, + { + "id": "2:c13", + "mod": 2, + "file": "examples/notes/main.rx", + "kind": "reader", + "site": true, + "name": "{…}", + "line": 26, + "region": "2:r10", + "base": "examples/notes/main.rx|/component:App/errored/else|reader:{…}", + "sig": "", + "key": "examples/notes/main.rx|/component:App/errored/else|reader:{…}" + }, + { + "id": "2:c14", + "mod": 2, + "file": "examples/notes/main.rx", + "kind": "reader", + "site": true, + "name": "if", + "line": 28, + "region": "2:r12", + "base": "examples/notes/main.rx|/component:App/errored/else/errored/loading|reader:if", + "sig": "current", + "key": "examples/notes/main.rx|/component:App/errored/else/errored/loading|reader:if" + }, + { + "id": "2:c15", + "mod": 2, + "file": "examples/notes/main.rx", + "kind": "prop", + "site": true, + "name": "NoteEditor note", + "line": 28, + "region": "2:r13", + "base": "examples/notes/main.rx|/component:App/errored/else/errored/loading/then|prop:NoteEditor note", + "sig": "current", + "key": "examples/notes/main.rx|/component:App/errored/else/errored/loading/then|prop:NoteEditor note" + } + ], + "edges": [ + { + "from": "0:s6", + "to": "0:s0", + "type": "call", + "line": 11 + }, + { + "from": "0:s6", + "to": "0:s5", + "type": "call", + "line": 11 + }, + { + "from": "0:s7", + "to": "0:s1", + "type": "call", + "line": 15 + }, + { + "from": "0:s7", + "to": "0:s5", + "type": "call", + "line": 15 + }, + { + "from": "0:s8", + "to": "0:s2", + "type": "call", + "line": 20 + }, + { + "from": "0:s8", + "to": "0:s5", + "type": "call", + "line": 20 + }, + { + "from": "0:s9", + "to": "0:s11", + "type": "read", + "mode": "tracked", + "probe": null, + "field": null, + "line": 28 + }, + { + "from": "0:s11", + "to": "0:s6", + "type": "call", + "line": 28 + }, + { + "from": "0:s10", + "to": "0:s12", + "type": "read", + "mode": "tracked", + "probe": null, + "field": "page", + "line": 29 + }, + { + "from": "0:s10", + "to": "0:s12", + "type": "read", + "mode": "tracked", + "probe": null, + "field": "id", + "line": 29 + }, + { + "from": "0:s12", + "to": "0:s7", + "type": "call", + "line": 29 + }, + { + "from": "0:s14", + "to": "0:s9", + "type": "write", + "op": "write", + "path": false, + "line": 32 + }, + { + "from": "0:s15", + "to": "0:s10", + "type": "write", + "op": "write", + "path": false, + "line": 33 + }, + { + "from": "0:s15", + "to": "0:s13", + "type": "write", + "op": "write", + "path": false, + "line": 33 + }, + { + "from": "0:s16", + "to": "0:s10", + "type": "write", + "op": "write", + "path": false, + "line": 34 + }, + { + "from": "0:s17", + "to": "0:s13", + "type": "write", + "op": "write", + "path": false, + "line": 35 + }, + { + "from": "0:s17", + "to": "0:s11", + "type": "write", + "op": "optimistic", + "path": false, + "line": 35 + }, + { + "from": "0:s17", + "to": "0:s11", + "type": "write", + "op": "write", + "path": false, + "line": 35 + }, + { + "from": "0:s17", + "to": "0:s12", + "type": "write", + "op": "refresh", + "path": false, + "line": 35 + }, + { + "from": "0:s17", + "to": "0:s8", + "type": "call", + "line": 35 + }, + { + "from": "1:s7", + "to": "1:c0", + "type": "read", + "mode": "snapshot", + "probe": null, + "field": "note", + "line": 9 + }, + { + "from": "1:c0", + "to": "0:s15", + "type": "call", + "line": 9 + }, + { + "from": "1:s7", + "to": "1:c1", + "type": "read", + "mode": "tracked", + "probe": null, + "field": "note", + "line": 9 + }, + { + "from": "1:s7", + "to": "1:c3", + "type": "read", + "mode": "tracked", + "probe": null, + "field": "note", + "line": 10 + }, + { + "from": "1:s8", + "to": "1:c4", + "type": "read", + "mode": "tracked", + "probe": null, + "field": "notes", + "line": 21 + }, + { + "from": "1:s8", + "to": "1:c6", + "type": "read", + "mode": "tracked", + "probe": null, + "field": "notes", + "line": 24 + }, + { + "from": "1:c7", + "to": "1:s7", + "type": "passes", + "field": "note" + }, + { + "from": "1:s9", + "to": "1:s10", + "type": "read", + "mode": "snapshot", + "probe": null, + "field": "note", + "line": 30 + }, + { + "from": "1:s9", + "to": "1:s11", + "type": "read", + "mode": "snapshot", + "probe": null, + "field": "note", + "line": 31 + }, + { + "from": "1:s10", + "to": "1:s12", + "type": "read", + "mode": "tracked", + "probe": null, + "field": "trim", + "line": 32 + }, + { + "from": "1:s10", + "to": "1:s13", + "type": "read", + "mode": "tracked", + "probe": null, + "field": null, + "line": 33 + }, + { + "from": "1:s9", + "to": "1:s13", + "type": "read", + "mode": "tracked", + "probe": null, + "field": "note", + "line": 33 + }, + { + "from": "1:s11", + "to": "1:s13", + "type": "read", + "mode": "tracked", + "probe": null, + "field": null, + "line": 33 + }, + { + "from": "1:s10", + "to": "1:c12", + "type": "read", + "mode": "tracked", + "probe": null, + "field": null, + "line": 40 + }, + { + "from": "1:c13", + "to": "1:s10", + "type": "write", + "op": "write", + "path": false, + "line": 40 + }, + { + "from": "1:s11", + "to": "1:c14", + "type": "read", + "mode": "tracked", + "probe": null, + "field": null, + "line": 41 + }, + { + "from": "1:c15", + "to": "1:s11", + "type": "write", + "op": "write", + "path": false, + "line": 41 + }, + { + "from": "1:s12", + "to": "1:c16", + "type": "read", + "mode": "tracked", + "probe": null, + "field": null, + "line": 42 + }, + { + "from": "1:s12", + "to": "1:c18", + "type": "read", + "mode": "tracked", + "probe": null, + "field": null, + "line": 42 + }, + { + "from": "0:s13", + "to": "1:c19", + "type": "read", + "mode": "tracked", + "probe": null, + "field": null, + "line": 43 + }, + { + "from": "0:s13", + "to": "1:c21", + "type": "read", + "mode": "tracked", + "probe": null, + "field": null, + "line": 43 + }, + { + "from": "1:s13", + "to": "1:c22", + "type": "read", + "mode": "tracked", + "probe": null, + "field": null, + "line": 44 + }, + { + "from": "1:s12", + "to": "1:c22", + "type": "read", + "mode": "tracked", + "probe": null, + "field": null, + "line": 44 + }, + { + "from": "1:s9", + "to": "1:c23", + "type": "read", + "mode": "snapshot", + "probe": null, + "field": "note", + "line": 44 + }, + { + "from": "1:s10", + "to": "1:c23", + "type": "read", + "mode": "snapshot", + "probe": null, + "field": null, + "line": 44 + }, + { + "from": "1:s11", + "to": "1:c23", + "type": "read", + "mode": "snapshot", + "probe": null, + "field": null, + "line": 44 + }, + { + "from": "1:c23", + "to": "0:s17", + "type": "call", + "line": 44 + }, + { + "from": "1:r7", + "to": "1:s4", + "type": "renders" + }, + { + "from": "2:s12", + "to": "2:s9", + "type": "call", + "line": 8 + }, + { + "from": "2:s12", + "to": "2:s13", + "type": "read", + "mode": "tracked", + "probe": null, + "field": null, + "line": 9 + }, + { + "from": "2:s13", + "to": "2:c2", + "type": "read", + "mode": "tracked", + "probe": null, + "field": null, + "line": 16 + }, + { + "from": "0:s9", + "to": "2:c4", + "type": "read", + "mode": "tracked", + "probe": null, + "field": null, + "line": 18 + }, + { + "from": "2:c5", + "to": "0:s14", + "type": "call", + "line": 18 + }, + { + "from": "0:s10", + "to": "2:c6", + "type": "read", + "mode": "tracked", + "probe": null, + "field": "page", + "line": 19 + }, + { + "from": "2:c7", + "to": "0:s16", + "type": "call", + "line": 19 + }, + { + "from": "2:s13", + "to": "2:c8", + "type": "read", + "mode": "tracked", + "probe": null, + "field": null, + "line": 20 + }, + { + "from": "0:s10", + "to": "2:c10", + "type": "read", + "mode": "tracked", + "probe": null, + "field": "page", + "line": 23 + }, + { + "from": "0:s9", + "to": "2:c11", + "type": "read", + "mode": "tracked", + "probe": null, + "field": null, + "line": 24 + }, + { + "from": "2:c12", + "to": "1:s8", + "type": "passes", + "field": "notes" + }, + { + "from": "0:s11", + "to": "2:c12", + "type": "read", + "mode": "tracked", + "probe": null, + "field": null, + "line": 24 + }, + { + "from": "0:s12", + "to": "2:c14", + "type": "read", + "mode": "tracked", + "probe": null, + "field": null, + "line": 28 + }, + { + "from": "2:c15", + "to": "1:s9", + "type": "passes", + "field": "note" + }, + { + "from": "0:s12", + "to": "2:c15", + "type": "read", + "mode": "tracked", + "probe": null, + "field": null, + "line": 28 + }, + { + "from": "2:r9", + "to": "1:s5", + "type": "renders" + }, + { + "from": "2:r14", + "to": "1:s6", + "type": "renders" + }, + { + "from": "2:r16", + "to": "2:s10", + "type": "renders" + } + ], + "regions": [ + { + "id": "0:r0", + "mod": 0, + "kind": "program", + "name": null, + "parent": null, + "key": "examples/notes/data.rx|" + }, + { + "id": "1:r0", + "mod": 1, + "kind": "program", + "name": null, + "parent": null, + "key": "examples/notes/ui.rx|" + }, + { + "id": "1:r1", + "mod": 1, + "kind": "component", + "name": "Row", + "parent": "1:r0", + "key": "examples/notes/ui.rx|/component:Row" + }, + { + "id": "1:r2", + "mod": 1, + "kind": "component", + "name": "NoteList", + "parent": "1:r0", + "key": "examples/notes/ui.rx|/component:NoteList" + }, + { + "id": "1:r3", + "mod": 1, + "kind": "component", + "name": "NoteEditor", + "parent": "1:r0", + "key": "examples/notes/ui.rx|/component:NoteEditor" + }, + { + "id": "1:r4", + "mod": 1, + "kind": "then", + "name": null, + "parent": "1:r2", + "key": "examples/notes/ui.rx|/component:NoteList/then" + }, + { + "id": "1:r5", + "mod": 1, + "kind": "else", + "name": null, + "parent": "1:r2", + "key": "examples/notes/ui.rx|/component:NoteList/else" + }, + { + "id": "1:r6", + "mod": 1, + "kind": "for", + "name": null, + "parent": "1:r5", + "key": "examples/notes/ui.rx|/component:NoteList/else/for" + }, + { + "id": "1:r7", + "mod": 1, + "kind": "children", + "name": "Row", + "parent": "1:r6", + "key": "examples/notes/ui.rx|/component:NoteList/else/for/children:Row" + }, + { + "id": "1:r8", + "mod": 1, + "kind": "then", + "name": null, + "parent": "1:r3", + "key": "examples/notes/ui.rx|/component:NoteEditor/then" + }, + { + "id": "1:r9", + "mod": 1, + "kind": "else", + "name": null, + "parent": "1:r3", + "key": "examples/notes/ui.rx|/component:NoteEditor/else" + }, + { + "id": "1:r10", + "mod": 1, + "kind": "then", + "name": null, + "parent": "1:r3", + "key": "examples/notes/ui.rx|/component:NoteEditor/then#1" + }, + { + "id": "1:r11", + "mod": 1, + "kind": "else", + "name": null, + "parent": "1:r3", + "key": "examples/notes/ui.rx|/component:NoteEditor/else#1" + }, + { + "id": "2:r0", + "mod": 2, + "kind": "program", + "name": null, + "parent": null, + "key": "examples/notes/main.rx|" + }, + { + "id": "2:r1", + "mod": 2, + "kind": "imported", + "name": "NoteList", + "parent": null, + "key": "examples/notes/main.rx|/imported:NoteList" + }, + { + "id": "2:r2", + "mod": 2, + "kind": "imported", + "name": "NoteEditor", + "parent": null, + "key": "examples/notes/main.rx|/imported:NoteEditor" + }, + { + "id": "2:r3", + "mod": 2, + "kind": "component", + "name": "App", + "parent": "2:r0", + "key": "examples/notes/main.rx|/component:App" + }, + { + "id": "2:r4", + "mod": 2, + "kind": "then", + "name": null, + "parent": "2:r3", + "key": "examples/notes/main.rx|/component:App/then" + }, + { + "id": "2:r5", + "mod": 2, + "kind": "else", + "name": null, + "parent": "2:r3", + "key": "examples/notes/main.rx|/component:App/else" + }, + { + "id": "2:r6", + "mod": 2, + "kind": "errored", + "name": null, + "parent": "2:r3", + "key": "examples/notes/main.rx|/component:App/errored" + }, + { + "id": "2:r7", + "mod": 2, + "kind": "then", + "name": null, + "parent": "2:r6", + "key": "examples/notes/main.rx|/component:App/errored/then" + }, + { + "id": "2:r8", + "mod": 2, + "kind": "loading", + "name": null, + "parent": "2:r7", + "key": "examples/notes/main.rx|/component:App/errored/then/loading" + }, + { + "id": "2:r9", + "mod": 2, + "kind": "children", + "name": "NoteList", + "parent": "2:r8", + "key": "examples/notes/main.rx|/component:App/errored/then/loading/children:NoteList" + }, + { + "id": "2:r10", + "mod": 2, + "kind": "else", + "name": null, + "parent": "2:r6", + "key": "examples/notes/main.rx|/component:App/errored/else" + }, + { + "id": "2:r11", + "mod": 2, + "kind": "errored", + "name": null, + "parent": "2:r10", + "key": "examples/notes/main.rx|/component:App/errored/else/errored" + }, + { + "id": "2:r12", + "mod": 2, + "kind": "loading", + "name": null, + "parent": "2:r11", + "key": "examples/notes/main.rx|/component:App/errored/else/errored/loading" + }, + { + "id": "2:r13", + "mod": 2, + "kind": "then", + "name": null, + "parent": "2:r12", + "key": "examples/notes/main.rx|/component:App/errored/else/errored/loading/then" + }, + { + "id": "2:r14", + "mod": 2, + "kind": "children", + "name": "NoteEditor", + "parent": "2:r13", + "key": "examples/notes/main.rx|/component:App/errored/else/errored/loading/then/children:NoteEditor" + }, + { + "id": "2:r15", + "mod": 2, + "kind": "else", + "name": null, + "parent": "2:r12", + "key": "examples/notes/main.rx|/component:App/errored/else/errored/loading/else" + }, + { + "id": "2:r16", + "mod": 2, + "kind": "children", + "name": "App", + "parent": "2:r0", + "key": "examples/notes/main.rx|/children:App" + } + ], + "lines": { + "examples/notes/data.rx": { + "1": "// data.rx — the notes as the server has them, the route, and the only ways to change them.", + "2": "import { dbNotes, dbNote, dbSave, Conflict } from \"./api\"", + "4": "export type Note = { id: number; title: string; body: string; updated: string }", + "5": "export type Route = { page: \"list\" } | { page: \"note\"; id: number }", + "7": "export error NotFound(id: number) => `note ${id} not found`", + "9": "// The server's half: what leaves it is a Note — the owner column stays there (SF-6).", + "10": "fn note(r: { id: number; title: string; body: string; updated: string }): Note => ({ id: r.id, title: r.title, body: r.body, updated: r.updated })", + "11": "server fn listNotes(q: string) {", + "12": " let rows = await dbNotes(q)", + "13": " return rows.map(r => note(r))", + "14": "}", + "15": "server fn getNote(id: number) {", + "16": " let r = await dbNote(id)", + "17": " if (r == null) { throw NotFound(id) }", + "18": " return note(r)", + "19": "}", + "20": "server fn saveNote(id: number, title: string, body: string) {", + "21": " let r = await dbSave(id, title, body)", + "22": " return note(r)", + "23": "}", + "25": "// The client's half.", + "26": "export source query: string := \"\"", + "27": "export source route: Route := { page: \"list\" }", + "28": "export source notes: Note[] key id = await listNotes(query)", + "29": "export current = route.page == \"note\" ? await getNote(route.id) : null", + "30": "export source saveError: string := \"\"", + "32": "export action search(q: string) { query := q }", + "33": "export action open(id: number) { route := { page: \"note\", id: id }; saveError := \"\" }", + "34": "export action back() { route := { page: \"list\" } }", + "35": "export action save(id: number, title: string, body: string) {", + "36": " saveError := \"\"", + "37": " guess notes := ns => ns.map(n => n.id == id ? { ...n, title: title, body: body } : n)", + "38": " try {", + "39": " try {", + "40": " let saved = await saveNote(id, title, body)", + "41": " notes := ns => ns.map(n => n.id == id ? saved : n)", + "42": " refresh current", + "43": " } catch (e: Conflict) {", + "44": " saveError := `someone else saved first: ${e.message}`", + "45": " }", + "46": " } catch (e) {", + "47": " saveError := e.message", + "48": " }", + "49": "}" + }, + "examples/notes/ui.rx": { + "1": "// ui.rx — the pieces of view. Each component's stylesheet scopes only its own view (07 §6b).", + "2": "import { Note } from \"./data.rx\"", + "3": "import { open, save, saveError } from \"./data.rx\"", + "5": "export error TitleRequired() => \"a note needs a title\"", + "7": "component Row(props: { note: Note }) {", + "8": " ", + "9": " { open(props.note.id) }}>{props.note.title}", + "10": " {props.note.updated}", + "11": " ", + "12": "}", + "14": "export component NoteList(props: { notes: Note[] }) {", + "15": " ", + "21": " if len(props.notes) == 0 {", + "22": "

    no notes

    ", + "23": " } else {", + "24": " {for n in props.notes { }}
    ", + "25": " }", + "26": "}", + "28": "// The editor's drafts are its own: snapshots of the note it was opened with (E-4).", + "29": "export component NoteEditor(props: { note: Note }) {", + "30": " source title := peek(props.note.title)", + "31": " source body := peek(props.note.body)", + "32": " problem = title.trim() == \"\" ? \"a note needs a title\" : \"\"", + "33": " dirty = title != props.note.title || body != props.note.body", + "34": " ", + "39": "
    ", + "40": " { title := e.currentTarget.value }} />", + "41": "