Skip to content

Commit 51b4a5d

Browse files
author
naman-contentstack
committed
Merge branch 'v2-dev' into feat/DX-5418
2 parents 592569b + 99fb6a3 commit 51b4a5d

95 files changed

Lines changed: 11800 additions & 2529 deletions

File tree

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

.cursor/commands/code-review.md

Lines changed: 122 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,122 @@
1+
---
2+
name: code-review
3+
description: Automated PR review using comprehensive checklist tailored for Contentstack CLI plugins
4+
---
5+
6+
# Code Review Command
7+
8+
## Usage Patterns
9+
10+
### Scope-Based Reviews
11+
- `/code-review` - Review all current changes with full checklist
12+
- `/code-review --scope typescript` - Focus on TypeScript configuration and patterns
13+
- `/code-review --scope testing` - Focus on Mocha/Chai/Sinon test patterns
14+
- `/code-review --scope contentstack` - Focus on API integration and CLI patterns
15+
- `/code-review --scope oclif` - Focus on command structure and OCLIF patterns
16+
17+
### Severity Filtering
18+
- `/code-review --severity critical` - Show only critical issues (security, breaking changes)
19+
- `/code-review --severity high` - Show high and critical issues
20+
- `/code-review --severity all` - Show all issues including suggestions
21+
22+
### Package-Aware Reviews
23+
- `/code-review --package contentstack-import` - Review changes in specific package
24+
- `/code-review --package-type plugin` - Review plugin packages only
25+
- `/code-review --package-type library` - Review library packages (e.g., variants)
26+
27+
### File Type Focus
28+
- `/code-review --files commands` - Review command files only
29+
- `/code-review --files tests` - Review test files only
30+
- `/code-review --files modules` - Review import/export modules
31+
32+
## Comprehensive Review Checklist
33+
34+
### Monorepo Structure Compliance
35+
- **Package organization**: Proper placement in `packages/` structure
36+
- **pnpm workspace**: Correct `package.json` workspace configuration
37+
- **Build artifacts**: No `lib/` directories committed to version control
38+
- **Dependencies**: Proper use of shared utilities (`@contentstack/cli-command`, `@contentstack/cli-utilities`)
39+
40+
### TypeScript Standards (Repository-Specific)
41+
- **Configuration compliance**: Follows package-specific TypeScript config
42+
- **Naming conventions**: kebab-case files, PascalCase classes, camelCase functions
43+
- **Type safety**: Appropriate use of strict mode vs relaxed settings per package
44+
- **Import patterns**: ES modules with proper default/named exports
45+
- **Migration strategy**: Proper use of `@ts-ignore` during gradual migration
46+
47+
### OCLIF Command Patterns (Actual Implementation)
48+
- **Base class usage**: Extends `@contentstack/cli-command` (not `@oclif/core`)
49+
- **Command structure**: Proper `static description`, `examples`, `flags`
50+
- **Topic organization**: Uses `cm` topic structure (`cm:stacks:import`)
51+
- **Error handling**: Uses `handleAndLogError` from utilities
52+
- **Validation**: Early flag validation and user-friendly error messages
53+
- **Service delegation**: Commands orchestrate, services implement business logic
54+
55+
### Testing Excellence (Mocha/Chai/Sinon Stack)
56+
- **Framework compliance**: Uses Mocha + Chai + Sinon (not Jest)
57+
- **File patterns**: Follows `*.test.ts` naming (or `*.test.js` for bootstrap)
58+
- **Directory structure**: Proper placement in `test/unit/`, `test/lib/`, etc.
59+
- **Mock patterns**: Proper Sinon stubbing of SDK methods
60+
- **Coverage configuration**: Correct nyc setup (watch for `inlcude` typo)
61+
- **Test isolation**: Proper `beforeEach`/`afterEach` with `sinon.restore()`
62+
- **No real API calls**: All external dependencies properly mocked
63+
64+
### Contentstack API Integration (Real Patterns)
65+
- **SDK usage**: Proper `managementSDKClient` and fluent API chaining
66+
- **Authentication**: Correct `configHandler` and token alias handling
67+
- **Rate limiting compliance**:
68+
- Batch spacing (minimum 1 second between batches)
69+
- 429 retry handling with exponential backoff
70+
- Pagination throttling for variants
71+
- **Error handling**: Proper `handleAndLogError` usage and user-friendly messages
72+
- **Configuration**: Proper regional endpoint and management token handling
73+
74+
### Import/Export Module Architecture
75+
- **BaseClass extension**: Proper inheritance from import/export BaseClass
76+
- **Batch processing**: Correct use of `makeConcurrentCall` and `logMsgAndWaitIfRequired`
77+
- **Module organization**: Proper entity-specific module structure
78+
- **Configuration handling**: Proper `ModuleClassParams` usage
79+
- **Progress feedback**: Appropriate user feedback during long operations
80+
81+
### Security and Best Practices
82+
- **Token security**: No API keys or tokens logged or committed
83+
- **Input validation**: Proper validation of user inputs and flags
84+
- **Error exposure**: No sensitive information in error messages
85+
- **File permissions**: Proper handling of file system operations
86+
- **Process management**: Appropriate use of `process.exit(1)` for critical failures
87+
88+
### Performance Considerations
89+
- **Concurrent processing**: Proper use of `Promise.allSettled` for batch operations
90+
- **Memory management**: Appropriate handling of large datasets
91+
- **Rate limiting**: Compliance with Contentstack API limits (10 req/sec)
92+
- **Batch sizing**: Appropriate batch sizes for different operations
93+
- **Progress tracking**: Efficient progress reporting without performance impact
94+
95+
### Package-Specific Patterns
96+
- **Plugin vs Library**: Correct `oclif.commands` configuration for plugin packages
97+
- **Command compilation**: Proper build pipeline (`tsc``lib/commands``oclif manifest`)
98+
- **Dependency management**: Correct use of shared vs package-specific dependencies
99+
- **Test variations**: Handles different test patterns per package (JS vs TS, different structures)
100+
101+
## Review Execution
102+
103+
### Automated Checks
104+
1. **Lint compliance**: ESLint and TypeScript compiler checks
105+
2. **Test coverage**: nyc coverage thresholds (where enforced)
106+
3. **Build verification**: Successful compilation to `lib/` directories
107+
4. **Dependency audit**: No security vulnerabilities in dependencies
108+
109+
### Manual Review Focus Areas
110+
1. **API integration patterns**: Verify proper SDK usage and error handling
111+
2. **Rate limiting implementation**: Check for proper throttling mechanisms
112+
3. **Test quality**: Verify comprehensive mocking and error scenario coverage
113+
4. **Command usability**: Ensure clear help text and examples
114+
5. **Monorepo consistency**: Check for consistent patterns across packages
115+
116+
### Common Issues to Flag
117+
- **Coverage config typos**: `"inlcude"` instead of `"include"` in `.nycrc.json`
118+
- **Inconsistent TypeScript**: Mixed strict mode usage without migration plan
119+
- **Real API calls in tests**: Any unmocked external dependencies
120+
- **Missing rate limiting**: API calls without proper throttling
121+
- **Build artifacts committed**: Any `lib/` directories in version control
122+
- **Inconsistent error handling**: Not using utilities error handling patterns

