Skip to content

Scripting: project scripts and contributions from a language

Audience: model authors and build engineers · about 5 minutes · Prerequisites: Scripting the workbench

Project scripts

A script is the body of an async function with workbench, args, log and cancelled(); return gives its result. workbench.scripts.run(text) runs text you hold. A project can also keep scripts in files named *.script.js (found up to four folders deep, skipping node_modules, generated and build) or list them in project.json:

{
  "scripts":  [{ "name": "tidy", "file": "tools/tidy.js", "description": "Normalise the model" }],
  "triggers": [{ "on": "open", "script": "tidy" }, { "on": "save", "script": "report" }]
}

workbench.scripts.list() lists them, workbench.scripts.runFile("tidy") runs one, and workbench.scripts.fire("open") runs the open triggers in order (a failing or untrusted one is reported in the result and the rest still run). A script found in a project is arbitrary code, so the host must say it is trusted first; a host that has no trust policy runs nothing it discovered. From the command line that decision is --trust-project-code. Edits a script makes inside workbench.transaction carry the origin script:<name> in the audit log.

The Workbench Scripts sample (File > Load Sample…, or samples/workbench-scripts/ in the repository) is a ready-made project (the IDE puts the scripts in your copy of the sample, so Run Workbench Script… finds them straight away) with three scripts (a report, an atomic edit with arguments, an open trigger), the project.json that lists them, and the exact commands to run them.

In the IDE

Run Workbench Script… (Tools menu, or the command palette) lists the project's scripts, asks which to run, and shows what it logged and returned in the Messages panel. The first time you run a script, and again after you change it, the IDE asks you to confirm: it is JavaScript with access to the project's files. Your approval is remembered for that exact text. In a restricted workspace (VS Code's Restricted Mode) no project script runs at all, approved or not.

project.json triggers run on their own when a project opens ("on": "open") and after the model is saved ("on": "save"). Because nobody chose to run them at that moment, a trigger runs only a script you approved before, whatever the trust setting; any other trigger script is skipped with a Messages line that tells you to run it once with the command. A trigger that edits the model makes the app save again, so triggers do not fire again for a short while after one ran, and not while one is running.

Scripts and tests

A script does something; a test expects something. When you want to check what the workbench API does to a model (and have the result in the Tests pane, strukts test and Verify), write it as a JS test: describe / it / expect with the same workbench, each test on its own copy of the model. workbench.tests.run() runs a model's tests from a script; it takes an optional trust hook (default: the same trust the script itself runs under).

Contribute actions, commands and listeners from a language

A concept can offer more than its own editing behaviour. Its contributes() method returns actions (offered on a node, named in menus), commands (callable by id) and event handlers:

class Report extends Concept() {
    head = "report";
    contributes() {
        return {
            actions: [{
                id: "refresh",
                label: "Refresh this report",
                menus: ["context", "palette"],
                isApplicable: ({ node }) => node.children.length > 0,
                run: ({ node, workbench }) => workbench.transaction(() => { /* edit the node */ }, { label: "refresh" }),
            }],
            commands: [{ id: "reports.count", run: (args, { workbench }) => workbench.model.active().nodes(workbench.model.resolve("concept", "Report")).length }],
            events: { "checks.finished": ({ errors }, { lang }) => { /* react */ } },
        };
    }
}

In the IDE the active document's language (and the languages it imports) is activated for you while the document is open, and withdrawn when you move to another language. An action that lists "context" in its menus appears in the editor's right-click menu under Actions, for the node under the cursor and only when its isApplicable accepts it. Elsewhere, nothing is live until the language is activated: workbench.languages.activate(lang) registers everything its concepts declare under the owner language:<name>, and deactivate (or disposing the returned handle) removes it all. A subconcept inherits its parent's contributions; an action with the same id replaces the parent's for the subconcept's nodes. workbench.actions.list({ node }) shows what applies to a node, workbench.actions.run(id, { node }) runs one, and workbench.commands.execute(id, args) runs a command. Every run is audited with the origin action:<id> or command:<id>.

You can register a command without a language too; give it an owner so it disappears with it:

const owner = "script:demo";
workbench.commands.register({ id: "demo.add", label: "Add", run: ([a, b]) => a + b }, owner);
assert(workbench.commands.has("demo.add"));
assert(workbench.commands.execute("demo.add", [2, 3]) === 5);
workbench.owners.dispose(owner);
assert(!workbench.commands.has("demo.add"), "gone with its owner");

A language cannot rewrite itself

Code that runs for language L (a check, an action, a command) gets a workbench whose languages write methods refuse to modify L while it runs, and throw InvalidEditError. It may edit any other language. A project script, which belongs to no language, may edit any.

Edit a language

workbench.languages can create a language and change its concepts and enums with the same calls the Language Editor uses. A change tells you which nodes of the open model lost their concept (orphans); nothing is deleted behind your back. Persist with await workbench.languages.save(language).

const demo = workbench.languages.create({ name: "cookbook-demo", concepts: [{ head: "thing", slots: [] }] });
try {
    assert(workbench.languages.concepts("cookbook-demo").some((c) => c.head === "thing"));
    const gone = workbench.languages.deleteConcept(demo, "thing");
    assert(typeof gone.orphans === "number");
    workbench.languages.setConcept(demo, { head: "item", slots: [] });
    assert(workbench.languages.find("cookbook-demo").getConcept("item"));
} finally {
    workbench.languages.remove(demo);
}
assert(workbench.languages.find("cookbook-demo") === null);

A language can declare the API major it was written for in its language.json ("apiVersion": "0"). Activating a language whose major differs from the workbench's returns a warning (activation.warnings) and is audited; it still activates.

Commands

workbench.commands.list() lists every command you can run: the application's own (everything in the command palette and the menus) and the ones languages and scripts registered. workbench.commands.execute(id) runs one and returns what it returned. An application command runs through the active document's handlers, so one the document cannot run right now (for example Run Generator in a document without a generator) fails with UnavailableError; each row's runnable tells you beforehand. Registering a command with an id that is already an application command is refused. Every run is audited with the origin command:<id>.

A command you register can say where a host with menus lists it and which key runs it: menu ("file", "edit", "view", "run", "navigate", "tools" (the default) or "help") and keybinding (in Theia's grammar, e.g. "ctrlcmd+alt+k"). A command with a description shows it as the menu tooltip. A key binding that collides with an existing one is refused: the command is not drawn and a warning says why.

const rows = workbench.commands.list();
assert(Array.isArray(rows));
assert(rows.every((r) => typeof r.id === "string" && (r.source === "registry" || r.source === "host")));

Find your way around

workbench.help() lists every namespace with a one-line summary and marks the ones this host does not provide; workbench.help("git") lists one namespace's members and says why it is off. workbench.describe() returns the same as data (namespaces, capabilities, who registered which listener, action, command or contribution), which is what an API explorer draws.

const text = workbench.help();
assert(text.includes("checks") && text.includes("transaction"));
const d = workbench.describe();
assert(d.namespaces.some((n) => n.name === "model" && n.available));
assert(workbench.help("checks").includes("run"));

In the Model Console, print(workbench.help()) shows the list, and typing workbench. (or workbench.checks., ...) offers the API's members from the live object. Workbench API Explorer (command palette, Tools) shows the same in a window: every namespace on this host, which are unavailable and why, and what languages and scripts have registered.

Typings for your language

workbench.languages.typings() returns a TypeScript declaration generated from the language: the concept heads, their capitalised names and every concept's slots. It is virtual: generated in memory, never written to disk.

const dts = workbench.languages.typings();
assert(dts.includes("type Head ="));
return dts.length;