# flash-oss/medici architecture

> Architecture diagram of the GitHub repository flash-oss/medici, generated by GitDiagram from its file tree, README and a sample of source files (last updated 2026-07-08). It is an AI-made overview: check details against the source.

- Interactive diagram: https://gitdiagram.com/flash-oss/medici
- Repository: https://github.com/flash-oss/medici

## Overview

1. **What this repo is**
   - `medici` is a TypeScript/Mongoose library that implements a double-entry accounting ledger on MongoDB.
   - The core abstraction is a **Book**: a logical partition of journals and transactions identified by a book name.

2. **Public API surface**
   - `src/index.ts` exports the main entry points: `Book`, `Entry`, `mongoTransaction`, schema registration helpers, index sync helpers, and custom error types.
   - `Book` is the primary façade. `Entry` is the fluent builder used to assemble a journal before commit.

3. **Core write flow**
   - A caller creates an `Entry`, adds debits and credits, then commits it through the `Book`.
   - The commit path validates accounting invariants, especially that the journal balances to zero.
   - On success, Medici writes a **journal document** plus its child **transaction documents**.

4. **Persistence model**
   - The main MongoDB-backed entities are modeled in `src/models/`: `journal`, `transaction`, `balance`, and `lock`.
   - Journals store the high-level event metadata; transactions store account-level lines.
   - Key journal fields are duplicated onto transactions so most reads can avoid populating/joining the journal collection.

5. **Read/query flow**
   - Balance and ledger queries go through parsing helpers under `src/helper/parse/`.
   - Query input is split into:
     - structural fields like account, date range, and journal references
     - arbitrary metadata filters
   - The parser uses the transaction schema to decide whether a field belongs at the top level or inside `meta`.

6. **Balance caching subsystem**
   - `.balance()` can use a snapshot cache stored in the `medici_balances` collection.
   - The flow is: find the latest snapshot, aggregate only newer transactions, then combine the two results.
   - This cache is time-based and TTL-backed, so it is a distinct subsystem from the canonical ledger data.

7. **Consistency and concurrency**
   - The repo supports MongoDB sessions and ACID-style transactions via `mongoTransaction`.
   - A lock model and `writelockAccounts()` are used to make balance checks reliable inside a transaction.
   - This is the main boundary between ordinary reads/writes and stronger consistency guarantees.

8. **Voiding and reversal logic**
   - Voiding does not delete history. Instead, the original journal is marked voided and an equal/opposite reversing journal is created.
   - `handleVoidMemo` and related helpers manage default void memo behavior and propagation of void metadata.
   - This keeps the ledger auditable and preserves accounting integrity.

9. **Schema customization and index management**
   - The library supports replacing the default journal/transaction schemas with custom Mongoose schemas.
   - `setTransactionSchema`, `setJournalSchema`, `initModels`, and `syncIndexes` coordinate model initialization and index enforcement.
   - `extractObjectIdKeysFromSchema` and index helpers exist so custom schema fields still participate correctly in querying and performance tuning.

10. **Safety and data-shaping helpers**
   - Helpers such as `flattenObject`, `safeSetKeyToMetaObject`, `isPrototypeAttribute`, and `addReversedTransactions` protect against prototype pollution and normalize user input into Mongo-friendly shapes.
   - The codebase is deliberately defensive because user-supplied account names, metadata, and query filters all influence persistence and read paths.

11. **Error boundary**
   - Domain-specific failures are isolated under `src/errors/`.
   - Errors distinguish constructor/validation problems, missing journals, invalid account paths, consistency failures, and void-related conflicts.
   - This gives the architecture a clear separation between normal application behavior and ledger invariant violations.

12. **Operational/tooling layer**
   - The repo is TypeScript-first, tested with spec files under `spec/`, and benchmarked with scripts under `bench/`.
   - CI workflows and lint/type configs are present, but they support the library rather than define runtime behavior.
   - The external dependency that materially shapes the architecture is MongoDB via Mongoose, with some operations intentionally using the lower-level MongoDB driver semantics for transactions and consistency.

