Skip to content

Commit 6ecd6e0

Browse files
docs: Add AGENTS.md (#1165)
1 parent 76fb870 commit 6ecd6e0

7 files changed

Lines changed: 1728 additions & 0 deletions

File tree

.claude/skills/debug-api/skill.md

Lines changed: 204 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,204 @@
1+
---
2+
name: debug-api
3+
description: Debug HTTP/network/API failures in mParticle Web SDK including fetch failed/fetch error/request failed/API call failed/endpoint not responding/401 unauthorized/403 forbidden/404 not found/500 internal server error/502 bad gateway/503 service unavailable/504 gateway timeout/network error/timeout/ETIMEDOUT/connection timeout/ECONNREFUSED/response format wrong/DTO mismatch/type mismatch in response/unexpected response/null response/undefined response/empty response/missing data/API contract changed/batch upload failed/identity API failed/config API failed/events API failed
4+
---
5+
6+
# API Debug Skill - Web SDK
7+
8+
## Purpose
9+
Diagnose network/API failures in the mParticle Web SDK through systematic request/response inspection and API client debugging.
10+
11+
## Core Principles
12+
- **Network tab is truth**: Inspect actual requests, not assumptions
13+
- **Mock vs real divergence**: fetch-mock works but real API fails → contract drift
14+
- **Batch timing matters**: Events batched before upload (100 events or 30 seconds)
15+
- **Three API systems**: Events, Identity, and Config APIs have different shapes
16+
17+
## Architecture Context
18+
HTTP clients in `src/apiClient.ts` (Events), `src/identityApiClient.ts` (Identity), `src/configAPIClient.ts` (Config). Uses fetch API. Batch upload in `src/batchUploader.ts`. Tests use fetch-mock for HTTP mocking.
19+
20+
## Failure Classification
21+
22+
**Request never sent:**
23+
- Network offline → browser blocking
24+
- Batch not full → waiting for 100 events or 30 second interval
25+
- API client not initialized → SDK init failed
26+
- Config disabled feature → server config blocking
27+
28+
**Request fails:**
29+
- 401 → Auth token invalid/expired
30+
- 403 → Workspace permissions issue
31+
- 404 → URL wrong (trailing slash, workspace ID, endpoint)
32+
- 500 → Backend error (check server logs)
33+
- Timeout → slow network/server hang
34+
- CORS → should not happen with mParticle APIs (same-origin or configured)
35+
36+
**Response wrong:**
37+
- DTO mismatch → backend changed contract
38+
- Null/undefined → optional fields missing
39+
- Type error → response shape unexpected
40+
- Empty response → valid but no data
41+
42+
**SDK-specific issues:**
43+
- Batch upload stuck → timer not advancing
44+
- Identity callback not fired → response parsing failed
45+
- Config not loading → initial config fetch failed
46+
- Events not forwarding → kits not initialized
47+
48+
## Investigation Strategy
49+
50+
### 1. Network Inspection
51+
Use browser DevTools Network tab:
52+
- Request URL (exact match with workspace ID)
53+
- Request headers (Content-Type, User-Agent)
54+
- Request payload (batch structure, identity request)
55+
- Response status (200/401/403/404/500)
56+
- Response body (success flags, error messages)
57+
- Timing (slow? timeout?)
58+
59+
### 2. API Client State
60+
Log client state:
61+
```typescript
62+
// In apiClient.ts
63+
console.log({ url, payload, config: mpInstance._Store })
64+
65+
// In identityApiClient.ts
66+
console.log({ identityRequest, callback })
67+
68+
// In batchUploader.ts
69+
console.log({ batchSize, uploadInterval, queuedEvents })
70+
```
71+
72+
### 3. Verify API Endpoints
73+
Check endpoint construction:
74+
- Events: `/v1/[workspace]/events`
75+
- Identity: `/v1/[workspace]/identify` (or `/login`, `/logout`, `/modify`)
76+
- Config: `/v1/[workspace]/config`
77+
78+
Ensure workspace ID (devToken/apiKey) is correct.
79+
80+
### 4. fetch-mock vs Real API
81+
If fetch-mock works but real fails:
82+
- Compare mock URL vs real endpoint
83+
- Check mock response shape vs real DTO
84+
- Verify auth headers match
85+
- Look for hardcoded test data
86+
87+
## Common Root Causes
88+
89+
**Auth failures:**
90+
- API key (devToken) missing or wrong
91+
- API key passed incorrectly in request
92+
- Workspace disabled or suspended
93+
- Environment mismatch (dev key in production)
94+
95+
**Events API issues:**
96+
- Batch structure malformed
97+
- Event validation failed (data plan)
98+
- Consent state blocking events
99+
- Kit filtering rules blocking
100+
101+
**Identity API issues:**
102+
- Identity request validation failed
103+
- MPID not found (new user)
104+
- Identity callback error → silent failure
105+
- User identities malformed
106+
107+
**Config API issues:**
108+
- Config fetch failed → kits not initialized
109+
- Config cache stale → using old settings
110+
- Server-side config override → unexpected behavior
111+
112+
**Batch upload issues:**
113+
- Timer not advancing → events never sent
114+
- Batch size threshold not met → waiting for 100 events
115+
- Upload interval not met → waiting for 30 seconds
116+
- Network offline → queued but not sent
117+
118+
## Obscure Debugging Vectors
119+
120+
- **Network throttling**: Fast 3G reveals timeout issues
121+
- **Disable cache**: Force fresh requests to test caching theory
122+
- **Copy as fetch**: Right-click network request → replay in console
123+
- **fetch-mock logging**: Enable fetch-mock logging in tests
124+
- **Batch queue inspection**: Log `mpInstance._Batch` to see queued events
125+
- **Identity MPID check**: Verify MPID exists in localStorage
126+
- **Config inspection**: Check `mpInstance._Store` for loaded config
127+
- **Session ID check**: Verify session ID in event payload
128+
129+
## Debugging Flow
130+
131+
1. Reproduce failure, open network tab
132+
2. Identify request: sent? failed? wrong response?
133+
3. Check API key (devToken) in request
134+
4. Verify endpoint URL format (workspace ID, path)
135+
5. Compare fetch-mock handler vs real API response
136+
6. Log API client state before/after request
137+
7. Check batch queue status (if Events API)
138+
8. Test with network throttling enabled
139+
140+
## Success Criteria
141+
- Request succeeds with correct response
142+
- Events uploaded to mParticle servers
143+
- Identity callbacks fire correctly
144+
- Config loaded and applied
145+
- Works across 3+ attempts (no fluke)
146+
- Screenshot: network tab + successful response
147+
148+
## SDK-Specific API Patterns
149+
150+
**Events API (`/v1/[workspace]/events`):**
151+
- Batch of events in payload
152+
- Response indicates success/failure per event
153+
- Retry logic for failed uploads
154+
- Validate event structure before sending
155+
156+
**Identity API (`/v1/[workspace]/identify`):**
157+
- Single identity request
158+
- Callback with result (success/error)
159+
- MPID returned in response
160+
- User identities in request
161+
162+
**Config API (`/v1/[workspace]/config`):**
163+
- Fetched on SDK init
164+
- Contains kit configurations
165+
- Workspace settings
166+
- Feature flags
167+
168+
**Common Headers:**
169+
```
170+
Content-Type: application/json
171+
User-Agent: mParticle web SDK
172+
```
173+
174+
## Test Debugging
175+
176+
**fetch-mock configuration:**
177+
```typescript
178+
import fetchMock from 'fetch-mock/esm/client'
179+
180+
fetchMock.post('/v1/test-workspace/events', {
181+
status: 200,
182+
body: { Store: true }
183+
})
184+
```
185+
186+
**Verify mock called:**
187+
```typescript
188+
expect(fetchMock.called('/v1/test-workspace/events')).toBe(true)
189+
```
190+
191+
**Check request payload:**
192+
```typescript
193+
const calls = fetchMock.calls('/v1/test-workspace/events')
194+
console.log(JSON.parse(calls[0][1].body))
195+
```
196+
197+
## Self-Improvement
198+
**CRITICAL**: Update with:
199+
- Events API contract changes
200+
- Identity API error patterns
201+
- Config API structure updates
202+
- Batch upload timing solutions
203+
- fetch-mock anti-patterns
204+
- Common SDK API failures
Lines changed: 190 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,190 @@
1+
---
2+
name: debug-build
3+
description: Debug TypeScript/Rollup build failures in mParticle Web SDK including TS2307 cannot find module/TS2345 argument type mismatch/TS2339 property doesn't exist/TS2322 type not assignable/TS2532 object possibly undefined/TS2554 expected X arguments/TS2769 no overload matches/TS7006 implicit any/TS7053 element implicitly has any/compilation error/compilation failed/compile error/tsc failed/tsc error/build failed/build error/rollup error/module not found/cannot resolve module/cannot find module/failed to resolve/import error/export error/declaration file missing/missing type declarations/@types package missing/bundle error/bundling failed/chunk load error
4+
---
5+
6+
# Build Debug Skill - Web SDK
7+
8+
## Purpose
9+
Fix TypeScript compilation and Rollup bundling failures in the mParticle Web SDK that block development and deployment.
10+
11+
## Core Principles
12+
- **Types are contracts**: TS errors reveal actual vs expected interfaces
13+
- **Module resolution is path math**: Cannot find module → path calculation wrong
14+
- **Avoid `any`**: Use proper types where possible, but SDK has strictNullChecks=false
15+
- **Build before test**: TS errors block everything downstream
16+
17+
## Architecture Context
18+
TypeScript in `tsconfig.json` (ES5 target, no strict mode). Rollup in `rollup.config.js` builds IIFE, CommonJS, and ESM bundles. Build must pass before dev/test/deploy.
19+
20+
## Failure Classification
21+
22+
**Type errors:**
23+
- TS2307: Cannot find module → import path wrong or missing declaration
24+
- TS2345: Argument type mismatch → function signature changed
25+
- TS2339: Property doesn't exist → interface outdated or typo
26+
- TS2322: Type not assignable → incompatible types
27+
- TS2769: No overload matches → wrong argument count/types
28+
- TS7006: Implicit any → no type annotation (less strict in this SDK)
29+
30+
**Module resolution:**
31+
- Cannot find module → path wrong, file moved, extension missing
32+
- Circular dependency → A imports B imports A
33+
- Ambient module missing → @types package not installed
34+
- Path mapping wrong → tsconfig paths not resolving
35+
36+
**Rollup errors:**
37+
- Module not found → file path incorrect or missing
38+
- Chunk size exceeded → bundle too large (check with `npm run bundle`)
39+
- Plugin failure → Rollup plugin crashed (Babel, TypeScript, Uglify)
40+
- Circular dependency warning → refactor to break cycle
41+
42+
**Build output issues:**
43+
- IIFE format broken → browser <script> tag fails
44+
- CommonJS format broken → npm package fails
45+
- ESM format broken → modern bundlers fail
46+
- Stub file broken → pre-init capture fails
47+
48+
## Investigation Strategy
49+
50+
### 1. Locate Error
51+
Build output shows:
52+
- File path and line number
53+
- Error code (TS2XXX)
54+
- Expected vs actual types
55+
- Quick fix suggestions
56+
57+
Navigate to exact location.
58+
59+
### 2. Check Recent Changes
60+
- What file was last modified?
61+
- Did interface change?
62+
- Was dependency added/removed?
63+
- Did someone add untyped code?
64+
65+
### 3. Validate Types
66+
Hover in IDE to see inferred types:
67+
- What does TS think this is?
68+
- Does it match expectation?
69+
- Where did inference go wrong?
70+
71+
### 4. Module Resolution Debug
72+
Check import path:
73+
- Relative vs absolute correct?
74+
- File extension needed?
75+
- Index file exists?
76+
- tsconfig paths configured?
77+
78+
## Common Root Causes
79+
80+
**TS2307 Cannot find module:**
81+
- Import path relative/absolute wrong
82+
- File extension required but missing (.ts/.js)
83+
- File moved but import not updated
84+
- @types package missing (`npm install -D @types/package`)
85+
- tsconfig paths not including directory
86+
87+
**TS2345 Argument type mismatch:**
88+
- Function signature changed upstream
89+
- Optional param became required
90+
- Type widened/narrowed
91+
- Generic constraint violated
92+
93+
**TS2339 Property doesn't exist:**
94+
- Interface outdated (API contract changed)
95+
- Typo in property name
96+
- Property optional but not checked (use `?.`)
97+
- Type guard failed (narrowing didn't work)
98+
99+
**Circular dependency:**
100+
- A imports B, B imports A → refactor to shared file
101+
- Barrel export (index.ts) imports from files that import it
102+
- Type-only import can break cycle: `import type { X } from './y'`
103+
104+
**Rollup module not found:**
105+
- Import path incorrect for Rollup resolution
106+
- File extension required for some imports
107+
- Plugin order wrong in rollup.config.js
108+
- Node module not installed
109+
110+
## Obscure Debugging Vectors
111+
112+
- **npm run build:ts**: TypeScript compilation only (faster than full build)
113+
- **tsc --noEmit**: Check types without building
114+
- **tsc --traceResolution**: See module resolution path
115+
- **tsc --listFiles**: All files included in compilation
116+
- **npm run bundle**: Check minified bundle size (uglify + gzip)
117+
- **rollup --environment BUILD:iife**: Build only IIFE format
118+
- **VSCode restart**: Language server cache stale
119+
- **Check dist/ output**: Verify all three formats generated
120+
121+
## Debugging Flow
122+
123+
1. Run build: `npm run build` or `npm run build:ts`
124+
2. Read first error (fix top-down, errors cascade)
125+
3. Navigate to file:line
126+
4. Check recent changes to that file
127+
5. Validate types with IDE hover
128+
6. Fix issue (import, type, signature)
129+
7. Re-run build (verify no cascade errors)
130+
8. Run `npm run bundle` to verify bundle size
131+
9. Run full test suite to confirm
132+
133+
## Success Criteria
134+
- `npm run build` completes successfully
135+
- All three bundles generated (IIFE, CommonJS, ESM)
136+
- Bundle size reasonable (check with `npm run bundle`)
137+
- No new implicit `any` types introduced
138+
- Stub file generated correctly
139+
- Screenshot: successful build output
140+
141+
## SDK-Specific Build Targets
142+
143+
**IIFE bundle (dist/mparticle.js):**
144+
- Browser <script> tag usage
145+
- Global `mParticle` variable
146+
- Minified with Uglify
147+
148+
**CommonJS (dist/mparticle.common.js):**
149+
- npm/Node.js environments
150+
- `require('mparticle')` syntax
151+
152+
**ESM (dist/mparticle.esm.js):**
153+
- Modern bundlers
154+
- Tree-shaking support
155+
- `import mParticle from 'mparticle'`
156+
157+
**Stub (dist/mparticle.stub.js):**
158+
- Pre-init API call capture
159+
- Async snippet loading
160+
161+
## Build Commands Reference
162+
163+
```bash
164+
# Full build (all formats)
165+
npm run build
166+
167+
# Individual formats
168+
npm run build:iife # Browser bundle
169+
npm run build:npm # CommonJS
170+
npm run build:esm # ES Modules
171+
npm run build:stub # Stub file
172+
173+
# Development
174+
npm run build:dev # Dev build with sourcemaps
175+
npm run watch # Watch IIFE and rebuild
176+
npm run watch:all # Watch all formats
177+
178+
# Analysis
179+
npm run bundle # Uglify + gzip for size
180+
npm run uglify # Minify only
181+
npm run gzip # Gzip only
182+
```
183+
184+
## Self-Improvement
185+
**CRITICAL**: Update with:
186+
- Module resolution patterns specific to Rollup
187+
- Type inference gotchas in non-strict mode
188+
- Rollup configuration issues
189+
- Build performance optimizations
190+
- Common SDK build failures

0 commit comments

Comments
 (0)