Contributing Guidelines

This document provides comprehensive guidelines for contributing to WooAI Chatbot Pro. Following these standards ensures consistent, maintainable code and streamlined collaboration.

TL;DR: Fork → Branch → Code → Test → PR. We review within 48h usually.

Please don't:


1. Getting Started

Prerequisites

Ensure your development environment meets these requirements:

Requirement Minimum Version Recommended
PHP 8.1 8.2+
Node.js 18.0.0 20 LTS
npm 9.0.0 10+
Composer 2.0 2.7+
WordPress 6.0 6.4+
WooCommerce 8.0 9.0+

Repository Structure

WP_plugin_chat_ai/
├── assets/                 # Frontend assets (compiled)
│   ├── admin/             # Admin panel assets
│   └── chat/              # Chat widget assets
├── assets/src/            # Source TypeScript/React files
├── includes/              # PHP source (PSR-4 autoloaded)
├── templates/             # PHP template files
├── tests/                 # Test suites
├── docs/                  # Documentation
├── vendor/                # Composer dependencies (git-ignored)
├── node_modules/          # npm dependencies (git-ignored)
├── composer.json          # PHP dependencies
├── package.json           # Node dependencies
├── webpack.config.js      # Build configuration
├── tsconfig.json          # TypeScript configuration
├── phpcs.xml              # PHP_CodeSniffer config
└── woo-ai-chatbot-pro.php # Main plugin file

2. Development Setup

Clone and Install

# Clone the repository
git clone https://github.com/LeoWebMarketing/WP_plugin_chat_ai.git
cd WP_plugin_chat_ai

# Install PHP dependencies
composer install

# Install Node dependencies
npm install

Environment Configuration

Copy the example environment file and configure your API keys:

cp .env.example .env

Required configuration in .env:

# AI Provider API Keys (at least one required)
GEMINI_API_KEY=your_gemini_api_key
OPENAI_API_KEY=your_openai_api_key
ANTHROPIC_API_KEY=your_anthropic_api_key

# Supabase Configuration (for RAG features)
SUPABASE_URL=https://your-project.supabase.co
SUPABASE_ANON_KEY=your_anon_key
SUPABASE_SERVICE_KEY=your_service_key

# Development
DEBUG_MODE=true
LOG_LEVEL=debug

API Key Sources:

Local WordPress Setup

  1. Install Local or configure LAMP/LEMP stack
  2. Create a new WordPress site
  3. Symlink or copy the plugin to wp-content/plugins/
  4. Activate WooCommerce and WooAI Chatbot Pro
# Symlink example (macOS/Linux)
ln -s /path/to/WP_plugin_chat_ai /path/to/wordpress/wp-content/plugins/woo-ai-chatbot-pro

Build Process

# Development build with watch mode
npm run dev

# Production build (minified, optimized)
npm run build

# Development build (single run)
npm run build:dev

# Type checking
npm run typecheck

# Linting
npm run lint          # ESLint with auto-fix
npm run lint:check    # ESLint check only

# PHP Code Sniffer
composer run phpcs    # Check standards
composer run phpcbf   # Auto-fix violations

# PHPStan static analysis
composer run phpstan

# Run tests
npm run test          # Jest tests
composer run test     # PHPUnit tests

3. Code Standards

PHP

WordPress Coding Standards

All PHP code must adhere to WordPress Coding Standards:

<?php
/**
 * Class description.
 *
 * @package WooAIChatbot
 * @since   1.0.0
 */

declare(strict_types=1);

namespace WooAIChatbot\Services;

use WooAIChatbot\Contracts\ProviderInterface;
use WooAIChatbot\Exceptions\ApiException;

/**
 * Handles AI provider operations.
 */
class AIService {

    /**
     * Provider instance.
     *
     * @var ProviderInterface
     */
    private ProviderInterface $provider;

    /**
     * Constructor.
     *
     * @param ProviderInterface $provider AI provider instance.
     */
    public function __construct( ProviderInterface $provider ) {
        $this->provider = $provider;
    }

