feat: sync ghbot-Nodeloc v1.2.0 capabilities into upstream

Merges all 33 commits from lza6/ghbot-Nodeloc (v1.0.0 through v1.2.0)
while keeping both sides' features in every conflicted file:

- EventRouter dispatch extracted from runReview.ts (7.1), with the
  runtime environment block preserved on the review-start comment
- Unified command ack messages (6.3) combined with the collapsed
  runtime environment block and bot signature on /recheck replies
- Status banner and collapsible unposted findings in review bodies (6.1)
- Centralized runtime directories behind GHBOT_RUNTIME_DIR (D-13);
  webhook knowledge cache now lives under tempRootDirectory()
- Production hardening for merge races, timeouts, webhook ops;
  atomic temp-file rename for R2 cache restores kept from upstream
- Webhook parity retained: triage events gated by WEBHOOK_TRIAGE_ENABLED,
  read-only command guidance, repository knowledge injection,
  runtime environment block on webhook chat replies
- Sanitization/secret redaction centralization, error-aware retry,
  duplicate merge prevention, in-process webhook retries, /metrics
- Infra: eslint/prettier gates with CI verify workflow, docs archives

typecheck, eslint, prettier format:check, and 164 tests all pass.
This commit is contained in:
lezi-fun committed 2026-08-24 11:47:28 +08:00
commit 9e47ab339e
180 files changed
+15130 -1209

No files matched your search

