Skip to content

Arena/6362b41e affinescript - #865

Merged
hyperpolymath merged 3 commits into
mainfrom
arena/6362b41e-affinescript
Dec 2, 2026
Merged

hyperpolymath merged 3 commits into
mainfrom
arena/6362b41e-affinescript

Conversation

@hyperpolymath

Copy link
Copy Markdown
Owner

Summary

Closes #

Type of change

  • 🐛 Bug fix (non-breaking change that fixes an issue)
  • ✨ New feature (non-breaking change that adds functionality)
  • 💥 Breaking change (would change existing behaviour)
  • 🕳️ Soundness fix (fixes a checker/proof false-negative)
  • 📖 Documentation
  • 🧹 Refactor / tech debt (behaviour-preserving)
  • ⚡ Performance
  • 🔧 Build / CI / tooling

How has this been verified?

Checklist

  • My commits are signed (git commit -S).
  • I ran the project's own checks/tests locally and they pass.
  • New files carry the correct SPDX-License-Identifier (code/config MPL-2.0,
    prose CC-BY-SA-4.0); I did not relicense existing files.
  • Docs are updated, and no public claim now overstates what the code does.
  • I have not introduced a soundness hole (or I have flagged where I might have).

Notes for reviewers

Arena Agent and others added 2 commits October 31, 2026 19:11
…scriptDom.affine)

Item (4) of the userscript brief, in the only form that fits the target: the
ESM runtime (packages/affine-js) cannot be bundled to an IIFE (import.meta,
dynamic import("node:fs/promises"), import("node:url")), so the reconciler is
authored in AffineScript and compiled into the same single file.

- UserscriptDom: Attr/Spec/Element/Group over opaque Node handles; create,
  patch (attribute add *and* remove, text only when changed), set_text_of,
  unmount, group/reconcile/unmount_all, member_count. A reconciler, not a vdom
  diff: an Element remembers its state, which is what makes in-place patching
  possible without get_attribute or a recursive vnode type.
- lib/codegen_userscript.ml: lower the `len` typechecker builtin to .length.
  It has no extern declaration to be lowered through, so without this any
  reachable `len` emitted a call to an undefined global.
- docs: the guide now points at UserscriptDom as the IIFE-buildable runtime.