    /**
     * Generate response from AI.
     *
     * @param string $prompt User prompt.
     * @param array  $context Conversation context.
     *
     * @return string Generated response.
     *
     * @throws ApiException If API request fails.
     */
    public function generate_response( string $prompt, array $context = [] ): string {
        if ( empty( $prompt ) ) {
            throw new \InvalidArgumentException( 'Prompt cannot be empty.' );
        }

        return $this->provider->complete( $prompt, $context );
    }
}

PSR-4 Autoloading

Namespace convention: WooAIChatbot\{SubNamespace}

{
    "autoload": {
        "psr-4": {
            "WooAIChatbot\\": "includes/"
        }
    }
}

File structure must mirror namespace:

PHPCS Configuration

The project uses WordPress Coding Standards. Run before every commit:

# Check violations
composer run phpcs

# Auto-fix where possible
composer run phpcbf

JavaScript/TypeScript

ESLint Rules

The project enforces strict TypeScript and React patterns:

# Lint with auto-fix
npm run lint

# Check only (used in CI)
npm run lint:check

TypeScript Strict Mode

All TypeScript must pass strict type checking:

// tsconfig.json strict mode is enabled
// Avoid 'any' - use proper types

// Bad
const processData = (data: any) => { ... };

// Good
interface ChatMessage {
    id: string;
    content: string;
    role: 'user' | 'assistant';
    timestamp: Date;
}

const processData = (data: ChatMessage): void => { ... };

React Patterns

Use functional components with hooks:

import React, { useState, useCallback, useMemo } from 'react';
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card';
import { Button } from '@/components/ui/button';

interface ChatWidgetProps {
    initialMessage?: string;
    onSend: (message: string) => Promise<void>;
}

export const ChatWidget: React.FC<ChatWidgetProps> = ({
    initialMessage = '',
    onSend,
}) => {
    const [message, setMessage] = useState(initialMessage);
    const [isLoading, setIsLoading] = useState(false);

    const handleSubmit = useCallback(async () => {
        if (!message.trim()) return;

        setIsLoading(true);
        try {
            await onSend(message);
            setMessage('');
        } finally {
            setIsLoading(false);
        }
    }, [message, onSend]);

    const isDisabled = useMemo(
        () => isLoading || !message.trim(),
        [isLoading, message]
    );

    return (
        <Card>
            <CardHeader>
                <CardTitle>Chat</CardTitle>
            </CardHeader>
            <CardContent>
                <Button onClick={handleSubmit} disabled={isDisabled}>
                    {isLoading ? 'Sending...' : 'Send'}
                </Button>
            </CardContent>
        </Card>
    );
};

CSS

Tailwind Conventions

Use Tailwind CSS utility classes. Prefer composition over custom CSS:

// Use Tailwind utilities
<div className="flex items-center gap-4 p-4 bg-white dark:bg-gray-900 rounded-lg shadow-sm">
    <span className="text-sm font-medium text-gray-700 dark:text-gray-200">
        {label}
    </span>
</div>

BEM Naming (Legacy CSS)

For non-Tailwind CSS, use BEM methodology:

/* Block */
.woo-chatbot {}

/* Element */
.woo-chatbot__header {}
.woo-chatbot__message {}

/* Modifier */
.woo-chatbot__message--user {}
.woo-chatbot__message--assistant {}

RTL Considerations

The project supports RTL languages (Hebrew). Use logical properties:

/* Use logical properties for RTL support */
.element {
    margin-inline-start: 1rem;  /* Not margin-left */
    padding-inline-end: 1rem;   /* Not padding-right */
    text-align: start;          /* Not text-align: left */
}

PostCSS automatically generates RTL variants via postcss-rtlcss.


4. Git Workflow

Branch Naming

# Features
feature/add-claude-provider
feature/rag-vector-search
feature/multilingual-support

# Bug fixes
fix/session-timeout-issue
fix/api-rate-limiting
fix/rtl-alignment

# Refactoring
refactor/provider-abstraction
refactor/database-queries

# Documentation
docs/api-reference
docs/installation-guide

# Chores
chore/update-dependencies
chore/ci-configuration

Commit Messages

Follow Conventional Commits:

# Format
<type>(<scope>): <description>

[optional body]

[optional footer(s)]

Types

Type Description
feat New feature
fix Bug fix
docs Documentation only
style Code style (formatting, semicolons)
refactor Code change without feature/fix
perf Performance improvement
test Adding/updating tests
build Build system changes
ci CI configuration
chore Maintenance tasks

Scope Examples

Examples

feat(providers): add Anthropic Claude support

Implement ClaudeProvider class with streaming support.
Includes rate limiting and error handling.

Closes #42

---

fix(chat): resolve message duplication on reconnect

Messages were being duplicated when WebSocket reconnected.
Added deduplication based on message ID.

Fixes #87

---

refactor(api): extract validation to dedicated class

Move request validation logic from controllers to
RequestValidator class for better separation of concerns.

BREAKING CHANGE: ValidationException now extends ApiException

Pull Requests

PR Template

## Summary

Brief description of changes.

## Type of Change

- [ ] Bug fix (non-breaking change fixing an issue)
- [ ] New feature (non-breaking change adding functionality)
- [ ] Breaking change (fix or feature causing existing functionality to change)
- [ ] Documentation update

## Changes Made

- Bullet points describing specific changes
- Include file paths for significant changes

## Testing

- [ ] Unit tests pass (`composer run test`)
- [ ] Integration tests pass
- [ ] Manual testing performed
- [ ] Tested on PHP 8.1 and 8.2

## Screenshots (if applicable)

## Checklist

- [ ] Code follows project coding standards
- [ ] Self-reviewed the code
- [ ] Added/updated documentation
- [ ] Added/updated tests
- [ ] No new warnings generated

Review Process

  1. Create PR from feature branch to main
  2. Ensure all CI checks pass
  3. Request review from maintainer
  4. Address review feedback
  5. Squash and merge when approved

Merge Requirements


5. Testing Requirements

Required Coverage

Running Tests

# PHP Tests
composer run test                    # All tests
composer run test:unit              # Unit tests only
composer run test:integration       # Integration tests
composer run test:coverage          # Generate coverage report

# JavaScript Tests
npm run test                        # Run Jest tests
npm run test:watch                  # Watch mode
npm run test:coverage               # Coverage report

Pre-PR Checklist

# Run all checks before creating PR
npm run typecheck && npm run lint && npm run test
composer run phpcs && composer run phpstan && composer run test

CI Checks

All PRs trigger:

  1. PHP syntax check (php -l)
  2. PHPCS (WordPress Coding Standards)
  3. PHPStan (Level 5)
  4. PHPUnit tests
  5. ESLint
  6. TypeScript compilation
  7. Jest tests
  8. Build verification

6. Documentation

Inline Documentation

PHPDoc Standards

/**
 * Generate AI response based on user input and context.
 *
 * This method orchestrates the AI response generation by:
 * 1. Validating input parameters
 * 2. Retrieving relevant context via RAG
 * 3. Calling the configured AI provider
 * 4. Processing and sanitizing the response
 *
 * @since 1.0.0
 *
 * @param string $prompt      User's input message.
 * @param array  $options {
 *     Optional. Configuration options.
 *
 *     @type string $model       AI model to use.
 *     @type int    $max_tokens  Maximum response tokens.
 *     @type float  $temperature Response creativity (0.0-1.0).
 *     @type bool   $use_rag     Whether to use RAG context.
 * }
 *
 * @return string Sanitized AI response.
 *
 * @throws ApiException        If API request fails.
 * @throws ValidationException If input validation fails.
 */
public function generate( string $prompt, array $options = [] ): string;

JSDoc Standards

/**
 * Custom hook for managing chat state and API interactions.
 *
 * Handles message sending, receiving, and conversation history.
 * Implements optimistic updates and error recovery.
 *
 * @param config - Configuration options
 * @param config.endpoint - API endpoint URL
 * @param config.sessionId - Current session identifier
 * @param config.onError - Error callback
 *
 * @returns Chat state and control functions
 *
 * @example
 * ```tsx
 * const { messages, sendMessage, isLoading } = useChat({
 *     endpoint: '/wp-json/woo-ai-chatbot/v1/chat',
 *     sessionId: 'abc123',
 * });
 * ```
 */
