---
title: defineEvent
description: Declare a typed event that any luna emits with ctx.emit and any luna type hears through its on option.
related:
  - /events/emit-events
  - /events/listen-to-events
  - /events/react-to-table-changes
---

`defineEvent` declares a typed event. Any luna emits it with `ctx.emit`, and any luna type hears it through its `on` option.

```ts luna/lunas/events.ts
import { defineEvent, t } from "luna";

export const CardDone = defineEvent("cards.done", t.object({ card: t.int(), owner: t.string() }));
```

## Reference

### defineEvent(name, type, options)

| Prop | Type | Default | Description |
| - | - | - | - |
| `name` | `string` | - | The event's name: letters, digits, `_`, `.` and `-`, at most 128 characters. |
| `type` | `Ty<T>` | - | The payload's type, built with `t`. |
| `options.retention?` | `EventRetention` | `{ maxAge: "7d" }` | How long each emitting luna keeps the events it emitted, for listeners that come later. |

It returns an `EventDef`.

| Prop | Type | Default | Description |
| - | - | - | - |
| `name` | `string` | - | The name it was declared with. |
| `type` | `Ty<T>` | - | The payload's type. |
| `map` | `(fn: (e: T, from: Record<string, any>) => R) => Source<R, T>` | - | A source that sends each listener only the fields `fn` names. |

### EventRetention

An event leaves the emitter's keeping once it passes any limit you set. Leave out `retention` to keep events for 7 days. Pass `{}` to set no limit.

| Prop | Type | Default | Description |
| - | - | - | - |
| `maxAge?` | `string \| number` | - | Drops events older than this, as a duration such as `"30d"` or milliseconds. |
| `maxCount?` | `number` | - | Keeps at most this many events, the newest. |
| `maxBytes?` | `number` | - | Keeps at most this many bytes of events, the newest. |

### ctx.emit(event, payload)

| Prop | Type | Default | Description |
| - | - | - | - |
| `event` | `EventDef` | - | The event to emit. |
| `payload` | `EventOf<E>` | - | The payload, of the event's type. |

It returns a `number`: the event's place in this luna's log of that event. The [ctx](/sdk/ctx) page covers the rest of `ctx`.

### The on option and listen

A luna type lists what it hears in `on`. The function receives `listen` and returns a list of its results: `on: (listen) => [listen(source, options, handler)]`.

| Prop | Type | Default | Description |
| - | - | - | - |
| `source` | `EventDef \| Source \| TableChanges` | - | An event, a mapped event, or a luna type's table changes. |
| `options.key?` | `(item, from) => unknown` | - | Names which luna of this type hears each item, and is left out on a type with no key. |
| `handler` | `(ctx, item, from: From) => void \| Promise<void>` | - | Runs for each event or change, with this type's `ctx`. |

The key function only names values. It may return a field of the payload or row, a key field of the emitting luna from `from`, a constant, `day(field)` or `hash(n)`. A type with several key fields returns an object with each of them.

The handler's third argument is a `From`, the emitting luna:

| Prop | Type | Default | Description |
| - | - | - | - |
| `type` | `string` | - | The emitting luna's type. |
| `key` | `Record<string, unknown>` | - | The emitting luna's key. |

### day(field) and hash(n)

| Prop | Type | Default | Description |
| - | - | - | - |
| `day(field)?` | `never` | - | The UTC day, as `YYYY-MM-DD`, of a field that holds milliseconds since the epoch. |
| `hash(n)?` | `never` | - | A bucket from 0 to `n - 1`, picked by a hash of the emitting luna's key. `n` is 1 to 1024. |

Both are imported from `"luna"` and used only inside a key function, such as `key: (e) => day(e.at)`.

### TableChanges

Every luna type has `changes`, with one `TableChanges` for each of its tables, such as `Card.changes.notes`.

| Prop | Type | Default | Description |
| - | - | - | - |
| `where` | `(w: Record<string, unknown>) => TableChanges` | - | Only rows that match, with a value or `eq`, `ne`, `lt`, `lte`, `gt`, `gte`, `in` and `isNull`. |
| `map` | `(fn: (row, from) => M) => TableChanges` | - | Sends each listener only the fields `fn` names, from the row and the emitting luna's key. |

### TableChange

