Skip to main content

CODE PATTERNS

37 reference implementations. Match these shapes when you write.

These aren't suggestions. They're battle-tested shapes that every agent knows how to read. Write your code to match these patterns and the whole team can review, test, and extend it without asking what you meant.

Stark avatarStark
37 patterns|14 with multi-framework tabs|5 domains

WEB

The foundation. Every web app starts here.

api-route.tsAPI Route4 frameworks

Validation, auth, service call, consistent response format.

export async function POST(req: NextRequest) {
  const body = schema.parse(await req.json())
  const result = await service.create(body)
  return NextResponse.json(result)
}
View with framework tabs →
service.tsService4 frameworks

Business logic, ownership checks, typed errors.

export class ProjectService {
  async create(data: CreateInput): Promise<Project> {
    // ownership check, validation, persist
  }
}
View with framework tabs →
component.tsxComponent4 frameworks

Loading, empty, error, success states. Keyboard accessible.

export function ProjectList({ projects }: Props) {
  if (!projects) return <Skeleton />
  if (projects.length === 0) return <Empty />
  return <ul role="list">...</ul>
}
View with framework tabs →
middleware.tsMiddleware4 frameworks

Auth, request logging, rate limiting.

export function withAuth(handler: Handler) {
  return async (req: NextRequest) => {
    const session = await getSession(req)
    if (!session) return unauthorized()
    return handler(req, session)
  }
}
View with framework tabs →
error-handling.tsError Handling4 frameworks

Canonical error strategy — single source of truth.

export class ApiError extends Error {
  constructor(
    public code: ErrorCode,
    message: string,
    public status: number = 500
  ) { super(message) }
}
View with framework tabs →
job-queue.tsJob Queue4 frameworks

Background jobs: idempotency, retry, dead letter queue.

export async function processJob(job: Job) {
  if (await isProcessed(job.id)) return // idempotent
  try { await execute(job) }
  catch { await retry(job) }
}
View with framework tabs →
multi-tenant.tsMulti-Tenant4 frameworks

Workspace scoping, tenant isolation, role-based access.

export function scopedQuery<T>(workspace: string) {
  return db.query<T>()
    .where('workspace_id', workspace)
    // tenant isolation enforced
}
View with framework tabs →
sse-endpoint.tsSSE EndpointNext.js

Server-Sent Events: lifecycle, keepalive, timeout, and React hook.

export function GET(req: NextRequest) {
  const stream = new ReadableStream({
    start(controller) {
      const send = (data: string) =>
        controller.enqueue(`data: ${data}\n\n`)
    }
  })
}
View full pattern →
third-party-script.tsThird-Party ScriptTypeScript

External script loading with 3 states: loading, ready, error.

type ScriptState = 'loading' | 'ready' | 'error';

function loadScript(src: string) {
  const el = document.createElement('script');
  el.onload = () => state = 'ready';
  el.onerror = () => state = 'error';
}
View full pattern →
combobox.tsxCombobox2 frameworks

Accessible combobox with value source management, keyboard nav, async search.

function useCombobox<T>(options: ComboboxOptions<T>) {
  const [isOpen, setIsOpen] = useState(false)
  const [query, setQuery] = useState("")
  // Two value sources: display vs search
}
View with framework tabs →

SYSTEMS

Infrastructure that runs itself.

ad-platform-adapter.tsAd Platform AdapterTypeScript

Split interface: setup (interactive) + runtime adapter + read-only daemon.

interface AdPlatformAdapter {
  createCampaign(config: CampaignConfig): Promise<Campaign>
  getCampaignMetrics(id: string): Promise<Metrics>
  pauseCampaign(id: string): Promise<void>
}
View full pattern →
financial-transaction.tsFinancial TransactionTypeScript

Branded Cents type, hash-chained append log, atomic writes, per-project path resolution.

type Cents = number & { __brand: "cents" };
function toCents(dollars: number): Cents {
  return Math.round(dollars * 100) as Cents;
}
View full pattern →
daemon-process.tsDaemon ProcessTypeScript

PID management, Unix socket API, job scheduler, signal handling, per-project configuration.

class Daemon {
  async start() {
    this.writePid();
    this.startSocket();
    this.scheduleJobs();
    process.on("SIGTERM", () => this.shutdown());
  }
}
View full pattern →
revenue-source-adapter.tsRevenue Source AdapterTypeScript

Read-only revenue interface with Stripe + Paddle reference implementations.

interface RevenueAdapter {
  getTransactions(since: Date): Promise<Transaction[]>
  getBalance(): Promise<Cents>
  getSubscriptionMRR(): Promise<Cents>
}
View full pattern →
oauth-token-lifecycle.tsOAuth Token LifecycleTypeScript

Refresh at 80% TTL, failure escalation, vault integration.

class TokenManager {
  async getToken(): Promise<string> {
    if (this.shouldRefresh()) await this.refresh();
    return this.accessToken;
  }
}
View full pattern →
outbound-rate-limiter.tsOutbound Rate LimiterTypeScript

Token bucket for external API calls with per-platform limits.

class RateLimiter {
  async acquire(): Promise<void> {
    while (this.tokens <= 0) {
      await this.waitForRefill();
    }
    this.tokens--;
  }
}
View full pattern →
database-migration.tsDatabase MigrationTypeScript

Safe migrations: backward-compatible adds, batched ops, rollback.