.cursor/commands/execute-tests.md

Lines changed: 107 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,107 @@
1+
---
2+
name: execute-tests
3+
description: Run tests by scope, file, or module with intelligent filtering for this pnpm monorepo
4+
---
5+
6+
# Execute Tests Command
7+
8+
## Usage Patterns
9+
10+
### Monorepo-Wide Testing
11+
- `/execute-tests` - Run all tests across all packages
12+
- `/execute-tests --coverage` - Run all tests with nyc coverage report
13+
- `/execute-tests --parallel` - Run package tests in parallel using pnpm
14+
15+
### Package-Specific Testing
16+
- `/execute-tests packages/contentstack-audit/` - Run tests for specific package
17+
- `/execute-tests packages/contentstack-import/` - Run import package tests
18+
- `/execute-tests packages/contentstack-export/` - Run export package tests
19+
- `/execute-tests contentstack-migration` - Run tests by package name (shorthand)
20+
21+
### Scope-Based Testing
22+
- `/execute-tests unit` - Run unit tests only (`test/unit/**/*.test.ts`)
23+
- `/execute-tests commands` - Run command tests (`test/commands/**/*.test.ts`)
24+
- `/execute-tests services` - Run service layer tests
25+
- `/execute-tests modules` - Run import/export module tests
26+
27+
### File Pattern Testing
28+
- `/execute-tests *.test.ts` - Run all TypeScript tests
29+
- `/execute-tests *.test.js` - Run JavaScript tests (bootstrap package)
30+
- `/execute-tests test/unit/services/` - Run tests for specific directory
31+
32+
### Watch and Development
33+
- `/execute-tests --watch` - Run tests in watch mode with file monitoring
34+
- `/execute-tests --debug` - Run tests with debug output enabled
35+
- `/execute-tests --bail` - Stop on first test failure
36+
37+
## Intelligent Filtering
38+
39+
### Repository-Aware Detection
40+
- **Test patterns**: Primarily `*.test.ts`, some `*.test.js` (bootstrap), rare `*.spec.ts`
41+
- **Directory structures**: `test/unit/`, `test/lib/`, `test/seed/`, `test/commands/`
42+
- **Package variations**: Different test layouts per package
43+
- **Build exclusion**: Ignores `lib/` directories (compiled artifacts)
44+
45+
### Monorepo Integration
46+
- **pnpm workspace support**: Uses `pnpm -r --filter` for package targeting
47+
- **Dependency awareness**: Understands package interdependencies
48+
- **Parallel execution**: Leverages pnpm's parallel capabilities
49+
- **Selective testing**: Can target specific packages or file patterns
50+
51+
### Framework Detection
52+
- **Mocha configuration**: Respects `.mocharc.json` files per package
53+
- **TypeScript compilation**: Handles `pretest: tsc -p test` scripts
54+
- **Coverage integration**: Works with nyc configuration (`.nycrc.json`)
55+
- **Test helpers**: Detects and includes test initialization files
56+
57+
## Execution Examples
58+
59+
### Common Workflows
60+
```bash
61+
# Run all tests with coverage
62+
/execute-tests --coverage
63+
64+
# Test specific package during development
65+
/execute-tests packages/contentstack-import/ --watch
66+
67+
# Run only unit tests across all packages
68+
/execute-tests unit
69+
70+
# Test import/export modules specifically
71+
/execute-tests modules --coverage
72+
73+
# Debug failing tests in audit package
74+
/execute-tests packages/contentstack-audit/ --debug --bail
75+
```
76+
77+
### Package-Specific Commands Generated
78+
```bash
79+
# For contentstack-import package
80+
cd packages/contentstack-import && pnpm test
81+
82+
# For all packages with coverage
83+
pnpm -r --filter './packages/*' run test:coverage
84+
85+
# For specific test file
86+
cd packages/contentstack-export && npx mocha test/unit/export/modules/stack.test.ts
87+
```
88+
89+
## Configuration Awareness
90+
91+
### Mocha Integration
92+
- Respects individual package `.mocharc.json` configurations
93+
- Handles TypeScript compilation via `ts-node/register`
94+
- Supports test helpers and initialization files
95+
- Manages timeout settings per package
96+
97+
### Coverage Integration
98+
- Uses nyc for coverage reporting
99+
- Respects `.nycrc.json` configurations (with typo detection)
100+
- Generates HTML, text, and lcov reports
101+
- Handles TypeScript source mapping
102+
103+
### pnpm Workspace Features
104+
- Leverages workspace dependency resolution
105+
- Supports filtered execution by package patterns
106+
- Enables parallel test execution across packages
107+
- Respects package-specific scripts and configurations

