@contract-kit/ports
v1.0.0
Published
Framework-agnostic port definitions for contract-kit - standardize outbound dependencies like db, mailer, cache
Maintainers
Readme
@contract-kit/ports
Shared port interfaces, provider lifecycle helpers, and test adapters for Contract Kit applications.
Application code depends on ports. Infra and providers implement those ports. This package gives common framework-level ports a stable shape without forcing your app to use a specific database, auth system, logger, queue, or cache.
Install
bun add @contract-kit/portsDefine app ports
import {
createMemoryCache,
createMemoryStorage,
createNoopLogger,
createSystemClock,
createUuidIdGenerator,
definePorts,
} from "@contract-kit/ports";
import { createMemoryMailer } from "@contract-kit/mail";
export const ports = definePorts({
cache: createMemoryCache(),
storage: createMemoryStorage(),
mailer: createMemoryMailer(),
logger: createNoopLogger(),
clock: createSystemClock(),
ids: createUuidIdGenerator(),
});
export type AppPorts = typeof ports;Use PortsContext<AppPorts> when defining app context:
import type { PortsContext } from "@contract-kit/ports";
import type { AppPorts } from "@/ports";
export interface AppContext extends PortsContext<AppPorts> {
requestId: string;
}Core exports
| Export | Purpose |
| --- | --- |
| definePorts(ports) | Typed identity helper for app port wiring |
| PortsContext<P> | Context type helper for objects with ports |
| createProvider(definition) | Define a lifecycle provider that can install ports |
| createPortsBuilder() | Incrementally compose port objects |
| AuthPort | Request authentication boundary |
| CachePort | String cache boundary |
| ClockPort | Deterministic time boundary |
| GatePort | Application authorization boundary |
| IdGeneratorPort | Deterministic id boundary |
| LoggerPort | Structured logging boundary |
| RateLimitPort | Rate limiting boundary |
| EventBusPort | Domain event publish/subscribe boundary |
| JobDispatcherPort | Background job dispatch boundary |
| UnitOfWorkPort<TxPorts> | App-owned transaction boundary |
| StoragePort | Object/file storage boundary |
| MailerPort | Mail sending boundary, re-exported from @contract-kit/mail |
Test adapters
This package includes small in-memory or deterministic adapters for common ports:
import {
createAnonymousAuth,
createFrozenClock,
createMemoryCache,
createMemoryLogger,
createMemoryRateLimiter,
createMemoryStorage,
createNoopUnitOfWork,
createSequenceIdGenerator,
createStaticAuth,
} from "@contract-kit/ports";Use these in tests, examples, and starter apps. Production apps can replace them with first-party providers or app-owned infra adapters without changing use cases.
Storage
Use StoragePort for application workflows that write or read objects such as
exports, imports, attachments, generated PDFs, or uploaded files:
import { createMemoryStorage } from "@contract-kit/ports";
const storage = createMemoryStorage({
publicBaseUrl: "https://cdn.example.com",
});
await storage.put("avatars/user_123.png", avatarBytes, {
contentType: "image/png",
visibility: "public",
metadata: { userId: "user_123" },
});
const object = await storage.get("avatars/user_123.png");
const url = await storage.publicUrl("avatars/user_123.png");Object bodies are one-shot reads: use object.text(), object.bytes(),
object.arrayBuffer(), or object.stream() once per returned object. Storage
keys must be relative object keys with no leading slash, trailing slash,
backslashes, empty path segments, or . / .. path segments.
The memory adapter is intended for tests and pure in-memory examples.
Framework apps should use @contract-kit/provider-storage-local for local
filesystem storage. Production apps can use
@contract-kit/provider-storage-s3 for AWS S3, Cloudflare R2, MinIO, and other
S3-compatible object stores while use cases keep calling ctx.ports.storage.
Authorization gate
Use definePolicy(...) and createGate(...) when repeated authorization rules
need a typed home:
import { createGate, definePolicy, deny } from "@contract-kit/ports";
type AppContext = {
user?: { id: string; role: "admin" | "writer" };
};
type Post = {
authorId: string;
};
const postPolicy = definePolicy({
"posts.update": (ctx: AppContext, post: Post) =>
ctx.user?.id === post.authorId || ctx.user?.role === "admin",
"posts.publish": (ctx: AppContext) => {
if (ctx.user?.role === "admin") return true;
return deny("Only admins can publish posts.");
},
});
const gate = createGate({
policies: [postPolicy],
});
const ctx = { user: { id: "user_1", role: "writer" } } satisfies AppContext;
const requestGate = gate.bind(ctx);
await requestGate.authorize("posts.update", { authorId: "user_1" });Install the gate as a port, then bind it in request context so use cases can
call ctx.gate.authorize(...). Apps can pass onDeny to createGate(...) to
map denied decisions to their own error catalog.
Unit of work
Use UnitOfWorkPort<TxPorts> when a workflow needs a clear transaction
boundary:
import type { UnitOfWorkPort } from "@contract-kit/ports";
type TransactionPorts = {
posts: PostRepository;
};
export type AppPorts = {
posts: PostRepository;
uow: UnitOfWorkPort<TransactionPorts>;
};createNoopUnitOfWork(...) is useful for tests and in-memory adapters. Real
database adapters should bind transaction-scoped repositories to their ORM or
SQL transaction client.
Providers
createProvider(...) defines startup-time adapters that can validate config,
run setup, install ports, and clean up on stop:
import { createNoopLogger, createProvider } from "@contract-kit/ports";
import { z } from "zod";
export const loggerProvider = createProvider({
name: "logger",
config: {
schema: z.object({ LEVEL: z.string().default("info") }),
envPrefix: "LOG_",
},
setup: () => ({
ports: {
logger: createNoopLogger(),
},
}),
});Read next
- Docs site ports guide: https://contract-kit.dev/ports
- Providers: https://contract-kit.dev/providers
- Database and transactions: https://contract-kit.dev/database
License
MIT
