# mod

**Modular Open Design** — all the building blocks you need for your project, and for every project you start next: a plug-and-play set of stable, headless, swappable TypeScript packages, installed à la carte to build new apps fast.

`mod` is a pnpm/turbo monorepo for reusable application primitives. The packages here are meant to be installed à la carte by new apps, not adopted as a framework. Each package gives an app one focused backend capability through a typed API that stays stable while the implementation underneath can be optimized, replaced, or wired to a different provider.

**The goal:** a free and open-source, host-agnostic application boilerplate that any project can build on — running on serverless edge, a self-hosted Node server, a container, or anywhere else, with whatever framework, provider, and validation library the adopting project already uses. Every package is designed for an unknown adopter on an unknown host, so its public API is treated as a stable, semver-grade contract shaped to the standard interface for that capability, and no host, framework, provider, or validation library is ever imposed or bundled — each stays behind a swappable adapter.

That unknown adopter is increasingly an AI agent, not only a human, so the project is built to be developed with and operated by agents. Every capability is discoverable and callable from its types, its generated declarations, and a machine-readable manifest of exports — no source-reading required — with typed inputs, outputs, and errors, uniform packaging across modules, and a behavioral test per export that doubles as a usage example. The aim is that an agent which has learned one package can adopt and wire any of them.

The operating principle is simple:

> Be lazy in the implementation, strict at the contract.

Inside a package, keep code direct. At the public API, treat the boundary as product surface: typed inputs and outputs, explicit errors, no hidden framework dependency, no bundled provider SDK unless it is the point of the adapter, and behavior that stays predictable under fallback and edge inputs.

## Why Not Another Bloated Library

Most application libraries ask the host app to accept their stack: their router shape, their client runtime, their provider SDK, their build assumptions, and their upgrade path. `mod` moves the other way. Each package is a narrow, headless primitive that can be adopted without turning the consuming app into a framework migration.

- **Edge-first without edge lock-in:** server-facing modules use web-standard `Request`/`Response`, explicit runtime boundaries, and no import-time side effects.
- **Install only what you need:** packages install à la carte, so `uploads`, `ledger`, `search`, `seo`, `billing`, `realtime`, or `helpdesk` can land independently.
- **Provider SDKs stay behind adapters:** integrations can be swapped or optimized without leaking vendor clients through the public API.
- **Frameworks stay optional:** React overlays live in sibling packages such as `i18n-react` and `realtime-react`; core modules remain headless TypeScript.
- **Small dependencies by default:** foundation modules keep zero or near-zero runtime dependencies, and packages keep peers external instead of smuggling a second platform into the app.
- **Boilerplate without the trap:** start a new app with production-shaped backend modules, then swap providers, frameworks, or host policy without rewriting the app around a giant kit.

## The Floor

`mod` is minimal above the line, not below it. Packages avoid framework weight, hidden runtimes, and broad dependency trees, but they do not skip the parts that make backend code dependable in a real app.

Every module is built around baseline product guarantees:

- **clear inputs:** modules fail predictably when they receive bad or incomplete data;
- **graceful fallbacks:** optional providers, missing data, and unavailable host features have defined behavior;
- **safe write paths:** retries, duplicate requests, destructive actions, and partial failures are handled deliberately;
- **security by default:** auth, sessions, webhooks, uploads, and money-adjacent flows keep trust checks close to the module;
- **accessible overlays:** UI-facing packages include accessible behavior instead of making each app rediscover it;
- **hardened critical flows:** payment, refund, webhook, session, and password logic preserves known-good protections.

The result is a small surface area with serious defaults: enough structure to reuse safely, not enough structure to take over the app.

## What You Can Build With It

`mod` packages cover common backend capabilities without making every app carry the whole stack:

- account and tenant foundations with `auth` and `tenancy`;
- operational jobs and messaging with `jobs`, `mail`, and `notifications`;
- product and commerce flows with `billing`, `ledger`, `tax`, and future composites;
- app content features with `uploads`, `search`, `seo`, `ai`, and `realtime`;
- user-facing overlays with optional React packages where UI integration is useful.

Server-facing modules are designed for constrained edge and serverless runtimes, so they use web-standard `Request`/`Response`, keep provider SDKs behind adapters, and avoid import-time side effects.

## Module Layers

