CLAUDE.md - AI Assistant Guide
CLAUDE.md - AI Assistant Guide
This document provides essential context for AI assistants working with the bloqr-backend codebase.
Project Overview
Bloqr Compiler is a Compiler-as-a-Service for adblock filter lists. It transforms, optimizes, and combines filter lists from multiple sources with real-time progress tracking.
- Version: 0.7.12
- Runtime: Deno 2.4+ (primary), Node.js compatible, Cloudflare Workers compatible
- Language: TypeScript (strict mode, 100% type-safe)
- License: MIT
- JSR Package:
@jk-com/bloqr-compiler
Quick Commands
# Developmentdeno task dev # Development with watch modedeno task compile # Run compiler CLI
# Testingdeno task test # Run all testsdeno task test:watch # Tests in watch modedeno task test:coverage # Generate coverage reports
# Code Qualitydeno task lint # Lint codedeno task fmt # Format codedeno task fmt:check # Check formattingdeno task check # Type check
# Build & Deploydeno task build # Build standalone executabledeno task wrangler:dev # Run wrangler dev server (port 8787)deno task wrangler:deploy # Deploy to Cloudflare Workers
# Benchmarksdeno task bench # Run performance benchmarksProject Structure
mindmap
root((Project structure))
src["src/"]
cli["cli/ — CLI implementation (ArgumentParser, ConfigurationLoader)"]
compiler["compiler/ — Core compilation (FilterCompiler, SourceCompiler)"]
configuration["configuration/ — Config validation (pure TypeScript, no AJV)"]
transformations["transformations/ — 11 rule transformations"]
downloader["downloader/ — Content fetching and preprocessing"]
platform["platform/ — Platform abstraction (Workers, Deno, Node.js)"]
storage["storage/ — Caching and health monitoring"]
filters["filters/ — Rule filtering utilities"]
utils["utils/ — RuleUtils, Wildcard, TldUtils, etc."]
types["types/ — TypeScript interfaces (IConfiguration, ISource)"]
indexTs["index.ts — Library exports"]
modTs["mod.ts — Deno module exports"]
cliDeno["cli.deno.ts — Deno CLI entry point"]
worker["worker/"]
workerTs["worker.ts — Cloudflare Worker (main API handler)"]
htmlTs["html.ts — HTML templates"]
public["public/ — Static web UI assets"]
examples["examples/ — Example filter list configurations"]
docs["docs/ — Additional documentation"]
Architecture Patterns
The codebase uses these key patterns:
- Strategy Pattern: Transformations (SyncTransformation, AsyncTransformation)
- Builder Pattern: TransformationPipeline construction
- Factory Pattern: TransformationRegistry
- Composite Pattern: CompositeFetcher for chaining fetchers
- Adapter Pattern: Platform abstraction layer
Two Compiler Classes
- FilterCompiler (
src/compiler/) - File system-based, for Deno/Node.js CLI - WorkerCompiler (
src/platform/) - Platform-agnostic, for Workers/browsers
Transformation System
11 available transformations applied in order:
ConvertToAscii- Non-ASCII to PunycodeRemoveComments- Remove ! and # comment linesCompress- Hosts to adblock syntax conversionRemoveModifiers- Strip unsupported modifiersValidate- Remove dangerous/incompatible rulesValidateAllowIp- Like Validate but keeps IPsDeduplicate- Remove duplicate rulesInvertAllow- Convert blocks to allow rulesRemoveEmptyLines- Remove blank linesTrimLines- Remove leading/trailing whitespaceInsertFinalNewLine- Add final newline
All transformations extend SyncTransformation or AsyncTransformation base classes in src/transformations/base/.
Code Conventions
Naming
- Classes: PascalCase (
FilterCompiler,RemoveCommentsTransformation) - Functions/methods: camelCase (
executeSync,validate) - Constants: UPPER_SNAKE_CASE (
CACHE_TTL,RATE_LIMIT_MAX_REQUESTS) - Interfaces: I-prefixed (
IConfiguration,ILogger,ISource) - Enums: PascalCase (
TransformationType,SourceType)
File Organization
- Each module in its own directory with
index.tsexports - Tests co-located as
*.test.tsnext to source files - No deeply nested directory structures
TypeScript
- Strict mode enabled (all strict options)
- No implicit any
- Explicit return types on public methods
- Use interfaces over type aliases for object shapes
Error Handling
- Custom error types for specific scenarios
- Validation results over exceptions where possible
- Retry logic with exponential backoff for network operations
Testing
Tests use Deno’s native testing framework:
# Run all testsdeno test --allow-read --allow-write --allow-net --allow-env
# Run specific test filedeno test src/utils/RuleUtils.test.ts --allow-read
# Run with coveragedeno task test:coverageTest file conventions:
- Co-located with source:
FileName.ts->FileName.test.ts - Use
Deno.test()with descriptive names - Mock external dependencies (network, file system)
Configuration Schema
interface IConfiguration { name: string; // Required description?: string; homepage?: string; license?: string; version?: string; sources: ISource[]; // Required, non-empty transformations?: TransformationType[]; exclusions?: string[]; // Patterns to exclude inclusions?: string[]; // Patterns to include}
interface ISource { source: string; // URL or file path name?: string; type?: 'adblock' | 'hosts'; transformations?: TransformationType[]; exclusions?: string[]; inclusions?: string[];}Pattern types: plain string (contains), *.wildcard, /regex/
API Endpoints (Worker)
POST /compile- JSON compilation APIPOST /compile/stream- Streaming with SSEPOST /compile/batch- Batch up to 10 listsPOST /compile/async- Queue-based async compilationPOST /compile/batch/async- Queue-based batch compilationGET /metrics- Performance metricsGET /- Interactive web UI
Key Files to Know
| File | Purpose |
|---|---|
src/compiler/FilterCompiler.ts | Main compilation logic |
src/platform/WorkerCompiler.ts | Platform-agnostic compiler |
src/transformations/TransformationRegistry.ts | Transformation management |
src/configuration/ConfigurationValidator.ts | Config validation |
src/downloader/FilterDownloader.ts | Content fetching with retries |
src/types/index.ts | Core type definitions |
worker/worker.ts | Cloudflare Worker API handler |
deno.json | Deno tasks and configuration |
wrangler.toml | Cloudflare Workers config |
Platform Support
The codebase supports multiple runtimes through the platform abstraction layer:
- Deno (primary) - Full file system access
- Node.js - npm-compatible via
package.json - Cloudflare Workers - No file system, HTTP-only
- Web Workers - Browser background threads
Use FilterCompiler for CLI/server environments, WorkerCompiler for edge/browser.
Dependencies
Minimal external dependencies:
@luca/cases(JSR) - String case conversion@std/*(Deno Standard Library) - Core utilitiestldts(npm) - TLD/domain parsingwrangler(dev) - Cloudflare deployment
Common Tasks
Adding a New Transformation
- Create
src/transformations/MyTransformation.ts - Extend
SyncTransformationorAsyncTransformation - Implement
execute(lines: string[]): string[] - Register in
TransformationRegistry.ts - Add to
TransformationTypeenum insrc/types/index.ts - Write co-located tests
Modifying the API
- Edit
worker/worker.ts - Update route handlers
- Test with
deno task wrangler:dev - Deploy with
deno task wrangler:deploy
Adding CLI Options
- Add to
ParsedArgumentsinterface insrc/cli/ArgumentParser.ts - Update
parseArgs()insrc/cli/ArgumentParser.ts(add toboolean,string, orcollectarrays) - Add to
ICliArgsinterface insrc/cli/CliApp.deno.ts - Update
parseArgs()insrc/cli/CliApp.deno.ts - Handle the new flag in
buildTransformations(),createConfig(),readConfig(), orrun()as appropriate - Add the field to
CliArgumentsOutputtype andCliArgumentsSchemainsrc/configuration/schemas.ts - Update
showHelp()in bothArgumentParser.tsandCliApp.deno.ts - Update
docs/usage/CLI.md
CI/CD Pipeline
GitHub Actions workflow (.github/workflows/ci.yml):
- Test: Run all tests with coverage
- Type Check: Full TypeScript validation
- Security: Trivy vulnerability scanning
- JSR Publish: Auto-publish on master push
- Worker Deploy: Deploy to Cloudflare Workers
- Pages Deploy: Deploy static assets
Environment Variables
See .env.example for available options:
PORT- Server port (default: 8787)DENO_DIR- Deno cache directory- Cloudflare bindings configured in
wrangler.toml
Useful Links
- README.md - Full project documentation
- TESTING.md - Testing guide
- docs/api/README.md - API documentation
- docs/EXTENSIBILITY.md - Custom extensions
- CHANGELOG.md - Version history