Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions .claude/CLAUDE.md
Original file line number Diff line number Diff line change
Expand Up @@ -138,6 +138,7 @@ The "no Node.js / no Bun" rules in the language policy table have two approved e
| Path | Banned thing(s) used | Rationale | Unblock condition |
|---|---|---|---|
| `packages/affinescript-cli/mod.js` | `process.platform`/`process.arch`/`process.env`, `node:fs/promises`, `node:child_process`, `Bun.spawn`, `Bun.file`, `Bun.write` | The shim is the **compiler-distribution front door**. Its consumers β€” LSP installers, IDE extensions, CI scripts wiring AffineScript into a build pipeline β€” overwhelmingly live in Node and Bun ecosystems, not Deno. Forcing them to install Deno solely to fetch+verify+exec a binary defeats the shim's "ergonomic install" purpose. The branches are guarded by single-line runtime detection at module load; nothing else in the repo depends on this pattern. | None β€” this is the intended steady state. The shim's whole job is to be runtime-agnostic. |
| `test/e2e/userscript/*.mjs` | `node:fs`, `node:module`, `node:url`, `node:path`; optionally `playwright` (headless Chromium) or `jsdom` | The **userscript target's page fixture** (`--target userscript`). The emitted artefact is a classic script, so the only way to assert its real behaviour β€” div append/teardown, menu-command lifetime, storage fallback, add/remove listener balance β€” is to run it in a page. Compiled-output test harnesses, not shipped code or build tooling; same role as the existing `tests/codegen-*/*.harness.mjs`. `dom_harness.mjs` executes the emitted `stdlib/UserscriptDom.affine` against a recording fake DOM (no engine needed); `harness.mjs` drives a page. | None β€” test-harness steady state. It reads a build artefact and drives a page; it is never imported by anything in `lib/`, `bin/` or `stdlib/`. |
| `editors/vscode/test/**/*.js` | `node:*`, Mocha, `@vscode/test-electron` (Electron-based VS Code download + launch) | The **in-editor smoke harness** for issue #139 β€” loads the compiled `out/extension.cjs` in a real VS Code extension host and asserts activation, command registration, `restartLsp` cycling, and `deactivate` teardown. The VS Code extension host is npm/Node-native; `@vscode/test-electron` (the official runner) downloads a real Electron VS Code and launches it under `xvfb-run`. No Deno equivalent exists, and the test cannot be expressed in any other runtime. Scope is strictly `editors/vscode/test/` β€” no production code uses Node. | None β€” this is the intended steady state, paralleling the `affine-vscode-publish.yml` workflow that already uses npm at publish time (#104). |