.cursor/rules/contentstack-cli.mdc

Lines changed: 165 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,165 @@
1+
---
2+
description: 'Contentstack CLI specific patterns and API integration'
3+
globs: ['**/import/**/*.ts', '**/export/**/*.ts', '**/modules/**/*.ts', '**/services/**/*.ts', '**/utils/**/*.ts']
4+
alwaysApply: false
5+
---
6+
7+
# Contentstack CLI Standards
8+
9+
## API Integration
10+
11+
- Use `@contentstack/cli-utilities` for SDK factory: `managementSDKClient(config)`
12+
- Stack-scoped API access: `stackAPIClient.asset()`, `stackAPIClient.extension()`
13+
- Fluent SDK chaining: `stack.contentType().entry().query().find()`
14+
- Custom HTTP for variants: `apiClient.put/get` with path strings
15+
16+
## Authentication
17+
18+
- Use `@contentstack/cli-utilities` for token management
19+
- Management token alias: `configHandler.get('tokens.<alias>')`
20+
- OAuth context: `configHandler.get('userUid'|'email'|'oauthOrgUid')`
21+
- Authentication check: `isAuthenticated()` before operations
22+
- Never log API keys or tokens in console or files
23+
24+
## Rate Limiting - Multiple Mechanisms
25+
26+
### Batch Spacing (Import/Export)
27+
```typescript
28+
// ✅ GOOD - Ensure minimum 1 second between batches
29+
async logMsgAndWaitIfRequired(processName: string, start: number): Promise<void> {
30+
const end = Date.now();
31+
const exeTime = end - start;
32+
if (exeTime < 1000) await this.delay(1000 - exeTime);
33+
}
34+
```
35+
36+
### 429 Retry (Branches)
37+
```typescript
38+
// ✅ GOOD - Handle 429 with retry
39+
export async function handleErrorMsg(err, retryCallback?: () => Promise<any>) {
40+
if (err?.status === 429 || err?.response?.status === 429) {
41+
await new Promise((resolve) => setTimeout(resolve, 1000)); // 1 sec delay
42+
if (retryCallback) {
43+
return retryCallback(); // Retry the request
44+
}
45+
}
46+
}
47+
```
48+
49+
### Variant Pagination Throttle
50+
```typescript
51+
// ✅ GOOD - Throttle variant API requests
52+
if (requestTime < 1000) {
53+
await delay(1000 - requestTime);
54+
}
55+
```
56+
57+
## Error Handling
58+
59+
### Standard Pattern
60+
```typescript
61+
// ✅ GOOD - Use handleAndLogError from utilities
62+
try {
63+
const result = await this.stack.contentType().entry().fetch();
64+
} catch (error) {
65+
handleAndLogError(error);
66+
this.logAndPrintErrorDetails(error, config);
67+
}
68+
```
69+
70+
### User-Friendly Errors
71+
```typescript
72+
// ✅ GOOD - User-facing error display
73+
cliux.print(errorMessage, { color: 'red' });
74+
// For critical failures
75+
process.exit(1);
76+
```
77+
78+
## Module Architecture (Import/Export)
79+
80+
### BaseClass Pattern
81+
```typescript
82+
// ✅ GOOD - Extend BaseClass for entity modules
83+
export class ContentTypes extends BaseClass {
84+
constructor(params: ModuleClassParams) {
85+
super(params);
86+
// Entity-specific initialization
87+
}
88+
89+
async import(): Promise<void> {
90+
// Use this.makeConcurrentCall for batching
91+
// Use this.logMsgAndWaitIfRequired for rate limiting
92+
}
93+
}
94+
```
95+
96+
### Batch Processing
97+
```typescript
98+
// ✅ GOOD - Concurrent batch processing
99+
const batches = chunk(apiContent, batchSize);
100+
for (const batch of batches) {
101+
const start = Date.now();
102+
await this.makeConcurrentCall(batch, this.processItem.bind(this));
103+
await this.logMsgAndWaitIfRequired('Processing', start, batches.length, batchIndex);
104+
}
105+
```
106+
107+
## Configuration Patterns
108+
109+
### Import/Export Config
110+
```typescript
111+
// ✅ GOOD - Use configHandler for management tokens
112+
const config = {
113+
host: configHandler.get('region.cma'),
114+
managementTokenAlias: flags.alias,
115+
stackApiKey: flags['stack-api-key'],
116+
rateLimit: 5, // Default rate limit
117+
};
118+
```
119+
120+
### Regional Configuration
121+
```typescript
122+
// ✅ GOOD - Handle regional endpoints
123+
const defaultConfig = {
124+
host: 'https://api.contentstack.io',
125+
cdn: 'https://cdn.contentstack.io',
126+
// Regional developer hub URLs
127+
};
128+
```
129+
130+
## Testing Patterns
131+
132+
### SDK Mocking
133+
```typescript
134+
// ✅ GOOD - Mock stack client methods
135+
const mockStackClient = {
136+
fetch: sinon.stub().resolves({ name: 'Test Stack', uid: 'stack-uid' }),
137+
locale: sinon.stub().returns({
138+
query: sinon.stub().returns({
139+
find: sinon.stub().resolves({ items: [], count: 0 }),
140+
}),
141+
}),
142+
};
143+
```
144+
145+
### Error Simulation
146+
```typescript
147+
// ✅ GOOD - Test error handling
148+
it('should handle 429 rate limit', async () => {
149+
const error = { status: 429 };
150+
mockClient.fetch.rejects(error);
151+
// Test retry logic
152+
});
153+
```
154+
155+
## Package-Specific Patterns
156+
157+
### Plugin vs Library
158+
- **Plugin packages**: Have `oclif.commands` in package.json
159+
- **Library packages** (e.g., variants): No OCLIF commands, consumed by other packages
160+
161+
### Monorepo Structure
162+
- Commands: `packages/*/src/commands/cm/**/*.ts`
163+
- Modules: `packages/*/src/{import,export,modules}/**/*.ts`
164+
- Utilities: `packages/*/src/utils/**/*.ts`
165+
- Built artifacts: `packages/*/lib/**` (not source)

0 commit comments

Comments
 (0)