The platform is organized bottom-up. Higher layers do not get built before their dependencies exist.

| Layer | Role | Examples |
| --- | --- | --- |
| L0 | Foundation with zero or near-zero runtime dependencies | `@platform-modules/util`, `@platform-modules/db`, `@platform-modules/i18n` |
| L1 | Core infrastructure | `@platform-modules/jobs`, `@platform-modules/mail`, `@platform-modules/auth`, `@platform-modules/tenancy` |
| L2 | Domain primitives | `@platform-modules/ledger`, `@platform-modules/tax`, `@platform-modules/uploads`, `@platform-modules/notifications`, `@platform-modules/search`, `@platform-modules/seo`, `@platform-modules/ai`, `@platform-modules/realtime`, `@platform-modules/billing`, `@platform-modules/audit` |
| L3 | Composite bolt-ons | `@platform-modules/marketing`, `@platform-modules/helpdesk` |
| Sibling overlays | Framework-specific integrations for headless core packages | `@platform-modules/i18n-react`, `@platform-modules/realtime-react` |

Some capabilities deliberately do not become packages. If a package would only move complexity around instead of making apps simpler, it stays as host code, a smaller utility, or a documented pattern.

## Package Families

The platform is assembled from package families that can be adopted independently:

- foundations: `util`, `db`, `i18n`;
- infrastructure: `jobs`, `mail`, `auth`, `tenancy`;
- domain primitives: `ledger`, `tax`, `uploads`, `notifications`, `search`, `seo`, `ai`, `realtime`, `billing`, `audit`;
- overlays and composites: `i18n-react`, `realtime-react`, `marketing`, `helpdesk`.

## Package Catalog

Current packages are versioned at `0.0.1` and ship as independent ESM packages under the `@platform-modules/*` scope.

| Package | Layer | Purpose | Public subpaths |
| --- | --- | --- | --- |
| `@platform-modules/ai` | L2 | Provider-neutral AI execution with fallback, pricing helpers, redaction, and OpenAI-compatible, Anthropic, Google, and mock adapters. | `.`, `openai-compat`, `anthropic`, `google`, `mock`, `pricing`, `redact` |
| `@platform-modules/audit` | L2 | Append-only actor/entity/action audit logging over the database seam, with never-throw write behavior and keyset listing. | `.` |
| `@platform-modules/auth` | L1 | Headless auth seams with custom and Better Auth engines plus OTP email support. | `.`, `engine-custom`, `engine-better-auth`, `otp-email` |
| `@platform-modules/billing` | L2 | Billing orchestration that composes database, jobs, ledger, and tax with Stripe and Sumit adapters. | `.`, `stripe`, `sumit` |
| `@platform-modules/db` | L0 | Database and transaction contracts with Neon HTTP, Neon serverless, postgres.js, and PGlite adapters. | `.`, `neon-http`, `neon-serverless`, `postgres-js`, `pglite` |
| `@platform-modules/helpdesk` | L3 | Polymorphic support cases, state transitions, and SLA-ready helpdesk primitives over the database seam. | `.` |
| `@platform-modules/i18n` | L0 | Locale dictionaries, directionality, formatting, pluralization, routing, loaders, localized picking, and zod helpers. | `.`, `rtl`, `format`, `plural`, `routing`, `loader`, `pick`, `zod` |
| `@platform-modules/i18n-react` | Sibling | React provider, hooks, language switcher behavior, and store integration for the headless i18n package. | `.`, `store` |
| `@platform-modules/jobs` | L1 | Job envelopes, handler registry, retry/ack behavior, and queue/outbox/database/Durable Object runners. | `.`, `cf-queues`, `db-poll`, `outbox`, `do-runner` |
| `@platform-modules/ledger` | L2 | Append-only ledger entries, guarded debits, balance reads, vesting, lifetime, and balance-after helpers. | `.`, `vesting`, `lifetime`, `balance-after` |
| `@platform-modules/mail` | L1 | Message creation, validation, rendering, and provider adapters for Resend, SES, Postmark, and Brevo. | `.`, `resend`, `ses`, `postmark`, `brevo` |
| `@platform-modules/marketing` | L3 | Campaign and lifecycle marketing primitives with self-managed and Brevo paths, segments, scheduling, and automation. | `.`, `self-managed`, `brevo`, `segments`, `scheduling`, `automation` |
| `@platform-modules/notifications` | L2 | Notification routing with host-provided preference/dedup seams plus email and web-push adapters. | `.`, `email`, `webpush` |
| `@platform-modules/realtime` | L2 | Browser-safe realtime contracts plus Workers server helpers for channels, publishing, and queue consumption. | `.`, `server` |
| `@platform-modules/realtime-react` | Sibling | React hooks and components for consuming the headless realtime package. | `.` |
| `@platform-modules/search` | L2 | Federated search seam for host-registered entity query functions, backed by database and FTS utilities. | `.` |
| `@platform-modules/seo` | L2 | SEO primitives for JSON-LD, sitemaps, crawl gates, canonical URLs, hreflang, and robots output. | `.`, `jsonld`, `sitemap`, `gate`, `canonical`, `hreflang`, `robots` |
| `@platform-modules/tax` | L2 | VAT rates table and helpers for applying and extracting tax. | `rates-table` |
| `@platform-modules/tenancy` | L1 | Tenant membership, RBAC, and database isolation adapters for row-level or foreign-key scoped access. | `.`, `rbac-triad`, `rbac-flat`, `isolation-fk`, `isolation-rls` |
| `@platform-modules/uploads` | L2 | Upload validation and limits: magic bytes, image dimensions, size limits, quota, S3-compatible presign, and R2 binding helpers. | `magic-bytes`, `image-dimensions`, `size-limit`, `quota`, `presign-s3compat`, `r2-binding` |
| `@platform-modules/util` | L0 | Shared web-standard utilities for crypto, tokens, passwords, dates, time zones, and full-text-search safety. | `.`, `crypto`, `tokens`, `password`, `datetime`, `timezone`, `fts/sanitize-tsquery`, `fts/safe-headline`, `fts/rank` |

