@mikulgohil/ai-kit 1.2.1 → 1.3.1

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/README.md CHANGED
@@ -1,36 +1,177 @@
1
- # ai-kit
1
+ <p align="center">
2
+ <h1 align="center">AI Kit</h1>
3
+ <p align="center">
4
+ Make AI coding assistants actually useful.<br/>
5
+ One command. Project-aware AI from the first conversation.
6
+ </p>
7
+ </p>
2
8
 
3
- AI-assisted development setup kit. Auto-detects your tech stack and generates tailored CLAUDE.md, .cursorrules, hooks, agents, context modes, slash commands, and developer guides.
9
+ <p align="center">
10
+ <a href="https://www.npmjs.com/package/@mikulgohil/ai-kit"><img src="https://img.shields.io/npm/v/@mikulgohil/ai-kit.svg" alt="npm version" /></a>
11
+ <a href="https://www.npmjs.com/package/@mikulgohil/ai-kit"><img src="https://img.shields.io/npm/dm/@mikulgohil/ai-kit.svg" alt="npm downloads" /></a>
12
+ <a href="https://github.com/mikulgohil/ai-kit/blob/main/LICENSE"><img src="https://img.shields.io/npm/l/@mikulgohil/ai-kit.svg" alt="license" /></a>
13
+ <a href="https://mikulgohil.github.io/ai-kit-docs"><img src="https://img.shields.io/badge/docs-ai--kit--docs-blue" alt="documentation" /></a>
14
+ </p>
4
15
 
5
- ## Installation
16
+ ---
17
+
18
+ ## The Problem
19
+
20
+ AI coding tools are powerful, but they start every project from zero:
21
+
22
+ - **Wrong patterns** — The AI writes Pages Router code when you use App Router, CSS when you use Tailwind
23
+ - **No standards** — No docs, no tests, no JSDoc, no error boundaries unless you explicitly ask every time
24
+ - **Repeated context** — You explain the same conventions in every conversation, every day
25
+ - **Inconsistent output** — Developer A gets different AI behavior than Developer B on the same project
26
+ - **No quality gates** — AI-generated code goes straight to PR without validation
27
+ - **Same mistakes** — No system to track what went wrong, so the team keeps hitting the same issues
28
+
29
+ **The result:** Teams spend more time fixing AI output than they save generating it.
30
+
31
+ ## The Solution
6
32
 
7
33
  ```bash
8
34
  npx @mikulgohil/ai-kit init
9
35
  ```
10
36
 
11
- Requires Node >= 18.
37
+ One command. 30 seconds. Your AI assistant goes from generic to project-aware.
38
+
39
+ AI Kit scans your project, detects your tech stack, and generates tailored rules, skills, agents, hooks, and guides — so every AI interaction follows your standards, from the first conversation.
40
+
41
+ ---
42
+
43
+ ## What You Get
44
+
45
+ | Generated | What It Does |
46
+ |-----------|-------------|
47
+ | **CLAUDE.md** | Project-aware rules for Claude Code — your stack, conventions, and patterns |
48
+ | **.cursorrules** + `.cursor/rules/*.mdc` | Same rules formatted for Cursor AI with scoped file matching |
49
+ | **39 Skills** | Auto-discovered workflows — `/review`, `/new-component`, `/security-check`, `/pre-pr`, and 35 more |
50
+ | **8 Agents** | Specialized AI assistants for delegation — planner, reviewer, security, E2E, build-resolver, and more |
51
+ | **3 Context Modes** | Switch between dev (build fast), review (check quality), and research (understand code) |
52
+ | **Automated Hooks** | Auto-format, TypeScript checks, console.log warnings, mistakes auto-capture, git safety |
53
+ | **6 Guides** | Developer playbooks for prompts, tokens, hooks, agents, Figma workflow |
54
+ | **Doc Scaffolds** | Mistakes log, decisions log, time log — structured knowledge tracking |
55
+ | **Component Docs** | Auto-generated `.ai.md` files per component with health scores and Sitecore integration |
56
+
57
+ ---
58
+
59
+ ## Key Features
60
+
61
+ ### Auto Stack Detection
62
+
63
+ Scans your `package.json`, config files, and directory structure to detect your exact stack — then generates rules tailored to it.
64
+
65
+ | What It Detects | What the AI Learns |
66
+ |---|---|
67
+ | Next.js 15 with App Router | Server Components, Server Actions, `app/` routing patterns |
68
+ | Sitecore XM Cloud | `<Text>`, `<RichText>`, `<Image>` field helpers, placeholder patterns |
69
+ | Tailwind CSS v4 | `@theme` tokens, utility class patterns, responsive prefixes |
70
+ | TypeScript strict mode | No `any`, proper null checks, discriminated unions |
71
+ | Turborepo monorepo | Workspace conventions, cross-package imports |
72
+ | Figma + design tokens | Token mapping, design-to-code workflow |
73
+
74
+ ### 39 Pre-Built Skills
75
+
76
+ Skills are structured AI workflows that get applied automatically — you don't type a command, the AI recognizes what you're doing and loads the right skill.
77
+
78
+ | Category | Skills |
79
+ |---|---|
80
+ | **Getting Started** | `prompt-help`, `understand` |
81
+ | **Building** | `new-component`, `new-page`, `api-route`, `error-boundary`, `extract-hook`, `figma-to-code`, `design-tokens`, `schema-gen`, `storybook-gen` |
82
+ | **Quality & Review** | `review`, `pre-pr`, `test`, `accessibility-audit`, `security-check`, `responsive-check`, `type-fix`, `perf-audit`, `bundle-check`, `i18n-check` |
83
+ | **Maintenance** | `fix-bug`, `refactor`, `optimize`, `migrate`, `dep-check`, `sitecore-debug` |
84
+ | **Workflow** | `document`, `commit-msg`, `env-setup`, `changelog`, `release` |
85
+ | **Session** | `save-session`, `resume-session`, `checkpoint` |
86
+ | **Orchestration** | `orchestrate`, `quality-gate`, `harness-audit` |
12
87
 
