Appearance
Server globals serverside
Everything available to serverside scripts, weapon server halves, classes and serverside NPC code (globals.d.ts).
Source
Generated from templates/server/data/scripts/globals.d.ts. To change this page, edit the JSDoc in that file.
Overview
Ambient declarations for host functions injected by the ClearScript V8 runtime (see GServer). These are available to every script in this folder without needing an import.
Fire-and-forget host calls (like echo) are batched: they queue JS-side and are delivered to the server in one batch at the next flush point (end of the current server tick at the latest, 50ms at 20 TPS). Ordering between batched calls is preserved, but their arguments must be JSON-serializable and they cannot return values. Calls that return values or take callbacks (sleep, setTimeout, ...) reach the server directly instead.
Declarations
echo function
ts
declare function echo(msg: string): voidPrints a message to the server console. Batched: delivered at the next flush point (end of the current server tick at the latest). The argument must be JSON-serializable.
sleep function
ts
declare function sleep(seconds: number): Promise<void>Cooperatively pauses the calling (async) script for the given number of seconds. Other scripts keep running while this one is suspended. Resolution is tied to server ticks, so resume timing is rounded up to the next tick (50ms at 20 TPS).
setTimeout function
ts
declare function setTimeout(handler: (...args: any[]) => void, ms?: number, ...args: any[]): numberRuns handler once after ms milliseconds (rounded up to the next server tick). Returns an id usable with clearTimeout. Extra args are forwarded to the handler.
clearTimeout function
ts
declare function clearTimeout(id: number | null | undefined): voidCancels a pending setTimeout by id. null, undefined or an unknown id is a no-op.
setInterval function
ts
declare function setInterval(handler: (...args: any[]) => void, ms?: number, ...args: any[]): numberRuns handler repeatedly every ms milliseconds (fires at most once per server tick). Returns an id usable with clearInterval. Extra args are forwarded to the handler.
clearInterval function
ts
declare function clearInterval(id: number | null | undefined): voidCancels a running setInterval by id. null, undefined or an unknown id is a no-op.
triggerClient function
ts
declare function triggerClient(scriptType: 'weapon', scriptName: string, ...params: any[]): voidSends an action to the CURRENT player's client, invoking onActionClientSide(...params) on their copy of the named weapon. Batched; params must be JSON-serializable.
"Current player" is the player whose event is being handled — valid inside onActionServerSide, onPlayerJoined and onPlayerLeft. There is no current player after an await or inside timer callbacks; calls made there are dropped (with a server-console log). scriptType is "weapon" for now (clients run nothing else); scriptName is the weapon's name — in a weapon's serverside half, this.name reaches its own clientside half:
ts
export function onActionServerSide(this: ScriptThis, player: Player, action: string) {
triggerClient('weapon', this.name, 'reply', 'hi ' + player.account)
}sendPM function
ts
declare function sendPM(target: string | Player, text: string): voidSends a SYSTEM private message to a player on any server, via GSocial. The client receives it as onPMReceived({ account: <this server's name>, server: <this server's name>, system: true }, text). Online-only: dropped if they aren't connected anywhere. Text max 200 characters. Accepts an account name or a Player. Unlike triggerClient, needs no player context.
ts
sendPM(player, 'Welcome back!')
sendPM('SomeAccount', 'Server restarts in 5 minutes')findplayer function
ts
declare function findplayer(account: string): Player | nullThe online player logged in with this account name (case-insensitive) — a full Player object, client./clientr. flag bags included — or null when they aren't connected to THIS server. Needs no player context, so it works from timers, onInitialized and async continuations. Like every Player, x/y/level are a snapshot taken by this call.
ts
const p = findplayer('SomeAccount')
if (p) p.clientr.gold = (p.clientr.gold ?? 0) + 10allplayers global
ts
declare const allplayers: readonly Player[]Every player online on THIS server, in connection order — full Player objects, client./clientr. flag bags included. Needs no player context. Each read builds a fresh snapshot array (x/y/level as of that read), so read it once into a local rather than indexing it in a loop, and compare players by account or id, not ===.
ts
const online = allplayers
for (const p of online) sendPM(p, 'Server restarts in 5 minutes')createlevel function
ts
declare function createlevel(name: string, fillTile: number, width?: number, height?: number): stringCreates a new blank level named <name>.glvl, width x height tiles (8-512 per side, default 64x64), filled with fillTile on layer 0 (65535 = empty). Names are 1-32 characters (letters, digits, _ or -) WITHOUT extension; creation fails if any level (saved or unsaved) already uses the name. The level lives in server memory and is served to players immediately, but its .glvl file is only written when someone saves it (findlevel(name).savelevel() or "update level") — unsaved levels vanish on server restart. Returns '' on success or a player-presentable error message. Direct call: the result is available immediately.
copylevel function
ts
declare function copylevel(original: string, newName: string): stringCopies a level to a new .glvl file in the same folder as the original. The copy takes the original's current state, including unsaved in-game edits: tiles, collision, NPCs, links and tileset. It's written to disk right away, so no savelevel is needed. original is a level file name such as 'town.glvl' (not a gmap). newName follows the createlevel rules (1-32 letters, digits, _ or -), with or without '.glvl', and the copy fails if any level (saved or unsaved) already uses it. Returns '' on success or a player-presentable error message. Direct call.
ts
const error = copylevel('arena.glvl', 'arena_' + player.account)deletelevel function
ts
declare function deletelevel(name: string): stringDeletes a level for good: its .glvl file and any unsaved in-memory copy. Everyone in the level, in the shared world or in an instance of it, is warped to the server's start position first. Then the level's NPCs, local ones included, are unloaded and their timers stop. Refuses gmaps, gmap members and the server's start level. Returns '' on success or a player-presentable error message. Direct call. Don't call it from an NPC in the level being deleted, because that NPC is unloaded too.
ts
deletelevel('arena_' + player.account + '.glvl')findlevel function
ts
declare function findlevel(name: string): ServerLevel | nullA level object for a level or gmap by file name — findlevel('town.glvl') or findlevel('world.gmap') — with the same API as player.level. Works for any level, whether or not anyone is in it, including unsaved levels made with createlevel. Returns null when no such level or gmap exists. Direct call.
ts
const town = findlevel('town.glvl')
town?.setleveltiletype(10, 4, 22)LevelNpcInfo interface
ts
interface LevelNpcInfoA baked level NPC as stored in the level file (see LevelEditor.getlevelnpcs).
LevelNpcInfo.index
ts
index: numberPosition in the level's NPC list; shifts down when an earlier NPC is removed.
LevelNpcInfo.x
ts
x: numberX position in tiles (fractions allowed).
LevelNpcInfo.y
ts
y: numberY position in tiles (fractions allowed).
LevelNpcInfo.image
ts
image: stringImage asset path ('' = none).
LevelNpcInfo.serverscript
ts
serverscript: stringTypeScript source of the serverside half ('' = none).
LevelNpcInfo.clientscript
ts
clientscript: stringTypeScript source of the clientside half ('' = none).
LevelNpcPatch interface
ts
interface LevelNpcPatchFields to set on a baked level NPC (addlevelnpc / setlevelnpc); omitted fields keep their value ('' / 0 for a new NPC).
LevelNpcPatch.x
ts
x?: numberX position in tiles.
LevelNpcPatch.y
ts
y?: numberY position in tiles.
LevelNpcPatch.image
ts
image?: stringImage asset path ('' = none).
LevelNpcPatch.serverscript
ts
serverscript?: stringTypeScript source of the serverside half.
LevelNpcPatch.clientscript
ts
clientscript?: stringTypeScript source of the clientside half.
LevelLinkInfo interface
ts
interface LevelLinkInfoA level link as stored in the level file (see LevelEditor.getlevellinks).
LevelLinkInfo.index
ts
index: numberPosition in the level's link list; shifts down when an earlier link is removed.
LevelLinkInfo.x
ts
x: numberTrigger rect left edge, whole tiles.
LevelLinkInfo.y
ts
y: numberTrigger rect top edge, whole tiles.
LevelLinkInfo.w
ts
w: numberTrigger rect width in tiles (at least 1).
LevelLinkInfo.h
ts
h: numberTrigger rect height in tiles (at least 1).
LevelLinkInfo.destlevel
ts
destlevel: stringDestination level (or gmap) file name, e.g. "house.glvl".
LevelLinkInfo.destx
ts
destx: numberArrival x in the destination, tiles (ignored when keepx).
LevelLinkInfo.desty
ts
desty: numberArrival y in the destination, tiles (ignored when keepy).
LevelLinkInfo.keepx
ts
keepx: booleanKeep the player's current x instead of destx (Graal "playerx"), for seamless edge links.
LevelLinkInfo.keepy
ts
keepy: booleanKeep the player's current y instead of desty (Graal "playery").
LevelLinkPatch interface
ts
interface LevelLinkPatchFields to set on a level link (addlevellink / setlevellink); omitted fields keep their value (0 / '' / false for a new link). The result must be a valid link: a destination, w and h >= 1, the rect inside the level.
LevelLinkPatch.x
ts
x?: numberTrigger rect left edge, whole tiles.
LevelLinkPatch.y
ts
y?: numberTrigger rect top edge, whole tiles.
LevelLinkPatch.w
ts
w?: numberTrigger rect width in tiles.
LevelLinkPatch.h
ts
h?: numberTrigger rect height in tiles.
LevelLinkPatch.destlevel
ts
destlevel?: stringDestination level (or gmap) file name.
LevelLinkPatch.destx
ts
destx?: numberArrival x in the destination, tiles.
LevelLinkPatch.desty
ts
desty?: numberArrival y in the destination, tiles.
LevelLinkPatch.keepx
ts
keepx?: booleanKeep the player's current x instead of destx.
LevelLinkPatch.keepy
ts
keepy?: booleanKeep the player's current y instead of desty.
LevelEditor interface
ts
interface LevelEditorOnline-editing methods shared by every serverside level object — player.level, findlevel(), the player-scoped global level and an NPC's this.level. All edits go into the server's in-memory copy of the level: tile, tile-type and link changes reach players immediately, NPC edits are staged until reloadlevel(), and nothing touches the .glvl file until savelevel().
Coordinates are whole tiles in the object's own space: on a gmap object, gmap-global tiles that route to the member level underneath; in an NPC's this.level, member-local. NPC and link editing need a single level, so on a gmap object the *levelnpc* and *levellink* methods fail — use findlevel(memberName). Objects for an instance read the shared template but every edit fails. None of these check staff rights: gate them in your script (player.hasstaffright('leveleditor')).
LevelEditor.setleveltile
ts
setleveltile(layer: number, x: number, y: number, tileId: number): booleanSets one tile: tileId is a row-major tileset index (65535 = empty/erase). Every player who sees the level — the initiating player included — receives the change immediately. No-op repaints don't broadcast. Returns false for out-of-range arguments (including a layer the level doesn't have).
LevelEditor.getleveltile
ts
getleveltile(layer: number, x: number, y: number): numberThe tile id at (x, y) on layer in the level's current server state, unsaved edits included (65535 = empty); -1 when out of range.
LevelEditor.getleveltiletype
ts
getleveltiletype(x: number, y: number): numberThe collision tile type at (x, y) in the level's current server state (1 = walkable, 22 = blocking, 11 water, 12 lava, ...); -1 when out of range.
LevelEditor.setleveltiletype
ts
setleveltiletype(x: number, y: number, type: number): booleanSets the collision tile type (1-255; 22 blocks movement) of one tile. Every player who sees the level gets it immediately — walls block (or stop blocking) at once. Returns false for out-of-range arguments.
LevelEditor.setleveltiletypes
ts
setleveltiletypes(x: number, y: number, w: number, h: number, types: number | number[]): booleanSets the collision tile types of a w x h rect at (x, y): types is one type for the whole rect or a row-major array of exactly w * h types (each 1-255). The rect must lie inside the level (on a gmap it may cross member seams, but not holes). All-or-nothing: any invalid value fails the whole call and changes nothing. Sent to players as one update per level touched.
ts
player.level?.setleveltiletypes(10, 4, 6, 1, 22) // a wall segmentLevelEditor.getlevelnpcs
ts
getlevelnpcs(): LevelNpcInfo[] | nullThe level's baked NPCs in its current server state (staged edits included), in index order — positions and full script sources. Local NPCs (putnpc) aren't part of the level and are never listed. Null on gmap objects.
LevelEditor.addlevelnpc
ts
addlevelnpc(data: LevelNpcPatch, live?: boolean): numberAppends a baked NPC and returns its index (-1 on a gmap object, an instance, or invalid fields). Staged: running NPCs don't change until reloadlevel() — unless live is true, which also spawns the new NPC in the running level right away (like reloadlevelnpc(index)).
ts
const town = findlevel('town.glvl')
const index = town?.addlevelnpc({ x: 30, y: 20, image: 'images/sign.png',
serverscript: "export function onCreated() { this.chat = 'Hi' }" }, true)@param data The new NPC's fields; omitted ones are '' / 0. @param live True to spawn it in the running level now; omitted/false stages it.
LevelEditor.setlevelnpc
ts
setlevelnpc(index: number, patch: LevelNpcPatch, live?: boolean): booleanChanges fields of the baked NPC at index — staged until reloadlevel(), or with live true applied at once by restarting just that NPC (like reloadlevelnpc(index)). A wrongly typed field fails the whole call. Returns false for bad indices and on gmap objects.
@param index The NPC's position in getlevelnpcs(). @param patch The fields to change; omitted ones keep their value. @param live True to restart the running NPC with the change now; omitted/false stages it.
LevelEditor.removelevelnpc
ts
removelevelnpc(index: number, live?: boolean): booleanRemoves the baked NPC at index. Staged: the running NPC keeps running until reloadlevel() — unless live is true, which removes it from the level right away (its timers die, players stop seeing it). Every later NPC's index shifts down by one — re-read getlevelnpcs() after removing. Returns false for bad indices and on gmap objects.
@param index The NPC's position in getlevelnpcs(). @param live True to remove the running NPC now; omitted/false stages it.
LevelEditor.reloadlevelnpc
ts
reloadlevelnpc(index: number): booleanRestarts just the baked NPC at index from the level's current server state (staged edits to it included) — the per-NPC reloadlevel(). The running NPC is torn down (its timers die) and recreated: onCreated fires, then onPlayerEnters for every player who sees the level, and players get the fresh NPC — clientside script included — without reloading the level. An NPC just added with addlevelnpc spawns. Other NPCs, putnpc locals and the level's shared state (this.level.<key>) are untouched. Instanced copies of the level restart it too. A level nobody has entered yet just picks the change up when it activates. The first compile of a new script blocks the server briefly. An NPC that reloads itself ends its own script (onCreated runs again on the fresh copy, so guard against loops). Returns false for bad indices, on gmap objects and on instance objects.
ts
town?.setlevelnpc(3, { serverscript: source })
town?.reloadlevelnpc(3)@param index The NPC's position in getlevelnpcs().
LevelEditor.getlevellinks
ts
getlevellinks(): LevelLinkInfo[] | nullThe level's links (warp rects) in its current server state, in index order. Null on gmap objects.
LevelEditor.addlevellink
ts
addlevellink(data: LevelLinkPatch): numberAppends a link and returns its index, or -1 when the result isn't a valid link (no destlevel, an empty rect, a rect outside the level), on a gmap object or an instance. Live: every player who sees the level gets the new link list immediately — a link that appears under a player only fires once they step out and back in. The destination isn't checked; a link to a missing level does nothing when touched.
ts
player.level?.addlevellink({ x: 30, y: 0, w: 4, h: 1,
destlevel: 'north.glvl', destx: 0, desty: 62, keepx: true })LevelEditor.setlevellink
ts
setlevellink(index: number, patch: LevelLinkPatch): booleanChanges fields of the link at index (live, like addlevellink). The whole call fails if a field is wrongly typed or the changed link isn't valid. Returns false for bad indices and on gmap objects.
LevelEditor.removelevellink
ts
removelevellink(index: number): booleanRemoves the link at index (live). Every later link's index shifts down by one — re-read getlevellinks() after removing. Returns false for bad indices and on gmap objects.
LevelEditor.savelevel
ts
savelevel(): booleanWrites the in-memory copy — tile, tile type, NPC and link edits, or a level made with createlevel — to the .glvl file; on a gmap object, every member with unsaved edits. Running state isn't touched (reloadlevel() or reloadlevelnpc() applies staged NPC edits). Saved NPC scripts are type-checked in the background; errors go to the server log. True when there was nothing to save; false for a failed write (the edits stay in memory).
LevelEditor.reloadlevel
ts
reloadlevel(): booleanApplies the level's current server state to everything running: its NPCs are recreated from its NPC list (onCreated fires again; putnpc locals survive) and every player who sees it reloads it in place. The way to make all staged NPC edits live at once (reloadlevelnpc() does one NPC). On a gmap object, reloads every member with staged changes.
LevelEditor.resetlevel
ts
resetlevel(): booleanDiscards all unsaved edits (tiles, tile types, NPCs, links) and reloads from the .glvl file like reloadlevel(); on a gmap object, every edited member. False for a createlevel level that was never saved — it has no file to return to.
gmaptolevel function
ts
declare function gmaptolevel(gmapName: string, gx: number, gy: number): { level: string; x: number; y: number } | nullConverts gmap-global tile coordinates to the member level under them and its member-local coordinates. Null when the gmap doesn't exist or (gx, gy) is outside its grid. On a gmap, player.x/y are already gmap-global, so gmaptolevel(player.level, player.x, player.y) tells you which member level a player is standing in. Direct call: reads live data.
leveltogmap function
ts
declare function leveltogmap(levelName: string, x: number, y: number): { gmap: string; x: number; y: number } | nullConverts member-level-local tile coordinates to gmap-global. Null when the level belongs to no gmap. Warps already auto-translate member destinations; use this when you need the numbers yourself. Direct call: reads live data.
ScriptThis interface
ts
interface ScriptThisEvery handler in a server script runs with this bound to the script's own object: this.name is the script's name (file name without .ts; a weapon's serverside half gets the bare weapon name, matching its clientside this.name). Scripts may stash extra state on this between calls. Only function declarations see it — arrow functions ignore this.
export is optional: every top-level function is exported by the build (so function onCreated() is a handler), and the script's own functions and joined class exports are callable on this too. Inside a top-level function this is always the script: a bare helper(...) call from a handler falls back to the running script's self instead of JS's undefined.
this types as any in handlers (noImplicitThis is off in tsconfig.json); annotate a handler with this: ScriptThis if you want it typed:
ts
export function onActionServerSide(this: ScriptThis, player: Player) { ... }ScriptThis.name
ts
name: stringThe script's name, e.g. "test" for test.ts or weapons/test.ts.
ScriptThis.join
ts
join(name: string): booleanJoins this script to a class (scripts/classes/<name>.ts): the class's exported handlers fire after this script's own, its exported helpers become callable on this, and its onCreated runs now with this script as this. A serverside join also joins the class's clientside half (<name>.client.ts, when one exists) on every client. Re-joining re-checks the class version and re-fires its onCreated. Returns false when the class doesn't exist.
ScriptThis.leave
ts
leave(name: string): booleanRemoves a joined class's handlers from this script.
ScriptThis.joinedclasses
ts
readonly joinedclasses: readonly string[]Currently joined class names, in join order.
ScriptThis.[key]
ts
[key: string]: anyScripts may keep arbitrary state on this.
serverOptions global
ts
declare const serverOptions: { … }The server's configuration from serveroptions.json (next to the server binary), available from onInitialized onward. Beyond the typed options below, every extra top-level key an admin adds to the file shows up here verbatim — e.g. a "motd": "..." line is read as serverOptions.motd. The object is deep-frozen; writes are silently ignored.
serverOptions.name
ts
readonly name: stringDisplay name of the server.
serverOptions.startLevel
ts
readonly startLevel: stringLevel new accounts start in; returning players resume their saved level.
serverOptions.startX
ts
readonly startX: numberStart position for new accounts, in tiles.
serverOptions.startY
ts
readonly startY: numberStart position for new accounts, in tiles.
serverOptions.maxPlayers
ts
readonly maxPlayers: numberMaximum simultaneous logged-in players; 0 or less means unlimited.
serverOptions.[key]
ts
readonly [key: string]: anyAdmin-defined custom properties.
server global
ts
declare const server: Record<string, any>Server-only global flags, persisted in data/flags.json across restarts. Values can be anything JSON-serializable (strings, numbers, booleans, arrays, plain objects); flag names are 1-128 characters, values up to 8192 characters of JSON. Assigning null or undefined deletes a flag, as does delete server.foo. Reads return a fresh copy per access — mutating a nested value does NOT store it; reassign to write:
ts
const inv = server.inventory ?? []; inv.push('sword');
server.inventory = inv;Direct calls (not batched): a write is readable back immediately. Never sent to clients — for server-visible state, see serverr.
serverr global
ts
declare const serverr: Record<string, any>Global flags mirrored to EVERY client, persisted in data/flags.json. Same value rules and reassign-to-write caveat as server. Each write (or delete) is broadcast immediately and readable in clientside scripts as serverr.foo (read-only there); clients also get the full set at login.
Player interface
ts
interface PlayerSnapshot of a player's state at the moment an event fired (backed by ScriptPlayer on the host side). chat is live rather than a snapshot: reads see the player's current chat bubble, and assigning it sets the bubble for everyone in their level (the player's own client included). client and clientr are the player's live flag bags.
Player.id
ts
id: numberServer-assigned player id, unique per login.
Player.account
ts
account: stringAccount name the player logged in with.
Player.nick
ts
nick: stringDisplay name rendered under the player, for everyone in their level. Defaults to the account name; players change it with the setnick chat command. Assigning '' resets it to the account name. Sanitized like chat and trimmed to 40 chars.
Player.nickcolor
ts
nickcolor: stringName tag text color as 'r,g,b' (default '255,255,255'), for everyone in the player's level. Only scripts can change it — there is no chat command — and it's saved in the account file. Invalid values are ignored.
ts
player.nickcolor = '255,215,0' // goldPlayer.nickshadow
ts
nickshadow: booleanWhether the name tag has a 1px drop shadow (default true). Script-only; saved in the account file.
Player.nickshadowcolor
ts
nickshadowcolor: stringName tag shadow color as 'r,g,b' (default '0,0,0'). Script-only; saved in the account file. Invalid values are ignored.
Player.level
ts
level: ServerLevel | nullThe level (or gmap) the player is in, as a level object — use player.level.name for the file name, player.level.putnpc(...) etc. to act on it. Null until they enter their first level. Inside an instance this is the instanced copy, but name is still the plain file name.
Player.instance
ts
readonly instance: Instance | nullThe instance the player is in, or null in the shared world. Live (not a snapshot): reflects the instance they're in right now.
Player.x
ts
x: numberPosition in tiles. Read-only in practice: move players with warpto.
Player.y
ts
y: numberPosition in tiles. Read-only in practice: move players with warpto.
Player.chat
ts
chat: stringChat bubble above the player's head. Assigning shows it to everyone in their level ('' clears it); it fades 5s after the player moves. Text is trimmed to 200 chars and control characters become spaces.
Player.setAni
ts
setAni(name: string, ...params: any[]): voidPlays a .gan animation on the player, visible to everyone in their level. Pass the animation name without the extension, e.g. player.setAni('sword'). Values after the name are the animation's params: PARAM sprites draw the image named at their (0-based) slot, and the gani script reads them as params, e.g. player.setAni('carry', 'pot.png'). At most 16 JSON-serializable values (2048 characters of JSON). Every call replaces the previous params.
Player.ani
ts
ani: stringCurrent animation name (without the .gan extension). Assigning plays it like setAni(name) with no params.
Player.aniParams
ts
readonly aniParams: readonly any[]The current animation's setAni params ([] when none). Read-only, deep-frozen.
Player.head
ts
head: stringHead image, e.g. 'head0.png'. '' means the client default.
Player.body
ts
body: stringBody image, e.g. 'body.png'. '' means the client default.
Player.colors
ts
colors: string[]Body colors as 'r,g,b' strings, recoloring the body's reserved key colors: [0] skin, [1] coat, [2] sleeves, [3] shoes, [4] belt. Always five entries. Assigning an index (player.colors[1] = '255,0,0') updates everyone in the level and persists; invalid indices or values are ignored. Assigning an array sets each slot it provides.
Player.hasright
ts
hasright(mode: 'r' | 'w' | 'rw', path: string): booleanWhether this player's staff rights grant folder access on a data/-relative path: mode 'r' (read), 'w' (write) or 'rw' (requires both), e.g. player.hasright('w', 'levels/town.glvl'). Staff-list accounts with no rights record have full access; everyone else without a record has none. Serverside only.
Player.hasstaffright
ts
hasstaffright(name: string): booleanWhether this player's staff rights include a named right from the rights catalog — e.g. player.hasstaffright('leveleditor') to gate an online level/NPC editor. Resolved like hasright: staff-list accounts with no rights record hold every right. Serverside only.
Player.warpto
ts
warpto(level: string, x: number, y: number, options?: WarpOptions): booleanWarps this player to a level (or gmap) at tile (x, y) — the same path link touches and RC warps take, so warps to a gmap member land on the gmap with translated coordinates. The client transitions once it has fully downloaded the destination. Serverside only; false when the level doesn't exist.
Instances: with no options (or no instance key) the warp inherits — it stays in the player's current instance when the level is one of its members and lands in the shared world otherwise (exactly like links). { instance: inst } warps into that instance (false when the level isn't one of its members or it was destroyed); { instance: null } always lands in the shared world.
Player.addWeapon
ts
addWeapon(name: string): booleanGrants a weapon (scripts/weapons/<name>) to this player; their client downloads and runs its clientside half immediately. No-op if they already have it. Serverside only; false when no such weapon exists.
Player.removeWeapon
ts
removeWeapon(name: string): booleanTakes a weapon away from this player; their client unloads it immediately. Serverside only; false (and a no-op) when they don't have it.
Player.hasWeapon
ts
hasWeapon(name: string): booleanWhether this player currently has the named weapon. (Clientside scripts have the same check on their local player.)
Player.client
ts
client: Record<string, any>Per-player flags, readable AND writable both here and in the player's clientside scripts (as client.foo there); persisted in the account file. Values must be JSON-serializable; names 1-128 chars, values up to 8192 chars of JSON. Assigning null/undefined (or delete) removes a flag. Server writes sync to the client immediately; reads return a fresh copy per access, so mutate-then-reassign nested values.
Player.clientr
ts
clientr: Record<string, any>Per-player flags only the server can write; the player's clientside scripts see them read-only (as clientr.foo). Persisted in the account file. Same value rules and reassign-to-write caveat as client.
Player.attr
ts
attr: Record<string, any>Player attributes: public per-player values only the server can write. Every client that can see this player — the player's own included — reads them (read-only) as .attr.foo on its player handles (player.attr, players[i].attr, findplayer(acc).attr), e.g. to draw a healthbar. Persisted in the account file. Names 1-128 chars, values up to 8192 chars of JSON, and at most 16384 chars per player in total (names + values). Assigning null/undefined (or delete) removes an attribute; assigning an unchanged value sends nothing. Each change is broadcast immediately, so mutate-then-reassign nested values and avoid writing every tick.
ts
player.attr.health = 100
player.attr.team = 'red'An ATTR sprite in the player's animation draws the image held by the attribute it names, so player.attr.hat = 'hat1.png' dresses every gani with an ATTR "hat" sprite (non-string values draw nothing).
A value naming a .gan attaches that gani's script to the player on every client that sees them, without changing their animation: a string ending in ".gan", or an array whose first element is one (the rest become the script's params array). Changing the value restarts the script; removing it stops it.
ts
player.attr.light = ['light.gan', 255, 0, 0] // params = [255, 0, 0]Event handlers. Scripts subscribe by exporting a function with the matching name; the server invokes it on every script that exports one:
export function onCreated(): void
Fired every time the script loads: at server startup and again on every hot reload (RC script update). Put (re)initialization here — including this.join() calls, which must be re-made after an update.export function onInitialized(): void
Fired once at server startup, after onCreated. NOT re-fired when the script is updated — use it for boot-only work.export function onPlayerJoined(player: Player): void
Fired when a player logs in to the server.export function onPlayerLeft(player: Player): void
Fired when a logged-in player disconnects from the server.export function onActionServerSide(player: Player, ...params: any[]): void
Fired when a client calls triggerServer targeting this script.playeris the triggering player; the client's params follow (JSON round-tripped). triggerClient inside answers that same player.export function onPlayerEntersInstance(player: Player, instance: Instance): void
Fired when a player enters an instance (arriving from the shared world or from another instance). triggerClient inside answers that player.export function onPlayerLeavesInstance(player: Player, instance: Instance): void
Fired when a player leaves an instance: a warp/link out, a warp into a different instance, a disconnect, or being evicted by destroy().export function onInstanceDestroyed(instance: Instance): void
Fired when an instance is destroyed (by script, RC, or destroyWhenEmpty), BEFORE its players are moved out and its NPCs unloaded — the shared state is still readable here, so save results now.
ServerLevel interface
ts
interface ServerLevel extends LevelEditorA reference to a specific level (or gmap) — what player.level and findlevel() return. Includes the LevelEditor methods. Same API shape as an NPC script's this.level, but bound to the named level-or-gmap context: on a gmap, all coordinates are gmap-global tiles. Snapshot semantics: taken when the event fired; a player kept across an await may have moved on.
ServerLevel.name
ts
readonly name: stringThe level's file name, e.g. "start.glvl" (or "world.gmap").
ServerLevel.players
ts
readonly players: Player[]Snapshots of the players in this level — on a gmap, everyone anywhere on it (gmap-global x/y). Full Player objects, client./clientr. flag bags included. A fresh array on every read.
ServerLevel.findPlayersCircle
ts
findPlayersCircle(x: number, y: number, radius: number): Player[]Players whose 2x2 body center (player.x + 1, player.y + 1) is within radius tiles of (x, y), nearest first. On a gmap the whole gmap is searched and (x, y) are gmap-global. Empty on bad arguments.
ServerLevel.findPlayersRect
ts
findPlayersRect(x: number, y: number, w: number, h: number): Player[]Players whose 2x2 body overlaps the rect [x, x+w) × [y, y+h), tile units (negative w/h extend left/up). On a gmap the whole gmap is searched and coordinates are gmap-global. Empty on bad arguments.
ServerLevel.findPath
ts
findPath(x1: number, y1: number, x2: number, y2: number, options?: FindPathOptions): PathPoint[] | nullA* path from (x1, y1) to (x2, y2) around blocking tiles and (by default) blocking NPCs — see FindPathOptions. Coordinates are floored to whole tiles and name the TOP-LEFT of the mover's footprint. Returns the turning points from start to goal (straight runs collapsed), or null when the goal is blocked, unreachable, or the search budget runs out. On a gmap paths cross member seams; coordinates are gmap-global.
ServerLevel.putnpc
ts
putnpc(x: number, y: number, serverScript: string, clientScript?: string): NpcThis | nullSpawns a LOCAL NPC at (x, y) in this level. The script arguments are inline TypeScript SOURCE strings (Graal putnpc2-style); the first compile of a novel script briefly blocks the server tick, identical sources are cached. Never saved to the level file: lives until destroy() or server restart, surviving hot reloads (/clearnpcs in RC clears strays). On a gmap, (x, y) are gmap-global and the NPC lands in the member level under them. Returns the NPC's full this-style handle, or null when the level can't be resolved.
ServerLevel.onwall
ts
onwall(x: number, y: number, w?: number, h?: number): booleanTrue when a blocking collision tile intersects [x, x+w) × [y, y+h), in tile units (fractions allowed). Omit w/h to test the single tile containing (x, y). Tiles outside the level count as blocked, and so do blocking NPCs (see NpcThis.dontblock); players don't.
ServerLevel.tiletype
ts
tiletype(x: number, y: number): numberCollision type of the tile containing (x, y); -1 when out of range.
ServerLevel.shoot
ts
shoot(x: number, y: number, gan: string, angle: number, speed: number,
lifetime: number, data?: any): Projectile | nullSpawns a projectile with its CENTER at (x, y) in this level's space — same semantics and arguments as the player-scoped level.shoot. Returns null on bad arguments.
PathPoint interface
ts
interface PathPointA waypoint returned by findPath: a whole-tile footprint top-left.
PathPoint.x
ts
x: numberTile x (the footprint's left edge).
PathPoint.y
ts
y: numberTile y (the footprint's top edge).
FindPathOptions interface
ts
interface FindPathOptionsOptions for findPath. Every cell the mover steps into is tested as a width x height rect anchored at the cell's top-left, like onwall. A player walking with the lower-body idiom uses { width: 2, height: 1 } with start/goal at (player.x, player.y + 1).
FindPathOptions.width
ts
width?: numberFootprint width in tiles (default 1, max 16).
FindPathOptions.height
ts
height?: numberFootprint height in tiles (default 1, max 16).
FindPathOptions.diagonal
ts
diagonal?: booleanAllow 8-directional steps (default true). Diagonals never cut wall corners.
FindPathOptions.npcs
ts
npcs?: booleanTreat blocking NPCs as walls (default true). Inside an NPC script the NPC itself never blocks its own path.
FindPathOptions.players
ts
players?: booleanTreat players' lower bodies (x, y+1, 2, 1) as walls (default false).
FindPathOptions.maxNodes
ts
maxNodes?: numberSearch budget: cells expanded before giving up and returning null (default 4000, max 20000). The search runs on the server tick, so keep long searches rare.
WarpOptions interface
ts
interface WarpOptionsOptions for {@link Player.warpto}.
WarpOptions.instance
ts
instance?: Instance | nullInstance destination: an Instance warps into it (the level must be a member), null lands in the shared world. Omitted = inherit (stay in the current instance when the level is a member, else shared world).
InstanceOptions interface
ts
interface InstanceOptionsOptions for {@link instances.create}.
InstanceOptions.name
ts
name: stringType label, 1-64 chars, e.g. 'goblin-cave'. Not unique: many instances can share a name. Shown by the RC /instances command and filterable with instances.list(name).
InstanceOptions.levels
ts
levels: string[]Member levels and gmaps: file names with optional * and ? wildcards, case-insensitive (e.g. ['cave_*.glvl', 'cave.gmap']). A gmap brings all of its member levels with it. Links and inheriting warps to a member stay inside the instance; links to anything else exit it.
InstanceOptions.exit
ts
exit?: { level: string, x: number, y: number }Where players go when the instance is destroyed (or when they log in after it's gone). Omitted = back to where each player entered it from.
InstanceOptions.destroyWhenEmpty
ts
destroyWhenEmpty?: numberAuto-destroy after the instance has been empty this many seconds (counted from creation until someone arrives, so leave time to warp players in). Omitted = persist until destroy() is called.
Instance interface
ts
interface InstanceA live instance: a private copy of a set of member levels/gmaps with its own NPCs, level state and players. Instances are memory-only — gone on server restart. Every property other than the built-ins below is shared state (like an NPC's this.level, but one bag for the WHOLE instance): inst.kills = 3 is readable as this.instance.kills by every NPC in every member level, and by any script holding the handle. Live JS values, never persisted; cleared when the instance is destroyed.
Instance.[key]
ts
[key: string]: anyShared instance state: any key that isn't a built-in.
Instance.id
ts
readonly id: stringUnique id, e.g. 'k3f9a2c1'. Stable for the instance's lifetime.
Instance.name
ts
readonly name: stringThe type label given to instances.create.
Instance.levels
ts
readonly levels: string[]The member patterns given to instances.create (a fresh copy per read).
Instance.players
ts
readonly players: Player[]Players in the instance (including any mid-warp into it).
Instance.alive
ts
readonly alive: booleanFalse once destroy() has started; the handle is inert afterwards.
Instance.destroy
ts
destroy(): booleanDestroys the instance: fires onInstanceDestroyed, warps everyone in it to their exit, unloads its NPCs (timers stop) and projectiles, and clears its state. Returns false when it was already destroyed.
instances global
ts
declare const instances: { … }Creates and finds instances — private, replayable copies of levels and gmaps (quests, dungeons, arenas). Serverside only.
ts
const inst = instances.create({ name: 'goblin-cave', levels: ['cave\_\*.glvl'], destroyWhenEmpty: 60 })
player.warpto('cave\_1.glvl', 30, 30, { instance: inst })instances.create
ts
create(options: InstanceOptions): InstanceCreates an instance (persisting until destroy() unless destroyWhenEmpty is set). Throws on an empty name, no member levels, or a non-positive destroyWhenEmpty.
instances.get
ts
get(id: string): Instance | nullA live instance by id, or null.
instances.list
ts
list(name?: string): Instance[]Live instances, oldest first — only those with this name when given.
Projectile interface
ts
interface ProjectileA live projectile spawned by level.shoot.
Projectile.id
ts
readonly id: numberUnique id for this server run.
Projectile.destroy
ts
destroy(): booleanRemoves the projectile mid-flight, silently: no onShotAt/onShot fires anywhere. Safe to call after it already stopped (returns false then).
level global
ts
declare const level: LevelEditor & {
/** The current player's level (or gmap) name; '' outside a player-scoped handler. */
readonly name: string
/**
* Players in the current player's level (on a gmap, anywhere on it, with
* gmap-global x/y), as full Player objects with client./clientr. bags.
* Empty outside a player-scoped handler.
*/
readonly players: Player[]
/**
* Players whose 2x2 body center is within `radius` tiles of (x, y) in the
* current player's coordinate space, nearest first — see
* ServerLevel.findPlayersCircle. Empty outside a player-scoped handler.
*/
findPlayersCircle(x: number, y: number, radius: number): Player[]
/**
* Players whose 2x2 body overlaps [x, x+w) × [y, y+h) in the current
* player's coordinate space — see ServerLevel.findPlayersRect. Empty
* outside a player-scoped handler.
*/
findPlayersRect(x: number, y: number, w: number, h: number): Player[]
/**
* A* path in the current player's level (gmap-global on gmaps) — see
* ServerLevel.findPath. Null outside a player-scoped handler.
*/
findPath(x1: number, y1: number, x2: number, y2: number, options?: FindPathOptions): PathPoint[] | null
/**
* Spawns a projectile with its CENTER at (x, y), in the current player's
* coordinate space: level tiles, or gmap-global tiles when they are on a
* gmap (where it crosses member seams). `gan` is the animation it renders
* (e.g. 'arrow'; the flight angle picks the gani direction). `angle` is
* radians, Graal-style: 0=right, PI/2=up, PI=left, 3*PI/2=down. `speed`
* is tiles/sec (max 100), `lifetime` seconds (max 60). `data` is any
* JSON-serializable payload, delivered to every callback.
*
* The projectile stops on the first blocking tile (onShotAt on clientside
* scripts and the level's serverside NPCs), on lifetime expiry (same), on
* an NPC shape (onShot(data) on that NPC, server + client) or on a player
* (onShot(data) on the HIT player's clientside weapon scripts). Returns
* null outside a player-scoped handler or on bad arguments.
*/
shoot(x: number, y: number, gan: string, angle: number, speed: number,
lifetime: number, data?: any): Projectile | null
/**
* Spawns a LOCAL NPC at (x, y) in the current player's coordinate space:
* level tiles, or gmap-global tiles when they are on a gmap (the NPC
* lands in the member level under the point; off-grid returns null). The
* script arguments are inline TypeScript SOURCE strings (Graal
* putnpc2-style), compiled like level NPC scripts — the first compile of
* a novel script briefly blocks the server tick; identical sources are
* cached.
*
* The NPC is never saved to the level file: it lives until destroy() or
* server restart, surviving level hot reloads (/clearnpcs <level> in RC
* clears strays). Returns the NPC's full `this`-style handle (see
* NpcThis) or null — like shoot, also null outside a player-scoped
* handler.
*/
putnpc(x: number, y: number, serverScript: string, clientScript?: string): NpcThis | null
}The CURRENT player's level. Like triggerClient, "current player" only exists synchronously inside a player-scoped handler (onActionServerSide, onPlayerJoined, ...) — after an await or inside timer callbacks there is none, and level.name is '' / level.shoot returns null.
NPC scripts: use this.level instead — it is the NPC's own level and also accepts member-local coordinates; this global is player-scoped. A bare level inside an NPC script is THIS global, not this.level.
SqlRow type
ts
type SqlRow = Record<string, number | string | null | { $blob: string }>A row returned by Database.query: column name -> value. SQLite INTEGERs arrive as JS numbers (values beyond 2^53 lose precision), REALs as numbers, TEXT as strings, NULL as null, and BLOBs wrapped as { $blob: base64 }. Duplicate column names collide in the object form — use AS aliases.
SqlParam type
ts
type SqlParam = number | string | boolean | nullA value bindable to a ? placeholder. Booleans store as SQLite's 1/0.
Database interface
ts
interface DatabaseA server-side SQLite database handle from opendatabase(). The database file is created lazily on the first query/exec. All SQL runs serialized on one server-wide worker thread; each statement is atomic (no cross-statement transaction API). Multi-statement SQL is allowed — all statements execute and the last result set with columns is returned.
Database.name
ts
readonly name: stringThe database name this handle was opened with.
Database.query
ts
query(sql: string, params?: SqlParam[]): Promise<SqlRow[]>Runs SQL and resolves with its rows. Parameters bind to bare ? placeholders in order.
Database.exec
ts
exec(sql: string, params?: SqlParam[]): Promise<{ rowsAffected: number; lastInsertRowId: number }>Runs SQL and resolves with change counts: rowsAffected (rows inserted/updated/deleted) and lastInsertRowId (this connection's most recent INSERT rowid).
opendatabase function
ts
declare function opendatabase(name: string): DatabaseOpens a named server-side SQLite database (data/databases/<name>.db), creating it on first use. Names: 1-64 chars of letters, digits, _ and -; an invalid name throws synchronously. Pending queries of an unloaded script park unresolved across a hot reload, like cancelled sleeps.
Headers class
ts
declare class Headers implements Iterable<[string, string]>A case-insensitive HTTP header list, as in the web Fetch API. Names are stored lower-cased; iteration yields [name, value] pairs sorted by name, and a repeated name's values are joined with ", ".
Headers.constructor
ts
constructor(init?: HeadersInit)Builds a header list from a name→value object, [name, value] pairs, or another Headers.
Headers.append
ts
append(name: string, value: string): voidAdds a value, joining it onto any existing value for that name with ", ".
Headers.set
ts
set(name: string, value: string): voidReplaces every value for that name.
Headers.get
ts
get(name: string): string | nullThe (joined) value for that name, or null when absent.
Headers.has
ts
has(name: string): booleanWhether the header is present.
Headers.delete
ts
delete(name: string): voidRemoves the header.
Headers.forEach
ts
forEach(cb: (value: string, name: string, headers: Headers) => void, thisArg?: unknown): voidCalls cb(value, name, headers) for every header, sorted by name.
Headers.entries
ts
entries(): IterableIterator<[string, string]>[name, value] pairs sorted by name.
Headers.keys
ts
keys(): IterableIterator<string>Header names (lower-cased), sorted.
Headers.values
ts
values(): IterableIterator<string>Header values, in name order.
Headers.[Symbol.iterator]
ts
[Symbol.iterator](): IterableIterator<[string, string]>Same as entries().
HeadersInit type
ts
type HeadersInit = Headers | Record<string, string> | [string, string][]Anything fetch() and new Headers() accept as headers.
FetchInit interface
ts
interface FetchInitOptions for fetch(). A subset of the web RequestInit plus a timeout.
FetchInit.method
ts
method?: stringHTTP method: GET (default), POST, PUT, PATCH, DELETE, HEAD or OPTIONS. Case-insensitive.
FetchInit.headers
ts
headers?: HeadersInitRequest headers. A body without a Content-Type is sent as text/plain;charset=UTF-8.
FetchInit.body
ts
body?: string | nullRequest body, sent as UTF-8 (max 4 MB). Strings only — use JSON.stringify(...) for JSON (and set Content-Type: application/json). GET and HEAD requests cannot have a body.
FetchInit.timeout
ts
timeout?: numberNon-standard: give up after this many milliseconds. Default 15000, max 60000.
Response interface
ts
interface ResponseThe response to a fetch(). The body is fully buffered before the promise resolves.
Response.status
ts
readonly status: numberHTTP status code.
Response.statusText
ts
readonly statusText: stringHTTP reason phrase, e.g. "OK" or "Not Found".
Response.ok
ts
readonly ok: booleanTrue for a 2xx status. fetch() still resolves for 4xx/5xx — check this.
Response.url
ts
readonly url: stringThe final URL, after any redirects.
Response.redirected
ts
readonly redirected: booleanWhether redirects were followed to reach url.
Response.headers
ts
readonly headers: HeadersResponse headers.
Response.bodyUsed
ts
readonly bodyUsed: booleanWhether text()/json()/arrayBuffer() has been called; the body can only be read once.
Response.text
ts
text(): Promise<string>The body as text (decoded with the response charset, UTF-8 by default).
Response.json
ts
json(): Promise<any>The body parsed as JSON; rejects on invalid JSON.
Response.arrayBuffer
ts
arrayBuffer(): Promise<ArrayBuffer>The raw body bytes.
fetch function
ts
declare function fetch(input: string | { url: string }, init?: FetchInit): Promise<Response>Makes an outbound HTTP(S) request, like the web Fetch API. The request runs off the server tick, so awaiting it never stalls the game; the promise settles on a later tick. It resolves for any HTTP status (check res.ok) and rejects with a TypeError on network errors, timeouts, an invalid URL/method, or a blocked address.
Limits: http/https only; 15 s default timeout (init.timeout, max 60 s); 4 MB request and response bodies; at most 5 redirects; 16 requests in flight server-wide (more queue, beyond 256 they reject). Loopback, private, link-local and other reserved addresses are refused unless serveroptions.json sets fetchAllowPrivate. No streaming and no AbortSignal. Pending fetches of an unloaded script park unresolved across a hot reload, like cancelled sleeps.
WebSocketOptions interface
ts
interface WebSocketOptionsNon-standard extra options for new WebSocket().
WebSocketOptions.headers
ts
headers?: HeadersInitExtra HTTP headers for the opening handshake, for services that authenticate it (browsers can't send these; Discord's gateway doesn't need any). Handshake-reserved headers (Upgrade, Sec-WebSocket-*) throw.
WebSocketEvent interface
ts
interface WebSocketEventThe event passed to WebSocket open and error handlers.
WebSocketEvent.type
ts
readonly type: string"open" or "error".
WebSocketEvent.target
ts
readonly target: WebSocketThe socket the event is for.
WebSocketEvent.message
ts
readonly message?: stringNon-standard, error events only: why the connection failed.
WebSocketMessageEvent interface
ts
interface WebSocketMessageEventThe event passed to WebSocket message handlers.
WebSocketMessageEvent.type
ts
readonly type: 'message'Always "message".
WebSocketMessageEvent.target
ts
readonly target: WebSocketThe socket the message arrived on.
WebSocketMessageEvent.data
ts
readonly data: string | ArrayBufferA text frame's string, or a binary frame's bytes.
WebSocketCloseEvent interface
ts
interface WebSocketCloseEventThe event passed to WebSocket close handlers. Always the socket's last event.
WebSocketCloseEvent.type
ts
readonly type: 'close'Always "close".
WebSocketCloseEvent.target
ts
readonly target: WebSocketThe socket that closed.
WebSocketCloseEvent.code
ts
readonly code: numberThe close code: the peer's code on a clean close, 1005 if it sent none, 1006 when the connection failed or dropped, 1009 when an incoming message exceeded 16 MB.
WebSocketCloseEvent.reason
ts
readonly reason: stringThe peer's close reason ("" if none).
WebSocketCloseEvent.wasClean
ts
readonly wasClean: booleanWhether the closing handshake completed.
WebSocket class
ts
declare class WebSocketAn outbound WebSocket connection, like the browser WebSocket class. Connecting, sending and receiving run off the server tick; handlers fire on a later tick in the context of the script that created the socket. Every socket ends with exactly one close event (preceded by an error event when the connection failed).
The socket belongs to the script that constructed it: unloading or hot-reloading that script aborts it silently (no close event), so (re)connect from onCreated. Limits: ws/wss only; 32 open sockets server-wide; 16 MB per incoming message and 16 MB of unsent data (beyond it the socket fails). The same private-address policy as fetch applies (fetchAllowPrivate). No permessage-deflate compression.
WebSocket.CONNECTING
ts
static readonly CONNECTING: 0readyState: connecting.
WebSocket.OPEN
ts
static readonly OPEN: 1readyState: open — send() works.
WebSocket.CLOSING
ts
static readonly CLOSING: 2readyState: close() called, waiting for the closing handshake.
WebSocket.CLOSED
ts
static readonly CLOSED: 3readyState: closed; the socket is finished.
WebSocket.constructor
ts
constructor(url: string, protocols?: string | string[], options?: WebSocketOptions)Starts connecting to a ws:// or wss:// URL. Throws a SyntaxError for an invalid URL, subprotocol or header, or when 32 sockets are already open. @param protocols subprotocols to offer; the server's pick lands in protocol.
WebSocket.url
ts
readonly url: stringThe URL passed to the constructor.
WebSocket.readyState
ts
readonly readyState: number0 connecting, 1 open, 2 closing, 3 closed — compare with WebSocket.OPEN etc.
WebSocket.protocol
ts
readonly protocol: stringThe subprotocol the server selected ("" if none), set once open.
WebSocket.extensions
ts
readonly extensions: stringAlways "" (no extensions are negotiated).
WebSocket.bufferedAmount
ts
readonly bufferedAmount: numberBytes queued by send() that haven't reached the network yet.
WebSocket.binaryType
ts
binaryType: 'arraybuffer'Binary messages always arrive as ArrayBuffer; assigning anything else throws.
WebSocket.onopen
ts
onopen: ((event: WebSocketEvent) => void) | nullFires once the connection is established.
WebSocket.onmessage
ts
onmessage: ((event: WebSocketMessageEvent) => void) | nullFires for each complete incoming message.
WebSocket.onerror
ts
onerror: ((event: WebSocketEvent) => void) | nullFires when the connection fails (just before close); event.message says why.
WebSocket.onclose
ts
onclose: ((event: WebSocketCloseEvent) => void) | nullFires once when the socket is finished, cleanly or not.
WebSocket.send
ts
send(data: string | ArrayBuffer | ArrayBufferView): voidQueues a message: a string is sent as a text frame, an ArrayBuffer or typed array as a binary frame. Throws an InvalidStateError while still connecting; ignored once closing or closed.
WebSocket.close
ts
close(code?: number, reason?: string): voidStarts the closing handshake after already-queued messages. code must be 1000 (default) or 3000-4999 and reason at most 123 UTF-8 bytes, else it throws. A server that doesn't answer within 5 s gets dropped (unclean close).
WebSocket.addEventListener
ts
addEventListener(type: 'open' | 'error', listener: (event: WebSocketEvent) => void, options?: { once?: boolean }): void
addEventListener(type: 'message', listener: (event: WebSocketMessageEvent) => void, options?: { once?: boolean }): void
addEventListener(type: 'close', listener: (event: WebSocketCloseEvent) => void, options?: { once?: boolean }): voidAdds a listener; once removes it after the first call.
WebSocket.removeEventListener
ts
removeEventListener(type: 'open' | 'message' | 'error' | 'close', listener: (event: any) => void): voidRemoves a listener added with addEventListener.
FileErrorCode type
ts
type FileErrorCode = 'ENOENT' | 'EEXIST' | 'EACCES' | 'EISDIR' | 'ENOTDIR' | 'ENOTEMPTY' | 'EINVAL' | 'EFBIG' | 'EIO'Why a files call failed, Node-style: ENOENT (no such file/folder), EEXIST (target exists and overwrite wasn't set), EACCES (protected or read-only path), EISDIR / ENOTDIR (folder where a file was expected, or the reverse), ENOTEMPTY (folder delete without recursive), EINVAL (bad path, bad argument or invalid JSON), EFBIG (over the 16 MB file or 10,000-entry listing limit), EIO (any other disk error).
FileError interface
ts
interface FileError extends ErrorThe Error a rejected files call rejects with: a message plus its code.
FileError.code
ts
code: FileErrorCodeWhat went wrong — branch on this, not the message.
FileStat interface
ts
interface FileStatOne file or folder, from files.stat() or files.list().
FileStat.name
ts
name: stringThe bare name, e.g. 'shop.json'.
FileStat.path
ts
path: stringThe data/-relative path with forward slashes, e.g. 'config/shop.json'.
FileStat.isDirectory
ts
isDirectory: booleanTrue for folders.
FileStat.size
ts
size: numberSize in bytes (0 for folders).
FileStat.modified
ts
modified: numberLast modification time, in milliseconds since the Unix epoch.
files global
ts
declare const files: { … }Reads and writes files in the server's data folder — the same tree the GRC File Browser shows. Paths are relative to it with forward slashes ('config/shop.json'); '..' can't climb out, and symbolic links are refused. Engine-owned folders are protected: accounts/, databases/ and the compile caches can't be touched at all (they're also hidden from list()), while scripts/, flags.json and collections.json are read-only.
Every call is async and runs on one server-wide background worker, so a script's operations complete in the order it issued them and never stall the game loop. Failures reject with a {@link FileError}. Single reads and writes are capped at 16 MB. Writing a level file hot-reloads it for players inside, exactly like saving it from GRC. Pending calls of an unloaded script park unresolved across a hot reload, like cancelled sleeps.
files.readText
ts
readText(path: string): Promise<string>Reads a UTF-8 text file (a leading byte-order mark is dropped).
files.writeText
ts
writeText(path: string, text: string): Promise<void>Writes a UTF-8 text file, replacing it if present and creating missing parent folders. The replace is atomic: readers see the old or the new contents, never half a file.
files.appendText
ts
appendText(path: string, text: string): Promise<void>Appends text to a file, creating it (and its parent folders) if missing — handy for logs.
files.readJson
ts
readJson<T = any>(path: string): Promise<T>Reads and parses a JSON file. Invalid JSON rejects with code EINVAL.
files.writeJson
ts
writeJson(path: string, value: any, indent?: number): Promise<void>Writes a value as JSON (pretty-printed with indent spaces, default 2; pass 0 for compact), atomically like writeText.
files.readBytes
ts
readBytes(path: string): Promise<Uint8Array>Reads a file's raw bytes.
files.writeBytes
ts
writeBytes(path: string, data: Uint8Array | ArrayBuffer): Promise<void>Writes raw bytes, atomically like writeText.
files.exists
ts
exists(path: string): Promise<boolean>Whether a file or folder exists. Protected paths still reject with EACCES.
files.stat
ts
stat(path: string): Promise<FileStat>Details of one file or folder; rejects with ENOENT when missing.
files.list
ts
list(path?: string, options?: { recursive?: boolean }): Promise<FileStat[]>A folder's entries sorted by path — the data folder itself when path is omitted. With recursive, every file and folder beneath it. Protected folders and symbolic links are left out.
files.mkdir
ts
mkdir(path: string): Promise<void>Creates a folder and any missing parents. Already existing is fine.
files.delete
ts
delete(path: string, options?: { recursive?: boolean }): Promise<void>Deletes a file or folder. A folder that isn't empty needs { recursive: true }, which deletes everything inside it.
files.rename
ts
rename(from: string, to: string, options?: { overwrite?: boolean }): Promise<void>Moves or renames a file or folder, creating the target's parent folders. An existing target file rejects with EEXIST unless { overwrite: true }; an existing target folder always does.
files.copy
ts
copy(from: string, to: string, options?: { overwrite?: boolean }): Promise<void>Copies a file (folders aren't supported). An existing target rejects with EEXIST unless { overwrite: true }.
CollectionQueryRow interface
ts
interface CollectionQueryRowA record's replicated query() result row.
CollectionQueryRow.key
ts
key: stringCollectionQueryRow.record
ts
record: anyCollectionBag interface
ts
interface CollectionBagOne scope's records of a collection: key → JSON value. Reads and writes are synchronous against server memory; changes are delta-synced to the audience once per tick and persisted in the background. Record keys are 1-128 chars, record values up to 64 KB of JSON. Collections flagged read-only in RC's Collections tool reject set/patch/delete with a throw — their records are edited in RC (item catalogs); reads and query() still work. A collection may also carry a record SCHEMA (defined in RC): writes must then be objects with every required field present, matching types, and no fields outside the schema — violations throw with a precise message (patch is judged by the record it produces, not the fields passed).
CollectionBag.get
ts
get(key: string): anyThe record's parsed value, or undefined. Returns a fresh copy — reassign via set/patch to write.
CollectionBag.keys
ts
keys(): string[]All record keys, sorted.
CollectionBag.set
ts
set(key: string, value: any): voidStores a record (whole-value replacement).
CollectionBag.patch
ts
patch(key: string, fields: Record<string, any>): voidShallow-merges fields into the record — a targeted server-side op with no read-modify-write race. Patching a missing (or non-object) record replaces it wholesale.
CollectionBag.delete
ts
delete(key: string): voidRemoves a record. Removing a missing key is a no-op.
CollectionBag.query
ts
query(opts?: { where?: string; params?: SqlParam[]; limit?: number; offset?: number }):
Promise<CollectionQueryRow[]>Paged SELECT against the collection's table (sql backing only). where addresses record fields by (dotted) name — 'itemId = ?' or 'ench.level > ?' — with params bound to ? in order. Default limit 100, max 1000. Pending writes flush first, so the query sees them.
Collection interface
ts
interface Collection extends CollectionBagA collection handle. Global collections expose the record methods directly; account/level/group collections require .for(target) to pick the scope. The handle is stateless and resolves at use time.
Collection.name
ts
readonly name: stringCollection.for
ts
for(target: Player | string): CollectionBagOne scope's record set. The target depends on the collection's scope axis: a Player or bare account name (account — works for offline accounts), a member-level name (level), or a group id string (group).
Collection.subscribe
ts
subscribe(player: Player, scope?: string): voidDelivers a replica to an online player: for LAZY owner/all collections ("nothing ships until a script subscribes"), and for GROUP collections of either timing — there, subscription IS membership, so this is how a player joins a guild/party/trade audience. scope is required for group collections and must be omitted otherwise. Idempotent. The delivery is a snapshot, or a cheap catch-up when the client still has a cached copy. Throws for eager owner/all (delivered at login), level replicas (managed by level presence), audience 'none', and replicate 'cache' (clients pull records per-key with the clientside fetch()).
Collection.unsubscribe
ts
unsubscribe(player: Player, scope?: string): voidRevokes a subscribed replica: the client's mirror empties (its cached copy is kept for a later catch-up). No-op when not subscribed.
collection function
ts
declare function collection(name: string): CollectionA stateless handle on a collection: a server-authoritative, delta-synced, keyed record store. Collections are DEFINED BY STAFF in RC's Collections tool (persisted in data/collections.json, loaded at boot) — scripts can read and write records but deliberately cannot create collections or change their scope/audience/backing. Using an undefined collection throws at the call site, not here.
WeaponHandle interface
ts
interface WeaponHandleA handle on another loaded weapon script, from findweapon().
WeaponHandle.name
ts
readonly name: stringThe weapon's bare name, e.g. "gun".
WeaponHandle.trigger
ts
trigger(event: string, ...params: any[]): booleanInvokes the named exported handler on that script RIGHT NOW (its own export, then any joined classes), with this bound to that script and the params passed as live values — a Player object arrives intact, no JSON round trip. The triggerClient player context is inherited. Returns false when the script has since unloaded or its handler threw (the error is logged); true otherwise, including when it exports no such handler.
findweapon function
ts
declare function findweapon(name: string): WeaponHandle | nullFinds the LOADED serverside half of a weapon (scripts/weapons/<name>.ts) so one script can call into another — the item system uses it to deliver onEquipped / onUnequipped / onItemUsed to an item's weapon script:
ts
findweapon('gun')?.trigger('onEquipped', player, entry)null when no such weapon script is loaded. Names never contain '/'.
findWeapon function
ts
declare function findWeapon(name: string): WeaponHandle | nullAlias of findweapon.
GRC plugins (rcplugins)
RcWidgetBase interface
ts
interface RcWidgetBaseProps every plugin widget accepts.
RcWidgetBase.id
ts
id?: stringNames the widget so the script can patch it (win.patch), read its value (win.values) and receive its events (win.on). Unique within a window.
RcWidgetBase.disabled
ts
disabled?: booleanGreys the widget out; buttons and inputs stop accepting input.
RcWidgetBase.hidden
ts
hidden?: booleanLeaves the widget out of the layout entirely.
RcWidgetBase.flex
ts
flex?: numberFlex grow factor inside a row/column (e.g. 1 to take the free space).
RcWidgetBase.width
ts
width?: number | stringFixed width: pixels, or a CSS length like '40%'.
RcWidgetBase.height
ts
height?: number | stringFixed height: pixels, or a CSS length.
RcWidgetBase.tooltip
ts
tooltip?: stringText shown when hovering the widget.
RcWidgetBase.title
ts
title?: stringA tab's label when this widget is a direct child of a tabs widget.
RcStackWidget interface
ts
interface RcStackWidget extends RcWidgetBaseLays its children out vertically ('column') or horizontally ('row', wraps when narrow).
RcStackWidget.type
ts
type: 'column' | 'row'RcStackWidget.children
ts
children?: RcWidget[]RcStackWidget.gap
ts
gap?: numberSpace between children in pixels (default 8).
RcStackWidget.padding
ts
padding?: numberInner padding in pixels.
RcStackWidget.align
ts
align?: 'start' | 'center' | 'end' | 'stretch'Cross-axis alignment of the children.
RcStackWidget.scroll
ts
scroll?: booleanScrolls when the children don't fit.
RcSplitWidget interface
ts
interface RcSplitWidget extends RcWidgetBaseTwo panes with a draggable divider between them. Only the first two children are shown.
RcSplitWidget.type
ts
type: 'split'RcSplitWidget.children
ts
children?: RcWidget[]RcSplitWidget.direction
ts
direction?: 'horizontal' | 'vertical''horizontal' (default) puts the panes side by side; 'vertical' stacks them.
RcSplitWidget.size
ts
size?: number | stringThe first pane's starting size: pixels, or a CSS length (default '40%').
RcTabsWidget interface
ts
interface RcTabsWidget extends RcWidgetBaseA tab strip: each child is one tab, labelled by its title. Fires 'tab' when the staff member switches.
RcTabsWidget.type
ts
type: 'tabs'RcTabsWidget.children
ts
children?: RcWidget[]RcTabsWidget.selected
ts
selected?: numberThe tab to show (0-based). Patch it to switch tabs from the script.
RcGroupWidget interface
ts
interface RcGroupWidget extends RcWidgetBaseA titled box around its children (stacked vertically).
RcGroupWidget.type
ts
type: 'group'RcGroupWidget.title
ts
title?: stringRcGroupWidget.children
ts
children?: RcWidget[]RcHeadingWidget interface
ts
interface RcHeadingWidget extends RcWidgetBaseA heading line.
RcHeadingWidget.type
ts
type: 'heading'RcHeadingWidget.text
ts
text: stringRcHeadingWidget.level
ts
level?: 1 | 2 | 31 (largest) to 3; default 2.
RcTextWidget interface
ts
interface RcTextWidget extends RcWidgetBasePlain text. Newlines are kept; staff can select and copy it.
RcTextWidget.type
ts
type: 'text'RcTextWidget.text
ts
text: stringRcTextWidget.muted
ts
muted?: booleanDimmed, for hints and secondary information.
RcTextWidget.monospace
ts
monospace?: booleanMonospaced, for ids, paths and code.
RcSeparatorWidget interface
ts
interface RcSeparatorWidget extends RcWidgetBaseA horizontal rule.
RcSeparatorWidget.type
ts
type: 'separator'RcButtonWidget interface
ts
interface RcButtonWidget extends RcWidgetBaseA button. Fires 'click' (it needs an id to be clickable).
RcButtonWidget.type
ts
type: 'button'RcButtonWidget.text
ts
text: stringRcButtonWidget.variant
ts
variant?: 'default' | 'primary' | 'danger''primary' for the main action, 'danger' for destructive ones.
RcInputWidget interface
ts
interface RcInputWidget extends RcWidgetBaseA single-line input. Its value is a string, or a number (null when empty) for inputType 'number'. Fires 'change'; Enter inside a form fires the form's 'submit'.
RcInputWidget.type
ts
type: 'input'RcInputWidget.inputType
ts
inputType?: 'text' | 'number' | 'password''text' (default), 'number' or 'password'.
RcInputWidget.label
ts
label?: stringLabel shown above the input.
RcInputWidget.value
ts
value?: string | number | nullLabel shown above the input.
RcInputWidget.placeholder
ts
placeholder?: stringLabel shown above the input.
RcInputWidget.readonly
ts
readonly?: booleanShows the value but blocks editing.
RcInputWidget.min
ts
min?: numberBounds and step for inputType 'number'.
RcInputWidget.max
ts
max?: numberUpper bound for inputType 'number'.
RcInputWidget.step
ts
step?: numberStep for inputType 'number'.
RcTextAreaWidget interface
ts
interface RcTextAreaWidget extends RcWidgetBaseA multi-line text input (string value). Fires 'change'.
RcTextAreaWidget.type
ts
type: 'textarea'RcTextAreaWidget.label
ts
label?: stringRcTextAreaWidget.value
ts
value?: stringRcTextAreaWidget.placeholder
ts
placeholder?: stringRcTextAreaWidget.rows
ts
rows?: numberVisible lines (default 4).
RcTextAreaWidget.readonly
ts
readonly?: booleanVisible lines (default 4).
RcCheckboxWidget interface
ts
interface RcCheckboxWidget extends RcWidgetBaseA checkbox (boolean value). Fires 'change'.
RcCheckboxWidget.type
ts
type: 'checkbox'RcCheckboxWidget.label
ts
label?: stringRcCheckboxWidget.value
ts
value?: booleanRcCheckboxWidget.readonly
ts
readonly?: booleanRcSelectOption type
ts
type RcSelectOption = string | { value: string; label?: string }One select choice: a plain string, or a value with a different display label.
RcSelectWidget interface
ts
interface RcSelectWidget extends RcWidgetBaseA dropdown (string value: the chosen option's value; defaults to the first option). Fires 'change'.
RcSelectWidget.type
ts
type: 'select'RcSelectWidget.label
ts
label?: stringRcSelectWidget.options
ts
options: RcSelectOption[]RcSelectWidget.value
ts
value?: stringRcSelectWidget.readonly
ts
readonly?: booleanRcCodeWidget interface
ts
interface RcCodeWidget extends RcWidgetBaseA code editor (GRC's Monaco editor, string value). Fires 'change'.
RcCodeWidget.type
ts
type: 'code'RcCodeWidget.label
ts
label?: stringRcCodeWidget.value
ts
value?: stringRcCodeWidget.language
ts
language?: stringMonaco language id: 'json', 'typescript', 'sql', 'plaintext' (default)...
RcCodeWidget.readonly
ts
readonly?: booleanMonaco language id: 'json', 'typescript', 'sql', 'plaintext' (default)...
RcImageSource type
ts
type RcImageSource = string | { src: string; rect?: string | [number, number, number, number] }An image to show: an asset name resolved like a game client's request ('items.png', 'icons/sword.png'), or a data:image/... URL. The object form crops it to rect — 'left,top,width,height' or [left, top, width, height] in source pixels — e.g. one icon from a sheet, like an item's imagerect.
RcImageWidget interface
ts
interface RcImageWidget extends RcWidgetBaseAn image, or a rect of one. Plugin windows can show any image the game serves to players, whatever the staff member's folder rights; names the server doesn't host fall back to the Login Server's default assets. Up to about 960 KB per image. With an id, clicking it fires 'click' with the point in source pixels ({@link RcPluginImageClickEvent}) — handy for picking an icon from a sheet.
RcImageWidget.type
ts
type: 'image'RcImageWidget.src
ts
src: stringAsset name or data:image URL.
RcImageWidget.rect
ts
rect?: string | [number, number, number, number]Crop: 'left,top,width,height' or [left, top, width, height] in source pixels.
RcImageWidget.scale
ts
scale?: numberZoom when width/height aren't given (default 1). With width and/or height (pixels), the image is fitted inside them, keeping its aspect.
RcImageWidget.smooth
ts
smooth?: booleanSmooth scaling. Default off: pixel art stays crisp when zoomed.
RcTableColumn type
ts
type RcTableColumn = string | { key: string; title?: string; width?: number | string; image?: boolean | number }A table column: a row key, with an optional header and width. A bare string is the key and header. With image, the cells hold {@link RcImageSource}s drawn as thumbnails (true = 24 px tall, or a height).
RcTableWidget interface
ts
interface RcTableWidget extends RcWidgetBaseA table of rows (plain objects). Clicking a row selects it and fires 'select'; double-clicking fires 'activate' — both with the row and its index.
RcTableWidget.type
ts
type: 'table'RcTableWidget.columns
ts
columns?: RcTableColumn[]Which row keys to show, in order. Omitted: every key of the first row.
RcTableWidget.rows
ts
rows: Record<string, any>[]Which row keys to show, in order. Omitted: every key of the first row.
RcTableWidget.selectable
ts
selectable?: booleanRows can be selected (default true).
RcTableWidget.selected
ts
selected?: numberThe highlighted row index (-1 for none). Patch it to select from the script.
RcTableWidget.empty
ts
empty?: stringText shown when there are no rows.
RcListItem type
ts
type RcListItem = string | { value?: string; label: string; detail?: string; icon?: RcImageSource }One list entry: a plain string, or a label with an optional value, right-aligned detail and icon.
RcListWidget interface
ts
interface RcListWidget extends RcWidgetBaseA clickable list. Fires 'select' and 'activate' (double-click) with the item and its index.
RcListWidget.type
ts
type: 'list'RcListWidget.items
ts
items: RcListItem[]RcListWidget.selected
ts
selected?: numberThe highlighted item index (-1 for none).
RcListWidget.empty
ts
empty?: stringText shown when the list is empty.
RcListWidget.iconSize
ts
iconSize?: numberHeight of item icons in pixels (default 20).
RcFormField interface
ts
interface RcFormFieldOne field of a form widget. Fields are inputs in their own right: their id keys their value in win.values(), and they fire 'change' like the standalone inputs (as the field's own id). They can be patched by id too.
RcFormField.id
ts
id: stringRcFormField.type
ts
type?: 'text' | 'number' | 'password' | 'textarea' | 'checkbox' | 'select'The input kind (default 'text').
RcFormField.label
ts
label?: stringThe label left of the input (default: the id).
RcFormField.value
ts
value?: string | number | boolean | nullThe label left of the input (default: the id).
RcFormField.placeholder
ts
placeholder?: stringThe label left of the input (default: the id).
RcFormField.options
ts
options?: RcSelectOption[]Choices for type 'select'.
RcFormField.disabled
ts
disabled?: booleanChoices for type 'select'.
RcFormField.readonly
ts
readonly?: booleanChoices for type 'select'.
RcFormField.hidden
ts
hidden?: booleanChoices for type 'select'.
RcFormField.min
ts
min?: numberNumber bounds and step.
RcFormField.max
ts
max?: numberUpper bound for type 'number'.
RcFormField.step
ts
step?: numberStep for type 'number'.
RcFormField.rows
ts
rows?: numberVisible lines for type 'textarea'.
RcFormWidget interface
ts
interface RcFormWidget extends RcWidgetBaseLabelled fields in a two-column grid — the quick way to build an editor. Enter in a field fires the form's 'submit'. win.values(formId) returns { fieldId: value } for its fields; patch { values: {...} } fills them in.
RcFormWidget.type
ts
type: 'form'RcFormWidget.fields
ts
fields: RcFormField[]RcFormWidget.values
ts
values?: Record<string, any>Field values by field id (overrides each field's own value).
RcWidget type
ts
type RcWidget =
| RcStackWidget | RcSplitWidget | RcTabsWidget | RcGroupWidget
| RcHeadingWidget | RcTextWidget | RcSeparatorWidget | RcButtonWidget
| RcInputWidget | RcTextAreaWidget | RcCheckboxWidget | RcSelectWidget | RcCodeWidget
| RcTableWidget | RcListWidget | RcFormWidget | RcImageWidgetAny plugin widget — the shape win.set() and win.patch(id, { children }) take.
RcPluginEvent interface
ts
interface RcPluginEventWhat every plugin event handler receives.
RcPluginEvent.type
ts
type: stringThe event name ('click', 'change', ...).
RcPluginEvent.widget
ts
widget: stringThe id of the widget (or form field) that fired it.
RcPluginEvent.values
ts
values: Record<string, any>Every input value in the window at the time of the event (same as win.values()).
RcPluginChangeEvent interface
ts
interface RcPluginChangeEvent extends RcPluginEventA 'change' event: an input's new value. Text inputs report after a short typing pause.
RcPluginChangeEvent.value
ts
value: anyRcPluginSelectEvent interface
ts
interface RcPluginSelectEvent extends RcPluginEventA table or list 'select' / 'activate' event.
RcPluginSelectEvent.index
ts
index: numberThe row or item's position.
RcPluginSelectEvent.row
ts
row?: Record<string, any>The table row object (tables only).
RcPluginSelectEvent.item
ts
item?: RcListItemThe list item (lists only).
RcPluginImageClickEvent interface
ts
interface RcPluginImageClickEvent extends RcPluginEventA 'click' on an image widget: the point clicked, in source-image pixels (rect offset included).
RcPluginImageClickEvent.x
ts
x: numberRcPluginImageClickEvent.y
ts
y: numberRcPluginTabEvent interface
ts
interface RcPluginTabEvent extends RcPluginEventA tabs widget's 'tab' event.
RcPluginTabEvent.index
ts
index: numberRcPluginTabEvent.title
ts
title: stringRcStaff interface
ts
interface RcStaffThe staff member a plugin window belongs to.
RcStaff.account
ts
readonly account: stringTheir account name.
RcStaff.hasRight
ts
hasRight(name: string): booleanWhether they hold a named staff right (catalog or plugin-declared), checked live.
RcStaff.hasFolderRight
ts
hasFolderRight(mode: 'r' | 'w' | 'rw', path: string): booleanWhether their folder rights grant 'r', 'w' or 'rw' on a data/-relative file path.
RcDialogOptions interface
ts
interface RcDialogOptionsOptions for win.confirm().
RcDialogOptions.title
ts
title?: stringDialog heading.
RcDialogOptions.okText
ts
okText?: stringOK button text (default 'OK').
RcDialogOptions.cancelText
ts
cancelText?: stringCancel button text (default 'Cancel').
RcPromptOptions interface
ts
interface RcPromptOptions extends RcDialogOptionsOptions for win.prompt().
RcPromptOptions.value
ts
value?: stringThe text the input starts with.
RcPromptOptions.placeholder
ts
placeholder?: stringHint shown in the empty input.
RcPluginWindow interface
ts
interface RcPluginWindowOne open plugin window in a staff member's GRC. Everything the window shows comes from win.set / win.patch; every interaction arrives through win.on handlers. Calls after the window closed are ignored.
RcPluginWindow.id
ts
readonly id: numberA server-unique id for this window, e.g. to key per-window state in a Map.
RcPluginWindow.pluginId
ts
readonly pluginId: stringThe plugin's id.
RcPluginWindow.isOpen
ts
readonly isOpen: booleanFalse once the staff member (or the script) closed it, or they disconnected.
RcPluginWindow.staff
ts
readonly staff: RcStaffWho the window belongs to.
RcPluginWindow.set
ts
set(root: RcWidget): voidReplaces the whole widget tree (and resets every input to the values in it).
RcPluginWindow.patch
ts
patch(id: string, props: Record<string, any>): voidMerges props into one widget or form field by id: new rows for a table, { disabled: true }, { text: 'Saved' }, { value: 3 } for an input, { values: {...} } for a form, { children: [...] } for a container.
RcPluginWindow.values
ts
values(): Record<string, any>
values(id: string): anyInput values by widget id. With an id: that input's value, or for a form/container an object of the input values inside it.
RcPluginWindow.on
ts
on(event: 'click', id: string, handler: (e: RcPluginEvent & Partial<RcPluginImageClickEvent>) => void | Promise<void>): RcPluginWindow
on(event: 'change', id: string, handler: (e: RcPluginChangeEvent) => void | Promise<void>): RcPluginWindow
on(event: 'select' | 'activate', id: string, handler: (e: RcPluginSelectEvent) => void | Promise<void>): RcPluginWindow
on(event: 'submit', id: string, handler: (e: RcPluginEvent) => void | Promise<void>): RcPluginWindow
on(event: 'tab', id: string, handler: (e: RcPluginTabEvent) => void | Promise<void>): RcPluginWindowRuns when a button is clicked, or an image (with x/y: see RcPluginImageClickEvent).
RcPluginWindow.off
ts
off(event: string, id: string, handler?: Function): RcPluginWindowRemoves one handler, or every handler for that event and widget.
RcPluginWindow.toast
ts
toast(message: string, kind?: 'info' | 'success' | 'warning' | 'error'): voidShows a short notification in the corner of the window.
RcPluginWindow.setTitle
ts
setTitle(title: string): voidChanges the window title.
RcPluginWindow.confirm
ts
confirm(message: string, options?: RcDialogOptions): Promise<boolean>Asks a yes/no question; resolves true for OK, false for Cancel or a closed window.
RcPluginWindow.prompt
ts
prompt(message: string, options?: RcPromptOptions): Promise<string | null>Asks for a line of text; resolves the text, or null when cancelled or closed.
RcPluginWindow.close
ts
close(): voidCloses the window (onClose still runs).
RcPluginOptions interface
ts
interface RcPluginOptionsWhat rcplugins.register() takes.
RcPluginOptions.title
ts
title: stringThe toolbar button and window title (1-64 characters).
RcPluginOptions.right
ts
right?: stringA staff right needed to see and use the plugin: an existing one like 'sql', or a new name (lowercase letters, digits, '_') that then appears in the Staff Rights editor. Omitted: every staff member can use it.
RcPluginOptions.width
ts
width?: numberStarting window width in pixels (default 800).
RcPluginOptions.height
ts
height?: numberStarting window height in pixels (default 600).
RcPluginOptions.onOpen
ts
onOpen(win: RcPluginWindow, staff: RcStaff): void | Promise<void>Builds a newly opened window: call win.set() and register win.on() handlers.
RcPluginOptions.onClose
ts
onClose?(win: RcPluginWindow, staff: RcStaff): void | Promise<void>Runs after a window closed (by the staff member, the script, or a disconnect).
rcplugins global
ts
declare const rcplugins: { … }GRC plugins: a server script adds a button to every (allowed) staff member's GRC toolbar; clicking it opens a window whose UI and logic live in the script — item editors, report viewers, moderation panels. The script describes the window as a tree of widgets (forms, tables, lists, tabs, buttons...) that GRC renders natively, and handles the staff member's clicks and edits as events.
A registration belongs to the script that made it and goes away when that script unloads. On a hot reload, open windows of a plugin the new version registers again are rebuilt in place (onOpen runs again).
rcplugins.register
ts
register(id: string, options: RcPluginOptions): voidRegisters (or updates) a plugin. Throws on a bad id or one another script owns.
rcplugins.unregister
ts
unregister(id: string): voidRemoves a plugin; its open windows close.
rcplugins.list
ts
list(): string[]The ids this server's scripts have registered.