This file provides guidance to Claude Code (claude.ai/code) when working with code in this repository.
ALWAYS ask for confirmation before implementing fixes.
- Even if you think you found the solution, ASK FIRST
- We are partners working together, not working alone
- Present your findings and proposed solution, then wait for confirmation
- Have a dialogue - discuss the issue and explore solutions together
- Never assume you have the complete picture without user input
Find and fix the ROOT CAUSE, not symptoms.
- NEVER rush to conclusions when investigating issues
- NEVER make assumptions about what's causing a problem
- ALWAYS do thorough investigation before proposing solutions
- Easy fixes are usually wrong - dig deeper
- Read all relevant code paths before making changes
- Verify assumptions with actual code inspection
Always write tests BEFORE implementing new features.
- Write failing tests first, then implement code to make them pass
- Run tests after implementation to verify
- Both JavaScript (Jest) and PHP should follow TDD
When tests fail, ALWAYS investigate the implementation first, NOT the tests.
Critical Testing Principles:
-
Tests exist to catch bugs in the implementation
- A failing test is doing its job - it found a problem
- NEVER change tests to make them pass without understanding WHY they're failing
- The implementation is guilty until proven innocent
-
Investigate implementation before changing tests
- When a test fails, read the implementation code it's testing
- Understand what changed in the implementation
- Check if the implementation has a bug or if the behavior intentionally changed
- Only update tests if the implementation's NEW behavior is correct
-
Tests must be thorough, not just happy paths
- Happy path tests are necessary but insufficient
- Test edge cases: empty inputs, null values, errors, boundary conditions
- Test failure scenarios: network errors, validation failures, missing data
- Test security: injection attacks, path traversal, unauthorized access
- Comprehensive tests strengthen the codebase and catch regressions
-
Bad testing practices to avoid
- ❌ Making tests pass by weakening assertions
- ❌ Removing tests that fail without understanding why
- ❌ Only testing the happy path
- ❌ Changing tests to match bugs in implementation
- ❌ Writing tests that always pass regardless of implementation
-
Good testing practices
- ✅ Read the implementation when tests fail
- ✅ Verify the implementation is correct before changing tests
- ✅ Test error handling and edge cases
- ✅ Use descriptive test names that explain what's being tested
- ✅ Write tests that would fail if the implementation had bugs
Example workflow when tests fail:
// ❌ WRONG: Change test to match (potentially buggy) implementation
test('processes data', () => {
const result = processData(null);
expect(result).toBeUndefined(); // Changed from expect().toThrow() to make it pass
});
// ✅ RIGHT: Investigate implementation, find it should handle null
test('processes data', () => {
const result = processData(null);
expect(() => processData(null)).toThrow('Data cannot be null'); // Test catches the bug
});
// Then fix the implementation to handle null properlyWe do not care about backwards-compatibility.
- No backwards-compatibility hacks (no unused parameter renames like
_var, no// removedcomments, no re-exports of deleted code) - Delete unused code completely instead of commenting it out
- Refactor fearlessly - if something is better done differently, change it
- Prioritize code clarity over preserving old patterns
- Run linters and fix issues before considering work complete
- PHPStan must pass at current level
- All tests must pass before committing
This is a JS-first plugin - JavaScript is preferred over PHP whenever possible.
- If something CAN be done in JavaScript, it SHOULD be done in JavaScript
- PHP should primarily serve as a thin REST API layer
- Target environment: WordPress Playground (browser-based WASM environment)
- Everything should be reactive - use React state, contexts, and hooks
- Browser-based processing prevents PHP timeout issues in Playground
- Examples: Static site generation runs in browser, asset processing in JS, HTML parsing with parse5
When to Use PHP vs JavaScript:
- JavaScript: UI logic, data processing, file operations (via REST), HTML parsing, static site generation, asset tracking, URL discovery
- PHP: REST API endpoints, database queries, WordPress hooks/filters, server-side file I/O, authentication/security
- Rule of thumb: If it can run in the browser without significant performance penalty, use JavaScript
Provider Isolation (CRITICAL)
- Providers MUST be completely isolated to their own files
- NO provider-specific logic in core architecture or abstractions
- Core code should only interact with provider interface via JavaScript ProviderRegistry
- Providers register via
altolith.providers.registerJavaScript hook for 3rd-party extensibility - Each provider is self-contained: all logic, configuration, validation within JavaScript provider class
- 3rd-party plugins can hook in and add their own providers in JavaScript
- Example:
LocalFilesystemProvider(JavaScript) contains ALL local filesystem logic - nothing in core
Provider Instances Architecture
- Multiple instances of the same provider type are supported
- Instance ID format:
{provider_type}:{uuid}(e.g.,local-filesystem:a3f2c1b0-...) - Each instance has its own configuration stored in settings
ProviderRegistrymanages both provider types AND instances- Users can configure multiple instances (e.g., multiple S3 buckets, multiple local paths)
- Instance configs stored in
altolith_deploy_settings['providers']array
Provider Extension Pattern for 3rd-Party Plugins
- 3rd-party providers extend
AbstractProviderin JavaScript - JavaScript providers implement the provider interface and are dynamically loaded
- Register via
altolith.providers.registerJavaScript hook or directly withProviderRegistry.register()
This plugin is part of the Altolith ecosystem (all plugins with altolith prefix).
- Designed to work together with other Altolith plugins
- Consider cross-plugin compatibility when making architectural changes
- Shared conventions across Altolith plugins should be maintained
- Other Altolith plugins may extend or integrate with this plugin's provider system
# Production build (minified)
npm run build
# Development build (unminified for debugging)
npm run build:dev
# Watch mode (auto-rebuild on changes)
npm start# Run JavaScript tests
npm run test:js
# Run JavaScript tests in watch mode
npm run test:js:watch
# Run JavaScript tests with coverage
npm run test:js:coverage
# Run single JavaScript test file
npm run test:js -- path/to/test/file.test.js
# Run PHP tests (PHPUnit)
composer test
# Run specific PHP test suite
composer test:unit # Unit tests only
composer test:integration # Integration tests only
# Run single PHP test file or method
composer test -- --filter TestClassName
composer test -- --filter testMethodName
# Run PHPStan (static analysis)
composer phpstan# Lint JavaScript
npm run lint:js
# Fix JavaScript linting issues
npm run lint:js:fix
# Check PHP code style
composer check-cs
# Fix PHP code style
composer fix-cs
# Run PHPStan
composer phpstan
# Run all checks (CS + PHPStan)
composer checkAltolith Deploy is a WordPress plugin that exports WordPress sites as static HTML or WordPress Playground blueprint bundles. The plugin uses a universal compatibility design - it works identically in both traditional hosting environments and WordPress Playground's browser-based WASM environment.
Target: WordPress Playground (browser-based WASM environment)
Key principles:
- No environment detection - code works identically everywhere
- Never use
sys_get_temp_dir()- ALWAYS useTempDirectoryManager::getTempFilePath()which useswp-content/uploads/altolith-temp - Never use
realpath()directly - ALWAYS usePathValidatorwhich has WASM-compatible fallbacks - Never make external HTTP calls from PHP - use filter-based architecture for WordPress.org API checks
- Browser-based static site generation - prevents PHP timeouts
Namespace: Altolith\Deploy
Entry Point: altolith-deploy.php → Plugin::getInstance()
Core Components:
-
Plugin.php- Main orchestrator (singleton pattern)- Initializes all subsystems
- Registers REST API routes via controller classes
- Handles CORS for WordPress Playground compatibility
- Manages provider registry
-
Provider System (Extensible architecture)
ProviderRegistry(JavaScript) - Singleton registry managing all provider types and instances- Provider classes are static (no base class needed)
LocalFilesystemStaticSiteProvider(JavaScript) - Stores static site files locallyLocalFilesystemBlueprintBundleProvider(JavaScript) - Stores blueprint bundles locally- Providers register via
altolith.providers.registerJavaScript hook - Instance IDs format:
{provider_type}:{uuid}
-
REST API Controllers (
includes/REST/)- Each controller is a dedicated class (separation of concerns)
- Export controllers handle multi-step export workflow
- All endpoints use namespace
altolith/deploy - CORS headers automatically added for Playground compatibility
- No provider-specific logic in controllers
-
Services (
includes/Services/)ExportService- Complete site export (database + wp-content)BlueprintBundleGenerator- WordPress Playground blueprint creation- Provider-agnostic - work with any provider via interface
-
Utilities (
includes/Utilities/)TempDirectoryManager- Universal temp file handling (critical for Playground)PathValidator- Universal path validation (WASM-compatible)FileManager- File operations with persistence trackingCredentialEncryption- Secure credential storage
What PHP Handles:
- Authentication and security
- Database queries
- WordPress hooks/filters integration
- Server-side file I/O (when absolutely necessary)
- REST API endpoints (thin layer)
Build System: Webpack via @wordpress/scripts
Entry Points:
admin-settings→ Settings page UI (assets/src/admin-settings/)
Key Patterns:
-
Context-based Reactive State Management
ExportContext- Export workflow state- Custom hooks consume contexts
- State flows reactively through component tree
-
Multi-Step Workflow System (
assets/src/export/)- Steps defined in
steps/index.jsand registered via WordPress hooks - Each step declares dependencies and provides data
useExportController.jsorchestrates step execution via StepExecutor- Progress tracking via
progressManager.js - State persisted in IndexedDB (Playground-compatible)
- Steps defined in
-
Browser-Based Asset Management
- Static site generation runs entirely in browser
- HTML parsing with
parse5library (pure JavaScript) - URL rewriting for static sites
- Asset tracking and deduplication
-
Provider Integration
- Providers dynamically loaded via
window.altolith.providerScriptsBaseUrl - Providers implement standard methods (getId, getName, deploy, etc.)
- Config fields built via
ConfigFieldBuilder - Each provider is isolated in its own file
- Providers dynamically loaded via
What JavaScript Handles:
- All UI logic and rendering
- Data processing and transformation
- HTML parsing and manipulation
- Static site generation workflow
- Asset tracking and management
- URL discovery and processing
- State management (React + IndexedDB)
Settings:
GET /altolith/deploy/settings- Get plugin settingsPOST /altolith/deploy/settings- Update settings
Export Operations:
POST /altolith/deploy/export/createArchive- Create WordPress archivePOST /altolith/deploy/export/initArchive- Initialize archivePOST /altolith/deploy/export/finalizeArchive- Finalize archivePOST /altolith/deploy/export/generateBlueprintBundle- Generate blueprintGET /altolith/deploy/export/steps/getHtmlContent- Get HTML for URL
Provider Management:
GET/POST/DELETE /altolith/deploy/providers/{providerId}/config- Manage provider configPOST /altolith/deploy/providers/{providerId}/test- Test provider
URL Discovery & Assets:
POST /altolith/deploy/url-discovery/discover- Discover site URLsGET /altolith/deploy/assets/manifest- Get assets manifest
Local Storage:
POST /altolith/deploy/local-storage/upload- Upload fileDELETE /altolith/deploy/local-storage/delete- Delete fileGET /altolith/deploy/local-storage/download- Download file
PHP:
- Settings stored in
altolith_deploy_settingsoption - Provider instance configs stored in settings array under
providerskey
JavaScript:
- Workflow state tracked in React state + IndexedDB (for resume-after-failure)
- Reactive updates via React contexts and hooks
- Caching: Only
wporgCacheremains (WordPress.org plugin/theme existence checks, 7-day TTL)
Critical Files:
TempDirectoryManager.php- Universal temp directory solutionPathValidator.php- Universal path validationFileManager.php- Persistent file operations
Path Traversal Prevention:
- All user-provided paths validated via
PathValidator - Reject
..sequences, absolute paths, null bytes - Validation occurs BEFORE filesystem operations
Credential Encryption:
- Provider credentials encrypted with
wp_salt('auth') - Hash-based integrity verification
- Stored in WordPress options (database)
CORS Security:
- Whitelisted origins only (Playground domains + same-origin)
- Local development requires
ALTOLITH_ALLOW_LOCAL_CORSconstant - Custom origins via
altolith_deploy_cors_allowed_originsfilter
JavaScript Tests:
- Jest + React Testing Library
- Mock WordPress dependencies (
@wordpress/api-fetch, etc.) - Test files colocated with source in
__tests__directories - Follow TDD - write tests before implementation
PHP Tests:
- Framework: PHPUnit 9.6 with wp-phpunit integration
- Test Organization:
tests/Unit/- Unit tests for isolated componentstests/Integration/- Integration tests for REST API and workflowstests/Helpers/TestCase.php- Base test case with helper methods
- Coverage: Tests cover security, business logic, and integration scenarios
- Key Test Suites:
- Security Tests: PathValidator (path traversal, injection), CredentialEncryption
- Business Logic: ProviderRegistry, FileManager, TempDirectoryManager
- Integration Tests: ProviderConfigController (REST API with encryption)
- Testing Philosophy:
- Tests catch bugs in implementation, not written just for coverage
- Test edge cases, error conditions, and security boundaries
- Test actual behavior, not implementation details
- Mock providers for isolation, real WordPress functions for integration
- Running Tests:
composer test- Run all testscomposer test:unit- Unit tests onlycomposer test:integration- Integration tests onlycomposer test -- --filter TestName- Run specific test
- Static Analysis:
- PHPStan (level 9) for type safety
- PHP_CodeSniffer (WordPress Coding Standards)
- PHP-CS-Fixer for auto-fixing
- TDD Workflow: Write tests before implementation
1. Write Tests First
// assets/src/providers/my-provider/__tests__/index.test.js
describe('MyProvider', () => {
it('should implement required provider methods', () => {
// Test all required methods exist (getId, getName, deploy, etc.)
});
});2. Create Provider Class (JavaScript)
// assets/src/providers/my-provider/MyProvider.js
import { AbstractProvider } from '@altolith/providers/base/AbstractProvider';
class MyProvider extends AbstractProvider {
getId() {
return 'my-provider';
}
getName() {
return 'My Provider';
}
// Implement ALL provider logic here - nothing in core
getProviderSpecificConfigFields() {
// Configuration fields
}
async uploadFile(sourcePath, destinationPath, options = {}) {
// Upload implementation
}
}3. Register Provider
// assets/src/providers/my-provider/index.js
import { MyProvider } from './MyProvider';
import ProviderRegistry from '@altolith/providers/registry/ProviderRegistry';
import { doAction } from '@wordpress/hooks';
// Create and register provider
const provider = new MyProvider();
ProviderRegistry.register(provider.getId(), provider);
doAction('altolith.providers.register', provider);Key Rules:
- ALL provider logic stays in provider files
- NO provider-specific code in core architecture
- Each provider is completely self-contained
- Test first, then implement
1. Write Tests First
// assets/src/export/steps/__tests__/myStep.test.js
describe('myStep', () => {
it('should return standard response format', async () => {
// Test implementation
});
});2. Create Step Definition
// assets/src/export/steps/myStep/index.js
import { addAction } from '@wordpress/hooks';
import StepRegistry from '../../registry/StepRegistry';
addAction('altolith.export.register_steps', 'altolith/my-step', (registry) => {
registry.register({
id: 'myStep',
label: 'My Step',
description: 'Does something custom',
supportsProgress: true,
requires: {
someData: { from: 'someOtherStep', required: true },
api: { from: 'initial', required: true },
},
provides: {
myStepResult: 'object',
},
handler: async (context) => {
// Step implementation
return { myStepResult: { success: true } };
},
});
});5. Create REST Endpoint (If Needed)
// includes/REST/Export/ExportStepsController.php
// Add endpoint ONLY if server-side processing required
// Keep it thin - delegate to JavaScript when possible1. Write Tests First
// Test settings UI and validation2. Add Setting to UI
// assets/src/admin-settings/
// Add field to settings form3. Register in REST Controller
// includes/REST/SettingsController.php
// Add validation and sanitization4. Add to Defaults
// Core/SettingsRepository.php
// Add default valueMake code testable by design, not as an afterthought.
-
Prefer pure functions - Functions that:
- Take inputs as parameters (no hidden dependencies)
- Return outputs (no side effects)
- Always produce same output for same input
- Example:
sanitizeKeyForStatus(key),isExcludedUrl(url)
-
Use dependency injection - Pass dependencies as parameters:
// Bad: Hard-coded dependency function processData() { const data = localStorage.getItem('key'); return JSON.parse(data); } // Good: Dependency injected function processData(storage) { const data = storage.get('key'); return data; }
-
Abstract browser APIs - Create thin wrappers:
storage.js- Wraps localStorageapiFetch- Already abstracted via utils/api.js- Makes mocking easy in tests
-
Separate pure logic from side effects:
// Bad: Mixed concerns function processAndSave(html) { const processed = html.replace(...); localStorage.setItem('result', processed); return processed; } // Good: Separated function processHtml(html) { // Pure, testable return html.replace(...); } function saveResult(processed, storage) { // Side effect isolated storage.set('result', processed); }
Always write tests for:
- Pure utility functions (htmlProcessor, assetExclusions, etc.)
- Business logic functions
- Data transformations
- Configuration validation
- Edge cases and error conditions
Don't worry about testing:
- React hooks with complex dependencies (useExportController)
- High-level orchestration functions (uploadFilesWithProgress)
- Simple pass-through wrappers
Storage abstraction (assets/src/utils/storage.js):
import { storage } from '../../utils/storage';
// In production code
storage.set('key', value);
const data = storage.get('key', defaultValue);
// In tests
jest.mock('../../utils/storage', () => ({
storage: {
get: jest.fn(),
set: jest.fn(),
// ... other methods
}
}));- Co-locate tests with source code
- Tests go in
__tests__/subdirectory - Test file naming:
filename.test.jsforfilename.js - Example:
assets/src/utils/__tests__/storage.test.js
Before (Hard to test):
function processAndUpload() {
const html = fetch('/page').then(r => r.text());
const processed = processHtml(html);
localStorage.setItem('result', processed);
return uploadToServer(processed);
}After (Easy to test):
// Pure function - easy to test
export function processHtml(html, siteUrl) {
// ... processing logic
return processed;
}
// Composition with injected dependencies
async function processAndUpload(fetcher, storage, uploader) {
const html = await fetcher('/page');
const processed = processHtml(html);
storage.set('result', processed);
return uploader(processed);
}altolith-deploy/
├── includes/ # PHP backend (thin REST API layer)
│ ├── Admin/ # WordPress admin integration
│ ├── CLI/ # WP-CLI commands
│ ├── Core/ # Core utilities (settings, etc.)
│ ├── (Providers directory removed - providers are JavaScript-only)
│ ├── REST/ # REST API controllers (provider-agnostic)
│ │ └── Export/ # Export workflow controllers
│ ├── Services/ # Business logic services (provider-agnostic)
│ ├── Sync/ # Sync/export logic
│ │ └── Blueprint/ # Blueprint generation
│ └── Utilities/ # Helper utilities (Playground-compatible)
│
├── assets/
│ ├── src/ # JavaScript source (primary logic layer)
│ │ ├── admin-settings/ # Settings page
│ │ ├── export/ # Main export feature
│ │ │ ├── components/ # React components
│ │ │ ├── hooks/ # Custom React hooks
│ │ │ ├── steps/ # Workflow step definitions
│ │ │ ├── executor/ # Step executor and dependency resolver
│ │ │ ├── registry/ # Step registry
│ │ │ └── utils/ # Utilities (DOM, assets, etc.)
│ │ ├── providers/ # Provider implementations (isolated)
│ │ ├── contexts/ # React contexts
│ │ ├── hooks/ # Shared hooks
│ │ ├── utils/ # Shared utilities
│ │ └── components/ # Shared components
│ └── build/ # Compiled assets (generated)
│
└── tests/ # Test files
PHP:
- WordPress 6.4+
- PHP 7.4+ (8.1+ recommended)
JavaScript:
- React 18
- WordPress Components
- parse5 (HTML parsing - critical for browser-based generation)
- p-retry (retry logic)
- idb (IndexedDB wrapper - Playground-compatible storage)
- uuid (UUID generation)
Webpack:
- Disables code splitting (all code in single bundles)
- Dynamic imports set to
eagermode - No chunk files created
- Source maps removed from node_modules code
- Minification controlled via
MINIFYenv var (default: false for easier debugging)