# jun-del/wr-audit-logger architecture

> Architecture diagram of the GitHub repository jun-del/wr-audit-logger, generated by GitDiagram from its file tree, README and a sample of source files (last updated 2026-04-06). It is an AI-made overview: check details against the source.

- Interactive diagram: https://gitdiagram.com/jun-del/wr-audit-logger
- Repository: https://github.com/jun-del/wr-audit-logger

## Overview

1. **What this repo is**
   - `wr-audit-logger` is a TypeScript library, not an application.
   - Its architecture sits at the **Drizzle ORM / PostgreSQL boundary**: application code uses a wrapped Drizzle database instance, and the library transparently records audit events for write operations.

2. **Public surface**
   - The main entrypoint is `src/index.ts`.
   - The package exposes:
     - logger creation (`createAuditLogger`)
     - audit table/schema helpers (`createAuditTableSQL`, `createAuditTableSQLFor`, `createAuditLogsTable`)
     - shared types and the default audit table shape
   - The README shows that the primary integration pattern is: create logger → replace `db` with the wrapped version → set per-request context → run normal inserts/updates/deletes.

3. **Core interception layer**
   - `src/core/interceptor.ts` is the main control point.
   - It wraps Drizzle operations so insert/update/delete calls can be observed without manual logging calls.
   - `src/core/AuditLogger.ts` likely orchestrates this wrapper, config, context, and write strategy.
   - `src/core/context.ts` provides request/job-scoped context so the audit record can carry user identity, IP, user agent, metadata, and transaction IDs.

4. **Write-path data flow**
   - The normal application write hits the wrapped DB.
   - The interceptor identifies the operation type and table.
   - Capture modules extract the record identity and payload changes.
   - A normalized audit event is produced.
   - The event is persisted through the storage layer, unless a custom writer is configured.
   - If `strictMode` is off, audit failures are meant to be isolated from the business write; if on, audit failure can fail the main operation.

5. **Capture subsystem**
   - `src/capture/insert.ts`, `update.ts`, and `delete.ts` handle operation-specific extraction logic.
   - This is where the library determines:
     - action type
     - affected table
     - primary key / record ID
     - values to store for the operation
   - The README’s `updateValuesMode` setting implies this layer can emit either changed fields or full row snapshots for updates.
   - The “auto-injected `.returning()`” behavior in the README indicates the capture layer can force row retrieval when the original query did not ask for returned data.

6. **Storage subsystem**
   - `src/storage/schema.ts` and `src/storage/column-map.ts` define the audit table contract and how logical fields map to physical column names.
   - `src/storage/writer.ts` is the default persistence path for a single audit record.
   - `src/storage/batch-writer.ts` and `src/storage/batched-custom-writer.ts` add asynchronous buffering and flush behavior for high-throughput audit logging.
   - This layer is where built-in audit rows are translated into SQL writes against the audit table.

7. **Default schema vs custom storage**
   - The README makes a clear distinction between the built-in writer and `customWriter`.
   - With the built-in writer, the library owns the audit schema contract and expects standard columns like `user_id`, `action`, `table_name`, `record_id`, `values`, `metadata`, and `transaction_id`.
   - With `customWriter`, the library still computes the audit event, but the application takes over final persistence into any shape of table or sink it wants.

8. **Utilities that support correctness**
   - `src/utils/primary-key.ts` resolves record identity from configured primary key fields.
   - `src/utils/serializer.ts` handles stable conversion of values for storage in JSON/SQL-compatible form.
   - `src/utils/migration.ts` supports schema creation/update helpers for the audit table.
   - `src/utils/metadata.ts` and `src/utils/logging.ts` support derived metadata and internal diagnostics.

9. **Type and config boundary**
   - `src/types/config.ts` and `src/types/audit.ts` define the public configuration and audit event shapes.
   - These types reflect the repo’s main extension points:
     - per-table primary key mapping
     - field allowlists / exclusion lists
     - audit table naming and column remapping
     - batching behavior
     - custom writers
   - The types are important because this is a library whose correctness depends heavily on static schema alignment with Drizzle models.