NOTE: not compiled yet — the sandbox still cannot build (sedlex fetches
UnicodeData.txt from unicode.org); test/test_stdlib_aot.ml picks every
stdlib/*.affine up automatically, so `dune test` is its first check.

Co-authored-by: arena-agent <297053741+arena-agent@users.noreply.github.com>
…it exposed

The DOM runtime is no longer authored blind: the toolchain now builds here
(sedlex 3.2 install fixed, see below), so everything in this commit was
compiled and run before it was written down.

- test/e2e/userscript/dom.affine: create -> patch (attribute dropped, text
  changed) -> text-only patch -> reconcile 0->3 and 3->2 -> teardown.
- test/e2e/userscript/dom_harness.mjs: runs that artefact against a recording
  fake DOM. UserscriptDom only reaches the page through createElement/
  appendChild/removeChild/*Attribute/textContent, so no browser and no jsdom
  are needed -- 12 checks (markers, attribute add/remove sequence, empty page
  after teardown) run anywhere a compiler does.
- run.sh: compiles the fixture, holds it to the single-capsule/no-import/
  size-budget rules, then runs the harness. Suite: 57 -> 69 checks.
- lib/codegen_userscript.ml: `show` is a typechecker builtin like `len`, so
  it reached the emitter with no extern to lower through and emitted a call to
  an undefined global. Lower it to `__as_show`, matching the other JS
  backends, and define that in the runtime.
- stdlib/UserscriptDom.affine: `for`/`if` statements do not take a trailing
  semicolon -- parsing caught it, `check` now passes.
- tools/bootstrap-ocaml-toolchain.sh: `sedlex.ppx` is a public_name inside
  the `sedlex` package, not a package; naming it as an install target failed
  the sedlex step with "Unknown package sedlex.ppx".

Measured: dom.affine 7,991 B; probe 18,523 B; probe+banner 18,861 B;
reachability 4,351 B; hello 4,318 B (budget 24,576).

Co-authored-by: arena-agent <297053741+arena-agent@users.noreply.github.com>
@gitnotebooks

gitnotebooks Bot commented Dec 2, 2026

Copy link
Copy Markdown

@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Dec 2, 2026 •

Copy link
Copy Markdown
Codex Review Summary: ✅ Completed

This comment shows the latest Codex review activity on this pull request.

Review Status Commit Review trigger
📝 Code Review ✅ Completed 2026-12-02T15:53:41.089060Z 5d9ca65 PR opened
🔒 Security Review ✅ Completed 2026-12-02T15:50:34.346876Z 5d9ca65 PR opened
ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review" or "@codex security review".

Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings.

@coderabbitai

coderabbitai Bot commented Dec 2, 2026 •

Copy link
Copy Markdown
Contributor

Explain Change →

Caution

Review failed

The pull request is closed.

  • Autofix · Keep fixing CodeRabbit findings and required CI, and resolving merge conflicts

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

Share

Signed-off-by: Jonathan D.A. Jewell <6759885+hyperpolymath@users.noreply.github.com>
@hyperpolymath
hyperpolymath merged commit 2f323ac into main Dec 2, 2026
13 of 16 checks passed
@hyperpolymath
hyperpolymath deleted the arena/6362b41e-affinescript branch December 2, 2026 15:43
@sonarqubecloud

sonarqubecloud Bot commented Dec 2, 2026

Copy link
Copy Markdown

Quality Gate Failed Quality Gate failed

Failed conditions
C Security Rating on New Code (required ≥ A)

See analysis details on SonarQube Cloud

Catch issues before they fail your Quality Gate with our IDE extension SonarQube for IDE

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 5d9ca65a08

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

Comment thread lib/codegen_userscript.ml
Comment on lines +454 to +456
const probe = "__affinescript_userscript_probe__";
store.setItem(probe, "1");
store.removeItem(probe);

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1 Badge Preserve localStorage data while probing availability

When the host page already has a value under __affinescript_userscript_probe__, every call to capabilities() overwrites that value and then deletes it. Since userscripts run against arbitrary pages and capabilities() is called by each settings operation, this can silently corrupt page-owned localStorage; preserve and restore any prior value or use a collision-resistant temporary key.

Useful? React with 👍 / 👎.

Comment thread lib/codegen_userscript.ml
Comment on lines +1012 to +1016
| Some g -> " && (" ^ gen_expr ctx g ^ ")"
| None -> ""
in
let body = gen_expr ctx arm.ma_body in
"if (" ^ cond ^ guard ^ ") { " ^ bindings ^ "return " ^ body ^ "; } else "

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1 Badge Bind match variables before evaluating arm guards

For a guarded arm such as Some(x) if x > 0 => ..., the generated condition evaluates the guard before the branch emits const x = __scrut.value, causing a ReferenceError (or reading an unrelated outer binding). This affects both expression and statement matches; test the pattern first, introduce its bindings, and only then evaluate the guard before selecting the arm.

Useful? React with 👍 / 👎.

Comment thread stdlib/Userscript.affine
Comment on lines +165 to +170
let can_read = us_gm_has("getValue");
let can_write = us_gm_has("setValue");
Caps #{
manager: can_read,
gm_storage: can_read,
local_storage: us_local_available(),

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Select storage capabilities per operation

With partial userscript grants, gm_storage is true solely when GM_getValue exists, while the computed can_write is ignored and GM_deleteValue is not checked at all. For example, a script granted only GM_getValue with usable localStorage routes set_setting and delete_setting to missing GM functions and returns HostRejected instead of using the documented localStorage fallback; each operation needs to check its corresponding GM capability.

Useful? React with 👍 / 👎.

Comment thread lib/codegen_userscript.ml
| ExprApp (func, args) ->
let arg_strs = List.map (gen_expr ctx) args in
(match func with
| ExprVar id when id.name = "len" && List.length arg_strs = 1 ->

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Let local definitions shadow intrinsic lowerings

When a program defines its own len, calls are still unconditionally rewritten to .length; for example, the repository's supported fn len(xs: IntList) -> Int shape would produce an invalid result under this target. The same name-only dispatch also affects show and every userscript extern name, so intrinsic lowering should be suppressed when the flattened program contains a same-named local function or constant.

Useful? React with 👍 / 👎.

Comment thread bin/main.ml
(* The default output path is a wasm module; a userscript is one .js file,
so an unspecified -o becomes out.user.js instead of silently writing a
JS source file called out.wasm. *)
let output = if userscript && output = "out.wasm" then "out.user.js" else output in

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Honor explicit output paths equal to the default

When a caller explicitly supplies -o out.wasm with the userscript target, this equality check treats the requested path as if it were an omitted option and writes out.user.js instead. Build scripts that always pass an output path will then fail to find the promised artifact; the CLI needs to retain whether -o was supplied rather than inferring omission from its value.

Useful? React with 👍 / 👎.

Comment on lines +121 to +123
pub fn patch_from(el: Element, s: Spec) -> Element {
patch(el, s.attrs, s.text)
}

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Replace elements when a patched spec changes the tag

patch_from discards s.html_tag, so patching an existing <p> with a Spec for <div> updates attributes and text but leaves a <p> in the page. Because the public API accepts an arbitrary Spec and documents no same-tag precondition, it must either replace the DOM node when the tag changes or reject such a patch explicitly.

Useful? React with 👍 / 👎.

Comment thread lib/codegen_userscript.ml
// here rather than awaited, because top-level `await` is not allowed in a
// non-module script.
try {
const __as_result = main();

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Reject parameterized userscript entry points

The generated capsule always invokes main() with no arguments, but the target never validates that the source main has zero parameters. A program with fn main(x: Int) therefore compiles successfully and runs with x === undefined, producing invalid values or delayed runtime failures instead of a build diagnostic.

Useful? React with 👍 / 👎.

Comment thread lib/jcs.ml
match v with
| `Null -> Buffer.add_string buf "null"; Ok ()
| `Bool b -> Buffer.add_string buf (if b then "true" else "false"); Ok ()
| `Int i -> Buffer.add_string buf (string_of_int i); Ok ()

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Reject integers outside the interoperable JCS range

The Int branch emits arbitrary OCaml integers verbatim, including values such as 9007199254740993 that cannot be represented by the IEEE-754 number model required by JCS/I-JSON consumers. Such a consumer parses that value as 9007199254740992 and canonicalizes different bytes, defeating the promised cross-implementation canonical form; reject non-interoperable integers or require them to be represented as strings.

Useful? React with 👍 / 👎.

Comment thread lib/codegen_userscript.ml
Comment on lines +204 to +207
(match fd.fd_body with
| FnExpr e -> expr_unsupported e
| FnBlock blk -> block_unsupported blk
| FnExtern -> None)

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Reject unbound extern methods inside impl blocks

A bodiless ImplFn is explicitly treated as supported regardless of its name, unlike top-level extern functions. An impl containing an extern method with no userscript lowering therefore passes the build-time closed-capability check and is emitted as a function that only throws at runtime; run these methods through extern_name so unsupported host access is rejected during compilation.

Useful? React with 👍 / 👎.

Comment thread stdlib/Userscript.affine
manager: can_read,
gm_storage: can_read,
local_storage: us_local_available(),
menu: us_gm_has("registerMenuCommand"),

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Require unregister capability before issuing menu handles

capabilities().menu checks only GM_registerMenuCommand, so a script granted registration but not GM_unregisterMenuCommand receives a handle that the API says must be released, yet release_menu_command can only fail and leave the native menu active. Require both capabilities before registering a releasable command, or provide a release path that does not depend on the missing grant.

Useful? React with 👍 / 👎.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant