main.js & handlers
Whatever you cannot assemble from actions, you write in main.js: every exported function is a handler that you select in the builder as the action "Script handler (main.js)". Handlers receive a context from the runtime – they load data, read and write the state, store, export and talk to the host.
Hosted apps do not load an SDK. Everything a handler needs is in the context.
Your first handler
/** @type {MethacoreHandler} */
export async function begruessen({ data, setState, toast }) {
const profil = await data.load("me.profile");
setState("profil", profil);
await toast(`Hallo ${profil.firstName}!`, "green");
}
In the builder: Button → Actions → On click → Script handler (main.js) → begruessen. In app.json:
{ "type": "script", "handler": "begruessen" }
The template every new app starts with:
// Handlers exported here can be used as "script" actions in the builder.
// Each handler receives { state, getState, setState, data, storage, exportRows, toast, navigate, event, item, args }.
/** @type {MethacoreHandler} */
export async function onStart({ setState, data }) {
const profile = await data.load("me.profile");
setState("profile", profile);
}
To run a handler on start, attach it to the On load event of the root node.
The context
| Field | Type | Meaning |
|---|---|---|
state | object | the state at the moment the action started |
getState() | () ⇒ object | the current state, also after an await |
setState(key, value) | void | sets a key; dots separate levels ("formular.name"). The app then re-renders. |
data.load(source, params?) | Promise | loads a data source, e.g. data.load("me.groups") |
storage | object | the app storage: list, get, set, delete |
exportRows(rows, options) | Promise | exports a list as CSV, XLSX or PDF |
toast(message, color?) | Promise | notice in the host; color is green, blue, orange or red |
navigate(path) | Promise | asks the host to switch to one of its pages |
event | any | payload of the event, e.g. { value } for change |
item | any | row of a table (rowClick) or entry of a list |
args | object | the args configured on the action, already evaluated |
state is a snapshot. If you need the latest state after an await, use getState().
Types and autocompletion
The Studio's code area knows the types from the runtime's HANDLER_TYPES. With /** @type {MethacoreHandler} */ above a function you get autocompletion for the whole context:
declare type MethacoreState = Record<string, any>;
declare type MethacoreSource = "me.profile" | "me.groups" | "me.events" | "me.trainingplans" | "me.competitions" | "me.membercard" | "storage.list" | "storage.get" | "storage.put" | "storage.delete" | "request";
declare type MethacoreStorageScope = "org" | "user";
declare interface MethacoreExportOptions {
format: "csv" | "xlsx" | "pdf";
filename?: string;
columns?: { key: string; label?: string }[];
/** CSV only: semicolon and BOM for German Excel. */
excel?: boolean;
/** PDF only. */
title?: string;
}
declare interface MethacoreHandlerContext {
/** State at the moment the action started. */
state: MethacoreState;
/** Current state, also after awaits. */
getState(): MethacoreState;
setState(key: string, value: unknown): void;
/** Payload of the event, e.g. { value } of a change. */
event?: any;
/** Row of a table or list the event came from. */
item?: any;
/** Arguments configured on the script action. */
args?: Record<string, any>;
/** Loads a data source of the Builder, e.g. await data.load("me.groups"). */
data: { load(source: MethacoreSource, params?: Record<string, unknown>): Promise<any> };
/** App storage of the organisation (default) or of the member. */
storage: {
list(collection: string, options?: { scope?: MethacoreStorageScope; limit?: number; offset?: number }): Promise<{ items: { key: string; value: any; updatedAt: string }[]; total: number }>;
get(collection: string, key: string, options?: { scope?: MethacoreStorageScope }): Promise<{ key: string; value: any; updatedAt: string }>;
set(collection: string, key: string, value: unknown, options?: { scope?: MethacoreStorageScope }): Promise<void>;
delete(collection: string, key: string, options?: { scope?: MethacoreStorageScope }): Promise<void>;
};
exportRows(rows: Record<string, unknown>[], options: MethacoreExportOptions): Promise<void>;
toast(message: string, color?: "green" | "blue" | "orange" | "red"): Promise<void>;
navigate(path: string): Promise<void>;
}
declare type MethacoreHandler = (context: MethacoreHandlerContext) => unknown;
Examples
Storing with your own key
/** @type {MethacoreHandler} */
export async function anheften({ getState, setState, storage, toast }) {
const text = String(getState().neu ?? "").trim();
if (!text) return toast("Schreib zuerst etwas.", "orange");
const key = `n-${Date.now().toString(36)}`;
await storage.set("pinnwand", key, { text, am: new Date().toISOString() });
const seite = await storage.list("pinnwand", { limit: 100 });
setState("notizen", seite.items);
setState("neu", "");
}
Clicking a table row
/** @type {MethacoreHandler} */
export function auswaehlen({ item, setState }) {
setState("auswahl", item);
setState("detailOffen", true);
}
A node with "visible": "{{state.detailOffen}}" then shows the details.
Filtered export
/** @type {MethacoreHandler} */
export async function exportieren({ getState, exportRows, args }) {
const termine = (getState().termine ?? []).filter((termin) => termin.location === args.ort);
await exportRows(termine, {
format: "pdf",
filename: `termine-${args.ort}`,
title: `Termine in ${args.ort}`,
columns: [
{ key: "title", label: "Termin" },
{ key: "start", label: "Beginn" },
],
});
}
{ "type": "script", "handler": "exportieren", "args": { "ort": "{{state.ort}}" } }
Validating input before saving
/** @type {MethacoreHandler} */
export async function anmelden({ state, storage, toast, navigate }) {
const { name, email } = state.formular ?? {};
if (!name || !/^[^@\s]+@[^@\s]+$/.test(email ?? "")) {
return toast("Bitte Name und eine gültige E-Mail angeben.", "red");
}
await storage.set("anmeldungen", `a-${Date.now()}`, { name, email }, { scope: "user" });
await toast("Du bist angemeldet.", "green");
await navigate("/apps");
}
Errors
If a handler throws or a call fails, the app shows "Action failed: <message>" and writes the error to the console. The remaining actions in the same chain then no longer run. Catch errors yourself if you want to show your own message:
export async function laden({ data, setState, toast }) {
try {
setState("ausweis", (await data.load("me.membercard")).card);
} catch (error) {
await toast("Der Ausweis ist gerade nicht erreichbar.", "orange");
}
}
What main.js can – and cannot – do
main.jsis an ES module. You load other.jsfiles of the draft with a relative import:import { format } from "./format.js";- Export named functions or a default object containing functions. Handler names follow the rules for JavaScript identifiers.
- Network only via the context: the security policy allows connections to
*.api.methacore.deand to the Artim Developer Portal, nothing else.fetchto other addresses fails. - The app runs in a sandboxed iframe without its own origin: no
localStorage, no cookies. For persistent data there is the app storage. - No access to the host's DOM. You control the appearance via
styling.css, not via script. - If
main.jscannot be loaded, the app still starts – only script actions then report that their handler is missing.
The old sdk parameter
Earlier handlers received an sdk object. It is still in the context but deprecated and will disappear in a later schema version. Here is how to migrate:
| Old | New |
|---|---|
sdk.api.apps.me.profile() | data.load("me.profile") |
sdk.api.apps.me.groups() | data.load("me.groups") |
sdk.api.apps.storage.list("c", { scope }) | storage.list("c", { scope }) |
sdk.api.apps.storage.put("c", "k", v) | storage.set("c", "k", v) |
sdk.api.apps.storage.delete("c", "k") | storage.delete("c", "k") |
sdk.api.request("members", "/members") | data.load("request", { section: "members", path: "/members" }) |
sdk.host.toast(text, color) | toast(text, color) |
sdk.host.navigate(path) | navigate(path) |
sdk.exportRows(rows, options) | exportRows(rows, options) |