sisyo 1.2.0 → 1.3.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/bin/sisyo.js +86 -32
- package/package.json +1 -1
- package/templates/.claude/skills/fastapi-best-practices/ASYNC-PATTERNS.md +121 -0
- package/templates/.claude/skills/fastapi-best-practices/DATABASE.md +153 -0
- package/templates/.claude/skills/fastapi-best-practices/DEPENDENCIES.md +140 -0
- package/templates/.claude/skills/fastapi-best-practices/PROJECT-STRUCTURE.md +90 -0
- package/templates/.claude/skills/fastapi-best-practices/PYDANTIC-GUIDE.md +155 -0
- package/templates/.claude/skills/fastapi-best-practices/SKILL.md +123 -0
- package/templates/.claude/skills/react-page-oriented/SKILL.md +407 -0
- package/templates/.claude/skills/react-page-oriented/triggers.md +12 -0
- /package/templates/{CLAUDE.md → SISYO.md} +0 -0
package/bin/sisyo.js
CHANGED
|
@@ -5,40 +5,79 @@ const path = require("path");
|
|
|
5
5
|
|
|
6
6
|
const RESET = "\x1b[0m";
|
|
7
7
|
const GREEN = "\x1b[32m";
|
|
8
|
+
const YELLOW = "\x1b[33m";
|
|
8
9
|
const CYAN = "\x1b[36m";
|
|
9
10
|
const BOLD = "\x1b[1m";
|
|
10
11
|
const DIM = "\x1b[2m";
|
|
11
12
|
|
|
12
13
|
function log(msg) { console.log(msg); }
|
|
13
14
|
function ok(msg) { log(`${GREEN}+${RESET} ${msg}`); }
|
|
15
|
+
function up(msg) { log(`${YELLOW}~${RESET} ${msg}`); }
|
|
14
16
|
function info(msg) { log(`${DIM} ${msg}${RESET}`); }
|
|
15
17
|
|
|
16
|
-
|
|
18
|
+
// System files that get replaced on --update
|
|
19
|
+
const SYSTEM_FILES = [
|
|
20
|
+
"SISYO.md",
|
|
21
|
+
".claude/rules/docs.md",
|
|
22
|
+
".claude/skills/vibe-docs/SKILL.md",
|
|
23
|
+
];
|
|
24
|
+
|
|
25
|
+
function isSystemFile(relativePath) {
|
|
26
|
+
return SYSTEM_FILES.some(f => relativePath === f || relativePath.endsWith(f));
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
function ensureClaudeMdImport(target) {
|
|
30
|
+
const claudePath = path.join(target, "CLAUDE.md");
|
|
31
|
+
const importLine = "@SISYO.md";
|
|
32
|
+
if (fs.existsSync(claudePath)) {
|
|
33
|
+
const content = fs.readFileSync(claudePath, "utf8");
|
|
34
|
+
if (!content.includes(importLine)) {
|
|
35
|
+
fs.appendFileSync(claudePath, `\n${importLine}\n`);
|
|
36
|
+
up("CLAUDE.md (added @SISYO.md import)");
|
|
37
|
+
}
|
|
38
|
+
} else {
|
|
39
|
+
fs.writeFileSync(claudePath, `${importLine}\n`);
|
|
40
|
+
ok("CLAUDE.md");
|
|
41
|
+
}
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
function copyDir(src, dest, { updateMode = false } = {}) {
|
|
17
45
|
fs.mkdirSync(dest, { recursive: true });
|
|
18
46
|
for (const entry of fs.readdirSync(src, { withFileTypes: true })) {
|
|
19
47
|
const srcPath = path.join(src, entry.name);
|
|
20
48
|
const destPath = path.join(dest, entry.name);
|
|
21
49
|
if (entry.isDirectory()) {
|
|
22
|
-
copyDir(srcPath, destPath);
|
|
50
|
+
copyDir(srcPath, destPath, { updateMode });
|
|
23
51
|
} else {
|
|
24
|
-
|
|
52
|
+
const rel = path.relative(process.cwd(), destPath);
|
|
25
53
|
if (fs.existsSync(destPath)) {
|
|
26
|
-
|
|
54
|
+
if (updateMode && isSystemFile(rel)) {
|
|
55
|
+
fs.copyFileSync(srcPath, destPath);
|
|
56
|
+
up(`${rel} (updated)`);
|
|
57
|
+
} else {
|
|
58
|
+
info(`skip ${rel} (exists)`);
|
|
59
|
+
}
|
|
27
60
|
continue;
|
|
28
61
|
}
|
|
29
62
|
fs.copyFileSync(srcPath, destPath);
|
|
30
|
-
ok(
|
|
63
|
+
ok(rel);
|
|
31
64
|
}
|
|
32
65
|
}
|
|
33
66
|
}
|
|
34
67
|
|
|
35
68
|
function main() {
|
|
36
|
-
const
|
|
69
|
+
const args = process.argv.slice(2);
|
|
70
|
+
const updateMode = args.includes("--update");
|
|
71
|
+
const targetDir = args.find(a => !a.startsWith("-")) || ".";
|
|
37
72
|
const target = path.resolve(targetDir);
|
|
38
73
|
const templatesDir = path.join(__dirname, "..", "templates");
|
|
39
74
|
|
|
40
75
|
log("");
|
|
41
|
-
|
|
76
|
+
if (updateMode) {
|
|
77
|
+
log(`${BOLD}${CYAN}sisyo${RESET} ${DIM}Updating system files...${RESET}`);
|
|
78
|
+
} else {
|
|
79
|
+
log(`${BOLD}${CYAN}sisyo${RESET} ${DIM}Smart docs for Claude Code${RESET}`);
|
|
80
|
+
}
|
|
42
81
|
log("");
|
|
43
82
|
|
|
44
83
|
if (!fs.existsSync(templatesDir)) {
|
|
@@ -47,31 +86,42 @@ function main() {
|
|
|
47
86
|
}
|
|
48
87
|
|
|
49
88
|
// Copy all templates
|
|
50
|
-
copyDir(templatesDir, target);
|
|
89
|
+
copyDir(templatesDir, target, { updateMode });
|
|
90
|
+
|
|
91
|
+
// Ensure CLAUDE.md imports SISYO.md
|
|
92
|
+
ensureClaudeMdImport(target);
|
|
51
93
|
|
|
52
94
|
// Get today's date
|
|
53
95
|
const today = new Date().toISOString().split("T")[0];
|
|
54
96
|
|
|
55
|
-
// Update dates in MAP.md and handoff
|
|
56
|
-
|
|
57
|
-
|
|
58
|
-
|
|
59
|
-
|
|
60
|
-
|
|
61
|
-
|
|
97
|
+
// Update dates in MAP.md and handoff (only on fresh install, not --update)
|
|
98
|
+
if (!updateMode) {
|
|
99
|
+
const mapPath = path.join(target, "docs", "MAP.md");
|
|
100
|
+
if (fs.existsSync(mapPath)) {
|
|
101
|
+
let mapContent = fs.readFileSync(mapPath, "utf8");
|
|
102
|
+
if (mapContent.includes("YYYY-MM-DD")) {
|
|
103
|
+
mapContent = mapContent.replace(/YYYY-MM-DD/g, today);
|
|
104
|
+
fs.writeFileSync(mapPath, mapContent);
|
|
105
|
+
}
|
|
106
|
+
}
|
|
62
107
|
|
|
63
|
-
|
|
64
|
-
|
|
65
|
-
|
|
66
|
-
|
|
67
|
-
|
|
68
|
-
|
|
108
|
+
const handoffPath = path.join(target, "docs", "99_progress", "handoff.md");
|
|
109
|
+
if (fs.existsSync(handoffPath)) {
|
|
110
|
+
let content = fs.readFileSync(handoffPath, "utf8");
|
|
111
|
+
if (content.includes("YYYY-MM-DD")) {
|
|
112
|
+
content = content.replace(/YYYY-MM-DD/g, today);
|
|
113
|
+
fs.writeFileSync(handoffPath, content);
|
|
114
|
+
}
|
|
115
|
+
}
|
|
69
116
|
|
|
70
|
-
|
|
71
|
-
|
|
72
|
-
|
|
73
|
-
|
|
74
|
-
|
|
117
|
+
const todoPath = path.join(target, "docs", "99_progress", "todo.md");
|
|
118
|
+
if (fs.existsSync(todoPath)) {
|
|
119
|
+
let content = fs.readFileSync(todoPath, "utf8");
|
|
120
|
+
if (content.includes("YYYY-MM-DD")) {
|
|
121
|
+
content = content.replace(/YYYY-MM-DD/g, today);
|
|
122
|
+
fs.writeFileSync(todoPath, content);
|
|
123
|
+
}
|
|
124
|
+
}
|
|
75
125
|
}
|
|
76
126
|
|
|
77
127
|
// Add to .gitignore if exists
|
|
@@ -87,13 +137,17 @@ function main() {
|
|
|
87
137
|
}
|
|
88
138
|
|
|
89
139
|
log("");
|
|
90
|
-
|
|
91
|
-
|
|
92
|
-
|
|
93
|
-
|
|
94
|
-
|
|
140
|
+
if (updateMode) {
|
|
141
|
+
log(`${BOLD}Done!${RESET} System files updated. Your docs are untouched.`);
|
|
142
|
+
} else {
|
|
143
|
+
log(`${BOLD}Done!${RESET} Next steps:`);
|
|
144
|
+
log("");
|
|
145
|
+
log(` 1. Edit ${CYAN}SISYO.md${RESET} — replace [Project Name] with yours`);
|
|
146
|
+
log(` 2. Open Claude Code and start building`);
|
|
147
|
+
log(` 3. Docs auto-update as you work`);
|
|
148
|
+
}
|
|
95
149
|
log("");
|
|
96
|
-
log(`${DIM}Docs system:
|
|
150
|
+
log(`${DIM}Docs system: SISYO.md -> docs/MAP.md -> _summary.md -> detail files${RESET}`);
|
|
97
151
|
log("");
|
|
98
152
|
}
|
|
99
153
|
|
package/package.json
CHANGED
|
@@ -0,0 +1,121 @@
|
|
|
1
|
+
# Async Patterns
|
|
2
|
+
|
|
3
|
+
## Route Types Comparison
|
|
4
|
+
|
|
5
|
+
| Route Type | Blocking Code | Event Loop | Use Case |
|
|
6
|
+
|------------|--------------|------------|----------|
|
|
7
|
+
| `async def` + `await` | Non-blocking | Free | Async I/O (httpx, asyncpg) |
|
|
8
|
+
| `def` (sync) | Runs in threadpool | Free | Sync libraries, simple ops |
|
|
9
|
+
| `async def` + blocking | BLOCKS EVERYTHING | Blocked | NEVER DO THIS |
|
|
10
|
+
|
|
11
|
+
## I/O Operations
|
|
12
|
+
|
|
13
|
+
### Async Database Calls
|
|
14
|
+
|
|
15
|
+
```python
|
|
16
|
+
# GOOD - async database
|
|
17
|
+
@router.get("/users/{user_id}")
|
|
18
|
+
async def get_user(user_id: int):
|
|
19
|
+
user = await db.fetch_one("SELECT * FROM users WHERE id = $1", user_id)
|
|
20
|
+
return user
|
|
21
|
+
```
|
|
22
|
+
|
|
23
|
+
### Sync Libraries in Async Routes
|
|
24
|
+
|
|
25
|
+
```python
|
|
26
|
+
from fastapi.concurrency import run_in_threadpool
|
|
27
|
+
|
|
28
|
+
@router.get("/sync-lib")
|
|
29
|
+
async def use_sync_library():
|
|
30
|
+
# Run sync code in threadpool
|
|
31
|
+
result = await run_in_threadpool(sync_client.fetch_data)
|
|
32
|
+
return result
|
|
33
|
+
```
|
|
34
|
+
|
|
35
|
+
### HTTP Calls
|
|
36
|
+
|
|
37
|
+
```python
|
|
38
|
+
import httpx
|
|
39
|
+
|
|
40
|
+
# GOOD - async HTTP client
|
|
41
|
+
@router.get("/external")
|
|
42
|
+
async def call_external():
|
|
43
|
+
async with httpx.AsyncClient() as client:
|
|
44
|
+
response = await client.get("https://api.example.com/data")
|
|
45
|
+
return response.json()
|
|
46
|
+
```
|
|
47
|
+
|
|
48
|
+
## CPU-Intensive Tasks
|
|
49
|
+
|
|
50
|
+
CPU-bound work blocks regardless of async/sync. Offload to workers:
|
|
51
|
+
|
|
52
|
+
```python
|
|
53
|
+
from fastapi import BackgroundTasks
|
|
54
|
+
|
|
55
|
+
@router.post("/process")
|
|
56
|
+
async def process_data(background_tasks: BackgroundTasks):
|
|
57
|
+
# Queue for background processing
|
|
58
|
+
background_tasks.add_task(heavy_computation, data)
|
|
59
|
+
return {"status": "processing"}
|
|
60
|
+
|
|
61
|
+
# For heavy CPU work, use Celery or multiprocessing
|
|
62
|
+
```
|
|
63
|
+
|
|
64
|
+
## Common Mistakes
|
|
65
|
+
|
|
66
|
+
### Blocking in Async Route
|
|
67
|
+
|
|
68
|
+
```python
|
|
69
|
+
# BAD - blocks entire server
|
|
70
|
+
@router.get("/terrible")
|
|
71
|
+
async def terrible():
|
|
72
|
+
time.sleep(10) # NEVER do this in async route
|
|
73
|
+
return {"done": True}
|
|
74
|
+
|
|
75
|
+
# GOOD - use sync route for blocking code
|
|
76
|
+
@router.get("/acceptable")
|
|
77
|
+
def acceptable():
|
|
78
|
+
time.sleep(10) # runs in threadpool
|
|
79
|
+
return {"done": True}
|
|
80
|
+
|
|
81
|
+
# BEST - use async sleep
|
|
82
|
+
@router.get("/perfect")
|
|
83
|
+
async def perfect():
|
|
84
|
+
await asyncio.sleep(10)
|
|
85
|
+
return {"done": True}
|
|
86
|
+
```
|
|
87
|
+
|
|
88
|
+
### Sync ORM in Async Route
|
|
89
|
+
|
|
90
|
+
```python
|
|
91
|
+
# BAD
|
|
92
|
+
@router.get("/users")
|
|
93
|
+
async def get_users():
|
|
94
|
+
return db.query(User).all() # sync ORM blocks event loop
|
|
95
|
+
|
|
96
|
+
# GOOD - use async ORM or threadpool
|
|
97
|
+
@router.get("/users")
|
|
98
|
+
async def get_users():
|
|
99
|
+
return await run_in_threadpool(lambda: db.query(User).all())
|
|
100
|
+
|
|
101
|
+
# BEST - use async ORM (SQLAlchemy 2.0 async)
|
|
102
|
+
@router.get("/users")
|
|
103
|
+
async def get_users():
|
|
104
|
+
result = await session.execute(select(User))
|
|
105
|
+
return result.scalars().all()
|
|
106
|
+
```
|
|
107
|
+
|
|
108
|
+
## Dependencies
|
|
109
|
+
|
|
110
|
+
Prefer async dependencies when possible:
|
|
111
|
+
|
|
112
|
+
```python
|
|
113
|
+
# GOOD - async dependency
|
|
114
|
+
async def get_current_user(token: str = Depends(oauth2_scheme)):
|
|
115
|
+
user = await users_service.get_by_token(token)
|
|
116
|
+
return user
|
|
117
|
+
|
|
118
|
+
# OK but less efficient - sync dependency runs in threadpool
|
|
119
|
+
def get_settings():
|
|
120
|
+
return Settings()
|
|
121
|
+
```
|
|
@@ -0,0 +1,153 @@
|
|
|
1
|
+
# Database Patterns
|
|
2
|
+
|
|
3
|
+
## Naming Conventions
|
|
4
|
+
|
|
5
|
+
| Convention | Rule | Example |
|
|
6
|
+
|------------|------|---------|
|
|
7
|
+
| Tables | `lower_case_snake`, singular | `post`, `user_playlist` |
|
|
8
|
+
| Group by module | prefix with module | `payment_account`, `payment_bill` |
|
|
9
|
+
| Datetime columns | `_at` suffix | `created_at`, `updated_at` |
|
|
10
|
+
| Date columns | `_date` suffix | `birth_date`, `due_date` |
|
|
11
|
+
|
|
12
|
+
## SQLAlchemy Index Naming
|
|
13
|
+
|
|
14
|
+
```python
|
|
15
|
+
from sqlalchemy import MetaData
|
|
16
|
+
|
|
17
|
+
POSTGRES_INDEXES_NAMING_CONVENTION = {
|
|
18
|
+
"ix": "%(column_0_label)s_idx",
|
|
19
|
+
"uq": "%(table_name)s_%(column_0_name)s_key",
|
|
20
|
+
"ck": "%(table_name)s_%(constraint_name)s_check",
|
|
21
|
+
"fk": "%(table_name)s_%(column_0_name)s_fkey",
|
|
22
|
+
"pk": "%(table_name)s_pkey",
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
metadata = MetaData(naming_convention=POSTGRES_INDEXES_NAMING_CONVENTION)
|
|
26
|
+
```
|
|
27
|
+
|
|
28
|
+
## SQL-First Approach
|
|
29
|
+
|
|
30
|
+
Let database do the heavy lifting:
|
|
31
|
+
|
|
32
|
+
```python
|
|
33
|
+
from sqlalchemy import select, func, text, desc
|
|
34
|
+
|
|
35
|
+
async def get_posts_with_creator(
|
|
36
|
+
creator_id: UUID4,
|
|
37
|
+
limit: int = 10,
|
|
38
|
+
offset: int = 0
|
|
39
|
+
) -> list[dict]:
|
|
40
|
+
query = (
|
|
41
|
+
select(
|
|
42
|
+
posts.c.id,
|
|
43
|
+
posts.c.title,
|
|
44
|
+
posts.c.slug,
|
|
45
|
+
# Build JSON in database
|
|
46
|
+
func.json_build_object(
|
|
47
|
+
text("'id', profiles.id"),
|
|
48
|
+
text("'name', profiles.name"),
|
|
49
|
+
text("'username', profiles.username"),
|
|
50
|
+
).label("creator"),
|
|
51
|
+
)
|
|
52
|
+
.select_from(posts.join(profiles, posts.c.owner_id == profiles.c.id))
|
|
53
|
+
.where(posts.c.owner_id == creator_id)
|
|
54
|
+
.order_by(desc(posts.c.created_at))
|
|
55
|
+
.limit(limit)
|
|
56
|
+
.offset(offset)
|
|
57
|
+
)
|
|
58
|
+
return await database.fetch_all(query)
|
|
59
|
+
```
|
|
60
|
+
|
|
61
|
+
## Alembic Migrations
|
|
62
|
+
|
|
63
|
+
### Config
|
|
64
|
+
|
|
65
|
+
```ini
|
|
66
|
+
# alembic.ini
|
|
67
|
+
file_template = %%(year)d-%%(month).2d-%%(day).2d_%%(slug)s
|
|
68
|
+
```
|
|
69
|
+
|
|
70
|
+
Generates: `2024-01-15_add_user_email_index.py`
|
|
71
|
+
|
|
72
|
+
### Migration Best Practices
|
|
73
|
+
|
|
74
|
+
1. **Always reversible** - include `downgrade()` function
|
|
75
|
+
2. **Descriptive names** - `add_posts_title_idx`, not `update_1`
|
|
76
|
+
3. **Static structure** - only data can be dynamic, not schema
|
|
77
|
+
|
|
78
|
+
```python
|
|
79
|
+
# Good migration
|
|
80
|
+
def upgrade():
|
|
81
|
+
op.add_column('users', sa.Column('avatar_url', sa.String(500)))
|
|
82
|
+
op.create_index('users_email_idx', 'users', ['email'])
|
|
83
|
+
|
|
84
|
+
def downgrade():
|
|
85
|
+
op.drop_index('users_email_idx', 'users')
|
|
86
|
+
op.drop_column('users', 'avatar_url')
|
|
87
|
+
```
|
|
88
|
+
|
|
89
|
+
## Async Database Setup
|
|
90
|
+
|
|
91
|
+
```python
|
|
92
|
+
# src/database.py
|
|
93
|
+
from sqlalchemy.ext.asyncio import create_async_engine, AsyncSession
|
|
94
|
+
from sqlalchemy.orm import sessionmaker
|
|
95
|
+
|
|
96
|
+
engine = create_async_engine(
|
|
97
|
+
settings.DATABASE_URL,
|
|
98
|
+
echo=settings.ENVIRONMENT == "local",
|
|
99
|
+
)
|
|
100
|
+
|
|
101
|
+
async_session = sessionmaker(
|
|
102
|
+
engine,
|
|
103
|
+
class_=AsyncSession,
|
|
104
|
+
expire_on_commit=False,
|
|
105
|
+
)
|
|
106
|
+
|
|
107
|
+
async def get_session() -> AsyncGenerator[AsyncSession, None]:
|
|
108
|
+
async with async_session() as session:
|
|
109
|
+
try:
|
|
110
|
+
yield session
|
|
111
|
+
await session.commit()
|
|
112
|
+
except Exception:
|
|
113
|
+
await session.rollback()
|
|
114
|
+
raise
|
|
115
|
+
```
|
|
116
|
+
|
|
117
|
+
## Query Patterns
|
|
118
|
+
|
|
119
|
+
### Pagination
|
|
120
|
+
|
|
121
|
+
```python
|
|
122
|
+
from pydantic import BaseModel
|
|
123
|
+
|
|
124
|
+
class PaginationParams(BaseModel):
|
|
125
|
+
limit: int = 10
|
|
126
|
+
offset: int = 0
|
|
127
|
+
|
|
128
|
+
async def get_paginated(
|
|
129
|
+
session: AsyncSession,
|
|
130
|
+
params: PaginationParams
|
|
131
|
+
) -> list[Post]:
|
|
132
|
+
result = await session.execute(
|
|
133
|
+
select(Post)
|
|
134
|
+
.order_by(Post.created_at.desc())
|
|
135
|
+
.limit(params.limit)
|
|
136
|
+
.offset(params.offset)
|
|
137
|
+
)
|
|
138
|
+
return result.scalars().all()
|
|
139
|
+
```
|
|
140
|
+
|
|
141
|
+
### Eager Loading
|
|
142
|
+
|
|
143
|
+
```python
|
|
144
|
+
from sqlalchemy.orm import selectinload
|
|
145
|
+
|
|
146
|
+
# Avoid N+1 queries
|
|
147
|
+
async def get_posts_with_comments(session: AsyncSession):
|
|
148
|
+
result = await session.execute(
|
|
149
|
+
select(Post)
|
|
150
|
+
.options(selectinload(Post.comments))
|
|
151
|
+
)
|
|
152
|
+
return result.scalars().all()
|
|
153
|
+
```
|
|
@@ -0,0 +1,140 @@
|
|
|
1
|
+
# Dependencies
|
|
2
|
+
|
|
3
|
+
## Validation Dependencies
|
|
4
|
+
|
|
5
|
+
Use dependencies for database/service validations:
|
|
6
|
+
|
|
7
|
+
```python
|
|
8
|
+
# src/posts/dependencies.py
|
|
9
|
+
from fastapi import Depends, HTTPException, status
|
|
10
|
+
from pydantic import UUID4
|
|
11
|
+
|
|
12
|
+
async def valid_post_id(post_id: UUID4) -> dict:
|
|
13
|
+
"""Validate post exists and return it."""
|
|
14
|
+
post = await service.get_by_id(post_id)
|
|
15
|
+
if not post:
|
|
16
|
+
raise HTTPException(
|
|
17
|
+
status_code=status.HTTP_404_NOT_FOUND,
|
|
18
|
+
detail="Post not found"
|
|
19
|
+
)
|
|
20
|
+
return post
|
|
21
|
+
|
|
22
|
+
# src/posts/router.py
|
|
23
|
+
@router.get("/posts/{post_id}")
|
|
24
|
+
async def get_post(post: dict = Depends(valid_post_id)):
|
|
25
|
+
return post
|
|
26
|
+
|
|
27
|
+
@router.put("/posts/{post_id}")
|
|
28
|
+
async def update_post(
|
|
29
|
+
update_data: PostUpdate,
|
|
30
|
+
post: dict = Depends(valid_post_id),
|
|
31
|
+
):
|
|
32
|
+
return await service.update(post["id"], update_data)
|
|
33
|
+
```
|
|
34
|
+
|
|
35
|
+
## Chaining Dependencies
|
|
36
|
+
|
|
37
|
+
```python
|
|
38
|
+
# src/auth/dependencies.py
|
|
39
|
+
from fastapi.security import OAuth2PasswordBearer
|
|
40
|
+
|
|
41
|
+
oauth2_scheme = OAuth2PasswordBearer(tokenUrl="/auth/token")
|
|
42
|
+
|
|
43
|
+
async def parse_jwt_data(
|
|
44
|
+
token: str = Depends(oauth2_scheme)
|
|
45
|
+
) -> dict:
|
|
46
|
+
try:
|
|
47
|
+
payload = jwt.decode(token, settings.JWT_SECRET, algorithms=[settings.JWT_ALG])
|
|
48
|
+
except JWTError:
|
|
49
|
+
raise HTTPException(status_code=401, detail="Invalid token")
|
|
50
|
+
return {"user_id": payload["sub"]}
|
|
51
|
+
|
|
52
|
+
async def get_current_user(
|
|
53
|
+
token_data: dict = Depends(parse_jwt_data)
|
|
54
|
+
) -> User:
|
|
55
|
+
user = await users_service.get_by_id(token_data["user_id"])
|
|
56
|
+
if not user:
|
|
57
|
+
raise HTTPException(status_code=401, detail="User not found")
|
|
58
|
+
return user
|
|
59
|
+
|
|
60
|
+
async def get_current_active_user(
|
|
61
|
+
user: User = Depends(get_current_user)
|
|
62
|
+
) -> User:
|
|
63
|
+
if not user.is_active:
|
|
64
|
+
raise HTTPException(status_code=403, detail="Inactive user")
|
|
65
|
+
return user
|
|
66
|
+
```
|
|
67
|
+
|
|
68
|
+
## Ownership Validation
|
|
69
|
+
|
|
70
|
+
```python
|
|
71
|
+
async def valid_owned_post(
|
|
72
|
+
post: dict = Depends(valid_post_id),
|
|
73
|
+
user: User = Depends(get_current_user),
|
|
74
|
+
) -> dict:
|
|
75
|
+
if post["creator_id"] != user.id:
|
|
76
|
+
raise HTTPException(status_code=403, detail="Not authorized")
|
|
77
|
+
return post
|
|
78
|
+
|
|
79
|
+
@router.delete("/posts/{post_id}")
|
|
80
|
+
async def delete_post(post: dict = Depends(valid_owned_post)):
|
|
81
|
+
await service.delete(post["id"])
|
|
82
|
+
return {"deleted": True}
|
|
83
|
+
```
|
|
84
|
+
|
|
85
|
+
## Caching Behavior
|
|
86
|
+
|
|
87
|
+
Dependencies are cached within a request. Same dependency = called once:
|
|
88
|
+
|
|
89
|
+
```python
|
|
90
|
+
# parse_jwt_data called only ONCE even though used in multiple deps
|
|
91
|
+
@router.get("/posts/{post_id}")
|
|
92
|
+
async def get_user_post(
|
|
93
|
+
post: dict = Depends(valid_owned_post), # uses parse_jwt_data
|
|
94
|
+
user: User = Depends(get_current_active_user), # also uses parse_jwt_data
|
|
95
|
+
):
|
|
96
|
+
return post
|
|
97
|
+
```
|
|
98
|
+
|
|
99
|
+
## REST Path Variable Consistency
|
|
100
|
+
|
|
101
|
+
Use same path variable names to enable dependency chaining:
|
|
102
|
+
|
|
103
|
+
```python
|
|
104
|
+
# src/profiles/dependencies.py
|
|
105
|
+
async def valid_profile_id(profile_id: UUID4) -> dict:
|
|
106
|
+
profile = await service.get_by_id(profile_id)
|
|
107
|
+
if not profile:
|
|
108
|
+
raise HTTPException(status_code=404, detail="Profile not found")
|
|
109
|
+
return profile
|
|
110
|
+
|
|
111
|
+
# src/creators/dependencies.py
|
|
112
|
+
async def valid_creator_id(
|
|
113
|
+
profile: dict = Depends(valid_profile_id) # chains from profile
|
|
114
|
+
) -> dict:
|
|
115
|
+
if not profile["is_creator"]:
|
|
116
|
+
raise HTTPException(status_code=403, detail="Not a creator")
|
|
117
|
+
return profile
|
|
118
|
+
|
|
119
|
+
# Both use profile_id in path
|
|
120
|
+
@router.get("/profiles/{profile_id}")
|
|
121
|
+
async def get_profile(profile: dict = Depends(valid_profile_id)):
|
|
122
|
+
return profile
|
|
123
|
+
|
|
124
|
+
@router.get("/creators/{profile_id}") # same path var name!
|
|
125
|
+
async def get_creator(creator: dict = Depends(valid_creator_id)):
|
|
126
|
+
return creator
|
|
127
|
+
```
|
|
128
|
+
|
|
129
|
+
## Prefer Async Dependencies
|
|
130
|
+
|
|
131
|
+
```python
|
|
132
|
+
# GOOD - async dependency
|
|
133
|
+
async def get_db_session() -> AsyncGenerator[AsyncSession, None]:
|
|
134
|
+
async with async_session() as session:
|
|
135
|
+
yield session
|
|
136
|
+
|
|
137
|
+
# OK but less efficient - runs in threadpool
|
|
138
|
+
def get_settings() -> Settings:
|
|
139
|
+
return Settings()
|
|
140
|
+
```
|
|
@@ -0,0 +1,90 @@
|
|
|
1
|
+
# Project Structure
|
|
2
|
+
|
|
3
|
+
## Domain-Based Organization
|
|
4
|
+
|
|
5
|
+
```
|
|
6
|
+
fastapi-project/
|
|
7
|
+
├── alembic/ # migrations
|
|
8
|
+
├── src/
|
|
9
|
+
│ ├── auth/ # auth domain
|
|
10
|
+
│ │ ├── router.py # endpoints
|
|
11
|
+
│ │ ├── schemas.py # pydantic models
|
|
12
|
+
│ │ ├── models.py # db models
|
|
13
|
+
│ │ ├── service.py # business logic
|
|
14
|
+
│ │ ├── dependencies.py # route dependencies
|
|
15
|
+
│ │ ├── config.py # local config
|
|
16
|
+
│ │ ├── constants.py # error codes, enums
|
|
17
|
+
│ │ ├── exceptions.py # custom exceptions
|
|
18
|
+
│ │ └── utils.py # helpers
|
|
19
|
+
│ ├── posts/ # posts domain
|
|
20
|
+
│ │ └── ... (same structure)
|
|
21
|
+
│ ├── aws/ # external service
|
|
22
|
+
│ │ ├── client.py # API client
|
|
23
|
+
│ │ ├── schemas.py
|
|
24
|
+
│ │ └── ...
|
|
25
|
+
│ ├── config.py # global config
|
|
26
|
+
│ ├── models.py # shared models
|
|
27
|
+
│ ├── exceptions.py # global exceptions
|
|
28
|
+
│ ├── database.py # db connection
|
|
29
|
+
│ └── main.py # app initialization
|
|
30
|
+
├── tests/
|
|
31
|
+
│ ├── auth/
|
|
32
|
+
│ ├── posts/
|
|
33
|
+
│ └── conftest.py
|
|
34
|
+
├── requirements/
|
|
35
|
+
│ ├── base.txt
|
|
36
|
+
│ ├── dev.txt
|
|
37
|
+
│ └── prod.txt
|
|
38
|
+
├── .env
|
|
39
|
+
└── alembic.ini
|
|
40
|
+
```
|
|
41
|
+
|
|
42
|
+
## File Responsibilities
|
|
43
|
+
|
|
44
|
+
| File | Purpose |
|
|
45
|
+
|------|---------|
|
|
46
|
+
| `router.py` | All endpoints for the module |
|
|
47
|
+
| `schemas.py` | Pydantic request/response models |
|
|
48
|
+
| `models.py` | SQLAlchemy/database models |
|
|
49
|
+
| `service.py` | Business logic, DB operations |
|
|
50
|
+
| `dependencies.py` | FastAPI dependencies |
|
|
51
|
+
| `constants.py` | Enums, error codes |
|
|
52
|
+
| `config.py` | Environment-specific settings |
|
|
53
|
+
| `exceptions.py` | Custom HTTP exceptions |
|
|
54
|
+
| `utils.py` | Pure utility functions |
|
|
55
|
+
|
|
56
|
+
## Main App Setup
|
|
57
|
+
|
|
58
|
+
```python
|
|
59
|
+
# src/main.py
|
|
60
|
+
from fastapi import FastAPI
|
|
61
|
+
from src.auth.router import router as auth_router
|
|
62
|
+
from src.posts.router import router as posts_router
|
|
63
|
+
from src.config import settings
|
|
64
|
+
|
|
65
|
+
app_configs = {"title": "My API"}
|
|
66
|
+
|
|
67
|
+
# Hide docs in production
|
|
68
|
+
if settings.ENVIRONMENT not in ("local", "staging"):
|
|
69
|
+
app_configs["openapi_url"] = None
|
|
70
|
+
|
|
71
|
+
app = FastAPI(**app_configs)
|
|
72
|
+
|
|
73
|
+
app.include_router(auth_router, prefix="/auth", tags=["Auth"])
|
|
74
|
+
app.include_router(posts_router, prefix="/posts", tags=["Posts"])
|
|
75
|
+
```
|
|
76
|
+
|
|
77
|
+
## Cross-Module Imports
|
|
78
|
+
|
|
79
|
+
Always use explicit module names to avoid confusion:
|
|
80
|
+
|
|
81
|
+
```python
|
|
82
|
+
# GOOD
|
|
83
|
+
from src.auth import constants as auth_constants
|
|
84
|
+
from src.auth import service as auth_service
|
|
85
|
+
from src.notifications import service as notification_service
|
|
86
|
+
|
|
87
|
+
# BAD
|
|
88
|
+
from src.auth.constants import *
|
|
89
|
+
from ..auth import service # relative imports can be confusing
|
|
90
|
+
```
|
|
@@ -0,0 +1,155 @@
|
|
|
1
|
+
# Pydantic Guide
|
|
2
|
+
|
|
3
|
+
## Schema Design
|
|
4
|
+
|
|
5
|
+
### Request Validation
|
|
6
|
+
|
|
7
|
+
```python
|
|
8
|
+
from enum import StrEnum
|
|
9
|
+
from pydantic import BaseModel, Field, EmailStr, AnyUrl, field_validator
|
|
10
|
+
import re
|
|
11
|
+
|
|
12
|
+
class UserRole(StrEnum):
|
|
13
|
+
ADMIN = "admin"
|
|
14
|
+
USER = "user"
|
|
15
|
+
GUEST = "guest"
|
|
16
|
+
|
|
17
|
+
class UserCreate(BaseModel):
|
|
18
|
+
username: str = Field(min_length=1, max_length=128, pattern="^[A-Za-z0-9-_]+$")
|
|
19
|
+
email: EmailStr
|
|
20
|
+
age: int | None = Field(ge=18, default=None)
|
|
21
|
+
role: UserRole = UserRole.USER
|
|
22
|
+
website: AnyUrl | None = None
|
|
23
|
+
|
|
24
|
+
@field_validator("username")
|
|
25
|
+
@classmethod
|
|
26
|
+
def username_lowercase(cls, v: str) -> str:
|
|
27
|
+
return v.lower()
|
|
28
|
+
```
|
|
29
|
+
|
|
30
|
+
### Password Validation
|
|
31
|
+
|
|
32
|
+
```python
|
|
33
|
+
STRONG_PASSWORD_PATTERN = r"^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)(?=.*[@$!%*?&])[A-Za-z\d@$!%*?&]{8,}$"
|
|
34
|
+
|
|
35
|
+
class UserCreate(BaseModel):
|
|
36
|
+
password: str
|
|
37
|
+
|
|
38
|
+
@field_validator("password")
|
|
39
|
+
@classmethod
|
|
40
|
+
def validate_password(cls, v: str) -> str:
|
|
41
|
+
if not re.match(STRONG_PASSWORD_PATTERN, v):
|
|
42
|
+
raise ValueError(
|
|
43
|
+
"Password must contain at least one lowercase, "
|
|
44
|
+
"one uppercase, one digit, and one special character"
|
|
45
|
+
)
|
|
46
|
+
return v
|
|
47
|
+
```
|
|
48
|
+
|
|
49
|
+
## Custom Base Model
|
|
50
|
+
|
|
51
|
+
```python
|
|
52
|
+
from datetime import datetime
|
|
53
|
+
from zoneinfo import ZoneInfo
|
|
54
|
+
from pydantic import BaseModel, ConfigDict
|
|
55
|
+
from fastapi.encoders import jsonable_encoder
|
|
56
|
+
|
|
57
|
+
def datetime_to_gmt_str(dt: datetime) -> str:
|
|
58
|
+
if not dt.tzinfo:
|
|
59
|
+
dt = dt.replace(tzinfo=ZoneInfo("UTC"))
|
|
60
|
+
return dt.strftime("%Y-%m-%dT%H:%M:%S%z")
|
|
61
|
+
|
|
62
|
+
class CustomModel(BaseModel):
|
|
63
|
+
model_config = ConfigDict(
|
|
64
|
+
json_encoders={datetime: datetime_to_gmt_str},
|
|
65
|
+
populate_by_name=True,
|
|
66
|
+
from_attributes=True, # for ORM mode
|
|
67
|
+
)
|
|
68
|
+
|
|
69
|
+
def serializable_dict(self, **kwargs):
|
|
70
|
+
"""Return dict with only serializable fields."""
|
|
71
|
+
return jsonable_encoder(self.model_dump())
|
|
72
|
+
```
|
|
73
|
+
|
|
74
|
+
## Settings Management
|
|
75
|
+
|
|
76
|
+
Split settings by domain:
|
|
77
|
+
|
|
78
|
+
```python
|
|
79
|
+
# src/auth/config.py
|
|
80
|
+
from pydantic_settings import BaseSettings
|
|
81
|
+
|
|
82
|
+
class AuthConfig(BaseSettings):
|
|
83
|
+
JWT_ALG: str = "HS256"
|
|
84
|
+
JWT_SECRET: str
|
|
85
|
+
JWT_EXP: int = 5 # minutes
|
|
86
|
+
REFRESH_TOKEN_EXP: int = 60 * 24 * 30 # 30 days
|
|
87
|
+
SECURE_COOKIES: bool = True
|
|
88
|
+
|
|
89
|
+
auth_settings = AuthConfig()
|
|
90
|
+
|
|
91
|
+
# src/config.py
|
|
92
|
+
from pydantic import PostgresDsn, RedisDsn
|
|
93
|
+
from pydantic_settings import BaseSettings
|
|
94
|
+
|
|
95
|
+
class Config(BaseSettings):
|
|
96
|
+
DATABASE_URL: PostgresDsn
|
|
97
|
+
REDIS_URL: RedisDsn | None = None
|
|
98
|
+
ENVIRONMENT: str = "production"
|
|
99
|
+
CORS_ORIGINS: list[str] = []
|
|
100
|
+
|
|
101
|
+
settings = Config()
|
|
102
|
+
```
|
|
103
|
+
|
|
104
|
+
## Response Models
|
|
105
|
+
|
|
106
|
+
```python
|
|
107
|
+
# Separate input/output schemas
|
|
108
|
+
class UserCreate(BaseModel):
|
|
109
|
+
username: str
|
|
110
|
+
email: EmailStr
|
|
111
|
+
password: str
|
|
112
|
+
|
|
113
|
+
class UserResponse(BaseModel):
|
|
114
|
+
id: UUID4
|
|
115
|
+
username: str
|
|
116
|
+
email: EmailStr
|
|
117
|
+
created_at: datetime
|
|
118
|
+
|
|
119
|
+
model_config = ConfigDict(from_attributes=True)
|
|
120
|
+
|
|
121
|
+
class UserInDB(UserResponse):
|
|
122
|
+
hashed_password: str # internal only, never expose
|
|
123
|
+
```
|
|
124
|
+
|
|
125
|
+
## Nested Objects
|
|
126
|
+
|
|
127
|
+
```python
|
|
128
|
+
class Author(BaseModel):
|
|
129
|
+
id: UUID4
|
|
130
|
+
name: str
|
|
131
|
+
|
|
132
|
+
class PostResponse(BaseModel):
|
|
133
|
+
id: UUID4
|
|
134
|
+
title: str
|
|
135
|
+
author: Author # nested object
|
|
136
|
+
tags: list[str] = []
|
|
137
|
+
```
|
|
138
|
+
|
|
139
|
+
## Validation Error Messages
|
|
140
|
+
|
|
141
|
+
ValueError in Pydantic schemas becomes 422 Unprocessable Entity:
|
|
142
|
+
|
|
143
|
+
```python
|
|
144
|
+
class ProfileCreate(BaseModel):
|
|
145
|
+
username: str
|
|
146
|
+
|
|
147
|
+
@field_validator("username")
|
|
148
|
+
@classmethod
|
|
149
|
+
def validate_username(cls, v: str) -> str:
|
|
150
|
+
if v.lower() in ["admin", "root", "system"]:
|
|
151
|
+
raise ValueError("Username is reserved")
|
|
152
|
+
return v
|
|
153
|
+
|
|
154
|
+
# Response: {"detail": [{"loc": ["body", "username"], "msg": "Username is reserved", "type": "value_error"}]}
|
|
155
|
+
```
|
|
@@ -0,0 +1,123 @@
|
|
|
1
|
+
---
|
|
2
|
+
name: fastapi-best-practices
|
|
3
|
+
description: FastAPI project structure, async patterns, Pydantic schemas, dependency injection, and database patterns. Use when building FastAPI backends, creating REST APIs, or reviewing Python web service code.
|
|
4
|
+
---
|
|
5
|
+
|
|
6
|
+
# FastAPI Best Practices
|
|
7
|
+
|
|
8
|
+
## Quick Start
|
|
9
|
+
|
|
10
|
+
```python
|
|
11
|
+
# Domain-based structure (recommended for scalable projects)
|
|
12
|
+
src/
|
|
13
|
+
├── auth/
|
|
14
|
+
│ ├── router.py # endpoints
|
|
15
|
+
│ ├── schemas.py # pydantic models
|
|
16
|
+
│ ├── models.py # db models
|
|
17
|
+
│ ├── service.py # business logic
|
|
18
|
+
│ ├── dependencies.py
|
|
19
|
+
│ └── exceptions.py
|
|
20
|
+
├── posts/
|
|
21
|
+
│ └── ...
|
|
22
|
+
├── config.py # global config
|
|
23
|
+
├── database.py # db connection
|
|
24
|
+
└── main.py # FastAPI app init
|
|
25
|
+
```
|
|
26
|
+
|
|
27
|
+
## Core Principles
|
|
28
|
+
|
|
29
|
+
### 1. Async Routes Done Right
|
|
30
|
+
|
|
31
|
+
```python
|
|
32
|
+
# BAD - blocks event loop
|
|
33
|
+
@router.get("/bad")
|
|
34
|
+
async def bad_route():
|
|
35
|
+
time.sleep(10) # blocks everything!
|
|
36
|
+
return {"ok": True}
|
|
37
|
+
|
|
38
|
+
# GOOD - sync route runs in threadpool
|
|
39
|
+
@router.get("/good")
|
|
40
|
+
def good_route():
|
|
41
|
+
time.sleep(10) # runs in separate thread
|
|
42
|
+
return {"ok": True}
|
|
43
|
+
|
|
44
|
+
# BEST - truly async
|
|
45
|
+
@router.get("/best")
|
|
46
|
+
async def best_route():
|
|
47
|
+
await asyncio.sleep(10) # non-blocking
|
|
48
|
+
return {"ok": True}
|
|
49
|
+
```
|
|
50
|
+
|
|
51
|
+
### 2. Pydantic Validation
|
|
52
|
+
|
|
53
|
+
```python
|
|
54
|
+
from pydantic import BaseModel, Field, EmailStr
|
|
55
|
+
|
|
56
|
+
class UserCreate(BaseModel):
|
|
57
|
+
username: str = Field(min_length=1, max_length=128, pattern="^[A-Za-z0-9-_]+$")
|
|
58
|
+
email: EmailStr
|
|
59
|
+
age: int = Field(ge=18, default=None)
|
|
60
|
+
```
|
|
61
|
+
|
|
62
|
+
### 3. Dependencies for Validation
|
|
63
|
+
|
|
64
|
+
```python
|
|
65
|
+
async def valid_post_id(post_id: UUID4) -> dict:
|
|
66
|
+
post = await service.get_by_id(post_id)
|
|
67
|
+
if not post:
|
|
68
|
+
raise PostNotFound()
|
|
69
|
+
return post
|
|
70
|
+
|
|
71
|
+
@router.get("/posts/{post_id}")
|
|
72
|
+
async def get_post(post: dict = Depends(valid_post_id)):
|
|
73
|
+
return post
|
|
74
|
+
```
|
|
75
|
+
|
|
76
|
+
## Detailed Guides
|
|
77
|
+
|
|
78
|
+
| Topic | File | When to Use |
|
|
79
|
+
|-------|------|-------------|
|
|
80
|
+
| Project Structure | [PROJECT-STRUCTURE.md](PROJECT-STRUCTURE.md) | Starting new project, organizing modules |
|
|
81
|
+
| Async Patterns | [ASYNC-PATTERNS.md](ASYNC-PATTERNS.md) | I/O operations, CPU tasks, blocking code |
|
|
82
|
+
| Pydantic Usage | [PYDANTIC-GUIDE.md](PYDANTIC-GUIDE.md) | Schema design, validation, config |
|
|
83
|
+
| Dependencies | [DEPENDENCIES.md](DEPENDENCIES.md) | Auth, validation, reusable logic |
|
|
84
|
+
| Database | [DATABASE.md](DATABASE.md) | SQLAlchemy, migrations, naming |
|
|
85
|
+
|
|
86
|
+
## Import Conventions
|
|
87
|
+
|
|
88
|
+
```python
|
|
89
|
+
# Cross-module imports - use explicit module names
|
|
90
|
+
from src.auth import constants as auth_constants
|
|
91
|
+
from src.notifications import service as notification_service
|
|
92
|
+
from src.posts.constants import ErrorCode as PostsErrorCode
|
|
93
|
+
```
|
|
94
|
+
|
|
95
|
+
## Testing Setup
|
|
96
|
+
|
|
97
|
+
```python
|
|
98
|
+
import pytest
|
|
99
|
+
from httpx import AsyncClient, ASGITransport
|
|
100
|
+
from src.main import app
|
|
101
|
+
|
|
102
|
+
@pytest.fixture
|
|
103
|
+
async def client():
|
|
104
|
+
async with AsyncClient(
|
|
105
|
+
transport=ASGITransport(app=app),
|
|
106
|
+
base_url="http://test"
|
|
107
|
+
) as client:
|
|
108
|
+
yield client
|
|
109
|
+
|
|
110
|
+
@pytest.mark.asyncio
|
|
111
|
+
async def test_endpoint(client: AsyncClient):
|
|
112
|
+
resp = await client.post("/posts")
|
|
113
|
+
assert resp.status_code == 201
|
|
114
|
+
```
|
|
115
|
+
|
|
116
|
+
## Code Quality
|
|
117
|
+
|
|
118
|
+
Use `ruff` for linting and formatting:
|
|
119
|
+
|
|
120
|
+
```bash
|
|
121
|
+
ruff check --fix src
|
|
122
|
+
ruff format src
|
|
123
|
+
```
|
|
@@ -0,0 +1,407 @@
|
|
|
1
|
+
---
|
|
2
|
+
name: react-page-oriented
|
|
3
|
+
description:
|
|
4
|
+
React page-oriented folder architecture. Components live where they're used.
|
|
5
|
+
Structure mirrors UI hierarchy. Use when creating pages, deciding file vs folder,
|
|
6
|
+
organizing components, or setting up React/Next.js projects. Defines co-location
|
|
7
|
+
rules for hooks, styles, tests.
|
|
8
|
+
license: MIT
|
|
9
|
+
metadata:
|
|
10
|
+
author: HoangThang
|
|
11
|
+
version: '2.0.0'
|
|
12
|
+
---
|
|
13
|
+
|
|
14
|
+
# React Page-Oriented Architecture
|
|
15
|
+
|
|
16
|
+
## Philosophy
|
|
17
|
+
|
|
18
|
+
**Components live where they're used. Structure mirrors UI hierarchy.**
|
|
19
|
+
|
|
20
|
+
- Child components belong IN their parent folder (not in a separate `components/` subfolder)
|
|
21
|
+
- Shared components are organized by LEVEL (page-level vs app-level)
|
|
22
|
+
- No premature abstraction - extract only when truly needed
|
|
23
|
+
|
|
24
|
+
> **Component Patterns:** This skill covers **folder/file organization only**.
|
|
25
|
+
> For component composition patterns (compound components, context, state management),
|
|
26
|
+
> follow the **vercel-composition-patterns** skill.
|
|
27
|
+
|
|
28
|
+
---
|
|
29
|
+
|
|
30
|
+
## Core Rules
|
|
31
|
+
|
|
32
|
+
### Rule 1: Page as Root
|
|
33
|
+
|
|
34
|
+
Every feature starts with a Page component as the root.
|
|
35
|
+
|
|
36
|
+
```
|
|
37
|
+
src/pages/
|
|
38
|
+
├── ProductPage/
|
|
39
|
+
├── OrderPage/
|
|
40
|
+
├── CustomerPage/
|
|
41
|
+
└── DashboardPage/
|
|
42
|
+
```
|
|
43
|
+
|
|
44
|
+
### Rule 2: Children Live IN Parent Folder
|
|
45
|
+
|
|
46
|
+
**Child components go DIRECTLY in parent folder** - NOT in a `components/` subfolder.
|
|
47
|
+
|
|
48
|
+
```
|
|
49
|
+
❌ DON'T: Separate components folder
|
|
50
|
+
ChatFrame/
|
|
51
|
+
├── ChatFrame.tsx
|
|
52
|
+
├── components/ # ❌ No! Don't create this
|
|
53
|
+
│ ├── ChatInput.tsx
|
|
54
|
+
│ └── ChatMessages.tsx
|
|
55
|
+
└── context/ # ❌ No! Don't create this
|
|
56
|
+
└── ChatContext.tsx
|
|
57
|
+
|
|
58
|
+
✅ DO: Children directly in parent
|
|
59
|
+
ChatFrame/
|
|
60
|
+
├── ChatFrame.tsx # Parent component
|
|
61
|
+
├── ChatFrame.css # Parent styles
|
|
62
|
+
├── ChatContext.tsx # Context for this component
|
|
63
|
+
├── ChatInput.tsx # Child component
|
|
64
|
+
├── ChatMessages.tsx # Child component
|
|
65
|
+
└── useChatFrame.ts # Hook for this component
|
|
66
|
+
```
|
|
67
|
+
|
|
68
|
+
### Rule 3: File vs Folder Decision
|
|
69
|
+
|
|
70
|
+
**File (`.tsx`)** - Component has NO children or related files
|
|
71
|
+
|
|
72
|
+
```
|
|
73
|
+
StatusBadge.tsx ✅ Simple, no children
|
|
74
|
+
LoadingSpinner.tsx ✅ Static UI
|
|
75
|
+
```
|
|
76
|
+
|
|
77
|
+
**Folder** - Component HAS children OR related files (css, hook, context)
|
|
78
|
+
|
|
79
|
+
```
|
|
80
|
+
ChatFrame/ ✅ Has children (ChatInput, ChatMessages)
|
|
81
|
+
├── ChatFrame.tsx
|
|
82
|
+
├── ChatFrame.css
|
|
83
|
+
├── ChatInput.tsx
|
|
84
|
+
└── ChatMessages.tsx
|
|
85
|
+
|
|
86
|
+
Avatar/ ✅ Has related files (css)
|
|
87
|
+
├── Avatar.tsx
|
|
88
|
+
└── Avatar.css
|
|
89
|
+
```
|
|
90
|
+
|
|
91
|
+
### Rule 4: Shared Components by Level
|
|
92
|
+
|
|
93
|
+
Components shared within a scope stay at that scope's root:
|
|
94
|
+
|
|
95
|
+
| Scope | Location | Example |
|
|
96
|
+
|-------|----------|---------|
|
|
97
|
+
| Used by 1 component | Inside that component's folder | `ChatFrame/ChatInput.tsx` |
|
|
98
|
+
| Used by siblings in same page | Page folder root | `ProductPage/StatusBadge.tsx` |
|
|
99
|
+
| Used across multiple pages | `src/components/` | `components/Button.tsx` |
|
|
100
|
+
| Used app-wide (layout) | `src/layouts/` | `layouts/Sidebar.tsx` |
|
|
101
|
+
|
|
102
|
+
**Example - Page-level shared component:**
|
|
103
|
+
|
|
104
|
+
```
|
|
105
|
+
ProductPage/
|
|
106
|
+
├── ProductPage.tsx
|
|
107
|
+
├── StatusBadge.tsx # ✅ Shared by ProductList AND ProductDetail
|
|
108
|
+
├── ProductList/
|
|
109
|
+
│ ├── ProductList.tsx # Uses StatusBadge
|
|
110
|
+
│ └── ProductRow.tsx
|
|
111
|
+
└── ProductDetail/
|
|
112
|
+
└── ProductDetail.tsx # Also uses StatusBadge
|
|
113
|
+
```
|
|
114
|
+
|
|
115
|
+
### Rule 5: No index.tsx for Re-export
|
|
116
|
+
|
|
117
|
+
❌ **Never do this:**
|
|
118
|
+
```
|
|
119
|
+
ProductList/
|
|
120
|
+
├── index.tsx # export { ProductList } from './ProductList'
|
|
121
|
+
└── ProductList.tsx
|
|
122
|
+
```
|
|
123
|
+
|
|
124
|
+
✅ **Always import directly:**
|
|
125
|
+
```tsx
|
|
126
|
+
import { ProductList } from './ProductList/ProductList'
|
|
127
|
+
import { Button } from '@/components/Button'
|
|
128
|
+
```
|
|
129
|
+
|
|
130
|
+
### Rule 6: Maximum Nesting Depth = 4
|
|
131
|
+
|
|
132
|
+
```
|
|
133
|
+
pages/ProductPage/ProductList/ProductRow/RowActions.tsx
|
|
134
|
+
│ │ │ │ └── Level 4 (MAX)
|
|
135
|
+
│ │ │ └── Level 3
|
|
136
|
+
│ │ └── Level 2
|
|
137
|
+
│ └── Level 1
|
|
138
|
+
└── Root
|
|
139
|
+
```
|
|
140
|
+
|
|
141
|
+
If deeper → Flatten or move to `components/`
|
|
142
|
+
|
|
143
|
+
---
|
|
144
|
+
|
|
145
|
+
## Detailed Structure Example
|
|
146
|
+
|
|
147
|
+
```
|
|
148
|
+
src/
|
|
149
|
+
├── pages/
|
|
150
|
+
│ ├── ChatPage/
|
|
151
|
+
│ │ ├── ChatPage.tsx # Page entry
|
|
152
|
+
│ │ ├── ChatPage.css
|
|
153
|
+
│ │ │
|
|
154
|
+
│ │ ├── ChatFrame/ # Main chat UI
|
|
155
|
+
│ │ │ ├── ChatFrame.tsx # Parent component
|
|
156
|
+
│ │ │ ├── ChatFrame.css
|
|
157
|
+
│ │ │ ├── ChatContext.tsx # Context lives WITH provider
|
|
158
|
+
│ │ │ ├── useChatFrame.ts # Hook lives WITH component
|
|
159
|
+
│ │ │ ├── ChatHeader.tsx # Child - simple file
|
|
160
|
+
│ │ │ ├── ChatInput.tsx # Child - simple file
|
|
161
|
+
│ │ │ ├── ChatMessages/ # Child - has own children
|
|
162
|
+
│ │ │ │ ├── ChatMessages.tsx
|
|
163
|
+
│ │ │ │ ├── ChatMessages.css
|
|
164
|
+
│ │ │ │ ├── MessageItem.tsx # Grandchild
|
|
165
|
+
│ │ │ │ └── TypingIndicator.tsx
|
|
166
|
+
│ │ │ └── ChatError.tsx # Child - simple file
|
|
167
|
+
│ │ │
|
|
168
|
+
│ │ └── SessionList/ # Sidebar component
|
|
169
|
+
│ │ ├── SessionList.tsx
|
|
170
|
+
│ │ ├── SessionItem.tsx
|
|
171
|
+
│ │ └── useSessionList.ts
|
|
172
|
+
│ │
|
|
173
|
+
│ ├── ProductPage/
|
|
174
|
+
│ │ ├── ProductPage.tsx
|
|
175
|
+
│ │ ├── StatusBadge.tsx # ✅ Shared within this page only
|
|
176
|
+
│ │ │
|
|
177
|
+
│ │ ├── ProductList/
|
|
178
|
+
│ │ │ ├── ProductList.tsx
|
|
179
|
+
│ │ │ ├── ProductRow.tsx # Uses parent's StatusBadge
|
|
180
|
+
│ │ │ └── useProductList.ts
|
|
181
|
+
│ │ │
|
|
182
|
+
│ │ └── ProductDetail/
|
|
183
|
+
│ │ ├── ProductDetail.tsx # Uses parent's StatusBadge
|
|
184
|
+
│ │ ├── ProductGallery/
|
|
185
|
+
│ │ │ ├── ProductGallery.tsx
|
|
186
|
+
│ │ │ ├── Thumbnail.tsx
|
|
187
|
+
│ │ │ └── Lightbox.tsx
|
|
188
|
+
│ │ └── ProductReviews/
|
|
189
|
+
│ │ ├── ProductReviews.tsx
|
|
190
|
+
│ │ ├── ReviewItem.tsx
|
|
191
|
+
│ │ └── ReviewForm.tsx
|
|
192
|
+
│ │
|
|
193
|
+
│ └── OrderPage/
|
|
194
|
+
│ ├── OrderPage.tsx
|
|
195
|
+
│ └── OrderList/
|
|
196
|
+
│ ├── OrderList.tsx
|
|
197
|
+
│ └── OrderRow.tsx
|
|
198
|
+
│
|
|
199
|
+
├── components/ # ✅ Cross-page shared ONLY
|
|
200
|
+
│ ├── Button.tsx # Simple - file
|
|
201
|
+
│ ├── Input.tsx
|
|
202
|
+
│ ├── Modal/ # Has children - folder
|
|
203
|
+
│ │ ├── Modal.tsx
|
|
204
|
+
│ │ ├── Modal.css
|
|
205
|
+
│ │ ├── ModalHeader.tsx
|
|
206
|
+
│ │ ├── ModalBody.tsx
|
|
207
|
+
│ │ └── ModalFooter.tsx
|
|
208
|
+
│ ├── Avatar/
|
|
209
|
+
│ │ ├── Avatar.tsx
|
|
210
|
+
│ │ └── Avatar.css
|
|
211
|
+
│ └── MarkdownRenderer/
|
|
212
|
+
│ ├── MarkdownRenderer.tsx
|
|
213
|
+
│ └── MarkdownRenderer.css
|
|
214
|
+
│
|
|
215
|
+
├── layouts/
|
|
216
|
+
│ ├── MainLayout.tsx
|
|
217
|
+
│ ├── Sidebar.tsx
|
|
218
|
+
│ └── Header.tsx
|
|
219
|
+
│
|
|
220
|
+
├── hooks/ # ✅ App-wide hooks ONLY
|
|
221
|
+
│ ├── useAuth.ts
|
|
222
|
+
│ └── useApi.ts
|
|
223
|
+
│
|
|
224
|
+
├── store/ # State management
|
|
225
|
+
│ ├── chatStore.ts
|
|
226
|
+
│ └── sessionStore.ts
|
|
227
|
+
│
|
|
228
|
+
├── services/ # API calls
|
|
229
|
+
│ └── AgentClient.ts
|
|
230
|
+
│
|
|
231
|
+
├── types/ # Global types
|
|
232
|
+
│ ├── chat.types.ts
|
|
233
|
+
│ └── session.types.ts
|
|
234
|
+
│
|
|
235
|
+
└── App.tsx
|
|
236
|
+
```
|
|
237
|
+
|
|
238
|
+
---
|
|
239
|
+
|
|
240
|
+
## Co-location Patterns
|
|
241
|
+
|
|
242
|
+
### Everything Related Lives Together
|
|
243
|
+
|
|
244
|
+
```
|
|
245
|
+
ChatFrame/
|
|
246
|
+
├── ChatFrame.tsx # Component
|
|
247
|
+
├── ChatFrame.css # Styles
|
|
248
|
+
├── ChatFrame.test.tsx # Tests
|
|
249
|
+
├── ChatFrame.types.ts # Types (if complex)
|
|
250
|
+
├── ChatContext.tsx # Context for this subtree
|
|
251
|
+
├── useChatFrame.ts # Logic hook
|
|
252
|
+
├── ChatHeader.tsx # Child component
|
|
253
|
+
├── ChatInput.tsx # Child component
|
|
254
|
+
└── ChatMessages/ # Complex child → folder
|
|
255
|
+
├── ChatMessages.tsx
|
|
256
|
+
└── MessageItem.tsx
|
|
257
|
+
```
|
|
258
|
+
|
|
259
|
+
### Context Lives with Provider
|
|
260
|
+
|
|
261
|
+
Context should be in the same folder as the component that provides it:
|
|
262
|
+
|
|
263
|
+
```
|
|
264
|
+
❌ DON'T:
|
|
265
|
+
src/
|
|
266
|
+
├── context/
|
|
267
|
+
│ └── ChatContext.tsx # Far from provider
|
|
268
|
+
└── pages/ChatPage/ChatFrame/ChatFrame.tsx
|
|
269
|
+
|
|
270
|
+
✅ DO:
|
|
271
|
+
src/pages/ChatPage/
|
|
272
|
+
└── ChatFrame/
|
|
273
|
+
├── ChatFrame.tsx # Provides context
|
|
274
|
+
└── ChatContext.tsx # Lives here
|
|
275
|
+
```
|
|
276
|
+
|
|
277
|
+
### Hooks Live with Components
|
|
278
|
+
|
|
279
|
+
```
|
|
280
|
+
❌ DON'T:
|
|
281
|
+
src/
|
|
282
|
+
├── hooks/
|
|
283
|
+
│ └── useChatFrame.ts # Only used by ChatFrame
|
|
284
|
+
└── pages/ChatPage/ChatFrame/ChatFrame.tsx
|
|
285
|
+
|
|
286
|
+
✅ DO:
|
|
287
|
+
src/pages/ChatPage/
|
|
288
|
+
└── ChatFrame/
|
|
289
|
+
├── ChatFrame.tsx
|
|
290
|
+
└── useChatFrame.ts # Lives here
|
|
291
|
+
```
|
|
292
|
+
|
|
293
|
+
---
|
|
294
|
+
|
|
295
|
+
## When to Extract to `components/`
|
|
296
|
+
|
|
297
|
+
Extract when **ALL** apply:
|
|
298
|
+
|
|
299
|
+
- [ ] Used by 2+ different pages
|
|
300
|
+
- [ ] Truly generic (no page-specific logic)
|
|
301
|
+
- [ ] Stable API (props won't change often)
|
|
302
|
+
- [ ] Self-contained (minimal dependencies)
|
|
303
|
+
|
|
304
|
+
**Do NOT extract when:**
|
|
305
|
+
|
|
306
|
+
- Used by only 1 page → Keep in page folder
|
|
307
|
+
- Used by siblings in same page → Keep at page root
|
|
308
|
+
- Contains page-specific logic → Keep local
|
|
309
|
+
- Still evolving → Keep local, extract later
|
|
310
|
+
|
|
311
|
+
---
|
|
312
|
+
|
|
313
|
+
## Import Order
|
|
314
|
+
|
|
315
|
+
```tsx
|
|
316
|
+
// 1. React
|
|
317
|
+
import { useState, useEffect } from 'react'
|
|
318
|
+
|
|
319
|
+
// 2. External libraries
|
|
320
|
+
import { useQuery } from '@tanstack/react-query'
|
|
321
|
+
|
|
322
|
+
// 3. Absolute imports (shared)
|
|
323
|
+
import { Button } from '@/components/Button'
|
|
324
|
+
import { useAuth } from '@/hooks/useAuth'
|
|
325
|
+
|
|
326
|
+
// 4. Relative imports (local - same page/component tree)
|
|
327
|
+
import { ChatInput } from './ChatInput'
|
|
328
|
+
import { useChatFrame } from './useChatFrame'
|
|
329
|
+
|
|
330
|
+
// 5. Types
|
|
331
|
+
import type { Message } from '@/types/chat.types'
|
|
332
|
+
|
|
333
|
+
// 6. Styles
|
|
334
|
+
import './ChatFrame.css'
|
|
335
|
+
```
|
|
336
|
+
|
|
337
|
+
---
|
|
338
|
+
|
|
339
|
+
## Anti-Patterns
|
|
340
|
+
|
|
341
|
+
### ❌ Separate `components/` folder inside pages
|
|
342
|
+
|
|
343
|
+
```
|
|
344
|
+
❌ DON'T:
|
|
345
|
+
pages/ChatPage/
|
|
346
|
+
├── ChatPage.tsx
|
|
347
|
+
├── components/ # ❌ Don't create this!
|
|
348
|
+
│ ├── ChatFrame.tsx
|
|
349
|
+
│ └── ChatInput.tsx
|
|
350
|
+
└── context/ # ❌ Don't create this!
|
|
351
|
+
└── ChatContext.tsx
|
|
352
|
+
|
|
353
|
+
✅ DO:
|
|
354
|
+
pages/ChatPage/
|
|
355
|
+
├── ChatPage.tsx
|
|
356
|
+
├── ChatFrame/ # Children in parent folder
|
|
357
|
+
│ ├── ChatFrame.tsx
|
|
358
|
+
│ ├── ChatContext.tsx # Context with component
|
|
359
|
+
│ └── ChatInput.tsx
|
|
360
|
+
```
|
|
361
|
+
|
|
362
|
+
### ❌ Barrel Files
|
|
363
|
+
|
|
364
|
+
```tsx
|
|
365
|
+
// ❌ DON'T
|
|
366
|
+
import { ChatFrame, ChatInput } from '@/pages/ChatPage'
|
|
367
|
+
|
|
368
|
+
// ✅ DO
|
|
369
|
+
import { ChatFrame } from '@/pages/ChatPage/ChatFrame/ChatFrame'
|
|
370
|
+
```
|
|
371
|
+
|
|
372
|
+
### ❌ Premature Extraction
|
|
373
|
+
|
|
374
|
+
```
|
|
375
|
+
❌ DON'T: Extract before needed
|
|
376
|
+
components/
|
|
377
|
+
└── ChatStatusBadge.tsx # Only used in ChatPage!
|
|
378
|
+
|
|
379
|
+
✅ DO: Keep local
|
|
380
|
+
pages/ChatPage/StatusBadge.tsx
|
|
381
|
+
```
|
|
382
|
+
|
|
383
|
+
---
|
|
384
|
+
|
|
385
|
+
## Quick Reference
|
|
386
|
+
|
|
387
|
+
```
|
|
388
|
+
Q: Where does child component go?
|
|
389
|
+
A: Directly in parent folder. NO separate components/ subfolder.
|
|
390
|
+
|
|
391
|
+
Q: Where does context go?
|
|
392
|
+
A: Same folder as the component that provides it.
|
|
393
|
+
|
|
394
|
+
Q: Where does hook go?
|
|
395
|
+
A: Same folder as the component that uses it (if used by 1).
|
|
396
|
+
In hooks/ only if used app-wide.
|
|
397
|
+
|
|
398
|
+
Q: File or Folder?
|
|
399
|
+
A: Has children OR related files (css, hook)? → Folder
|
|
400
|
+
Just a simple component? → File
|
|
401
|
+
|
|
402
|
+
Q: When to extract to components/?
|
|
403
|
+
A: Only when 2+ different pages need it.
|
|
404
|
+
|
|
405
|
+
Q: Shared within one page?
|
|
406
|
+
A: Keep at that page's root folder.
|
|
407
|
+
```
|
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
# react-page-oriented
|
|
2
|
+
|
|
3
|
+
React page-oriented architecture patterns. Structure mirrors UI hierarchy with components living where they're used.
|
|
4
|
+
|
|
5
|
+
Use when:
|
|
6
|
+
- Creating new React pages or components
|
|
7
|
+
- Refactoring React folder structure
|
|
8
|
+
- Deciding where to place a new component
|
|
9
|
+
- Reviewing React project architecture
|
|
10
|
+
- Questions about file vs folder for components
|
|
11
|
+
- Organizing page-specific vs shared components
|
|
12
|
+
- Setting up new React/Next.js projects
|
|
File without changes
|