# Modules

> What each module of effect-cqrs exports.

Everything is exported from `effect-cqrs` as a namespace, as in `import { Aggregate, ViewModel } from "effect-cqrs"`, and each module also has its own path, such as `effect-cqrs/ViewModel`. `PersonalDataNode` only has its own path, which keeps `node:crypto` out of code for browsers.

## Aggregate

Defines aggregates. [Source](https://github.com/davidnussio/effect-cqrs/blob/main/src/Aggregate.ts)

| Export                                                                | What it is                                                                         |
| --------------------------------------------------------------------- | ---------------------------------------------------------------------------------- |
| `make<State>()({ name, events, initial, projection, versions })`      | Starts an aggregate, to which `.command(name, { payload, handler })` adds commands |
| `evolve(aggregate, state, event, meta)`                               | Applies one event with the aggregate’s projection                                  |
| `historical(aggregate, tag, version, value)`, `Historical`            | An event as an older version of its schema stored it                               |
| `schemaVersion(aggregate, tag)`, `Versions`                           | The version new events are written in, and the type of `versions`                  |
| `EventMeta`, `CommandContext`                                         | What projections and handlers receive besides the event or payload                 |
| `State`, `Event`, `CommandName`, `Payload`, `CommandError`, `Context` | Types derived from an aggregate                                                    |

## AggregateService

Runs an aggregate against the event store. [Source](https://github.com/davidnussio/effect-cqrs/blob/main/src/AggregateService.ts)

| Export                                                                            | What it is                                                                                                   |
| --------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------ |
| `make(aggregate, { maxRetries, stateCacheSize, commandIdsPerStream, snapshots })` | The service: `commands`, `dispatch`, `state`, `history`                                                      |
| `SnapshotOptions`                                                                 | `every`, `schema` and `version` of the snapshots                                                             |
| `CommandOptions`                                                                  | `commandId` and `expectedVersion`, the last argument of a typed command                                      |
| `CommandResult`, `HistoryEntry`                                                   | What a command and `history` return                                                                          |
| `UnknownCommand`, `InvalidCommand`, `WrongExpectedVersion`, `EventDecodeError`    | Its errors, besides the store’s                                                                              |
| `CommandFailure`, `ReadError`                                                     | What every command, and every read, can fail with                                                            |
| `commandIdKey`                                                                    | The metadata key that records a command’s [`commandId`](https://effect-cqrs.dambox.ch/guides/commands/#retries-and-command-ids)           |
| `makeEventDecoder(aggregate, keys)`, `makeEventEncoder(aggregate, keys)`          | Convert between stored JSON and an aggregate’s events, decrypting and encrypting personal fields with `keys` |
| `MetricNames`                                                                     | The names of the [metrics](https://effect-cqrs.dambox.ch/guides/commands/#metrics) the service records                                    |

## CommandGateway

One entry point for the commands of several aggregates, see [several aggregates](https://effect-cqrs.dambox.ch/guides/commands/#several-aggregates). [Source](https://github.com/davidnussio/effect-cqrs/blob/main/src/CommandGateway.ts)

| Export                             | What it is                                                                    |
| ---------------------------------- | ----------------------------------------------------------------------------- |
| `make(entries, { interceptors })`  | The gateway over aggregates or their services: `send`, `dispatch`, `services` |
| `Interceptor<E, R>`, `CommandInfo` | What runs around every command, and what it learns about the command          |
| `Command`                          | The typed command `send` takes                                                |
| `UnroutableCommand`                | `dispatch` can’t tell which aggregate a command is for                        |

## PersonalData

Crypto-shredding of personal fields, see [personal data](https://effect-cqrs.dambox.ch/guides/personal-data/). [Source](https://github.com/davidnussio/effect-cqrs/blob/main/src/PersonalData.ts)

| Export                                                                           | What it is                                                          |
| -------------------------------------------------------------------------------- | ------------------------------------------------------------------- |
| `field(schema, { redacted, subject })`                                           | Marks a field of an event as personal                               |
| `forget(subject)`                                                                | Destroys the key of a subject and records it in the log             |
| `Keys`, `layerMemory`, `layerSql`, `make(backend)`                               | The keys of subjects, and where they are stored                     |
| `MasterKey`, `layerMasterKey`, `layerMasterKeyConfig`, `layerMasterKeyEphemeral` | What wraps the keys of subjects                                     |
| `Backend`, `makeMemoryBackend`, `makeSqlBackend`                                 | Key stores, to implement another                                    |
| `migrations({ table })`                                                          | The migrations of the key table, for `layerSql({ migrate: false })` |
| `Cipher`, `webCrypto`                                                            | AES-256-GCM, on WebCrypto unless another cipher is provided         |
| `SubjectForgotten`, `PersonalDataError`                                          | Its errors                                                          |
| `streamName`, `subjectForgottenType`                                             | Where forgetting is recorded                                        |

## PersonalDataNode

The [personal data](https://effect-cqrs.dambox.ch/guides/personal-data/#on-node) cipher on `node:crypto`, imported from `effect-cqrs/PersonalDataNode`. [Source](https://github.com/davidnussio/effect-cqrs/blob/main/src/PersonalDataNode.ts)

| Export        | What it is                                                              |
| ------------- | ----------------------------------------------------------------------- |
| `layerCipher` | Encrypts personal fields synchronously, in the same format as WebCrypto |
| `cipher`      | The `Cipher` it provides                                                |

## EventVersions

Older shapes of an event. [Source](https://github.com/davidnussio/effect-cqrs/blob/main/src/EventVersions.ts)

| Export                    | What it is                                                                    |
| ------------------------- | ----------------------------------------------------------------------------- |
| `from(schema)`            | Starts a history at version 1, to which `.next(schema, upcast)` adds versions |
| `decoders(tag, versions)` | One decoder per old version, all the way to the current one                   |
| `current(versions)`       | The version new events are written in                                         |

## Causation

Why events were recorded. [Source](https://github.com/davidnussio/effect-cqrs/blob/main/src/Causation.ts)

| Export                                  | What it is                                                    |
| --------------------------------------- | ------------------------------------------------------------- |
| `withCausation(causation)`              | Runs an effect whose commands record these ids                |
| `causedBy(stored)`, `fromEvent(stored)` | Makes a stored event the cause of the commands an effect runs |
| `CurrentCausation`                      | The reference that holds them, `undefined` outside any        |

## Ids

The ids the framework makes up, such as new correlations. [Source](https://github.com/davidnussio/effect-cqrs/blob/main/src/Ids.ts)

| Export               | What it is                                                      |
| -------------------- | --------------------------------------------------------------- |
| `IdGenerator`        | The reference that makes them, `crypto.randomUUID()` by default |
| `next`               | A new id from the current generator                             |
| `sequential(prefix)` | A generator of `prefix-1`, `prefix-2` and so on, for tests      |

## Metadata

What commands carry beside their payload, such as the software version. [Source](https://github.com/davidnussio/effect-cqrs/blob/main/src/Metadata.ts)

| Export                   | What it is                                                                              |
| ------------------------ | --------------------------------------------------------------------------------------- |
| `withMetadata(metadata)` | Runs an effect whose commands record this metadata on top of the current one            |
| `layer(metadata)`        | Provides metadata to the services built on top, for values such as the software version |
| `CurrentMetadata`        | The reference that holds it, `{}` outside any                                           |
| `Metadata`               | The type and schema of metadata: a JSON object                                          |

## ViewModel

Projects events into read models. [Source](https://github.com/davidnussio/effect-cqrs/blob/main/src/ViewModel.ts)

| Export                                                                            | What it is                                                                                                                                    |
| --------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------- |
| `make({ name, aggregates, handlers, dispose, onForget, onFailure, transaction })` | Defines a view model. `onForget` erases what it stored about a [forgotten subject](https://effect-cqrs.dambox.ch/guides/personal-data/#view-models)                        |
| `layer([...])`                                                                    | Runs view models in the background and provides `ViewModels`                                                                                  |
| `ViewModels`                                                                      | The service: `replay`, `caughtUp`, `status`, `parked`, `retryParked`                                                                          |
| `stall`, `park({ attempts })`, `FailurePolicy`                                    | What a view model does about an event that keeps failing, see [parking events](https://effect-cqrs.dambox.ch/guides/view-models/#parking-events)                           |
| `sqlTransaction`, `Transaction`                                                   | Runs each batch with its checkpoint in one transaction, see [checkpoints in a transaction](https://effect-cqrs.dambox.ch/guides/view-models/#checkpoints-in-a-transaction) |
| `Status`, `RetryParkedOptions`, `RetryParkedResult`                               | What `status` and `retryParked` give and take                                                                                                 |
| `MetricNames`                                                                     | The names of the metrics view models record                                                                                                   |
| `ViewModelError`, `UnknownViewModel`                                              | A handler’s failure, and a replay of an unknown name                                                                                          |

## ParkedEvents

Events view models gave up on, see [parking events](https://effect-cqrs.dambox.ch/guides/view-models/#parking-events). [Source](https://github.com/davidnussio/effect-cqrs/blob/main/src/ParkedEvents.ts)

| Export                                    | What it is                                                      |
| ----------------------------------------- | --------------------------------------------------------------- |
| `ParkedEvents`                            | The service: `park`, `list`, `remove`                           |
| `layerMemory`, `makeMemory`               | Parked events in memory                                         |
| `layerSql({ table, migrate })`, `makeSql` | Parked events in a table, on SQLite or PostgreSQL               |
| `migrations({ table })`                   | The migrations of the table, for `layerSql({ migrate: false })` |
| `ParkedEvent`                             | What it records, and its schema                                 |

## Leases

Which process runs each view model, see [several processes](https://effect-cqrs.dambox.ch/guides/view-models/#several-processes). [Source](https://github.com/davidnussio/effect-cqrs/blob/main/src/Leases.ts)

| Export                                                | What it is                               |
| ----------------------------------------------------- | ---------------------------------------- |
| `Leases`                                              | The service: `acquire(name)`             |
| `layerMemory`, `memory`                               | Leases that are always held, the default |
| `layerPostgres({ interval, prefix })`, `makePostgres` | Leases on PostgreSQL advisory locks      |
| `Lease`                                               | A lease: `held` and `changes`            |

## Saga

Processes that span several aggregates, as durable workflows from `effect/workflow`, see [sagas](https://effect-cqrs.dambox.ch/guides/sagas/). [Source](https://github.com/davidnussio/effect-cqrs/blob/main/src/Saga.ts)

| Export                                                       | What it is                                                                                                        |
| ------------------------------------------------------------ | ----------------------------------------------------------------------------------------------------------------- |
| `workflow(tag, { payload, idempotencyKey, success, error })` | Defines a saga’s workflow: `Workflow.make` with a `causation` field added to the payload                          |
| `toLayer(workflow, execute)`                                 | Registers the workflow’s body with the engine. Its commands record the event that started the saga as their cause |
| `command(name, { execute, error })`                          | Runs a command as an activity, so a replay of the workflow returns the saved outcome instead of running it again  |
| `start(workflow, payload)`                                   | Starts a run without waiting for it, and returns its execution id                                                 |
| `make({ name, aggregates, handlers, onFailure })`            | The trigger: a view model whose handlers start workflows with `start`                                             |
| `layer([...])`                                               | Runs triggers in the background, apart from the view models, and provides `Sagas`                                 |
| `Sagas`                                                      | The service that manages the triggers, with what `ViewModel.ViewModels` has                                       |
| `SagaWorkflow`                                               | The type of a workflow whose payload carries its causation                                                        |
| `CausationSchema`, `CommandOutcome`                          | Schemas of that causation, and of what a saga keeps of a command it ran: aggregate, version and position          |

## CommandApi

Serves an aggregate over HTTP, see [integration](https://effect-cqrs.dambox.ch/guides/integration/#http). [Source](https://github.com/davidnussio/effect-cqrs/blob/main/src/CommandApi.ts)

| Export                                                               | What it is                                                                                            |
| -------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------- |
| `group(aggregate, { name, prefix, state, errors })`                  | An `HttpApiGroup` with a `POST` endpoint per command, `history` and, with the `state` option, `state` |
| `layer(api, name, service)`                                          | Implements the group with an aggregate service, or an effect that makes one                           |
| `InvalidCommandError`, `ConcurrencyConflictError`, `CommandRejected` | The errors it answers with `400`, `409` and `422`                                                     |
| `commandResult(events)`, `historyEntry(events)`                      | Schemas of what a command and `history` answer                                                        |

## EventCatalog

JSON Schema of events and commands, and a compatibility guard, see [integration](https://effect-cqrs.dambox.ch/guides/integration/#event-catalog). [Source](https://github.com/davidnussio/effect-cqrs/blob/main/src/EventCatalog.ts)

| Export                                                  | What it is                                                            |
| ------------------------------------------------------- | --------------------------------------------------------------------- |
| `events(aggregate)`, `commands(aggregate)`              | JSON Schema of every event version and command payload                |
| `document(aggregates, { title, version, description })` | An AsyncAPI 3.0 document of them                                      |
| `captureSamples(aggregates, { perVersion })`            | Stored payloads of each event type and version, without personal data |
| `saveSamples(path, samples)`, `readSamples(path)`       | Keep samples in a JSON file                                           |
| `checkCompatibility(aggregate, samples)`                | Fails with `IncompatibleSamples` when a sample no longer decodes      |
| `Sample`, `IncompatibleSamples`                         | A sample, and the guard’s error                                       |

## Outbox

Publishes events to other systems, see [integration](https://effect-cqrs.dambox.ch/guides/integration/#outbox). [Source](https://github.com/davidnussio/effect-cqrs/blob/main/src/Outbox.ts)

| Export                                                             | What it is                                              |
| ------------------------------------------------------------------ | ------------------------------------------------------- |
| `make({ name, aggregates, messages, publish, batchSize, linger })` | Defines an outbox                                       |
| `layer([...])`                                                     | Runs outboxes in the background and provides `Outboxes` |
| `Outboxes`                                                         | The service: `published` and `status`                   |
| `Message`, `Mapped`, `Mappings`                                    | What is published, and what a mapping returns           |
| `OutboxError`                                                      | A failure to publish                                    |

## EventStore

The append-only log. [Source](https://github.com/davidnussio/effect-cqrs/blob/main/src/EventStore.ts)

| Export                                               | What it is                                                                             |
| ---------------------------------------------------- | -------------------------------------------------------------------------------------- |
| `EventStore`                                         | The service: `append`, `read`, `subscribe`, `head`, `changes`                          |
| `layerMemory`, `makeMemory`                          | The store in memory                                                                    |
| `make(backend, options)`, `Backend`, `MakeOptions`   | Builds a store on another database                                                     |
| `groupCommit(appendGroup)`                           | Group commit for a backend: concurrent appends to different streams in one transaction |
| `StoredEvent`, `EventFilter`, `AppendInput`          | What it stores, selects and takes                                                      |
| `eventId(event)`                                     | An event’s id as a cause, like `account/alice@4`                                       |
| `toStored(input, event, index, position, timestamp)` | A new event’s stored form, for a backend                                               |
| `ConcurrencyConflict`, `EventStoreError`             | Its errors                                                                             |

## Checkpoints

How far each view model has read. [Source](https://github.com/davidnussio/effect-cqrs/blob/main/src/Checkpoints.ts)

| Export        | What it is                   |
| ------------- | ---------------------------- |
| `Checkpoints` | The service: `get` and `set` |
| `layerMemory` | Checkpoints in memory        |

## SqliteEventStore and PostgresEventStore

Durable stores through `effect/sql`. [SQLite](https://github.com/davidnussio/effect-cqrs/blob/main/src/SqliteEventStore.ts), [PostgreSQL](https://github.com/davidnussio/effect-cqrs/blob/main/src/PostgresEventStore.ts)

| Export                             | What it is                                                                               |
| ---------------------------------- | ---------------------------------------------------------------------------------------- |
| `layer(options)`                   | The event store, given a `SqlClient`                                                     |
| `layerCheckpoints(options)`        | Checkpoints in the same database                                                         |
| `migrations(options)`, `Migration` | The schema as SQL, for your own migration tooling                                        |
| `Options`                          | `eventsTable`, `checkpointsTable`, `migrate`, `pollInterval`, and `listen` on PostgreSQL |

## Fixture

Tests an aggregate. [Source](https://github.com/davidnussio/effect-cqrs/blob/main/src/Fixture.ts)

| Export                     | What it is                                                                       |
| -------------------------- | -------------------------------------------------------------------------------- |
| `make(aggregate)`          | A fixture: `givenEvents`, `when`, `whenFails`, `inspectState`, `checkInvariants` |
| `InvariantOptions`, `Step` | What `checkInvariants` takes, and one command it generates                       |
| `Scenario`, `Outcome`      | The chain, and what yielding it gives                                            |
| `ExpectationFailed`        | The defect a failed expectation raises                                           |