What a listener's handler receives for each change of a table's row.

| Prop | Type | Default | Description |
| - | - | - | - |
| `op` | `"upsert" \| "delete" \| "clear"` | - | What happened to the row. |
| `key?` | `unknown[]` | - | The row's primary key values, set for `upsert` and `delete`. |
| `row?` | `R` | - | The row as it is now, set for `upsert`. |

`clear` means everything from that emitting luna goes. It comes when the luna was destroyed, or before it sends all its rows again, such as after a deploy changes the listen.

## Good to know

- An emit is a write. It goes out once the handler commits, and a handler that fails takes it back, as does a `ctx.transaction` that throws.
- Luna checks each payload against the event's type. A payload of another type, or one over 1 MiB as JSON, fails the call.
- A listener hears one emitting luna's events and changes in order. Luna delivers each batch at least once and skips a batch the listener already ran, so the handler runs once for each item.
- Items come in batches, each in one transaction. A batch that fails is tried again.
- Each event reaches one luna per listen: the one its key names. There is no broadcast to every luna of a type.
- A listen added by a later deploy catches up. It hears the events each emitter still keeps, and every row of a table that matches its `where`.
- A row that stops matching the `where`, or whose key now names another luna, reaches the luna that had it as a `delete`.
- A key function that computes a value, such as a template string, throws when the type is defined. It may only name fields.
- A listen can fill key fields of type string, int, uuid and enum.
- `in` in a `where` takes at most 100 values.
- Every event your app's modules define is part of its deploy, whether or not a type listens to it.

## Examples

### Emit an event

```ts luna/lunas/card.ts
import { defineLuna, t, table } from "luna";
import { CardDone } from "./events.ts";

export const Card = defineLuna({
  name: "Card",
  key: { board: t.string(), card: t.int() },
  schema: { notes: table({ id: t.id(), text: t.string(), done: t.bool().default(false) }) },
  handlers: (h) => ({
    finish: h({ args: { owner: t.string() } }, (ctx, { owner }) => {
      ctx.emit(CardDone, { card: ctx.key.card, owner });
    }),
  }),
});
```

### Hear an event in the luna it names

```ts luna/lunas/user.ts
import { defineLuna, t, table } from "luna";
import { CardDone } from "./events.ts";

export const User = defineLuna({
  name: "User",
  key: { id: t.string() },
  schema: { done: table({ id: t.id(), card: t.int(), board: t.string() }) },
  on: (listen) => [
    listen(CardDone, { key: (e) => e.owner }, (ctx, e, from) => {
      ctx.db.done.insert({ card: e.card, board: String(from.key.board) });
    }),
  ],
  handlers: (h) => ({
    done: h({ query: true }, (ctx) => ctx.db.done.find({ orderBy: "id" })),
  }),
});
```

### Keep a copy of another type's rows

Each `Board` keeps the open notes of its cards. The key comes from the emitting card's own key.

```ts luna/lunas/board.ts
import { defineLuna, t, table } from "luna";
import { Card } from "./card.ts";

export const Board = defineLuna({
  name: "Board",
  key: { id: t.string() },
  schema: {
    open: table({ card: t.int(), note: t.int(), text: t.string() }, { primaryKey: ["card", "note"] }),
  },
  on: (listen) => [
    listen(Card.changes.notes.where({ done: false }), { key: (_row, from) => from.board }, (ctx, change, from) => {
      const card = Number(from.key.card);
      if (change.op === "upsert") ctx.db.open.upsert({ card, note: change.row!.id, text: change.row!.text });
      else if (change.op === "delete") ctx.db.open.delete({ where: { card, note: Number(change.key![0]) } });
      else ctx.db.open.delete({ where: { card } });
    }),
  ],
  handlers: (h) => ({
    open: h({ query: true }, (ctx) => ctx.db.open.find({ orderBy: "card" })),
  }),
});
```

### Keep events for longer

```ts luna/lunas/events.ts
export const CardMoved = defineEvent("cards.moved", t.object({ card: t.int(), to: t.string() }), {
  retention: { maxAge: "30d", maxCount: 10_000 },
});
```

## Version history

| Version | Change |
| --- | --- |
| 0.0.9 | `defineEvent`, `ctx.emit` and listens added. |