Main entry points: [`src/Book.ts`](https://github.com/flash-oss/medici/blob/master/src/Book.ts) (Book), [`src/models/transaction.ts`](https://github.com/flash-oss/medici/blob/master/src/models/transaction.ts) (Transaction), [`src/errors/MediciError.ts`](https://github.com/flash-oss/medici/blob/master/src/errors/MediciError.ts) (Medici Error), [`src/index.ts`](https://github.com/flash-oss/medici/blob/master/src/index.ts) (Index)

## Diagram (Mermaid)

```mermaid
flowchart TD

subgraph group_api["Public API"]
  node_src_index["Index<br/>exports<br/>[index.ts]"]
end

subgraph group_core["Ledger Core"]
  node_book["Book<br/>ledger façade<br/>[Book.ts]"]
  node_entry["Entry<br/>journal builder<br/>[Entry.ts]"]
end

subgraph group_persistence["Mongo Models"]
  node_journal_model[("Journal<br/>[journal.ts]")]
  node_transaction_model[("Transaction<br/>[transaction.ts]")]
  node_balance_model[("Balance<br/>snapshot model<br/>[balance.ts]")]
  node_lock_model[("Lock<br/>[lock.ts]")]
end

subgraph group_query["Read Path"]
  node_parse_balance["Balance Parse<br/>query parser"]
  node_parse_filter["Filter Parse<br/>query parser"]
  node_parse_account["Account Parse<br/>field parser"]
end

subgraph group_consistency["Consistency"]
  node_mongo_transaction["Mongo Tx<br/>session helper"]
  node_writelock["Write Lock<br/>locking helper"]
  node_void_helper["Void Memo<br/>void helper<br/>[handleVoidMemo.ts]"]
  node_reversed_tx["Reverse Tx<br/>reversal helper"]
end

subgraph group_helpers["Helpers"]
  node_init_models["Init Models<br/>model setup<br/>[initModels.ts]"]
  node_sync_indexes["Sync Indexes<br/>index helper<br/>[syncIndexes.ts]"]
  node_schema_extract["ObjectId Keys<br/>schema helper"]
  node_flatten["Flatten<br/>shape helper<br/>[flattenObject.ts]"]
  node_safe_meta["Safe Meta<br/>input guard"]
end

subgraph group_errors["Errors"]
  node_medici_error["Medici Error<br/>base error<br/>[MediciError.ts]"]
  node_journal_nf["Not Found<br/>domain error"]
  node_consistency_err["Consistency<br/>domain error"]
  node_account_err["Account Path<br/>domain error"]
  node_void_err["Voided Journal<br/>domain error"]
  node_tx_err["Transaction<br/>domain error"]
end

node_src_index -->|"exports"| node_book
node_src_index -->|"exports"| node_entry
node_src_index -->|"exports"| node_mongo_transaction
node_src_index -->|"exports"| node_init_models
node_src_index -->|"exports"| node_sync_indexes
node_src_index -->|"exports"| node_medici_error
node_book -->|"builds"| node_entry
node_book -->|"writes"| node_journal_model
node_book -->|"writes"| node_transaction_model
node_book -->|"throws"| node_consistency_err
node_entry -->|"uses"| node_parse_filter
node_book -->|"uses"| node_parse_balance
node_book -->|"uses"| node_parse_filter
node_book -->|"uses"| node_parse_account
node_book -->|"wraps"| node_mongo_transaction
node_book -->|"coordinates"| node_writelock
node_book -->|"voids"| node_void_helper
node_book -->|"voids"| node_reversed_tx
node_book -->|"throws"| node_journal_nf
node_book -->|"throws"| node_void_err
node_parse_balance -->|"reads"| node_balance_model
node_parse_filter -->|"targets"| node_transaction_model
node_parse_account -->|"targets"| node_transaction_model
node_balance_model -->|"aggregates"| node_transaction_model
node_balance_model -.->|"references"| node_journal_model
node_mongo_transaction -->|"uses"| node_lock_model
node_mongo_transaction -.->|"wraps"| node_medici_error
node_void_helper -->|"feeds"| node_reversed_tx
node_init_models -->|"binds"| node_journal_model
node_init_models -->|"binds"| node_transaction_model
node_init_models -->|"binds"| node_balance_model
node_init_models -->|"binds"| node_lock_model
node_sync_indexes -->|"syncs"| node_journal_model
node_sync_indexes -->|"syncs"| node_transaction_model
node_schema_extract -->|"supports"| node_transaction_model
node_flatten -->|"supports"| node_safe_meta
node_safe_meta -->|"protects"| node_transaction_model
node_medici_error -->|"base"| node_consistency_err
node_medici_error -->|"base"| node_account_err
node_medici_error -->|"base"| node_tx_err
node_medici_error -->|"base"| node_journal_nf
node_medici_error -->|"base"| node_void_err

click node_src_index "https://github.com/flash-oss/medici/blob/master/src/index.ts"
click node_book "https://github.com/flash-oss/medici/blob/master/src/Book.ts"
click node_entry "https://github.com/flash-oss/medici/blob/master/src/Entry.ts"
click node_journal_model "https://github.com/flash-oss/medici/blob/master/src/models/journal.ts"
click node_transaction_model "https://github.com/flash-oss/medici/blob/master/src/models/transaction.ts"
click node_balance_model "https://github.com/flash-oss/medici/blob/master/src/models/balance.ts"
click node_lock_model "https://github.com/flash-oss/medici/blob/master/src/models/lock.ts"
click node_parse_balance "https://github.com/flash-oss/medici/blob/master/src/helper/parse/parseBalanceQuery.ts"
click node_parse_filter "https://github.com/flash-oss/medici/blob/master/src/helper/parse/parseFilterQuery.ts"
click node_parse_account "https://github.com/flash-oss/medici/blob/master/src/helper/parse/parseAccountField.ts"
click node_mongo_transaction "https://github.com/flash-oss/medici/blob/master/src/helper/mongoTransaction.ts"
click node_void_helper "https://github.com/flash-oss/medici/blob/master/src/helper/handleVoidMemo.ts"
click node_reversed_tx "https://github.com/flash-oss/medici/blob/master/src/helper/addReversedTransactions.ts"
click node_init_models "https://github.com/flash-oss/medici/blob/master/src/helper/initModels.ts"
click node_sync_indexes "https://github.com/flash-oss/medici/blob/master/src/helper/syncIndexes.ts"
click node_schema_extract "https://github.com/flash-oss/medici/blob/master/src/helper/extractObjectIdKeysFromSchema.ts"
click node_flatten "https://github.com/flash-oss/medici/blob/master/src/helper/flattenObject.ts"
click node_safe_meta "https://github.com/flash-oss/medici/blob/master/src/helper/safeSetKeyToMetaObject.ts"
click node_medici_error "https://github.com/flash-oss/medici/blob/master/src/errors/MediciError.ts"
click node_journal_nf "https://github.com/flash-oss/medici/blob/master/src/errors/JournalNotFoundError.ts"
click node_consistency_err "https://github.com/flash-oss/medici/blob/master/src/errors/ConsistencyError.ts"
click node_account_err "https://github.com/flash-oss/medici/blob/master/src/errors/InvalidAccountPathLengthError.ts"
click node_void_err "https://github.com/flash-oss/medici/blob/master/src/errors/JournalAlreadyVoidedError.ts"
click node_tx_err "https://github.com/flash-oss/medici/blob/master/src/errors/TransactionError.ts"

classDef toneNeutral fill:#f8fafc,stroke:#334155,stroke-width:1.5px,color:#0f172a
classDef toneBlue fill:#dbeafe,stroke:#2563eb,stroke-width:1.5px,color:#172554
classDef toneAmber fill:#fef3c7,stroke:#d97706,stroke-width:1.5px,color:#78350f
classDef toneMint fill:#dcfce7,stroke:#16a34a,stroke-width:1.5px,color:#14532d
classDef toneRose fill:#ffe4e6,stroke:#e11d48,stroke-width:1.5px,color:#881337
classDef toneIndigo fill:#e0e7ff,stroke:#4f46e5,stroke-width:1.5px,color:#312e81
classDef toneTeal fill:#ccfbf1,stroke:#0f766e,stroke-width:1.5px,color:#134e4a
class node_src_index,node_medici_error,node_journal_nf,node_consistency_err,node_account_err,node_void_err,node_tx_err toneBlue
class node_book,node_entry toneAmber
class node_journal_model,node_transaction_model,node_balance_model,node_lock_model toneMint
class node_parse_balance,node_parse_filter,node_parse_account toneRose
class node_mongo_transaction,node_writelock,node_void_helper,node_reversed_tx toneIndigo
class node_init_models,node_sync_indexes,node_schema_extract,node_flatten,node_safe_meta toneTeal
```

## Components

### Public API

Primary entry points exposed to library consumers.

- [Index](https://github.com/flash-oss/medici/blob/master/src/index.ts): exports · Package surface exporting the library entry points. · `src/index.ts`

### Ledger Core

Book and entry flow for composing and committing journals.

- [Book](https://github.com/flash-oss/medici/blob/master/src/Book.ts): ledger façade · Main façade for ledger operations on a named book. · `src/Book.ts`
- [Entry](https://github.com/flash-oss/medici/blob/master/src/Entry.ts): journal builder · Fluent builder used to assemble balanced ledger entries before commit. · `src/Entry.ts`

### Mongo Models

Canonical collections and model wiring for ledger data.

- [Journal](https://github.com/flash-oss/medici/blob/master/src/models/journal.ts): journal model · High-level journal records with event metadata and void state. · `src/models/journal.ts`
- [Transaction](https://github.com/flash-oss/medici/blob/master/src/models/transaction.ts): transaction model · Account-level ledger lines; duplicates key journal fields for read efficiency. · `src/models/transaction.ts`
- [Balance](https://github.com/flash-oss/medici/blob/master/src/models/balance.ts): snapshot model · Cached balance snapshots stored for fast balance queries. · `src/models/balance.ts`
- [Lock](https://github.com/flash-oss/medici/blob/master/src/models/lock.ts): lock model · Lock records used to coordinate stronger consistency during writes. · `src/models/lock.ts`

### Read Path

Query parsing and balance computation, including cache use.

- [Balance Parse](https://github.com/flash-oss/medici/blob/master/src/helper/parse/parseBalanceQuery.ts): query parser · Splits balance query input into structural fields and metadata filters. · `src/helper/parse/parseBalanceQuery.ts`
- [Filter Parse](https://github.com/flash-oss/medici/blob/master/src/helper/parse/parseFilterQuery.ts): query parser · Normalizes arbitrary filter conditions for ledger and balance lookups. · `src/helper/parse/parseFilterQuery.ts`
- [Account Parse](https://github.com/flash-oss/medici/blob/master/src/helper/parse/parseAccountField.ts): field parser · Resolves account-related query fields and boundaries. · `src/helper/parse/parseAccountField.ts`

### Consistency

Transactions, locking, and void/reversal behavior.

- [Mongo Tx](https://github.com/flash-oss/medici/blob/master/src/helper/mongoTransaction.ts): session helper · Wraps MongoDB session/transaction execution for ACID-style writes. · `src/helper/mongoTransaction.ts`
- **Write Lock**: locking helper · Applies account locks so balance checks stay reliable inside transactions.
- [Void Memo](https://github.com/flash-oss/medici/blob/master/src/helper/handleVoidMemo.ts): void helper · Builds and propagates default void memo and reversal metadata. · `src/helper/handleVoidMemo.ts`
- [Reverse Tx](https://github.com/flash-oss/medici/blob/master/src/helper/addReversedTransactions.ts): reversal helper · Creates opposite transactions for voided journals. · `src/helper/addReversedTransactions.ts`

### Helpers

Shared normalization, schema, and setup utilities.

- [Init Models](https://github.com/flash-oss/medici/blob/master/src/helper/initModels.ts): model setup · Initializes or rebinds Mongoose models for the library. · `src/helper/initModels.ts`
- [Sync Indexes](https://github.com/flash-oss/medici/blob/master/src/helper/syncIndexes.ts): index helper · Coordinates index enforcement across customizable schemas. · `src/helper/syncIndexes.ts`
- [ObjectId Keys](https://github.com/flash-oss/medici/blob/master/src/helper/extractObjectIdKeysFromSchema.ts): schema helper · Finds ObjectId-bearing paths in custom schemas for query/index support. · `src/helper/extractObjectIdKeysFromSchema.ts`
- [Flatten](https://github.com/flash-oss/medici/blob/master/src/helper/flattenObject.ts): shape helper · Flattens nested objects into Mongo-friendly field shapes. · `src/helper/flattenObject.ts`
- [Safe Meta](https://github.com/flash-oss/medici/blob/master/src/helper/safeSetKeyToMetaObject.ts): input guard · Writes metadata defensively while avoiding prototype pollution. · `src/helper/safeSetKeyToMetaObject.ts`

### Errors

Domain-specific failure types.

- [Medici Error](https://github.com/flash-oss/medici/blob/master/src/errors/MediciError.ts): base error · Shared base class for domain errors. · `src/errors/MediciError.ts`
- [Not Found](https://github.com/flash-oss/medici/blob/master/src/errors/JournalNotFoundError.ts): domain error · Raised when a referenced journal cannot be found. · `src/errors/JournalNotFoundError.ts`
- [Consistency](https://github.com/flash-oss/medici/blob/master/src/errors/ConsistencyError.ts): domain error · Raised when balance or write invariants fail. · `src/errors/ConsistencyError.ts`
- [Account Path](https://github.com/flash-oss/medici/blob/master/src/errors/InvalidAccountPathLengthError.ts): domain error · Raised for invalid account path lengths. · `src/errors/InvalidAccountPathLengthError.ts`
- [Voided Journal](https://github.com/flash-oss/medici/blob/master/src/errors/JournalAlreadyVoidedError.ts): domain error · Raised when an already voided journal is voided again. · `src/errors/JournalAlreadyVoidedError.ts`
- [Transaction](https://github.com/flash-oss/medici/blob/master/src/errors/TransactionError.ts): domain error · Raised for transaction-level validation and write failures. · `src/errors/TransactionError.ts`

## Connections

- Index → Book: exports · Public API exports the main ledger façade.
- Index → Entry: exports · Public API exports the journal builder.
- Index → Mongo Tx: exports · Public API exposes transaction wrapper.
- Index → Init Models: exports · Public API exposes model/schema helpers.
- Index → Sync Indexes: exports · Public API exposes index synchronization.
- Index → Medici Error: exports · Public API re-exports error types.
- Book → Entry: builds · Book accepts entries and commits them.
- Book → Journal: writes · Commit path persists journal documents.
- Book → Transaction: writes · Commit path persists transaction lines.
- Book → Consistency: throws · Book enforces accounting and consistency invariants.
- Entry → Filter Parse: uses · Entry and commit flow normalize user-provided fields.
- Book → Balance Parse: uses · Balance queries are parsed before aggregation.
- Book → Filter Parse: uses · Ledger queries are split into structural and meta filters.
- Book → Account Parse: uses · Account-specific query fields are normalized.
- Book → Mongo Tx: wraps · Write operations can run inside MongoDB sessions.
- Book → Write Lock: coordinates · Strong balance checks rely on account locking.
- Book → Void Memo: voids · Voiding flow prepares memo and reversal metadata.
- Book → Reverse Tx: voids · Voiding creates reversing transactions instead of deleting history.
- Book → Not Found: throws · Lookup and void flows can fail when a journal is missing.
- Book → Voided Journal: throws · Voiding an already voided journal is rejected.
- Balance Parse → Balance: reads · Balance query parser drives snapshot and aggregation logic.
- Filter Parse → Transaction: targets · Filter parsing uses transaction schema shape.
- Account Parse → Transaction: targets · Account field parsing depends on transaction schema layout.
- Balance → Transaction: aggregates · Snapshot cache is combined with newer transactions.
- Balance → Journal: references · Balance snapshots are anchored to journal/transaction history.
- Mongo Tx → Lock: uses · Transactional writes can acquire and release locks.
- Mongo Tx → Medici Error: wraps · Transaction wrapper propagates domain failures.
- Void Memo → Reverse Tx: feeds · Void memo handling informs reversal transaction creation.
- Init Models → Journal: binds · Model initialization wires the journal schema.
- Init Models → Transaction: binds · Model initialization wires the transaction schema.
- Init Models → Balance: binds · Model initialization wires the balance cache model.
- Init Models → Lock: binds · Model initialization wires the lock model.
- Sync Indexes → Journal: syncs · Index management enforces journal indexes.
- Sync Indexes → Transaction: syncs · Index management enforces transaction indexes.
- ObjectId Keys → Transaction: supports · Custom schema support needs ObjectId path discovery.
- Flatten → Safe Meta: supports · Flattening and safe metadata shaping work together.
- Safe Meta → Transaction: protects · Metadata normalization feeds persistence safely.
- Medici Error → Consistency: base · Consistency failures derive from the shared error base.
- Medici Error → Account Path: base · Account path validation errors derive from the shared error base.
- Medici Error → Transaction: base · Transaction errors derive from the shared error base.
- Medici Error → Not Found: base · Missing journal errors derive from the shared error base.
- Medici Error → Voided Journal: base · Void conflicts derive from the shared error base.
