CodePress Engine Development
A skill for developing and testing the CodePress HTML Babel plugin, which enables visual editing of React/JSX applications through encoded DOM attributes and a development server.
What This Skill Does
Helps you work on the codepress-engine project by following established conventions for code style, testing, and architecture. The project consists of a Babel plugin (index.js) that injects metadata into JSX elements and a Fastify development server (server.js) that handles visual editing operations.
Step-by-Step Instructions
1. Understanding the Architecture
Before making changes, understand the two-part system:
**Babel Plugin (index.js)**:
Injects encoded file path and line number attributes into JSX elementsAuto-detects git branch and repository informationUses XOR encryption for file paths with URL-safe base64 encodingAdds repository/branch info only to container elementsZero configuration required**Development Server (server.js)**:
Fastify-based HTTP server with CORS supportTwo API endpoints: `/visual-editor-api` (regular) and `/visual-editor-api-ai` (AI-powered)Text change engine supporting insert, delete, and replace operationsPrettier integration for code formattingImage processing and file saving capabilitiesBackend API integration with authentication2. Running Build and Test Commands
Use these commands for common development tasks:
```bash
Build the plugin
npm run build
Run all tests (42 tests total)
npm test
Run specific test
npx jest test/index.test.js -t "test description"
Test server functionality
npx jest test/server.test.js
Lint the code
npx eslint src/
```
3. Code Style Guidelines
**JavaScript Conventions**:
Group imports: NodeJS core → third-party → localUse camelCase for variables/functions, PascalCase for classesNamed function expressions with JSDoc commentsComprehensive try/catch blocks with descriptive errors2-space indentation, use semicolonsPrefer async/await over raw promisesInclude JSDoc type annotations for parameters and returns**Plugin Configuration**:
Pass options directly to Babel pluginAuto-detect git information (no manual override)Use sensible defaults for optional parametersDocument all options with JSDocValidate and normalize optionsProvide colored console feedback**Server Architecture**:
Use Fastify patterns and pluginsImplement comprehensive request validationHandle errors with proper HTTP status codesUse service functions for separation of concernsImplement authentication and CORS properlyFormat code with Prettier after modifications4. Writing Tests
**Testing Principles**:
Write unit tests for all public functionsMock external dependencies (fs, os, node-fetch, prettier)Isolate tests from environment dependenciesTest both success and error scenariosUse proper Jest mocking patternsVerify all API endpoints and operations**Plugin Tests** (test/index.test.js):
JSX attribute injection with line numbersGit branch and repository detectionFile path encoding/decodingProduction mode safetyNode modules exclusion**Server Tests** (test/server.test.js):
Visual editor API endpointsText insert/delete/replace operationsRequest validation for regular and AI modesImage handling (base64 processing)Backend API communicationError handling scenarios5. Making Changes
**Before modifying code**:
1. Read the relevant files (index.js or server.js)
2. Review existing tests to understand expected behavior
3. Check JSDoc comments for function contracts
4. Understand the encoding/decoding system if working with file paths
**When adding features**:
1. Update JSDoc comments with new parameters/behavior
2. Add corresponding tests to the test suite
3. Ensure existing tests still pass
4. Update this guide if architecture changes
5. Run linting to verify code style
**When fixing bugs**:
1. Write a failing test that reproduces the bug
2. Implement the fix
3. Verify the test now passes
4. Check for similar issues elsewhere in the codebase
6. Key Architecture Patterns
**Encoding System** (index.js):
XOR encryption for file pathsURL-safe base64 encodingDecode with same XOR key to retrieve original path**Text Change Engine** (server.js):
Insert: Add text at specific positionDelete: Remove character rangeReplace: Substitute text between positionsAll operations preserve file structure**Service Functions** (server.js):
`applyTextChanges()`: Process text modifications`callCodepressBackend()`: Communicate with backend API`formatWithPrettier()`: Apply code formatting`saveBase64Image()`: Handle image uploadsImportant Constraints
**Environment**: Server only runs in development mode**Production Safety**: Plugin is safe for production with no external dependencies**File Locking**: Server uses lock file for single instance operation**Authentication**: Supports both API tokens and OAuth**Error Handling**: All errors must have descriptive messages and proper HTTP status codesExamples
**Adding a new API endpoint**:
```javascript
// In server.js
fastify.post('/new-endpoint', {
schema: {
body: {
type: 'object',
required: ['param1'],
properties: {
param1: { type: 'string' }
}
}
}
}, async (request, reply) => {
try {
// Implement endpoint logic
return { success: true };
} catch (error) {
console.error('Error:', error);
return reply.status(500).send({ error: error.message });
}
});
```
**Testing the new endpoint**:
```javascript
// In test/server.test.js
describe('New endpoint tests', () => {
it('should handle valid request', async () => {
const response = await app.inject({
method: 'POST',
url: '/new-endpoint',
payload: { param1: 'value' }
});
expect(response.statusCode).toBe(200);
expect(response.json()).toHaveProperty('success', true);
});
});
```