@pageai/ralph-loop 1.0.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/.agent/PROMPT.md +58 -0
- package/.agent/STEERING.md +3 -0
- package/.agent/logs/LOG.md +13 -0
- package/.agent/prd/.gitkeep +0 -0
- package/.agent/screenshots/.gitkeep +0 -0
- package/.agent/skills/component-refactoring/SKILL.md +247 -0
- package/.agent/skills/component-refactoring/references/complexity-patterns.md +485 -0
- package/.agent/skills/component-refactoring/references/component-splitting.md +419 -0
- package/.agent/skills/component-refactoring/references/hook-extraction.md +317 -0
- package/.agent/skills/e2e-tester/SKILL.md +595 -0
- package/.agent/skills/frontend-code-review/SKILL.md +73 -0
- package/.agent/skills/frontend-code-review/references/code-quality.md +28 -0
- package/.agent/skills/frontend-code-review/references/performance.md +36 -0
- package/.agent/skills/frontend-testing/SKILL.md +316 -0
- package/.agent/skills/frontend-testing/assets/component-test.template.tsx +293 -0
- package/.agent/skills/frontend-testing/assets/hook-test.template.ts +207 -0
- package/.agent/skills/frontend-testing/assets/utility-test.template.ts +154 -0
- package/.agent/skills/frontend-testing/references/async-testing.md +345 -0
- package/.agent/skills/frontend-testing/references/checklist.md +188 -0
- package/.agent/skills/frontend-testing/references/common-patterns.md +449 -0
- package/.agent/skills/frontend-testing/references/mocking.md +289 -0
- package/.agent/skills/frontend-testing/references/workflow.md +265 -0
- package/.agent/skills/prd-creator/JSON.md +613 -0
- package/.agent/skills/prd-creator/PRD.md +196 -0
- package/.agent/skills/prd-creator/SKILL.md +143 -0
- package/.agent/skills/skill-creator/SKILL.md +355 -0
- package/.agent/skills/skill-creator/references/output-patterns.md +86 -0
- package/.agent/skills/skill-creator/references/workflows.md +28 -0
- package/.agent/skills/skill-creator/scripts/init_skill.py +300 -0
- package/.agent/skills/skill-creator/scripts/package_skill.py +110 -0
- package/.agent/skills/vercel-react-best-practices/AGENTS.md +2249 -0
- package/.agent/skills/vercel-react-best-practices/SKILL.md +125 -0
- package/.agent/skills/vercel-react-best-practices/rules/advanced-event-handler-refs.md +55 -0
- package/.agent/skills/vercel-react-best-practices/rules/advanced-use-latest.md +49 -0
- package/.agent/skills/vercel-react-best-practices/rules/async-api-routes.md +38 -0
- package/.agent/skills/vercel-react-best-practices/rules/async-defer-await.md +80 -0
- package/.agent/skills/vercel-react-best-practices/rules/async-dependencies.md +36 -0
- package/.agent/skills/vercel-react-best-practices/rules/async-parallel.md +28 -0
- package/.agent/skills/vercel-react-best-practices/rules/async-suspense-boundaries.md +99 -0
- package/.agent/skills/vercel-react-best-practices/rules/bundle-barrel-imports.md +59 -0
- package/.agent/skills/vercel-react-best-practices/rules/bundle-conditional.md +31 -0
- package/.agent/skills/vercel-react-best-practices/rules/bundle-defer-third-party.md +49 -0
- package/.agent/skills/vercel-react-best-practices/rules/bundle-dynamic-imports.md +35 -0
- package/.agent/skills/vercel-react-best-practices/rules/bundle-preload.md +50 -0
- package/.agent/skills/vercel-react-best-practices/rules/client-event-listeners.md +74 -0
- package/.agent/skills/vercel-react-best-practices/rules/client-swr-dedup.md +56 -0
- package/.agent/skills/vercel-react-best-practices/rules/js-batch-dom-css.md +82 -0
- package/.agent/skills/vercel-react-best-practices/rules/js-cache-function-results.md +80 -0
- package/.agent/skills/vercel-react-best-practices/rules/js-cache-property-access.md +28 -0
- package/.agent/skills/vercel-react-best-practices/rules/js-cache-storage.md +70 -0
- package/.agent/skills/vercel-react-best-practices/rules/js-combine-iterations.md +32 -0
- package/.agent/skills/vercel-react-best-practices/rules/js-early-exit.md +50 -0
- package/.agent/skills/vercel-react-best-practices/rules/js-hoist-regexp.md +45 -0
- package/.agent/skills/vercel-react-best-practices/rules/js-index-maps.md +37 -0
- package/.agent/skills/vercel-react-best-practices/rules/js-length-check-first.md +49 -0
- package/.agent/skills/vercel-react-best-practices/rules/js-min-max-loop.md +82 -0
- package/.agent/skills/vercel-react-best-practices/rules/js-set-map-lookups.md +24 -0
- package/.agent/skills/vercel-react-best-practices/rules/js-tosorted-immutable.md +57 -0
- package/.agent/skills/vercel-react-best-practices/rules/rendering-activity.md +26 -0
- package/.agent/skills/vercel-react-best-practices/rules/rendering-animate-svg-wrapper.md +47 -0
- package/.agent/skills/vercel-react-best-practices/rules/rendering-conditional-render.md +40 -0
- package/.agent/skills/vercel-react-best-practices/rules/rendering-content-visibility.md +38 -0
- package/.agent/skills/vercel-react-best-practices/rules/rendering-hoist-jsx.md +46 -0
- package/.agent/skills/vercel-react-best-practices/rules/rendering-hydration-no-flicker.md +82 -0
- package/.agent/skills/vercel-react-best-practices/rules/rendering-svg-precision.md +28 -0
- package/.agent/skills/vercel-react-best-practices/rules/rerender-defer-reads.md +39 -0
- package/.agent/skills/vercel-react-best-practices/rules/rerender-dependencies.md +45 -0
- package/.agent/skills/vercel-react-best-practices/rules/rerender-derived-state.md +29 -0
- package/.agent/skills/vercel-react-best-practices/rules/rerender-functional-setstate.md +74 -0
- package/.agent/skills/vercel-react-best-practices/rules/rerender-lazy-state-init.md +58 -0
- package/.agent/skills/vercel-react-best-practices/rules/rerender-memo.md +44 -0
- package/.agent/skills/vercel-react-best-practices/rules/rerender-transitions.md +40 -0
- package/.agent/skills/vercel-react-best-practices/rules/server-after-nonblocking.md +73 -0
- package/.agent/skills/vercel-react-best-practices/rules/server-cache-lru.md +41 -0
- package/.agent/skills/vercel-react-best-practices/rules/server-cache-react.md +26 -0
- package/.agent/skills/vercel-react-best-practices/rules/server-parallel-fetching.md +79 -0
- package/.agent/skills/vercel-react-best-practices/rules/server-serialization.md +38 -0
- package/.agent/skills/vitest-best-practices/AGENTS.md +84 -0
- package/.agent/skills/vitest-best-practices/SKILL.md +130 -0
- package/.agent/skills/vitest-best-practices/references/aaa-pattern.md +260 -0
- package/.agent/skills/vitest-best-practices/references/assertions.md +393 -0
- package/.agent/skills/vitest-best-practices/references/async-testing.md +454 -0
- package/.agent/skills/vitest-best-practices/references/error-handling.md +382 -0
- package/.agent/skills/vitest-best-practices/references/organization.md +212 -0
- package/.agent/skills/vitest-best-practices/references/parameterized-tests.md +297 -0
- package/.agent/skills/vitest-best-practices/references/performance.md +528 -0
- package/.agent/skills/vitest-best-practices/references/snapshot-testing.md +483 -0
- package/.agent/skills/vitest-best-practices/references/test-doubles.md +499 -0
- package/.agent/skills/vitest-best-practices/references/vitest-features.md +529 -0
- package/.agent/skills/web-design-guidelines/SKILL.md +39 -0
- package/.agent/tasks/.gitkeep +0 -0
- package/.agent/tasks.json +1 -0
- package/.claude/agents/code-reviewer.md +172 -0
- package/.claude/commands/aw.md +50 -0
- package/.claude/hooks/play-sound.js +87 -0
- package/.claude/hooks/pre-tool-use.js +40 -0
- package/.claude/settings.json +54 -0
- package/.claude/settings.local.json +13 -0
- package/.mcp.json +31 -0
- package/AGENTS.md +44 -0
- package/CLAUDE.md +1 -0
- package/README.md +236 -0
- package/bin/cli.js +156 -0
- package/bin/lib/copy.js +149 -0
- package/bin/lib/display.js +137 -0
- package/package.json +65 -0
- package/ralph.sh +333 -0
- package/scripts/lib/args.sh +44 -0
- package/scripts/lib/cleanup.sh +53 -0
- package/scripts/lib/constants.sh +25 -0
- package/scripts/lib/display.sh +196 -0
- package/scripts/lib/logging.sh +30 -0
- package/scripts/lib/notify.sh +41 -0
- package/scripts/lib/output.sh +147 -0
- package/scripts/lib/preflight.sh +57 -0
- package/scripts/lib/preview.sh +77 -0
- package/scripts/lib/promise.sh +76 -0
- package/scripts/lib/spinner.sh +85 -0
- package/scripts/lib/terminal.sh +57 -0
- package/scripts/lib/timing.sh +223 -0
|
@@ -0,0 +1,58 @@
|
|
|
1
|
+
---
|
|
2
|
+
title: Use Lazy State Initialization
|
|
3
|
+
impact: MEDIUM
|
|
4
|
+
impactDescription: wasted computation on every render
|
|
5
|
+
tags: react, hooks, useState, performance, initialization
|
|
6
|
+
---
|
|
7
|
+
|
|
8
|
+
## Use Lazy State Initialization
|
|
9
|
+
|
|
10
|
+
Pass a function to `useState` for expensive initial values. Without the function form, the initializer runs on every render even though the value is only used once.
|
|
11
|
+
|
|
12
|
+
**Incorrect (runs on every render):**
|
|
13
|
+
|
|
14
|
+
```tsx
|
|
15
|
+
function FilteredList({ items }: { items: Item[] }) {
|
|
16
|
+
// buildSearchIndex() runs on EVERY render, even after initialization
|
|
17
|
+
const [searchIndex, setSearchIndex] = useState(buildSearchIndex(items))
|
|
18
|
+
const [query, setQuery] = useState('')
|
|
19
|
+
|
|
20
|
+
// When query changes, buildSearchIndex runs again unnecessarily
|
|
21
|
+
return <SearchResults index={searchIndex} query={query} />
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
function UserProfile() {
|
|
25
|
+
// JSON.parse runs on every render
|
|
26
|
+
const [settings, setSettings] = useState(
|
|
27
|
+
JSON.parse(localStorage.getItem('settings') || '{}')
|
|
28
|
+
)
|
|
29
|
+
|
|
30
|
+
return <SettingsForm settings={settings} onChange={setSettings} />
|
|
31
|
+
}
|
|
32
|
+
```
|
|
33
|
+
|
|
34
|
+
**Correct (runs only once):**
|
|
35
|
+
|
|
36
|
+
```tsx
|
|
37
|
+
function FilteredList({ items }: { items: Item[] }) {
|
|
38
|
+
// buildSearchIndex() runs ONLY on initial render
|
|
39
|
+
const [searchIndex, setSearchIndex] = useState(() => buildSearchIndex(items))
|
|
40
|
+
const [query, setQuery] = useState('')
|
|
41
|
+
|
|
42
|
+
return <SearchResults index={searchIndex} query={query} />
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
function UserProfile() {
|
|
46
|
+
// JSON.parse runs only on initial render
|
|
47
|
+
const [settings, setSettings] = useState(() => {
|
|
48
|
+
const stored = localStorage.getItem('settings')
|
|
49
|
+
return stored ? JSON.parse(stored) : {}
|
|
50
|
+
})
|
|
51
|
+
|
|
52
|
+
return <SettingsForm settings={settings} onChange={setSettings} />
|
|
53
|
+
}
|
|
54
|
+
```
|
|
55
|
+
|
|
56
|
+
Use lazy initialization when computing initial values from localStorage/sessionStorage, building data structures (indexes, maps), reading from the DOM, or performing heavy transformations.
|
|
57
|
+
|
|
58
|
+
For simple primitives (`useState(0)`), direct references (`useState(props.value)`), or cheap literals (`useState({})`), the function form is unnecessary.
|
|
@@ -0,0 +1,44 @@
|
|
|
1
|
+
---
|
|
2
|
+
title: Extract to Memoized Components
|
|
3
|
+
impact: MEDIUM
|
|
4
|
+
impactDescription: enables early returns
|
|
5
|
+
tags: rerender, memo, useMemo, optimization
|
|
6
|
+
---
|
|
7
|
+
|
|
8
|
+
## Extract to Memoized Components
|
|
9
|
+
|
|
10
|
+
Extract expensive work into memoized components to enable early returns before computation.
|
|
11
|
+
|
|
12
|
+
**Incorrect (computes avatar even when loading):**
|
|
13
|
+
|
|
14
|
+
```tsx
|
|
15
|
+
function Profile({ user, loading }: Props) {
|
|
16
|
+
const avatar = useMemo(() => {
|
|
17
|
+
const id = computeAvatarId(user)
|
|
18
|
+
return <Avatar id={id} />
|
|
19
|
+
}, [user])
|
|
20
|
+
|
|
21
|
+
if (loading) return <Skeleton />
|
|
22
|
+
return <div>{avatar}</div>
|
|
23
|
+
}
|
|
24
|
+
```
|
|
25
|
+
|
|
26
|
+
**Correct (skips computation when loading):**
|
|
27
|
+
|
|
28
|
+
```tsx
|
|
29
|
+
const UserAvatar = memo(function UserAvatar({ user }: { user: User }) {
|
|
30
|
+
const id = useMemo(() => computeAvatarId(user), [user])
|
|
31
|
+
return <Avatar id={id} />
|
|
32
|
+
})
|
|
33
|
+
|
|
34
|
+
function Profile({ user, loading }: Props) {
|
|
35
|
+
if (loading) return <Skeleton />
|
|
36
|
+
return (
|
|
37
|
+
<div>
|
|
38
|
+
<UserAvatar user={user} />
|
|
39
|
+
</div>
|
|
40
|
+
)
|
|
41
|
+
}
|
|
42
|
+
```
|
|
43
|
+
|
|
44
|
+
**Note:** If your project has [React Compiler](https://react.dev/learn/react-compiler) enabled, manual memoization with `memo()` and `useMemo()` is not necessary. The compiler automatically optimizes re-renders.
|
|
@@ -0,0 +1,40 @@
|
|
|
1
|
+
---
|
|
2
|
+
title: Use Transitions for Non-Urgent Updates
|
|
3
|
+
impact: MEDIUM
|
|
4
|
+
impactDescription: maintains UI responsiveness
|
|
5
|
+
tags: rerender, transitions, startTransition, performance
|
|
6
|
+
---
|
|
7
|
+
|
|
8
|
+
## Use Transitions for Non-Urgent Updates
|
|
9
|
+
|
|
10
|
+
Mark frequent, non-urgent state updates as transitions to maintain UI responsiveness.
|
|
11
|
+
|
|
12
|
+
**Incorrect (blocks UI on every scroll):**
|
|
13
|
+
|
|
14
|
+
```tsx
|
|
15
|
+
function ScrollTracker() {
|
|
16
|
+
const [scrollY, setScrollY] = useState(0)
|
|
17
|
+
useEffect(() => {
|
|
18
|
+
const handler = () => setScrollY(window.scrollY)
|
|
19
|
+
window.addEventListener('scroll', handler, { passive: true })
|
|
20
|
+
return () => window.removeEventListener('scroll', handler)
|
|
21
|
+
}, [])
|
|
22
|
+
}
|
|
23
|
+
```
|
|
24
|
+
|
|
25
|
+
**Correct (non-blocking updates):**
|
|
26
|
+
|
|
27
|
+
```tsx
|
|
28
|
+
import { startTransition } from 'react'
|
|
29
|
+
|
|
30
|
+
function ScrollTracker() {
|
|
31
|
+
const [scrollY, setScrollY] = useState(0)
|
|
32
|
+
useEffect(() => {
|
|
33
|
+
const handler = () => {
|
|
34
|
+
startTransition(() => setScrollY(window.scrollY))
|
|
35
|
+
}
|
|
36
|
+
window.addEventListener('scroll', handler, { passive: true })
|
|
37
|
+
return () => window.removeEventListener('scroll', handler)
|
|
38
|
+
}, [])
|
|
39
|
+
}
|
|
40
|
+
```
|
|
@@ -0,0 +1,73 @@
|
|
|
1
|
+
---
|
|
2
|
+
title: Use after() for Non-Blocking Operations
|
|
3
|
+
impact: MEDIUM
|
|
4
|
+
impactDescription: faster response times
|
|
5
|
+
tags: server, async, logging, analytics, side-effects
|
|
6
|
+
---
|
|
7
|
+
|
|
8
|
+
## Use after() for Non-Blocking Operations
|
|
9
|
+
|
|
10
|
+
Use Next.js's `after()` to schedule work that should execute after a response is sent. This prevents logging, analytics, and other side effects from blocking the response.
|
|
11
|
+
|
|
12
|
+
**Incorrect (blocks response):**
|
|
13
|
+
|
|
14
|
+
```tsx
|
|
15
|
+
import { logUserAction } from '@/app/utils'
|
|
16
|
+
|
|
17
|
+
export async function POST(request: Request) {
|
|
18
|
+
// Perform mutation
|
|
19
|
+
await updateDatabase(request)
|
|
20
|
+
|
|
21
|
+
// Logging blocks the response
|
|
22
|
+
const userAgent = request.headers.get('user-agent') || 'unknown'
|
|
23
|
+
await logUserAction({ userAgent })
|
|
24
|
+
|
|
25
|
+
return new Response(JSON.stringify({ status: 'success' }), {
|
|
26
|
+
status: 200,
|
|
27
|
+
headers: { 'Content-Type': 'application/json' }
|
|
28
|
+
})
|
|
29
|
+
}
|
|
30
|
+
```
|
|
31
|
+
|
|
32
|
+
**Correct (non-blocking):**
|
|
33
|
+
|
|
34
|
+
```tsx
|
|
35
|
+
import { after } from 'next/server'
|
|
36
|
+
import { headers, cookies } from 'next/headers'
|
|
37
|
+
import { logUserAction } from '@/app/utils'
|
|
38
|
+
|
|
39
|
+
export async function POST(request: Request) {
|
|
40
|
+
// Perform mutation
|
|
41
|
+
await updateDatabase(request)
|
|
42
|
+
|
|
43
|
+
// Log after response is sent
|
|
44
|
+
after(async () => {
|
|
45
|
+
const userAgent = (await headers()).get('user-agent') || 'unknown'
|
|
46
|
+
const sessionCookie = (await cookies()).get('session-id')?.value || 'anonymous'
|
|
47
|
+
|
|
48
|
+
logUserAction({ sessionCookie, userAgent })
|
|
49
|
+
})
|
|
50
|
+
|
|
51
|
+
return new Response(JSON.stringify({ status: 'success' }), {
|
|
52
|
+
status: 200,
|
|
53
|
+
headers: { 'Content-Type': 'application/json' }
|
|
54
|
+
})
|
|
55
|
+
}
|
|
56
|
+
```
|
|
57
|
+
|
|
58
|
+
The response is sent immediately while logging happens in the background.
|
|
59
|
+
|
|
60
|
+
**Common use cases:**
|
|
61
|
+
|
|
62
|
+
- Analytics tracking
|
|
63
|
+
- Audit logging
|
|
64
|
+
- Sending notifications
|
|
65
|
+
- Cache invalidation
|
|
66
|
+
- Cleanup tasks
|
|
67
|
+
|
|
68
|
+
**Important notes:**
|
|
69
|
+
|
|
70
|
+
- `after()` runs even if the response fails or redirects
|
|
71
|
+
- Works in Server Actions, Route Handlers, and Server Components
|
|
72
|
+
|
|
73
|
+
Reference: [https://nextjs.org/docs/app/api-reference/functions/after](https://nextjs.org/docs/app/api-reference/functions/after)
|
|
@@ -0,0 +1,41 @@
|
|
|
1
|
+
---
|
|
2
|
+
title: Cross-Request LRU Caching
|
|
3
|
+
impact: HIGH
|
|
4
|
+
impactDescription: caches across requests
|
|
5
|
+
tags: server, cache, lru, cross-request
|
|
6
|
+
---
|
|
7
|
+
|
|
8
|
+
## Cross-Request LRU Caching
|
|
9
|
+
|
|
10
|
+
`React.cache()` only works within one request. For data shared across sequential requests (user clicks button A then button B), use an LRU cache.
|
|
11
|
+
|
|
12
|
+
**Implementation:**
|
|
13
|
+
|
|
14
|
+
```typescript
|
|
15
|
+
import { LRUCache } from 'lru-cache'
|
|
16
|
+
|
|
17
|
+
const cache = new LRUCache<string, any>({
|
|
18
|
+
max: 1000,
|
|
19
|
+
ttl: 5 * 60 * 1000 // 5 minutes
|
|
20
|
+
})
|
|
21
|
+
|
|
22
|
+
export async function getUser(id: string) {
|
|
23
|
+
const cached = cache.get(id)
|
|
24
|
+
if (cached) return cached
|
|
25
|
+
|
|
26
|
+
const user = await db.user.findUnique({ where: { id } })
|
|
27
|
+
cache.set(id, user)
|
|
28
|
+
return user
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
// Request 1: DB query, result cached
|
|
32
|
+
// Request 2: cache hit, no DB query
|
|
33
|
+
```
|
|
34
|
+
|
|
35
|
+
Use when sequential user actions hit multiple endpoints needing the same data within seconds.
|
|
36
|
+
|
|
37
|
+
**With Vercel's [Fluid Compute](https://vercel.com/docs/fluid-compute):** LRU caching is especially effective because multiple concurrent requests can share the same function instance and cache. This means the cache persists across requests without needing external storage like Redis.
|
|
38
|
+
|
|
39
|
+
**In traditional serverless:** Each invocation runs in isolation, so consider Redis for cross-process caching.
|
|
40
|
+
|
|
41
|
+
Reference: [https://github.com/isaacs/node-lru-cache](https://github.com/isaacs/node-lru-cache)
|
|
@@ -0,0 +1,26 @@
|
|
|
1
|
+
---
|
|
2
|
+
title: Per-Request Deduplication with React.cache()
|
|
3
|
+
impact: MEDIUM
|
|
4
|
+
impactDescription: deduplicates within request
|
|
5
|
+
tags: server, cache, react-cache, deduplication
|
|
6
|
+
---
|
|
7
|
+
|
|
8
|
+
## Per-Request Deduplication with React.cache()
|
|
9
|
+
|
|
10
|
+
Use `React.cache()` for server-side request deduplication. Authentication and database queries benefit most.
|
|
11
|
+
|
|
12
|
+
**Usage:**
|
|
13
|
+
|
|
14
|
+
```typescript
|
|
15
|
+
import { cache } from 'react'
|
|
16
|
+
|
|
17
|
+
export const getCurrentUser = cache(async () => {
|
|
18
|
+
const session = await auth()
|
|
19
|
+
if (!session?.user?.id) return null
|
|
20
|
+
return await db.user.findUnique({
|
|
21
|
+
where: { id: session.user.id }
|
|
22
|
+
})
|
|
23
|
+
})
|
|
24
|
+
```
|
|
25
|
+
|
|
26
|
+
Within a single request, multiple calls to `getCurrentUser()` execute the query only once.
|
|
@@ -0,0 +1,79 @@
|
|
|
1
|
+
---
|
|
2
|
+
title: Parallel Data Fetching with Component Composition
|
|
3
|
+
impact: CRITICAL
|
|
4
|
+
impactDescription: eliminates server-side waterfalls
|
|
5
|
+
tags: server, rsc, parallel-fetching, composition
|
|
6
|
+
---
|
|
7
|
+
|
|
8
|
+
## Parallel Data Fetching with Component Composition
|
|
9
|
+
|
|
10
|
+
React Server Components execute sequentially within a tree. Restructure with composition to parallelize data fetching.
|
|
11
|
+
|
|
12
|
+
**Incorrect (Sidebar waits for Page's fetch to complete):**
|
|
13
|
+
|
|
14
|
+
```tsx
|
|
15
|
+
export default async function Page() {
|
|
16
|
+
const header = await fetchHeader()
|
|
17
|
+
return (
|
|
18
|
+
<div>
|
|
19
|
+
<div>{header}</div>
|
|
20
|
+
<Sidebar />
|
|
21
|
+
</div>
|
|
22
|
+
)
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
async function Sidebar() {
|
|
26
|
+
const items = await fetchSidebarItems()
|
|
27
|
+
return <nav>{items.map(renderItem)}</nav>
|
|
28
|
+
}
|
|
29
|
+
```
|
|
30
|
+
|
|
31
|
+
**Correct (both fetch simultaneously):**
|
|
32
|
+
|
|
33
|
+
```tsx
|
|
34
|
+
async function Header() {
|
|
35
|
+
const data = await fetchHeader()
|
|
36
|
+
return <div>{data}</div>
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
async function Sidebar() {
|
|
40
|
+
const items = await fetchSidebarItems()
|
|
41
|
+
return <nav>{items.map(renderItem)}</nav>
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
export default function Page() {
|
|
45
|
+
return (
|
|
46
|
+
<div>
|
|
47
|
+
<Header />
|
|
48
|
+
<Sidebar />
|
|
49
|
+
</div>
|
|
50
|
+
)
|
|
51
|
+
}
|
|
52
|
+
```
|
|
53
|
+
|
|
54
|
+
**Alternative with children prop:**
|
|
55
|
+
|
|
56
|
+
```tsx
|
|
57
|
+
async function Layout({ children }: { children: ReactNode }) {
|
|
58
|
+
const header = await fetchHeader()
|
|
59
|
+
return (
|
|
60
|
+
<div>
|
|
61
|
+
<div>{header}</div>
|
|
62
|
+
{children}
|
|
63
|
+
</div>
|
|
64
|
+
)
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
async function Sidebar() {
|
|
68
|
+
const items = await fetchSidebarItems()
|
|
69
|
+
return <nav>{items.map(renderItem)}</nav>
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
export default function Page() {
|
|
73
|
+
return (
|
|
74
|
+
<Layout>
|
|
75
|
+
<Sidebar />
|
|
76
|
+
</Layout>
|
|
77
|
+
)
|
|
78
|
+
}
|
|
79
|
+
```
|
|
@@ -0,0 +1,38 @@
|
|
|
1
|
+
---
|
|
2
|
+
title: Minimize Serialization at RSC Boundaries
|
|
3
|
+
impact: HIGH
|
|
4
|
+
impactDescription: reduces data transfer size
|
|
5
|
+
tags: server, rsc, serialization, props
|
|
6
|
+
---
|
|
7
|
+
|
|
8
|
+
## Minimize Serialization at RSC Boundaries
|
|
9
|
+
|
|
10
|
+
The React Server/Client boundary serializes all object properties into strings and embeds them in the HTML response and subsequent RSC requests. This serialized data directly impacts page weight and load time, so **size matters a lot**. Only pass fields that the client actually uses.
|
|
11
|
+
|
|
12
|
+
**Incorrect (serializes all 50 fields):**
|
|
13
|
+
|
|
14
|
+
```tsx
|
|
15
|
+
async function Page() {
|
|
16
|
+
const user = await fetchUser() // 50 fields
|
|
17
|
+
return <Profile user={user} />
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
'use client'
|
|
21
|
+
function Profile({ user }: { user: User }) {
|
|
22
|
+
return <div>{user.name}</div> // uses 1 field
|
|
23
|
+
}
|
|
24
|
+
```
|
|
25
|
+
|
|
26
|
+
**Correct (serializes only 1 field):**
|
|
27
|
+
|
|
28
|
+
```tsx
|
|
29
|
+
async function Page() {
|
|
30
|
+
const user = await fetchUser()
|
|
31
|
+
return <Profile name={user.name} />
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
'use client'
|
|
35
|
+
function Profile({ name }: { name: string }) {
|
|
36
|
+
return <div>{name}</div>
|
|
37
|
+
}
|
|
38
|
+
```
|
|
@@ -0,0 +1,84 @@
|
|
|
1
|
+
# Vitest Best Practices
|
|
2
|
+
|
|
3
|
+
> **Note:**
|
|
4
|
+
> This document is mainly for agents and LLMs to follow when maintaining, generating, or refactoring vitest tests. Humans may also find it useful, but guidance here is optimized for automation and consistency by AI-assisted workflows.
|
|
5
|
+
|
|
6
|
+
---
|
|
7
|
+
|
|
8
|
+
## Abstract
|
|
9
|
+
|
|
10
|
+
Comprehensive guide for testing with `vitest`, designed for AI agents and LLMs. Each rule includes one-line summaries here, with links to detailed examples in the `references/` folder. Load reference files only when you need detailed implementation guidance for a specific rule.
|
|
11
|
+
|
|
12
|
+
Use the `vitest` testing framework. Design tests to be short, simple, flat, and instantly understandable.
|
|
13
|
+
|
|
14
|
+
---
|
|
15
|
+
|
|
16
|
+
## How to Use This Guide
|
|
17
|
+
|
|
18
|
+
1. **Start here**: Scan the rule summaries to identify relevant patterns
|
|
19
|
+
2. **Load references as needed**: Click through to detailed examples only when implementing
|
|
20
|
+
3. **Progressive loading**: Each reference file is self-contained with examples
|
|
21
|
+
|
|
22
|
+
This structure minimizes context usage while providing complete implementation guidance when needed.
|
|
23
|
+
|
|
24
|
+
---
|
|
25
|
+
|
|
26
|
+
## General Test Structure
|
|
27
|
+
|
|
28
|
+
Use `it()` with sentence-style descriptions:
|
|
29
|
+
|
|
30
|
+
**✅ Correct: appropriate structure**
|
|
31
|
+
```ts
|
|
32
|
+
describe('ProductsService', () => {
|
|
33
|
+
describe('Add new product', () => {
|
|
34
|
+
it('should have status "pending approval" when no price is specified', () => {
|
|
35
|
+
const newProduct = new ProductService().add(/*...*/);
|
|
36
|
+
expect(newProduct.status).toEqual('pendingApproval');
|
|
37
|
+
});
|
|
38
|
+
});
|
|
39
|
+
});
|
|
40
|
+
```
|
|
41
|
+
|
|
42
|
+
---
|
|
43
|
+
|
|
44
|
+
## 1. General
|
|
45
|
+
|
|
46
|
+
### 1.1 Organization
|
|
47
|
+
Place test files next to implementation; one test file per module.
|
|
48
|
+
[View detailed examples](references/organization.md)
|
|
49
|
+
|
|
50
|
+
### 1.2 AAA Pattern
|
|
51
|
+
Structure tests as Arrange, Act, Assert for clarity.
|
|
52
|
+
[View detailed examples](references/aaa-pattern.md)
|
|
53
|
+
|
|
54
|
+
### 1.3 Parameterized Tests
|
|
55
|
+
Use `it.each` for variations; one behavior per test.
|
|
56
|
+
[View detailed examples](references/parameterized-tests.md)
|
|
57
|
+
|
|
58
|
+
### 1.4 Error Handling
|
|
59
|
+
Test negative cases, fault injection, and recovery thoroughly.
|
|
60
|
+
[View detailed examples](references/error-handling.md)
|
|
61
|
+
|
|
62
|
+
### 1.5 Assertions
|
|
63
|
+
Use strict assertions (`toEqual`, `toStrictEqual`) over loose ones.
|
|
64
|
+
[View detailed examples](references/assertions.md)
|
|
65
|
+
|
|
66
|
+
### 1.6 Test Doubles
|
|
67
|
+
Prefer fakes > stubs > spies/mocks; avoid over-mocking.
|
|
68
|
+
[View detailed examples](references/test-doubles.md)
|
|
69
|
+
|
|
70
|
+
### 1.7 Async Testing
|
|
71
|
+
Test promises, async/await, and timers correctly.
|
|
72
|
+
[View detailed examples](references/async-testing.md)
|
|
73
|
+
|
|
74
|
+
### 1.8 Performance
|
|
75
|
+
Keep tests fast through efficient setup and avoiding expensive operations.
|
|
76
|
+
[View detailed examples](references/performance.md)
|
|
77
|
+
|
|
78
|
+
### 1.9 Vitest Features
|
|
79
|
+
Use coverage, watch mode, benchmarking, and other vitest-specific features.
|
|
80
|
+
[View detailed examples](references/vitest-features.md)
|
|
81
|
+
|
|
82
|
+
### 1.10 Snapshot Testing
|
|
83
|
+
Use snapshots for appropriate cases; avoid common pitfalls.
|
|
84
|
+
[View detailed examples](references/snapshot-testing.md)
|
|
@@ -0,0 +1,130 @@
|
|
|
1
|
+
---
|
|
2
|
+
name: vitest-best-practices
|
|
3
|
+
description: Comprehensive vitest testing patterns covering test structure, AAA pattern, parameterized tests, assertions, mocking, test doubles, error handling, async testing, and performance optimization. Use when writing, reviewing, or refactoring vitest tests, or when user mentions vitest, testing, TDD, test coverage, mocking, assertions, or test files (*.test.ts, *.spec.ts).
|
|
4
|
+
compatibility: Requires vitest testing framework
|
|
5
|
+
---
|
|
6
|
+
|
|
7
|
+
# Vitest Best Practices
|
|
8
|
+
|
|
9
|
+
## When to Apply This Skill
|
|
10
|
+
|
|
11
|
+
Use this skill when you encounter any of these scenarios:
|
|
12
|
+
|
|
13
|
+
### File Patterns
|
|
14
|
+
|
|
15
|
+
- Working with `*.test.ts`, `*.spec.ts`, or similar test files
|
|
16
|
+
- Creating new test files for TypeScript/JavaScript modules
|
|
17
|
+
- Reviewing existing vitest test suites
|
|
18
|
+
|
|
19
|
+
### User Intent Keywords
|
|
20
|
+
|
|
21
|
+
- User mentions: vitest, testing, TDD, BDD, unit tests, integration tests
|
|
22
|
+
- User asks to: write tests, add test coverage, fix failing tests, refactor tests
|
|
23
|
+
- User discusses: mocking, stubbing, assertions, test performance, test organization
|
|
24
|
+
|
|
25
|
+
### Code Context
|
|
26
|
+
|
|
27
|
+
- Files importing from `vitest` (`describe`, `it`, `expect`, `vi`)
|
|
28
|
+
- Test setup/teardown code (`beforeEach`, `afterEach`, `beforeAll`, `afterAll`)
|
|
29
|
+
- Mock/spy implementations using `vi.mock()`, `vi.spyOn()`, `vi.fn()`
|
|
30
|
+
- Assertion chains (`expect(...).toEqual()`, `.toBe()`, `.toThrow()`, etc.)
|
|
31
|
+
|
|
32
|
+
### Common Tasks
|
|
33
|
+
|
|
34
|
+
- Writing new test cases for existing functionality
|
|
35
|
+
- Refactoring tests for better clarity or performance
|
|
36
|
+
- Debugging flaky or failing tests
|
|
37
|
+
- Improving test coverage or maintainability
|
|
38
|
+
- Reviewing test code for best practices compliance
|
|
39
|
+
|
|
40
|
+
## Do NOT Use This Skill When
|
|
41
|
+
|
|
42
|
+
- Writing end-to-end tests with Playwright/Cypress (different scope)
|
|
43
|
+
- The task is purely about implementation code, not tests
|
|
44
|
+
|
|
45
|
+
## What This Skill Covers
|
|
46
|
+
|
|
47
|
+
This skill provides comprehensive guidance on:
|
|
48
|
+
|
|
49
|
+
1. **Test Organization**: File placement, naming conventions, grouping strategies
|
|
50
|
+
2. **AAA Pattern**: Arrange, Act, Assert structure for clarity
|
|
51
|
+
3. **Parameterized Tests**: Using `it.each()` for testing variations
|
|
52
|
+
4. **Error Handling**: Testing exceptions, edge cases, and fault injection
|
|
53
|
+
5. **Assertions**: Choosing strict assertions (`toEqual`, `toStrictEqual`, `toThrow`)
|
|
54
|
+
6. **Test Doubles**: Fakes, stubs, mocks, spies - when to use each
|
|
55
|
+
7. **Async Testing**: Promises, async/await, timers, and concurrent tests
|
|
56
|
+
8. **Performance**: Fast tests, avoiding expensive operations, cleanup patterns
|
|
57
|
+
9. **Vitest-Specific Features**: Coverage, watch mode, benchmarking, type testing, setup files
|
|
58
|
+
10. **Snapshot Testing**: When and how to use snapshots effectively
|
|
59
|
+
|
|
60
|
+
## How to Use
|
|
61
|
+
|
|
62
|
+
This skill uses a **progressive disclosure** structure to minimize context usage:
|
|
63
|
+
|
|
64
|
+
### 1. Start with the Overview (AGENTS.md)
|
|
65
|
+
|
|
66
|
+
Read [AGENTS.md](AGENTS.md) for a concise overview of all rules with one-line summaries.
|
|
67
|
+
|
|
68
|
+
### 2. Load Specific Rules as Needed
|
|
69
|
+
|
|
70
|
+
When you identify a relevant optimization, load the corresponding reference file for detailed implementation guidance:
|
|
71
|
+
|
|
72
|
+
**Core Patterns:**
|
|
73
|
+
- [organization.md](references/organization.md)
|
|
74
|
+
- [aaa-pattern.md](references/aaa-pattern.md)
|
|
75
|
+
- [parameterized-tests.md](references/parameterized-tests.md)
|
|
76
|
+
- [error-handling.md](references/error-handling.md)
|
|
77
|
+
- [assertions.md](references/assertions.md)
|
|
78
|
+
- [test-doubles.md](references/test-doubles.md)
|
|
79
|
+
|
|
80
|
+
**Advanced Topics:**
|
|
81
|
+
- [async-testing.md](references/async-testing.md)
|
|
82
|
+
- [performance.md](references/performance.md)
|
|
83
|
+
- [vitest-features.md](references/vitest-features.md)
|
|
84
|
+
- [snapshot-testing.md](references/snapshot-testing.md)
|
|
85
|
+
|
|
86
|
+
### 3. Apply the Pattern
|
|
87
|
+
|
|
88
|
+
Each reference file contains:
|
|
89
|
+
- ❌ Incorrect examples showing the anti-pattern
|
|
90
|
+
- ✅ Correct examples showing the optimal implementation
|
|
91
|
+
- Explanations of why the pattern matters
|
|
92
|
+
|
|
93
|
+
## Quick Example
|
|
94
|
+
|
|
95
|
+
This skill helps you transform unclear tests into clear, maintainable ones:
|
|
96
|
+
|
|
97
|
+
**Before (unclear):**
|
|
98
|
+
```ts
|
|
99
|
+
test('product test', () => {
|
|
100
|
+
const p = new ProductService().add({name: 'Widget'});
|
|
101
|
+
expect(p.status).toBe('pendingApproval');
|
|
102
|
+
});
|
|
103
|
+
```
|
|
104
|
+
|
|
105
|
+
**After (optimized with this skill):**
|
|
106
|
+
```ts
|
|
107
|
+
describe('ProductService', () => {
|
|
108
|
+
describe('Add new product', () => {
|
|
109
|
+
it('should have status "pending approval" when no price is specified', () => {
|
|
110
|
+
// Arrange
|
|
111
|
+
const productService = new ProductService();
|
|
112
|
+
|
|
113
|
+
// Act
|
|
114
|
+
const newProduct = productService.add({name: 'Widget'});
|
|
115
|
+
|
|
116
|
+
// Assert
|
|
117
|
+
expect(newProduct.status).toEqual('pendingApproval');
|
|
118
|
+
});
|
|
119
|
+
});
|
|
120
|
+
});
|
|
121
|
+
```
|
|
122
|
+
|
|
123
|
+
## Key Principles
|
|
124
|
+
|
|
125
|
+
- **Clarity over cleverness**: Tests should be instantly understandable
|
|
126
|
+
- **Flat structure**: Avoid deep nesting in describe blocks
|
|
127
|
+
- **One assertion per concept**: Focus tests on single behaviors
|
|
128
|
+
- **Strict assertions**: Prefer `toEqual` over `toBe`, `toStrictEqual` when needed
|
|
129
|
+
- **Minimal mocking**: Use real implementations when practical
|
|
130
|
+
- **Fast execution**: Keep tests quick through efficient setup/teardown
|