10. **Operational behavior**
   - The library is designed to preserve business transaction semantics while attaching audit context.
   - The README’s transaction example shows that all operations inside a transaction share the same `transaction_id`.
   - Batched mode introduces an async queue/flush boundary: writes can be buffered and flushed later, optionally waiting for persistence before returning.

11. **Testing shape**
   - The test layout suggests strong emphasis on integration with real database behavior:
     - `tests/integration/*` covers automatic audit capture, returning behavior, batch mode, and custom writer flows.
     - `tests/unit/*` covers logger, batching, config, metadata, and SQL edge cases.
   - This indicates the architecture is validated not just by isolated functions but by end-to-end DB interception behavior.

12. **How to draw the architecture**
   - A good diagram would show:
     - application code on the left
     - wrapped Drizzle DB / transaction boundary in the middle
     - interception and capture logic inside the library
     - storage writer or custom writer on the right
     - PostgreSQL audit table as the default sink
     - request/job context feeding into the audit event
   - The key architectural idea is that this library is a **transparent audit pipeline attached to Drizzle writes**, with optional batching and pluggable storage.

Main entry points: [`src/core/AuditLogger.ts`](https://github.com/jun-del/wr-audit-logger/blob/main/src/core/AuditLogger.ts) (Audit Logger), [`src/storage/writer.ts`](https://github.com/jun-del/wr-audit-logger/blob/main/src/storage/writer.ts) (Audit Writer), [`src/types/audit.ts`](https://github.com/jun-del/wr-audit-logger/blob/main/src/types/audit.ts) (Audit Types), [`src/core/interceptor.ts`](https://github.com/jun-del/wr-audit-logger/blob/main/src/core/interceptor.ts) (Interceptor)

## Diagram (Mermaid)

```mermaid
flowchart TD

subgraph group_public["Public API"]
  node_index["API Entry<br/>public entrypoint<br/>[index.ts]"]
  node_config["Config Types<br/>public config<br/>[config.ts]"]
  node_audittypes["Audit Types<br/>audit model<br/>[audit.ts]"]
end

subgraph group_core["Core"]
  node_logger["Audit Logger<br/>orchestrator<br/>[AuditLogger.ts]"]
  node_interceptor["Interceptor<br/>db wrapper<br/>[interceptor.ts]"]
  node_context["Request Context<br/>scoped state<br/>[context.ts]"]
end

subgraph group_capture["Capture"]
  node_insertcap["Insert Capture<br/>capture step<br/>[insert.ts]"]
  node_updatecap["Update Capture<br/>capture step<br/>[update.ts]"]
  node_deletecap["Delete Capture<br/>capture step<br/>[delete.ts]"]
end

subgraph group_storage["Storage"]
  node_writer["Audit Writer<br/>default sink<br/>[writer.ts]"]
  node_batchwriter["Batch Writer<br/>buffered sink<br/>[batch-writer.ts]"]
  node_customwriter["Custom Writer<br/>pluggable sink"]
  node_schema[("Audit Schema<br/>table contract<br/>[schema.ts]")]
  node_colmap["Column Map<br/>field mapping<br/>[column-map.ts]"]
end

subgraph group_utils["Utils"]
  node_pk["Primary Key<br/>identity helper<br/>[primary-key.ts]"]
  node_serializer["Serializer<br/>value helper<br/>[serializer.ts]"]
  node_migration["Migration Helpers<br/>schema helper<br/>[migration.ts]"]
  node_metadata["Metadata Helpers<br/>support helper<br/>[metadata.ts]"]
end

subgraph group_tests["Tests"]
  node_tests_integration["Integration Tests<br/>test suite"]
  node_tests_unit["Unit Tests<br/>test suite"]
end

node_consumer["Consumer App<br/>external client"]

node_consumer -->|"uses API"| node_index
node_index -->|"re-exports"| node_config
node_index -->|"re-exports"| node_audittypes
node_index -->|"creates"| node_logger
node_logger -->|"wraps db"| node_interceptor
node_logger -->|"attaches"| node_context
node_logger -->|"default sink"| node_writer
node_logger -->|"optional batching"| node_batchwriter
node_logger -->|"pluggable sink"| node_customwriter
node_interceptor -->|"detects"| node_insertcap
node_interceptor -->|"detects"| node_updatecap
node_interceptor -->|"detects"| node_deletecap
node_insertcap -->|"resolves id"| node_pk
node_updatecap -->|"resolves id"| node_pk
node_deletecap -->|"resolves id"| node_pk
node_insertcap -->|"normalizes"| node_serializer
node_updatecap -->|"normalizes"| node_serializer
node_deletecap -->|"normalizes"| node_serializer
node_insertcap -->|"emits"| node_audittypes
node_updatecap -->|"emits"| node_audittypes
node_deletecap -->|"emits"| node_audittypes
node_writer -->|"writes to"| node_schema
node_writer -->|"maps fields"| node_colmap
node_writer -->|"supports"| node_migration
node_batchwriter -->|"flushes to"| node_writer
node_batchwriter -->|"buffers for"| node_customwriter
node_schema -->|"defines"| node_migration
node_context -->|"enriches"| node_audittypes
node_metadata -->|"enriches"| node_audittypes
node_tests_integration -->|"verifies"| node_interceptor
node_tests_integration -->|"verifies"| node_writer
node_tests_integration -->|"verifies"| node_batchwriter
node_tests_integration -->|"verifies"| node_customwriter
node_tests_unit -->|"verifies"| node_logger
node_tests_unit -->|"verifies"| node_serializer

click node_index "https://github.com/jun-del/wr-audit-logger/blob/main/src/index.ts"
click node_config "https://github.com/jun-del/wr-audit-logger/blob/main/src/types/config.ts"
click node_audittypes "https://github.com/jun-del/wr-audit-logger/blob/main/src/types/audit.ts"
click node_logger "https://github.com/jun-del/wr-audit-logger/blob/main/src/core/AuditLogger.ts"
click node_interceptor "https://github.com/jun-del/wr-audit-logger/blob/main/src/core/interceptor.ts"
click node_context "https://github.com/jun-del/wr-audit-logger/blob/main/src/core/context.ts"
click node_insertcap "https://github.com/jun-del/wr-audit-logger/blob/main/src/capture/insert.ts"
click node_updatecap "https://github.com/jun-del/wr-audit-logger/blob/main/src/capture/update.ts"
click node_deletecap "https://github.com/jun-del/wr-audit-logger/blob/main/src/capture/delete.ts"
click node_pk "https://github.com/jun-del/wr-audit-logger/blob/main/src/utils/primary-key.ts"
click node_serializer "https://github.com/jun-del/wr-audit-logger/blob/main/src/utils/serializer.ts"
click node_writer "https://github.com/jun-del/wr-audit-logger/blob/main/src/storage/writer.ts"
click node_batchwriter "https://github.com/jun-del/wr-audit-logger/blob/main/src/storage/batch-writer.ts"
click node_customwriter "https://github.com/jun-del/wr-audit-logger/blob/main/src/storage/batched-custom-writer.ts"
click node_schema "https://github.com/jun-del/wr-audit-logger/blob/main/src/storage/schema.ts"
click node_colmap "https://github.com/jun-del/wr-audit-logger/blob/main/src/storage/column-map.ts"
click node_migration "https://github.com/jun-del/wr-audit-logger/blob/main/src/utils/migration.ts"
click node_metadata "https://github.com/jun-del/wr-audit-logger/blob/main/src/utils/metadata.ts"
click node_tests_integration "https://github.com/jun-del/wr-audit-logger/tree/main/tests/integration"
click node_tests_unit "https://github.com/jun-del/wr-audit-logger/tree/main/tests/unit"

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_index,node_config,node_audittypes toneBlue
class node_logger,node_interceptor,node_context toneAmber
class node_insertcap,node_updatecap,node_deletecap toneMint
class node_writer,node_batchwriter,node_customwriter,node_schema,node_colmap toneRose
class node_pk,node_serializer,node_migration,node_metadata toneIndigo
class node_tests_integration,node_tests_unit toneTeal
class node_consumer toneNeutral
```

## Components

### Public API

Package entrypoints and shared contracts

- [API Entry](https://github.com/jun-del/wr-audit-logger/blob/main/src/index.ts): public entrypoint · Main package exports for logger creation, schema helpers, and shared types · `src/index.ts`
- [Config Types](https://github.com/jun-del/wr-audit-logger/blob/main/src/types/config.ts): public config · Logger options, batching, custom writer, and table mapping settings · `src/types/config.ts`
- [Audit Types](https://github.com/jun-del/wr-audit-logger/blob/main/src/types/audit.ts): audit model · Normalized audit event shape and default table contract · `src/types/audit.ts`

### Core

Drizzle interception and orchestration

- [Audit Logger](https://github.com/jun-del/wr-audit-logger/blob/main/src/core/AuditLogger.ts): orchestrator · Builds the wrapped database, coordinates context, capture, and write strategy · `src/core/AuditLogger.ts`
- [Interceptor](https://github.com/jun-del/wr-audit-logger/blob/main/src/core/interceptor.ts): db wrapper · Hooks Drizzle insert, update, and delete operations transparently · `src/core/interceptor.ts`
- [Request Context](https://github.com/jun-del/wr-audit-logger/blob/main/src/core/context.ts): scoped state · Carries user, request, transaction, and metadata into audit events · `src/core/context.ts`

### Capture

Operation-specific write extraction

- [Insert Capture](https://github.com/jun-del/wr-audit-logger/blob/main/src/capture/insert.ts): capture step · Extracts insert action, table, identity, and row payload · `src/capture/insert.ts`
- [Update Capture](https://github.com/jun-del/wr-audit-logger/blob/main/src/capture/update.ts): capture step · Extracts update action and either changed fields or row snapshots · `src/capture/update.ts`
- [Delete Capture](https://github.com/jun-del/wr-audit-logger/blob/main/src/capture/delete.ts): capture step · Extracts delete action and record identity · `src/capture/delete.ts`

### Storage

Default audit persistence and batching

- [Audit Writer](https://github.com/jun-del/wr-audit-logger/blob/main/src/storage/writer.ts): default sink · Persists a single audit row into the built-in audit table · `src/storage/writer.ts`
- [Batch Writer](https://github.com/jun-del/wr-audit-logger/blob/main/src/storage/batch-writer.ts): buffered sink · Buffers audit rows and flushes them asynchronously or on demand · `src/storage/batch-writer.ts`
- [Custom Writer](https://github.com/jun-del/wr-audit-logger/blob/main/src/storage/batched-custom-writer.ts): pluggable sink · Application-defined persistence path for audit events · `src/storage/batched-custom-writer.ts`
- [Audit Schema](https://github.com/jun-del/wr-audit-logger/blob/main/src/storage/schema.ts): table contract · Default audit table shape and SQL helpers · `src/storage/schema.ts`
- [Column Map](https://github.com/jun-del/wr-audit-logger/blob/main/src/storage/column-map.ts): field mapping · Maps logical audit fields onto physical column names · `src/storage/column-map.ts`

### Utils

Helpers for identity, serialization, and migration

- [Primary Key](https://github.com/jun-del/wr-audit-logger/blob/main/src/utils/primary-key.ts): identity helper · Resolves record identity from configured primary key fields · `src/utils/primary-key.ts`
- [Serializer](https://github.com/jun-del/wr-audit-logger/blob/main/src/utils/serializer.ts): value helper · Normalizes values for JSON and SQL-safe storage · `src/utils/serializer.ts`
- [Migration Helpers](https://github.com/jun-del/wr-audit-logger/blob/main/src/utils/migration.ts): schema helper · Creates or updates the audit table schema · `src/utils/migration.ts`
- [Metadata Helpers](https://github.com/jun-del/wr-audit-logger/blob/main/src/utils/metadata.ts): support helper · Derived metadata and internal diagnostics support · `src/utils/metadata.ts`

### Tests

Integration and unit coverage

- [Integration Tests](https://github.com/jun-del/wr-audit-logger/tree/main/tests/integration): test suite · End-to-end capture, returning, batching, and custom writer coverage · `tests/integration`
- [Unit Tests](https://github.com/jun-del/wr-audit-logger/tree/main/tests/unit): test suite · Logger, batching, config, metadata, and SQL edge cases · `tests/unit`

### Other components

- **Consumer App**: external client · Application code that uses the wrapped Drizzle database

## Connections

- Consumer App → API Entry: uses API · Application imports logger creation and helper exports
- API Entry → Config Types: re-exports · Exposes public configuration types
- API Entry → Audit Types: re-exports · Exposes audit event and schema types
- API Entry → Audit Logger: creates · Primary entrypoint constructs the audit logger
- Audit Logger → Interceptor: wraps db · Builds the Drizzle interception layer
- Audit Logger → Request Context: attaches · Supplies request and transaction context to writes
- Audit Logger → Audit Writer: default sink · Uses built-in persistence when custom writer is absent
- Audit Logger → Batch Writer: optional batching · Can buffer audit writes for throughput
- Audit Logger → Custom Writer: pluggable sink · Can delegate persistence to application code
- Interceptor → Insert Capture: detects · Routes insert operations to capture logic
- Interceptor → Update Capture: detects · Routes update operations to capture logic
- Interceptor → Delete Capture: detects · Routes delete operations to capture logic
- Insert Capture → Primary Key: resolves id · Derives record identity for insert auditing
- Update Capture → Primary Key: resolves id · Derives record identity for update auditing
- Delete Capture → Primary Key: resolves id · Derives record identity for delete auditing
- Insert Capture → Serializer: normalizes · Serializes captured values for storage
- Update Capture → Serializer: normalizes · Serializes changed fields or snapshots
- Delete Capture → Serializer: normalizes · Serializes delete payload data
- Insert Capture → Audit Types: emits · Produces normalized audit events
- Update Capture → Audit Types: emits · Produces normalized audit events
- Delete Capture → Audit Types: emits · Produces normalized audit events
- Audit Writer → Audit Schema: writes to · Persists audit rows into the default audit table
- Audit Writer → Column Map: maps fields · Translates logical audit fields to table columns
- Audit Writer → Migration Helpers: supports · Works with schema creation and update helpers
- Batch Writer → Audit Writer: flushes to · Batched mode eventually uses the default writer path
- Batch Writer → Custom Writer: buffers for · Buffered writes can target a custom sink
- Audit Schema → Migration Helpers: defines · Schema contract feeds table creation helpers
- Request Context → Audit Types: enriches · Context fields are attached to audit events
- Metadata Helpers → Audit Types: enriches · Derived metadata is included in audit payloads
- Integration Tests → Interceptor: verifies · Covers transparent interception behavior
- Integration Tests → Audit Writer: verifies · Covers built-in persistence flows
- Integration Tests → Batch Writer: verifies · Covers buffered and async flush behavior
- Integration Tests → Custom Writer: verifies · Covers pluggable writer flows
- Unit Tests → Audit Logger: verifies · Covers orchestration and config edges
- Unit Tests → Serializer: verifies · Covers value normalization cases