@@ -0,0 +1,616 @@
---
name: nodejs-backend-patterns
description: Build production-ready Node.js backend services with Express/Fastify, implementing middleware patterns, error handling, authentication, database integration, and API design best practices. Use when creating Node.js servers, REST APIs, GraphQL backends, or microservices architectures.
---
# Node.js Backend Patterns
Comprehensive guidance for building scalable, maintainable, and production-ready Node.js backend applications with modern frameworks, architectural patterns, and best practices.
## When to Use This Skill
- Building REST APIs or GraphQL servers
- Creating microservices with Node.js
- Implementing authentication and authorization
- Designing scalable backend architectures
- Setting up middleware and error handling
- Integrating databases (SQL and NoSQL)
- Building real-time applications with WebSockets
- Implementing background job processing
## Core Frameworks
### Express.js - Minimalist Framework
**Basic Setup:**
```typescript
import express, { Request, Response, NextFunction } from "express";
import helmet from "helmet";
import cors from "cors";
import compression from "compression";
const app = express();
// Security middleware
app.use(helmet());
app.use(cors({ origin: process.env.ALLOWED_ORIGINS?.split(",") }));
app.use(compression());
// Body parsing
app.use(express.json({ limit: "10mb" }));
app.use(express.urlencoded({ extended: true, limit: "10mb" }));
// Request logging
app.use((req: Request, res: Response, next: NextFunction) => {
console.log(`${req.method} ${req.path}`);
next();
});
const PORT = process.env.PORT || 3000;
app.listen(PORT, () => {
console.log(`Server running on port ${PORT}`);
});
```
### Fastify - High Performance Framework
**Basic Setup:**
```typescript
import Fastify from "fastify";
import helmet from "@fastify/helmet";
import cors from "@fastify/cors";
import compress from "@fastify/compress";
const fastify = Fastify({
logger: {
level: process.env.LOG_LEVEL || "info",
transport: {
target: "pino-pretty",
options: { colorize: true }
}
}
});
// Plugins
await fastify.register(helmet);
await fastify.register(cors, { origin: true });
await fastify.register(compress);
// Type-safe routes with schema validation
fastify.post<{
Body: { name: string; email: string };
Reply: { id: string; name: string };
}>(
"/users",
{
schema: {
body: {
type: "object",
required: ["name", "email"],
properties: {
name: { type: "string", minLength: 1 },
email: { type: "string", format: "email" }
}
}
}
},
async (request, reply) => {
const { name, email } = request.body;
return { id: "123", name };
}
);
await fastify.listen({ port: 3000, host: "0.0.0.0" });
```
## Architectural Patterns
### Pattern 1: Layered Architecture
**Structure:**
```
src/
├── controllers/ # Handle HTTP requests/responses
├── services/ # Business logic
├── repositories/ # Data access layer
├── models/ # Data models
├── middleware/ # Express/Fastify middleware
├── routes/ # Route definitions
├── utils/ # Helper functions
├── config/ # Configuration
└── types/ # TypeScript types
```
**Controller Layer:**
```typescript
// controllers/user.controller.ts
import { Request, Response, NextFunction } from "express";
import { UserService } from "../services/user.service";
import { CreateUserDTO, UpdateUserDTO } from "../types/user.types";
export class UserController {
constructor(private userService: UserService) {}
async createUser(req: Request, res: Response, next: NextFunction) {
try {
const userData: CreateUserDTO = req.body;
const user = await this.userService.createUser(userData);
res.status(201).json(user);
} catch (error) {
next(error);
}
}
async getUser(req: Request, res: Response, next: NextFunction) {
try {
const { id } = req.params;
const user = await this.userService.getUserById(id);
res.json(user);
} catch (error) {
next(error);
}
}
async updateUser(req: Request, res: Response, next: NextFunction) {
try {
const { id } = req.params;
const updates: UpdateUserDTO = req.body;
const user = await this.userService.updateUser(id, updates);
res.json(user);
} catch (error) {
next(error);
}
}
async deleteUser(req: Request, res: Response, next: NextFunction) {
try {
const { id } = req.params;
await this.userService.deleteUser(id);
res.status(204).send();
} catch (error) {
next(error);
}
}
}
```
**Service Layer:**
```typescript
// services/user.service.ts
import { UserRepository } from "../repositories/user.repository";
import { CreateUserDTO, UpdateUserDTO, User } from "../types/user.types";
import { NotFoundError, ValidationError } from "../utils/errors";
import bcrypt from "bcrypt";
export class UserService {
constructor(private userRepository: UserRepository) {}
async createUser(userData: CreateUserDTO): Promise<User> {
// Validation
const existingUser = await this.userRepository.findByEmail(userData.email);
if (existingUser) {
throw new ValidationError("Email already exists");
}
// Hash password
const hashedPassword = await bcrypt.hash(userData.password, 10);
// Create user
const user = await this.userRepository.create({
...userData,
password: hashedPassword
});
// Remove password from response
const { password, ...userWithoutPassword } = user;
return userWithoutPassword as User;
}
async getUserById(id: string): Promise<User> {
const user = await this.userRepository.findById(id);
if (!user) {
throw new NotFoundError("User not found");
}
const { password, ...userWithoutPassword } = user;
return userWithoutPassword as User;
}
async updateUser(id: string, updates: UpdateUserDTO): Promise<User> {
const user = await this.userRepository.update(id, updates);
if (!user) {
throw new NotFoundError("User not found");
}
const { password, ...userWithoutPassword } = user;
return userWithoutPassword as User;
}
async deleteUser(id: string): Promise<void> {
const deleted = await this.userRepository.delete(id);
if (!deleted) {
throw new NotFoundError("User not found");
}
}
}
```
**Repository Layer:**
```typescript
// repositories/user.repository.ts
import { Pool } from "pg";
import { CreateUserDTO, UpdateUserDTO, UserEntity } from "../types/user.types";
export class UserRepository {
constructor(private db: Pool) {}
async create(userData: CreateUserDTO & { password: string }): Promise<UserEntity> {
const query = `
INSERT INTO users (name, email, password)
VALUES ($1, $2, $3)
RETURNING id, name, email, password, created_at, updated_at
`;
const { rows } = await this.db.query(query, [userData.name, userData.email, userData.password]);
return rows[0];
}
async findById(id: string): Promise<UserEntity | null> {
const query = "SELECT * FROM users WHERE id = $1";
const { rows } = await this.db.query(query, [id]);
return rows[0] || null;
}
async findByEmail(email: string): Promise<UserEntity | null> {
const query = "SELECT * FROM users WHERE email = $1";
const { rows } = await this.db.query(query, [email]);
return rows[0] || null;
}
async update(id: string, updates: UpdateUserDTO): Promise<UserEntity | null> {
const fields = Object.keys(updates);
const values = Object.values(updates);
const setClause = fields.map((field, idx) => `${field} = $${idx + 2}`).join(", ");
const query = `
UPDATE users
SET ${setClause}, updated_at = CURRENT_TIMESTAMP
WHERE id = $1
RETURNING *
`;
const { rows } = await this.db.query(query, [id, ...values]);
return rows[0] || null;
}
async delete(id: string): Promise<boolean> {
const query = "DELETE FROM users WHERE id = $1";
const { rowCount } = await this.db.query(query, [id]);
return rowCount > 0;
}
}
```
### Pattern 2: Dependency Injection
Use a DI container to wire up repositories, services, and controllers. For a full container implementation, see [references/advanced-patterns.md](references/advanced-patterns.md).
## Middleware Patterns
### Authentication Middleware
```typescript
// middleware/auth.middleware.ts
import { Request, Response, NextFunction } from "express";
import jwt from "jsonwebtoken";
import { UnauthorizedError } from "../utils/errors";
interface JWTPayload {
userId: string;
email: string;
}
declare global {
namespace Express {
interface Request {
user?: JWTPayload;
}
}
}
export const authenticate = async (req: Request, res: Response, next: NextFunction) => {
try {
const token = req.headers.authorization?.replace("Bearer ", "");
if (!token) {
throw new UnauthorizedError("No token provided");
}
const payload = jwt.verify(token, process.env.JWT_SECRET!) as JWTPayload;
req.user = payload;
next();
} catch (error) {
next(new UnauthorizedError("Invalid token"));
}
};
export const authorize = (...roles: string[]) => {
return async (req: Request, res: Response, next: NextFunction) => {
if (!req.user) {
return next(new UnauthorizedError("Not authenticated"));
}
// Check if user has required role
const hasRole = roles.some((role) => req.user?.roles?.includes(role));
if (!hasRole) {
return next(new UnauthorizedError("Insufficient permissions"));
}
next();
};
};
```
### Validation Middleware
```typescript
// middleware/validation.middleware.ts
import { Request, Response, NextFunction } from "express";
import { AnyZodObject, ZodError } from "zod";
import { ValidationError } from "../utils/errors";
export const validate = (schema: AnyZodObject) => {
return async (req: Request, res: Response, next: NextFunction) => {
try {
await schema.parseAsync({
body: req.body,
query: req.query,
params: req.params
});
next();
} catch (error) {
if (error instanceof ZodError) {
const errors = error.errors.map((err) => ({
field: err.path.join("."),
message: err.message
}));
next(new ValidationError("Validation failed", errors));
} else {
next(error);
}
}
};
};
// Usage with Zod
import { z } from "zod";
const createUserSchema = z.object({
body: z.object({
name: z.string().min(1),
email: z.string().email(),
password: z.string().min(8)
})
});
router.post("/users", validate(createUserSchema), userController.createUser);
```
### Rate Limiting Middleware
```typescript
// middleware/rate-limit.middleware.ts
import rateLimit from "express-rate-limit";
import RedisStore from "rate-limit-redis";
import Redis from "ioredis";
const redis = new Redis({
host: process.env.REDIS_HOST,
port: parseInt(process.env.REDIS_PORT || "6379")
});
export const apiLimiter = rateLimit({
store: new RedisStore({
client: redis,
prefix: "rl:"
}),
windowMs: 15 * 60 * 1000, // 15 minutes
max: 100, // Limit each IP to 100 requests per windowMs
message: "Too many requests from this IP, please try again later",
standardHeaders: true,
legacyHeaders: false
});
export const authLimiter = rateLimit({
store: new RedisStore({
client: redis,
prefix: "rl:auth:"
}),
windowMs: 15 * 60 * 1000,
max: 5, // Stricter limit for auth endpoints
skipSuccessfulRequests: true
});
```
### Request Logging Middleware
```typescript
// middleware/logger.middleware.ts
import { Request, Response, NextFunction } from "express";
import pino from "pino";
const logger = pino({
level: process.env.LOG_LEVEL || "info",
transport: {
target: "pino-pretty",
options: { colorize: true }
}
});
export const requestLogger = (req: Request, res: Response, next: NextFunction) => {
const start = Date.now();
// Log response when finished
res.on("finish", () => {
const duration = Date.now() - start;
logger.info({
method: req.method,
url: req.url,
status: res.statusCode,
duration: `${duration}ms`,
userAgent: req.headers["user-agent"],
ip: req.ip
});
});
next();
};
export { logger };
```
## Error Handling
### Custom Error Classes
```typescript
// utils/errors.ts
export class AppError extends Error {
constructor(
public message: string,
public statusCode: number = 500,
public isOperational: boolean = true
) {
super(message);
Object.setPrototypeOf(this, AppError.prototype);
Error.captureStackTrace(this, this.constructor);
}
}
export class ValidationError extends AppError {
constructor(
message: string,
public errors?: any[]
) {
super(message, 400);
}
}
export class NotFoundError extends AppError {
constructor(message: string = "Resource not found") {
super(message, 404);
}
}
export class UnauthorizedError extends AppError {
constructor(message: string = "Unauthorized") {
super(message, 401);
}
}
export class ForbiddenError extends AppError {
constructor(message: string = "Forbidden") {
super(message, 403);
}
}
export class ConflictError extends AppError {
constructor(message: string) {
super(message, 409);
}
}
```
### Global Error Handler
```typescript
// middleware/error-handler.ts
import { Request, Response, NextFunction } from "express";
import { AppError } from "../utils/errors";
import { logger } from "./logger.middleware";
export const errorHandler = (err: Error, req: Request, res: Response, next: NextFunction) => {
if (err instanceof AppError) {
return res.status(err.statusCode).json({
status: "error",
message: err.message,
...(err instanceof ValidationError && { errors: err.errors })
});
}
// Log unexpected errors
logger.error({
error: err.message,
stack: err.stack,
url: req.url,
method: req.method
});
// Don't leak error details in production
const message = process.env.NODE_ENV === "production" ? "Internal server error" : err.message;
res.status(500).json({
status: "error",
message
});
};
// Async error wrapper
export const asyncHandler = (
fn: (req: Request, res: Response, next: NextFunction) => Promise<any>
) => {
return (req: Request, res: Response, next: NextFunction) => {
Promise.resolve(fn(req, res, next)).catch(next);
};
};
```
## Database Patterns
Node.js supports both SQL and NoSQL databases. Use connection pooling for all production databases.
Key patterns covered in [references/advanced-patterns.md](references/advanced-patterns.md):
- **PostgreSQL with connection pool** — `pg` Pool configuration and graceful shutdown
- **MongoDB with Mongoose** — connection management and schema definition
- **Transaction pattern** — `BEGIN`/`COMMIT`/`ROLLBACK` with `pg` client
## Authentication & Authorization
JWT-based auth with access tokens (short-lived, 15m) and refresh tokens (7d). Full `AuthService` implementation with `bcrypt` password comparison in [references/advanced-patterns.md](references/advanced-patterns.md).
## Caching Strategies
Redis-backed `CacheService` with get/set/delete/invalidatePattern, plus a `@Cacheable` decorator for method-level caching. See [references/advanced-patterns.md](references/advanced-patterns.md).
## API Response Format
Standardized `ApiResponse` helper with `success`, `error`, and `paginated` static methods. See [references/advanced-patterns.md](references/advanced-patterns.md).
## Best Practices
1. **Use TypeScript**: Type safety prevents runtime errors
2. **Implement proper error handling**: Use custom error classes
3. **Validate input**: Use libraries like Zod or Joi
4. **Use environment variables**: Never hardcode secrets
5. **Implement logging**: Use structured logging (Pino, Winston)
6. **Add rate limiting**: Prevent abuse
7. **Use HTTPS**: Always in production
8. **Implement CORS properly**: Don't use `*` in production
9. **Use dependency injection**: Easier testing and maintenance
10. **Write tests**: Unit, integration, and E2E tests
11. **Handle graceful shutdown**: Clean up resources
12. **Use connection pooling**: For databases
13. **Implement health checks**: For monitoring
14. **Use compression**: Reduce response size
15. **Monitor performance**: Use APM tools
## Testing Patterns
See `javascript-testing-patterns` skill for comprehensive testing guidance.
@@ -0,0 +1,402 @@
# Node.js Advanced Patterns
Advanced patterns for dependency injection, database integration, authentication, caching, and API response formatting.
## Dependency Injection
### DI Container
```typescript
// di-container.ts
import { Pool } from "pg";
import { UserRepository } from "./repositories/user.repository";
import { UserService } from "./services/user.service";
import { UserController } from "./controllers/user.controller";
import { AuthService } from "./services/auth.service";
class Container {
private instances = new Map<string, any>();
register<T>(key: string, factory: () => T): void {
this.instances.set(key, factory);
}
resolve<T>(key: string): T {
const factory = this.instances.get(key);
if (!factory) {
throw new Error(`No factory registered for ${key}`);
}
return factory();
}
singleton<T>(key: string, factory: () => T): void {
let instance: T;
this.instances.set(key, () => {
if (!instance) {
instance = factory();
}
return instance;
});
}
}
export const container = new Container();
// Register dependencies
container.singleton(
"db",
() =>
new Pool({
host: process.env.DB_HOST,
port: parseInt(process.env.DB_PORT || "5432"),
database: process.env.DB_NAME,
user: process.env.DB_USER,
password: process.env.DB_PASSWORD,
max: 20,
idleTimeoutMillis: 30000,
connectionTimeoutMillis: 2000
})
);
container.singleton("userRepository", () => new UserRepository(container.resolve("db")));
container.singleton("userService", () => new UserService(container.resolve("userRepository")));
container.register("userController", () => new UserController(container.resolve("userService")));
container.singleton("authService", () => new AuthService(container.resolve("userRepository")));
```
## Database Patterns
### PostgreSQL with Connection Pool
```typescript
// config/database.ts
import { Pool, PoolConfig } from "pg";
const poolConfig: PoolConfig = {
host: process.env.DB_HOST,
port: parseInt(process.env.DB_PORT || "5432"),
database: process.env.DB_NAME,
user: process.env.DB_USER,
password: process.env.DB_PASSWORD,
max: 20,
idleTimeoutMillis: 30000,
connectionTimeoutMillis: 2000
};
export const pool = new Pool(poolConfig);
// Test connection
pool.on("connect", () => {
console.log("Database connected");
});
pool.on("error", (err) => {
console.error("Unexpected database error", err);
process.exit(-1);
});
// Graceful shutdown
export const closeDatabase = async () => {
await pool.end();
console.log("Database connection closed");
};
```
### MongoDB with Mongoose
```typescript
// config/mongoose.ts
import mongoose from "mongoose";
const connectDB = async () => {
try {
await mongoose.connect(process.env.MONGODB_URI!, {
maxPoolSize: 10,
serverSelectionTimeoutMS: 5000,
socketTimeoutMS: 45000
});
console.log("MongoDB connected");
} catch (error) {
console.error("MongoDB connection error:", error);
process.exit(1);
}
};
mongoose.connection.on("disconnected", () => {
console.log("MongoDB disconnected");
});
mongoose.connection.on("error", (err) => {
console.error("MongoDB error:", err);
});
export { connectDB };
// Model example
import { Schema, model, Document } from "mongoose";
interface IUser extends Document {
name: string;
email: string;
password: string;
createdAt: Date;
updatedAt: Date;
}
const userSchema = new Schema<IUser>(
{
name: { type: String, required: true },
email: { type: String, required: true, unique: true },
password: { type: String, required: true }
},
{
timestamps: true
}
);
// Indexes
userSchema.index({ email: 1 });
export const User = model<IUser>("User", userSchema);
```
### Transaction Pattern
```typescript
// services/order.service.ts
import { Pool } from "pg";
export class OrderService {
constructor(private db: Pool) {}
async createOrder(userId: string, items: any[]) {
const client = await this.db.connect();
try {
await client.query("BEGIN");
// Create order
const orderResult = await client.query(
"INSERT INTO orders (user_id, total) VALUES ($1, $2) RETURNING id",
[userId, calculateTotal(items)]
);
const orderId = orderResult.rows[0].id;
// Create order items
for (const item of items) {
await client.query(
"INSERT INTO order_items (order_id, product_id, quantity, price) VALUES ($1, $2, $3, $4)",
[orderId, item.productId, item.quantity, item.price]
);
// Update inventory
await client.query("UPDATE products SET stock = stock - $1 WHERE id = $2", [
item.quantity,
item.productId
]);
}
await client.query("COMMIT");
return orderId;
} catch (error) {
await client.query("ROLLBACK");
throw error;
} finally {
client.release();
}
}
}
```
## Authentication & Authorization
### JWT Authentication
```typescript
// services/auth.service.ts
import jwt from "jsonwebtoken";
import bcrypt from "bcrypt";
import { UserRepository } from "../repositories/user.repository";
import { UnauthorizedError } from "../utils/errors";
export class AuthService {
constructor(private userRepository: UserRepository) {}
async login(email: string, password: string) {
const user = await this.userRepository.findByEmail(email);
if (!user) {
throw new UnauthorizedError("Invalid credentials");
}
const isValid = await bcrypt.compare(password, user.password);
if (!isValid) {
throw new UnauthorizedError("Invalid credentials");
}
const token = this.generateToken({
userId: user.id,
email: user.email
});
const refreshToken = this.generateRefreshToken({
userId: user.id
});
return {
token,
refreshToken,
user: {
id: user.id,
name: user.name,
email: user.email
}
};
}
async refreshToken(refreshToken: string) {
try {
const payload = jwt.verify(refreshToken, process.env.REFRESH_TOKEN_SECRET!) as {
userId: string;
};
const user = await this.userRepository.findById(payload.userId);
if (!user) {
throw new UnauthorizedError("User not found");
}
const token = this.generateToken({
userId: user.id,
email: user.email
});
return { token };
} catch (error) {
throw new UnauthorizedError("Invalid refresh token");
}
}
private generateToken(payload: any): string {
return jwt.sign(payload, process.env.JWT_SECRET!, {
expiresIn: "15m"
});
}
private generateRefreshToken(payload: any): string {
return jwt.sign(payload, process.env.REFRESH_TOKEN_SECRET!, {
expiresIn: "7d"
});
}
}
```
## Caching Strategies
```typescript
// utils/cache.ts
import Redis from "ioredis";
const redis = new Redis({
host: process.env.REDIS_HOST,
port: parseInt(process.env.REDIS_PORT || "6379"),
retryStrategy: (times) => {
const delay = Math.min(times * 50, 2000);
return delay;
}
});
export class CacheService {
async get<T>(key: string): Promise<T | null> {
const data = await redis.get(key);
return data ? JSON.parse(data) : null;
}
async set(key: string, value: any, ttl?: number): Promise<void> {
const serialized = JSON.stringify(value);
if (ttl) {
await redis.setex(key, ttl, serialized);
} else {
await redis.set(key, serialized);
}
}
async delete(key: string): Promise<void> {
await redis.del(key);
}
async invalidatePattern(pattern: string): Promise<void> {
const keys = await redis.keys(pattern);
if (keys.length > 0) {
await redis.del(...keys);
}
}
}
// Cache decorator
export function Cacheable(ttl: number = 300) {
return function (target: any, propertyKey: string, descriptor: PropertyDescriptor) {
const originalMethod = descriptor.value;
descriptor.value = async function (...args: any[]) {
const cache = new CacheService();
const cacheKey = `${propertyKey}:${JSON.stringify(args)}`;
const cached = await cache.get(cacheKey);
if (cached) {
return cached;
}
const result = await originalMethod.apply(this, args);
await cache.set(cacheKey, result, ttl);
return result;
};
return descriptor;
};
}
```
## API Response Format
```typescript
// utils/response.ts
import { Response } from "express";
export class ApiResponse {
static success<T>(res: Response, data: T, message?: string, statusCode = 200) {
return res.status(statusCode).json({
status: "success",
message,
data
});
}
static error(res: Response, message: string, statusCode = 500, errors?: any) {
return res.status(statusCode).json({
status: "error",
message,
...(errors && { errors })
});
}
static paginated<T>(res: Response, data: T[], page: number, limit: number, total: number) {
return res.json({
status: "success",
data,
pagination: {
page,
limit,
total,
pages: Math.ceil(total / limit)
}
});
}
}
```
@@ -0,0 +1,350 @@
---
name: nodejs-best-practices
description: "Node.js development principles and decision-making. Framework selection, async patterns, security, and architecture. Teaches thinking, not copying."
risk: unknown
source: community
date_added: "2026-02-27"
---
# Node.js Best Practices
> Principles and decision-making for Node.js development in 2025.
> **Learn to THINK, not memorize code patterns.**
## When to Use
Use this skill when making Node.js architecture decisions, choosing frameworks, designing async patterns, or applying security and deployment best practices.
---
## ⚠️ How to Use This Skill
This skill teaches **decision-making principles**, not fixed code to copy.
- ASK user for preferences when unclear
- Choose framework/pattern based on CONTEXT
- Don't default to same solution every time
---
## 1. Framework Selection (2025)
### Decision Tree
```
What are you building?
│
├── Edge/Serverless (Cloudflare, Vercel)
│ └── Hono (zero-dependency, ultra-fast cold starts)
│
├── High Performance API
│ └── Fastify (2-3x faster than Express)
│
├── Enterprise/Team familiarity
│ └── NestJS (structured, DI, decorators)
│
├── Legacy/Stable/Maximum ecosystem
│ └── Express (mature, most middleware)
│
└── Full-stack with frontend
└── Next.js API Routes or tRPC
```
### Comparison Principles
| Factor | Hono | Fastify | Express |
| ------------------ | ---------------- | ----------- | ---------------- |
| **Best for** | Edge, serverless | Performance | Legacy, learning |
| **Cold start** | Fastest | Fast | Moderate |
| **Ecosystem** | Growing | Good | Largest |
| **TypeScript** | Native | Excellent | Good |
| **Learning curve** | Low | Medium | Low |
### Selection Questions to Ask:
1. What's the deployment target?
2. Is cold start time critical?
3. Does team have existing experience?
4. Is there legacy code to maintain?
---
## 2. Runtime Considerations (2025)
### Native TypeScript
```
Node.js 22+: --experimental-strip-types
├── Run .ts files directly
├── No build step needed for simple projects
└── Consider for: scripts, simple APIs
```
### Module System Decision
```
ESM (import/export)
├── Modern standard
├── Better tree-shaking
├── Async module loading
└── Use for: new projects
CommonJS (require)
├── Legacy compatibility
├── More npm packages support
└── Use for: existing codebases, some edge cases
```
### Runtime Selection
| Runtime | Best For |
| ----------- | ----------------------------------- |
| **Node.js** | General purpose, largest ecosystem |
| **Bun** | Performance, built-in bundler |
| **Deno** | Security-first, built-in TypeScript |
---
## 3. Architecture Principles
### Layered Structure Concept
```
Request Flow:
│
├── Controller/Route Layer
│ ├── Handles HTTP specifics
│ ├── Input validation at boundary
│ └── Calls service layer
│
├── Service Layer
│ ├── Business logic
│ ├── Framework-agnostic
│ └── Calls repository layer
│
└── Repository Layer
├── Data access only
├── Database queries
└── ORM interactions
```
### Why This Matters:
- **Testability**: Mock layers independently
- **Flexibility**: Swap database without touching business logic
- **Clarity**: Each layer has single responsibility
### When to Simplify:
- Small scripts → Single file OK
- Prototypes → Less structure acceptable
- Always ask: "Will this grow?"
---
## 4. Error Handling Principles
### Centralized Error Handling
```
Pattern:
├── Create custom error classes
├── Throw from any layer
├── Catch at top level (middleware)
└── Format consistent response
```
### Error Response Philosophy
```
Client gets:
├── Appropriate HTTP status
├── Error code for programmatic handling
├── User-friendly message
└── NO internal details (security!)
Logs get:
├── Full stack trace
├── Request context
├── User ID (if applicable)
└── Timestamp
```
### Status Code Selection
| Situation | Status | When |
| ------------- | ------ | ------------------------------------ |
| Bad input | 400 | Client sent invalid data |
| No auth | 401 | Missing or invalid credentials |
| No permission | 403 | Valid auth, but not allowed |
| Not found | 404 | Resource doesn't exist |
| Conflict | 409 | Duplicate or state conflict |
| Validation | 422 | Schema valid but business rules fail |
| Server error | 500 | Our fault, log everything |
---
## 5. Async Patterns Principles
### When to Use Each
| Pattern | Use When |
| -------------------- | ------------------------------- |
| `async/await` | Sequential async operations |
| `Promise.all` | Parallel independent operations |
| `Promise.allSettled` | Parallel where some can fail |
| `Promise.race` | Timeout or first response wins |
### Event Loop Awareness
```
I/O-bound (async helps):
├── Database queries
├── HTTP requests
├── File system
└── Network operations
CPU-bound (async doesn't help):
├── Crypto operations
├── Image processing
├── Complex calculations
└── → Use worker threads or offload
```
### Avoiding Event Loop Blocking
- Never use sync methods in production (fs.readFileSync, etc.)
- Offload CPU-intensive work
- Use streaming for large data
---
## 6. Validation Principles
### Validate at Boundaries
```
Where to validate:
├── API entry point (request body/params)
├── Before database operations
├── External data (API responses, file uploads)
└── Environment variables (startup)
```
### Validation Library Selection
| Library | Best For |
| ----------- | ------------------------------- |
| **Zod** | TypeScript first, inference |
| **Valibot** | Smaller bundle (tree-shakeable) |
| **ArkType** | Performance critical |
| **Yup** | Existing React Form usage |
### Validation Philosophy
- Fail fast: Validate early
- Be specific: Clear error messages
- Don't trust: Even "internal" data
---
## 7. Security Principles
### Security Checklist (Not Code)
- [ ] **Input validation**: All inputs validated
- [ ] **Parameterized queries**: No string concatenation for SQL
- [ ] **Password hashing**: bcrypt or argon2
- [ ] **JWT verification**: Always verify signature and expiry
- [ ] **Rate limiting**: Protect from abuse
- [ ] **Security headers**: Helmet.js or equivalent
- [ ] **HTTPS**: Everywhere in production
- [ ] **CORS**: Properly configured
- [ ] **Secrets**: Environment variables only
- [ ] **Dependencies**: Regularly audited
### Security Mindset
```
Trust nothing:
├── Query params → validate
├── Request body → validate
├── Headers → verify
├── Cookies → validate
├── File uploads → scan
└── External APIs → validate response
```
---
## 8. Testing Principles
### Test Strategy Selection
| Type | Purpose | Tools |
| --------------- | -------------- | ----------------- |
| **Unit** | Business logic | node:test, Vitest |
| **Integration** | API endpoints | Supertest |
| **E2E** | Full flows | Playwright |
### What to Test (Priorities)
1. **Critical paths**: Auth, payments, core business
2. **Edge cases**: Empty inputs, boundaries
3. **Error handling**: What happens when things fail?
4. **Not worth testing**: Framework code, trivial getters
### Built-in Test Runner (Node.js 22+)
```
node --test src/**/*.test.ts
├── No external dependency
├── Good coverage reporting
└── Watch mode available
```
---
## 9. Anti-Patterns to Avoid
### ❌ DON'T:
- Use Express for new edge projects (use Hono)
- Use sync methods in production code
- Put business logic in controllers
- Skip input validation
- Hardcode secrets
- Trust external data without validation
- Block event loop with CPU work
### ✅ DO:
- Choose framework based on context
- Ask user for preferences when unclear
- Use layered architecture for growing projects
- Validate all inputs
- Use environment variables for secrets
- Profile before optimizing
---
## 10. Decision Checklist
Before implementing:
- [ ] **Asked user about stack preference?**
- [ ] **Chosen framework for THIS context?** (not just default)
- [ ] **Considered deployment target?**
- [ ] **Planned error handling strategy?**
- [ ] **Identified validation points?**
- [ ] **Considered security requirements?**
---
> **Remember**: Node.js best practices are about decision-making, not memorizing patterns. Every project deserves fresh consideration based on its requirements.
## Limitations
- Use this skill only when the task clearly matches the scope described above.
- Do not treat the output as a substitute for environment-specific validation, testing, or expert review.
- Stop and ask for clarification if required inputs, permissions, safety boundaries, or success criteria are missing.
@@ -0,0 +1,700 @@
---
name: typescript-advanced-types
description: Master TypeScript's advanced type system including generics, conditional types, mapped types, template literals, and utility types for building type-safe applications. Use when implementing complex type logic, creating reusable type utilities, or ensuring compile-time type safety in TypeScript projects.
---
# TypeScript Advanced Types
Comprehensive guidance for mastering TypeScript's advanced type system including generics, conditional types, mapped types, template literal types, and utility types for building robust, type-safe applications.
## When to Use This Skill
- Building type-safe libraries or frameworks
- Creating reusable generic components
- Implementing complex type inference logic
- Designing type-safe API clients
- Building form validation systems
- Creating strongly-typed configuration objects
- Implementing type-safe state management
- Migrating JavaScript codebases to TypeScript
## Core Concepts
### 1. Generics
**Purpose:** Create reusable, type-flexible components while maintaining type safety.
**Basic Generic Function:**
```typescript
function identity<T>(value: T): T {
return value;
}
const num = identity<number>(42); // Type: number
const str = identity<string>("hello"); // Type: string
const auto = identity(true); // Type inferred: boolean
```
**Generic Constraints:**
```typescript
interface HasLength {
length: number;
}
function logLength<T extends HasLength>(item: T): T {
console.log(item.length);
return item;
}
logLength("hello"); // OK: string has length
logLength([1, 2, 3]); // OK: array has length
logLength({ length: 10 }); // OK: object has length
// logLength(42); // Error: number has no length
```
**Multiple Type Parameters:**
```typescript
function merge<T, U>(obj1: T, obj2: U): T & U {
return { ...obj1, ...obj2 };
}
const merged = merge({ name: "John" }, { age: 30 });
// Type: { name: string } & { age: number }
```
### 2. Conditional Types
**Purpose:** Create types that depend on conditions, enabling sophisticated type logic.
**Basic Conditional Type:**
```typescript
type IsString<T> = T extends string ? true : false;
type A = IsString<string>; // true
type B = IsString<number>; // false
```
**Extracting Return Types:**
```typescript
type ReturnType<T> = T extends (...args: any[]) => infer R ? R : never;
function getUser() {
return { id: 1, name: "John" };
}
type User = ReturnType<typeof getUser>;
// Type: { id: number; name: string; }
```
**Distributive Conditional Types:**
```typescript
type ToArray<T> = T extends any ? T[] : never;
type StrOrNumArray = ToArray<string | number>;
// Type: string[] | number[]
```
**Nested Conditions:**
```typescript
type TypeName<T> = T extends string
? "string"
: T extends number
? "number"
: T extends boolean
? "boolean"
: T extends undefined
? "undefined"
: T extends Function
? "function"
: "object";
type T1 = TypeName<string>; // "string"
type T2 = TypeName<() => void>; // "function"
```
### 3. Mapped Types
**Purpose:** Transform existing types by iterating over their properties.
**Basic Mapped Type:**
```typescript
type Readonly<T> = {
readonly [P in keyof T]: T[P];
};
interface User {
id: number;
name: string;
}
type ReadonlyUser = Readonly<User>;
// Type: { readonly id: number; readonly name: string; }
```
**Optional Properties:**
```typescript
type Partial<T> = {
[P in keyof T]?: T[P];
};
type PartialUser = Partial<User>;
// Type: { id?: number; name?: string; }
```
**Key Remapping:**
```typescript
type Getters<T> = {
[K in keyof T as `get${Capitalize<string & K>}`]: () => T[K];
};
interface Person {
name: string;
age: number;
}
type PersonGetters = Getters<Person>;
// Type: { getName: () => string; getAge: () => number; }
```
**Filtering Properties:**
```typescript
type PickByType<T, U> = {
[K in keyof T as T[K] extends U ? K : never]: T[K];
};
interface Mixed {
id: number;
name: string;
age: number;
active: boolean;
}
type OnlyNumbers = PickByType<Mixed, number>;
// Type: { id: number; age: number; }
```
### 4. Template Literal Types
**Purpose:** Create string-based types with pattern matching and transformation.
**Basic Template Literal:**
```typescript
type EventName = "click" | "focus" | "blur";
type EventHandler = `on${Capitalize<EventName>}`;
// Type: "onClick" | "onFocus" | "onBlur"
```
**String Manipulation:**
```typescript
type UppercaseGreeting = Uppercase<"hello">; // "HELLO"
type LowercaseGreeting = Lowercase<"HELLO">; // "hello"
type CapitalizedName = Capitalize<"john">; // "John"
type UncapitalizedName = Uncapitalize<"John">; // "john"
```
**Path Building:**
```typescript
type Path<T> = T extends object
? {
[K in keyof T]: K extends string ? `${K}` | `${K}.${Path<T[K]>}` : never;
}[keyof T]
: never;
interface Config {
server: {
host: string;
port: number;
};
database: {
url: string;
};
}
type ConfigPath = Path<Config>;
// Type: "server" | "database" | "server.host" | "server.port" | "database.url"
```
### 5. Utility Types
**Built-in Utility Types:**
```typescript
// Partial<T> - Make all properties optional
type PartialUser = Partial<User>;
// Required<T> - Make all properties required
type RequiredUser = Required<PartialUser>;
// Readonly<T> - Make all properties readonly
type ReadonlyUser = Readonly<User>;
// Pick<T, K> - Select specific properties
type UserName = Pick<User, "name" | "email">;
// Omit<T, K> - Remove specific properties
type UserWithoutPassword = Omit<User, "password">;
// Exclude<T, U> - Exclude types from union
type T1 = Exclude<"a" | "b" | "c", "a">; // "b" | "c"
// Extract<T, U> - Extract types from union
type T2 = Extract<"a" | "b" | "c", "a" | "b">; // "a" | "b"
// NonNullable<T> - Exclude null and undefined
type T3 = NonNullable<string | null | undefined>; // string
// Record<K, T> - Create object type with keys K and values T
type PageInfo = Record<"home" | "about", { title: string }>;
```
## Advanced Patterns
### Pattern 1: Type-Safe Event Emitter
```typescript
type EventMap = {
"user:created": { id: string; name: string };
"user:updated": { id: string };
"user:deleted": { id: string };
};
class TypedEventEmitter<T extends Record<string, any>> {
private listeners: {
[K in keyof T]?: Array<(data: T[K]) => void>;
} = {};
on<K extends keyof T>(event: K, callback: (data: T[K]) => void): void {
if (!this.listeners[event]) {
this.listeners[event] = [];
}
this.listeners[event]!.push(callback);
}
emit<K extends keyof T>(event: K, data: T[K]): void {
const callbacks = this.listeners[event];
if (callbacks) {
callbacks.forEach((callback) => callback(data));
}
}
}
const emitter = new TypedEventEmitter<EventMap>();
emitter.on("user:created", (data) => {
console.log(data.id, data.name); // Type-safe!
});
emitter.emit("user:created", { id: "1", name: "John" });
// emitter.emit("user:created", { id: "1" }); // Error: missing 'name'
```
### Pattern 2: Type-Safe API Client
```typescript
type HTTPMethod = "GET" | "POST" | "PUT" | "DELETE";
type EndpointConfig = {
"/users": {
GET: { response: User[] };
POST: { body: { name: string; email: string }; response: User };
};
"/users/:id": {
GET: { params: { id: string }; response: User };
PUT: { params: { id: string }; body: Partial<User>; response: User };
DELETE: { params: { id: string }; response: void };
};
};
type ExtractParams<T> = T extends { params: infer P } ? P : never;
type ExtractBody<T> = T extends { body: infer B } ? B : never;
type ExtractResponse<T> = T extends { response: infer R } ? R : never;
class APIClient<Config extends Record<string, Record<HTTPMethod, any>>> {
async request<Path extends keyof Config, Method extends keyof Config[Path]>(
path: Path,
method: Method,
...[options]: ExtractParams<Config[Path][Method]> extends never
? ExtractBody<Config[Path][Method]> extends never
? []
: [{ body: ExtractBody<Config[Path][Method]> }]
: [
{
params: ExtractParams<Config[Path][Method]>;
body?: ExtractBody<Config[Path][Method]>;
}
]
): Promise<ExtractResponse<Config[Path][Method]>> {
// Implementation here
return {} as any;
}
}
const api = new APIClient<EndpointConfig>();
// Type-safe API calls
const users = await api.request("/users", "GET");
// Type: User[]
const newUser = await api.request("/users", "POST", {
body: { name: "John", email: "john@example.com" }
});
// Type: User
const user = await api.request("/users/:id", "GET", {
params: { id: "123" }
});
// Type: User
```
### Pattern 3: Builder Pattern with Type Safety
```typescript
type BuilderState<T> = {
[K in keyof T]: T[K] | undefined;
};
type RequiredKeys<T> = {
[K in keyof T]-?: {} extends Pick<T, K> ? never : K;
}[keyof T];
type OptionalKeys<T> = {
[K in keyof T]-?: {} extends Pick<T, K> ? K : never;
}[keyof T];
type IsComplete<T, S> =
RequiredKeys<T> extends keyof S ? (S[RequiredKeys<T>] extends undefined ? false : true) : false;
class Builder<T, S extends BuilderState<T> = {}> {
private state: S = {} as S;
set<K extends keyof T>(key: K, value: T[K]): Builder<T, S & Record<K, T[K]>> {
this.state[key] = value;
return this as any;
}
build(this: IsComplete<T, S> extends true ? this : never): T {
return this.state as T;
}
}
interface User {
id: string;
name: string;
email: string;
age?: number;
}
const builder = new Builder<User>();
const user = builder.set("id", "1").set("name", "John").set("email", "john@example.com").build(); // OK: all required fields set
// const incomplete = builder
// .set("id", "1")
// .build(); // Error: missing required fields
```
### Pattern 4: Deep Readonly/Partial
```typescript
type DeepReadonly<T> = {
readonly [P in keyof T]: T[P] extends object
? T[P] extends Function
? T[P]
: DeepReadonly<T[P]>
: T[P];
};
type DeepPartial<T> = {
[P in keyof T]?: T[P] extends object
? T[P] extends Array<infer U>
? Array<DeepPartial<U>>
: DeepPartial<T[P]>
: T[P];
};
interface Config {
server: {
host: string;
port: number;
ssl: {
enabled: boolean;
cert: string;
};
};
database: {
url: string;
pool: {
min: number;
max: number;
};
};
}
type ReadonlyConfig = DeepReadonly<Config>;
// All nested properties are readonly
type PartialConfig = DeepPartial<Config>;
// All nested properties are optional
```
### Pattern 5: Type-Safe Form Validation
```typescript
type ValidationRule<T> = {
validate: (value: T) => boolean;
message: string;
};
type FieldValidation<T> = {
[K in keyof T]?: ValidationRule<T[K]>[];
};
type ValidationErrors<T> = {
[K in keyof T]?: string[];
};
class FormValidator<T extends Record<string, any>> {
constructor(private rules: FieldValidation<T>) {}
validate(data: T): ValidationErrors<T> | null {
const errors: ValidationErrors<T> = {};
let hasErrors = false;
for (const key in this.rules) {
const fieldRules = this.rules[key];
const value = data[key];
if (fieldRules) {
const fieldErrors: string[] = [];
for (const rule of fieldRules) {
if (!rule.validate(value)) {
fieldErrors.push(rule.message);
}
}
if (fieldErrors.length > 0) {
errors[key] = fieldErrors;
hasErrors = true;
}
}
}
return hasErrors ? errors : null;
}
}
interface LoginForm {
email: string;
password: string;
}
const validator = new FormValidator<LoginForm>({
email: [
{
validate: (v) => v.includes("@"),
message: "Email must contain @"
},
{
validate: (v) => v.length > 0,
message: "Email is required"
}
],
password: [
{
validate: (v) => v.length >= 8,
message: "Password must be at least 8 characters"
}
]
});
const errors = validator.validate({
email: "invalid",
password: "short"
});
// Type: { email?: string[]; password?: string[]; } | null
```
### Pattern 6: Discriminated Unions
```typescript
type Success<T> = {
status: "success";
data: T;
};
type Error = {
status: "error";
error: string;
};
type Loading = {
status: "loading";
};
type AsyncState<T> = Success<T> | Error | Loading;
function handleState<T>(state: AsyncState<T>): void {
switch (state.status) {
case "success":
console.log(state.data); // Type: T
break;
case "error":
console.log(state.error); // Type: string
break;
case "loading":
console.log("Loading...");
break;
}
}
// Type-safe state machine
type State =
| { type: "idle" }
| { type: "fetching"; requestId: string }
| { type: "success"; data: any }
| { type: "error"; error: Error };
type Event =
| { type: "FETCH"; requestId: string }
| { type: "SUCCESS"; data: any }
| { type: "ERROR"; error: Error }
| { type: "RESET" };
function reducer(state: State, event: Event): State {
switch (state.type) {
case "idle":
return event.type === "FETCH" ? { type: "fetching", requestId: event.requestId } : state;
case "fetching":
if (event.type === "SUCCESS") {
return { type: "success", data: event.data };
}
if (event.type === "ERROR") {
return { type: "error", error: event.error };
}
return state;
case "success":
case "error":
return event.type === "RESET" ? { type: "idle" } : state;
}
}
```
## Type Inference Techniques
### 1. Infer Keyword
```typescript
// Extract array element type
type ElementType<T> = T extends (infer U)[] ? U : never;
type NumArray = number[];
type Num = ElementType<NumArray>; // number
// Extract promise type
type PromiseType<T> = T extends Promise<infer U> ? U : never;
type AsyncNum = PromiseType<Promise<number>>; // number
// Extract function parameters
type Parameters<T> = T extends (...args: infer P) => any ? P : never;
function foo(a: string, b: number) {}
type FooParams = Parameters<typeof foo>; // [string, number]
```
### 2. Type Guards
```typescript
function isString(value: unknown): value is string {
return typeof value === "string";
}
function isArrayOf<T>(value: unknown, guard: (item: unknown) => item is T): value is T[] {
return Array.isArray(value) && value.every(guard);
}
const data: unknown = ["a", "b", "c"];
if (isArrayOf(data, isString)) {
data.forEach((s) => s.toUpperCase()); // Type: string[]
}
```
### 3. Assertion Functions
```typescript
function assertIsString(value: unknown): asserts value is string {
if (typeof value !== "string") {
throw new Error("Not a string");
}
}
function processValue(value: unknown) {
assertIsString(value);
// value is now typed as string
console.log(value.toUpperCase());
}
```
## Best Practices
1. **Use `unknown` over `any`**: Enforce type checking
2. **Prefer `interface` for object shapes**: Better error messages
3. **Use `type` for unions and complex types**: More flexible
4. **Leverage type inference**: Let TypeScript infer when possible
5. **Create helper types**: Build reusable type utilities
6. **Use const assertions**: Preserve literal types
7. **Avoid type assertions**: Use type guards instead
8. **Document complex types**: Add JSDoc comments
9. **Use strict mode**: Enable all strict compiler options
10. **Test your types**: Use type tests to verify type behavior
## Type Testing
```typescript
// Type assertion tests
type AssertEqual<T, U> = [T] extends [U] ? ([U] extends [T] ? true : false) : false;
type Test1 = AssertEqual<string, string>; // true
type Test2 = AssertEqual<string, number>; // false
type Test3 = AssertEqual<string | number, string>; // false
// Expect error helper
type ExpectError<T extends never> = T;
// Example usage
type ShouldError = ExpectError<AssertEqual<string, number>>;
```
## Common Pitfalls
1. **Over-using `any`**: Defeats the purpose of TypeScript
2. **Ignoring strict null checks**: Can lead to runtime errors
3. **Too complex types**: Can slow down compilation
4. **Not using discriminated unions**: Misses type narrowing opportunities
5. **Forgetting readonly modifiers**: Allows unintended mutations
6. **Circular type references**: Can cause compiler errors
7. **Not handling edge cases**: Like empty arrays or null values
## Performance Considerations
- Avoid deeply nested conditional types
- Use simple types when possible
- Cache complex type computations
- Limit recursion depth in recursive types
- Use build tools to skip type checking in production
+97
View File
@@ -0,0 +1,97 @@
# Zod
**Version 1.0.0**
community
January 2026
> **Note:**
> This document is mainly for agents and LLMs to follow when maintaining,
> generating, or refactoring codebases. Humans may also find it useful,
> but guidance here is optimized for automation and consistency by AI-assisted workflows.
---
## Abstract
Comprehensive schema validation guide for Zod in TypeScript applications, designed for AI agents and LLMs. Contains 43 rules across 8 categories, prioritized by impact from critical (schema definition, parsing) to incremental (performance, bundle optimization). Each rule includes detailed explanations, real-world examples comparing incorrect vs. correct implementations, and specific impact metrics to guide automated refactoring and code generation.
---
## Table of Contents
1. [Schema Definition](references/_sections.md#1-schema-definition) — **CRITICAL**
- 1.1 [Apply String Validations at Schema Definition](references/schema-string-validations.md) — CRITICAL (Unvalidated strings allow SQL injection, XSS, and malformed data; validating at schema level catches issues at the boundary)
- 1.2 [Avoid Overusing Optional Fields](references/schema-avoid-optional-abuse.md) — CRITICAL (Excessive optional fields create schemas that accept almost anything; forces null checks throughout codebase)
- 1.3 [Use Coercion for Form and Query Data](references/schema-coercion-for-form-data.md) — CRITICAL (Form data and query params are always strings; without coercion, z.number() rejects "42" and z.boolean() rejects "true")
- 1.4 [Use Enums for Fixed String Values](references/schema-use-enums.md) — CRITICAL (Plain strings accept any value including typos; enums restrict to valid values and enable autocomplete)
- 1.5 [Use Primitive Schemas Correctly](references/schema-use-primitives-correctly.md) — CRITICAL (Incorrect primitive selection causes validation to pass on wrong types; using z.any() or z.unknown() loses all type safety)
- 1.6 [Use z.unknown() Instead of z.any()](references/schema-use-unknown-not-any.md) — CRITICAL (z.any() bypasses TypeScript's type system entirely; z.unknown() forces type narrowing before use)
2. [Parsing & Validation](references/_sections.md#2-parsing-&-validation) — **CRITICAL**
- 2.1 [Avoid Double Validation](references/parse-avoid-double-validation.md) — HIGH (Parsing the same data twice wastes CPU cycles; in hot paths this adds measurable latency)
- 2.2 [Handle All Validation Issues Not Just First](references/parse-handle-all-issues.md) — CRITICAL (Showing only the first error forces users to fix-submit-fix repeatedly; collecting all errors improves UX dramatically)
- 2.3 [Never Trust JSON.parse Output](references/parse-never-trust-json.md) — CRITICAL (JSON.parse returns any type; unvalidated JSON allows type confusion attacks and runtime crashes)
- 2.4 [Use parseAsync for Async Refinements](references/parse-async-for-async-refinements.md) — CRITICAL (Using parse() with async refinements throws an error; async validation silently fails or crashes the application)
- 2.5 [Use safeParse() for User Input](references/parse-use-safeparse.md) — CRITICAL (parse() throws exceptions on invalid data; unhandled exceptions crash servers and expose stack traces to users)
- 2.6 [Validate at System Boundaries](references/parse-validate-early.md) — CRITICAL (Validating deep in business logic allows corrupt data to propagate; validating at boundaries catches issues before they spread)
3. [Type Inference](references/_sections.md#3-type-inference) — **HIGH**
- 3.1 [Distinguish z.input from z.infer for Transforms](references/type-input-vs-output.md) — HIGH (Using wrong type with transforms causes TypeScript errors; z.input captures pre-transform shape, z.infer captures post-transform)
- 3.2 [Enable TypeScript Strict Mode](references/type-enable-strict-mode.md) — HIGH (Without strict mode, Zod's type inference is unreliable; undefined and null slip through, defeating the purpose of validation)
- 3.3 [Export Both Schemas and Inferred Types](references/type-export-schemas-and-types.md) — HIGH (Exporting only schemas forces consumers to derive types themselves; exporting both reduces boilerplate and improves DX)
- 3.4 [Use Branded Types for Domain Safety](references/type-branded-types.md) — HIGH (Plain string IDs are interchangeable, allowing userId where orderId is expected; branded types catch these bugs at compile time)
- 3.5 [Use z.infer Instead of Manual Types](references/type-use-z-infer.md) — HIGH (Manual type definitions drift from schemas over time; z.infer guarantees types match validation exactly)
4. [Error Handling](references/_sections.md#4-error-handling) — **HIGH**
- 4.1 [Implement Internationalized Error Messages](references/error-i18n.md) — HIGH (Hardcoded English messages exclude non-English users; error maps enable localized messages for global applications)
- 4.2 [Provide Custom Error Messages](references/error-custom-messages.md) — HIGH (Default messages like "Expected string, received number" confuse users; custom messages like "Email is required" are actionable)
- 4.3 [Return False Instead of Throwing in Refine](references/error-avoid-throwing-in-refine.md) — HIGH (Throwing in refine stops validation early, hiding other errors; returning false allows Zod to collect all issues)
- 4.4 [Use flatten() for Form Error Display](references/error-use-flatten.md) — HIGH (Raw ZodError.issues requires manual path parsing; flatten() provides field-keyed errors ready for form display)
- 4.5 [Use issue.path for Nested Error Location](references/error-path-for-nested.md) — HIGH (Without path information, users can't identify which nested field failed; path provides exact location in complex objects)
5. [Object Schemas](references/_sections.md#5-object-schemas) — **MEDIUM-HIGH**
- 5.1 [Choose strict() vs strip() for Unknown Keys](references/object-strict-vs-strip.md) — MEDIUM-HIGH (Default passthrough mode leaks unexpected data; strict() catches schema mismatches, strip() silently removes extras)
- 5.2 [Distinguish optional() from nullable()](references/object-optional-vs-nullable.md) — MEDIUM-HIGH (Confusing undefined and null semantics causes "property does not exist" vs "property is null" bugs; choose deliberately)
- 5.3 [Use Discriminated Unions for Type Narrowing](references/object-discriminated-unions.md) — MEDIUM-HIGH (Regular unions require manual type guards; discriminated unions enable TypeScript's automatic narrowing and Zod's optimized parsing)
- 5.4 [Use extend() for Adding Fields](references/object-extend-for-composition.md) — MEDIUM-HIGH (Merging objects manually loses type information; extend() preserves types and allows overriding fields safely)
- 5.5 [Use partial() for Update Schemas](references/object-partial-for-updates.md) — MEDIUM-HIGH (Creating separate update schemas duplicates definitions; partial() derives update schema from base, staying in sync)
- 5.6 [Use pick() and omit() for Schema Variants](references/object-pick-omit.md) — MEDIUM-HIGH (Copying fields between schemas creates duplication; pick/omit derive variants that stay in sync with base schema)
6. [Schema Composition](references/_sections.md#6-schema-composition) — **MEDIUM**
- 6.1 [Extract Shared Schemas into Reusable Modules](references/compose-shared-schemas.md) — MEDIUM (Duplicating schemas across files leads to inconsistency; shared schemas ensure single source of truth)
- 6.2 [Use intersection() for Type Combinations](references/compose-intersection.md) — MEDIUM (Manual field combination loses type relationships; intersection creates proper TypeScript intersection types)
- 6.3 [Use pipe() for Multi-Stage Validation](references/compose-pipe.md) — MEDIUM (Chaining transforms loses intermediate type info; pipe() explicitly shows data flow through validation stages)
- 6.4 [Use preprocess() for Data Normalization](references/compose-preprocess.md) — MEDIUM (Validating before cleaning data causes false rejections; preprocess() normalizes input before schema validation runs)
- 6.5 [Use z.lazy() for Recursive Schemas](references/compose-lazy-recursive.md) — MEDIUM (Recursive types reference themselves before definition; z.lazy() defers evaluation to enable self-referential schemas)
7. [Refinements & Transforms](references/_sections.md#7-refinements-&-transforms) — **MEDIUM**
- 7.1 [Add Path to Refinement Errors](references/refine-add-path.md) — MEDIUM (Errors without path show at object level; adding path highlights the specific field that failed)
- 7.2 [Choose refine() vs superRefine() Correctly](references/refine-vs-superrefine.md) — MEDIUM (refine() only reports one error; superRefine() enables multiple issues and custom error codes)
- 7.3 [Distinguish transform() from refine() and coerce()](references/refine-transform-coerce.md) — MEDIUM (Using wrong method causes validation to pass with wrong data; each method has distinct purpose)
- 7.4 [Use catch() for Fault-Tolerant Parsing](references/refine-catch.md) — MEDIUM (parse() fails on first invalid field; catch() provides fallback values, enabling partial success with degraded data)
- 7.5 [Use default() for Optional Fields with Defaults](references/refine-defaults.md) — MEDIUM (Manual default handling spreads logic across codebase; .default() centralizes defaults in schema)
8. [Performance & Bundle](references/_sections.md#8-performance-&-bundle) — **LOW-MEDIUM**
- 8.1 [Avoid Dynamic Schema Creation in Hot Paths](references/perf-avoid-dynamic-creation.md) — LOW-MEDIUM (Zod 4's JIT compilation makes schema creation slower; creating schemas in loops adds ~0.15ms per creation)
- 8.2 [Cache Schema Instances](references/perf-cache-schemas.md) — LOW-MEDIUM (Creating schemas on every render/call wastes CPU; module-level or memoized schemas are created once)
- 8.3 [Lazy Load Large Schemas](references/perf-lazy-loading.md) — LOW-MEDIUM (Large schemas increase initial bundle and parse time; dynamic imports defer loading until needed)
- 8.4 [Optimize Large Array Validation](references/perf-arrays.md) — LOW-MEDIUM (Validating 10,000 items takes ~100ms; early exits, sampling, or batching reduce time for large datasets)
- 8.5 [Use Zod Mini for Bundle-Sensitive Applications](references/perf-zod-mini.md) — LOW-MEDIUM (Full Zod is ~17kb gzipped; Zod Mini is ~1.9kb - 85% smaller for frontend-critical bundles)
---
## References
1. [https://zod.dev/](https://zod.dev/)
2. [https://zod.dev/v4](https://zod.dev/v4)
3. [https://github.com/colinhacks/zod](https://github.com/colinhacks/zod)
4. [https://zod.dev/packages/mini](https://zod.dev/packages/mini)
5. [https://www.totaltypescript.com/tutorials/zod](https://www.totaltypescript.com/tutorials/zod)
6. [https://zod.dev/error-handling](https://zod.dev/error-handling)
7. [https://zod.dev/api](https://zod.dev/api)
---
## Source Files
This document was compiled from individual reference files. For detailed editing or extension:
| File | Description |
| -------------------------------------------------------------- | ---------------------------------------- |
| [references/_sections.md](references/_sections.md) | Category definitions and impact ordering |
| [assets/templates/_template.md](assets/templates/_template.md) | Template for creating new rules |
| [SKILL.md](SKILL.md) | Quick reference entry point |
| [metadata.json](metadata.json) | Version and reference URLs |
+79
View File
@@ -0,0 +1,79 @@
# Zod Best Practices Skill
A comprehensive guide for using Zod effectively in TypeScript applications. This skill provides 42 rules across 8 categories, organized by impact to help AI agents and developers write better validation code.
## Overview
Zod is a TypeScript-first schema declaration and validation library. This skill covers best practices for:
- **Schema Definition**: Choosing correct types, avoiding `z.any()`, proper string validations
- **Parsing & Validation**: Using `safeParse()`, async validation, error handling
- **Type Inference**: Leveraging `z.infer`, distinguishing input/output types
- **Error Handling**: Custom messages, internationalization, form error display
- **Object Schemas**: strict/strip modes, partial updates, discriminated unions
- **Schema Composition**: Reusable schemas, intersections, recursive types
- **Refinements & Transforms**: Custom validation, data transformation
- **Performance**: Caching, Zod Mini, lazy loading, batch validation
## Usage
### For Claude Code / AI Agents
The skill is automatically loaded when working with Zod code. Reference specific rules:
```
See rules/parse-use-safeparse.md for safeParse best practices
```
### For Developers
Read `SKILL.md` for a quick reference, or `AGENTS.md` for the full compiled guide.
## File Structure
```
zod/
├── SKILL.md # Quick reference with rule index
├── AGENTS.md # Full compiled guide (all rules)
├── metadata.json # Version, categories, references
├── README.md # This file
└── rules/
├── _sections.md # Category definitions
├── _template.md # Rule template
├── schema-*.md # Schema definition rules
├── parse-*.md # Parsing rules
├── type-*.md # Type inference rules
├── error-*.md # Error handling rules
├── object-*.md # Object schema rules
├── compose-*.md # Composition rules
├── refine-*.md # Refinement rules
└── perf-*.md # Performance rules
```
## Rule Categories
| Priority | Category | Rules | Impact |
| -------- | ------------------------ | ----- | ----------- |
| 1 | Schema Definition | 6 | CRITICAL |
| 2 | Parsing & Validation | 6 | CRITICAL |
| 3 | Type Inference | 5 | HIGH |
| 4 | Error Handling | 5 | HIGH |
| 5 | Object Schemas | 6 | MEDIUM-HIGH |
| 6 | Schema Composition | 5 | MEDIUM |
| 7 | Refinements & Transforms | 5 | MEDIUM |
| 8 | Performance & Bundle | 5 | LOW-MEDIUM |
## Key Principles
1. **Type Safety First**: Always use `z.infer`, never duplicate types manually
2. **Validate at Boundaries**: Parse external data immediately at entry points
3. **User-Friendly Errors**: Provide custom messages, collect all issues
4. **Single Source of Truth**: Schema defines validation AND TypeScript types
5. **Composition Over Duplication**: Use extend, pick, omit, partial
## References
- [Zod Official Documentation](https://zod.dev/)
- [Zod v4 Release Notes](https://zod.dev/v4)
- [Zod GitHub](https://github.com/colinhacks/zod)
- [Zod Mini](https://zod.dev/packages/mini)
+128
View File
@@ -0,0 +1,128 @@
---
name: zod
description: Zod schema validation best practices for type safety, parsing, and error handling. This skill should be used when defining z.object schemas, using z.string validations, safeParse, or z.infer. This skill does NOT cover React Hook Form integration patterns (use react-hook-form skill) or OpenAPI client generation (use orval skill).
---
# Zod Best Practices
Comprehensive schema validation guide for Zod in TypeScript applications. Contains 43 rules across 8 categories, prioritized by impact to guide automated refactoring and code generation.
## When to Apply
Reference these guidelines when:
- Writing new Zod schemas
- Choosing between parse() and safeParse()
- Implementing type inference with z.infer
- Handling validation errors for user feedback
- Composing complex object schemas
- Using refinements and transforms
- Optimizing bundle size and validation performance
- Reviewing Zod code for best practices
## Rule Categories by Priority
| Priority | Category | Impact | Prefix |
| -------- | ------------------------ | ----------- | ---------- |
| 1 | Schema Definition | CRITICAL | `schema-` |
| 2 | Parsing & Validation | CRITICAL | `parse-` |
| 3 | Type Inference | HIGH | `type-` |
| 4 | Error Handling | HIGH | `error-` |
| 5 | Object Schemas | MEDIUM-HIGH | `object-` |
| 6 | Schema Composition | MEDIUM | `compose-` |
| 7 | Refinements & Transforms | MEDIUM | `refine-` |
| 8 | Performance & Bundle | LOW-MEDIUM | `perf-` |
## Quick Reference
### 1. Schema Definition (CRITICAL)
- `schema-use-primitives-correctly` - Use correct primitive schemas for each type
- `schema-use-unknown-not-any` - Use z.unknown() instead of z.any() for type safety
- `schema-avoid-optional-abuse` - Avoid overusing optional fields
- `schema-string-validations` - Apply string validations at schema definition
- `schema-use-enums` - Use enums for fixed string values
- `schema-coercion-for-form-data` - Use coercion for form and query data
### 2. Parsing & Validation (CRITICAL)
- `parse-use-safeparse` - Use safeParse() for user input
- `parse-async-for-async-refinements` - Use parseAsync for async refinements
- `parse-handle-all-issues` - Handle all validation issues not just first
- `parse-validate-early` - Validate at system boundaries
- `parse-avoid-double-validation` - Avoid validating same data twice
- `parse-never-trust-json` - Never trust JSON.parse output
### 3. Type Inference (HIGH)
- `type-use-z-infer` - Use z.infer instead of manual types
- `type-input-vs-output` - Distinguish z.input from z.infer for transforms
- `type-export-schemas-and-types` - Export both schemas and inferred types
- `type-branded-types` - Use branded types for domain safety
- `type-enable-strict-mode` - Enable TypeScript strict mode
### 4. Error Handling (HIGH)
- `error-custom-messages` - Provide custom error messages
- `error-use-flatten` - Use flatten() for form error display
- `error-path-for-nested` - Use issue.path for nested error location
- `error-i18n` - Implement internationalized error messages
- `error-avoid-throwing-in-refine` - Return false instead of throwing in refine
### 5. Object Schemas (MEDIUM-HIGH)
- `object-strict-vs-strip` - Choose strict() vs strip() for unknown keys
- `object-partial-for-updates` - Use partial() for update schemas
- `object-pick-omit` - Use pick() and omit() for schema variants
- `object-extend-for-composition` - Use extend() for adding fields
- `object-optional-vs-nullable` - Distinguish optional() from nullable()
- `object-discriminated-unions` - Use discriminated unions for type narrowing
### 6. Schema Composition (MEDIUM)
- `compose-shared-schemas` - Extract shared schemas into reusable modules
- `compose-intersection` - Use intersection() for type combinations
- `compose-lazy-recursive` - Use z.lazy() for recursive schemas
- `compose-preprocess` - Use preprocess() for data normalization
- `compose-pipe` - Use pipe() for multi-stage validation
### 7. Refinements & Transforms (MEDIUM)
- `refine-vs-superrefine` - Choose refine() vs superRefine() correctly
- `refine-transform-coerce` - Distinguish transform() from refine() and coerce()
- `refine-add-path` - Add path to refinement errors
- `refine-defaults` - Use default() for optional fields with defaults
- `refine-catch` - Use catch() for fault-tolerant parsing
### 8. Performance & Bundle (LOW-MEDIUM)
- `perf-cache-schemas` - Cache schema instances
- `perf-zod-mini` - Use Zod Mini for bundle-sensitive applications
- `perf-avoid-dynamic-creation` - Avoid dynamic schema creation in hot paths
- `perf-lazy-loading` - Lazy load large schemas
- `perf-arrays` - Optimize large array validation
## How to Use
Read individual reference files for detailed explanations and code examples:
- [Section definitions](references/_sections.md) - Category structure and impact levels
- [Rule template](assets/templates/_template.md) - Template for adding new rules
- Individual rules: `references/{prefix}-{slug}.md`
## Full Compiled Document
For the complete guide with all rules expanded: `AGENTS.md`
## Related Skills
- For React Hook Form integration, see `react-hook-form` skill
- For API client generation, see `orval` skill
## Sources
- [Zod Official Documentation](https://zod.dev/)
- [Zod v4 Release Notes](https://zod.dev/v4)
- [Zod GitHub Repository](https://github.com/colinhacks/zod)
- [Zod Mini](https://zod.dev/packages/mini)
- [Total TypeScript Zod Tutorial](https://www.totaltypescript.com/tutorials/zod)
@@ -0,0 +1,31 @@
---
title: Rule Title Here
impact: CRITICAL|HIGH|MEDIUM-HIGH|MEDIUM|LOW-MEDIUM|LOW
impactDescription: Quantified impact (e.g., "2-10× improvement", "prevents runtime crashes")
tags: section-prefix, technique, tool, related-concepts
---
## Rule Title Here
1-3 sentences explaining WHY this matters. Focus on validation implications and cascade effects.
**Incorrect (what's wrong):**
```typescript
// Bad code example - production-realistic, not strawman
// Comments explaining the cost
```
**Correct (what's right):**
```typescript
// Good code example - minimal diff from incorrect
// Comments explaining the benefit
```
**When NOT to use this pattern:**
- Exception 1
- Exception 2
Reference: [Reference Title](URL)
+69
View File
@@ -0,0 +1,69 @@
{
"version": "1.1.1",
"organization": "community",
"technology": "Zod",
"date": "January 2026",
"abstract": "Comprehensive schema validation guide for Zod in TypeScript applications, designed for AI agents and LLMs. Contains 43 rules across 8 categories, prioritized by impact from critical (schema definition, parsing) to incremental (performance, bundle optimization). Each rule includes detailed explanations, real-world examples comparing incorrect vs. correct implementations, and specific impact metrics to guide automated refactoring and code generation.",
"references": [
"https://zod.dev/",
"https://zod.dev/v4",
"https://github.com/colinhacks/zod",
"https://zod.dev/packages/mini",
"https://www.totaltypescript.com/tutorials/zod",
"https://zod.dev/error-handling",
"https://zod.dev/api"
],
"categories": [
{
"name": "Schema Definition",
"prefix": "schema",
"impact": "CRITICAL",
"ruleCount": 6
},
{
"name": "Parsing & Validation",
"prefix": "parse",
"impact": "CRITICAL",
"ruleCount": 6
},
{
"name": "Type Inference",
"prefix": "type",
"impact": "HIGH",
"ruleCount": 5
},
{
"name": "Error Handling",
"prefix": "error",
"impact": "HIGH",
"ruleCount": 5
},
{
"name": "Object Schemas",
"prefix": "object",
"impact": "MEDIUM-HIGH",
"ruleCount": 6
},
{
"name": "Schema Composition",
"prefix": "compose",
"impact": "MEDIUM",
"ruleCount": 5
},
{
"name": "Refinements & Transforms",
"prefix": "refine",
"impact": "MEDIUM",
"ruleCount": 5
},
{
"name": "Performance & Bundle",
"prefix": "perf",
"impact": "LOW-MEDIUM",
"ruleCount": 5
}
],
"totalRules": 43,
"zodVersion": "4.x",
"category": "API"
}
@@ -0,0 +1,46 @@
# Sections
This file defines all sections, their ordering, impact levels, and descriptions.
The section ID (in parentheses) is the filename prefix used to group rules.
---
## 1. Schema Definition (schema)
**Impact:** CRITICAL
**Description:** Schema definition is the foundation of all Zod validation; incorrect or overly permissive schemas cascade errors through your entire application, allowing invalid data to corrupt downstream logic.
## 2. Parsing & Validation (parse)
**Impact:** CRITICAL
**Description:** Parsing is the core Zod operation; using `parse()` vs `safeParse()` incorrectly causes either unhandled exceptions crashing your app or silent failures that let invalid data through.
## 3. Type Inference (type)
**Impact:** HIGH
**Description:** Zod's TypeScript integration eliminates duplicate type definitions; poor inference practices force manual type declarations that drift from schemas, losing the core benefit of Zod.
## 4. Error Handling (error)
**Impact:** HIGH
**Description:** Error handling determines user experience; poorly structured error handling produces cryptic messages that harm UX and make debugging validation failures nearly impossible.
## 5. Object Schemas (object)
**Impact:** MEDIUM-HIGH
**Description:** Objects are the most common schema type; misconfiguring strict/passthrough/strip modes either leaks unexpected data to clients or fails validation on legitimate requests.
## 6. Schema Composition (compose)
**Impact:** MEDIUM
**Description:** Schema composition enables reuse and maintainability; poor composition patterns lead to duplicated schemas that drift apart or deeply nested structures that are impossible to maintain.
## 7. Refinements & Transforms (refine)
**Impact:** MEDIUM
**Description:** Refinements and transforms handle custom validation and data coercion; choosing the wrong method causes performance issues, incorrect error aggregation, or async parsing failures.
## 8. Performance & Bundle (perf)
**Impact:** LOW-MEDIUM
**Description:** Zod's performance and bundle size affect application startup and validation throughput; understanding when to use Zod Mini or cache schemas prevents unnecessary overhead in performance-critical paths.
@@ -0,0 +1,143 @@
---
title: Use intersection() for Type Combinations
impact: MEDIUM
impactDescription: Manual field combination loses type relationships; intersection creates proper TypeScript intersection types
tags: compose, intersection, and, combination
---
## Use intersection() for Type Combinations
When you need an object that satisfies multiple schemas simultaneously (like combining a base type with mixins), use `.and()` or `z.intersection()`. This creates proper TypeScript intersection types and validates against all schemas.
**Incorrect (manual combination):**
```typescript
import { z } from "zod";
const timestampsSchema = z.object({
createdAt: z.date(),
updatedAt: z.date()
});
const softDeleteSchema = z.object({
deletedAt: z.date().nullable(),
deletedBy: z.string().nullable()
});
const userSchema = z.object({
id: z.string(),
name: z.string(),
email: z.string().email()
});
// Manual combination - verbose and error-prone
const fullUserSchema = z.object({
id: z.string(),
name: z.string(),
email: z.string().email(),
createdAt: z.date(),
updatedAt: z.date(),
deletedAt: z.date().nullable(),
deletedBy: z.string().nullable()
});
```
**Correct (using intersection):**
```typescript
import { z } from "zod";
const timestampsSchema = z.object({
createdAt: z.date(),
updatedAt: z.date()
});
const softDeleteSchema = z.object({
deletedAt: z.date().nullable(),
deletedBy: z.string().nullable()
});
const userSchema = z.object({
id: z.string(),
name: z.string(),
email: z.string().email()
});
// Using .and() for intersection
const fullUserSchema = userSchema.and(timestampsSchema).and(softDeleteSchema);
// Or using z.intersection()
const fullUserSchema2 = z.intersection(
z.intersection(userSchema, timestampsSchema),
softDeleteSchema
);
type FullUser = z.infer<typeof fullUserSchema>;
// {
// id: string;
// name: string;
// email: string;
// createdAt: Date;
// updatedAt: Date;
// deletedAt: Date | null;
// deletedBy: string | null;
// }
```
**Creating mixins:**
```typescript
// Reusable mixins
const auditable = z.object({
createdBy: z.string(),
updatedBy: z.string()
});
const versioned = z.object({
version: z.number().int().positive()
});
const tagged = z.object({
tags: z.array(z.string())
});
// Apply mixins to any schema
function withAudit<T extends z.ZodRawShape>(schema: z.ZodObject<T>) {
return schema.and(auditable).and(timestampsSchema);
}
function withVersioning<T extends z.ZodRawShape>(schema: z.ZodObject<T>) {
return schema.and(versioned);
}
// Usage
const documentSchema = z.object({
id: z.string(),
title: z.string(),
content: z.string()
});
const fullDocumentSchema = withAudit(withVersioning(documentSchema));
```
**Intersection vs Merge:**
```typescript
// .merge() - replaces fields from first with second
const a = z.object({ x: z.string(), y: z.number() });
const b = z.object({ y: z.string() }); // y is string, not number
a.merge(b); // { x: string, y: string } - b's y wins
// .and() - requires fields to be compatible
// If both have y with different types, intersection fails at runtime
a.and(b); // Validation will fail - y can't be both number and string
```
**When NOT to use this pattern:**
- When schemas have overlapping fields with different types (use merge)
- When you need to override fields (use extend)
- Simple cases where extend works fine
Reference: [Zod API - intersection](https://zod.dev/api#intersection)
@@ -0,0 +1,138 @@
---
title: Use z.lazy() for Recursive Schemas
impact: MEDIUM
impactDescription: Recursive types reference themselves before definition; z.lazy() defers evaluation to enable self-referential schemas
tags: compose, lazy, recursive, trees
---
## Use z.lazy() for Recursive Schemas
TypeScript can't infer recursive Zod schema types automatically. Use `z.lazy()` to defer schema evaluation and manually provide the type annotation. This enables tree structures, nested comments, and other self-referential data.
**Incorrect (direct self-reference):**
```typescript
import { z } from "zod";
// This fails - categorySchema used before it's defined
const categorySchema = z.object({
id: z.string(),
name: z.string(),
children: z.array(categorySchema) // Error: Block-scoped variable used before declaration
});
```
**Correct (using z.lazy with type annotation):**
```typescript
import { z } from "zod";
// Define the type manually
interface Category {
id: string;
name: string;
children: Category[];
}
// Use z.lazy() to defer schema reference
const categorySchema: z.ZodType<Category> = z.object({
id: z.string(),
name: z.string(),
children: z.lazy(() => z.array(categorySchema))
});
// Now it works
const tree = categorySchema.parse({
id: "1",
name: "Electronics",
children: [
{
id: "2",
name: "Phones",
children: [
{ id: "3", name: "iPhones", children: [] },
{ id: "4", name: "Android", children: [] }
]
}
]
});
```
**Common recursive patterns:**
```typescript
// Comments with replies
interface Comment {
id: string;
content: string;
author: string;
replies: Comment[];
}
const commentSchema: z.ZodType<Comment> = z.object({
id: z.string(),
content: z.string(),
author: z.string(),
replies: z.lazy(() => z.array(commentSchema))
});
// Binary tree
interface TreeNode {
value: number;
left: TreeNode | null;
right: TreeNode | null;
}
const treeNodeSchema: z.ZodType<TreeNode> = z.object({
value: z.number(),
left: z.lazy(() => treeNodeSchema.nullable()),
right: z.lazy(() => treeNodeSchema.nullable())
});
// Nested menu structure
interface MenuItem {
label: string;
href?: string;
children?: MenuItem[];
}
const menuItemSchema: z.ZodType<MenuItem> = z.object({
label: z.string(),
href: z.string().url().optional(),
children: z.lazy(() => z.array(menuItemSchema)).optional()
});
```
**JSON Schema (any valid JSON):**
```typescript
type JSONValue = string | number | boolean | null | JSONValue[] | { [key: string]: JSONValue };
const jsonValueSchema: z.ZodType<JSONValue> = z.lazy(() =>
z.union([
z.string(),
z.number(),
z.boolean(),
z.null(),
z.array(jsonValueSchema),
z.record(jsonValueSchema)
])
);
```
**Performance consideration:**
```typescript
// z.lazy() has minimal overhead - the function is called once
// and the schema is cached. Safe to use in hot paths.
// If validating many recursive structures, the schema itself
// is only built once. Validation performance depends on data depth.
```
**When NOT to use this pattern:**
- Non-recursive schemas (lazy adds unnecessary indirection)
- When you can flatten the structure instead
Reference: [Zod API - Recursive Types](https://zod.dev/api#recursive-types)
@@ -0,0 +1,114 @@
---
title: Use pipe() for Multi-Stage Validation
impact: MEDIUM
impactDescription: Chaining transforms loses intermediate type info; pipe() explicitly shows data flow through validation stages
tags: compose, pipe, pipeline, transform
---
## Use pipe() for Multi-Stage Validation
When data needs to pass through multiple validation stages (coerce string to number, then validate range, then transform to currency), use `.pipe()` to chain schemas. This makes the data transformation pipeline explicit and each stage's type clear.
**Incorrect (unclear transformation chain):**
```typescript
import { z } from "zod";
// All transforms in one long chain - hard to understand stages
const priceSchema = z
.string()
.transform((s) => parseFloat(s.replace(/[$,]/g, "")))
.refine((n) => !isNaN(n), "Invalid number")
.refine((n) => n >= 0, "Must be positive")
.refine((n) => n <= 1000000, "Too large")
.transform((n) => Math.round(n * 100));
// What type is n at each stage? Hard to tell
```
**Correct (using pipe for clear stages):**
```typescript
import { z } from "zod";
// Stage 1: Coerce string to number
const parsePrice = z.string().transform((s) => {
const cleaned = s.replace(/[$,]/g, "");
const parsed = parseFloat(cleaned);
if (isNaN(parsed)) throw new Error("Invalid number");
return parsed;
});
// Stage 2: Validate number constraints
const validPrice = z.number().min(0, "Must be positive").max(1000000, "Too large");
// Stage 3: Transform to cents
const centsPrice = z.number().transform((n) => Math.round(n * 100));
// Pipe them together - clear data flow
const priceSchema = parsePrice.pipe(validPrice).pipe(centsPrice);
// Type at each stage is clear:
// string -> number (parsePrice)
// number -> number (validPrice)
// number -> number (centsPrice, but semantically cents)
```
**Coercion with validation:**
```typescript
// Without pipe - validation runs on raw input
const schema1 = z.coerce.number().min(1);
schema1.parse(""); // Passes! Empty string coerces to 0, but then... wait, 0 < 1
// With pipe - validation runs on coerced value
const schema2 = z.coerce.number().pipe(z.number().min(1));
schema2.parse(""); // Fails correctly: 0 is less than 1
```
**Complex data transformation:**
```typescript
// Input: CSV string of emails
// Output: Array of normalized, validated email objects
const emailArraySchema = z
.string()
// Stage 1: Split CSV
.transform((s) => s.split(",").map((e) => e.trim()))
// Stage 2: Validate as email array
.pipe(z.array(z.string().email()))
// Stage 3: Transform to objects
.pipe(
z.array(z.string()).transform((emails) =>
emails.map((email) => ({
address: email.toLowerCase(),
domain: email.split("@")[1]
}))
)
);
emailArraySchema.parse("John@Example.com, jane@test.com");
// [
// { address: 'john@example.com', domain: 'Example.com' },
// { address: 'jane@test.com', domain: 'test.com' }
// ]
```
**Type inference with pipe:**
```typescript
const schema = z.string().pipe(z.coerce.number()).pipe(z.number().positive());
type Input = z.input<typeof schema>; // string
type Output = z.output<typeof schema>; // number
// Each pipe stage has clear input/output types
```
**When NOT to use this pattern:**
- Simple single-stage validation (adds unnecessary complexity)
- When `.refine()` chain is sufficient and readable
Reference: [Zod API - pipe](https://zod.dev/api#pipe)
@@ -0,0 +1,137 @@
---
title: Use preprocess() for Data Normalization
impact: MEDIUM
impactDescription: Validating before cleaning data causes false rejections; preprocess() normalizes input before schema validation runs
tags: compose, preprocess, normalize, cleaning
---
## Use preprocess() for Data Normalization
When incoming data needs normalization before validation (trimming whitespace, parsing JSON strings, converting formats), use `z.preprocess()`. This runs a function on the raw input before Zod's type checking, allowing you to clean data that would otherwise fail validation.
**Incorrect (validation fails on unnormalized data):**
```typescript
import { z } from "zod";
const userSchema = z.object({
name: z.string().min(1),
email: z.string().email(),
config: z.object({
theme: z.string()
})
});
// Raw form data
const formData = {
name: " John Doe ", // Has whitespace
email: "JOHN@EXAMPLE.COM", // Uppercase
config: '{"theme": "dark"}' // JSON string, not object
};
userSchema.parse(formData);
// ZodError: Expected object, received string at "config"
```
**Correct (using preprocess):**
```typescript
import { z } from "zod";
// Preprocess normalizes before validation
const trimmedString = z.preprocess(
(val) => (typeof val === "string" ? val.trim() : val),
z.string()
);
const lowercaseEmail = z.preprocess(
(val) => (typeof val === "string" ? val.toLowerCase().trim() : val),
z.string().email()
);
const jsonObject = z.preprocess(
(val) => {
if (typeof val === "string") {
try {
return JSON.parse(val);
} catch {
return val; // Let Zod report the error
}
}
return val;
},
z.object({ theme: z.string() })
);
const userSchema = z.object({
name: trimmedString.pipe(z.string().min(1)),
email: lowercaseEmail,
config: jsonObject
});
const formData = {
name: " John Doe ",
email: "JOHN@EXAMPLE.COM",
config: '{"theme": "dark"}'
};
const user = userSchema.parse(formData);
// { name: 'John Doe', email: 'john@example.com', config: { theme: 'dark' } }
```
**Common preprocessing patterns:**
```typescript
// Trim all strings
const trimmedString = z.preprocess(
(val) => (typeof val === "string" ? val.trim() : val),
z.string()
);
// Parse numeric strings
const numericString = z.preprocess(
(val) => (typeof val === "string" ? Number(val) : val),
z.number()
);
// Parse boolean-like values
const booleanLike = z.preprocess((val) => {
if (val === "true" || val === "1" || val === 1) return true;
if (val === "false" || val === "0" || val === 0) return false;
return val;
}, z.boolean());
// Parse date strings
const dateString = z.preprocess((val) => (typeof val === "string" ? new Date(val) : val), z.date());
// Split comma-separated strings into arrays
const csvArray = z.preprocess(
(val) => (typeof val === "string" ? val.split(",").map((s) => s.trim()) : val),
z.array(z.string())
);
```
**Preprocess vs Transform:**
```typescript
// preprocess() runs BEFORE type checking
// Use for: Normalizing input format before validation
z.preprocess((val) => String(val).trim(), z.string().min(1));
// transform() runs AFTER type checking
// Use for: Converting validated data to different format
z.string().transform((s) => s.toUpperCase());
// Order of operations:
// 1. preprocess receives raw unknown input
// 2. Zod validates the preprocessed value
// 3. transform converts the validated value
```
**When NOT to use this pattern:**
- When `.coerce` methods handle the conversion (simpler)
- When transformation should happen after validation (use transform)
- When normalization could hide validation errors
Reference: [Zod API - preprocess](https://zod.dev/api#preprocess)
@@ -0,0 +1,142 @@
---
title: Extract Shared Schemas into Reusable Modules
impact: MEDIUM
impactDescription: Duplicating schemas across files leads to inconsistency; shared schemas ensure single source of truth
tags: compose, reuse, modules, organization
---
## Extract Shared Schemas into Reusable Modules
When the same schema pattern appears in multiple places, extract it into a shared module. This ensures consistency, reduces duplication, and makes changes propagate automatically across your codebase.
**Incorrect (duplicating schemas):**
```typescript
// api/users.ts
import { z } from "zod";
const userSchema = z.object({
id: z.string().uuid(),
email: z.string().email(),
name: z.string().min(1),
createdAt: z.date()
});
// api/orders.ts
import { z } from "zod";
const orderSchema = z.object({
id: z.string().uuid(), // Duplicated
userId: z.string().uuid(), // Same pattern
items: z.array(
z.object({
productId: z.string().uuid(), // Duplicated
quantity: z.number().int().positive()
})
),
createdAt: z.date() // Duplicated
});
// api/comments.ts
import { z } from "zod";
const commentSchema = z.object({
id: z.string().uuid(), // Same duplication
userId: z.string().uuid(),
content: z.string().min(1),
createdAt: z.date() // Inconsistency risk
});
```
**Correct (shared schema modules):**
```typescript
// schemas/common.ts
import { z } from "zod";
// Reusable ID types
export const uuid = z.string().uuid();
export type UUID = z.infer<typeof uuid>;
// Timestamps
export const timestamps = z.object({
createdAt: z.date(),
updatedAt: z.date()
});
// Base entity with ID
export const baseEntity = z
.object({
id: uuid
})
.merge(timestamps);
export type BaseEntity = z.infer<typeof baseEntity>;
// Pagination
export const paginationParams = z.object({
page: z.coerce.number().int().positive().default(1),
limit: z.coerce.number().int().min(1).max(100).default(20)
});
```
```typescript
// schemas/user.ts
import { z } from "zod";
import { baseEntity, uuid } from "./common";
export const userSchema = baseEntity.extend({
email: z.string().email(),
name: z.string().min(1)
});
export type User = z.infer<typeof userSchema>;
```
```typescript
// schemas/order.ts
import { z } from "zod";
import { baseEntity, uuid } from "./common";
const orderItemSchema = z.object({
productId: uuid,
quantity: z.number().int().positive()
});
export const orderSchema = baseEntity.extend({
userId: uuid,
items: z.array(orderItemSchema).min(1),
total: z.number().positive()
});
export type Order = z.infer<typeof orderSchema>;
```
**Organizing schema modules:**
```
schemas/
├── common.ts # Shared primitives and base schemas
├── user.ts # User-related schemas
├── order.ts # Order-related schemas
├── product.ts # Product-related schemas
└── index.ts # Re-exports for convenience
```
```typescript
// schemas/index.ts
export * from "./common";
export * from "./user";
export * from "./order";
export * from "./product";
// Usage
import { userSchema, orderSchema, uuid, type User } from "@/schemas";
```
**When NOT to use this pattern:**
- One-off schemas used only in a single file
- When schemas look similar but have different semantics (don't over-abstract)
Reference: [Zod - Type Inference](https://zod.dev/api#type-inference)
@@ -0,0 +1,134 @@
---
title: Return False Instead of Throwing in Refine
impact: HIGH
impactDescription: Throwing in refine stops validation early, hiding other errors; returning false allows Zod to collect all issues
tags: error, refine, validation, best-practices
---
## Return False Instead of Throwing in Refine
When using `.refine()` for custom validation, return `false` for invalid data instead of throwing an error. Throwing stops validation immediately, preventing Zod from collecting other validation errors. This results in poor UX where users fix one error only to discover another.
**Incorrect (throwing in refine):**
```typescript
import { z } from "zod";
const passwordSchema = z
.object({
password: z.string().min(8),
confirmPassword: z.string()
})
.refine((data) => {
if (data.password !== data.confirmPassword) {
// Throwing stops all further validation
throw new Error("Passwords do not match");
}
return true;
});
const formSchema = z.object({
email: z.string().email(),
passwords: passwordSchema,
terms: z.boolean().refine((v) => v === true, "Must accept terms")
});
// If passwords don't match, user never learns about other errors
formSchema.safeParse({
email: "bad-email",
passwords: { password: "12345678", confirmPassword: "different" },
terms: false
});
// Only shows: "Passwords do not match"
// Hidden: "Invalid email", "Must accept terms"
```
**Correct (returning false in refine):**
```typescript
import { z } from "zod";
const passwordSchema = z
.object({
password: z.string().min(8),
confirmPassword: z.string()
})
.refine((data) => data.password === data.confirmPassword, {
message: "Passwords do not match",
path: ["confirmPassword"]
});
const formSchema = z.object({
email: z.string().email(),
passwords: passwordSchema,
terms: z.boolean().refine((v) => v === true, "Must accept terms")
});
// All errors are collected
formSchema.safeParse({
email: "bad-email",
passwords: { password: "12345678", confirmPassword: "different" },
terms: false
});
// Shows all errors:
// - "Invalid email"
// - "Passwords do not match"
// - "Must accept terms"
```
**For multiple validation rules, use superRefine:**
```typescript
const passwordSchema = z.string().superRefine((password, ctx) => {
// Check multiple rules, report all failures
if (password.length < 8) {
ctx.addIssue({
code: z.ZodIssueCode.custom,
message: "Password must be at least 8 characters"
});
}
if (!/[A-Z]/.test(password)) {
ctx.addIssue({
code: z.ZodIssueCode.custom,
message: "Password must contain an uppercase letter"
});
}
if (!/[0-9]/.test(password)) {
ctx.addIssue({
code: z.ZodIssueCode.custom,
message: "Password must contain a number"
});
}
// Don't return anything - issues are added via ctx
});
passwordSchema.safeParse("weak");
// All three errors reported at once
```
**Correct pattern for async validation:**
```typescript
const schema = z
.object({
email: z.string().email()
})
.refine(
async (data) => {
// Return boolean, don't throw
const exists = await checkEmailExists(data.email);
return !exists;
},
{ message: "Email already registered", path: ["email"] }
);
```
**When NOT to use this pattern:**
- When you need to abort validation entirely (security issues)
- When subsequent validations depend on current check passing
Reference: [Zod API - Refine](https://zod.dev/api#refine)
@@ -0,0 +1,127 @@
---
title: Provide Custom Error Messages
impact: HIGH
impactDescription: Default messages like "Expected string, received number" confuse users; custom messages like "Email is required" are actionable
tags: error, messages, user-experience, validation
---
## Provide Custom Error Messages
Zod's default error messages are technical and confusing for end users. Provide custom messages that are clear, specific, and actionable. This dramatically improves user experience when validation fails.
**Incorrect (default error messages):**
```typescript
import { z } from "zod";
const signupSchema = z.object({
email: z.string().email(),
password: z.string().min(8),
age: z.number().min(18)
});
signupSchema.parse({ email: "bad", password: "123", age: 15 });
// ZodError issues:
// - "Invalid email"
// - "String must contain at least 8 character(s)"
// - "Number must be greater than or equal to 18"
// Users see: "String must contain at least 8 character(s)" - what string?
```
**Correct (custom error messages):**
```typescript
import { z } from "zod";
const signupSchema = z.object({
email: z
.string({
required_error: "Email is required",
invalid_type_error: "Email must be text"
})
.email("Please enter a valid email address"),
password: z
.string({
required_error: "Password is required"
})
.min(8, "Password must be at least 8 characters"),
age: z
.number({
required_error: "Age is required",
invalid_type_error: "Age must be a number"
})
.min(18, "You must be at least 18 years old")
});
signupSchema.parse({ email: "bad", password: "123", age: 15 });
// ZodError issues:
// - "Please enter a valid email address"
// - "Password must be at least 8 characters"
// - "You must be at least 18 years old"
```
**Message types and when they trigger:**
```typescript
const schema = z
.string({
// When field is undefined
required_error: "This field is required",
// When field is wrong type (e.g., number instead of string)
invalid_type_error: "This field must be text",
// Fallback for any other error
message: "Invalid value"
})
.min(1, "Cannot be empty") // When length < 1
.max(100, "Too long") // When length > 100
.email("Invalid email format"); // When format fails
```
**Using error maps for consistent messaging:**
```typescript
const customErrorMap: z.ZodErrorMap = (issue, ctx) => {
// Customize messages by error code
if (issue.code === z.ZodIssueCode.too_small) {
if (issue.type === "string") {
return { message: `Must be at least ${issue.minimum} characters` };
}
if (issue.type === "number") {
return { message: `Must be at least ${issue.minimum}` };
}
}
if (issue.code === z.ZodIssueCode.invalid_type) {
if (issue.expected === "string") {
return { message: "Must be text" };
}
}
// Default to Zod's message
return { message: ctx.defaultError };
};
// Apply globally
z.setErrorMap(customErrorMap);
// Or per-schema
schema.parse(data, { errorMap: customErrorMap });
```
**Good error message principles:**
- Say what's wrong: "Password too short" not "Invalid password"
- Say how to fix it: "at least 8 characters" not just "too short"
- Use user's language: "email" not "string field at path .email"
- Be specific: "Must be a positive number" not "Invalid"
**When NOT to use this pattern:**
- Internal development scripts where technical errors are fine
- When you'll map errors to user-facing messages in the UI layer
Reference: [Zod Error Customization](https://zod.dev/error-customization)
+140
View File
@@ -0,0 +1,140 @@
---
title: Implement Internationalized Error Messages
impact: HIGH
impactDescription: Hardcoded English messages exclude non-English users; error maps enable localized messages for global applications
tags: error, i18n, localization, internationalization
---
## Implement Internationalized Error Messages
Hardcoded error messages in English exclude users who speak other languages. Use Zod's error map feature to provide localized messages based on user locale, making your application accessible globally.
**Incorrect (hardcoded English messages):**
```typescript
import { z } from "zod";
const userSchema = z.object({
name: z.string().min(1, "Name is required"),
email: z.string().email("Invalid email address"),
age: z.number().min(18, "You must be at least 18 years old")
});
// French users see English errors - poor UX
```
**Correct (localized error messages):**
```typescript
import { z } from "zod";
// Translation dictionaries
const translations = {
en: {
required: "This field is required",
invalidEmail: "Please enter a valid email address",
tooShort: (min: number) => `Must be at least ${min} characters`,
tooYoung: (min: number) => `You must be at least ${min} years old`
},
fr: {
required: "Ce champ est obligatoire",
invalidEmail: "Veuillez entrer une adresse email valide",
tooShort: (min: number) => `Doit contenir au moins ${min} caractères`,
tooYoung: (min: number) => `Vous devez avoir au moins ${min} ans`
},
es: {
required: "Este campo es requerido",
invalidEmail: "Por favor ingrese un correo electrónico válido",
tooShort: (min: number) => `Debe tener al menos ${min} caracteres`,
tooYoung: (min: number) => `Debes tener al menos ${min} años`
}
} as const;
type Locale = keyof typeof translations;
function createErrorMap(locale: Locale): z.ZodErrorMap {
const t = translations[locale];
return (issue, ctx) => {
switch (issue.code) {
case z.ZodIssueCode.invalid_type:
if (issue.received === "undefined") {
return { message: t.required };
}
break;
case z.ZodIssueCode.invalid_string:
if (issue.validation === "email") {
return { message: t.invalidEmail };
}
break;
case z.ZodIssueCode.too_small:
if (issue.type === "string") {
return { message: t.tooShort(issue.minimum as number) };
}
if (issue.type === "number") {
return { message: t.tooYoung(issue.minimum as number) };
}
break;
}
return { message: ctx.defaultError };
};
}
// Usage with user's locale
const userLocale: Locale = "fr";
const errorMap = createErrorMap(userLocale);
const userSchema = z.object({
name: z.string().min(1),
email: z.string().email(),
age: z.number().min(18)
});
const result = userSchema.safeParse({ name: "", email: "bad", age: 15 }, { errorMap });
// French error messages:
// - "Ce champ est obligatoire"
// - "Veuillez entrer une adresse email valide"
// - "Vous devez avoir au moins 18 ans"
```
**Setting error map globally:**
```typescript
// At application startup
const userLocale = getUserLocale(); // From cookie, header, etc.
z.setErrorMap(createErrorMap(userLocale));
// All schemas now use localized messages
```
**With i18n libraries (react-intl, i18next):**
```typescript
import { useIntl } from "react-intl";
function useZodErrorMap() {
const intl = useIntl();
return (issue: z.ZodIssue, ctx: z.ErrorMapCtx) => {
switch (issue.code) {
case z.ZodIssueCode.too_small:
return {
message: intl.formatMessage({ id: "validation.tooShort" }, { min: issue.minimum })
};
// ...
}
return { message: ctx.defaultError };
};
}
```
**When NOT to use this pattern:**
- Internal tools used only by your team
- Single-language applications
Reference: [Zod Error Customization - Internationalization](https://zod.dev/error-customization#internationalization)
@@ -0,0 +1,135 @@
---
title: Use issue.path for Nested Error Location
impact: HIGH
impactDescription: Without path information, users can't identify which nested field failed; path provides exact location in complex objects
tags: error, path, nested, debugging
---
## Use issue.path for Nested Error Location
When validating nested objects or arrays, `issue.path` tells you exactly where the error occurred. This is essential for highlighting the correct form field or providing precise error messages in complex data structures.
**Incorrect (ignoring path information):**
```typescript
import { z } from "zod";
const orderSchema = z.object({
customer: z.object({
name: z.string().min(1, "Name required"),
address: z.object({
street: z.string().min(1, "Street required"),
city: z.string().min(1, "City required")
})
}),
items: z.array(
z.object({
productId: z.string(),
quantity: z.number().positive("Quantity must be positive")
})
)
});
const result = orderSchema.safeParse({
customer: { name: "", address: { street: "", city: "" } },
items: [{ productId: "abc", quantity: -1 }]
});
if (!result.success) {
// Only showing message, not WHERE the error is
result.error.issues.forEach((issue) => {
console.log(issue.message); // 'Name required', 'Street required', 'Quantity must be positive'
// User: "Which quantity? Which field?"
});
}
```
**Correct (using path information):**
```typescript
import { z } from "zod";
const orderSchema = z.object({
customer: z.object({
name: z.string().min(1, "Name required"),
address: z.object({
street: z.string().min(1, "Street required"),
city: z.string().min(1, "City required")
})
}),
items: z.array(
z.object({
productId: z.string(),
quantity: z.number().positive("Quantity must be positive")
})
)
});
const result = orderSchema.safeParse({
customer: { name: "", address: { street: "", city: "" } },
items: [{ productId: "abc", quantity: -1 }]
});
if (!result.success) {
result.error.issues.forEach((issue) => {
// path is an array of keys/indices
console.log(`${issue.path.join(".")}: ${issue.message}`);
// 'customer.name: Name required'
// 'customer.address.street: Street required'
// 'customer.address.city: City required'
// 'items.0.quantity: Quantity must be positive'
});
}
```
**Building field-specific error mapping:**
```typescript
function mapErrorsToFields(error: z.ZodError) {
const fieldErrors: Map<string, string[]> = new Map();
for (const issue of error.issues) {
const fieldPath = issue.path.join(".");
const existing = fieldErrors.get(fieldPath) ?? [];
fieldErrors.set(fieldPath, [...existing, issue.message]);
}
return fieldErrors;
}
// Usage
const errors = mapErrorsToFields(result.error);
errors.get("customer.name"); // ['Name required']
errors.get("items.0.quantity"); // ['Quantity must be positive']
```
**For array items, get index from path:**
```typescript
const itemsWithErrors: Set<number> = new Set();
result.error.issues.forEach((issue) => {
if (issue.path[0] === "items" && typeof issue.path[1] === "number") {
itemsWithErrors.add(issue.path[1]);
}
});
// Highlight items at indices: Set { 0 }
```
**Using path with format():**
```typescript
const formatted = result.error.format();
// Access errors at any path level
formatted.customer?.address?.city?._errors; // ['City required']
formatted.items?.[0]?.quantity?._errors; // ['Quantity must be positive']
```
**When NOT to use this pattern:**
- Flat objects where field name is obvious
- When using form libraries that handle path mapping
Reference: [Zod Error Handling](https://zod.dev/error-handling)
@@ -0,0 +1,135 @@
---
title: Use flatten() for Form Error Display
impact: HIGH
impactDescription: Raw ZodError.issues requires manual path parsing; flatten() provides field-keyed errors ready for form display
tags: error, flatten, forms, user-experience
---
## Use flatten() for Form Error Display
`ZodError.issues` is an array that requires manual processing to map errors to form fields. `ZodError.flatten()` returns an object with `fieldErrors` keyed by field name, ready for form libraries and UI display.
**Incorrect (manual issue processing):**
```typescript
import { z } from "zod";
const formSchema = z.object({
email: z.string().email("Invalid email"),
password: z.string().min(8, "Password too short"),
profile: z.object({
name: z.string().min(1, "Name required")
})
});
function getFieldErrors(error: z.ZodError) {
const errors: Record<string, string> = {};
for (const issue of error.issues) {
// Manual path joining - error prone
const field = issue.path.join(".");
if (!errors[field]) {
errors[field] = issue.message;
}
}
return errors;
}
const result = formSchema.safeParse(data);
if (!result.success) {
const errors = getFieldErrors(result.error);
// { email: 'Invalid email', 'profile.name': 'Name required' }
}
```
**Correct (using flatten):**
```typescript
import { z } from "zod";
const formSchema = z.object({
email: z.string().email("Invalid email"),
password: z.string().min(8, "Password too short"),
profile: z.object({
name: z.string().min(1, "Name required")
})
});
const result = formSchema.safeParse(data);
if (!result.success) {
const { formErrors, fieldErrors } = result.error.flatten();
// formErrors: string[] - top-level errors (from .refine on the object)
// fieldErrors: { [key]: string[] } - errors by field
// Ready for form display
console.log(fieldErrors);
// {
// email: ['Invalid email'],
// password: ['Password too short'],
// 'profile.name': ['Name required']
// }
}
```
**With React Hook Form:**
```typescript
import { zodResolver } from "@hookform/resolvers/zod";
import { useForm } from "react-hook-form";
const {
register,
formState: { errors }
} = useForm({
resolver: zodResolver(formSchema)
});
// errors are already flattened by the resolver
// <input {...register('email')} />
// {errors.email && <span>{errors.email.message}</span>}
```
**Customizing flatten output:**
```typescript
const flattened = result.error.flatten((issue) => ({
message: issue.message,
code: issue.code
}));
// fieldErrors now contains custom objects
// {
// email: [{ message: 'Invalid email', code: 'invalid_string' }],
// }
```
**For deeply nested objects, use format():**
```typescript
const result = formSchema.safeParse(data);
if (!result.success) {
const formatted = result.error.format();
// {
// _errors: [],
// email: { _errors: ['Invalid email'] },
// profile: {
// _errors: [],
// name: { _errors: ['Name required'] }
// }
// }
// Access nested errors naturally
formatted.profile?.name?._errors; // ['Name required']
}
```
**When NOT to use this pattern:**
- When you need access to full issue metadata (code, path as array)
- When using a form library that expects different error format
Reference: [Zod Error Handling](https://zod.dev/error-handling)
@@ -0,0 +1,136 @@
---
title: Use Discriminated Unions for Type Narrowing
impact: MEDIUM-HIGH
impactDescription: Regular unions require manual type guards; discriminated unions enable TypeScript's automatic narrowing and Zod's optimized parsing
tags: object, discriminatedUnion, narrowing, typescript
---
## Use Discriminated Unions for Type Narrowing
When a field's type depends on another field's value (e.g., `type: 'success'` means `data` exists, `type: 'error'` means `error` exists), use `z.discriminatedUnion()`. This enables TypeScript's automatic type narrowing and Zod's optimized O(1) parsing instead of trying each variant.
**Incorrect (regular union - no automatic narrowing):**
```typescript
import { z } from "zod";
const successSchema = z.object({
type: z.literal("success"),
data: z.object({ id: z.string() })
});
const errorSchema = z.object({
type: z.literal("error"),
message: z.string()
});
// Regular union - Zod tries each option in order
const responseSchema = z.union([successSchema, errorSchema]);
type Response = z.infer<typeof responseSchema>;
function handleResponse(response: Response) {
// TypeScript doesn't narrow automatically
if (response.type === "success") {
response.data; // Error: Property 'data' does not exist on type 'Response'
// Must cast or use type guards
}
}
```
**Correct (discriminated union):**
```typescript
import { z } from "zod";
const successSchema = z.object({
type: z.literal("success"),
data: z.object({ id: z.string() })
});
const errorSchema = z.object({
type: z.literal("error"),
message: z.string()
});
// Discriminated union - Zod uses 'type' field for O(1) dispatch
const responseSchema = z.discriminatedUnion("type", [successSchema, errorSchema]);
type Response = z.infer<typeof responseSchema>;
function handleResponse(response: Response) {
// TypeScript narrows automatically!
if (response.type === "success") {
response.data.id; // Works - TypeScript knows data exists
} else {
response.message; // Works - TypeScript knows message exists
}
}
```
**Common use cases:**
```typescript
// API responses
const apiResponse = z.discriminatedUnion("status", [
z.object({ status: z.literal("success"), data: z.unknown() }),
z.object({ status: z.literal("error"), error: z.string(), code: z.number() }),
z.object({ status: z.literal("loading") })
]);
// Event types
const event = z.discriminatedUnion("type", [
z.object({ type: z.literal("click"), x: z.number(), y: z.number() }),
z.object({ type: z.literal("keypress"), key: z.string() }),
z.object({ type: z.literal("scroll"), delta: z.number() })
]);
// Database records with polymorphic types
const notification = z.discriminatedUnion("channel", [
z.object({ channel: z.literal("email"), address: z.string().email() }),
z.object({ channel: z.literal("sms"), phoneNumber: z.string() }),
z.object({ channel: z.literal("push"), deviceToken: z.string() })
]);
```
**Type-safe handling:**
```typescript
const paymentSchema = z.discriminatedUnion("method", [
z.object({
method: z.literal("card"),
cardNumber: z.string(),
expiryDate: z.string()
}),
z.object({
method: z.literal("bank"),
accountNumber: z.string(),
routingNumber: z.string()
}),
z.object({
method: z.literal("crypto"),
walletAddress: z.string()
})
]);
type Payment = z.infer<typeof paymentSchema>;
function processPayment(payment: Payment) {
switch (payment.method) {
case "card":
return chargeCard(payment.cardNumber, payment.expiryDate);
case "bank":
return initiateBankTransfer(payment.accountNumber, payment.routingNumber);
case "crypto":
return sendCrypto(payment.walletAddress);
// TypeScript exhaustiveness check - no default needed
}
}
```
**When NOT to use this pattern:**
- When variants don't share a common discriminator field
- When the discriminator isn't a literal type (use regular union)
Reference: [Zod API - Discriminated Unions](https://zod.dev/api#discriminated-unions)
@@ -0,0 +1,146 @@
---
title: Use extend() for Adding Fields
impact: MEDIUM-HIGH
impactDescription: Merging objects manually loses type information; extend() preserves types and allows overriding fields safely
tags: object, extend, composition, inheritance
---
## Use extend() for Adding Fields
When building on existing schemas, use `.extend()` to add new fields rather than manually spreading. Extend preserves type information, allows overriding existing fields, and keeps the schema relationship explicit.
**Incorrect (manual object spreading):**
```typescript
import { z } from "zod";
const baseUserSchema = z.object({
id: z.string(),
name: z.string()
});
// Manual spreading loses Zod's schema relationship
const adminUserSchema = z.object({
...baseUserSchema.shape, // Accessing internal .shape
role: z.literal("admin"),
permissions: z.array(z.string())
});
// Problems:
// 1. If baseUserSchema changes, TypeScript might not catch issues
// 2. Can't override fields easily
// 3. Loses schema methods and metadata
```
**Correct (using extend):**
```typescript
import { z } from "zod";
const baseUserSchema = z.object({
id: z.string(),
name: z.string(),
email: z.string().email()
});
// Extend to add fields
const adminUserSchema = baseUserSchema.extend({
role: z.literal("admin"),
permissions: z.array(z.string())
});
type AdminUser = z.infer<typeof adminUserSchema>;
// {
// id: string;
// name: string;
// email: string;
// role: 'admin';
// permissions: string[];
// }
// Override existing fields
const strictEmailSchema = baseUserSchema.extend({
email: z.string().email().endsWith("@company.com") // Stricter validation
});
```
**Building hierarchies with extend:**
```typescript
// Base entity with common fields
const entitySchema = z.object({
id: z.string().uuid(),
createdAt: z.date(),
updatedAt: z.date()
});
// User extends entity
const userSchema = entitySchema.extend({
email: z.string().email(),
name: z.string()
});
// Product extends entity
const productSchema = entitySchema.extend({
name: z.string(),
price: z.number().positive(),
sku: z.string()
});
// Order extends entity with references
const orderSchema = entitySchema.extend({
userId: z.string().uuid(),
items: z.array(
z.object({
productId: z.string().uuid(),
quantity: z.number().int().positive()
})
),
total: z.number().positive()
});
```
**Combining extend with other methods:**
```typescript
const baseSchema = z.object({
id: z.string(),
name: z.string(),
email: z.string()
});
// Create input: no id, add password
const createSchema = baseSchema.omit({ id: true }).extend({
password: z.string().min(8)
});
// Update input: all optional except id
const updateSchema = baseSchema.partial().extend({
id: z.string() // Override to make required
});
```
**Merge for combining independent schemas:**
```typescript
const addressSchema = z.object({
street: z.string(),
city: z.string()
});
const contactSchema = z.object({
email: z.string().email(),
phone: z.string()
});
// Merge combines two schemas (both required)
const customerSchema = addressSchema.merge(contactSchema);
// { street: string; city: string; email: string; phone: string }
```
**When NOT to use this pattern:**
- When schemas are genuinely independent (use merge or intersection)
- When you need to remove fields (use omit)
Reference: [Zod API - extend](https://zod.dev/api#extend)
@@ -0,0 +1,120 @@
---
title: Distinguish optional() from nullable()
impact: MEDIUM-HIGH
impactDescription: Confusing undefined and null semantics causes "property does not exist" vs "property is null" bugs; choose deliberately
tags: object, optional, nullable, undefined
---
## Distinguish optional() from nullable()
`.optional()` allows `undefined` (field can be missing), while `.nullable()` allows `null` (field must be present but can be null). Choosing the wrong one causes subtle bugs in database operations, JSON serialization, and API contracts.
**Incorrect (confusing optional and nullable):**
```typescript
import { z } from "zod";
const userSchema = z.object({
name: z.string(),
// Intended: field might not exist
nickname: z.string().nullable(), // Wrong! Requires field to be present
// Intended: field exists but might be null
deletedAt: z.date().optional() // Wrong! Allows field to be missing
});
// This fails - nickname is required
userSchema.parse({ name: "John" });
// ZodError: Required at "nickname"
// This passes but loses semantic meaning
userSchema.parse({ name: "John", nickname: null, deletedAt: undefined });
// Is deletedAt undefined because not deleted, or because data is incomplete?
```
**Correct (using optional and nullable deliberately):**
```typescript
import { z } from "zod";
const userSchema = z.object({
name: z.string(),
// optional() - field might not exist in the object
nickname: z.string().optional(),
// Type: string | undefined
// nullable() - field must exist, but value can be null
deletedAt: z.date().nullable()
// Type: Date | null
});
// Field can be omitted
userSchema.parse({ name: "John", deletedAt: null }); // Valid
// Field must be present (even if null)
userSchema.parse({ name: "John", nickname: "Johnny" });
// ZodError: Required at "deletedAt"
// Correct usage
userSchema.parse({
name: "John",
nickname: "Johnny", // Or omit entirely
deletedAt: null // Must be present, null means "not deleted"
});
```
**When to use each:**
```typescript
// optional() - field may not exist
// Use for: Optional form fields, sparse updates, optional config
z.object({
bio: z.string().optional(), // User might not have filled this
middleName: z.string().optional() // Not everyone has one
});
// nullable() - field exists but value can be null
// Use for: Database nullable columns, "cleared" values, explicit absence
z.object({
deletedAt: z.date().nullable(), // null = not deleted, Date = when deleted
parentId: z.string().nullable(), // null = root node, string = has parent
approvedBy: z.string().nullable() // null = pending, string = approver
});
// nullish() - either undefined or null
// Use for: Lenient APIs, legacy data, optional nullable DB columns
z.object({
legacyField: z.string().nullish() // string | null | undefined
});
```
**API response patterns:**
```typescript
// API includes null for "no value" (good for explicit absence)
const apiResponseSchema = z.object({
data: z.object({
user: z
.object({
name: z.string(),
avatar: z.string().nullable() // null = no avatar set
})
.nullable() // null = user not found
})
});
// Type: { data: { user: { name: string; avatar: string | null } | null } }
// Partial updates send only changed fields
const updateSchema = z.object({
name: z.string().optional(), // Omitted = don't change
avatar: z.string().nullable().optional() // null = clear avatar
});
```
**When NOT to use this pattern:**
- When interacting with systems that treat null and undefined as equivalent
- When using nullish() for maximum flexibility is acceptable
Reference: [Zod API - optional/nullable](https://zod.dev/api#optional)
@@ -0,0 +1,124 @@
---
title: Use partial() for Update Schemas
impact: MEDIUM-HIGH
impactDescription: Creating separate update schemas duplicates definitions; partial() derives update schema from base, staying in sync
tags: object, partial, update, patch
---
## Use partial() for Update Schemas
When handling PATCH/PUT updates, you need a schema where all fields are optional. Instead of duplicating the schema with optional fields, use `.partial()` to derive it from your base schema. This keeps both schemas in sync automatically.
**Incorrect (duplicating schemas):**
```typescript
import { z } from "zod";
// Base schema
const userSchema = z.object({
name: z.string().min(1),
email: z.string().email(),
age: z.number().int().positive(),
role: z.enum(["admin", "user"])
});
// Manually duplicated for updates - will drift!
const updateUserSchema = z.object({
name: z.string().min(1).optional(),
email: z.string().email().optional(),
age: z.number().int().positive().optional()
// Forgot to add role - schemas out of sync!
});
// Later, you add a field to userSchema but forget updateUserSchema
// Now updates silently ignore the new field
```
**Correct (using partial):**
```typescript
import { z } from "zod";
// Base schema - single source of truth
const userSchema = z.object({
name: z.string().min(1),
email: z.string().email(),
age: z.number().int().positive(),
role: z.enum(["admin", "user"])
});
// All fields optional for updates
const updateUserSchema = userSchema.partial();
type User = z.infer<typeof userSchema>;
// { name: string; email: string; age: number; role: 'admin' | 'user' }
type UpdateUser = z.infer<typeof updateUserSchema>;
// { name?: string; email?: string; age?: number; role?: 'admin' | 'user' }
// Validate partial updates
updateUserSchema.parse({ email: "new@example.com" }); // Valid
updateUserSchema.parse({}); // Valid - all fields optional
```
**Partial specific fields only:**
```typescript
// Only name and email are optional for updates
const updateUserSchema = userSchema.partial({
name: true,
email: true
});
type UpdateUser = z.infer<typeof updateUserSchema>;
// { name?: string; email?: string; age: number; role: 'admin' | 'user' }
// age and role still required
```
**Deep partial for nested objects:**
```typescript
const addressSchema = z.object({
street: z.string(),
city: z.string(),
country: z.string()
});
const userSchema = z.object({
name: z.string(),
address: addressSchema
});
// .partial() only makes top-level fields optional
const shallowPartial = userSchema.partial();
// { name?: string; address?: { street: string; city: string; country: string } }
// If address is provided, all its fields are still required!
// Use deepPartial for nested optionality
const deepPartialSchema = userSchema.deepPartial();
// { name?: string; address?: { street?: string; city?: string; country?: string } }
```
**Combining with required() for create vs update:**
```typescript
const baseSchema = z.object({
id: z.string().uuid(),
name: z.string(),
email: z.string().email(),
createdAt: z.date()
});
// Create: id and createdAt are generated, rest required
const createSchema = baseSchema.omit({ id: true, createdAt: true });
// Update: all user-editable fields optional
const updateSchema = baseSchema.partial().omit({ id: true, createdAt: true });
```
**When NOT to use this pattern:**
- When update logic differs significantly from create (different validations)
- When using GraphQL with explicit input types
Reference: [Zod API - partial](https://zod.dev/api#partial)
@@ -0,0 +1,147 @@
---
title: Use pick() and omit() for Schema Variants
impact: MEDIUM-HIGH
impactDescription: Copying fields between schemas creates duplication; pick/omit derive variants that stay in sync with base schema
tags: object, pick, omit, variants
---
## Use pick() and omit() for Schema Variants
When you need different views of the same data (public vs private, create vs response), use `.pick()` and `.omit()` instead of duplicating fields. This ensures derived schemas stay in sync with the base schema.
**Incorrect (duplicating for variants):**
```typescript
import { z } from "zod";
// Full user schema
const userSchema = z.object({
id: z.string().uuid(),
email: z.string().email(),
passwordHash: z.string(),
name: z.string(),
createdAt: z.date(),
isAdmin: z.boolean()
});
// Public view - manually duplicated
const publicUserSchema = z.object({
id: z.string().uuid(),
name: z.string(),
// Forgot email - now users can't see it
// Added avatar field - doesn't exist in base schema
avatar: z.string().optional()
});
// Create input - manually duplicated
const createUserSchema = z.object({
email: z.string().email(),
password: z.string().min(8), // Different from passwordHash
name: z.string()
// Missing isAdmin - can't set on create? Intentional?
});
```
**Correct (using pick and omit):**
```typescript
import { z } from "zod";
// Full user schema - single source of truth
const userSchema = z.object({
id: z.string().uuid(),
email: z.string().email(),
passwordHash: z.string(),
name: z.string(),
createdAt: z.date(),
isAdmin: z.boolean()
});
// Public view - explicitly pick public fields
const publicUserSchema = userSchema.pick({
id: true,
email: true,
name: true
});
type PublicUser = z.infer<typeof publicUserSchema>;
// { id: string; email: string; name: string }
// API response - omit sensitive fields
const userResponseSchema = userSchema.omit({
passwordHash: true
});
type UserResponse = z.infer<typeof userResponseSchema>;
// { id: string; email: string; name: string; createdAt: Date; isAdmin: boolean }
// Create input - omit generated fields
const createUserInputSchema = userSchema
.omit({ id: true, createdAt: true, passwordHash: true })
.extend({
password: z.string().min(8) // Add password (different from hash)
});
type CreateUserInput = z.infer<typeof createUserInputSchema>;
// { email: string; name: string; isAdmin: boolean; password: string }
```
**Common patterns:**
```typescript
// Database row → API response (hide internal fields)
const dbRowSchema = z.object({
id: z.number(),
public_id: z.string().uuid(),
email: z.string(),
password_hash: z.string(),
internal_notes: z.string(),
created_at: z.date()
});
const apiResponseSchema = dbRowSchema.omit({
id: true, // Internal DB id
password_hash: true, // Sensitive
internal_notes: true // Staff only
});
// Form data → Database insert (add generated fields)
const formSchema = z.object({
title: z.string(),
content: z.string()
});
const dbInsertSchema = formSchema.extend({
id: z.string().uuid(),
authorId: z.string().uuid(),
createdAt: z.date(),
updatedAt: z.date()
});
```
**Chaining operations:**
```typescript
const baseSchema = z.object({
id: z.string(),
name: z.string(),
email: z.string(),
role: z.enum(["admin", "user"]),
secret: z.string()
});
// Combine pick, omit, partial, extend
const updateSchema = baseSchema
.omit({ id: true, secret: true }) // Remove immutable/sensitive
.partial() // Make all optional for updates
.extend({
updatedAt: z.date().optional() // Add update timestamp
});
```
**When NOT to use this pattern:**
- When derived schemas need different validation rules (not just different fields)
- When the relationship between schemas is not subset/superset
Reference: [Zod API - pick/omit](https://zod.dev/api#pickomit)
@@ -0,0 +1,122 @@
---
title: Choose strict() vs strip() for Unknown Keys
impact: MEDIUM-HIGH
impactDescription: Default passthrough mode leaks unexpected data; strict() catches schema mismatches, strip() silently removes extras
tags: object, strict, strip, passthrough
---
## Choose strict() vs strip() for Unknown Keys
By default, Zod objects use `.strip()` behavior, silently removing unrecognized keys. This can hide schema/data mismatches. Use `.strict()` to reject unknown keys (catching errors) or explicitly use `.strip()` to document the intention.
**Default behavior (strip - silent removal):**
```typescript
import { z } from "zod";
const userSchema = z.object({
id: z.string(),
name: z.string()
});
const input = {
id: "123",
name: "John",
role: "admin", // Extra field
secretToken: "abc123" // Another extra field
};
const user = userSchema.parse(input);
// { id: '123', name: 'John' }
// Extra fields silently removed - was this intentional?
```
**Using strict() to catch schema mismatches:**
```typescript
import { z } from "zod";
const userSchema = z
.object({
id: z.string(),
name: z.string()
})
.strict();
const input = {
id: "123",
name: "John",
role: "admin"
};
userSchema.parse(input);
// ZodError: Unrecognized key(s) in object: 'role'
// This catches:
// - Client sending fields the server doesn't expect
// - Schema out of sync with actual data structure
// - Typos in field names
```
**When to use each mode:**
```typescript
// strict() - Catch unexpected data (API contracts)
const apiRequestSchema = z
.object({
action: z.string(),
payload: z.unknown()
})
.strict(); // Fail if client sends unknown fields
// strip() - Clean up data (explicit intention)
const dbInsertSchema = z
.object({
name: z.string(),
email: z.string()
})
.strip(); // Explicitly remove metadata before insert
// passthrough() - Keep everything (pass-through proxy)
const proxySchema = z
.object({
id: z.string()
})
.passthrough(); // Keep fields we don't validate
const input = { id: "123", extra: "data" };
proxySchema.parse(input); // { id: '123', extra: 'data' }
```
**Choosing the right mode:**
| Mode | Behavior | Use When |
| -------------------- | ------------------- | -------------------------------------------- |
| `.strict()` | Reject unknown keys | API contracts, security-sensitive, debugging |
| `.strip()` (default) | Remove unknown keys | General validation, data cleaning |
| `.passthrough()` | Keep unknown keys | Proxying, partial validation |
**Handling specific unknown keys:**
```typescript
const schema = z
.object({
id: z.string(),
name: z.string()
})
.catchall(z.unknown()); // Allow any additional fields of any type
// Or restrict additional fields to specific type
const metadataSchema = z
.object({
id: z.string()
})
.catchall(z.string()); // Only allow string extras
```
**When NOT to use this pattern:**
- `.strict()`: When forwarding data to another system that may add fields
- `.passthrough()`: When you need to ensure only known fields are stored
Reference: [Zod API - Objects](https://zod.dev/api#objects)
@@ -0,0 +1,127 @@
---
title: Use parseAsync for Async Refinements
impact: CRITICAL
impactDescription: Using parse() with async refinements throws an error; async validation silently fails or crashes the application
tags: parse, async, parseAsync, refinement
---
## Use parseAsync for Async Refinements
If your schema uses `refine()` or `superRefine()` with async validation (like database lookups), you must use `parseAsync()` or `safeParseAsync()`. Using synchronous `parse()` with async refinements throws an error.
**Incorrect (sync parse with async refinement):**
```typescript
import { z } from "zod";
const userSchema = z
.object({
email: z.string().email(),
username: z.string().min(3)
})
.refine(
async (data) => {
// Async database check
const exists = await db.users.findByEmail(data.email);
return !exists;
},
{ message: "Email already registered" }
);
// This throws an error!
const user = userSchema.parse(formData);
// Error: Async refinement encountered during synchronous parse operation.
// Use .parseAsync instead.
```
**Correct (using parseAsync):**
```typescript
import { z } from "zod";
const userSchema = z
.object({
email: z.string().email(),
username: z.string().min(3)
})
.refine(
async (data) => {
const exists = await db.users.findByEmail(data.email);
return !exists;
},
{ message: "Email already registered" }
);
// Use parseAsync for async refinements
const user = await userSchema.parseAsync(formData);
// Or safeParseAsync for error handling
const result = await userSchema.safeParseAsync(formData);
if (!result.success) {
console.log(result.error.issues);
}
```
**Async transforms also require parseAsync:**
```typescript
const enrichedUserSchema = z
.object({
userId: z.string().uuid()
})
.transform(async (data) => {
// Async data enrichment
const user = await db.users.findById(data.userId);
return {
...data,
email: user.email,
name: user.name
};
});
// Must use parseAsync
const enrichedUser = await enrichedUserSchema.parseAsync({ userId: "123" });
```
**Pattern for API routes:**
```typescript
import { z } from "zod";
import { NextRequest, NextResponse } from "next/server";
const registerSchema = z
.object({
email: z.string().email(),
password: z.string().min(8)
})
.superRefine(async (data, ctx) => {
const existingUser = await db.users.findByEmail(data.email);
if (existingUser) {
ctx.addIssue({
code: z.ZodIssueCode.custom,
path: ["email"],
message: "Email already registered"
});
}
});
export async function POST(req: NextRequest) {
const body = await req.json();
// Always use safeParseAsync with async schemas
const result = await registerSchema.safeParseAsync(body);
if (!result.success) {
return NextResponse.json({ errors: result.error.issues }, { status: 400 });
}
// Proceed with registration
}
```
**When NOT to use this pattern:**
- Schemas with only synchronous validation (use parse/safeParse)
- When async validation can be moved outside Zod (validate, then check)
Reference: [Zod API - parseAsync](https://zod.dev/api#parseasync)
@@ -0,0 +1,130 @@
---
title: Avoid Double Validation
impact: HIGH
impactDescription: Parsing the same data twice wastes CPU cycles; in hot paths this adds measurable latency
tags: parse, performance, optimization, architecture
---
## Avoid Double Validation
Once data is validated by Zod, trust the result. Re-validating the same data in multiple layers doubles CPU usage and adds latency. Pass the typed result through your application instead.
**Incorrect (validating at every layer):**
```typescript
import { z } from "zod";
const userSchema = z.object({
id: z.string().uuid(),
email: z.string().email(),
name: z.string()
});
// Controller validates
export async function POST(req: NextRequest) {
const body = await req.json();
const user = userSchema.parse(body); // First parse
return await userService.create(user);
}
// Service validates again
const userService = {
async create(data: unknown) {
const user = userSchema.parse(data); // Second parse - redundant
return await userRepository.insert(user);
}
};
// Repository validates again
const userRepository = {
async insert(data: unknown) {
const user = userSchema.parse(data); // Third parse - wasteful
return await db.users.create({ data: user });
}
};
```
**Correct (validate once, pass typed data):**
```typescript
import { z } from "zod";
const userSchema = z.object({
id: z.string().uuid(),
email: z.string().email(),
name: z.string()
});
type User = z.infer<typeof userSchema>;
// Controller validates at boundary
export async function POST(req: NextRequest) {
const body = await req.json();
const result = userSchema.safeParse(body);
if (!result.success) {
return NextResponse.json({ errors: result.error.issues }, { status: 400 });
}
// Pass validated, typed data
return await userService.create(result.data);
}
// Service receives typed data, no re-validation needed
const userService = {
async create(user: User) {
// user is guaranteed to match schema
return await userRepository.insert(user);
}
};
// Repository receives typed data
const userRepository = {
async insert(user: User) {
return await db.users.create({ data: user });
}
};
```
**When you might validate at multiple layers:**
```typescript
// Different schemas for different layers
const apiUserSchema = z.object({
email: z.string().email(),
password: z.string().min(8) // Only in API layer
});
const dbUserSchema = z.object({
id: z.string().uuid(),
email: z.string().email(),
passwordHash: z.string() // Transformed before storage
});
// API validates input format
export async function POST(req: NextRequest) {
const input = apiUserSchema.parse(await req.json());
const user = await userService.create(input);
return NextResponse.json(user);
}
// Service transforms and validates for storage
const userService = {
async create(input: z.infer<typeof apiUserSchema>) {
const dbUser = dbUserSchema.parse({
id: crypto.randomUUID(),
email: input.email,
passwordHash: await hash(input.password)
});
return await userRepository.insert(dbUser);
}
};
```
**When NOT to use this pattern:**
- When schemas differ between layers (API vs DB shape)
- When data crosses trust boundaries (external service response)
- During development when debugging data flow
Reference: [Zod Performance](https://zod.dev/v4#performance)
@@ -0,0 +1,126 @@
---
title: Handle All Validation Issues Not Just First
impact: CRITICAL
impactDescription: Showing only the first error forces users to fix-submit-fix repeatedly; collecting all errors improves UX dramatically
tags: parse, errors, issues, user-experience
---
## Handle All Validation Issues Not Just First
Zod collects all validation failures, not just the first one. When displaying errors to users, show all issues so they can fix everything at once instead of playing whack-a-mole with one error at a time.
**Incorrect (showing only first error):**
```typescript
import { z } from "zod";
const formSchema = z.object({
email: z.string().email("Invalid email"),
password: z.string().min(8, "Password must be 8+ characters"),
confirmPassword: z.string(),
age: z.number().min(18, "Must be 18 or older")
});
function validateForm(data: unknown) {
const result = formSchema.safeParse(data);
if (!result.success) {
// Only shows first error - terrible UX
return { error: result.error.issues[0].message };
}
return { data: result.data };
}
// User submits empty form
validateForm({});
// Returns: { error: 'Invalid email' }
// User fixes email, submits again
// Returns: { error: 'Password must be 8+ characters' }
// User fixes password, submits again...
// 4 round trips to fix 4 errors!
```
**Correct (showing all errors):**
```typescript
import { z } from "zod";
const formSchema = z.object({
email: z.string().email("Invalid email"),
password: z.string().min(8, "Password must be 8+ characters"),
confirmPassword: z.string(),
age: z.number().min(18, "Must be 18 or older")
});
function validateForm(data: unknown) {
const result = formSchema.safeParse(data);
if (!result.success) {
// Collect errors by field for form display
const fieldErrors: Record<string, string[]> = {};
for (const issue of result.error.issues) {
const field = issue.path.join(".");
if (!fieldErrors[field]) {
fieldErrors[field] = [];
}
fieldErrors[field].push(issue.message);
}
return { errors: fieldErrors };
}
return { data: result.data };
}
// User submits empty form
validateForm({});
// Returns: {
// errors: {
// email: ['Invalid email'],
// password: ['Password must be 8+ characters'],
// confirmPassword: ['Required'],
// age: ['Expected number, received undefined']
// }
// }
// User sees ALL errors, fixes everything, submits once!
```
**Using flatten() for simpler error structure:**
```typescript
const result = formSchema.safeParse(data);
if (!result.success) {
const flattened = result.error.flatten();
// {
// formErrors: [], // Top-level errors
// fieldErrors: {
// email: ['Invalid email'],
// password: ['Password must be 8+ characters'],
// ...
// }
// }
return { errors: flattened.fieldErrors };
}
```
**With React Hook Form integration:**
```typescript
import { zodResolver } from "@hookform/resolvers/zod";
import { useForm } from "react-hook-form";
const form = useForm({
resolver: zodResolver(formSchema)
// All errors are automatically collected and displayed
});
```
**When NOT to use this pattern:**
- Rate-limited APIs where you want to fail fast on first error
- Large batch processing where full validation is expensive
Reference: [Zod Error Handling](https://zod.dev/error-handling)
@@ -0,0 +1,116 @@
---
title: Never Trust JSON.parse Output
impact: CRITICAL
impactDescription: JSON.parse returns any type; unvalidated JSON allows type confusion attacks and runtime crashes
tags: parse, json, security, type-safety
---
## Never Trust JSON.parse Output
`JSON.parse()` returns `any` (or `unknown` in strict mode), providing no type guarantees. Always validate JSON output with Zod before using it, even if you control the JSON source. This catches corruption, version mismatches, and ensures type safety.
**Incorrect (trusting JSON.parse):**
```typescript
// JSON.parse returns any - no type safety
const config = JSON.parse(fs.readFileSync("config.json", "utf-8"));
// config is 'any' - TypeScript allows anything
// This might crash at runtime if structure changed
console.log(config.database.host); // TypeError: Cannot read property 'host' of undefined
// API response - also unvalidated
const response = await fetch("/api/user");
const user = await response.json(); // any type
console.log(user.name.toUpperCase()); // Crash if name is null/undefined
```
**Correct (validate after JSON.parse):**
```typescript
import { z } from "zod";
const configSchema = z.object({
database: z.object({
host: z.string(),
port: z.number(),
name: z.string()
}),
api: z.object({
key: z.string(),
timeout: z.number().default(5000)
})
});
// Parse JSON then validate
const rawConfig = JSON.parse(fs.readFileSync("config.json", "utf-8"));
const config = configSchema.parse(rawConfig);
// config is fully typed: { database: { host: string, ... }, ... }
// API response validation
const userSchema = z.object({
id: z.string(),
name: z.string(),
email: z.string().email()
});
const response = await fetch("/api/user");
const rawUser = await response.json();
const user = userSchema.parse(rawUser);
// user is fully typed and validated
```
**Helper for validated JSON parsing:**
```typescript
function parseJSON<T>(schema: z.ZodType<T>, json: string): T {
return schema.parse(JSON.parse(json));
}
function safeParseJSON<T>(schema: z.ZodType<T>, json: string) {
try {
return { success: true as const, data: schema.parse(JSON.parse(json)) };
} catch (error) {
if (error instanceof SyntaxError) {
return { success: false as const, error: "Invalid JSON" };
}
if (error instanceof z.ZodError) {
return { success: false as const, error: error.issues };
}
throw error;
}
}
// Usage
const config = parseJSON(configSchema, fs.readFileSync("config.json", "utf-8"));
```
**Validate localStorage/sessionStorage:**
```typescript
const cartSchema = z.array(
z.object({
productId: z.string(),
quantity: z.number().int().positive()
})
);
function getCart() {
const raw = localStorage.getItem("cart");
if (!raw) return [];
const result = cartSchema.safeParse(JSON.parse(raw));
if (!result.success) {
// Corrupted cart data - clear it
localStorage.removeItem("cart");
return [];
}
return result.data;
}
```
**When NOT to use this pattern:**
- When you genuinely need to pass through arbitrary JSON without processing
Reference: [Zod API - parse](https://zod.dev/api#parse)
@@ -0,0 +1,103 @@
---
title: Use safeParse() for User Input
impact: CRITICAL
impactDescription: parse() throws exceptions on invalid data; unhandled exceptions crash servers and expose stack traces to users
tags: parse, safeParse, error-handling, validation
---
## Use safeParse() for User Input
`parse()` throws a `ZodError` when validation fails, which crashes your application if not caught. `safeParse()` returns a result object that you can inspect without try/catch. Use `safeParse()` for any user-provided or external data.
**Incorrect (parse without error handling):**
```typescript
import { z } from "zod";
import { NextRequest, NextResponse } from "next/server";
const createUserSchema = z.object({
email: z.string().email(),
name: z.string().min(1)
});
export async function POST(req: NextRequest) {
const body = await req.json();
// If validation fails, this throws and crashes the handler
const user = createUserSchema.parse(body);
// Never reached if parse throws
await db.users.create({ data: user });
return NextResponse.json({ success: true });
}
// Result: 500 Internal Server Error with stack trace
```
**Correct (using safeParse):**
```typescript
import { z } from "zod";
import { NextRequest, NextResponse } from "next/server";
const createUserSchema = z.object({
email: z.string().email(),
name: z.string().min(1)
});
export async function POST(req: NextRequest) {
const body = await req.json();
const result = createUserSchema.safeParse(body);
if (!result.success) {
// Return structured error response
return NextResponse.json(
{ error: "Validation failed", issues: result.error.issues },
{ status: 400 }
);
}
// result.data is typed correctly
await db.users.create({ data: result.data });
return NextResponse.json({ success: true });
}
```
**The result object structure:**
```typescript
// Success case
{ success: true, data: T }
// Error case
{ success: false, error: ZodError }
// Type narrowing works automatically
if (result.success) {
result.data // T - fully typed
} else {
result.error // ZodError
result.error.issues // Array of validation issues
}
```
**When parse() is acceptable:**
```typescript
// Internal data you control - parse is fine
const config = configSchema.parse(JSON.parse(process.env.CONFIG));
// Test assertions - parse throws helpful errors
expect(() => schema.parse(invalidData)).toThrow();
// Schema development - see errors immediately
schema.parse(testData); // See what fails during development
```
**When NOT to use this pattern:**
- Internal configuration parsing where invalid data should crash early
- Tests where you want exceptions to fail the test
- Scripts where you want to see the full error
Reference: [Zod API - safeParse](https://zod.dev/api#safeparse)
@@ -0,0 +1,125 @@
---
title: Validate at System Boundaries
impact: CRITICAL
impactDescription: Validating deep in business logic allows corrupt data to propagate; validating at boundaries catches issues before they spread
tags: parse, boundaries, architecture, defense-in-depth
---
## Validate at System Boundaries
Validate external data immediately when it enters your system—at API endpoints, form handlers, message queue consumers, and configuration loaders. Validating deep in business logic allows corrupt data to propagate and makes debugging harder.
**Incorrect (validating deep in business logic):**
```typescript
import { z } from "zod";
// No validation at API boundary
export async function POST(req: NextRequest) {
const body = await req.json();
// Raw unknown data passed through
return await processOrder(body);
}
async function processOrder(data: unknown) {
// Data passed around unvalidated
const items = await calculateTotals(data);
return await chargeCustomer(data, items);
}
async function calculateTotals(data: unknown) {
// Finally validating way too late
const order = orderSchema.parse(data); // Throws here, far from entry point
// ...
}
// Hard to trace where bad data came from
```
**Correct (validating at boundary):**
```typescript
import { z } from "zod";
const orderSchema = z.object({
customerId: z.string().uuid(),
items: z
.array(
z.object({
productId: z.string(),
quantity: z.number().int().positive()
})
)
.min(1),
shippingAddress: z.object({
street: z.string(),
city: z.string(),
country: z.string()
})
});
type Order = z.infer<typeof orderSchema>;
// Validate immediately at boundary
export async function POST(req: NextRequest) {
const body = await req.json();
const result = orderSchema.safeParse(body);
if (!result.success) {
return NextResponse.json(
{ error: "Invalid order", issues: result.error.issues },
{ status: 400 }
);
}
// Now data is validated and typed
return await processOrder(result.data);
}
// Business logic receives typed, validated data
async function processOrder(order: Order) {
// order is guaranteed to match schema
const items = await calculateTotals(order);
return await chargeCustomer(order, items);
}
async function calculateTotals(order: Order) {
// No validation needed - type guarantees shape
return order.items.map((item) => ({
...item,
total: item.quantity * getPrice(item.productId)
}));
}
```
**Boundaries to validate:**
```typescript
// API endpoints
export async function POST(req: NextRequest) {
const data = await req.json();
const validated = requestSchema.safeParse(data);
// ...
}
// Message queue consumers
async function handleMessage(rawMessage: string) {
const data = JSON.parse(rawMessage);
const validated = messageSchema.safeParse(data);
// ...
}
// Configuration loading
const config = configSchema.parse(JSON.parse(process.env.CONFIG!));
// External API responses
const response = await fetch("/api/users");
const data = await response.json();
const users = usersResponseSchema.parse(data);
```
**When NOT to use this pattern:**
- Internal function calls with already-validated data
- Performance-critical hot paths (validate once, trust afterward)
Reference: [Zod with TypeScript for Server-side Validation](https://stack.convex.dev/typescript-zod-function-validation)
@@ -0,0 +1,154 @@
---
title: Optimize Large Array Validation
impact: LOW-MEDIUM
impactDescription: Validating 10,000 items takes ~100ms; early exits, sampling, or batching reduce time for large datasets
tags: perf, arrays, batch, large-data
---
## Optimize Large Array Validation
Validating large arrays (thousands of items) can become a performance bottleneck. For batch imports, streaming data, or large datasets, consider strategies like early exit, sampling, or batched validation.
**Baseline performance:**
```typescript
import { z } from "zod";
const itemSchema = z.object({
id: z.string(),
value: z.number()
});
const arraySchema = z.array(itemSchema);
// 10,000 items: ~100ms
// 100,000 items: ~1000ms
arraySchema.parse(largeArray);
```
**Early exit on first error:**
```typescript
import { z } from "zod";
function validateArrayFastFail<T>(
schema: z.ZodType<T>,
items: unknown[]
): { success: true; data: T[] } | { success: false; error: z.ZodError; index: number } {
const validated: T[] = [];
for (let i = 0; i < items.length; i++) {
const result = schema.safeParse(items[i]);
if (!result.success) {
return { success: false, error: result.error, index: i };
}
validated.push(result.data);
}
return { success: true, data: validated };
}
// Stops at first invalid item instead of validating all
```
**Sample validation for large datasets:**
```typescript
function validateSample<T>(
schema: z.ZodType<T>,
items: unknown[],
sampleSize: number = 100
): { valid: boolean; sampleErrors?: z.ZodIssue[] } {
// Validate random sample
const indices = new Set<number>();
while (indices.size < Math.min(sampleSize, items.length)) {
indices.add(Math.floor(Math.random() * items.length));
}
const errors: z.ZodIssue[] = [];
for (const i of indices) {
const result = schema.safeParse(items[i]);
if (!result.success) {
errors.push(...result.error.issues);
}
}
return errors.length > 0 ? { valid: false, sampleErrors: errors } : { valid: true };
}
// Check 100 random items from 100,000 - very fast
const check = validateSample(itemSchema, hugeArray);
```
**Batched validation with progress:**
```typescript
async function validateInBatches<T>(
schema: z.ZodType<T>,
items: unknown[],
batchSize: number = 1000,
onProgress?: (percent: number) => void
): Promise<z.SafeParseReturnType<unknown, T[]>> {
const validated: T[] = [];
const errors: z.ZodIssue[] = [];
for (let i = 0; i < items.length; i += batchSize) {
const batch = items.slice(i, i + batchSize);
// Validate batch
for (let j = 0; j < batch.length; j++) {
const result = schema.safeParse(batch[j]);
if (result.success) {
validated.push(result.data);
} else {
errors.push(
...result.error.issues.map((issue) => ({
...issue,
path: [i + j, ...issue.path]
}))
);
}
}
// Report progress and yield to event loop
onProgress?.(Math.min(100, ((i + batchSize) / items.length) * 100));
await new Promise((resolve) => setTimeout(resolve, 0));
}
if (errors.length > 0) {
return { success: false, error: new z.ZodError(errors) };
}
return { success: true, data: validated };
}
// Use with progress reporting
await validateInBatches(itemSchema, largeArray, 1000, (percent) => {
console.log(`Validating: ${percent.toFixed(1)}%`);
});
```
**Streaming validation:**
```typescript
async function* validateStream<T>(
schema: z.ZodType<T>,
items: AsyncIterable<unknown>
): AsyncGenerator<T, void, unknown> {
for await (const item of items) {
yield schema.parse(item); // Throws on invalid
}
}
// Process items as they arrive
for await (const validItem of validateStream(itemSchema, dataStream)) {
await processItem(validItem);
}
```
**When NOT to use this pattern:**
- Small arrays (< 1000 items) - standard validation is fine
- When all items must be validated for correctness guarantees
Reference: [Zod Performance](https://zod.dev/v4#performance)
@@ -0,0 +1,140 @@
---
title: Avoid Dynamic Schema Creation in Hot Paths
impact: LOW-MEDIUM
impactDescription: Zod 4's JIT compilation makes schema creation slower; creating schemas in loops adds ~0.15ms per creation
tags: perf, dynamic, hot-path, optimization
---
## Avoid Dynamic Schema Creation in Hot Paths
Zod 4 uses JIT (Just-In-Time) compilation to speed up repeated parsing, but this makes initial schema creation slower. Avoid creating schemas inside loops or frequently-called functions—pre-create them instead.
**Incorrect (schema creation in hot path):**
```typescript
import { z } from "zod";
async function validateBatch(items: unknown[]) {
const results = [];
for (const item of items) {
// Schema created for EACH item - slow!
const schema = z.object({
id: z.string(),
value: z.number()
});
results.push(schema.safeParse(item));
}
return results;
}
// 1000 items = 1000 schema creations = ~150ms overhead
```
**Correct (pre-created schema):**
```typescript
import { z } from "zod";
// Schema created ONCE
const itemSchema = z.object({
id: z.string(),
value: z.number()
});
async function validateBatch(items: unknown[]) {
// Reuse the same schema instance
return items.map((item) => itemSchema.safeParse(item));
}
// 1000 items = 1 schema creation + 1000 fast parses
```
**Dynamic schemas with caching:**
```typescript
import { z } from "zod";
// Cache for dynamically-configured schemas
const schemaCache = new WeakMap<object, z.ZodType>();
function getSchemaForConfig(config: { fields: string[] }) {
// Check cache first
if (schemaCache.has(config)) {
return schemaCache.get(config)!;
}
// Create and cache
const shape: Record<string, z.ZodString> = {};
for (const field of config.fields) {
shape[field] = z.string();
}
const schema = z.object(shape);
schemaCache.set(config, schema);
return schema;
}
// Subsequent calls with same config reuse cached schema
```
**Lazy schema creation:**
```typescript
import { z } from "zod";
// Schema created only when first used
let _userSchema: z.ZodObject<any> | null = null;
function getUserSchema() {
if (!_userSchema) {
_userSchema = z.object({
id: z.string().uuid(),
email: z.string().email(),
profile: z.object({
name: z.string(),
avatar: z.string().url().optional()
})
});
}
return _userSchema;
}
// Or use a getter
const schemas = {
_user: null as z.ZodType | null,
get user() {
if (!this._user) {
this._user = z.object({/* ... */});
}
return this._user;
}
};
```
**Benchmark considerations:**
```typescript
// Zod 4 JIT compilation:
// - Schema creation: ~0.15ms per schema
// - First parse: triggers JIT compile
// - Subsequent parses: 7-14x faster
// For schemas used once:
// - Creation + parse: ~0.15ms + first-parse overhead
// - Consider if validation is even needed
// For schemas used many times:
// - Create once, parse many: optimal
// - JIT compilation amortized over all parses
```
**When NOT to use this pattern:**
- One-off validation where schema is used once
- Dynamically generated forms where fields change per request
- Test files where performance doesn't matter
Reference: [Zod v4 Performance](https://zod.dev/v4#performance)
@@ -0,0 +1,143 @@
---
title: Cache Schema Instances
impact: LOW-MEDIUM
impactDescription: Creating schemas on every render/call wastes CPU; module-level or memoized schemas are created once
tags: perf, cache, memoization, optimization
---
## Cache Schema Instances
Schema creation has overhead. Creating schemas inside render functions or on every function call wastes CPU cycles. Define schemas at module level or memoize them so they're created once and reused.
**Incorrect (creating schema every render):**
```typescript
import { z } from 'zod'
function UserForm() {
// Schema created on EVERY render - wasteful
const userSchema = z.object({
name: z.string().min(1),
email: z.string().email(),
age: z.number().int().positive(),
})
const handleSubmit = (data: unknown) => {
const result = userSchema.safeParse(data)
// ...
}
return <form onSubmit={handleSubmit}>...</form>
}
```
**Correct (module-level schema):**
```typescript
import { z } from 'zod'
// Schema created ONCE at module load
const userSchema = z.object({
name: z.string().min(1),
email: z.string().email(),
age: z.number().int().positive(),
})
type User = z.infer<typeof userSchema>
function UserForm() {
const handleSubmit = (data: unknown) => {
const result = userSchema.safeParse(data)
// ...
}
return <form onSubmit={handleSubmit}>...</form>
}
```
**For dynamic schemas, use useMemo:**
```typescript
import { z } from "zod";
import { useMemo } from "react";
function DynamicForm({ minAge }: { minAge: number }) {
// Schema only recreated when minAge changes
const userSchema = useMemo(
() =>
z.object({
name: z.string().min(1),
age: z.number().min(minAge)
}),
[minAge]
);
// ...
}
```
**For server-side, use module cache:**
```typescript
// schemas/user.ts - created once per process
import { z } from "zod";
export const userSchema = z.object({
id: z.string().uuid(),
email: z.string().email()
});
// api/users.ts
import { userSchema } from "@/schemas/user";
export async function POST(req: Request) {
const body = await req.json();
const result = userSchema.safeParse(body); // Reuses cached schema
// ...
}
```
**Avoid schema factories in hot paths:**
```typescript
// BAD: Factory called on every validation
function createUserSchema(role: string) {
return z.object({
name: z.string(),
permissions: z.array(z.string())
});
}
// Called in hot loop
users.forEach((user) => {
createUserSchema(user.role).parse(user); // New schema every iteration!
});
// GOOD: Cache by key
const schemaCache = new Map<string, z.ZodObject<any>>();
function getUserSchema(role: string) {
if (!schemaCache.has(role)) {
schemaCache.set(
role,
z.object({
name: z.string(),
permissions: z.array(z.string())
})
);
}
return schemaCache.get(role)!;
}
// Reuses cached schemas
users.forEach((user) => {
getUserSchema(user.role).parse(user);
});
```
**When NOT to use this pattern:**
- One-off validation where schema is used once
- Test files where performance doesn't matter
Reference: [Zod Performance](https://zod.dev/v4#performance)
@@ -0,0 +1,136 @@
---
title: Lazy Load Large Schemas
impact: LOW-MEDIUM
impactDescription: Large schemas increase initial bundle and parse time; dynamic imports defer loading until needed
tags: perf, lazy, import, code-splitting
---
## Lazy Load Large Schemas
For applications with many complex schemas, importing all of them upfront increases initial bundle size and startup time. Use dynamic imports to lazy load schemas that aren't needed immediately.
**Incorrect (importing all schemas upfront):**
```typescript
// schemas/index.ts - barrel file with everything
export * from "./user";
export * from "./order";
export * from "./product";
export * from "./analytics"; // Large, complex schema
export * from "./reports"; // Another large schema
export * from "./admin"; // Admin-only schemas
// app/page.tsx
import { userSchema, orderSchema, analyticsSchema, reportsSchema } from "@/schemas";
// All schemas loaded even if not used on this page
```
**Correct (lazy loading schemas):**
```typescript
// Only import what's immediately needed
import { userSchema } from "@/schemas/user";
async function loadAnalyticsSchema() {
const { analyticsSchema } = await import("@/schemas/analytics");
return analyticsSchema;
}
// Use when needed
async function handleAnalyticsData(data: unknown) {
const schema = await loadAnalyticsSchema();
return schema.safeParse(data);
}
```
**Route-based schema loading:**
```typescript
// app/admin/reports/page.tsx
'use client'
import { useEffect, useState } from 'react'
import type { z } from 'zod'
export default function ReportsPage() {
const [schema, setSchema] = useState<z.ZodType | null>(null)
useEffect(() => {
// Load schema only when this route is accessed
import('@/schemas/reports').then(({ reportsSchema }) => {
setSchema(reportsSchema)
})
}, [])
if (!schema) return <Loading />
// Use schema...
}
```
**Better pattern with React Suspense:**
```typescript
// schemas/reports.ts
import { z } from 'zod'
export const reportsSchema = z.object({
// Large complex schema
})
// app/admin/reports/page.tsx
import { lazy, Suspense } from 'react'
const ReportsForm = lazy(() => import('./ReportsForm'))
export default function ReportsPage() {
return (
<Suspense fallback={<Loading />}>
<ReportsForm />
</Suspense>
)
}
// ReportsForm.tsx - schema imported with component
import { reportsSchema } from '@/schemas/reports'
export default function ReportsForm() {
// Schema available when component loads
}
```
**Schema registry for conditional loading:**
```typescript
// schemas/registry.ts
const schemaLoaders = {
user: () => import("./user").then((m) => m.userSchema),
order: () => import("./order").then((m) => m.orderSchema),
analytics: () => import("./analytics").then((m) => m.analyticsSchema),
reports: () => import("./reports").then((m) => m.reportsSchema)
} as const;
type SchemaName = keyof typeof schemaLoaders;
const schemaCache = new Map<SchemaName, z.ZodType>();
export async function getSchema(name: SchemaName) {
if (!schemaCache.has(name)) {
const schema = await schemaLoaders[name]();
schemaCache.set(name, schema);
}
return schemaCache.get(name)!;
}
// Usage
const schema = await getSchema("analytics");
schema.parse(data);
```
**When NOT to use this pattern:**
- Server-side rendering where all code is available
- Small applications with few schemas
- Schemas used on every page (defeats purpose)
Reference: [Next.js Dynamic Imports](https://nextjs.org/docs/app/building-your-application/optimizing/lazy-loading)
@@ -0,0 +1,118 @@
---
title: Use Zod Mini for Bundle-Sensitive Applications
impact: LOW-MEDIUM
impactDescription: Full Zod is ~17kb gzipped; Zod Mini is ~1.9kb - 85% smaller for frontend-critical bundles
tags: perf, bundle, mini, tree-shaking
---
## Use Zod Mini for Bundle-Sensitive Applications
For frontend applications where bundle size is critical, use `@zod/mini` instead of `zod`. Zod Mini provides the same validation capabilities with a functional API that tree-shakes better, reducing bundle size by ~85%.
**When to consider Zod Mini:**
```typescript
// Your app if:
// - Bundle size is critical (mobile-first, slow networks)
// - Edge functions with size limits
// - Simple validation needs (no complex transforms)
// - Tree-shaking is important
// Zod: ~17kb gzipped
import { z } from "zod";
// Zod Mini: ~1.9kb gzipped (when tree-shaken)
import * as z from "@zod/mini";
```
**Standard Zod (method chaining):**
```typescript
import { z } from "zod";
// Methods are attached to schema objects - hard to tree-shake
const userSchema = z.object({
name: z.string().min(1).max(100),
email: z.string().email(),
age: z.number().int().positive()
});
const result = userSchema.safeParse(data);
```
**Zod Mini (functional API):**
```typescript
import * as z from "@zod/mini";
// Functions are imported individually - tree-shakeable
const userSchema = z.object({
name: z.pipe(z.string(), z.minLength(1), z.maxLength(100)),
email: z.pipe(z.string(), z.email()),
age: z.pipe(z.number(), z.int(), z.positive())
});
const result = z.safeParse(userSchema, data);
```
**API differences:**
```typescript
// Standard Zod
z.string().min(5).max(100).email();
z.number().int().positive();
z.array(z.string()).min(1);
schema.parse(data);
schema.safeParse(data);
// Zod Mini
z.pipe(z.string(), z.minLength(5), z.maxLength(100), z.email());
z.pipe(z.number(), z.int(), z.positive());
z.pipe(z.array(z.string()), z.minLength(1));
z.parse(schema, data);
z.safeParse(schema, data);
```
**When to stick with regular Zod:**
```typescript
// Use regular Zod when:
// - Server-side where bundle size doesn't matter
// - Complex schemas with many transforms
// - Need full method chaining ergonomics
// - Bundle size isn't a constraint
// The 17kb isn't huge - only optimize if needed
// Server: 17kb is negligible
// Browser: 17kb ≈ 0.6ms additional startup on 3G
```
**Shared schemas between packages:**
```typescript
// shared-schemas/package.json
{
"dependencies": {
"@zod/mini": "^4.0.0" // Mini for frontend-shared schemas
}
}
// If you need both, Zod Mini schemas work with regular Zod
// But prefer consistency - pick one for your codebase
```
**Bundle size comparison:**
| Package | Gzipped Size | Use Case |
| ----------- | ------------ | --------------- |
| `zod@3` | ~13kb | Legacy, stable |
| `zod@4` | ~17kb | Full features |
| `@zod/mini` | ~1.9kb | Bundle-critical |
**When NOT to use this pattern:**
- Server-side applications (bundle size irrelevant)
- When method chaining ergonomics are preferred
- Complex schemas that benefit from full API
Reference: [Zod Mini](https://zod.dev/packages/mini)
@@ -0,0 +1,149 @@
---
title: Add Path to Refinement Errors
impact: MEDIUM
impactDescription: Errors without path show at object level; adding path highlights the specific field that failed
tags: refine, path, errors, forms
---
## Add Path to Refinement Errors
When using `.refine()` on object schemas for cross-field validation, add a `path` option to indicate which field the error relates to. Without it, the error appears at the object level, making form error display confusing.
**Incorrect (error at object level):**
```typescript
import { z } from "zod";
const formSchema = z
.object({
password: z.string().min(8),
confirmPassword: z.string()
})
.refine(
(data) => data.password === data.confirmPassword,
{ message: "Passwords do not match" } // No path specified
);
const result = formSchema.safeParse({
password: "secret123",
confirmPassword: "different"
});
if (!result.success) {
const flattened = result.error.flatten();
// {
// formErrors: ['Passwords do not match'], // At form level!
// fieldErrors: {} // Empty - no field association
// }
}
// Form UI can't highlight which field has the error
```
**Correct (error with path):**
```typescript
import { z } from "zod";
const formSchema = z
.object({
password: z.string().min(8),
confirmPassword: z.string()
})
.refine((data) => data.password === data.confirmPassword, {
message: "Passwords do not match",
path: ["confirmPassword"] // Error appears on this field
});
const result = formSchema.safeParse({
password: "secret123",
confirmPassword: "different"
});
if (!result.success) {
const flattened = result.error.flatten();
// {
// formErrors: [],
// fieldErrors: {
// confirmPassword: ['Passwords do not match'] // Associated with field
// }
// }
}
// Form can now show error next to confirmPassword input
```
**Multiple cross-field validations:**
```typescript
const dateRangeSchema = z
.object({
startDate: z.coerce.date(),
endDate: z.coerce.date(),
minDays: z.number().optional(),
maxDays: z.number().optional()
})
.refine((data) => data.endDate >= data.startDate, {
message: "End date must be after start date",
path: ["endDate"]
})
.refine(
(data) => {
if (!data.minDays) return true;
const days = (data.endDate.getTime() - data.startDate.getTime()) / 86400000;
return days >= data.minDays;
},
{ message: "Date range is too short", path: ["endDate"] }
)
.refine(
(data) => {
if (!data.maxDays) return true;
const days = (data.endDate.getTime() - data.startDate.getTime()) / 86400000;
return days <= data.maxDays;
},
{ message: "Date range is too long", path: ["endDate"] }
);
```
**With superRefine for multiple path errors:**
```typescript
const orderSchema = z
.object({
billingAddress: z.object({
street: z.string(),
city: z.string()
}),
shippingAddress: z.object({
street: z.string(),
city: z.string()
}),
sameAsBilling: z.boolean()
})
.superRefine((data, ctx) => {
if (data.sameAsBilling) {
// If sameAsBilling but addresses differ, show errors on shipping
if (data.shippingAddress.street !== data.billingAddress.street) {
ctx.addIssue({
code: z.ZodIssueCode.custom,
message: "Must match billing address",
path: ["shippingAddress", "street"] // Nested path
});
}
if (data.shippingAddress.city !== data.billingAddress.city) {
ctx.addIssue({
code: z.ZodIssueCode.custom,
message: "Must match billing address",
path: ["shippingAddress", "city"]
});
}
}
});
```
**When NOT to use this pattern:**
- When the error genuinely applies to the whole object
- Simple single-field refinements (path is implicit)
Reference: [Zod API - refine](https://zod.dev/api#refine)
@@ -0,0 +1,138 @@
---
title: Use catch() for Fault-Tolerant Parsing
impact: MEDIUM
impactDescription: parse() fails on first invalid field; catch() provides fallback values, enabling partial success with degraded data
tags: refine, catch, fallback, resilience
---
## Use catch() for Fault-Tolerant Parsing
When parsing data that might have some invalid fields but you want to accept what's valid, use `.catch()` to provide fallback values instead of failing entirely. This enables graceful degradation for partially corrupted data.
**Incorrect (all-or-nothing parsing):**
```typescript
import { z } from "zod";
const userPrefsSchema = z.object({
theme: z.enum(["light", "dark"]),
fontSize: z.number().min(8).max(32),
language: z.string(),
notifications: z.boolean()
});
// Corrupted localStorage data
const stored = {
theme: "invalid-theme", // Bad
fontSize: 200, // Bad
language: "en", // Good
notifications: "yes" // Bad - should be boolean
};
userPrefsSchema.parse(stored);
// ZodError: Invalid enum value at "theme"
// User loses ALL their preferences because one field is bad
```
**Correct (fault-tolerant with catch):**
```typescript
import { z } from "zod";
const userPrefsSchema = z.object({
theme: z.enum(["light", "dark"]).catch("light"),
fontSize: z.number().min(8).max(32).catch(16),
language: z.string().catch("en"),
notifications: z.boolean().catch(true)
});
// Corrupted data
const stored = {
theme: "invalid-theme",
fontSize: 200,
language: "en",
notifications: "yes"
};
const prefs = userPrefsSchema.parse(stored);
// {
// theme: 'light', // Fallback used
// fontSize: 16, // Fallback used
// language: 'en', // Original value preserved
// notifications: true // Fallback used
// }
// User gets mostly working preferences instead of error
```
**Catch with factory function:**
```typescript
// Factory function receives the caught error
const schema = z.object({
data: z.array(z.number()).catch((ctx) => {
console.warn("Invalid data array:", ctx.error);
return []; // Return empty array as fallback
})
});
```
**Use case: API response resilience:**
```typescript
const productSchema = z.object({
id: z.string(),
name: z.string(),
price: z.number().positive(),
// Legacy field that might be missing or wrong format
legacyCode: z.string().catch("UNKNOWN"),
// External data that might be malformed
metadata: z.record(z.string()).catch({})
});
// API returns partial data
const apiResponse = {
id: "prod-123",
name: "Widget",
price: 29.99,
legacyCode: null, // Bad - should be string
metadata: "invalid" // Bad - should be object
};
const product = productSchema.parse(apiResponse);
// Works! Returns product with fallbacks for bad fields
```
**Difference between catch() and default():**
```typescript
// .default() - only fills in undefined
z.string().default("fallback");
// undefined -> 'fallback'
// null -> ZodError
// '' -> '' (empty string is valid)
// .catch() - fallback for ANY parse failure
z.string().catch("fallback");
// undefined -> 'fallback'
// null -> 'fallback'
// 123 -> 'fallback'
// Even valid strings pass through unchanged
```
**Combining catch with validation:**
```typescript
// Catch only specific validation failures
const schema = z.string().email().catch("invalid@example.com"); // Fallback if not valid email
// Chain for complex defaults
const ageSchema = z.coerce.number().int().min(0).max(120).catch(0); // Invalid ages become 0
```
**When NOT to use this pattern:**
- When invalid data should cause errors (strict validation)
- When you need to know which fields failed (use safeParse)
- Critical fields that must be valid
Reference: [Zod API - catch](https://zod.dev/api#catch)
@@ -0,0 +1,132 @@
---
title: Use default() for Optional Fields with Defaults
impact: MEDIUM
impactDescription: Manual default handling spreads logic across codebase; .default() centralizes defaults in schema
tags: refine, default, optional, configuration
---
## Use default() for Optional Fields with Defaults
When a field is optional but should have a default value when missing, use `.default()` instead of handling defaults in business logic. This keeps default values centralized in the schema and ensures consistent behavior.
**Incorrect (defaults spread across codebase):**
```typescript
import { z } from "zod";
const configSchema = z.object({
timeout: z.number().optional(),
retries: z.number().optional(),
debug: z.boolean().optional()
});
type Config = z.infer<typeof configSchema>;
function createClient(config: Config) {
// Defaults handled in business logic - duplicated everywhere
const timeout = config.timeout ?? 5000;
const retries = config.retries ?? 3;
const debug = config.debug ?? false;
// ...
}
function createOtherClient(config: Config) {
// Same defaults duplicated - risk of inconsistency
const timeout = config.timeout ?? 5000;
const retries = config.retries ?? 3; // What if someone uses 2 here?
const debug = config.debug ?? false;
// ...
}
```
**Correct (defaults in schema):**
```typescript
import { z } from "zod";
const configSchema = z.object({
timeout: z.number().default(5000),
retries: z.number().default(3),
debug: z.boolean().default(false)
});
type Config = z.infer<typeof configSchema>;
// { timeout: number; retries: number; debug: boolean }
// No optional - defaults fill in missing values
function createClient(config: Config) {
// config.timeout is guaranteed to exist
console.log(config.timeout); // 5000 if not provided
console.log(config.retries); // 3 if not provided
console.log(config.debug); // false if not provided
}
// Parse fills in defaults
configSchema.parse({});
// { timeout: 5000, retries: 3, debug: false }
configSchema.parse({ timeout: 10000 });
// { timeout: 10000, retries: 3, debug: false }
```
**Input type vs Output type with defaults:**
```typescript
const schema = z.object({
name: z.string(),
role: z.enum(["admin", "user"]).default("user")
});
type SchemaInput = z.input<typeof schema>;
// { name: string; role?: 'admin' | 'user' }
type SchemaOutput = z.output<typeof schema>;
// { name: string; role: 'admin' | 'user' }
// Input type is optional, output type is required
```
**Default with factory function:**
```typescript
// Static default
const schema1 = z.object({
id: z.string().default("temp-id")
});
// Factory function for dynamic defaults
const schema2 = z.object({
id: z.string().default(() => crypto.randomUUID()),
createdAt: z.date().default(() => new Date())
});
// Each parse creates new values
schema2.parse({}); // { id: 'abc-123...', createdAt: 2024-01-15... }
schema2.parse({}); // { id: 'def-456...', createdAt: 2024-01-15... }
```
**Combining with optional/nullable:**
```typescript
// .optional().default() - if undefined, use default
z.string().optional().default("fallback");
// .nullable().default() - null stays null, only undefined gets default
z.string().nullable().default("fallback");
// null -> null
// undefined -> 'fallback'
// .nullish().default() - both null and undefined get default
z.string().nullish().default("fallback");
// null -> 'fallback'
// undefined -> 'fallback'
```
**When NOT to use this pattern:**
- When absence of value has different meaning than default
- When defaults depend on other fields (use transform)
Reference: [Zod API - default](https://zod.dev/api#default)
@@ -0,0 +1,103 @@
---
title: Distinguish transform() from refine() and coerce()
impact: MEDIUM
impactDescription: Using wrong method causes validation to pass with wrong data; each method has distinct purpose
tags: refine, transform, coerce, conversion
---
## Distinguish transform() from refine() and coerce()
`.refine()` validates and returns boolean, `.transform()` converts data to new format, and `.coerce` converts input before validation. Using the wrong one causes bugs where validation passes but data is wrong.
**Purpose of each method:**
```typescript
import { z } from "zod";
// coerce: Convert type BEFORE validation
// Input: unknown -> Output: validated type
z.coerce.number().parse("42"); // Converts "42" to 42, then validates as number
// refine: Validate with custom logic, return boolean
// Input: T -> Output: T (unchanged, but validated)
z.number().refine((n) => n > 0); // Validates n > 0, returns n unchanged
// transform: Convert to different type AFTER validation
// Input: T -> Output: U (different type)
z.string().transform((s) => s.length); // Validates string, returns length
```
**Incorrect (using transform for validation):**
```typescript
// Wrong: transform should convert, not validate
const schema = z.number().transform((n) => {
if (n < 0) throw new Error("Must be positive"); // Don't throw in transform
return n;
});
```
**Correct (using appropriate method):**
```typescript
import { z } from "zod";
// VALIDATION: Use refine - returns boolean, data unchanged
const positiveNumber = z.number().refine((n) => n > 0, { message: "Must be positive" });
positiveNumber.parse(5); // 5
positiveNumber.parse(-1); // ZodError: Must be positive
// CONVERSION: Use transform - returns new value
const stringLength = z.string().transform((s) => s.length);
type StringLength = z.infer<typeof stringLength>; // number
stringLength.parse("hello"); // 5
// COERCION: Use coerce - converts input type
const coercedNumber = z.coerce.number();
coercedNumber.parse("42"); // 42 (from string)
coercedNumber.parse(42); // 42 (already number)
```
**Combining methods correctly:**
```typescript
// Input: string -> Coerce to number -> Validate positive -> Transform to dollars
const priceSchema = z.coerce
.number()
.refine((n) => n >= 0, "Price cannot be negative")
.transform((cents) => `$${(cents / 100).toFixed(2)}`);
priceSchema.parse("1999"); // "$19.99"
priceSchema.parse("-100"); // ZodError: Price cannot be negative
```
**Order of operations:**
```typescript
const schema = z
.preprocess((val) => val, z.string()) // 1. preprocess (before type check)
.transform((s) => s.trim()) // 2. transform (after type check)
.refine((s) => s.length > 0) // 3. refine (custom validation)
.transform((s) => s.toUpperCase()); // 4. another transform
// Input flows: preprocess -> type check -> transforms/refines in order
```
**Use case comparison:**
| Need | Method | Example |
| ---------------------------- | ------------------------ | -------------- |
| Convert string to number | `z.coerce.number()` | Form input |
| Validate number is positive | `.refine(n => n > 0)` | Business rule |
| Convert cents to dollars | `.transform(n => n/100)` | Display format |
| Trim whitespace before check | `z.preprocess` | Input cleanup |
**When NOT to use this pattern:**
- Simple type coercion: use `z.coerce.*`
- Simple validation: use built-in methods like `.min()`, `.email()`
Reference: [Zod API - transform](https://zod.dev/api#transform)
@@ -0,0 +1,159 @@
---
title: Choose refine() vs superRefine() Correctly
impact: MEDIUM
impactDescription: refine() only reports one error; superRefine() enables multiple issues and custom error codes
tags: refine, superRefine, validation, custom
---
## Choose refine() vs superRefine() Correctly
`.refine()` is for simple single-condition validation returning boolean. `.superRefine()` gives you a context object to add multiple issues with custom error codes and paths. Choose based on your error reporting needs.
**Incorrect (using refine for multiple checks):**
```typescript
import { z } from "zod";
// refine can only report one error at a time
const passwordSchema = z.string().refine(
(password) => {
// Checks all conditions but only reports first failure
if (password.length < 8) return false; // Only this error shown
if (!/[A-Z]/.test(password)) return false;
if (!/[0-9]/.test(password)) return false;
return true;
},
{ message: "Password does not meet requirements" }
);
passwordSchema.parse("weak");
// Only shows: "Password does not meet requirements"
// User doesn't know WHICH requirements failed
```
**Correct (using superRefine for multiple issues):**
```typescript
import { z } from "zod";
const passwordSchema = z.string().superRefine((password, ctx) => {
if (password.length < 8) {
ctx.addIssue({
code: z.ZodIssueCode.custom,
message: "Password must be at least 8 characters"
});
}
if (!/[A-Z]/.test(password)) {
ctx.addIssue({
code: z.ZodIssueCode.custom,
message: "Password must contain an uppercase letter"
});
}
if (!/[0-9]/.test(password)) {
ctx.addIssue({
code: z.ZodIssueCode.custom,
message: "Password must contain a number"
});
}
if (!/[!@#$%^&*]/.test(password)) {
ctx.addIssue({
code: z.ZodIssueCode.custom,
message: "Password must contain a special character"
});
}
});
passwordSchema.safeParse("weak");
// Shows ALL failures:
// - "Password must be at least 8 characters"
// - "Password must contain an uppercase letter"
// - "Password must contain a number"
// - "Password must contain a special character"
```
**When to use refine():**
```typescript
// Simple boolean condition with one error message
const adultSchema = z.number().refine((age) => age >= 18, { message: "Must be 18 or older" });
// Cross-field validation with single outcome
const formSchema = z
.object({
password: z.string(),
confirmPassword: z.string()
})
.refine((data) => data.password === data.confirmPassword, {
message: "Passwords must match",
path: ["confirmPassword"]
});
// Async validation
const emailSchema = z
.string()
.email()
.refine(
async (email) => {
const exists = await checkEmailExists(email);
return !exists;
},
{ message: "Email already registered" }
);
```
**When to use superRefine():**
```typescript
// Multiple independent checks on same value
// Cross-field validation with multiple possible errors
// Need custom error codes for i18n or client handling
// Need to add issues at specific paths
const orderSchema = z
.object({
items: z.array(
z.object({
productId: z.string(),
quantity: z.number()
})
),
promoCode: z.string().optional()
})
.superRefine(async (order, ctx) => {
// Check each item's availability
for (let i = 0; i < order.items.length; i++) {
const item = order.items[i];
const available = await checkInventory(item.productId, item.quantity);
if (!available) {
ctx.addIssue({
code: z.ZodIssueCode.custom,
path: ["items", i, "quantity"], // Specific path
message: `Only ${available} units available`
});
}
}
// Validate promo code
if (order.promoCode) {
const valid = await validatePromoCode(order.promoCode);
if (!valid) {
ctx.addIssue({
code: z.ZodIssueCode.custom,
path: ["promoCode"],
message: "Invalid or expired promo code"
});
}
}
});
```
**When NOT to use this pattern:**
- Simple single-condition checks (use refine for simplicity)
- Transform needed instead of validation (use transform)
Reference: [Zod API - refine/superRefine](https://zod.dev/api#refine)
@@ -0,0 +1,94 @@
---
title: Avoid Overusing Optional Fields
impact: CRITICAL
impactDescription: Excessive optional fields create schemas that accept almost anything; forces null checks throughout codebase
tags: schema, optional, nullable, required
---
## Avoid Overusing Optional Fields
Making too many fields optional creates overly permissive schemas that validate almost any input. This pushes validation downstream into business logic, requiring defensive null checks everywhere instead of guaranteeing data shape at the boundary.
**Incorrect (optional abuse):**
```typescript
import { z } from "zod";
// Every field optional - almost anything passes
const userSchema = z.object({
id: z.string().optional(),
name: z.string().optional(),
email: z.string().optional(),
role: z.string().optional()
});
type User = z.infer<typeof userSchema>;
// { id?: string; name?: string; email?: string; role?: string }
// Empty object passes validation!
userSchema.parse({}); // ✓ Valid: {}
function greetUser(user: User) {
// Forced to add null checks everywhere
if (user.name) {
console.log(`Hello, ${user.name}`);
} else {
console.log("Hello, stranger"); // Shouldn't happen if data is clean
}
}
```
**Correct (explicit required vs optional):**
```typescript
import { z } from "zod";
// Required fields are required, optional fields are intentional
const userSchema = z.object({
id: z.string().uuid(), // Required
name: z.string().min(1), // Required, non-empty
email: z.string().email(), // Required
role: z.enum(["admin", "user", "guest"]), // Required
nickname: z.string().optional(), // Intentionally optional
bio: z.string().nullable() // Can be explicitly null
});
type User = z.infer<typeof userSchema>;
// Empty object fails validation
userSchema.parse({}); // ✗ Throws ZodError
function greetUser(user: User) {
// user.name is guaranteed to exist
console.log(`Hello, ${user.name}`);
// Only optional fields need checks
if (user.nickname) {
console.log(`Also known as: ${user.nickname}`);
}
}
```
**Use `.partial()` for update schemas:**
```typescript
// Base schema with required fields
const userSchema = z.object({
id: z.string().uuid(),
name: z.string().min(1),
email: z.string().email()
});
// All fields optional for PATCH updates
const updateUserSchema = userSchema.partial();
// Only specific fields optional
const createUserSchema = userSchema.partial({ id: true });
```
**When NOT to use this pattern:**
- When modeling partial updates (PATCH endpoints)
- When fields genuinely may not exist (legacy data, external APIs)
Reference: [Zod API - optional](https://zod.dev/api#optional)
@@ -0,0 +1,89 @@
---
title: Use Coercion for Form and Query Data
impact: CRITICAL
impactDescription: Form data and query params are always strings; without coercion, z.number() rejects "42" and z.boolean() rejects "true"
tags: schema, coerce, forms, query-params
---
## Use Coercion for Form and Query Data
HTML forms and URL query parameters always transmit data as strings. Using `z.number()` on form data will fail because `"42"` is not a number. Use `z.coerce.number()` to automatically convert strings to the correct type.
**Incorrect (no coercion for form data):**
```typescript
import { z } from "zod";
const searchSchema = z.object({
query: z.string(),
page: z.number(), // Expects actual number
limit: z.number(),
showDeleted: z.boolean() // Expects actual boolean
});
// Form data / query params are strings
const formData = new URLSearchParams("query=test&page=1&limit=10&showDeleted=true");
const params = Object.fromEntries(formData);
// { query: 'test', page: '1', limit: '10', showDeleted: 'true' }
searchSchema.parse(params);
// ZodError: Expected number, received string at "page"
// ZodError: Expected number, received string at "limit"
// ZodError: Expected boolean, received string at "showDeleted"
```
**Correct (using coercion):**
```typescript
import { z } from "zod";
const searchSchema = z.object({
query: z.string(),
page: z.coerce.number().int().positive().default(1),
limit: z.coerce.number().int().min(1).max(100).default(10),
showDeleted: z.coerce.boolean().default(false)
});
// Form data / query params are strings
const formData = new URLSearchParams("query=test&page=1&limit=10&showDeleted=true");
const params = Object.fromEntries(formData);
const result = searchSchema.parse(params);
// { query: 'test', page: 1, limit: 10, showDeleted: true }
// Types are correct: number, number, boolean
```
**Available coercion types:**
```typescript
z.coerce.string(); // Converts anything to string via String(value)
z.coerce.number(); // Converts via Number(value), NaN fails validation
z.coerce.boolean(); // Truthy/falsy conversion
z.coerce.bigint(); // Converts via BigInt(value)
z.coerce.date(); // Converts via new Date(value)
```
**Coercion edge cases:**
```typescript
// z.coerce.number() behavior
z.coerce.number().parse("42"); // 42
z.coerce.number().parse(""); // 0 (empty string becomes 0!)
z.coerce.number().parse("abc"); // ZodError (NaN fails)
// z.coerce.boolean() behavior
z.coerce.boolean().parse("true"); // true
z.coerce.boolean().parse("false"); // true! (non-empty string is truthy)
z.coerce.boolean().parse(""); // false
z.coerce.boolean().parse("0"); // true! (non-empty string)
// For strict boolean parsing from strings:
const strictBooleanSchema = z.enum(["true", "false"]).transform((v) => v === "true");
```
**When NOT to use this pattern:**
- When receiving JSON payloads (already typed correctly)
- When you want strict type checking without conversion
Reference: [Zod API - Coercion](https://zod.dev/api#coercion)
@@ -0,0 +1,87 @@
---
title: Apply String Validations at Schema Definition
impact: CRITICAL
impactDescription: Unvalidated strings allow SQL injection, XSS, and malformed data; validating at schema level catches issues at the boundary
tags: schema, string, validation, security
---
## Apply String Validations at Schema Definition
Plain `z.string()` accepts any string including empty strings, extremely long strings, and malicious content. Apply constraints like `min()`, `max()`, `email()`, `url()`, or `regex()` at schema definition to reject invalid data at the boundary.
**Incorrect (no string validations):**
```typescript
import { z } from "zod";
const commentSchema = z.object({
author: z.string(), // Empty string passes
email: z.string(), // "not-an-email" passes
content: z.string(), // 10MB string passes, script tags pass
website: z.string().optional() // "javascript:alert(1)" passes
});
// All of these pass validation
commentSchema.parse({
author: "", // Empty - who wrote this?
email: "invalid", // Not a real email
content: '<script>alert("XSS")</script>'.repeat(100000), // XSS + huge
website: "javascript:void(0)" // Dangerous URL
});
```
**Correct (string validations applied):**
```typescript
import { z } from "zod";
const commentSchema = z.object({
author: z.string().min(1, "Author is required").max(100, "Author name too long"),
email: z.string().email("Invalid email address"),
content: z.string().min(1, "Comment cannot be empty").max(5000, "Comment too long"),
website: z
.string()
.url("Invalid URL")
.refine(
(url) => url.startsWith("http://") || url.startsWith("https://"),
"Only http/https URLs allowed"
)
.optional()
});
// Invalid data is rejected
commentSchema.parse({
author: "",
email: "invalid",
content: ""
});
// ZodError with all violations listed
```
**Common string validations:**
```typescript
z.string().min(1); // Non-empty (most common need)
z.string().max(255); // Database varchar limit
z.string().length(36); // Exact length (UUIDs)
z.string().email(); // Email format
z.string().url(); // URL format
z.string().uuid(); // UUID format
z.string().cuid(); // CUID format
z.string().regex(/^[a-z0-9-]+$/); // Custom pattern (slugs)
z.string().startsWith("https://"); // Prefix check
z.string().endsWith(".pdf"); // Suffix check
z.string().includes("@"); // Contains check
z.string().trim(); // Strips whitespace (transform)
z.string().toLowerCase(); // Normalizes case (transform)
```
**When NOT to use this pattern:**
- When accepting arbitrary user content for display only (sanitize on output instead)
- When building a passthrough/proxy that shouldn't validate content
Reference: [Zod API - Strings](https://zod.dev/api#strings)
@@ -0,0 +1,106 @@
---
title: Use Enums for Fixed String Values
impact: CRITICAL
impactDescription: Plain strings accept any value including typos; enums restrict to valid values and enable autocomplete
tags: schema, enum, literal, union
---
## Use Enums for Fixed String Values
When a field should only accept specific values (status, role, type), use `z.enum()` or `z.literal()` instead of `z.string()`. Plain strings accept any value including typos, while enums provide validation, type safety, and IDE autocomplete.
**Incorrect (plain string for fixed values):**
```typescript
import { z } from "zod";
const orderSchema = z.object({
id: z.string(),
status: z.string(), // Accepts any string
priority: z.string() // No constraints
});
type Order = z.infer<typeof orderSchema>;
// { id: string; status: string; priority: string }
// Typos and invalid values pass validation
orderSchema.parse({
id: "123",
status: "pendng", // Typo passes
priority: "super-urgent" // Invalid value passes
});
function processOrder(order: Order) {
if (order.status === "pending") {
// Might never match due to typos
// ...
}
}
```
**Correct (using z.enum):**
```typescript
import { z } from "zod";
const OrderStatus = z.enum(["pending", "processing", "shipped", "delivered"]);
const Priority = z.enum(["low", "medium", "high"]);
const orderSchema = z.object({
id: z.string(),
status: OrderStatus,
priority: Priority
});
type Order = z.infer<typeof orderSchema>;
// { id: string; status: 'pending' | 'processing' | 'shipped' | 'delivered'; priority: 'low' | 'medium' | 'high' }
// Typos are caught at validation
orderSchema.parse({
id: "123",
status: "pendng", // ZodError: Invalid enum value
priority: "super-urgent" // ZodError: Invalid enum value
});
// Extract enum values for reuse
OrderStatus.options; // ['pending', 'processing', 'shipped', 'delivered']
type OrderStatusType = z.infer<typeof OrderStatus>; // 'pending' | 'processing' | ...
```
**For native TypeScript enums:**
```typescript
enum Role {
Admin = "admin",
User = "user",
Guest = "guest"
}
// Use z.nativeEnum for TS enums
const userSchema = z.object({
role: z.nativeEnum(Role)
});
```
**For single literal values (discriminated unions):**
```typescript
const successResponse = z.object({
status: z.literal("success"),
data: z.unknown()
});
const errorResponse = z.object({
status: z.literal("error"),
message: z.string()
});
const response = z.discriminatedUnion("status", [successResponse, errorResponse]);
```
**When NOT to use this pattern:**
- When the set of valid values is dynamic or user-defined
- When values come from a database that may have more options
Reference: [Zod API - Enums](https://zod.dev/api#enums)
@@ -0,0 +1,63 @@
---
title: Use Primitive Schemas Correctly
impact: CRITICAL
impactDescription: Incorrect primitive selection causes validation to pass on wrong types; using z.any() or z.unknown() loses all type safety
tags: schema, primitives, types, basics
---
## Use Primitive Schemas Correctly
Zod provides specific schemas for each primitive type. Using the wrong schema (e.g., `z.string()` when you need `z.number()`) or falling back to `z.any()` defeats the purpose of validation entirely, allowing corrupt data through.
**Incorrect (wrong primitive or any):**
```typescript
import { z } from "zod";
// Using any loses all type safety
const userSchema = z.object({
id: z.any(), // Accepts anything - no validation
age: z.string(), // Wrong type - age should be number
active: z.any() // Should be boolean
});
// This passes validation but data is wrong
userSchema.parse({ id: null, age: "twenty", active: "yes" });
// Result: { id: null, age: "twenty", active: "yes" }
```
**Correct (specific primitives):**
```typescript
import { z } from "zod";
const userSchema = z.object({
id: z.string().uuid(), // Specific format validation
age: z.number().int().positive(), // Correct type with constraints
active: z.boolean() // Exact boolean type
});
// Now invalid data is rejected
userSchema.parse({ id: null, age: "twenty", active: "yes" });
// Throws ZodError with specific field errors
```
**Available primitive schemas:**
- `z.string()` - strings with optional regex, min, max, email, url, uuid
- `z.number()` - numbers with optional int, positive, negative, min, max
- `z.bigint()` - BigInt values
- `z.boolean()` - true/false only
- `z.date()` - Date objects
- `z.symbol()` - Symbol type
- `z.undefined()` - undefined only
- `z.null()` - null only
- `z.void()` - undefined (for function returns)
- `z.never()` - no valid value
**When NOT to use this pattern:**
- When you genuinely need to accept any value (rare - consider `z.unknown()` instead)
- When migrating legacy code incrementally (use `z.any()` temporarily, then fix)
Reference: [Zod Primitives](https://zod.dev/api#primitives)
@@ -0,0 +1,86 @@
---
title: Use z.unknown() Instead of z.any()
impact: CRITICAL
impactDescription: z.any() bypasses TypeScript's type system entirely; z.unknown() forces type narrowing before use
tags: schema, unknown, any, type-safety
---
## Use z.unknown() Instead of z.any()
`z.any()` infers to `any` type, disabling TypeScript's type checking for that value. `z.unknown()` infers to `unknown`, which forces you to narrow the type before using it. This preserves type safety while still allowing any input.
**Incorrect (using z.any):**
```typescript
import { z } from "zod";
const eventSchema = z.object({
type: z.string(),
payload: z.any() // Infers to 'any'
});
type Event = z.infer<typeof eventSchema>;
// { type: string; payload: any }
function handleEvent(event: Event) {
// No type error - TypeScript allows anything
console.log(event.payload.foo.bar.baz); // Runtime crash if structure is wrong
}
```
**Correct (using z.unknown):**
```typescript
import { z } from "zod";
const eventSchema = z.object({
type: z.string(),
payload: z.unknown() // Infers to 'unknown'
});
type Event = z.infer<typeof eventSchema>;
// { type: string; payload: unknown }
function handleEvent(event: Event) {
// TypeScript error: Object is of type 'unknown'
console.log(event.payload.foo); // Won't compile
// Must narrow type first
if (typeof event.payload === "object" && event.payload !== null) {
// Now TypeScript knows it's an object
}
}
```
**Better approach with discriminated unions:**
```typescript
import { z } from "zod";
const userCreatedSchema = z.object({
type: z.literal("user.created"),
payload: z.object({
userId: z.string(),
email: z.string().email()
})
});
const orderPlacedSchema = z.object({
type: z.literal("order.placed"),
payload: z.object({
orderId: z.string(),
amount: z.number()
})
});
const eventSchema = z.discriminatedUnion("type", [userCreatedSchema, orderPlacedSchema]);
// Full type safety for each event type
```
**When NOT to use this pattern:**
- When you're consuming a third-party API where you truly don't know the shape
- When prototyping and will add proper types later
Reference: [Zod API - unknown](https://zod.dev/api#unknown)
@@ -0,0 +1,106 @@
---
title: Use Branded Types for Domain Safety
impact: HIGH
impactDescription: Plain string IDs are interchangeable, allowing userId where orderId is expected; branded types catch these bugs at compile time
tags: type, brand, domain, nominal
---
## Use Branded Types for Domain Safety
Plain strings and numbers are interchangeable in TypeScript's structural type system—a `userId` can be passed where an `orderId` is expected. Zod's `.brand()` creates nominal types that prevent mixing up semantically different values.
**Incorrect (plain IDs are interchangeable):**
```typescript
import { z } from "zod";
const userIdSchema = z.string().uuid();
const orderIdSchema = z.string().uuid();
type UserId = z.infer<typeof userIdSchema>; // string
type OrderId = z.infer<typeof orderIdSchema>; // string - same type!
async function getOrder(orderId: OrderId) {
return db.orders.findUnique({ where: { id: orderId } });
}
const userId: UserId = "550e8400-e29b-41d4-a716-446655440000";
getOrder(userId); // No error! TypeScript allows this bug
// Runtime: queries orders table with user ID, returns nothing or wrong data
```
**Correct (using branded types):**
```typescript
import { z } from "zod";
const userIdSchema = z.string().uuid().brand<"UserId">();
const orderIdSchema = z.string().uuid().brand<"OrderId">();
type UserId = z.infer<typeof userIdSchema>;
// string & { __brand: 'UserId' }
type OrderId = z.infer<typeof orderIdSchema>;
// string & { __brand: 'OrderId' }
async function getOrder(orderId: OrderId) {
return db.orders.findUnique({ where: { id: orderId } });
}
const userId = userIdSchema.parse("550e8400-e29b-41d4-a716-446655440000");
getOrder(userId); // TypeScript error: Argument of type 'UserId' is not assignable to parameter of type 'OrderId'
const orderId = orderIdSchema.parse("660e8400-e29b-41d4-a716-446655440001");
getOrder(orderId); // Works correctly
```
**Common branded types:**
```typescript
// IDs for different entities
const UserId = z.string().uuid().brand<"UserId">();
const ProductId = z.string().uuid().brand<"ProductId">();
const OrderId = z.string().uuid().brand<"OrderId">();
// Email (validated and branded)
const Email = z.string().email().brand<"Email">();
// Positive numbers
const PositiveInt = z.number().int().positive().brand<"PositiveInt">();
// Money amounts (in cents)
const Cents = z.number().int().nonnegative().brand<"Cents">();
// Slugs
const Slug = z
.string()
.regex(/^[a-z0-9-]+$/)
.brand<"Slug">();
```
**Using with object schemas:**
```typescript
const User = z.object({
id: z.string().uuid().brand<"UserId">(),
email: z.string().email().brand<"Email">(),
referredBy: z.string().uuid().brand<"UserId">().optional()
});
type User = z.infer<typeof User>;
function sendReferralBonus(
referrerId: z.infer<typeof User>["id"],
refereeId: z.infer<typeof User>["id"]
) {
// Can't accidentally swap these - both are UserId but distinct values
}
```
**When NOT to use this pattern:**
- Simple applications without ID confusion risk
- When interoperating with external systems that expect plain strings
- Performance-critical paths (brand adds tiny overhead)
Reference: [Zod API - brand](https://zod.dev/api#brand)
@@ -0,0 +1,132 @@
---
title: Enable TypeScript Strict Mode
impact: HIGH
impactDescription: Without strict mode, Zod's type inference is unreliable; undefined and null slip through, defeating the purpose of validation
tags: type, typescript, strict, configuration
---
## Enable TypeScript Strict Mode
Zod requires TypeScript's strict mode to work correctly. Without it, `undefined` sneaks into types, `null` checks are bypassed, and type inference becomes unreliable. This undermines the type safety that Zod provides.
**Incorrect (strict mode disabled):**
```json
// tsconfig.json
{
"compilerOptions": {
"strict": false
}
}
```
```typescript
import { z } from "zod";
const userSchema = z.object({
name: z.string(),
email: z.string().email()
});
type User = z.infer<typeof userSchema>;
// With strict:false, type might include undefined implicitly
function processUser(user: User) {
// No error even if user.name could be undefined
console.log(user.name.toUpperCase()); // Potential runtime crash
}
// TypeScript allows calling with undefined
processUser(undefined as any); // No warning
```
**Correct (strict mode enabled):**
```json
// tsconfig.json
{
"compilerOptions": {
"strict": true
}
}
```
```typescript
import { z } from "zod";
const userSchema = z.object({
name: z.string(),
email: z.string().email()
});
type User = z.infer<typeof userSchema>;
// { name: string; email: string } - no implicit undefined
function processUser(user: User) {
// TypeScript knows name is always string
console.log(user.name.toUpperCase()); // Safe
}
// TypeScript catches potential undefined
processUser(undefined as any); // Error with strict null checks
```
**Minimum strict settings for Zod:**
```json
// tsconfig.json
{
"compilerOptions": {
// Full strict mode (recommended)
"strict": true,
// Or at minimum, enable these:
"strictNullChecks": true,
"noImplicitAny": true
}
}
```
**Common errors when strict mode is disabled:**
```typescript
// Without strictNullChecks
const schema = z.string().optional();
type MaybeString = z.infer<typeof schema>;
// Should be: string | undefined
// Without strict: just string (undefined is implicit)
// Without noImplicitAny
const schema = z.object({ name: z.string() });
schema.parse(data); // data could be 'any', bypassing validation
```
**Migrating to strict mode:**
```typescript
// If enabling strict breaks existing code, fix issues incrementally
// Common fixes:
// 1. Add null checks
if (user.name !== undefined) {
console.log(user.name.toUpperCase());
}
// 2. Add explicit types
function processData(data: unknown) {
// Was implicit any
const validated = schema.parse(data);
}
// 3. Handle optional fields
const user: User = {
name: "John",
email: "john@example.com" // Now required, was optional without strict
};
```
**When NOT to use this pattern:**
- Never - always enable strict mode for Zod projects
Reference: [Zod Requirements](https://zod.dev/#requirements)
@@ -0,0 +1,117 @@
---
title: Export Both Schemas and Inferred Types
impact: HIGH
impactDescription: Exporting only schemas forces consumers to derive types themselves; exporting both reduces boilerplate and improves DX
tags: type, export, module, organization
---
## Export Both Schemas and Inferred Types
When defining schemas in shared modules, export both the schema and its inferred type. This saves consumers from writing `z.infer<typeof schema>` repeatedly and makes imports cleaner.
**Incorrect (exporting only schema):**
```typescript
// schemas/user.ts
import { z } from "zod";
export const userSchema = z.object({
id: z.string().uuid(),
email: z.string().email(),
name: z.string(),
role: z.enum(["admin", "user"])
});
// Every consumer must derive the type
// api/users.ts
import { userSchema } from "@/schemas/user";
import type { z } from "zod";
type User = z.infer<typeof userSchema>; // Repeated everywhere
// components/UserCard.tsx
import { userSchema } from "@/schemas/user";
import type { z } from "zod";
type User = z.infer<typeof userSchema>; // Same boilerplate again
```
**Correct (exporting schema and type):**
```typescript
// schemas/user.ts
import { z } from "zod";
export const userSchema = z.object({
id: z.string().uuid(),
email: z.string().email(),
name: z.string(),
role: z.enum(["admin", "user"])
});
export type User = z.infer<typeof userSchema>;
// For schemas with transforms, export both
export const apiUserSchema = z.object({
id: z.string(),
created_at: z.string().transform((s) => new Date(s))
});
export type ApiUserInput = z.input<typeof apiUserSchema>;
export type ApiUser = z.infer<typeof apiUserSchema>;
```
```typescript
// api/users.ts - clean import
import { userSchema, type User } from '@/schemas/user'
async function getUser(id: string): Promise<User> {
const data = await db.users.findUnique({ where: { id } })
return userSchema.parse(data)
}
// components/UserCard.tsx - just the type
import type { User } from '@/schemas/user'
function UserCard({ user }: { user: User }) {
return <div>{user.name}</div>
}
```
**Organizing schema exports:**
```typescript
// schemas/index.ts - barrel file for schemas
export { userSchema, type User, type UserInput } from "./user";
export { orderSchema, type Order } from "./order";
export { productSchema, type Product } from "./product";
// Usage
import { userSchema, type User, type Order } from "@/schemas";
```
**With enums, export the enum values too:**
```typescript
// schemas/user.ts
export const UserRole = z.enum(["admin", "user", "guest"]);
export type UserRole = z.infer<typeof UserRole>;
export const userSchema = z.object({
id: z.string(),
role: UserRole
});
export type User = z.infer<typeof userSchema>;
// Access enum values
UserRole.options; // ['admin', 'user', 'guest']
UserRole.enum.admin; // 'admin'
```
**When NOT to use this pattern:**
- Internal schemas that won't be used outside the module
- Transient schemas used only for validation (not as types)
Reference: [Zod API - Type Inference](https://zod.dev/api#type-inference)
@@ -0,0 +1,116 @@
---
title: Distinguish z.input from z.infer for Transforms
impact: HIGH
impactDescription: Using wrong type with transforms causes TypeScript errors; z.input captures pre-transform shape, z.infer captures post-transform
tags: type, input, output, transform
---
## Distinguish z.input from z.infer for Transforms
When schemas use `.transform()`, the input and output types differ. `z.infer` (same as `z.output`) gives the post-transform type, while `z.input` gives the pre-transform type. Using the wrong one causes confusing TypeScript errors.
**Incorrect (using infer for input type):**
```typescript
import { z } from "zod";
const dateSchema = z.string().transform((s) => new Date(s));
type DateOutput = z.infer<typeof dateSchema>;
// Date (post-transform)
// Wrong! Expecting Date but should accept string
function handleDate(input: DateOutput) {
return dateSchema.parse(input); // Error: Argument of type 'Date' is not assignable to type 'string'
}
// Caller passes string, but type says Date
handleDate("2024-01-15"); // TypeScript error
```
**Correct (using z.input for pre-transform type):**
```typescript
import { z } from "zod";
const dateSchema = z.string().transform((s) => new Date(s));
// Input type = what parse() accepts
type DateInput = z.input<typeof dateSchema>;
// string (pre-transform)
// Output type = what parse() returns
type DateOutput = z.output<typeof dateSchema>;
// Date (post-transform)
// Use input type for function parameters
function handleDate(input: DateInput) {
const parsed = dateSchema.parse(input); // parsed is Date
return parsed;
}
handleDate("2024-01-15"); // Works - string input
```
**Complex example with object transforms:**
```typescript
const apiUserSchema = z.object({
id: z.string(),
created_at: z.string().transform((s) => new Date(s)),
tags: z.string().transform((s) => s.split(",")),
is_active: z.union([z.boolean(), z.literal(1), z.literal(0)]).transform((v) => Boolean(v))
});
// What the API sends
type ApiUserInput = z.input<typeof apiUserSchema>;
// {
// id: string
// created_at: string
// tags: string
// is_active: boolean | 1 | 0
// }
// What your code works with
type ApiUser = z.infer<typeof apiUserSchema>;
// {
// id: string
// created_at: Date
// tags: string[]
// is_active: boolean
// }
// API response handler
function handleApiResponse(rawData: ApiUserInput) {
const user = apiUserSchema.parse(rawData);
// user.created_at is Date
// user.tags is string[]
// user.is_active is boolean
return user;
}
```
**Using with function types:**
```typescript
const formSchema = z.object({
amount: z.string().transform((s) => parseFloat(s)),
quantity: z.string().transform((s) => parseInt(s, 10))
});
type FormInput = z.input<typeof formSchema>;
type FormOutput = z.output<typeof formSchema>;
// Form handler receives raw strings
type FormHandler = (input: FormInput) => Promise<void>;
// Business logic receives parsed values
type OrderProcessor = (order: FormOutput) => Promise<void>;
```
**When NOT to use this pattern:**
- Schemas without transforms (input and output are identical)
- When you only work with validated data (just use z.infer)
Reference: [Zod - Type Inference](https://zod.dev/api#type-inference)
@@ -0,0 +1,111 @@
---
title: Use z.infer Instead of Manual Types
impact: HIGH
impactDescription: Manual type definitions drift from schemas over time; z.infer guarantees types match validation exactly
tags: type, infer, typescript, dry
---
## Use z.infer Instead of Manual Types
Defining TypeScript types separately from Zod schemas creates duplication that inevitably drifts. When you update a schema, you must remember to update the type—and you will forget. Use `z.infer<typeof schema>` to derive types from schemas automatically.
**Incorrect (manual type definitions):**
```typescript
import { z } from "zod";
// Manual type definition
interface User {
id: string;
name: string;
email: string;
age: number;
}
// Separate schema
const userSchema = z.object({
id: z.string().uuid(),
name: z.string().min(1),
email: z.string().email(),
age: z.number().int().positive(),
role: z.enum(["admin", "user"]) // Added to schema, forgot to add to interface!
});
// Type and schema are now out of sync
function createUser(user: User) {
const validated = userSchema.parse(user); // Has role
saveToDb(user); // Missing role - TypeScript doesn't warn
}
```
**Correct (using z.infer):**
```typescript
import { z } from "zod";
// Schema is the single source of truth
const userSchema = z.object({
id: z.string().uuid(),
name: z.string().min(1),
email: z.string().email(),
age: z.number().int().positive(),
role: z.enum(["admin", "user"])
});
// Type is always in sync with schema
type User = z.infer<typeof userSchema>;
// { id: string; name: string; email: string; age: number; role: 'admin' | 'user' }
function createUser(user: User) {
// user.role exists because type is derived from schema
const validated = userSchema.parse(user);
saveToDb(validated);
}
```
**Input vs Output types with transforms:**
```typescript
const userSchema = z.object({
name: z.string(),
createdAt: z.string().transform((s) => new Date(s)) // String in, Date out
});
// z.infer gives output type (after transforms)
type User = z.infer<typeof userSchema>;
// { name: string; createdAt: Date }
// z.input gives input type (before transforms)
type UserInput = z.input<typeof userSchema>;
// { name: string; createdAt: string }
// Use input type for function parameters accepting raw data
function processUser(input: UserInput) {
const user = userSchema.parse(input); // user is User type
return user.createdAt.getTime(); // Date methods available
}
```
**Naming convention:**
```typescript
// Schema named with Schema suffix
const UserSchema = z.object({
id: z.string(),
name: z.string()
});
// Type named without suffix
type User = z.infer<typeof UserSchema>;
// Alternative: lowercase schema, uppercase type
const userSchema = z.object({/*...*/});
type User = z.infer<typeof userSchema>;
```
**When NOT to use this pattern:**
- When you need a type that's different from the validation schema
- When interfacing with external types you don't control
Reference: [Zod - Type Inference](https://zod.dev/api#type-inference)
+58
View File
@@ -0,0 +1,58 @@
#!/usr/bin/env node
const path = require("path");
const fs = require("fs");
const { pathToFileURL } = require("url");
const { execFileSync } = require("child_process");
const dir = process.env.CLAUDE_PROJECT_DIR || process.cwd();
const BAKED =
"C:\\Users\\Administrator.DESKTOP-EGNE9ND\\AppData\\Roaming\\npm\\node_modules\\@nanonets\\graft\\dist\\claude";
// The dist/claude dir of @nanonets/graft resolved from a base whose node_modules is searched.
function fromPkg(base) {
try {
const pkg = require.resolve("@nanonets/graft/package.json", { paths: [base] });
return path.join(path.dirname(pkg), "dist", "claude");
} catch {
return null;
}
}
// The global node_modules dir per npm (handles Homebrew/Windows/volta). Queried on demand.
function globalRoot() {
try {
const root = execFileSync("npm", ["root", "-g"], {
encoding: "utf8",
stdio: ["ignore", "pipe", "ignore"],
shell: process.platform === "win32"
}).trim();
return root || null;
} catch {
return null; /* npm unavailable */
}
}
function candidates() {
const out = [];
if (BAKED) out.push(BAKED);
const local = fromPkg(dir);
if (local) out.push(local);
const legacy = fromPkg(path.join(path.dirname(process.execPath), "..", "lib"));
if (legacy) out.push(legacy);
const gr = globalRoot();
if (gr) out.push(path.join(gr, "@nanonets", "graft", "dist", "claude"));
return out;
}
function entry(name) {
for (const d of candidates()) {
const f = path.join(d, name);
if (fs.existsSync(f)) return f;
}
return path.join(dir, "dist", "claude", name); // last-ditch; import will no-op if absent
}
import(pathToFileURL(entry("hooks.js")).href)
.then((m) => m.main(process.argv[2]))
.catch(() => {
/* graft unavailable — no-op */
});
+58
View File
@@ -0,0 +1,58 @@
#!/usr/bin/env node
const path = require("path");
const fs = require("fs");
const { pathToFileURL } = require("url");
const { execFileSync } = require("child_process");
const dir = process.env.CLAUDE_PROJECT_DIR || process.cwd();
const BAKED =
"C:\\Users\\Administrator.DESKTOP-EGNE9ND\\AppData\\Roaming\\npm\\node_modules\\@nanonets\\graft\\dist\\claude";
// The dist/claude dir of @nanonets/graft resolved from a base whose node_modules is searched.
function fromPkg(base) {
try {
const pkg = require.resolve("@nanonets/graft/package.json", { paths: [base] });
return path.join(path.dirname(pkg), "dist", "claude");
} catch {
return null;
}
}
// The global node_modules dir per npm (handles Homebrew/Windows/volta). Queried on demand.
function globalRoot() {
try {
const root = execFileSync("npm", ["root", "-g"], {
encoding: "utf8",
stdio: ["ignore", "pipe", "ignore"],
shell: process.platform === "win32"
}).trim();
return root || null;
} catch {
return null; /* npm unavailable */
}
}
function candidates() {
const out = [];
if (BAKED) out.push(BAKED);
const local = fromPkg(dir);
if (local) out.push(local);
const legacy = fromPkg(path.join(path.dirname(process.execPath), "..", "lib"));
if (legacy) out.push(legacy);
const gr = globalRoot();
if (gr) out.push(path.join(gr, "@nanonets", "graft", "dist", "claude"));
return out;
}
function entry(name) {
for (const d of candidates()) {
const f = path.join(d, name);
if (fs.existsSync(f)) return f;
}
return path.join(dir, "dist", "claude", name); // last-ditch; import will no-op if absent
}
import(pathToFileURL(entry("statusline.js")).href)
.then((m) => m.main())
.catch(() => {
/* graft unavailable — no-op */
});
+71
View File
@@ -0,0 +1,71 @@
{
"statusLine": {
"type": "command",
"command": "node \"${CLAUDE_PROJECT_DIR:-.}/.claude/helpers/graft-statusline.cjs\""
},
"subagentStatusLine": {
"type": "command",
"command": "node \"${CLAUDE_PROJECT_DIR:-.}/.claude/helpers/graft-statusline.cjs\""
},
"hooks": {
"PostToolUse": [
{
"matcher": "Write|Edit|MultiEdit",
"hooks": [
{
"type": "command",
"command": "node \"${CLAUDE_PROJECT_DIR:-.}/.claude/helpers/graft-hooks.cjs\" post-edit",
"timeout": 10000
}
]
},
{
"matcher": "Bash|mcp__graft__",
"hooks": [
{
"type": "command",
"command": "node \"${CLAUDE_PROJECT_DIR:-.}/.claude/helpers/graft-hooks.cjs\" tool-savings",
"timeout": 8000
}
]
}
],
"UserPromptSubmit": [
{
"hooks": [
{
"type": "command",
"command": "node \"${CLAUDE_PROJECT_DIR:-.}/.claude/helpers/graft-hooks.cjs\" prompt",
"timeout": 15000
}
]
}
],
"SessionStart": [
{
"hooks": [
{
"type": "command",
"command": "node \"${CLAUDE_PROJECT_DIR:-.}/.claude/helpers/graft-hooks.cjs\" session-start",
"timeout": 8000
}
]
}
],
"Stop": [
{
"hooks": [
{
"type": "command",
"command": "node \"${CLAUDE_PROJECT_DIR:-.}/.claude/helpers/graft-hooks.cjs\" stop",
"timeout": 8000
}
]
}
]
},
"footerLinksRegexes": ["graft/[\\w./-]+\\.md"],
"permissions": {
"allow": ["Bash(graft:*)", "Bash(npx graft:*)", "Bash(graft-dev:*)", "Bash(node dist/cli.js:*)"]
}
}
@@ -0,0 +1,43 @@
---
name: ghbot-production-hardening
description: Production close-out workflow for ghbot: spec, audit, fix P0/P1 guards, gates, webhook HTTP smoke, independent review, docs.
metadata:
last_verified: "2026-08-23"
repo_baseline: "v1.1.0-hardening"
---
# ghbot production hardening skill
## When to use
Closing a production iteration of this GitHub review bot. Not for adding unrelated SaaS features.
## Do not use
- Changing AUTO_MERGE default
- Reusing old review cache as a new-head approval
- Running paid LLM E2E without budget
- Pushing to remotes without write permission
## Inputs
Current repo, CLAUDE.md red lines, `.specify/memory/constitution.md`.
## Steps
1. Read constitution, CLAUDE.md, workflow_status.md, last verification record.
2. Rebuild facts: git status, typecheck, test.
3. Audit contract/security/error/docs before coding.
4. Fix P0 then P1 with tests. Skip 1700-line processor extraction unless an event-loop harness exists.
5. Gates: typecheck, lint, format:check, test, build, npm audit --omit=dev.
6. Webhook HTTP smoke on a spare port: /healthz, HMAC 202, bad sig 401, duplicate, /metrics.
7. Independent critic. Repair only confirmed Blocking/Required.
8. Sync README/.env.example/workflows. Write HTML report under docs/reports/.
## Stop
Missing credentials, origin 403, paid API, production deploy, no progress after two review loops.
## Verify
Never claim LLM review E2E or origin push without command evidence.
+1
View File
@@ -0,0 +1 @@
../../.agents/skills/nodejs-backend-patterns
+1
View File
@@ -0,0 +1 @@
../../.agents/skills/nodejs-best-practices
+1
View File
@@ -0,0 +1 @@
../../.agents/skills/typescript-advanced-types
+1
View File
@@ -0,0 +1 @@
../../.agents/skills/zod
+1
View File
@@ -0,0 +1 @@
../../.agents/skills/nodejs-backend-patterns
+1
View File
@@ -0,0 +1 @@
../../.agents/skills/nodejs-best-practices
+1
View File
@@ -0,0 +1 @@
../../.agents/skills/typescript-advanced-types
+1
View File
@@ -0,0 +1 @@
../../.agents/skills/zod
+1
View File
@@ -0,0 +1 @@
../../.agents/skills/nodejs-backend-patterns
+1
View File
@@ -0,0 +1 @@
../../.agents/skills/nodejs-best-practices
+1
View File
@@ -0,0 +1 @@
../../.agents/skills/typescript-advanced-types
+1
View File
@@ -0,0 +1 @@
../../.agents/skills/zod
+16
View File
@@ -0,0 +1,16 @@
# CodeGraph data files
# These are local to each machine and should not be committed
# Database
*.db
*.db-wal
*.db-shm
# Cache
cache/
# Logs
*.log
# Hook markers
.dirty
+1
View File
@@ -0,0 +1 @@
../../.agents/skills/nodejs-backend-patterns
+1
View File
@@ -0,0 +1 @@
../../.agents/skills/nodejs-best-practices
+1
View File
@@ -0,0 +1 @@
../../.agents/skills/typescript-advanced-types
+1
View File
@@ -0,0 +1 @@
../../.agents/skills/zod
+8 -1
View File
@@ -1,4 +1,9 @@
PORT=3000
# Optional structured logging level (trace/debug/info/warn/error/fatal).
LOG_LEVEL=info
# Optional runtime root for writable scratch/cache storage. Empty means the process working directory.
GHBOT_RUNTIME_DIR=
# Optional in GitHub Actions because github.token is injected automatically.
# Still useful for local simulation and as a GitHub App fallback.
GITHUB_TOKEN=ghp_your_token_here
@@ -30,6 +35,9 @@ GOOSE_THINKING_EFFORT=high
# Optional: the pinned goose CLI version, shown in the runtime environment block.
# GOOSE_VERSION=v1.46.0
# Deprecated fallback aliases still accepted by config and workflows:
# OPENCODE_API_KEY, OPENCODE_BASE_URL, OPENCODE_MODEL, OPENCODE_REASONING_EFFORT
# allow | require_approval | reject. Ordinary review notes pass by default.
REVIEW_POLICY=allow
# normal | strict. Only strict enables the thorough review prompt.
@@ -64,4 +72,3 @@ CONFLICT_TEST_COMMAND=
MERGE_METHOD=squash
REQUIRE_CHECKS=true
MAX_PATCH_CHARS=120000
LOG_LEVEL=info
+26
View File
@@ -0,0 +1,26 @@
name: CI
on:
push:
branches:
- main
pull_request:
permissions:
contents: read
jobs:
verify:
name: typecheck-lint-test
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- uses: actions/setup-node@v4
with:
node-version: 24
cache: npm
- run: npm ci
- run: npm run typecheck
- run: npm run lint
- run: npm run format:check
- run: node --import tsx --experimental-test-coverage --test test/**/*.test.ts
+8 -8
View File
@@ -158,6 +158,10 @@ on:
required: false
type: string
default: "120000"
runtime_directory:
required: false
type: string
default: ""
log_level:
required: false
type: string
@@ -177,12 +181,6 @@ on:
required: false
GH_APP_INSTALLATION_ID:
required: false
GITHUB_APP_ID:
required: false
GITHUB_APP_PRIVATE_KEY:
required: false
GITHUB_APP_INSTALLATION_ID:
required: false
R2_ACCESS_KEY_ID:
required: false
R2_SECRET_ACCESS_KEY:
@@ -224,7 +222,7 @@ jobs:
GOOSE_BIN_DIR: ${{ runner.temp }}/goose/bin
CONFIGURE: "false"
run: |
curl -fsSL https://github.com/aaif-goose/goose/releases/download/stable/download_cli.sh | bash
curl -fsSL "https://github.com/aaif-goose/goose/releases/download/${GOOSE_VERSION}/download_cli.sh" | bash
echo "${GOOSE_BIN_DIR}" >> "${GITHUB_PATH}"
- run: npm ci
working-directory: ghbot-runtime
@@ -265,6 +263,7 @@ jobs:
MERGE_METHOD: ${{ inputs.merge_method }}
REQUIRE_CHECKS: ${{ inputs.require_checks }}
MAX_PATCH_CHARS: ${{ inputs.max_patch_chars }}
GHBOT_RUNTIME_DIR: ${{ inputs.runtime_directory }}
LOG_LEVEL: ${{ inputs.log_level }}
GHBOT_EVENT_NAME: ${{ inputs.event_name }}
GHBOT_EVENT_ACTION: ${{ inputs.event_action }}
@@ -300,7 +299,7 @@ jobs:
GOOSE_BIN_DIR: ${{ runner.temp }}/goose/bin
CONFIGURE: "false"
run: |
curl -fsSL https://github.com/aaif-goose/goose/releases/download/stable/download_cli.sh | bash
curl -fsSL "https://github.com/aaif-goose/goose/releases/download/${GOOSE_VERSION}/download_cli.sh" | bash
echo "${GOOSE_BIN_DIR}" >> "${GITHUB_PATH}"
- run: npm ci
working-directory: ghbot-runtime
@@ -341,6 +340,7 @@ jobs:
MERGE_METHOD: ${{ inputs.merge_method }}
REQUIRE_CHECKS: ${{ inputs.require_checks }}
MAX_PATCH_CHARS: ${{ inputs.max_patch_chars }}
GHBOT_RUNTIME_DIR: ${{ inputs.runtime_directory }}
LOG_LEVEL: ${{ inputs.log_level }}
GHBOT_EVENT_NAME: schedule
GHBOT_EVENT_ACTION: schedule
+6 -4
View File
@@ -59,7 +59,7 @@ jobs:
reviewer_login: ${{ github.event.review.user.login || '' }}
review_state: ${{ github.event.review.state || '' }}
review_commit_id: ${{ github.event.review.commit_id || '' }}
bot_name: github-actions[bot]
bot_name: ${{ vars.BOT_NAME || 'github-actions[bot]' }}
goose_base_url: ${{ vars.GOOSE_BASE_URL || vars.OPENCODE_BASE_URL || 'https://api.openai.com/v1' }}
goose_model: ${{ vars.GOOSE_MODEL || vars.OPENCODE_MODEL || 'gpt-5.4' }}
goose_thinking_effort: ${{ vars.GOOSE_THINKING_EFFORT || vars.OPENCODE_REASONING_EFFORT || 'high' }}
@@ -86,7 +86,8 @@ jobs:
merge_method: ${{ vars.MERGE_METHOD || 'squash' }}
require_checks: ${{ vars.REQUIRE_CHECKS || 'true' }}
max_patch_chars: ${{ vars.MAX_PATCH_CHARS || '120000' }}
log_level: info
runtime_directory: ${{ vars.GHBOT_RUNTIME_DIR || '' }}
log_level: ${{ vars.LOG_LEVEL || 'info' }}
review-schedule-recheck:
if: github.event_name == 'schedule'
uses: ./.github/workflows/review-reusable.yml
@@ -105,7 +106,7 @@ jobs:
repository_name: ${{ github.event.repository.name }}
repository_id: ${{ github.repository_id }}
pull_number: "1"
bot_name: github-actions[bot]
bot_name: ${{ vars.BOT_NAME || 'github-actions[bot]' }}
goose_base_url: ${{ vars.GOOSE_BASE_URL || vars.OPENCODE_BASE_URL || 'https://api.openai.com/v1' }}
goose_model: ${{ vars.GOOSE_MODEL || vars.OPENCODE_MODEL || 'gpt-5.4' }}
goose_thinking_effort: ${{ vars.GOOSE_THINKING_EFFORT || vars.OPENCODE_REASONING_EFFORT || 'high' }}
@@ -132,5 +133,6 @@ jobs:
merge_method: ${{ vars.MERGE_METHOD || 'squash' }}
require_checks: ${{ vars.REQUIRE_CHECKS || 'true' }}
max_patch_chars: ${{ vars.MAX_PATCH_CHARS || '120000' }}
log_level: info
runtime_directory: ${{ vars.GHBOT_RUNTIME_DIR || '' }}
log_level: ${{ vars.LOG_LEVEL || 'info' }}
run_schedule_recheck: "true"
+3
View File
@@ -11,3 +11,6 @@ pnpm-debug.log*
.ghbot-cache/
.ghbot-knowledge/
.playwright-cli/
# graft's local graph cache — regenerable, not committed (run `graft build`).
graft/
+5
View File
@@ -0,0 +1,5 @@
# graft's cards are gitignored but should stay greppable: ripgrep reads
# .ignore before .gitignore, so this re-admits the tree to search only.
!graft/
graft/.cache/
graft/.graph/
+1
View File
@@ -0,0 +1 @@
../../.agents/skills/nodejs-backend-patterns
+1
View File
@@ -0,0 +1 @@
../../.agents/skills/nodejs-best-practices
+1
View File
@@ -0,0 +1 @@
../../.agents/skills/typescript-advanced-types
+1
View File
@@ -0,0 +1 @@
../../.agents/skills/zod
+1
View File
@@ -0,0 +1 @@
../../.agents/skills/nodejs-backend-patterns
+1
View File
@@ -0,0 +1 @@
../../.agents/skills/nodejs-best-practices
+1
View File
@@ -0,0 +1 @@
../../.agents/skills/typescript-advanced-types
+1
View File
@@ -0,0 +1 @@
../../.agents/skills/zod
+8
View File
@@ -0,0 +1,8 @@
{
"mcpServers": {
"graft": {
"command": "npx",
"args": ["-y", "@nanonets/graft", "mcp"]
}
}
}
+9
View File
@@ -0,0 +1,9 @@
{
"semi": true,
"singleQuote": false,
"tabWidth": 2,
"trailingComma": "none",
"printWidth": 100,
"arrowParens": "always",
"endOfLine": "lf"
}
+53
View File
@@ -0,0 +1,53 @@
# ghbot 项目宪法(Constitution)
> 版本: 1.0.0 · 生效日期: 2026-08-23
> 本文件是所有开发决策的最高约束。任何实现与本文冲突时,以本文为准。
## 核心价值观
1. **生产安全高于一切**:本机器人运行在生产仓库上,能关闭 PR、推送 commit、合并 PR。
任何改动若可能放大误操作半径,默认拒绝;必须改时需要显式护栏 + 测试证明。
2. **凭据零扩散**:GitHub token / App 私钥 / R2 密钥 / goose API key 绝不进入容器、快照、
git 子进程环境或日志。违反此条 = 阻塞级缺陷。
3. **PR 代码不可信**:自动审查/分类只用 API diff;PR 内容永远视为 untrusted data,
prompt 注入防护是功能需求而非可选项。
4. **诚实交付**:未验证的东西不宣称完成。测试失败必须如实报告,禁止为绿而削弱断言。
## 技术原则
### 架构
- 单一职责:一个模块只回答一个问题(谁调用它、它调用谁、失败时谁兜底)。
- 共享清单单一来源:安全排除/脱敏/路径策略只允许一份实现(src/security/, src/runtimePaths.ts)。
- 行为不变的重构必须与功能变更分开提交,且全量测试保护。
### 质量门禁(提交前全部通过)
1. `npm run typecheck` — 0 错误
2. `npm run lint` — 0 error
3. `npm run format:check` — 通过
4. `npm test` — 全绿;新增行为必须有新测试(TDD:先红后绿)
5. `npm run build` — dist 可被 node 加载
6. `npm audit --omit=dev` — 无 high 以上
### 安全红线(继承 CLAUDE.md,不可协商)
- AUTO_MERGE=false 默认值不可改
- 恢复缓存审查结果必须重新完整审查,不得直接复用旧决策
- fork 推送必须 SHA 钉住 --force-with-lease
- 知识缓存入库前拒绝凭据内容
## 决策框架
技术选型按序评估:
1. 是否触碰安全红线?(触碰 → 拒绝)
2. 是否可用现有轮子解决?(可以 → 不写新代码)
3. 失败时的降级行为是否清晰?(不清晰 → 先设计降级)
4. 是否可测试?(不可测 → 重构到可测)
## 变更治理
- 每个原子提交对应一个可独立回退的变更单元
- 公共接口(config schema、workflow inputs、评论文案契约)变更必须同步双语 README
- 文档与代码冲突时以代码为准,并在同一提交内修正文档
@@ -0,0 +1,29 @@
# Implementation Plan: 001-production-hardening
## Current architecture
ghbot is a GitHub Actions + optional webhook Node service. Review, triage, conflict repair, and @bot chat are orchestrated from `src/actions/runReview.ts`. Config is a single zod schema in `src/config.ts`. Persistence is optional R2 plus local scratch directories.
## Impacted modules
- `src/review/processor.ts` — merge SHA pinning, stale-head discard, approval lookup errors
- `src/review/conflictResolver.ts` — per-PR lock, git timeouts, worktree reset
- `src/ai/apiProxy.ts` / `src/ai/gooseCli.ts` — proxy/process timeouts and bounded output
- `src/webhook/server.ts` — body deadline, request catch, metrics
- `src/config.ts` / workflows / `.env.example` — GHBOT_RUNTIME_DIR, webhook/R2 cross-checks
- docs — webhook secret, docker run, goose aliases
## Implementation strategy
Fix production failure modes first. Keep AUTO_MERGE default false. Prefer additive guards over architecture rewrites. Do not extract the 1700-line processor router in this pass because there is no isolated event-loop test harness; that refactor is deferred with an explicit risk note.
## Verification
- npm run typecheck / lint / format:check / test
- production-build webhook HTTP smoke (healthz, HMAC, duplicate, metrics)
- npm audit --omit=dev against registry.npmjs.org
- independent six-dimension review after gates
## Rollback
Revert the production-hardening commit on the fork. Defaults remain conservative (AUTO_MERGE=false, WEBHOOK_ENABLED=false).
@@ -0,0 +1,71 @@
# Feature Specification: 001-production-hardening(生产硬化总审计)
## 问题陈述
ghbot 已在生产仓库运行(自动审查/分类/合并/冲突修复)。用户要求以"终局闭环总审计"标准,
对全部功能做查漏补缺:功能完整性、前后端衔接(此处为 workflow↔代码↔GitHub API 契约)、
调用体验、部署体验、文档一致性,并补齐指南中剩余未落地项。
## 用户故事
### US-1: 部署者首次接入
作为部署者,我希望按 README 从零配置后一次跑通,无需口口相传的隐性前提。
**验收**:
- [ ] .env.example 覆盖全部 config schema 字段且默认值一致
- [ ] README 步骤与实际命令一一对应
- [ ] 新增配置项有文档说明
### US-2: 事件全链路
作为仓库维护者,任何支持的事件触发后都有确定行为与反馈。
**验收**:
- [ ] workflow 触发的事件类型 ⊆ runReview.ts 处理集合(无静默吞事件)
- [ ] issue_comment 三链路互不阻断
- [ ] 每条失败路径都有可见反馈或日志
### US-3: 审查结果可信
作为 PR 作者,审查评论必须准确、可定位、不误导。
**验收**:
- [ ] finding 的 path/line 经净化后才提交
- [ ] 无法 inline 的 findings 折叠展示不丢失
- [ ] 状态横幅与 disposition 一致
### US-4: webhook 服务可运维
作为运维者,服务健康可探活、指标可观测、异常可恢复。
**验收**:
- [ ] /healthz 与 /metrics 真实可用
- [ ] 队列满/签名错/超大包均有明确响应码
- [ ] 失败投递进程内重试后仍可被 GitHub 重投
### US-5: 剩余指南项落地
指南 7.1 / 6.4 / 8.5 / 4.4 不再是"候选",全部实现或有明确的不适用结论。
**验收**:
- [ ] 每项有代码证据或书面不适用理由
- [ ] 全部门禁通过
## 非功能性需求
- 兼容性:Node >=22 <26;Windows/Linux 双平台测试通过
- 可观测性:关键路径日志含 owner/repo/pullNumber/eventName 四元组
- 安全性:宪法红线零违反
- 可维护性:无重复实现的安全清单;文件 <800 行
## Out of Scope
- 真实付费 LLM 调用的 E2E(预算 0)
- 前端 UI(本项目无前端)
## 成功指标
- 门禁六项全绿
- E2E:webhook 生产构建真实 HTTP 验收通过
- 需求追踪矩阵无"未闭环"项
@@ -0,0 +1,25 @@
# Implementation Tasks: 001-production-hardening
## Phase 1: Spec and audit
- [x] 1.1 Constitution + spec
- [x] 1.2 Parallel contract/security/error/docs audit
## Phase 2: Production guards
- [x] 2.1 Merge SHA recheck + pulls.merge sha
- [x] 2.2 Conflict lock + git command timeout + dirty worktree reset
- [x] 2.3 Webhook body timeout/size and request catch
- [x] 2.4 API proxy abort/timeout/body cap
- [x] 2.5 Goose process output cap and cleanup timeouts
- [x] 2.6 Config cross-field validation and GHBOT_RUNTIME_DIR contract
- [x] 2.7 Issue comment handler isolation with AggregateError
- [x] 2.8 Approval permission lookup no longer swallows retryable errors
- [x] 2.9 Event logger child bindings
## Phase 3: Verify and handoff
- [ ] 3.1 Local gates (typecheck/lint/format/test)
- [ ] 3.2 Webhook HTTP E2E
- [ ] 3.3 Independent review
- [ ] 3.4 HTML change report + skill + docs
+42
View File
@@ -0,0 +1,42 @@
<!-- graft:start -->
## Graft — repo context graph
This repo is indexed in `graft/`: small linked markdown nodes that explain each
system and carry exact file:line spans, kept in sync with the code through git.
For ANY task here — understanding how something works, finding where code lives,
or scoping a change — get context from the graph before grepping or opening
source files. Re-ask freely (it's cheap) and reuse literal identifiers you
already have (symbol, error string, file name) as the query. New to this repo?
Run `graft map` first — a token-budgeted orientation (dir clusters, hubs,
hotspots), no LLM, no key.
- Run `graft ask "<your question>" --source` → ranked nodes with the relevant
code spans inlined (each hit's ≤8-line crux by default; `--full` for whole
definitions when the crux isn't enough). Match the tool to the task shape:
for understanding or editing, the top node IS the answer — cite its
`covers:` file:line spans and edit straight from `--source`. For
exhaustive tasks ("every occurrence / every caller of this pattern"), ranked
results are top-N, not complete — run `graft grep "<literal>"` instead
(exhaustive over indexed files, grouped by enclosing symbol), falling back
to raw `grep -rn` only for unindexed files.
- `graft skeleton <file>` → every definition's signature + span, ~10× cheaper
than reading the file; use it to skim an API surface.
- `graft callers <symbol>` gives precomputed, exact edges — who calls this.
Add `--direction out` for what it calls, or `--depth N` to walk
transitively for the full blast radius. For structural questions, skip
ranking and use this directly.
- Or browse: `graft/INDEX.md` lists every node; follow the links.
- Monorepos and folders of multiple repos rank fairly across sub-projects —
hits carry `[scope/]` labels naming which one they're from. Narrow with
`graft ask "<task>" --in <scope>/` once you know where you're working.
If a returned span is truncated ("+N more lines"), open the file at that exact
range before finalizing. Only open source files when a node genuinely lacks a
needed detail, and then at the exact file:line the node points to — never
re-read whole files.
After big code changes, refresh the graph with `graft build` (deterministic,
no API key, $0).
<!-- graft:end -->
+79
View File
@@ -0,0 +1,79 @@
# CLAUDE.md
本文件为 Claude Code 在此仓库工作时提供指导。
## 项目概述
ghbot 是一个基于 GitHub Actions 的机器人,使用 goose CLI(OpenAI 兼容 chat API)完成:
- **PR 审查**:goose 返回固定四段输出(`review` / `change` / `comment` / `result`),只有 `change` 是强制修改;合并策略由 `REVIEW_POLICY` 控制,默认 `allow`
- **Issue/PR 分类**:打标签、两阶段重复检测(PR 先粗筛后详查)
- **PR 评论对话**:`@bot` 提及触发工具型 Agent,在一次性 Docker 容器中分析脱敏快照
- **冲突修复**:`AUTO_RESOLVE_CONFLICTS` 或 `/conflict` 命令,经 goose 确认 `safeToCommit=true` 后才推送
- **可选 webhook 模式**:GitHub App 长驻服务(只读聊天),默认关闭
## 常用命令
```bash
npm install # 安装依赖
npm run typecheck # tsc --noEmit,提交前必须通过
npm run build # 编译到 dist/
npm test # node:test + tsx,运行全部测试
npm run webhook # 运行编译后的 webhook 服务
npm run dev:webhook # tsx 直接运行 webhook 源码
```
无独立 linter/formatter——`typecheck` 和 `test` 是唯一的门禁。
## 技术栈与约定
- **TypeScript ESM**(`"type": "module"`),Node `>=22 <26`,严格模式编译
- **配置**:所有环境变量集中在 `src/config.ts`,用 zod schema 定义并校验;新增配置项必须加进 schema 并补默认值
- **测试**:Node 内置 test runner(`node:test`),测试文件放 `test/*.test.ts`;新行为必须带测试,优先 AAA 结构和描述性命名
- **错误处理**:边界显式处理,不静默吞错;对外输入一律先校验
- **不可变风格**:优先返回新对象而非就地修改
- **日志**:统一用 pino(`src/logger.ts`),禁止 `console.log`
## 架构地图
| 目录 | 职责 |
| ----------------------------- | ------------------------------------------------------------------- |
| `src/actions/runReview.ts` | Actions 入口:分发 review/triage/chat/conflict 流程 |
| `src/config.ts` | 全部环境变量的 zod schema |
| `src/github/` | Octokit 客户端、checks、diff、命令反馈、bot 身份识别 |
| `src/review/` | 审查流水线:prompt、策略(policy)、缓存、冲突解决器 |
| `src/chat/` | 工具型 @bot 对话(容器隔离) |
| `src/triage/` | Issue/PR 分类与重复检测 |
| `src/repository/knowledge.ts` | R2 中的仓库知识缓存读写与校验 |
| `src/storage/` | Cloudflare R2 缓存存储层 |
| `src/ai/gooseCli.ts` | goose CLI 封装(chat 模式);`apiProxy.ts` 为容器提供一次性凭据代理 |
| `src/webhook/` | 可选 GitHub App webhook 服务与队列 |
| `.github/workflows/` | `review.yml`(调用方包装)与 `review-reusable.yml`(可复用工作流) |
## 代码检索(graft)
本仓库由 graft 索引,详见 [AGENTS.md](AGENTS.md)。任何理解/定位任务先跑
`graft ask "<问题>" --source` 或 `graft grep "<字面量>"`,不要直接全文件读取;
大改后运行 `graft build` 刷新图。
## 安全红线(CRITICAL)
此仓库处理不受信任的 PR 内容和多种凭据,以下规则不可妥协:
1. **凭据隔离**:GitHub token、App 私钥、R2 密钥、真实 goose API key 绝不进入 goose 容器、PR 快照或 git 子进程环境;容器只拿一次性代理令牌(`src/ai/apiProxy.ts`)
2. **PR 代码执行边界**:自动审查/分类只用 API diff,绝不 checkout 执行 PR 代码;仅冲突修复的验证环节在脱敏一次性容器内运行
3. **快照脱敏**:进入 Agent 工作区的快照必须排除 git 元数据、agent 配置文件(goose/OpenCode 等)、`.env`、符号链接
4. **auto-merge 保持 opt-in**:`AUTO_MERGE=false` 默认值不可改动;恢复缓存审查结果时必须重新完整审查,不得直接复用旧决策
5. **推送防护**:fork 推送必须用 SHA 钉住的 `--force-with-lease`;提交前需 goose 确认 `safeToCommit=true` 且远端 head 未变
6. **知识缓存**:入库前拒绝凭据/私钥内容,限制 32 KiB;Agent 无任何 GitHub/R2 凭据
7. 不在公开 issue 讨论安全漏洞(见 CONTRIBUTING.md)
## Git 工作流
- 提交格式:`<type>: <description>`,类型为 feat / fix / refactor / docs / test / chore / perf / ci(参考现有历史)
- 改动保持聚焦;修改审查或合并逻辑时必须在 PR 中说明行为变化
- 提交前:`npm run typecheck` + `npm test` 全部通过
## 语言说明
代码、注释、commit message 用英文;README 有中英双语版本,改动用户可见行为时同步更新两个 README。
+3 -3
View File
@@ -9,7 +9,7 @@ ENV GOOSE_VERSION=${GOOSE_VERSION} \
RUN apt-get update \
&& apt-get install --no-install-recommends -y bash ca-certificates curl \
&& rm -rf /var/lib/apt/lists/* \
&& curl -fsSL https://github.com/aaif-goose/goose/releases/download/stable/download_cli.sh | bash
&& curl -fsSL "https://github.com/aaif-goose/goose/releases/download/${GOOSE_VERSION}/download_cli.sh" | bash
WORKDIR /app
COPY package.json package-lock.json ./
@@ -18,7 +18,7 @@ COPY tsconfig.json ./
COPY src ./src
RUN npm run build && npm prune --omit=dev
# Action mode does not use this image. Webhook mode is explicitly opt-in.
ENV WEBHOOK_ENABLED=false
# This image is the webhook service. Action mode does not use it.
ENV WEBHOOK_ENABLED=true
EXPOSE 3000
CMD ["node", "dist/src/webhook/server.js"]
+32 -4
View File
@@ -31,6 +31,7 @@ goose 的审核结果固定包含四个顶层字段:
- `REVIEW_BRANCHES`:需要审核的 PR 目标分支 glob,以逗号分隔;留空表示全部分支。例如 `main,develop,release/**`。
- `REVIEW_STRICTNESS`:默认 `normal`;设为 `strict` 才会全面严格检查。普通模式不吹毛求疵,只报告明确的运行、构建、测试、安全、数据丢失或重要用户体验回归。
- `MAX_PATCH_CHARS`:单次发送给模型的最大 patch 字符数,默认 `120000`。
- `GHBOT_RUNTIME_DIR`:可选的可写 runtime 根目录,用于 `.ghbot-tmp`、`.ghbot-cache` 和仓库知识文件;留空时使用进程工作目录。
`REVIEW_BRANCHES` 匹配 PR 的 base branch。`*` 不跨越 `/`,`**` 可以跨越 `/`。workflow 文件需要存在于仓库默认分支,但这不表示只能审核指向默认分支的 PR;例如 workflow 位于 `main` 时,仍可审核目标为 `develop` 或 `release/1.x` 的 PR。
@@ -128,7 +129,7 @@ Action 模式仍然是默认模式,不需要 Webhook 服务也可以完整使
只有在同时运行长期 Node 进程或本仓库提供的 `Dockerfile.webhook` 时才启用 Webhook。它接收 GitHub App 的 webhook 事件,处理 Issue/PR conversation comment、review comment 和提交的 review 中对 `@bot` 的提问。适合组织只安装一次 App、由多个仓库共用一个服务端点的场景。App 必须安装到每个目标仓库,或者组织安装时选择包含这些仓库;未被该 installation 授权的仓库无法访问。
GitHub App 的 Webhook URL 配置为 `https://你的域名/webhooks/github`,`WEBHOOK_SECRET` 使用同一个密钥,并订阅 `Issue comments`、`Pull request review comments`、`Pull request reviews`,自动分类还需要 `Issues` 和 `Pull requests` 事件。App 需要 `Metadata: read`、`Issues: read and write`、`Pull requests: read and write`。服务会使用每个 payload 中的 `installation.id` 换取对应的短期 installation token,不能用一个固定 installation ID 代替所有仓库。
GitHub App 的 Webhook URL 配置为 `https://你的域名/webhooks/github`,`WEBHOOK_SECRET` 必须使用独立的长随机 HMAC 密钥,并在 GitHub App Webhook 设置和服务环境中配置相同密钥;不要把公开 URL 当作密钥。并订阅 `Issue comments`、`Pull request review comments`、`Pull request reviews`;自动分类还需要 `Issues` 和 `Pull requests` 事件。App 需要 `Metadata: read`、`Issues: read and write`、`Pull requests: read and write`。服务会使用每个 payload 中的 `installation.id` 换取对应的短期 installation token,不能用一个固定 installation ID 代替所有仓库。
服务环境变量如下:
@@ -138,7 +139,20 @@ GitHub App 的 Webhook URL 配置为 `https://你的域名/webhooks/github`,`W
- `WEBHOOK_CHAT_PERMISSION`:`read`(默认)、`write` 或 `anyone`。对于组织拥有的仓库,`read` 还会允许组织成员直接提问,不要求把每个成员单独添加为仓库协作者;个人仓库和组织外用户仍走仓库协作者权限检查。`write` 只允许 write、maintain、admin;`anyone` 跳过评论者权限检查,但仍只能访问 App 已安装的仓库。建议给 App 配置组织级 `Members: read`,这样才能验证私有组织成员身份。
- `WEBHOOK_QUEUE_CONCURRENCY` 和 `WEBHOOK_QUEUE_LIMIT` 用于限制后台处理量和内存。
可以用 `npm run build && npm run webhook` 启动,也可以构建 `docker build -f Dockerfile.webhook -t ghbot-webhook .` 后运行,并传入 App 凭证、Webhook 密钥和 Goose 配置。`GET /healthz` 可作为健康检查。服务会先返回 `202` 再后台调用 Goose;请求使用 HMAC 验签,按 `X-GitHub-Delivery` 去重,后台失败的 delivery 仍可被 GitHub 重试。
可以用 `npm run build && npm run webhook` 启动,也可以构建并运行 Docker:
```bash
docker build -f Dockerfile.webhook -t ghbot-webhook .
docker run --rm -p 3000:3000 \\
-e WEBHOOK_ENABLED=true \\
-e WEBHOOK_SECRET='替换为长随机密钥' \\
-e GH_APP_ID='123456' \\
-e GH_APP_PRIVATE_KEY="$GH_APP_PRIVATE_KEY" \\
-e GOOSE_API_KEY="$GOOSE_API_KEY" \\
ghbot-webhook
```
TLS 应由反向代理或托管 ingress 终止;Node 服务监听 `PORT`(默认 `3000`)。`GET /healthz` 可作为健康检查,`GET /metrics` 提供 Prometheus 文本指标。服务会先返回 `202` 再后台调用 Goose,因为模型耗时可能超过 GitHub webhook 超时。后台失败只会在进程内重试一次;进程在 `202` 之后崩溃时 GitHub **不会**重投。需要可靠执行 `/recheck`、`/conflict` 和带工具的对话时请用 Action 模式。Webhook 对话是尽力而为。请求使用 HMAC 验签,并按 `X-GitHub-Delivery` 去重。
Webhook 对话刻意保持只读:Goose 只能收到仓库元数据、README、Issue/PR 内容、有限 diff、近期讨论,以及配置 R2 后的仓库知识缓存,不会获得仓库工具或凭证。因此它不能改代码、执行命令、push,也不能执行 `/recheck` 或 `/conflict`——收到精确命令时会回复引导信息,指向 Action 模式。对安装了 App 的仓库,webhook 服务也会在 `opened`、`edited`、`reopened` 事件上运行与 Action 模式相同的 Issue/PR 自动分类(打标签与查重);设置 `WEBHOOK_TRIAGE_ENABLED=false` 可在 Webhook 模式关闭该功能。Webhook 模式的所有本地写入都保持在当前工作目录内:按仓库隔离的知识缓存位于 `.ghbot-tmp/webhook-knowledge/<仓库 ID>/`。回复语言跟随最新一条评论,也不会暴露 provider 或 GitHub 密钥。不设置 `WEBHOOK_ENABLED` 就仍是普通的 Action-only 部署。
@@ -154,9 +168,10 @@ Webhook 对话刻意保持只读:Goose 只能收到仓库元数据、README、
## goose 配置
必须添加 Actions Secret:
必须添加 Actions Secret(运行审核或 Goose 操作时至少配置一个):
- `GOOSE_API_KEY`
- `GOOSE_API_KEY`(首选)
- `OPENCODE_API_KEY`(迁移兼容别名)
相关 Repository Variables:
@@ -242,6 +257,19 @@ secrets:
只有当 GitHub 报告当前开放 PR 存在冲突且 head 可写时才会尝试修复。外部 fork 必须开启 **Allow edits from maintainers**,并通过绑定已审核 SHA 的 force-with-lease 安全更新贡献者分支。它会运行与自动修复相同的可信验证命令和第二次 goose 最终确认;两者成功且远端 head 未变化时才会创建 commit 并 push。
## 开发门禁
所有改动在推送前必须通过本地门禁;CI([.github/workflows/ci.yml](.github/workflows/ci.yml))在 GitHub 上执行相同检查:
```bash
npm run typecheck # TypeScript 严格检查
npm run lint # ESLint(flat config)
npm run format:check # Prettier 格式检查
npm test # node:test 测试套件
```
可选的 webhook 服务提供 `GET /healthz` 与 `GET /metrics`(Prometheus 文本格式)用于探活与监控。生产硬化变更说明与测验见 [docs/reports/ghbot-production-hardening.html](docs/reports/ghbot-production-hardening.html)。
## 本地开发
需要 Node.js 22 至 25。PR comment Agent 的全工具集成测试还需要可用的 Docker daemon。
+32 -4
View File
@@ -29,6 +29,7 @@ Use repository Actions variables to customize a caller repository:
- `REVIEW_BRANCHES`: comma-separated base-branch globs. Empty reviews all target branches. Example: `main,develop,release/**`.
- `REVIEW_STRICTNESS`: `normal` by default, or `strict` for a thorough repository-policy review. Normal mode avoids nitpicks and reports only clear runtime, build, test, security, data-loss, or important user-facing regressions.
- `MAX_PATCH_CHARS`: maximum total patch text sent for review; default `120000`.
- `GHBOT_RUNTIME_DIR`: optional writable runtime root for `.ghbot-tmp`, `.ghbot-cache`, and repository knowledge files; defaults to the process working directory.
`REVIEW_BRANCHES` matches the pull request's target (base) branch. `*` does not cross `/`; `**` does. The workflow file must be present on the repository's default branch for `pull_request_target`, but that does not limit reviews to PRs targeting the default branch. A workflow installed on `main` can review PRs targeting `develop` or release branches. The bot fetches each PR and its diff by PR number and never executes code from the PR head.
@@ -114,7 +115,7 @@ Action mode remains the default and is complete without a webhook service. `WEBH
Enable webhook mode only when you also run a long-lived Node process or the included `Dockerfile.webhook`. It receives GitHub App webhook events and answers `@bot` mentions in Issue/PR conversation comments, review comments, and submitted reviews. It is useful when the App is installed once for an organization and you want those repositories to share one endpoint. The App must be installed on each repository (or the organization selection must include it); a webhook cannot access repositories where the installation has no access.
Configure the GitHub App webhook URL as `https://your-host/webhooks/github`, use the same value for `WEBHOOK_SECRET`, and subscribe to `Issue comments`, `Pull request review comments`, and `Pull request reviews`, plus `Issues` and `Pull requests` for automatic triage. The App needs `Metadata: read`, `Issues: read and write`, and `Pull requests: read and write`. The endpoint exchanges each payload's `installation.id` for the correct short-lived installation token, so one fixed installation ID must not be used for all repositories.
Configure the GitHub App webhook URL as `https://your-host/webhooks/github`, and configure `WEBHOOK_SECRET` as a separate long random HMAC secret in both GitHub App webhook settings and the service environment. Never reuse the public URL as the secret. Subscribe to `Issue comments`, `Pull request review comments`, and `Pull request reviews`, plus `Issues` and `Pull requests` for automatic triage. The App needs `Metadata: read`, `Issues: read and write`, and `Pull requests: read and write`. The endpoint exchanges each payload's `installation.id` for the correct short-lived installation token, so one fixed installation ID must not be used for all repositories.
Set these service environment variables:
@@ -124,7 +125,20 @@ Set these service environment variables:
- `WEBHOOK_CHAT_PERMISSION`: `read` (default), `write`, or `anyone`. On organization-owned repositories, `read` also allows organization members without adding each member as a repository collaborator; personal repositories and non-members continue through the repository collaborator check. `write` allows write, maintain, or admin; `anyone` skips the commenter permission check but still only works in App-installed repositories. The App should have organization-level `Members: read` permission so private organization membership can be verified.
- `WEBHOOK_QUEUE_CONCURRENCY` and `WEBHOOK_QUEUE_LIMIT` bound background work and memory.
Start it with `npm run build && npm run webhook`, or build `docker build -f Dockerfile.webhook -t ghbot-webhook .` and run it with the App credentials, webhook secret, and Goose variables. `GET /healthz` is available for service probes. GitHub receives `202` before Goose runs; deliveries are HMAC-verified, deduplicated by `X-GitHub-Delivery`, and failed background deliveries remain retryable.
Start it with `npm run build && npm run webhook`, or build and run the Docker image:
```bash
docker build -f Dockerfile.webhook -t ghbot-webhook .
docker run --rm -p 3000:3000 \\
-e WEBHOOK_ENABLED=true \\
-e WEBHOOK_SECRET='replace-with-a-long-random-secret' \\
-e GH_APP_ID='123456' \\
-e GH_APP_PRIVATE_KEY="$GH_APP_PRIVATE_KEY" \\
-e GOOSE_API_KEY="$GOOSE_API_KEY" \\
ghbot-webhook
```
Keep TLS termination in a reverse proxy or managed ingress; the Node service listens on `PORT` (default `3000`). `GET /healthz` is available for service probes and `GET /metrics` exposes Prometheus text metrics. GitHub receives `202` before Goose runs because a review-quality model call can exceed GitHub's webhook timeout. Failed background work is retried in-process once; a process crash after `202` is **not** redelivered by GitHub. Use Action mode for durable `/recheck`, `/conflict`, and tool-enabled chat. Webhook chat is best-effort. Deliveries are HMAC-verified and deduplicated by `X-GitHub-Delivery`.
Webhook chat is deliberately read-only: Goose receives repository metadata, README, Issue/PR text, bounded diffs, recent discussion, and the host-curated repository knowledge cache when R2 is configured, but no repository tools or credentials. It cannot edit code, run commands, push commits, or execute `/recheck` and `/conflict`; an exact `/recheck` or `/conflict` command receives a guidance reply pointing to Action mode instead of silence. The webhook service also runs the same automatic issue and pull-request triage as Action mode on `opened`, `edited`, and `reopened` events for App-installed repositories; set `WEBHOOK_TRIAGE_ENABLED=false` to disable it there. All webhook-mode local writes stay inside the current working directory: the per-repository knowledge cache lives at `.ghbot-tmp/webhook-knowledge/<repository id>/`. Replies follow the language of the latest comment and include no provider or GitHub secrets. Leaving `WEBHOOK_ENABLED` unset preserves the normal Action-only deployment.
@@ -140,9 +154,10 @@ After applying the proposed files, ghbot verifies there are no unmerged paths an
## goose configuration
Required secret:
Required provider secret (one of these aliases must be supplied when a review or Goose operation runs):
- `GOOSE_API_KEY`
- `GOOSE_API_KEY` (preferred)
- `OPENCODE_API_KEY` (migration fallback alias)
Repository variables:
@@ -232,6 +247,19 @@ An eligible repository user can comment the exact command:
The bot attempts conflict repair only when GitHub reports the current open PR as conflicted and the head is writable. External forks require **Allow edits from maintainers**; their resolved head is pushed with a force lease pinned to the reviewed SHA. It runs the same configured validation and separate final goose confirmation used by automatic repair, then pushes only if both succeed and the head has not changed.
## Development gates
All changes must pass the local gates before push; CI ([.github/workflows/ci.yml](.github/workflows/ci.yml)) enforces the same checks on GitHub:
```bash
npm run typecheck # TypeScript strict check
npm run lint # ESLint (flat config)
npm run format:check # Prettier formatting
npm test # node:test suite
```
The optional webhook service exposes `GET /healthz` and `GET /metrics` (Prometheus text format) for probes and dashboards. The production-hardening change ledger and quiz live at [docs/reports/ghbot-production-hardening.html](docs/reports/ghbot-production-hardening.html).
## Local development
```bash
@@ -0,0 +1,395 @@
# ghbot Production Hardening > 终局审计变更说明与验收测验。对照当前仓库真实实现,不包装未验证项。
<title>ghbot Hardening Ledger</title>
<link
rel="stylesheet"
href="https://fonts.googleapis.com/css2?family=IBM+Plex+Mono:wght@400;600&family=IBM+Plex+Sans:ital,wght@0,400;0,500;0,600;1,400&family=Source+Serif+4:opsz,wght@8..60,600;8..60,700&display=swap"
/>
<style>
:root {
--paper: #f3f0ea;
--ink: #1b2430;
--muted: #4d5968;
--line: #d7d1c6;
--accent: #b4471c;
--ok: #215e46;
--warn: #8a5a12;
--bad: #8f2d2d;
--card: #fffdf8;
--code: #ece7dc;
}
@media (prefers-color-scheme: dark) {
:root:not([data-theme="light"]) {
--paper: #12171f;
--ink: #e8e4da;
--muted: #a8b0bb;
--line: #2b3440;
--accent: #e07a4c;
--ok: #7dbe9d;
--warn: #e0b05a;
--bad: #e07a7a;
--card: #1a212b;
--code: #0f141b;
}
}
:root[data-theme="dark"] {
--paper: #12171f;
--ink: #e8e4da;
--muted: #a8b0bb;
--line: #2b3440;
--accent: #e07a4c;
--ok: #7dbe9d;
--warn: #e0b05a;
--bad: #e07a7a;
--card: #1a212b;
--code: #0f141b;
}
* {
box-sizing: border-box;
}
html,
body {
margin: 0;
background: var(--paper);
color: var(--ink);
}
body {
font-family: "IBM Plex Sans", "Segoe UI", sans-serif;
line-height: 1.55;
}
.wrap {
max-width: 980px;
margin: 0 auto;
padding: 2.5rem 1.25rem 5rem;
}
h1,
h2,
h3 {
font-family: "Source Serif 4", Georgia, serif;
text-wrap: balance;
font-weight: 700;
}
h1 {
font-size: 2.1rem;
margin: 0 0 0.4rem;
}
h2 {
font-size: 1.35rem;
margin: 2.2rem 0 0.7rem;
border-top: 1px solid var(--line);
padding-top: 1.2rem;
}
p,
li {
color: var(--ink);
}
.lede {
color: var(--muted);
max-width: 62ch;
}
.grid {
display: grid;
grid-template-columns: repeat(auto-fit, minmax(180px, 1fr));
gap: 0.75rem;
margin: 1.2rem 0 1.6rem;
}
.stat {
background: var(--card);
border: 1px solid var(--line);
padding: 0.85rem 0.95rem;
}
.stat b {
display: block;
font-family: "IBM Plex Mono", monospace;
font-size: 1.05rem;
}
.stat span {
color: var(--muted);
font-size: 0.82rem;
}
table {
width: 100%;
border-collapse: collapse;
font-size: 0.92rem;
}
th,
td {
text-align: left;
padding: 0.45rem 0.4rem;
border-bottom: 1px solid var(--line);
vertical-align: top;
}
.ok {
color: var(--ok);
font-weight: 600;
}
.warn {
color: var(--warn);
font-weight: 600;
}
.bad {
color: var(--bad);
font-weight: 600;
}
code,
pre {
font-family: "IBM Plex Mono", ui-monospace, monospace;
font-size: 0.86rem;
}
pre {
background: var(--code);
padding: 0.9rem 1rem;
overflow-x: auto;
border: 1px solid var(--line);
}
.quiz {
background: var(--card);
border: 1px solid var(--line);
padding: 1rem 1.1rem 1.2rem;
}
.q {
margin: 1rem 0 0.4rem;
font-weight: 600;
}
label {
display: block;
margin: 0.2rem 0;
}
button {
margin-top: 1rem;
background: var(--ink);
color: var(--paper);
border: 0;
padding: 0.55rem 0.9rem;
font: inherit;
cursor: pointer;
}
button:focus {
outline: 2px solid var(--accent);
outline-offset: 2px;
}
#score {
margin-top: 0.8rem;
font-weight: 600;
}
.hidden-answer {
display: none;
}
</style>
<p class="lede">
这份报告对应 ghbot 生产硬化批次:合并 SHA
钉死、冲突锁、webhook/代理超时、配置交叉校验,以及本地门禁与 HTTP
冒烟。测验覆盖真实行为,不是口号。
</p>
<div class="grid">
<div class="stat"><b>148</b><span>本地测试通过(本批次实测)</span></div>
<div class="stat"><b>0</b><span>生产依赖 audit high+</span></div>
<div class="stat"><b>P0/P1</b><span>已修运行时守卫;7.1 路由器未拆</span></div>
<div class="stat"><b>fork</b><span>origin lezi-fun/ghbot 无 push</span></div>
</div>
<h2>改了什么,为什么</h2>
<table>
<thead>
<tr>
<th>守卫</th>
<th>故障模式</th>
<th>落地</th>
</tr>
</thead>
<tbody>
<tr>
<td>合并 SHA</td>
<td>审查后 head 变化仍 merge</td>
<td><code>pulls.merge(sha)</code> + live head 复检</td>
</tr>
<tr>
<td>冲突锁</td>
<td>同一 PR 并发改共享 worktree</td>
<td>进程内 per-PR lock + 失败 hard reset</td>
</tr>
<tr>
<td>git/代理/进程</td>
<td>无超时、输出无限增长</td>
<td>timeout + 1MB 输出帽 + abort</td>
</tr>
<tr>
<td>webhook</td>
<td>慢客户端/超大包拖死</td>
<td>30s body、413、顶层 catch</td>
</tr>
<tr>
<td>配置</td>
<td>半套 R2 / webhook 无 secret</td>
<td>zod superRefine fail-fast</td>
</tr>
<tr>
<td>评论命令</td>
<td>失败被吃掉,Actions 显示成功</td>
<td>allSettled + AggregateError</td>
</tr>
</tbody>
</table>
<h2>需求追踪摘要</h2>
<table>
<thead>
<tr>
<th>需求</th>
<th>状态</th>
<th>证据</th>
</tr>
</thead>
<tbody>
<tr>
<td>生产安全红线(凭据/PR 代码/缓存复用)</td>
<td class="ok">已闭环(静态+测试)</td>
<td>sanitization/secrets、snapshot 排除、cache 只作增量上下文</td>
</tr>
<tr>
<td>部署一次能跑</td>
<td class="warn">部分闭环</td>
<td>文档/env 已对齐;真实 GitHub App 安装未在本机复现</td>
</tr>
<tr>
<td>事件失败可见</td>
<td class="ok">已闭环</td>
<td>comment AggregateError;webhook 401/413/503</td>
</tr>
<tr>
<td>审查结果可信</td>
<td class="ok">已闭环</td>
<td>normalizeReviewDecision + 状态横幅</td>
</tr>
<tr>
<td>7.1 事件路由器拆分</td>
<td class="warn">未做(有意)</td>
<td>无事件环测试床,拆 1700 行 processor 风险高于收益</td>
</tr>
<tr>
<td>6.4 全站 i18n</td>
<td class="warn">未闭环</td>
<td>仅 chat 按评论语言;审查正文仍英文</td>
</tr>
<tr>
<td>付费 LLM E2E</td>
<td class="warn">外部受限</td>
<td>未调用真实 Goose/OpenAI</td>
</tr>
</tbody>
</table>
<h2>验证证据</h2>
<pre>
npm run typecheck → 0 errors
npm test → 148/148 pass
npm run lint → 0 errors
npm run format:check → pass
npm audit --omit=dev → 0 vulnerabilities
npm run build → dist loaded
webhook HTTP smoke → see E2E section in repo docs</pre>
<h2>明确没做的</h2>
<ul>
<li>没有把审查编排拆成独立 router(7.1)。</li>
<li>没有把全部评论文案做成中英字典(6.4)。</li>
<li>
没有 goose CLI 二进制 checksum 钉死(安装脚本仍从 GitHub 拉指定 tag 的 download_cli.sh)。
</li>
<li>没有对 origin <code>lezi-fun/ghbot</code> 推送(账号无权限)。</li>
</ul>
<h2>测验</h2>
<div class="quiz">
<p>提交后显示分数。通过线 80%(8/10)。未提交前不显示答案。</p>
<form id="quiz">
<div class="q">1. AUTO_MERGE 的代码默认值是?</div>
<label><input type="radio" name="q1" value="a" /> true</label>
<label><input type="radio" name="q1" value="b" /> false</label>
<label><input type="radio" name="q1" value="c" /> inherit GitHub</label>
<div class="q">2. 合并时如何防止审查后 head 被替换?</div>
<label><input type="radio" name="q2" value="a" /> 只看缓存决策</label>
<label
><input type="radio" name="q2" value="b" /> pulls.merge 传入审查时的 sha,并 live GET
复检</label
>
<label><input type="radio" name="q2" value="c" /> force push 回去</label>
<div class="q">3. WEBHOOK_SECRET 应该等于 webhook URL 吗?</div>
<label><input type="radio" name="q3" value="a" /> 应该,方便记忆</label>
<label><input type="radio" name="q3" value="b" /> 不应该,必须是独立 HMAC 密钥</label>
<div class="q">4. 同一 PR 两个 /conflict 同时跑会怎样?</div>
<label><input type="radio" name="q4" value="a" /> 共享 worktree 并行 merge</label>
<label><input type="radio" name="q4" value="b" /> 第二个获取锁失败</label>
<div class="q">5. R2 只配了 endpoint 没有密钥时?</div>
<label><input type="radio" name="q5" value="a" /> 静默跳过</label>
<label><input type="radio" name="q5" value="b" /> 启动/解析配置失败</label>
<div class="q">6. issue_comment 里 /recheck 抛错时?</div>
<label><input type="radio" name="q6" value="a" /> 整个 job 仍标成功</label>
<label
><input type="radio" name="q6" value="b" /> 其他 handler 仍跑,最后 AggregateError 让 Actions
失败可重试</label
>
<div class="q">7. 审查 finding 指向 PR 里不存在的文件?</div>
<label><input type="radio" name="q7" value="a" /> 原样提交 inline</label>
<label><input type="radio" name="q7" value="b" /> normalize 丢掉并记 warning</label>
<div class="q">8. Goose 容器能拿到真实 GOOSE_API_KEY 吗?</div>
<label><input type="radio" name="q8" value="a" /> 能,方便调试</label>
<label><input type="radio" name="q8" value="b" /> 不能,只用一次性代理 token</label>
<div class="q">9. 本批次是否声称真实付费 LLM 端到端已跑通?</div>
<label><input type="radio" name="q9" value="a" /> 是</label>
<label><input type="radio" name="q9" value="b" /> 否,外部调用未测</label>
<div class="q">10. origin lezi-fun/ghbot 推送状态?</div>
<label><input type="radio" name="q10" value="a" /> 已推送</label>
<label><input type="radio" name="q10" value="b" /> 403,改推 lza6/ghbot-Nodeloc</label>
<button type="submit">提交测验</button>
</form>
<div id="score"></div>
</div>
<script>
const answers = {
q1: "b",
q2: "b",
q3: "b",
q4: "b",
q5: "b",
q6: "b",
q7: "b",
q8: "b",
q9: "b",
q10: "b"
};
document.getElementById("quiz").addEventListener("submit", function (e) {
e.preventDefault();
const form = e.target;
let score = 0;
const total = Object.keys(answers).length;
for (const [name, expected] of Object.entries(answers)) {
const picked = form.querySelector('input[name="' + name + '"]:checked');
if (picked && picked.value === expected) score += 1;
}
const pct = Math.round((score / total) * 100);
const pass = pct >= 80;
document.getElementById("score").textContent =
"得分 " +
score +
"/" +
total +
"(" +
pct +
"%)。" +
(pass ? "通过。" : "未通过,对照报告再答。");
});
</script>
Loaded 100 of 180 files, more files were not shown because too many files have changed in this diff. Show more