13
- ## What Gets Generated
88
+ ### 8 Specialized Agents
14
89
 
15
- Running `init` scans your project and produces:
90
+ Agents handle delegated tasks with focused expertise:
16
91
 
17
- - **CLAUDE.md** Project-aware rules and conventions for Claude Code
18
- - **.cursorrules** — Equivalent rules for Cursor AI
19
- - **.cursor/rules/*.mdc** Modular rule files for Cursor
20
- - **.claude/skills/** 39 slash commands across 7 categories
21
- - **.claude/agents/** 8 specialized AI agents for delegation (planner, reviewer, security, E2E, build-resolver, doc-updater, refactor-cleaner, sitecore-specialist)
22
- - **.claude/contexts/** 3 context modes (dev, review, research)
23
- - **.claude/settings.local.json** Automated hooks (auto-format, typecheck, console.log warnings, git safety)
24
- - **ai-kit/guides/** 6 developer guides
25
- - **docs/**3 doc scaffolds: mistakes-log, decisions-log, time-log
92
+ | Agent | Purpose | Conditional |
93
+ |---|---|---|
94
+ | `planner` | Break features into implementation plans | No |
95
+ | `code-reviewer` | Deep quality and security review | No |
96
+ | `security-reviewer` | OWASP Top 10, XSS, CSRF, secrets detection | No |
97
+ | `build-resolver` | Diagnose and fix build/type errors | No |
98
+ | `doc-updater` | Keep documentation in sync with code | No |
99
+ | `refactor-cleaner` | Find and remove dead code | No |
100
+ | `e2e-runner` | Playwright tests with Page Object Model | Yes only if Playwright installed |
101
+ | `sitecore-specialist` | Sitecore XM Cloud patterns and debugging | Yes — only if Sitecore detected |
102
+
103
+ ### Automated Quality Hooks
104
+
105
+ Hooks run automatically as you code. Choose a profile during init:
106
+
107
+ | Profile | What Runs |
108
+ |---|---|
109
+ | **Minimal** | Auto-format + git push safety |
110
+ | **Standard** | + TypeScript type-check + console.log warnings + mistakes auto-capture |
111
+ | **Strict** | + ESLint check + stop-time console.log audit |
112
+
113
+ **Mistakes auto-capture** — When a build or lint command fails, the hook automatically logs the error to `docs/mistakes-log.md` with a timestamp and error preview. Your mistakes log builds itself over time.
114
+
115
+ ### Component Scanner & Docs
116
+
117
+ Discovers all React components and generates `.ai.md` documentation files with:
118
+
119
+ - Props table with types and required flags
120
+ - Health score (0-100) based on tests, stories, docs, and Sitecore integration
121
+ - Sitecore integration details (datasource fields, rendering params, placeholders, GraphQL queries)
122
+ - Smart merge — updates auto-generated sections while preserving manual edits
123
+
124
+ ### Project Health Dashboard
125
+
126
+ ```bash
127
+ npx @mikulgohil/ai-kit health
128
+ ```
129
+
130
+ One-glance view of your project's AI setup health across 5 sections: setup integrity, security, stack detection, tools/MCP status, and documentation. Outputs an A-F grade with actionable recommendations.
131
+
132
+ ### Security Audit
133
+
134
+ ```bash
135
+ npx @mikulgohil/ai-kit audit
136
+ ```
137
+
138
+ Scans for secrets in CLAUDE.md, MCP config security, .env gitignore status, hook validity, agent configuration, and more. Outputs an A-F health grade.
139
+
140
+ ### Token Tracking & Cost Estimates
141
+
142
+ ```bash
143
+ npx @mikulgohil/ai-kit tokens
144
+ ```
145
+
146
+ - Period summaries (today, this week, this month)
147
+ - Budget progress with alerts at 50%, 75%, 90%
148
+ - Per-project cost breakdown
149
+ - Week-over-week trends
150
+ - Model recommendations (Sonnet vs Opus optimization)
151
+ - ROI estimate (time saved vs cost)
152
+
153
+ ### Multi-Tool Support
154
+
155
+ Generate configs once, use across 5+ AI tools:
156
+
157
+ | Tool | Output |
158
+ |---|---|
159
+ | **Claude Code** | `CLAUDE.md` + skills + agents + contexts + hooks |
160
+ | **Cursor** | `.cursorrules` + `.cursor/rules/*.mdc` + skills |
161
+ | **Windsurf** | `.windsurfrules` (via `ai-kit export`) |
162
+ | **Aider** | `.aider.conf.yml` (via `ai-kit export`) |
163
+ | **Cline** | `.clinerules` (via `ai-kit export`) |
164
+
165
+ ---
26
166
 
27
167
  ## CLI Commands
28
168
 
29
169
  | Command | Description |
30
- |---------|-------------|
170
+ |---|---|
31
171
  | `ai-kit init [path]` | Scan project and generate all configs |
32
172
  | `ai-kit update [path]` | Re-scan and update existing generated files |
33
173
  | `ai-kit reset [path]` | Remove all AI Kit generated files |
174
+ | `ai-kit health [path]` | One-glance project health dashboard |
34
175
  | `ai-kit audit [path]` | Security and configuration health audit |
35
176
  | `ai-kit doctor [path]` | Diagnose setup issues |
36
177
  | `ai-kit diff [path]` | Preview what would change on update (dry run) |
@@ -40,106 +181,102 @@ Running `init` scans your project and produces:
40
181
 
41
182
  `path` defaults to the current directory if omitted.
42
183
 
43
- ## Features
184
+ ---
44
185
 
45
- ### Hooks (Automated Quality Checks)
186
+ ## Supported Tech Stacks
46
187
 
47
- Hooks run automatically as you code — no manual invocation needed. Choose a profile during init:
188
+ | Category | Technologies |
189
+ |---|---|
190
+ | **Frameworks** | Next.js (App Router, Pages Router, Hybrid), React |
191
+ | **CMS** | Sitecore XM Cloud (Content SDK v2), Sitecore JSS |
192
+ | **Styling** | Tailwind CSS (v3 + v4), SCSS, CSS Modules, styled-components |
193
+ | **Language** | TypeScript (with strict mode detection) |
194
+ | **Formatters** | Prettier, Biome (auto-detected for hooks) |
195
+ | **Monorepos** | Turborepo, Nx, Lerna, pnpm workspaces |
196
+ | **Design** | Figma MCP, Figma Code CLI, design tokens, visual tests |
197
+ | **Testing** | Playwright, Storybook, axe-core |
198
+ | **Quality** | ESLint, Snyk, Knip, @next/bundle-analyzer |
199
+ | **Package Managers** | npm, pnpm, yarn, bun |
48
200
 
49
- | Profile | What Runs |
50
- |---------|-----------|
51
- | **Minimal** | Auto-format + git push safety |
52
- | **Standard** | + TypeScript type-check + console.log warnings |
53
- | **Strict** | + ESLint check + stop-time console.log audit |
201
+ ---
54
202
 
55
- Auto-detects your formatter (Prettier or Biome) and generates the right hook.
203
+ ## Quick Start
56
204
 
57
- ### Agents (Specialized AI Assistants)
58
-
59
- Agents live in `.claude/agents/` and handle delegated tasks:
60
-
61
- | Agent | Purpose |
62
- |-------|---------|
63
- | `planner` | Break features into implementation plans |
64
- | `code-reviewer` | Deep quality and security review |
65
- | `security-reviewer` | OWASP Top 10, XSS, CSRF, secrets detection |
66
- | `e2e-runner` | Playwright tests with Page Object Model |
67
- | `build-resolver` | Diagnose and fix build/type errors |
68
- | `doc-updater` | Keep documentation in sync with code |
69
- | `refactor-cleaner` | Find and remove dead code |
70
- | `sitecore-specialist` | Sitecore XM Cloud patterns and debugging |
71
-
72
- Conditional agents are only generated when their tools are detected (e.g., `e2e-runner` requires Playwright, `sitecore-specialist` requires Sitecore).
73
-
74
- ### Context Modes
75
-
76
- Three modes change how the AI approaches work:
77
-
78
- | Mode | Focus |
79
- |------|-------|
80
- | **dev** | Building features — implementation over perfection |
81
- | **review** | Checking quality — security, a11y, types, performance |
82
- | **research** | Understanding code — read-only exploration and analysis |
205
+ ```bash
206
+ # 1. Run in any project directory
207
+ npx @mikulgohil/ai-kit init
83
208
 
84
- ### Session Management
209
+ # 2. Follow the interactive prompts (30 seconds)
85
210
 
86
- | Skill | Purpose |
87
- |-------|---------|
88
- | `/save-session` | Persist session context for later |
89
- | `/resume-session` | Restore and continue previous work |
90
- | `/checkpoint` | Snapshot all quality checks |
211
+ # 3. Check your project health
212
+ npx @mikulgohil/ai-kit health
91
213
 
92
- ### Multi-Agent Orchestration
214
+ # 4. Open in Claude Code or Cursor — AI now knows your project
215
+ ```
93
216
 
94
- | Skill | Purpose |
95
- |-------|---------|
96
- | `/orchestrate` | Coordinate multiple agents on complex tasks |
97
- | `/quality-gate` | Run all checks: types, lint, format, tests, a11y, security |
98
- | `/harness-audit` | Check AI configuration health |
217
+ ### Updating
99
218
 
100
- ### Security Audit
219
+ When your project evolves (new dependencies, framework upgrades):
101
220
 
102
221
  ```bash
103
- npx @mikulgohil/ai-kit audit
222
+ npx @mikulgohil/ai-kit update
104
223
  ```
105
224
 
106
- Checks for secrets in CLAUDE.md, MCP config security, .env gitignore, hook validity, agent frontmatter, and more. Outputs an A-F health grade.
225
+ Only content between `AI-KIT:START/END` markers is refreshed. Your custom rules and manual edits are preserved.
107
226
 
108
- ## Supported Stacks
227
+ ---
109
228
 
110
- **Frameworks** Next.js (App Router, Pages Router, Hybrid), React
229
+ ## Who Is This For?
111
230
 
112
- **CMS** — Sitecore XM Cloud, Sitecore JSS
231
+ **Individual developers** — Stop re-explaining context. Let AI Kit teach the AI your project once. Every conversation starts informed.
113
232
 
114
- **Styling** — Tailwind CSS, SCSS, CSS Modules, styled-components
233
+ **Tech leads** — Enforce coding standards through AI tools instead of code review comments. Standards are followed automatically, not policed manually.
115
234
 
116
- **Language** — TypeScript (with strict mode detection)
235
+ **Teams** — Same AI experience across every developer and every project. New hires get the same AI context as senior engineers.
117
236
 
118
- **Formatters** — Prettier, Biome (auto-detected for hooks)
237
+ **Enterprise** — Consistent AI governance across projects. Security audit, token tracking, and quality hooks provide visibility and control.
119
238
 
120
- **Monorepos** — Turborepo, Nx, Lerna, pnpm workspaces
239
+ ---
121
240
 
122
- **Design** Figma MCP, design tokens, visual tests
241
+ ## The Impact
123
242
 
124
- **Testing** Playwright, Storybook, axe-core
243
+ | Metric | Before AI Kit | After AI Kit |
244
+ |---|---|---|
245
+ | Context setup per conversation | 5-10 min | 0 min (auto-loaded) |
246
+ | Code review cycles per PR | 2-4 rounds | 1-2 rounds |
247
+ | Component creation time | 30-60 min | 10-15 min |
248
+ | New developer onboarding | 1-2 weeks | 2-3 days |
249
+ | Security issues caught | At PR review or production | At development time |
250
+ | Knowledge retention | Lost when developers leave | Logged in decisions, mistakes, and time logs |
251
+ | AI tool switching cost | Start over from scratch | Zero — same rules across 5+ tools |
125
252
 
126
- **Package managers** — npm, pnpm, yarn, bun
253
+ ---
127
254
 
128
- ## Updating
255
+ ## Documentation
129
256
 
130
- ```bash
131
- npx @mikulgohil/ai-kit update
132
- ```
257
+ Full documentation is available at **[mikulgohil.github.io/ai-kit-docs](https://mikulgohil.github.io/ai-kit-docs)**
258
+
259
+ | Page | What You'll Learn |
260
+ |---|---|
261
+ | [Getting Started](https://mikulgohil.github.io/ai-kit-docs/getting-started) | Step-by-step setup walkthrough |
262
+ | [CLI Reference](https://mikulgohil.github.io/ai-kit-docs/cli-reference) | All 10 commands with examples |
263
+ | [Skills & Commands](https://mikulgohil.github.io/ai-kit-docs/slash-commands) | All 39 skills with usage guides |
264
+ | [Hooks](https://mikulgohil.github.io/ai-kit-docs/hooks) | Hook profiles and configuration |
265
+ | [Agents](https://mikulgohil.github.io/ai-kit-docs/agents) | 8 specialized agents |
266
+ | [What Gets Generated](https://mikulgohil.github.io/ai-kit-docs/what-gets-generated) | Detailed breakdown of every generated file |
267
+ | [Changelog](https://mikulgohil.github.io/ai-kit-docs/changelog) | Version history and release notes |
133
268
 
134
- Re-scans your project and refreshes all generated files — CLAUDE.md, skills, agents, contexts, and hooks.
269
+ ---
135
270
 
136
- ## Further Reading
271
+ ## Requirements
137
272
 
138
- Detailed usage is covered in the generated guides under `ai-kit/guides/` after running `init`. Start with `getting-started.md`.
273
+ - **Node.js 18+**
274
+ - **A project with `package.json`**
275
+ - **Claude Code or Cursor** (at least one AI tool installed)
139
276
 
140
277
  ## Repository
141
278
 
142
- [https://github.com/mikulgohil/ai-kit](https://github.com/mikulgohil/ai-kit)
279
+ [github.com/mikulgohil/ai-kit](https://github.com/mikulgohil/ai-kit)
143
280
 
144
281
  ## License
145
282
 
@@ -0,0 +1,79 @@
1
+ ---
2
+ name: architect
3
+ description: System architect — SSR/SSG/ISR strategy, component hierarchy, data flow, rendering patterns for Next.js + Sitecore XM Cloud + Tailwind projects.
4
+ tools: Read, Glob, Grep, Bash
5
+ ---
6
+
7
+ # System Architect
8
+
9
+ You are a senior software architect specializing in Next.js, Sitecore XM Cloud, and Tailwind CSS projects. You make high-level design decisions and produce architecture decision records.
10
+
11
+ ## Core Responsibilities
12
+
13
+ ### Rendering Strategy
14
+ - Decide between SSR, SSG, ISR, and client-side rendering per route
15
+ - Configure `revalidate` intervals for ISR pages
16
+ - Identify pages that need `generateStaticParams` vs on-demand rendering
17
+ - Plan Streaming SSR with Suspense boundaries for slow data sources
18
+
19
+ ### Component Architecture
20
+ - Design component hierarchy: layout → page → section → UI primitives
21
+ - Separate Server Components (data fetching, static content) from Client Components (interactivity)
22
+ - Identify shared components vs page-specific components
23
+ - Plan prop drilling vs context vs composition patterns
24
+
25
+ ### Data Flow
26
+ - Map data sources: Sitecore Layout Service, Experience Edge GraphQL, external APIs
27
+ - Design fetching strategy: Server Component fetch, Server Actions, Route Handlers
28
+ - Plan caching layers: Next.js fetch cache, ISR, CDN, client-side cache
29
+ - Handle data dependencies between components
30
+
31
+ ### State Management
32
+ - Identify client-side state needs (forms, UI toggles, filters)
33
+ - Choose minimal state approach: URL params > server state > React state > global store
34
+ - Plan Server Action flows for mutations and revalidation
35
+
36
+ ## Output Format
37
+
38
+ When asked for architecture guidance, produce:
39
+
40
+ ```
41
+ ## Architecture Decision Record
42
+
43
+ ### Context
44
+ [What problem are we solving? What constraints exist?]
45
+
46
+ ### Decision
47
+ [What approach did we choose?]
48
+
49
+ ### Rendering Strategy
50
+ | Route | Strategy | Revalidation | Reason |
51
+ |-------|----------|-------------|--------|
52
+ | / | ISR | 60s | Content changes infrequently |
53
+ | /blog/[slug] | SSG | on-demand | Static content, revalidate on publish |
54
+
55
+ ### Component Hierarchy
56
+ [Tree structure of components with Server/Client annotations]
57
+
58
+ ### Data Flow
59
+ [How data moves from source → component, including caching]
60
+
61
+ ### Consequences
62
+ [Trade-offs, risks, follow-up items]
63
+ ```
64
+
65
+ ## Sitecore-Specific Patterns
66
+
67
+ - Layout Service data flows through `SitecorePagePropsFactory` → page props → component tree
68
+ - Experience Edge GraphQL for cross-page queries (navigation, search, listings)
69
+ - Component-level data via `ComponentRendering` props from Layout Service
70
+ - Personalization variants require SSR or edge middleware — cannot be statically generated
71
+ - Preview/editing mode requires SSR with draft content from CM instance
72
+
73
+ ## Rules
74
+
75
+ - Always prefer Server Components unless interactivity is required
76
+ - Keep the Client Component boundary as low in the tree as possible
77
+ - Do not over-architect — choose the simplest approach that meets requirements
78
+ - Consider Experience Editor compatibility in every architectural decision
79
+ - Document rendering strategy per route, not just globally
@@ -1,6 +1,6 @@
1
1
  ---
2
2
  name: sitecore-specialist
3
- description: Sitecore XM Cloud specialist — handles component mapping, GraphQL queries, layout service, Experience Edge, and personalization.
3
+ description: Sitecore XM Cloud specialist — handles component mapping, GraphQL queries, layout service, Experience Edge, personalization, and Content SDK v2.x.
4
4
  tools: Read, Write, Edit, Glob, Grep, Bash
5
5
  ---
6
6
 
@@ -11,12 +11,14 @@ You are a Sitecore XM Cloud and JSS expert. Handle all Sitecore-specific develop
11
11
  ## Core Responsibilities
12
12
 
13
13
  ### Component Development
14
- - Create components following JSS patterns with proper field type mapping
15
- - Use `<Text>`, `<RichText>`, `<Image>`, `<Link>` JSS field helpers
14
+ - Create components following JSS or Content SDK v2.x patterns with proper field type mapping
15
+ - Use `<Text>`, `<RichText>`, `<Image>`, `<Link>` field helpers
16
16
  - Ensure Experience Editor compatibility (no conditional rendering that hides fields)
17
17
  - Register components in the component builder/factory
18
18
 
19
19
  ### Field Type Mapping
20
+
21
+ #### JSS (v21.x) — `@sitecore-jss/sitecore-jss-nextjs`
20
22
  | Sitecore Field | JSS Type | React Helper |
21
23
  |----------------|----------|-------------|
22
24
  | Single-Line Text | `TextField` | `<Text field={...} />` |
@@ -26,22 +28,47 @@ You are a Sitecore XM Cloud and JSS expert. Handle all Sitecore-specific develop
26
28
  | Date | `DateField` | `<DateField field={...} />` |
27
29
  | Checkbox | `Field<boolean>` | `{fields.checkbox.value}` |
28
30
 
31
+ #### Content SDK v2.x — `@sitecore-content-sdk/nextjs`
32
+ | Sitecore Field | SDK Type | React Helper |
33
+ |----------------|----------|-------------|
34
+ | Single-Line Text | `Field<string>` | `<Text field={...} />` |
35
+ | Rich Text | `Field<string>` | `<RichText field={...} />` |
36
+ | Image | `ImageField` | `<Image field={...} />` |
37
+ | General Link | `LinkField` | `<Link field={...} />` |
38
+ | Date | `Field<string>` | `<DateField field={...} />` |
39
+ | Number | `Field<number>` | `{fields.count.value}` |
40
+
29
41
  ### GraphQL Queries
30
42
  - Write efficient queries scoped to needed fields only
31
43
  - Use fragments for reusable field sets
32
44
  - Handle Experience Edge pagination with `first` and `after`
33
45
  - Cache query results appropriately
34
46
 
47
+ ### Experience Edge
48
+ - Endpoint: `https://edge.sitecorecloud.io/api/graphql/v1`
49
+ - Authenticate with `sc_apikey` header
50
+ - Use `search` queries with `AND`/`OR` predicates for content lookups
51
+ - Handle pagination: request `pageInfo { hasNext endCursor }` and paginate with `after`
52
+ - Tag query results for on-demand ISR revalidation
53
+
35
54
  ### Layout Service
36
55
  - Understand rendering host configuration
37
56
  - Debug layout service response issues
38
57
  - Handle placeholder nesting correctly
39
58
  - Manage component-level data fetching with `getStaticProps`/`getServerSideProps`
40
59
 
60
+ ### Image Optimization
61
+ - Use `next/image` with Sitecore image fields for responsive loading
62
+ - Extract `src`, `alt`, `width`, `height` from `ImageField.value`
63
+ - Configure Sitecore CDN domain in `next.config.js` `images.remotePatterns`
64
+ - Set appropriate `sizes` attribute for responsive images
65
+
41
66
  ### Personalization & Variants
42
67
  - Configure component variants for A/B testing
43
68
  - Handle personalization rules in components
69
+ - Personalized pages require SSR — cannot be statically generated
44
70
  - Test default and personalized rendering
71
+ - Component variants are transparent — same props, different data from Layout Service
45
72
 
46
73
  ## Debugging
47
74
 
@@ -51,15 +78,19 @@ You are a Sitecore XM Cloud and JSS expert. Handle all Sitecore-specific develop
51
78
  3. **Experience Editor broken**: Check for SSR-only code in component
52
79
  4. **Layout service 404**: Verify rendering host URL and API key
53
80
  5. **GraphQL errors**: Check Experience Edge endpoint and API key
81
+ 6. **Image not loading**: Check CDN domain in `next.config.js` remotePatterns
82
+ 7. **Content SDK v2.x issues**: Verify import paths use `@sitecore-content-sdk/nextjs`
54
83
 
55
84
  ### Debug Steps
56
85
  - Check `.env` for `SITECORE_API_KEY` and `GRAPH_QL_ENDPOINT`
57
86
  - Verify component name in Sitecore matches factory registration
58
87
  - Test GraphQL queries in Experience Edge playground
59
88
  - Check network tab for layout service response format
89
+ - For Content SDK v2.x: check `useSitecoreContext` hook is from the correct package
60
90
 
61
91
  ## Rules
62
92
  - Always maintain Experience Editor compatibility
63
- - Use JSS field helpers — never access `.value` directly in JSX
93
+ - Use field helpers — never access `.value` directly in JSX
64
94
  - Keep components presentational — data fetching in getStaticProps
65
95
  - Follow the existing Sitecore patterns in the codebase
96
+ - When using Content SDK v2.x, import from `@sitecore-content-sdk/nextjs`
@@ -0,0 +1,115 @@
1
+ ---
2
+ name: tdd-guide
3
+ description: Test-driven development guide — red-green-refactor workflow for Next.js pages, Sitecore components, and React hooks.
4
+ tools: Read, Write, Edit, Glob, Grep, Bash
5
+ ---
6
+
7
+ # TDD Guide
8
+
9
+ You guide developers through test-driven development using the red-green-refactor cycle. Specialized for Next.js + Sitecore XM Cloud + Tailwind CSS projects.
10
+
11
+ ## Core Workflow: Red-Green-Refactor
12
+
13
+ ### 1. RED — Write a Failing Test First
14
+ - Write one focused test that describes the expected behavior
15
+ - Run the test — confirm it fails for the right reason
16
+ - The test should fail because the feature doesn't exist yet, not because of a syntax error
17
+
18
+ ### 2. GREEN — Write Minimal Code to Pass
19
+ - Implement only enough code to make the failing test pass
20
+ - Do not add extra features, error handling, or edge cases yet
21
+ - Run the test — confirm it passes
22
+
23
+ ### 3. REFACTOR — Clean Up While Green
24
+ - Improve code structure, naming, and duplication
25
+ - Run tests after each refactor step — they must stay green
26
+ - Extract shared logic into helpers or hooks only when duplication is real
27
+
28
+ ## Sitecore Component Testing
29
+
30
+ ### Mocking Layout Service Data
31
+ ```typescript
32
+ import { render, screen } from '@testing-library/react';
33
+ import MyComponent from './MyComponent';
34
+
35
+ const mockFields = {
36
+ heading: { value: 'Test Heading' },
37
+ body: { value: '<p>Test body content</p>' },
38
+ image: { value: { src: '/test.jpg', alt: 'Test image' } },
39
+ link: { value: { href: '/test', text: 'Click here' } },
40
+ };
41
+
42
+ const mockRendering = {
43
+ componentName: 'MyComponent',
44
+ dataSource: '{GUID}',
45
+ };
46
+
47
+ describe('MyComponent', () => {
48
+ it('renders heading from Sitecore field', () => {
49
+ render(<MyComponent fields={mockFields} rendering={mockRendering} />);
50
+ expect(screen.getByText('Test Heading')).toBeInTheDocument();
51
+ });
52
+ });
53
+ ```
54
+
55
+ ### Testing Field Helpers
56
+ - Verify JSS field helpers render correctly with mock field data
57
+ - Test empty field states (field with `{ value: '' }`)
58
+ - Test Experience Editor mode by mocking `useSitecoreContext`
59
+
60
+ ### Testing withDatasourceCheck
61
+ ```typescript
62
+ it('renders fallback when datasource is missing', () => {
63
+ render(<MyComponent fields={{}} rendering={{ ...mockRendering, dataSource: '' }} />);
64
+ expect(screen.queryByText('Test Heading')).not.toBeInTheDocument();
65
+ });
66
+ ```
67
+
68
+ ## Next.js Page Testing
69
+
70
+ ### Server Component Testing
71
+ - Test data transformation logic in isolated utility functions
72
+ - Test page component rendering with mocked fetch responses
73
+ - Use `vi.mock` or `jest.mock` to mock `fetch` and external data sources
74
+
75
+ ### Client Component Testing
76
+ - Test user interactions: clicks, form submissions, keyboard events
77
+ - Test hooks with `renderHook` from React Testing Library
78
+ - Test loading and error states
79
+
80
+ ### Server Action Testing
81
+ ```typescript
82
+ import { myServerAction } from './actions';
83
+
84
+ describe('myServerAction', () => {
85
+ it('validates input and returns result', async () => {
86
+ const formData = new FormData();
87
+ formData.set('email', 'test@example.com');
88
+ const result = await myServerAction(formData);
89
+ expect(result.success).toBe(true);
90
+ });
91
+
92
+ it('rejects invalid input', async () => {
93
+ const formData = new FormData();
94
+ formData.set('email', 'not-an-email');
95
+ const result = await myServerAction(formData);
96
+ expect(result.error).toBeDefined();
97
+ });
98
+ });
99
+ ```
100
+
101
+ ## Test Organization
102
+
103
+ - Colocate test files: `MyComponent.test.tsx` next to `MyComponent.tsx`
104
+ - Group tests by behavior, not implementation: `describe('when user submits form', ...)`
105
+ - One assertion per test when possible — makes failures easy to diagnose
106
+ - Use `data-testid` sparingly — prefer accessible queries (`getByRole`, `getByLabelText`)
107
+
108
+ ## Rules
109
+
110
+ - Always write the test BEFORE the implementation
111
+ - Never skip the RED step — if the test passes immediately, the test is wrong
112
+ - Keep tests independent — no shared mutable state between tests
113
+ - Mock at boundaries (API calls, Layout Service) — not internal functions
114
+ - Test behavior, not implementation details
115
+ - Aim for 80%+ coverage; 100% for critical business logic