Registry entries such as `affiliate`, `cache`, and `invoicing` remain WATCH items until they become real packages with stable boundaries.

## From Packages to Products

Packages are the building blocks. Three tiers compose them into something you can ship, and the dependency direction only ever points downward — so each tier stays swappable and nothing reaches back up.

- **Blueprint** — a themeless development base for a whole class of app (for example, a content-driven site, or a SaaS admin). A blueprint wires a chosen set of packages together with routing, layouts, content schemas, and agent skills, but ships **no colors or styling of its own**. You build *with* a blueprint.
- **Distribution** — a themed, installable, self-hostable **product** built on a blueprint: a theme, opinionated defaults, and a setup flow, so it can be installed and run much like a self-hosted application. You *install and run* a Distribution.
- **Instance** — one deployed site or app: a Distribution (or a blueprint) plus its own theme, content, and any project-specific extras.

Reusable code always lives in a package; a blueprint or Distribution is composition and configuration, not a place to hide new libraries. Blueprints and Distributions are emerging as the package set stabilizes — a Distribution graduates into its own repository, depending only on published packages, once the contracts it builds on are stable.

## Development

Install with the pinned package manager:

```sh
pnpm install
```

Common commands:

```sh
pnpm build
pnpm test
pnpm typecheck
pnpm gate
```

Per-package scripts follow the same shape where applicable:

```sh
pnpm --filter @platform-modules/<name> build
pnpm --filter @platform-modules/<name> test
pnpm --filter @platform-modules/<name> typecheck
```

Packages are ESM-only, use `exports` with `types` and `import` conditions, build with `tsup`, and keep runtime peers external. React integration is a separate sibling package such as `@platform-modules/i18n-react`, not a `./react` subpath on the core package.

## Package Discipline

Packages are built to be boring to adopt:

- ESM-only exports with `types` and `import` conditions;
- runtime peers kept external;
- provider SDKs hidden behind adapters;
- React integration shipped as separate sibling packages;
- host apps keep routing, middleware, deployment, and product policy.

## Consuming Packages

The repo is private during build-out and the packages are currently versioned at `0.0.1`; the end goal is a public, open-source release once the contracts stabilize. Consumers usually adopt modules through workspace or local file links until publishing is enabled.

Use the module's documented exports and keep host responsibilities in the host. A module should not own the consumer's middleware chain, framework routing, deployment model, or product policy unless that is explicitly part of the package.