export function useChat(config: ChatConfig): UseChatReturn;

README Updates

When adding features:

  1. Update feature list in main README
  2. Add configuration options to documentation
  3. Include usage examples
  4. Update changelog

7. Release Process

Version Bumping

Follow Semantic Versioning:

Update version in:

  1. woo-ai-chatbot-pro.php (plugin header)
  2. package.json
  3. composer.json

Changelog Updates

Maintain CHANGELOG.md following Keep a Changelog:

## [1.2.0] - 2025-01-15

### Added
- Claude AI provider support
- Streaming responses for all providers
- Hebrew language support

### Changed
- Improved RAG retrieval accuracy
- Updated shadcn/ui components

### Fixed
- Session persistence across page reloads
- RTL layout issues in chat widget

### Security
- Added input sanitization for message content

Tag Creation

# Create annotated tag
git tag -a v1.2.0 -m "Release v1.2.0 - Claude provider support"

# Push tags
git push origin v1.2.0

8. Security

Reporting Vulnerabilities

Do not open public issues for security vulnerabilities.

Report security issues via email: security@leowebmarketing.pro

Include:

Security Considerations

Input Sanitization

Always sanitize user input:

// Sanitize text input
$message = sanitize_text_field( wp_unslash( $_POST['message'] ?? '' ) );

// Sanitize HTML content
$content = wp_kses_post( $raw_content );

// Escape output
echo esc_html( $message );
echo esc_attr( $attribute );
echo esc_url( $url );

Capability Checks

Verify user capabilities before operations:

// Check capability before admin actions
if ( ! current_user_can( 'manage_woocommerce' ) ) {
    wp_die( esc_html__( 'Unauthorized access.', 'woo-ai-chatbot-pro' ) );
}

// Verify nonces for form submissions
if ( ! wp_verify_nonce( $_POST['_wpnonce'] ?? '', 'woo_ai_chatbot_settings' ) ) {
    wp_die( esc_html__( 'Security check failed.', 'woo-ai-chatbot-pro' ) );
}

API Key Protection

Never expose API keys:

// Store securely in options (encrypted if possible)
update_option( 'woo_ai_chatbot_api_key', $encrypted_key );

// Never log API keys
error_log( 'API request failed' ); // OK
error_log( 'API key: ' . $api_key ); // NEVER DO THIS

9. Community

Code of Conduct

We follow the Contributor Covenant Code of Conduct. Be respectful, inclusive, and constructive.

Communication Channels

Issue Reporting

Bug Reports

Use the bug report template:

**Describe the bug**
Clear description of the bug.

**To Reproduce**
1. Go to '...'
2. Click on '...'
3. See error

**Expected behavior**
What you expected to happen.

**Environment**
- WordPress version: [e.g., 6.4.2]
- WooCommerce version: [e.g., 8.5.1]
- PHP version: [e.g., 8.2.0]
- Plugin version: [e.g., 1.2.0]
- Browser: [e.g., Chrome 120]

**Screenshots**
If applicable.

**Additional context**
Any other relevant information.

Feature Requests

Use the feature request template:

**Is your feature request related to a problem?**
Clear description of the problem.

**Describe the solution you'd like**
Clear description of desired behavior.

**Describe alternatives you've considered**
Alternative solutions or features considered.

**Additional context**
Any other context, mockups, or examples.

Quick Reference

Essential Commands

# Development
npm run dev              # Start development with watch
npm run build            # Production build

# Quality Checks
npm run typecheck        # TypeScript check
npm run lint             # ESLint
composer run phpcs       # PHP CodeSniffer
composer run phpstan     # PHPStan

# Testing
npm run test             # JavaScript tests
composer run test        # PHP tests

# Full Pre-commit Check
npm run typecheck && npm run lint && composer run phpcs && composer run phpstan

Branch Workflow

main
 └── feature/your-feature
      └── Commit → Push → PR → Review → Merge

Thank you for contributing to WooAI Chatbot Pro. Your contributions help make this plugin better for everyone.