// Safe column add: nullable first, backfill, constrain
await db.schema.alterTable('users', (t) => {
  t.string('email_verified').nullable();
});
await batchUpdate('users', setDefault);
View full pattern →
data-pipeline.tsData PipelineTypeScript

ETL pipeline: typed stages, checkpoint/resume, quality checks.

const pipeline = new Pipeline([
  extract(source),
  validate(schema),
  transform(normalize),
  load(destination),
]);
await pipeline.run({ checkpoint: true });
View full pattern →
backtest-engine.tsBacktest EngineTypeScript

Walk-forward backtesting: no-lookahead, slippage, metrics.

const engine = new BacktestEngine(strategy);
const result = await engine.run(historicalData, {
  slippage: 0.001,
  commission: 0.0005,
});
console.log(result.sharpeRatio);
View full pattern →
execution-safety.tsExecution SafetyTypeScript

Trading execution: order validation, position limits, paper/live toggle.

const order = validateOrder({
  symbol: 'BTC/USDT',
  side: 'buy',
  size: 0.1,
}, exchangeRules);
await executor.submit(order);
View full pattern →
e2e-test.tsE2E Test2 frameworks

Playwright E2E + axe-core a11y: page objects, auth helpers, network mocks, CWV measurement.

test('homepage loads and is accessible', async ({ page }) => {
  await page.goto('/');
  await expect(page.getByRole('heading')).toBeVisible();
  const results = await new AxeBuilder({ page }).analyze();
  expect(results.violations).toHaveLength(0);
});
View with framework tabs →
browser-review.tsBrowser Review2 frameworks

Browser intelligence: console errors, behavioral walkthroughs, a11y audit, visual inspection.

async function browserReview(page: Page) {
  const errors: string[] = [];
  page.on('console', m => {
    if (m.type() === 'error') errors.push(m.text());
  });
  await page.goto('/');
  return { errors, screenshot: await page.screenshot() };
}
View with framework tabs →
stablecoin-adapter.tsStablecoin Adapter2 frameworks

Stablecoin off-ramp: Circle USDC adapter, transfer lifecycle, settlement.

interface StablecoinAdapter {
  getBalance(): Promise<BalanceCents>;
  initiateOfframp(amount: Cents): Promise<Transfer>;
  getTransferStatus(id: string): Promise<TransferState>;
}
View with framework tabs →
ad-billing-adapter.tsAd Billing Adapter2 frameworks

Ad platform billing: invoice reads, debit tracking, spend projection.

type BillingCapability =
  | 'FULLY_FUNDABLE'
  | 'MONITORED_ONLY'
  | 'UNSUPPORTED';

interface AdBillingAdapter {
  classifyBilling(): Promise<BillingCapability>;
  getInvoices(): Promise<Invoice[]>;
}
View with framework tabs →
funding-plan.tsFunding Plan2 frameworks

Treasury funding pipeline: state machine, policy engine, rebalancing.

type FundingPlanState =
  | 'DRAFT' | 'APPROVED'
  | 'EXECUTING' | 'SETTLED' | 'FAILED';

interface FundingPlan {
  id: string;
  state: FundingPlanState;
  amountCents: Cents;
  reason: string;
}
View with framework tabs →
kongo-integration.tsKongo Integration2 frameworks

Landing page engine: authenticated client, from-PRD page generation, growth signal polling, webhook handlers.

interface KongoClientConfig {
  apiKey: string;     // ke_live_ prefix, vault-sourced
  baseUrl?: string;   // Default: https://kongo.io/api/v1
  rateLimitPerMinute?: number;
}
View with framework tabs →

AI

The intelligence layer.

ai-orchestrator.tsAI OrchestratorTypeScript

Agent loop, tool use, retry, circuit breaker, fallback.

async function agentLoop(messages: Message[]) {
  for (let i = 0; i < MAX_ITERATIONS; i++) {
    const response = await model.complete(messages);
    if (response.stopReason === 'end_turn') return;
    // Execute tool calls, append results
  }
}
View full pattern →
ai-classifier.tsAI ClassifierTypeScript

Classification with confidence thresholds, human fallback.

async function classify(input: string) {
  const { label, confidence } = await model.classify(input);
  if (confidence > 0.9) return autoAct(label);
  if (confidence > 0.7) return softAct(label);
  return humanReview(input);
}
View full pattern →
ai-router.tsAI RouterTypeScript

Intent-based routing with fallback chains.

const intents = ['create_order', 'check_status', 'cancel'] as const;

async function route(input: string) {
  const intent = await detectIntent(input, intents);
  return handlers[intent](input);
}
View full pattern →
prompt-template.tsPrompt TemplateTypeScript

Versioned prompts with variable injection, testing.

const template = new PromptTemplate({
  version: '1.2',
  text: 'Classify this {{category}}: {{input}}',
  variables: ['category', 'input'],
});
View full pattern →
ai-eval.tsAI EvalTypeScript

Golden datasets, scoring, regression detection.

const suite = new EvalSuite('classifier-v2', [
  { input: 'refund please', expected: 'refund' },
  { input: 'where is my order', expected: 'status' },
]);
await suite.run(classifyFn);
View full pattern →
ai-tool-schema.tsAI Tool SchemaTypeScript

Type-safe tool definitions with provider adapters.

const searchTool = defineTool({
  name: 'search',
  description: 'Search the knowledge base',
  parameters: z.object({ query: z.string() }),
  execute: async ({ query }) => search(query),
});
View full pattern →