Browsers and Cloudflare Workers are NOT supported and never will be (the shim's purpose β€” fetch, save to disk, exec a native binary β€” cannot be done in a sandboxed JS runtime). The JSR runtime-compatibility checkboxes for this package should be: Deno βœ…, Bun βœ…, Node βœ…, Workers ❌, Browsers ❌.
Expand Down
15 changes: 15 additions & 0 deletions .github/workflows/ci.yml
Original file line number Diff line number Diff line change
Expand Up @@ -141,6 +141,21 @@ jobs:
cd affinescript-router/e2e
bun install --frozen-lockfile --ignore-scripts
opam exec -- bun test --timeout 60000
- name: Userscript target fixture (single-file IIFE, headless Chromium)
# Compiles test/e2e/userscript/probe.affine with --target userscript and
# runs the artefact in a real page: div append + teardown, menu command,
# setting round-trip, style release, listener spy (no listener left
# behind) β€” once under @grant none, once under @grant GM_*, once on a
# page that denies storage. Also gates the single-file contract (no
# import/export/dynamic import/eval/top-level await), the --iife /
# --target equivalence, --banner happy path + both refusals, the
# --wasm-gc conflict (E0827) and the two planted negatives.
# Reuses the Chromium pinned by affinescript-tea/e2e (installed above),
# so this adds no browser download; AFFINESCRIPT_E2E_STRICT turns a
# missing engine into a failure instead of a skip.
env:
AFFINESCRIPT_E2E_STRICT: "1"
run: opam exec -- ./tools/run_userscript_tests.sh
- name: Run face-transformer regression tests
run: opam exec -- ./tools/run_face_transformer_tests.sh
- name: Issue #35 Phase 3 β€” block extension.ts regression
Expand Down
194 changes: 184 additions & 10 deletions bin/main.ml
Original file line number Diff line number Diff line change
Expand Up @@ -510,13 +510,102 @@ let repl_cmd_fn () =
Format.eprintf "REPL not yet implemented@.";
`Error (false, "REPL not yet implemented")

(** Read and validate a [==UserScript==] banner file.

The banner is prepended verbatim, so it must be a complete metadata
block: an opening [==UserScript==] line, a closing [==/UserScript==]
line, and the opening before the closing. Anything else is a mistake
that would ship a script the manager cannot parse, so it is refused
rather than pasted through. *)
let read_userscript_banner (banner : string option) : (string, string) result =
match banner with
| None -> Ok ""
| Some path ->
(match (try Ok (read_file path) with Sys_error e -> Error e) with
| Error e -> Error (Printf.sprintf "cannot read --banner %s: %s" path e)
| Ok text ->
let contains needle =
let nl = String.length needle and tl = String.length text in
let rec scan i =
if i + nl > tl then false
else if String.sub text i nl = needle then true
else scan (i + 1)
in
scan 0
in
if not (contains "==UserScript==") then
Error (Printf.sprintf
"--banner %s is not a ==UserScript== metadata block \
(no `// ==UserScript==` opener)" path)
else if not (contains "==/UserScript==") then
Comment on lines +524 to +528

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 exact userscript metadata marker lines

The validator only searches for marker substrings, so a file such as console.log("==UserScript=="); console.log("==/UserScript=="); is accepted and prepended even though it contains no userscript metadata block. Managers will not recognize the resulting artifact as a valid userscript; require the exact // ==UserScript== and // ==/UserScript== lines in the proper block position rather than arbitrary substring occurrences.

Useful? React with πŸ‘Β / πŸ‘Ž.

Error (Printf.sprintf
"--banner %s has no `// ==/UserScript==` terminator" path)
else
let open_at =
try Some (Str.search_forward (Str.regexp_string "==UserScript==") text 0)
with Not_found -> None
in
let close_at =
try Some (Str.search_forward (Str.regexp_string "==/UserScript==") text 0)
with Not_found -> None
in
match (open_at, close_at) with
| (Some o, Some c) when c < o ->
Error (Printf.sprintf
"--banner %s closes before it opens (==/UserScript== \
precedes ==UserScript==)" path)
| _ -> Ok text)

(** Compile a file. With [--json], emits diagnostics for any
compilation errors. With [--wasm-gc], targets the WebAssembly GC
proposal instead of WASM 1.0 linear memory. *)
proposal instead of WASM 1.0 linear memory.

