9148c358d0
Topic_Agent/Topic_Blog/Topics/Topics_Biz/Topics_Meeting/Topics_Rag의 마크다운 지식 문서를 Topic_General/Topic_Programming/Topic_Graphic/Topic_Business 4개 카테고리로 재분류. - 중복 제거: frontmatter의 status:duplicate/merged + duplicate_of/redirect_to 필드로 자기 자신을 중복으로 선언한 리다이렉트 stub 1032개 제거, 완전 동일 내용 파일 472개 제거, 동일 파일명·다른 내용 충돌 시 더 큰(완전한) 버전만 유지(162개 제거) — 총 1639개 중복 제거. - 분류: 폴더 단위로 명확한 항목(AI_and_ML/Coding/Architecture 등 → Programming, Comfyui/Visual_Effects → Graphic, Topics_Biz/Topics_Meeting/사업 등 → Business, Poetic_Blog_Writing/창의성/Game_Design 등 → General)은 폴더 우선순위로, 나머지 혼재 폴더(Topic_Agent/Topic_Blog/Topics 루트/Thinking & Reasoning/Other/UI_UX_Assets)는 title/tags 키워드 스코어링으로 파일 단위 분류(불명확한 경우 General로 폴백). 원본 폴더명은 "From_*" 서브폴더로 보존해 추적 가능성 유지. - 최종 배치: Programming 2784 / General 1608 / Graphic 285 / Business 249 = 4926개 문서. - 에이전트 운영 상태(.astra/.agent/.obsidian/sessions/memory/_company/docs/lessons/_shared/src)는 지식 콘텐츠가 아니므로 재분류 대상에서 제외하고 원위치 유지. - Topics/Topic_email(상위 보호 폴더 Topic_email과 파일명 100% 중복) 삭제 — 보호 폴더 자체는 미변경. - 완전히 비게 된 Topic_Agent/Topic_Blog/Topics_Biz/Topics_Rag 폴더 제거.
6.7 KiB
6.7 KiB
id, title, category, status, canonical_id, aliases, duplicate_of, source_trust_level, confidence_score, verification_status, tags, raw_sources, last_reinforced, github_commit, tech_stack
| id | title | category | status | canonical_id | aliases | duplicate_of | source_trust_level | confidence_score | verification_status | tags | raw_sources | last_reinforced | github_commit | tech_stack | ||||||||||||
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
| wiki-2026-0508-zod-런타임-유효성-검사-통합 | Zod 런타임 유효성 검사 통합 | 10_Wiki/Topics | verified | self |
|
none | A | 0.9 | applied |
|
2026-05-10 | pending |
|
Zod 런타임 유효성 검사 통합
매 한 줄
"매 type schema = single source of truth". Zod는 매 TypeScript type을 런타임 schema 로 정의하고, parse 시점에 매 validation + type narrowing 을 동시 제공한다. API boundary, env vars, form input 매 unsafe input 의 매 첫 검증선.
매 핵심
매 동기 (Why Zod over alternatives)
- TypeScript types are erased: 매 컴파일 후
interface User는 매 사라짐 → API response 의data as User매 lying. - Zod = schema → type:
z.infer<typeof Schema>로 매 schema 가 source of truth. - Composability: 매
.merge,.partial,.extend,.transform으로 매 schema 합성. - Error-rich: parse failure 시 매 path, code, message tree 반환.
매 경쟁 라이브러리
- Yup: 매 older, schema → type 약함, 매 Zod 가 대체.
- io-ts: 매 더 functional (fp-ts), 매 learning curve 높음.
- Valibot: 매 tree-shakable, 매 bundle size 우선이면 고려 (~10x smaller).
- ArkType: 매 string-based syntax, 매 빠르지만 ecosystem 작음.
- Zod: 매 default choice in 2026 — DX, ecosystem (tRPC, React Hook Form), maturity.
매 응용
- API boundary: fetch response 매 parse 후 typed 으로 사용.
- Form validation: React Hook Form + zodResolver.
- env vars:
process.env의 매 schema parse, missing key 시 즉시 fail. - DB row → domain: ORM 결과 매
Schema.parse(row). - LLM structured output: Claude/GPT JSON response 매 schema 로 검증.
💻 패턴
Pattern 1: 기본 schema + type inference
import { z } from "zod";
export const UserSchema = z.object({
id: z.string().uuid(),
email: z.string().email(),
age: z.number().int().min(0).max(150),
role: z.enum(["admin", "user", "guest"]),
createdAt: z.coerce.date(),
});
export type User = z.infer<typeof UserSchema>;
// usage
const raw: unknown = await fetchUser();
const user = UserSchema.parse(raw); // throws ZodError if invalid
// ^? User
Pattern 2: safeParse for non-throw
const result = UserSchema.safeParse(raw);
if (!result.success) {
console.error(result.error.flatten());
return;
}
const user = result.data; // typed
Pattern 3: env validation (fail fast at boot)
const EnvSchema = z.object({
DATABASE_URL: z.string().url(),
PORT: z.coerce.number().int().positive().default(3000),
NODE_ENV: z.enum(["development", "production", "test"]),
ANTHROPIC_API_KEY: z.string().startsWith("sk-ant-"),
});
export const env = EnvSchema.parse(process.env);
// process exits at startup if invalid — better than runtime surprise
Pattern 4: discriminated union
const ResultSchema = z.discriminatedUnion("status", [
z.object({ status: z.literal("ok"), data: z.string() }),
z.object({ status: z.literal("error"), code: z.number() }),
]);
type Result = z.infer<typeof ResultSchema>;
// narrowing on .status works correctly
Pattern 5: transform for parse-not-validate
const DateSchema = z.string().transform((s, ctx) => {
const d = new Date(s);
if (isNaN(d.getTime())) {
ctx.addIssue({ code: "custom", message: "Invalid date" });
return z.NEVER;
}
return d;
});
const out = DateSchema.parse("2026-05-10"); // Date instance
Pattern 6: API client with Zod
async function fetchUser(id: string): Promise<User> {
const res = await fetch(`/api/users/${id}`);
const json = await res.json();
return UserSchema.parse(json); // unknown → User
}
Pattern 7: tRPC integration
import { router, procedure } from "./trpc";
export const userRouter = router({
create: procedure
.input(UserSchema.omit({ id: true, createdAt: true }))
.mutation(async ({ input }) => {
// input is fully typed + validated
return db.user.create({ data: input });
}),
});
Pattern 8: React Hook Form + Zod
import { useForm } from "react-hook-form";
import { zodResolver } from "@hookform/resolvers/zod";
const FormSchema = z.object({
email: z.string().email(),
password: z.string().min(8),
});
const { register, handleSubmit, formState } = useForm({
resolver: zodResolver(FormSchema),
});
Pattern 9: schema composition
const Base = z.object({ id: z.string(), createdAt: z.date() });
const Post = Base.extend({ title: z.string(), body: z.string() });
const PostUpdate = Post.partial().required({ id: true });
Pattern 10: refinement (custom rules)
const PasswordSchema = z
.object({ password: z.string(), confirm: z.string() })
.refine((d) => d.password === d.confirm, {
message: "Passwords do not match",
path: ["confirm"],
});
매 결정 기준
| 상황 | Approach |
|---|---|
| API boundary, untrusted input | Zod parse |
| Internal pure-TS code | Type only, no Zod |
| Bundle size critical (mobile, edge) | Valibot |
| Functional ergonomics | io-ts |
| LLM structured output (Claude/GPT) | Zod + tool schema |
| Performance hot path (>10k parses/sec) | Compile to TypeBox/AJV |
기본값: Zod 3.x — 매 modern TS app 의 default validation layer.
🔗 Graph
- 부모: TypeScript · Runtime_Validation
- 변형: Valibot · Yup · ArkType
- 응용: React Hook Form
- Adjacent: JSON Schema · 과잉 속성 체크 (Excess Property Checking)
🤖 LLM 활용
언제: untrusted boundary (API, form, env, LLM output) 매 parse. tool/function calling 의 매 input schema. 언제 X: internal pure-TS code 매 over-validation 불필요. hot loop 의 매 매 parse 호출.
❌ 안티패턴
- Anti1: parse everywhere: 매 internal function 매 Zod parse — 매 overhead 누적, 매 type only 충분.
- Anti2: as cast after parse:
Schema.parse(x) as MyType— 매 redundant, parse 가 이미 typed return. - Anti3: schema duplication: type + schema 따로 정의 — 매 z.infer 사용.
- Anti4: nested transforms with side effects: transform 안에서 fetch/IO — 매 pure 하게 유지.
🧪 검증 / 중복
- Verified (Zod docs colinhacks.com/zod, 2026 ecosystem).
- 신뢰도 A.
🕓 Changelog
| 날짜 | 변경 |
|---|---|
| 2026-05-08 | Phase 1 |
| 2026-05-10 | Manual cleanup — Zod runtime validation patterns + 2026 ecosystem context |