# The mindblown SDK

Every page mindblown serves carries one object, `window.mindblown`. This is its
reference.

<!-- audience: external -->
It is served at <https://mindblown.ai/sdk.md>, from the same build as the script
it describes, so it can neither get ahead of the code nor fall behind it.
<!-- /audience -->

## Contents

| Member | What it is for | Status |
| --- | --- | --- |
| [`viewer`](#viewer) | who is looking at the page | stable |
| [`load`](#load) | read private progress for this page | new |
| [`save`](#save) | write private progress with a revision check | new |
| [`remove`](#remove) | remove private progress with a revision check | new |
| [`creations`](#creations) | publish and read immutable JSON documents | new |
| [`run`](#run) | when a run starts and ends | stable |
| [`leaderboard`](#leaderboard) | the best each person did on this page | stable |
| [`room`](#room) | the seat, and the invitation -- see [multiplayer.md](/multiplayer.md) | new |
| [`live`](#live) | the match itself -- see [multiplayer.md](/multiplayer.md) | new |
| [`live.create`](#livecreate) | create a room with published resources | new |
| [`matches`](#matches) | read this account's completed match outcomes | new |
| [`push`](#push) | ask to tell this person things on their phone | new |
| [`world`](#world) | one shared place that keeps going while nobody looks, run by the page's own rules on our side | new |
| [`items`](#items) | the person's own vehicle, character or kept picture in a slot of this page -- see [inventory.md](/inventory.md) | new |
| [`generate`](#generate) | text and pictures made from what a viewer types -- see [generate.md](/generate.md) | new |
| [`shareUrl`](#shareurl) | the address this page can be sent to | new |
| [`event`](#event) | anything else that happened | stable |
| [`diagnostics`](#diagnostics) | expose bounded state for playback diagnostics | new |
| [`measure`](#measure) | up to five events the maker's numbers are drawn from | new |
| [`tune`](#tune) | the values a maker can change without a new build | new |
| [`sound`](#sound) | the visitor's own sound switch | stable |
| [`build`](#build) | which build of the page this is | new |
| [`recording`](#recording) | where your page draws people's names, for a recorded view -- see [multiplayer.md](/multiplayer.md) | new |
| [`events`](#events) | a queue, for a page that speaks before we load | stable |

## Before anything else

**Guard the object.** It is present on mindblown and nowhere else. A page that
assumes it cannot be opened anywhere else at all, including from a file while
you are building it.

```js
window.mindblown?.run?.start();      // optional chaining, every call
const mb = window.mindblown;
if (mb && mb.viewer) { /* ... */ }
```

**Nothing here is a credential.** The object never carries a token, and there is
nothing in it to authenticate with.

**Our script is the last thing in the body**, so it has run by the time
`DOMContentLoaded` fires. A page that acts any later finds the object already
there. A page that acts at parse time uses [`events`](#events).

**The head says what the page is.** Put one `<meta name="description">` in it:
one plain sentence that says what a person does on this page. Search results
and shared links show that sentence.

## `viewer`

Who is looking at the page.

```js
mb.viewer.id            // string
mb.viewer.username      // string
mb.viewer.signedIn      // boolean
mb.viewer.onchange(fn)  // (viewer) => void, returns () => void
```

| Property | Type | Meaning |
| --- | --- | --- |
| `id` | string | This person. `""` until known. Prefixed `anon:` when they have no account. |
| `username` | string | Their public handle. `""` when not known. |
| `signedIn` | boolean | True only once the API has confirmed it. |

`onchange(fn)` calls `fn` at once with the current value, then again on every
change. It returns a function that unsubscribes.

**Key on `id`. Show `username`.** A username is mutable: people change theirs,
and the old handle is kept only so old profile links keep working. Anything you
store under a username is orphaned the moment they rename, and nothing will tell
you it happened. An `id` never changes.

**mindblown is the only sign-in.** A page never invents its own accounts:
no usernames and passwords of its own, no login or sign-up form, and no password
reset. A page can keep its own list of players, with each player's record under
their mindblown `viewer.id` (in [`world.js`](#worldjs), `world.who.id`) and their
mindblown `username` to show. A display name, a character or a profile the person
picks is a field of that record, not an account. A call that needs an account answers `ACCOUNT_REQUIRED` (in
a room, `refused.needsAccount`), and the mindblown panel shows the sign-in: draw
"Sign in to play" and wait for `onchange`. This holds even when the person or the
instruction asks for accounts, a login, a password or a password reset of the
page's own, and when they allow a test or simulated version: build that part on
the mindblown sign-in, and say in your delivery that players sign in with
mindblown, so the page has no password of its own.

**A name can arrive before `signedIn` does.** The handle is read as the page
loads; proving the person behind it takes a round trip that does not always
finish. So `username` may be set while `signedIn` is still false.

**Signed out is not nobody.** A visitor with no account still gets a stable
`id`, prefixed `anon:`. It identifies a browser rather than a person: clearing
site data makes a new one, and one person can hold several. Remember somebody
with it. Do not settle a competition with it.

```js
mb.viewer.onchange((who) => {
  greeting.textContent = who.username ? `Welcome back, @${who.username}` : "Welcome";
  restoreProgress(who.id);
});
```

## `load`

Use private saves for progress, settings, and drafts. **Keep a person's progress
here and never in `localStorage`**: this follows their account to every device
and every place the page is opened, and the browser's own storage does not.
Each page has a separate namespace for each account.
Renames and rebuilds retain that namespace. A remix has a new namespace.
Your page owns the value's schema and its migrations.

```js
const mb = window.mindblown;
const saved = await mb?.load("progress");              // works from the first line
let progress = saved?.value ?? { schemaVersion: 1, level: 1 };

await mb?.save("progress", progress);                  // at each checkpoint
await mb?.remove("progress");                          // start over
```

`load`, `save` and `remove` exist from the page's first line. A call made before
our script has finished loading waits for it. Load once as the page starts, then
save at checkpoints: a level cleared, a match ended, a setting changed.

**A load waits for the visitor's sign-in state.** You do not need to wait for
`mb.viewer` first. One load can take up to 8 seconds before it answers or fails.
Do not stop waiting sooner, and do not start a second load while one is open.

**Load a key before you change it.** A save or removal of a key this page has
not loaded is refused with `LOAD_FIRST`, and so is one after `AUTH_CHANGED` until
you load again: a fresh start must never be written over progress the account
already has.

**A save is checked against what this page last saw.** If the value changed
somewhere else in the meantime -- another tab, another device -- the save is
refused with `REVISION_CONFLICT`, and `error.current` holds the newer value. Take
it, merge or ask, and save again; that save is checked against the newer value.
Nothing is overwritten silently.

When two windows may change one value at once and you must control every
change, pass `{ ifRevision, binding }` from the last result yourself:

```js
const prior = await mb.load("progress");
const next = await mb.save("progress", value, { ifRevision: prior.revision, binding: prior.binding });
```

All three methods return promises.
Each successful result contains `{ value, revision, bytes, binding, scope }`.

| Field | Meaning |
| --- | --- |
| `value` | Your JSON value; `null` when the key is absent |
| `revision` | An opaque revision; `null` when the key is absent |
| `bytes` | The compact UTF-8 JSON size; zero when absent |
| `binding` | An opaque value for subsequent changes in this document |
| `scope` | `"account"` for cloud saves; `"browser"` for browser saves |

Stored JSON `null` has a non-null revision. Deletion returns an absent result.
In the strict form, a null revision creates a value only when the key is absent,
and removal requires a concrete revision.
Revisions change after each save, including deletion and recreation.

After a timeout, load again before another change.
The earlier change can succeed even when its response is lost.

Signed-in visitors use their account saves across devices.
Confirmed signed-out visitors use browser storage.
An expired session or connection failure produces an error.
It does not select browser storage automatically.
Test seats cannot use private saves.

Show the active scope when it affects the user's progress.
Sign-in selects account saves and retains browser saves separately.
It does not import browser saves.
Account changes invalidate the binding. Load again after `AUTH_CHANGED`.
Browser saves can disappear when the user clears site data.
Browser partitioning can also separate saves between embedding contexts.

| Default limit | Value |
| --- | --- |
| One JSON value | 2 MiB |
| One namespace | 8 MiB and 32 keys |
| One key | 1–64 ASCII letters, digits, underscores, or hyphens |
| JSON nesting | 32 containers |
| Cloud changes | 60 successful saves or removals per minute, per account and page |

The first key character must be a letter or digit.
Use JSON values without cycles, functions, `undefined`, or non-finite numbers.
Sizes count compact UTF-8 JSON before compression.
The platform can configure cloud limits.
Quota errors include `error.limits` with the applicable limits.
Save at useful checkpoints, rather than on every animation frame.
Keep each large item, such as one drawing, under its own key.
A save then sends only the item that changed.

Errors expose `reason`, `status`, and a readable `message`.
Common reasons include `LOAD_FIRST`, `REVISION_CONFLICT`, `AUTH_CHANGED`, `QUOTA_EXCEEDED`, and `RATE_LIMITED`.
Unavailable storage produces an error; no value is silently discarded or truncated.

Private saves contain claims from the visitor's browser.
Do not use them as proof of scores, rewards, or competitive inventory.

## `save`

`mb.save(key, value)` writes a private JSON value. Add `{ ifRevision, binding }`
from the latest result only when you manage every change yourself.
See [private saves](#load) for limits, scope, and conflict handling.

## `remove`

`mb.remove(key)` removes a private value. The strict form takes
`{ ifRevision, binding }` with a concrete revision.
Successful removal returns the absent result described under [private saves](#load).

## `creations`

Publish layouts, challenges, and other JSON that visitors can share.
Publication requires a signed-in account. Test seats cannot publish.
Published documents are public to anyone with their identifier.
Keep private drafts in [private saves](#load).

```js
const request = {
  kind: "vault",
  schemaVersion: 1,
  value: layout,
  requestId: crypto.randomUUID()
};
const created = await mb.creations.publish(request);
const document = await mb.creations.get(created.id);
await mb.creations.remove(created.id);
```

`publish` and `get` return `{ id, kind, schemaVersion, value, bytes, hash }`.
`remove` returns `{ id, removed: true }`.
Each method returns a promise.
The identifier belongs to this page and never changes its content.
Publish another document when the content changes.
Your page validates the layout and its schema version before use.

Keep the request and its `requestId` until publication succeeds.
An identical explicit retry returns the same identifier after publication completes.
Changed content with the same request ID produces `IDEMPOTENCY_CONFLICT`.
Use a new request ID for a new publication.
The SDK does not retry writes automatically.

A timeout does not prove that publication failed.
Retry the same request to recover its identifier.
`PUBLICATION_PENDING` means another upload attempt still holds the request.
Wait before retrying that request.
The guaranteed retry window is twenty-four hours.
Do not assume an old request ID prevents duplicates after that window.

| Default limit | Value |
| --- | --- |
| One document | 32 KiB of compact UTF-8 JSON |
| One account and page | 16 active or pending documents and 256 KiB |
| Upload attempts | 10 per minute across one account's pages |
| `kind` | The same identifier rules as private save keys |
| `schemaVersion` | An integer from 1 through 2,147,483,647 |

Failed uploads consume an upload attempt after their reservation commits.
An identical retry of a completed publication consumes no additional upload attempt.
The owner can remove documents when a quota is exhausted.

Only the owner can remove a publication through the SDK.
Removal prevents later reads and new room attachments.
Retirement of the page also prevents public reads and new publications.
Platform takedown can make a document unavailable.
Always handle missing or unavailable documents.
Copies already delivered to visitors cannot be recalled.

`get` performs a public read without account credentials.
It does not list documents or search across pages.
Publication errors use the same `reason`, `status`, and `message` fields as private saves.

## `run`

When a run starts and ends.
<!-- audience: external -->
**Send `start()` and `end()`.** A publish through the API is not refused
without them. Mindblown's own builder refuses its publish without them. Send
them either way.
<!-- /audience -->
Your page is the only thing that knows, and everything outside it is reading
pixels and guessing.

`pause()` and `resume()` are required together once either one is there. Do not
add a pause your page does not have.


```js
mb.run.start();               // no arguments
mb.run.pause();
mb.run.resume();
mb.run.end(props);            // props: object, optional
```

| Call | When |
| --- | --- |
| `start()` | the run begins |
| `pause()` | it stops, and may continue |
| `resume()` | it continues |
| `end(props)` | it is over |

**A pause is not an end.** A paused page is a still picture, which is exactly
what an ended run looks like from outside. Without the word, anything watching
treats the pause as the end.

**`end()` may carry numbers**, and nothing else can supply them. The clock on
our side measures the whole interval including any pause. Yours is what the
person actually experienced, so send it if it matters. `props` follows the same
rules as [`event`](#event).

```js
mb.run.end({ seconds: 41, level: 3 });
```

<!-- audience: external -->
### Wire names

`run.start()`, `.pause()`, `.resume()` and `.end()` are the same call as
`event("game_start")`, `"game_pause"`, `"game_resume"` and `"game_end"`. Either
spelling reaches the same place. The short form exists because it reads better
in a page.
<!-- /audience -->

## `leaderboard`

The best each person did on this page. One board per metric, and a person holds
one row on it: their best, for as long as the page exists.

```js
mb.leaderboard.submit(metric, value, opts)  // Promise<void>
mb.leaderboard.top(metric, opts)            // Promise<Entry[]>
mb.leaderboard.mine(metric)                 // Promise<Entry|null>
```

| Argument | Rule |
| --- | --- |
| `metric` | lowercase, starts with a letter, at most 40 characters |
| `value` | a number, and a real one |
| `opts.lower` | `true` when a small value wins. Read on the FIRST submission only |
| `opts.label` | the board's name in plain words, at most 60 characters. Shown above the board on the page's own page |
| `opts.limit` | how many rows `top` returns. 20 by default, 100 at most |

An `Entry` is `{ username, profile_url, value, rank, at, mine }`. `username` is
empty for somebody with no account: they played, and your page may show them as
a guest. `mine` marks the caller's own row, so you can highlight it without
comparing identifiers you were never given.

**Link the name to `profile_url`.** A board is a list of people and a name on it
should lead to them. We build the address, so use the field and never assemble
one: it is empty for a guest, and it survives the app moving where profiles
live.

**Pick the direction on the first submission, because the name owns its meaning
for life.** A time is better small and a score is better large, and there is no
reading of the numbers that tells us which. So the first submission pins it, and
a later one that disagrees is **refused**: accepting it would silently reorder
every entry ever recorded, with no error anywhere and the old numbers still
sitting there looking right. If you need other semantics, use another name.

```js
mb.leaderboard.submit("score", 1200);                  // higher wins
mb.leaderboard.submit("time", 41.2, { lower: true });  // smaller wins
```

**Name every board in plain words.** The metric is a key and people never read
it; `opts.label` is what the page's own page shows above the board. Give it on
every submission: the latest name is kept, and a submission without one keeps
the name there is.

```js
mb.leaderboard.submit("m1_time", 41.2, { lower: true, label: "Mission 1 · Best time" });
```

**The value is a claim, and we do not pretend otherwise.** It is computed on the
visitor's machine, by code they can read and change. What is certain is WHO sent
it, and that everybody on one board played under the same rules. So a board is
worth having for the people who played your page, and is not a world record.

**Somebody signed in holds one row wherever they play, under their handle.
Somebody signed out holds one row per browser, and shows as a guest.** Both
appear on the board. Neither is a way to settle a competition with a prize on
it.

`submit` preserves the browser session and uses the account when signed in.
A page never receives a token. Signed-out visitors can submit as guests.
If submission fails or times out, the promise rejects. Offer a retry.
An authenticated failure never becomes an anonymous retry.

**Reading is free and public.** `top` needs no account and no permission: a
board is public by definition. Only a submission says who, and that is the only
part that needs anything.

```js
const rows = await mb.leaderboard.top("score", { limit: 10 });
rows.forEach((row) => {
  const who = document.createElement(row.profile_url ? "a" : "span");
  if (row.profile_url) who.href = row.profile_url;
  who.textContent = row.username || "guest";
  line.replaceChildren(`${row.rank}. `, who, ` - ${row.value}`);
});
```

**A board nobody has played is empty, not missing.** Asking before the first
person finishes returns `[]`.

**A submission is refused unless the page was opened.** We keep a record of who
loaded it, and a score from somebody with no such record is rejected. So submit
from the page, as the person plays it, rather than from anywhere else.
Submissions are also rate limited per address, and share that budget with the
play beacon.

## `room` -- playing together

More than one person on one page -- a table, a match, a shared board -- is its
own document: **[multiplayer.md](/multiplayer.md)**. Read all of it before
writing the first line of a page that seats two people. The rules there are
the ones the server enforces, and a refusal names that file.

```js
mb.live.lobby(fn)          // draw the lobby: who is here, the link
mb.live.match(fn)          // draw the match, once every seat is here
mb.live.play(opts)         // your button: { public: true, seats: N } finds people
mb.live.leave()            // give the seat back
mb.room.invite(name)       // ask somebody by name -- we draw the card
mb.room.look(name, opts)   // DEPRECATED 2026-09-15: turns are a rules file on live now
mb.room.act(name, turn)    // DEPRECATED 2026-09-15: see live.md, "Turns on live"
```

**We run the room and your page draws it.** A link to a room joins by itself,
and so does a page that opens already in its room. The match starts when every
seat is connected; the page never reads the address and never adds a Ready
step.

**There are three ways into a room, and a link is only one of them.** Share
the lobby's `state.link` and anybody who opens it joins. Call
`mb.room.invite(name)` -- the ROOM's name, the one you put in the link -- and WE
draw a card over your page: the person picks
somebody they have played with or follows, or types a username, and that person
gets a notification with a Join on it -- your page never sees a name or an
address and is told one number. Or call `mb.live.play({ public: true, seats: N })`
and we put them in a room that already has people in it. A page that only offers a link is leaving
two of the three out.

Three more things that are true before you read it: a guest can take a public
seat and join a named room that is already open, but opening a named room needs
an account, and the panel asks for one, so your page does not; every fact about
a room comes back from the room and never from the address; and seats are
numbered from 1.

## `live` -- the match itself

Paddles, cursors, a card table, a shared board: everybody at once or one at a
time, with your page's own rules run by the server. It is written down with
the seat and the invitation in **[multiplayer.md](/multiplayer.md)**. Read all
of it first.

```js
mb.live.match((channel) => {
  channel.send(input);                        // this seat's latest input
  channel.on("tick", (tick) => draw(tick));   // what the room says you may see
});
```

Your page ships `rules.js` at its root -- `init`, `step`, `view`, `done` --
and the room runs it. The page draws what the room sends and decides nothing.

### `live.create`

Create a named room with immutable documents from this page.
This operation requires a signed-in account. Test seats cannot create these rooms.
It returns the same channel interface `match` hands you.
The low-level `room.join` and `live.join` reject a supplied `resources` field with `INVALID_REQUEST`.

```js
const request = {
  seats: 2,
  resources: { layout: publishedLayout.id },
  requestId: crypto.randomUUID()
};
const channel = await mb.live.create(request);
channel.on("tick", (tick) => draw(tick));
channel.send(input);
const invitation = mb.shareUrl({ room: channel.room.name });
```

Use 2 through 1,000 seats and 1 through 4 named resources.
Resource names follow the [private save key rules](#load).
Each value is a published document's UUID from this page.
The combined documents must fit within 64 KiB of compact UTF-8 JSON.
Resources enter the server's rules context; private saves do not.
See [multiplayer.md](/multiplayer.md) for rules initialization and room lifecycle.

Keep the complete request until the room opens.
Retry the same request explicitly after a lost response or startup failure.
An identical retry uses the recorded room without joining another room.
It does not restore a released seat.
It does not release seats or close channels acquired after the original creation.
Changed options with the same request ID produce `IDEMPOTENCY_CONFLICT`.

Use a new request ID for another attempt.
The SDK does not retry creation automatically.

A successful new creation closes only the replaced channels held when the call began.
A request rejected before creation leaves those channels open.
Socket startup can fail after creation commits.
The promise resolves when the socket opens.
Later rules errors arrive through channel events.
A completed resource room does not start another attempt automatically.

After dispatch, startup failures include `reason`, `status`, `message`, `room`, and `requestId`.
`room` contains the committed room when its creation response arrived; otherwise it is `null`.
A timeout can leave a committed room. Retry with the same account and request.
`needsAccount` is true for a 401 response.

`RESOURCE_REVOKED` means the room cannot use its attached resources.
`AUTH_CHANGED` means the account changed during a request.
`CANCELLED` means the page closed or replaced a channel during startup.
`SERVICE_UNAVAILABLE` also covers unavailable infrastructure or disabled resource rooms.

## `matches`

Read completed outcomes for the current account on this page.
This operation requires a signed-in account. Test seats cannot read this history.
It returns recorded server outcomes, including ordinary and resource room matches.
It does not return another account's outcomes or the raw result payload.

```js
const first = await mb.matches.list({ limit: 20 });
for (const match of first.items) {
  console.log(match.room, match.endedAt, match.outcomes);
}
if (first.nextCursor !== null) {
  const next = await mb.matches.list({ limit: 20, cursor: first.nextCursor });
}
```

`list()` returns a promise for `{ items, nextCursor }`.
Omit the options to use the default limit of 20 matches.
The limit must be an integer from 1 through 100.
Results appear newest first. `nextCursor` is `null` after the last page.
Pass a returned cursor unchanged. It belongs to the current account and page.
Discard the cursor when the account changes.

| Item field | Meaning |
| --- | --- |
| `matchId`, `room`, `sequence` | The match UUID, room name, and match sequence. |
| `openedAt`, `endedAt` | UTC timestamps in RFC 3339 format. |
| `durationMs`, `ticks` | Recorded duration in milliseconds and tick count. |
| `outcomes` | This account's recorded seats, with `{ seat, place?, score?, won }`. |
| `manifestVersion`, `rulesDigest` | Optional resource manifest and rules provenance. |

One match can include several outcomes if the account held multiple recorded seats.
Missing `place` or `score` fields do not imply zero.
Errors include `reason`, `status`, and `message`.
An invalid limit or cursor produces `INVALID_REQUEST`.
An account change during the read produces `AUTH_CHANGED`.
History cannot write results or grant rewards.

## `push`

Ask to tell this person things when the page is closed: a raid on their base,
a building that finished, an invitation. Ask at a moment the person
understands, after a tap, never as the page opens.

```js
button.onclick = async () => {
  try {
    await mb.push.enable();
    note.textContent = "We will tell you.";
  } catch (error) {
    note.textContent = error.message;
  }
};
```

`enable()` returns a promise for `{ enabled: true }`. A signed-in account is required.
The page then sends notices with [`world.notify`](#world); each arrives on the phone.

| Reason | Meaning |
| --- | --- |
| `UNSUPPORTED` | This browser cannot show notices. On an iPhone, the page must be added to the home screen first. |
| `DENIED` | The person said no, now or before. Only their browser settings can change it. |
| `ACCOUNT_REQUIRED` | Nobody is signed in. |

## `world`

A world is ONE shared place per page. It keeps going while nobody looks.
Each person's things live in it, and other people can act on them while their
owner is away. The page decides what may happen, in a file it ships at
`/world.js`. That file runs on our side. Nobody can change a world by editing
the page in their browser.

Use a world when one person's action changes what another person owns.
Use [private saves](#load) for what belongs to one person only.
Use [`live`](#live) when people act at the same time and see each other move.

```js
const mb = window.mindblown;
const { answer, now } = await mb.world.act({ kind: "look" });
```

`act(input)` sends one JSON input and returns a promise for `{ answer, now }`.
`answer` is what `world.js` returned. `now` is the server clock in milliseconds.
A signed-in account is required; a signed-out visitor gets `ACCOUNT_REQUIRED`.
One input is at most 60 KiB. One person can act about five times a second.

### `world.js`

Ship it at the page root. It exports one function:

```js
export function act(world, input) {
  const key = "base:" + world.who.id;
  const base = world.get(key) ?? { gold: 100, since: world.now };
  base.gold += Math.floor((world.now - base.since) / 1000);
  base.since = world.now;
  world.put(key, base);
  return { base };
}
```

| `world.` | What it is |
| --- | --- |
| `who` | `{ id, name }` of the person who asked. `id` is the same as `mindblown.viewer.id`. `name` arrives already passed through `clean`. |
| `clean(text)` | The text with slurs, sexual terms and strong profanity masked as `•`. Pass every text one person writes and another reads through it: a clan name, a message, a sign. |
| `now` | The server clock, in milliseconds. Compute timers and production from it. |
| `rng()` | A random number from 0 to 1, from the server. |
| `get(key)` | One record, or `null`. |
| `put(key, value)` | Write one JSON record. At most 64 KiB, and 64 writes in one act. |
| `remove(key)` | Delete one record. |
| `sample(n, prefix)` | Up to 50 records whose key starts with `prefix`, as `{ key, value }`: a run of neighbouring keys from a random point. Random keys (an id) make it a fair sample. |
| `list(prefix, after, limit)` | Up to 100 records in key order, after the key `after`. |
| `notify(id, text)` | Tell another person who has acted in this world something. It appears in their mindblown notifications, and on their phone when they said yes to [`push`](#push). |
| `rank(metric, id, value, { lower })` | Put the CURRENT value of a person who has acted in this world on the page's [leaderboard](#leaderboard). |

A key is 1-128 letters, digits, `_`, `:`, `.` or `-`.

**One act is one transaction.** If `act` throws, nothing it wrote is kept, and
the caller gets `WORLD_THREW` with the message. Return a refusal as a value
(`{ refused: "gold" }`) when the person should see why.

**Nothing runs between acts.** There is no timer on our side. Store the time
something started, and compute what happened since when the next act reads it.
A building that finishes in an hour is `finishAt: world.now + 3600000`.

**The file follows the page.** A republished `world.js` runs within thirty
seconds. The records stay. Your file owns their shape and its migrations.
Before new rules first run, the world keeps a copy of every record (the last
three), so the page's owner can put the records back if a change breaks them.

**The file has no network, no DOM and no clock of its own.** Use `world.now`
and `world.rng`.

A notice or a rank for somebody who has never acted in this world is dropped.
A page that is taken down stops answering: `act` fails with `PAGE_GONE`.

A rank from a world is a standing: a lower value replaces a higher one. A
metric that a world ranks cannot also be written with `leaderboard.submit`.
Read it with `mb.leaderboard.top(metric)` as usual.

Errors include `reason`, `status`, and `message`. Reasons include
`ACCOUNT_REQUIRED`, `WORLD_THREW`, `TOO_LARGE`, `TOO_MANY_WRITES`, `BAD_KEY`,
`RATE_LIMITED`, `NO_WORLD` (no `world.js` at the page root), `WORLD_BUSY` (the world is
full right now; ask again after a second) and `AUTH_CHANGED`.

## `items`

A person keeps items, such as a car, and the same car fills a slot on every
page that accepts it. Declare the slots in `slots.json` beside the page, then:

```js
const car = await mb.items.get("car"); // the person's car, or null: draw your own
```

Before you write a page with a slot, read all of
**[inventory.md](/inventory.md)**: the slots file, the calls, and the rules every
vehicle and character obeys.

## `generate`

Make a text or a picture from what the viewer types, at the moment they type
it. The viewer who is signed in pays, from their own allowance.

```js
const answer = await mb.generate.text(`A crystal ball, asked about: ${typed}`, { max: 400 });
if (answer.refused) note.textContent = sayWhy(answer.refused);
else reading.textContent = answer.text;

const picture = await mb.generate.image(`a realistic ${typed}, studio light`, { size: "square" });
if (!picture.refused) img.src = picture.url;
```

`text(prompt, { max })` resolves `{ text }`, at most `max` characters (1 to
4000, default 1200). `image(prompt, { size })` resolves `{ url, sha }`: a PNG
on this page's own address, so a canvas can draw it. `size` is `square`
(default), `wide` or `tall`. An image takes 10 to 30 seconds, so show that it
is on its way. The prompt is 1 to 4000 characters, and the page may add its
own words to what the viewer typed.

A refusal is a value, never an error. Show each one in the page's own words:

| `refused` | Meaning |
| --- | --- |
| `sign_in` | Nobody is signed in. |
| `allowance` | The viewer's allowance is used up. |
| `too_fast` | More than 30 texts or 6 pictures a minute on this page, or 200 pictures a day. |
| `not_allowed` | The prompt, or the picture made from it, was refused by the safety check. |
| `unavailable` | Nothing could be made now. Try again later. |

Only a malformed call throws (`INVALID_REQUEST`).


## `shareUrl`

The address this page can be sent to.

```js
mb.shareUrl()                      // this page, shareable
mb.shareUrl({ room: "abc" })       // with something added
mb.shareUrl({ room: null })        // with something removed
```

**Use it for every link you hand a person.** Your page runs inside a frame and
its own `location.href` carries a marker of ours. A link built from that address
opens the page WITHOUT the frame around it, so the panel is not there — no sign
in, no rail, no way into a room. You cannot strip it yourself: you do not know
which parameters are ours, and the document that holds the real address is a
different origin from your page.

It keeps your own query, removes our marker, and applies whatever you pass.

## `event`

Anything else that happened.

```js
mb.event(name, props);        // name: string. props: object, optional.
```

| Argument | Rule |
| --- | --- |
| `name` | lowercase, starts with a letter, at most 40 characters |
| `props` | at most 8 entries |
| a key | lowercase, starts with a letter, at most 32 characters |
| a value | a string, a number or a boolean |
| a string value | at most 120 characters |
| the whole object | at most 1024 bytes |

**A signal that breaks a rule is refused whole, not trimmed.** A truncated name
is a different event, and a dropped property is a fact nobody recorded.

Plays are counted for you. Do not send an event for one.

```js
mb.event("level_cleared", { level: 3, seconds: 41 });
```

## `diagnostics`

Register a reader for the state that helps explain a failed interaction.
The SDK reads current values when it captures diagnostics.

```js
const stopDiagnostics = mb.diagnostics(() => ({
  fov: camera.fov,
  selected_class: player.classId,
  class_matches: player.classId === room.classId
}));
```

Return at most eight fields with lowercase keys of at most 25 characters.
Values can be finite numbers, booleans, or labels of at most 120 UTF-8 bytes.
Use technical identifiers and settings. Exclude names, typed text, cookies, and credentials.
The reader must return synchronously. Call the returned function to remove it.
A failed or invalid reader does not stop the page or its error report.

The SDK also captures viewport, visibility, focus, sound switch, and audio context state.
Existing pages receive these browser facts without a source change.
Each report keeps the current state and up to four earlier states within 8 KiB.
Errors carry diagnostics. The existing visit marks and exit also carry silent state reports.
The owner's Analytics > Performance tab shows these reports, including the owner's visits.
Diagnostic state stays in the event store and does not reach PostHog.

## `measure`

Up to five of your events that the maker's numbers are drawn from. Optional:
a page with nothing worth counting says nothing here, and every other event
still lands as before.

```js
mb.measure(list);   // list: [{ name, kind, label }], at most 5 entries
```

| Field | Rule |
| --- | --- |
| `name` | an event name, under the same rule as [`event`](#event). The events you send under it are what is counted |
| `kind` | `count`: how many times. `value`: the middle `props.value` of the times it happened. `step`: how many visits reached it at least once |
| `label` | a few words for the maker, at most 40 characters. Optional |

Pick the moments that say whether the page worked: reaching the end, a
score, a level cleared. Call it once, when the page loads, and then send the
events as usual.

```js
mb.measure([
  { name: "finished", kind: "step", label: "Reached the end" },
  { name: "score", kind: "value", label: "Score" },
]);
// later
mb.event("finished");
mb.event("score", { value: 1200 });
```

**The kind is pinned the first time a name is declared**, for the reason a
board's direction is: reading a count as a value would silently change every
row already stored. A later declaration with another kind is refused; the
label may change. Repeating the same list changes nothing.

## `tune`

The values a maker can change without a new build: every number, colour, text
and switch that sets how the page looks or behaves. Put them in `tune.json`,
next to the page, and read them from there. Do not write them as constants in
the code.

```json
{
  "speed":    { "value": 4, "min": 1, "max": 10, "step": 0.5, "label": "Speed" },
  "lives":    { "value": 3, "min": 1, "max": 9, "step": 1 },
  "accent":   { "value": "#ff3344", "kind": "color" },
  "mode":     { "value": "calm", "options": ["calm", "fast"] },
  "greeting": { "value": "Welcome", "kind": "text" },
  "music":    { "value": true }
}
```

| Kind | How it is written | Rule |
| --- | --- | --- |
| number | `value` is a number, with `min` and `max` | a value outside the range is clamped into it |
| boolean | `value` is `true` or `false` | |
| color | `"kind": "color"` | `#rrggbb` |
| choice | `options` | `value` is one of the options |
| text | `"kind": "text"` | at most 200 characters |

A name is lowercase, starts with a letter, and has at most 40 characters. At
most 40 entries. `label` is a few words for the maker, and it is optional. An
entry that breaks a rule is left out.

```js
mb.tune()        // Promise<{ [name]: value }>, never rejects
mb.tune.on(fn)   // (values) => void, returns () => void
```

Read the values once, when the page starts, and use them everywhere the page
would have used a constant. `on` is called when the maker tries other values
while the page runs. Apply them there if you can. A page that cannot is
restarted with the new values instead.

```js
const mb = window.mindblown;
const fromFile = () => fetch("tune.json").then((r) => r.json())
  .then((f) => Object.fromEntries(Object.entries(f).map(([k, e]) => [k, e.value])))
  .catch(() => ({}));
let tune = {};
(mb?.tune ? mb.tune() : fromFile()).then((values) => { tune = values; start(); });
mb?.tune?.on((next) => { tune = next; });
```

`fromFile` is for a page opened without us, while you build it: the same file,
so the page behaves the same on your machine and on mindblown.

**The maker changes a value without you.** A changed value is a new version of
the page, made from this file, so a value in the code instead of in the file is
a value nobody can change without a new build. A new name needs a build; a new
value never does.

## `sound`

The visitor's own sound switch. It belongs to whoever is holding the phone, and
it follows them from page to page.

```js
mb.sound.on             // boolean
mb.sound.set(next)      // next: boolean, returns boolean
mb.sound.toggle()       // returns boolean
mb.sound.onchange(fn)   // (on) => void, returns () => void
```

If your page draws its own sound control, read and write this one so the two
never disagree.

## `build`

Which build of the page is running: the id in its `/v/<id>/` link, which is the
same id the maker sees in the page's Versions list.

```js
mb.build                // "c464857d7113d3ec", or undefined
```

**If your page shows a build label, show `mb.build`, or its first 8 characters
as Versions does.** Never make up a label of your own: nobody can match it to a
link or to a version. It is `undefined`
outside mindblown and on a page that has never been published, so show nothing
then.

## `recording`

A few views of a page are recorded for its maker, and people's names never
reach a recording. Text we can see is masked for you. Names you draw in 3D are
not, so a room page with a 3D canvas calls `mb.recording.mask(fn)` to say where
they are -- see "Names on screen" in [multiplayer.md](/multiplayer.md).

## `events`

A queue, for a page that speaks before our script has loaded. Entries are
replayed in order the moment the object arrives.

```js
window.mindblown = window.mindblown || {};
window.mindblown.events = [["level_cleared", { level: 1 }]];
```

Each entry is `[name, props]` and reaches [`event`](#event) unchanged, so the
same rules apply.

You rarely need it by hand: `event`, `run` and `measure` exist from your page's
first line and queue the same way until our script arrives.
<!-- audience: external -->
A run queued this way uses the wire names: `["game_start"]` and
`["game_end", { seconds: 41 }]`.
<!-- /audience -->

## Stability

**A member marked stable never changes meaning.** If we need different
behaviour, it arrives under a different name. A page written against this
document keeps working.

**A member marked new is not yet promised.** It works and it is documented, and
its shape may still change while the first pages are written against it. It
becomes stable once it has carried real pages and stopped moving. Everything
else in [Contents](#contents) is stable.

**New members appear; old ones are not repurposed.** Check the table in
[Contents](#contents) for what exists today. Anything not listed there is not
part of the SDK, whatever you may find on the object.

**Reading a member you do not recognise is safe.** Guard every call, and a page
written for an older version of this document runs unchanged on a newer one.