[--target userscript] (alias [--iife]) selects the single-file
userscript target; the LLVM-triple reading of [--target] is unchanged
for every other value. *)
let compile_file face json wasm_gc vscode_ext vscode_adapter vscode_no_lc
deno_esm bun_esm target path output =
deno_esm bun_esm iife banner target path output =
let face = resolve_face ~quiet:json face path in
if deno_esm || Filename.check_suffix output ".deno.js" then
(* `--target userscript` / `--target iife` / `--iife` are target *modes*,
not LLVM triples (documented in the CLI reference). *)
let userscript =
iife
|| (match target with Some "userscript" | Some "iife" -> true | _ -> false)
in
(* 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 πŸ‘Β / πŸ‘Ž.

let banner_text, banner_error =
if userscript then
match read_userscript_banner banner with
| Ok t -> (Some t, None)
| Error m -> (None, Some m)
else (None, None)
in
if userscript && wasm_gc then
let message =
"--target userscript emits a single JS file and has no wasm module; \
it cannot be combined with --wasm-gc" in
if json then
json_finish [{ Affinescript.Json_output.severity = Error;
code = "E0827"; message;
span = Affinescript.Span.dummy; help = None; labels = [] }]
else begin
Format.eprintf "@[<v>Backend selection error: %s@]@." message;
`Error (false, "Backend selection error")
end
else if (match banner_error with Some _ -> true | None -> false) then
let message = Option.get banner_error in
if json then
json_finish [{ Affinescript.Json_output.severity = Error;
code = "E0827"; message;
span = Affinescript.Span.dummy; help = None; labels = [] }]
else begin
Format.eprintf "@[<v>Userscript banner error: %s@]@." message;
`Error (false, "Userscript banner error")
end
else if deno_esm || Filename.check_suffix output ".deno.js" then
let message = "Deno-ESM was removed; use --bun-esm (and a .bun.js output path)" in
if json then
json_finish [{ Affinescript.Json_output.severity = Error;
Expand Down Expand Up @@ -581,7 +670,38 @@ let compile_file face json wasm_gc vscode_ext vscode_adapter vscode_no_lc
let is_why3 = Filename.check_suffix output ".mlw" in
let is_lean = Filename.check_suffix output ".lean" in
let is_spirv = Filename.check_suffix output ".spv" in
if is_bun then begin
if userscript then begin
(* Reachability check FIRST: it walks the module graph the
resolver loaded, so a refusal can name the module. *)
match Affinescript.Codegen_userscript.check_reachable
~loader ~root_name:path prog with
| errs when errs <> [] ->
List.iter (fun (u : Affinescript.Codegen_userscript.unsupported) ->
add { severity = Error; code = "E0827";
message = Printf.sprintf
"userscript target: unsupported %s"
(Affinescript.Codegen_userscript.show_unsupported u);
span = Affinescript.Span.dummy;
help = Some "a userscript is one non-module file; \
remove the construct or build that module \
for another target";
labels = [] }) errs
| _ ->
let banner =
match banner_text with
| Some t when t <> "" -> Some t
| _ -> None
in
(match Affinescript.Codegen_userscript.codegen_userscript
?banner flat_prog resolve_ctx.symbols with
| Error msg ->
add { severity = Error; code = "E0827"; message = msg;
span = Affinescript.Span.dummy; help = None; labels = [] }
| Ok js ->
let oc = open_out_bin output in
output_string oc js;
close_out oc)
end else if is_bun then begin
match Affinescript.Codegen_deno.codegen_bun flat_prog resolve_ctx.symbols with
| Error msg ->
add { severity = Error; code = "E0825";
Expand Down Expand Up @@ -815,7 +935,37 @@ let compile_file face json wasm_gc vscode_ext vscode_adapter vscode_no_lc
let is_why3 = Filename.check_suffix output ".mlw" in
let is_lean = Filename.check_suffix output ".lean" in
let is_spirv = Filename.check_suffix output ".spv" in
if is_bun then
if userscript then
(match Affinescript.Codegen_userscript.check_reachable
~loader ~root_name:path prog with
| errs when errs <> [] ->
List.iter (fun (u : Affinescript.Codegen_userscript.unsupported) ->
Format.eprintf "@[<v>userscript target: unsupported %s@]@."
(Affinescript.Codegen_userscript.show_unsupported u)) errs;
Format.eprintf
"@[<v>A userscript is a single non-module file: no import/export, \
no dynamic import, no eval, no top-level await.@. Every reachable module must be expressible in plain JS with \
only the documented userscript bindings.@]@.";
`Error (false, "Userscript target error")
| _ ->
let banner =
match banner_text with
| Some t when t <> "" -> Some t
| _ -> None
in
(match Affinescript.Codegen_userscript.codegen_userscript
?banner flat_prog resolve_ctx.symbols with
| Error msg ->
Format.eprintf "@[<v>userscript codegen error: %s@]@." msg;
`Error (false, "Userscript codegen error")
| Ok js ->
let oc = open_out_bin output in
output_string oc js;
close_out oc;
Format.printf "Compiled %s -> %s (userscript, %d bytes)@."
path output (String.length js);
`Ok ()))
else if is_bun then
(match Affinescript.Codegen_deno.codegen_bun flat_prog resolve_ctx.symbols with
| Error e ->
Format.eprintf "@[<v>%s@]@." e;
Expand Down Expand Up @@ -1249,8 +1399,11 @@ let output_arg =
Arg.(value & opt string "out.wasm" & info ["o"; "output"] ~docv:"FILE" ~doc:"Output file")

let target_arg =
Arg.(value & opt (some string) None & info ["target"] ~docv:"TRIPLE"
~doc:"LLVM target triple for native (.ll) output. Overrides the \
Arg.(value & opt (some string) None & info ["target"] ~docv:"TRIPLE|MODE"
~doc:"Target selection. $(b,userscript) (alias $(b,iife)) selects the \
single-file userscript target (see $(b,--iife)); those two words \
are reserved and never read as triples. Any other value is an \
LLVM target triple for native (.ll) output. Overrides the \
AFFINESCRIPT_LLVM_TRIPLE env var; default is x86_64-unknown-linux-gnu. \
Accepts a full triple verbatim (e.g. riscv64-unknown-linux-gnu) or a \
shorthand: x86_64, aarch64/arm64, aarch64-android/android, riscv64, \
Expand Down Expand Up @@ -1301,6 +1454,27 @@ let bun_esm_arg =
Deno runtime shim. A `.bun.js` output extension selects this \
backend implicitly.")

(* Userscript target: `--target userscript` (alias `--iife`) emits ONE
ES2020 IIFE file β€” no import/export, no dynamic import, no eval, no
top-level await β€” suitable for Tampermonkey/Greasemonkey/Violentmonkey. *)
let iife_arg =
Arg.(value & flag & info ["iife"]
~doc:"Emit a single-file ES2020 userscript (shorthand for \
$(b,--target userscript)). The output is one IIFE with no \
import/export, no dynamic import, no eval and no top-level await; \
a construct the target cannot lower fails the build, naming the \
module and the construct. Pair with $(b,--banner) for the \
$(b,==UserScript==) metadata block.")

let banner_arg =
Arg.(value & opt (some string) None & info ["banner"] ~docv:"FILE"
~doc:"With $(b,--target userscript)/$(b,--iife), prepend the contents of \
FILE verbatim. FILE must be a complete $(b,==UserScript==) \
metadata block: an opening $(b,// ==UserScript==) line and a \
closing $(b,// ==/UserScript==) line. Declare $(b,@grant none) \
there unless the script needs the manager bindings in \
$(b,stdlib/Userscript.affine).")

(** Shared --face flag: select the parser surface-syntax face. *)
let face_arg =
let faces = Arg.enum [
Expand Down Expand Up @@ -1339,7 +1513,7 @@ let face_arg =
($(b,function)/$(b,set...to)/$(b,if...then)/$(b,end)/$(b,is)/$(b,and)/etc.). \
$(b,lucid)/$(b,lucidscript)/$(b,purescript) β€” PureScript-style \
($(b,module … where)/$(b,data)/$(b,class)/$(b,instance)/$(b,case … of)/\
$(b,\\x ->)/$(b,let … in)/$(b,True)/$(b,--) comments). \
$(b,\\\\x ->)/$(b,let … in)/$(b,True)/$(b,--) comments). \
$(b,cafe)/$(b,cafescripto)/$(b,coffee)/$(b,coffeescript) β€” CoffeeScript-style \
($(b,->)/$(b,=>)/$(b,@)/$(b,unless)/$(b,until)/postfix-if/postfix-unless/\
$(b,Yes)/$(b,No)/$(b,On)/$(b,Off)/$(b,#) comments/$(b,###) blocks). \
Expand Down Expand Up @@ -1644,11 +1818,11 @@ let repl_cmd =
Cmd.v info Term.(ret (const repl_cmd_fn $ const ()))

let compile_cmd =
let doc = "Compile a file to WebAssembly (1.0 or GC proposal), native Bun ESM (.bun.js/--bun-esm), Julia (.jl), JavaScript (.js), C (.c), a WGSL compute kernel (.wgsl), a Faust DSP program (.dsp), or an ONNX model (.onnx)" in
let doc = "Compile a file to WebAssembly (1.0 or GC proposal), native Bun ESM (.bun.js/--bun-esm), a single-file userscript (--target userscript/--iife), Julia (.jl), JavaScript (.js), C (.c), a WGSL compute kernel (.wgsl), a Faust DSP program (.dsp), or an ONNX model (.onnx)" in
let info = Cmd.info "compile" ~doc in
Cmd.v info Term.(ret (const compile_file $ face_arg $ json_arg $ wasm_gc_arg
$ vscode_ext_arg $ vscode_adapter_arg $ vscode_no_lc_arg $ deno_esm_arg
$ bun_esm_arg $ target_arg $ path_arg $ output_arg))
$ bun_esm_arg $ iife_arg $ banner_arg $ target_arg $ path_arg $ output_arg))

let fmt_cmd =
let doc = "Format a file" in
Expand Down
16 changes: 16 additions & 0 deletions docs/CAPABILITY-MATRIX.adoc
Original file line number Diff line number Diff line change
Expand Up @@ -212,6 +212,21 @@ under Bun. `tools/run_codegen_deno_tests.sh` (historical name) compiles
Migration and host-contract details:
link:guides/bun-esm-migration.adoc[guides/bun-esm-migration.adoc].

|Userscript (browser) |works |`lib/codegen_userscript.ml`,
`--target userscript` / `--iife` / `--banner FILE`. Direct AST→ES2020
single-file IIFE for userscript managers: no import/export, no dynamic
import, no `eval`, no top-level `await` (all four are checked on every
build). Host surface is a closed allowlist β€” `stdlib/Userscript.affine`'s
`us_*`/`dom_*` externs β€” and anything else is a build error naming the
construct and module (E0827); effect handlers, `unsafe` and float-cell
records are refused rather than miscompiled. `use prelude::*` is safe in a
page-injected file because the target prunes to what `main` reaches
(reachability, not minification). No WASM: the constructs that would need
linear memory are refused, and `wasm-unsafe-eval` is not available in the
page CSP a userscript inherits. Runtime fixture runs the compiled script in a
page under `@grant none`, `@grant GM_*` and a storage-denying page.
Guide: link:guides/userscript-target.adoc[guides/userscript-target.adoc].

|Node-CJS |works |`lib/codegen_node.ml`; CJS shim, handle table, the
`.affine` VS Code extension compiles through it. Live-host smoke
harness for the compiled extension landed via PR #317 / issue #139:
Expand Down Expand Up @@ -268,6 +283,7 @@ test is deleted or renamed without this section (and CI) noticing.
|Codegen (golden snapshots) |`test/test_golden.ml`
|Deno / JS host backends |`test/test_deno_builtins_consistency.ml`, `test/test_int_div_js.ml`
|Bun-ESM host backend |`tools/run_codegen_bun_tests.sh`
|Userscript target |`tools/run_userscript_tests.sh`; fixtures `test/e2e/userscript/probe.affine`, `test/e2e/userscript/reachability.affine`, negatives `test/e2e/userscript/negatives/missing_binding.affine`, `test/e2e/userscript/negatives/handle_leak.affine`
|Solo core (executable metatheory) |`test/test_solo_cesk.ml`
|===

Expand Down
3 changes: 2 additions & 1 deletion docs/NAVIGATION.adoc
Original file line number Diff line number Diff line change
Expand Up @@ -46,7 +46,8 @@ This guide helps you navigate the AffineScript repository structure.
|**docs/specs/** |Language specifications
|**docs/governance/** |Community and contribution docs
|**docs/standards/** |Design decisions, roadmap, releases
|**docs/guides/** |Testing reports and guides
|**docs/guides/** |Testing reports and guides; link:guides/userscript-target.adoc[shipping a userscript] covers the `--target userscript` build, `stdlib/Userscript.affine` and its page-injected contract
|**docs/reference/** |ABI/FFI, compiler capabilities; link:reference/JSON-AND-YAML.adoc[JSON and YAML conventions] records the I-JSON + JCS (`ijson-jcs`) and kyaml rules for machine-readable output
|**wiki/** |Extended documentation and wiki content
|===

Expand Down
Loading
Loading