Adblock Compiler — System Architecture

A comprehensive breakdown of the adblock-compiler system: modules, sub-modules, services, data flow, and deployment targets.


Table of Contents

  1. High-Level Overview
  2. System Context Diagram
  3. Core Compilation Pipeline
  4. Module Map
  5. Detailed Module Breakdown
  6. Cloudflare Worker (worker/)
  7. Web UI (public/)
  8. Cross-Cutting Concerns
  9. Data Flow Diagrams
  10. Deployment Architecture
  11. Technology Stack

High-Level Overview

The adblock-compiler is a compiler-as-a-service for adblock filter lists. It downloads filter list sources from remote URLs or local files, applies a configurable pipeline of transformations, and produces optimized, deduplicated output. It runs in three modes:

ModeRuntimeEntry Point
CLIDenosrc/cli.ts / src/cli/CliApp.deno.ts
LibraryDeno / Node.jssrc/index.ts (JSR: @jk-com/adblock-compiler)
Edge APICloudflare Workersworker/worker.ts

System Context Diagram

graph TD
    subgraph EW["External World"]
        FLS["Filter List Sources<br/>(URLs/Files)"]
        WB["Web Browser<br/>(Web UI)"]
        AC["API Consumers<br/>(CI/CD, scripts)"]
    end

    subgraph ACS["adblock-compiler System"]
        CLI["CLI App<br/>(Deno)"]
        WUI["Web UI<br/>(Static)"]
        CFW["Cloudflare Worker<br/>(Edge API)"]
        CORE["Core Library<br/>(FilterCompiler / WorkerCompiler)"]
        DL["Download & Fetch"]
        TP["Transform Pipeline"]
        VS["Validate & Schema"]
        ST["Storage & Cache"]
        DG["Diagnostics & Tracing"]
    end

    KV["Cloudflare KV<br/>(Cache, Rate Limit, Metrics)"]
    D1["Cloudflare D1<br/>(SQLite, Metadata)"]

    FLS --> CLI
    WB --> WUI
    AC --> CFW
    CLI --> CORE
    WUI --> CORE
    CFW --> CORE
    CORE --> DL
    CORE --> TP
    CORE --> VS
    CORE --> ST
    CORE --> DG
    ST --> KV
    ST --> D1

Core Compilation Pipeline

Every compilation—CLI, library, or API—follows this pipeline:

flowchart LR
    A["1. Config<br/>Loading"] --> B["2. Validate<br/>(Zod)"]
    B --> C["3. Download<br/>Sources"]
    C --> D["4. Per-Source<br/>Transforms"]
    D --> E["5. Merge<br/>All Sources"]
    E --> F["6. Global<br/>Transforms"]
    F --> G["7. Checksum<br/>& Header"]
    G --> H["8. Output<br/>(Rules)"]

Step-by-Step

StepComponentDescription
1ConfigurationLoader / API bodyLoad JSON configuration with source URLs and options
2ConfigurationValidator (Zod)Validate against ConfigurationSchema
3FilterDownloader / PlatformDownloaderFetch source content via HTTP, file system, or pre-fetched cache
4SourceCompiler + TransformationPipelineApply per-source transformations (e.g., remove comments, validate)
5FilterCompiler / WorkerCompilerMerge rules from all sources, apply exclusions/inclusions
6TransformationPipelineApply global transformations (e.g., deduplicate, compress)
7HeaderGenerator + checksum utilGenerate metadata header, compute checksum
8OutputWriter / HTTP response / SSE streamWrite to file, return JSON, or stream via SSE

Module Map

src/
├── index.ts                    # Library entry point (all public exports)
├── version.ts                  # Canonical VERSION constant
├── cli.ts / cli.deno.ts        # CLI entry points
│
├── compiler/                   # 🔧 Core compilation orchestration
│   ├── FilterCompiler.ts       #    Main compiler (file system access)
│   ├── SourceCompiler.ts       #    Per-source compilation
│   ├── IncrementalCompiler.ts  #    Incremental (delta) compilation
│   ├── HeaderGenerator.ts      #    Filter list header generation
│   └── index.ts
│
├── platform/                   # 🌐 Platform abstraction layer
│   ├── WorkerCompiler.ts       #    Edge/Worker compiler (no FS)
│   ├── HttpFetcher.ts          #    HTTP content fetcher
│   ├── PreFetchedContentFetcher.ts  # In-memory content provider
│   ├── CompositeFetcher.ts     #    Chain-of-responsibility fetcher
│   ├── PlatformDownloader.ts   #    Platform-agnostic downloader
│   ├── types.ts                #    IContentFetcher interface
│   └── index.ts
│
├── transformations/            # ⚙️ Rule transformation pipeline
│   ├── base/Transformation.ts  #    Abstract base classes
│   ├── TransformationRegistry.ts  # Registry + Pipeline
│   ├── CompressTransformation.ts
│   ├── DeduplicateTransformation.ts
│   ├── ValidateTransformation.ts
│   ├── RemoveCommentsTransformation.ts
│   ├── RemoveModifiersTransformation.ts
│   ├── ConvertToAsciiTransformation.ts
│   ├── InvertAllowTransformation.ts
│   ├── TrimLinesTransformation.ts
│   ├── RemoveEmptyLinesTransformation.ts
│   ├── InsertFinalNewLineTransformation.ts
│   ├── ExcludeTransformation.ts
│   ├── IncludeTransformation.ts
│   ├── ConflictDetectionTransformation.ts
│   ├── RuleOptimizerTransformation.ts
│   ├── TransformationHooks.ts
│   └── index.ts
│
├── downloader/                 # 📥 Filter list downloading
│   ├── FilterDownloader.ts     #    Deno-native downloader with retries
│   ├── ContentFetcher.ts       #    File system + HTTP abstraction
│   ├── PreprocessorEvaluator.ts  # !#if / !#include directives
│   ├── ConditionalEvaluator.ts #    Boolean expression evaluator
│   └── index.ts
│
├── configuration/              # ✅ Configuration validation
│   ├── ConfigurationValidator.ts  # Zod-based validator
│   ├── schemas.ts              #    Zod schemas for all request types
│   └── index.ts
│
├── config/                     # ⚡ Centralized constants & defaults
│   └── defaults.ts             #    NETWORK, WORKER, STORAGE defaults
│
├── storage/                    # 💾 Persistence & caching
│   ├── IStorageAdapter.ts      #    Abstract storage interface
│   ├── PrismaStorageAdapter.ts #    Prisma ORM adapter (SQLite default)
│   ├── D1StorageAdapter.ts     #    Cloudflare D1 adapter
│   ├── CachingDownloader.ts    #    Intelligent caching downloader
│   ├── ChangeDetector.ts       #    Content change detection
│   ├── SourceHealthMonitor.ts  #    Source health tracking
│   └── types.ts                #    StorageEntry, CacheEntry, etc.
│
├── services/                   # 🛠️ Business logic services
│   ├── FilterService.ts        #    Filter wildcard preparation
│   ├── ASTViewerService.ts     #    Rule AST parsing & display
│   ├── AnalyticsService.ts     #    Cloudflare Analytics Engine
│   └── index.ts
│
├── queue/                      # 📬 Async job queue
│   ├── IQueueProvider.ts       #    Abstract queue interface
│   ├── CloudflareQueueProvider.ts  # Cloudflare Queues impl
│   └── index.ts
│
├── diagnostics/                # 🔍 Observability & tracing
│   ├── DiagnosticsCollector.ts #    Event aggregation
│   ├── TracingContext.ts       #    Correlation & span management
│   ├── OpenTelemetryExporter.ts  # OTel bridge
│   ├── types.ts                #    DiagnosticEvent, TraceSeverity
│   └── index.ts
│
├── filters/                    # 🔍 Rule filtering
│   ├── RuleFilter.ts           #    Exclusion/inclusion pattern matching
│   └── index.ts
│
├── formatters/                 # 📄 Output formatting
│   ├── OutputFormatter.ts      #    Adblock, hosts, dnsmasq, etc.
│   └── index.ts
│
├── diff/                       # 📊 Diff reporting
│   ├── DiffReport.ts           #    Compilation diff generation
│   └── index.ts
│
├── plugins/                    # 🔌 Plugin system
│   ├── PluginSystem.ts         #    Plugin registry & loading
│   └── index.ts
│
├── deployment/                 # 🚀 Deployment tracking
│   └── version.ts              #    Deployment history & records
│
├── schemas/                    # 📋 JSON schemas
│   └── configuration.schema.json
│
├── types/                      # 📐 Core type definitions
│   ├── index.ts                #    IConfiguration, ISource, enums
│   ├── validation.ts           #    Validation-specific types
│   └── websocket.ts            #    WebSocket message types
│
├── utils/                      # 🧰 Shared utilities
│   ├── RuleUtils.ts            #    Rule parsing & classification
│   ├── StringUtils.ts          #    String manipulation
│   ├── TldUtils.ts             #    Top-level domain utilities
│   ├── Wildcard.ts             #    Glob/wildcard pattern matching
│   ├── CircuitBreaker.ts       #    Circuit breaker pattern
│   ├── AsyncRetry.ts           #    Retry with exponential backoff
│   ├── ErrorUtils.ts           #    Typed error hierarchy
│   ├── EventEmitter.ts         #    CompilerEventEmitter
│   ├── Benchmark.ts            #    Performance benchmarking
│   ├── BooleanExpressionParser.ts  # Boolean expression evaluation
│   ├── AGTreeParser.ts         #    AdGuard rule AST parser
│   ├── ErrorReporter.ts        #    Multi-target error reporting
│   ├── logger.ts               #    Logger, StructuredLogger
│   ├── checksum.ts             #    Filter list checksums
│   ├── headerFilter.ts         #    Header stripping utilities
│   └── PathUtils.ts            #    Safe path resolution
│
└── cli/                        # 💻 CLI application
    ├── CliApp.deno.ts          #    Main CLI app (Deno-specific)
    ├── ArgumentParser.ts       #    CLI argument parsing
    ├── ConfigurationLoader.ts  #    Config file loading
    ├── OutputWriter.ts         #    File output writing
    └── index.ts

worker/                         # ☁️ Cloudflare Worker
├── worker.ts                   #    Worker entry point
├── router.ts                   #    Modular request router
├── websocket.ts                #    WebSocket handler
├── html.ts                     #    Static HTML serving
├── schemas.ts                  #    API request validation
├── types.ts                    #    Env bindings, request/response types
├── tail.ts                     #    Tail worker (log consumer)
├── handlers/                   #    Route handlers
│   ├── compile.ts              #    Compilation endpoints
│   ├── metrics.ts              #    Metrics endpoints
│   ├── queue.ts                #    Queue management
│   └── admin.ts                #    Admin/D1 endpoints
├── middleware/                  #    Request middleware
│   └── index.ts                #    Rate limit, auth, size validation
├── workflows/                  #    Durable execution workflows
│   ├── CompilationWorkflow.ts
│   ├── BatchCompilationWorkflow.ts
│   ├── CacheWarmingWorkflow.ts
│   ├── HealthMonitoringWorkflow.ts
│   ├── WorkflowEvents.ts
│   └── types.ts
└── utils/                      #    Worker utilities
    ├── response.ts             #    JsonResponse helper
    └── errorReporter.ts        #    Worker error reporter

Detailed Module Breakdown

Compiler (src/compiler/)

The orchestration layer that drives the entire compilation process.

flowchart TD
    FC["FilterCompiler\n← Main entry point (has FS access)"]
    FC -->|uses| SC["SourceCompiler"]
    FC -->|uses| HG["HeaderGenerator"]
    FC -->|uses| TP["TransformationPipeline"]
    SC -->|uses| FD["FilterDownloader"]
ClassResponsibility
FilterCompilerOrchestrates full compilation: validation → download → transform → header → output. Has file system access via Deno.
SourceCompilerCompiles a single source: downloads content, applies per-source transformations.
IncrementalCompilerWraps FilterCompiler with content-hash-based caching; only recompiles changed sources. Uses ICacheStorage.
HeaderGeneratorGenerates metadata headers (title, description, version, timestamp, checksum placeholder).

Platform Abstraction (src/platform/)

Enables the compiler to run in environments without file system access (browsers, Cloudflare Workers, Deno Deploy).

flowchart TD
    WC["WorkerCompiler\n← No FS access"]
    WC -->|uses| CF["CompositeFetcher\n← Chain of Responsibility"]
    CF --> PFCF["PreFetchedContentFetcher"]
    CF --> HF["HttpFetcher\n(Fetch API)"]
ClassResponsibility
WorkerCompilerEdge-compatible compiler; delegates I/O to IContentFetcher chain.
IContentFetcherInterface: canHandle(source) + fetch(source).
HttpFetcherFetches via the standard Fetch API; works everywhere.
PreFetchedContentFetcherServes content from an in-memory map (for pre-fetched content from the worker).
CompositeFetcherTries fetchers in order; first match wins.
PlatformDownloaderPlatform-agnostic downloader with preprocessor directive support.

Transformations (src/transformations/)

The transformation pipeline uses the Strategy and Registry patterns.

flowchart TD
    TP["TransformationPipeline\n← Applies ordered transforms"]
    TP -->|delegates to| TR["TransformationRegistry\n← Maps type → instance"]
    TR -->|contains| ST1["SyncTransformation\n(Deduplicate)"]
    TR -->|contains| ST2["SyncTransformation\n(Compress)"]
    TR -->|contains| AT["AsyncTransformation\n(future async)"]

Base Classes:

ClassDescription
TransformationAbstract base; defines execute(rules): Promise<string[]>
SyncTransformationFor CPU-bound in-memory transforms; wraps sync method in Promise.resolve()
AsyncTransformationFor transforms needing I/O or external resources

Built-in Transformations:

TransformationTypeDescription
RemoveCommentsSyncStrips comment lines (!, #)
CompressSyncConverts hosts → adblock format, removes redundant rules
RemoveModifiersSyncStrips unsupported modifiers from rules
ValidateSyncValidates rules for DNS-level blocking, removes IPs
ValidateAllowIpSyncLike Validate but keeps IP address rules
DeduplicateSyncRemoves duplicate rules, preserves order
InvertAllowSyncConverts blocking rules to allow (exception) rules
RemoveEmptyLinesSyncStrips blank lines
TrimLinesSyncRemoves leading/trailing whitespace
InsertFinalNewLineSyncEnsures output ends with newline
ConvertToAsciiSyncConverts IDN/Unicode domains to punycode
ExcludeSyncApplies exclusion patterns
IncludeSyncApplies inclusion patterns
ConflictDetectionSyncDetects conflicting block/allow rules
RuleOptimizerSyncOptimizes and simplifies rules

Downloader (src/downloader/)

Handles fetching filter list content with preprocessor directive support.

flowchart TD
    FD["FilterDownloader\n← Static download() method"]
    FD -->|uses| CF["ContentFetcher\n(FS + HTTP)"]
    FD -->|uses| PE["PreprocessorEvaluator\n(!#if, !#include)"]
    PE -->|uses| CE["ConditionalEvaluator\n(boolean expr)"]
ClassResponsibility
FilterDownloaderDownloads from URLs or local files; supports retries, circuit breaker, exponential backoff.
ContentFetcherAbstraction over Deno.readTextFile and fetch() with DI interfaces (IFileSystem, IHttpClient).
PreprocessorEvaluatorProcesses !#if, !#else, !#endif, !#include, !#safari_cb_affinity directives.
ConditionalEvaluatorEvaluates boolean expressions with platform identifiers (e.g., windows && !android).

Configuration & Validation

src/configuration/ — Runtime validation:

ComponentDescription
ConfigurationValidatorValidates IConfiguration against Zod schemas; produces human-readable errors.
schemas.tsZod schemas for IConfiguration, ISource, CompileRequest, BatchRequest, HTTP options.

src/config/ — Centralized constants:

Constant GroupExamples
NETWORK_DEFAULTSTimeout (30s), max retries (3), circuit breaker threshold (5)
WORKER_DEFAULTSRate limit (10 req/60s), cache TTL (1h), max batch size (10)
STORAGE_DEFAULTSCache TTL (1h), max memory entries (100)
COMPILATION_DEFAULTSDefault source type (adblock), max concurrent downloads (10)
VALIDATION_DEFAULTSMax rule length (10K chars)
PREPROCESSOR_DEFAULTSMax include depth (10)

Storage (src/storage/)

Pluggable persistence layer with multiple backends.

flowchart TD
    ISA["IStorageAdapter\n← Abstract interface"]
    ISA --> PSA["PrismaStorageAdapter\n(SQLite, PostgreSQL, MySQL, etc.)"]
    ISA --> D1A["D1StorageAdapter\n(Edge)"]
    ISA --> MEM["(Memory) — Future"]
    CD["CachingDownloader"] -->|uses| ISA
    SHM["SourceHealthMonitor"] -->|uses| ISA
    CD -->|uses| CHD["ChangeDetector"]
ComponentDescription
IStorageAdapterInterface with hierarchical key-value ops, TTL support, filter list caching, compilation history.
PrismaStorageAdapterPrisma ORM backend: SQLite (default), PostgreSQL, MySQL, MongoDB, etc.
D1StorageAdapterCloudflare D1 (edge SQLite) backend.
CachingDownloaderWraps any IDownloader with caching, change detection, and health monitoring.
ChangeDetectorTracks content hashes to detect changes between compilations.
SourceHealthMonitorTracks fetch success/failure rates, latency, and health status per source.

Services (src/services/)

Higher-level business services.

ServiceResponsibility
FilterServiceDownloads exclusion/inclusion sources in parallel; prepares Wildcard patterns.
ASTViewerServiceParses adblock rules into structured AST using @adguard/agtree; provides category, type, syntax, properties.
AnalyticsServiceType-safe wrapper for Cloudflare Analytics Engine; tracks compilations, cache hits, rate limits, workflow events.

Queue (src/queue/)

Asynchronous job processing abstraction.

flowchart TD
    IQP["IQueueProvider\n← Abstract interface"]
    IQP --> CQP["CloudflareQueueProvider\n← Cloudflare Workers Queue binding"]
    CQP --> CM["CompileMessage\n(single compilation)"]
    CQP --> BCM["BatchCompileMessage\n(batch compilation)"]
    CQP --> CWM["CacheWarmMessage\n(cache warming)"]
    CQP --> HCM["HealthCheckMessage\n(source health checks)"]

Diagnostics & Tracing (src/diagnostics/)

End-to-end observability through the compilation pipeline.

flowchart LR
    TC["TracingContext\n(correlation ID, parent spans)"]
    DC["DiagnosticsCollector\n(event aggregation)"]
    OTE["OpenTelemetryExporter\n(Datadog, Honeycomb, Jaeger, etc.)"]
    TC --> DC
    DC -->|can export to| OTE
ComponentDescription
TracingContextCarries correlation ID, parent span, metadata through the pipeline.
DiagnosticsCollectorRecords operation start/end, network events, cache events, performance metrics.
OpenTelemetryExporterBridges to OpenTelemetry's Tracer API for distributed tracing integration.

Filters (src/filters/)

ComponentDescription
RuleFilterApplies exclusion/inclusion wildcard patterns to rule sets. Partitions into plain strings (fast) vs. regex/wildcards (slower) for optimized matching.

Formatters (src/formatters/)

ComponentDescription
OutputFormatterConverts adblock rules to multiple output formats: adblock, hosts (0.0.0.0), dnsmasq, plain domain list. Extensible via BaseFormatter.

Diff (src/diff/)

ComponentDescription
DiffReportGenerates rule-level and domain-level diff reports between two compilations. Outputs summary stats (added, removed, unchanged, % change).

Plugins (src/plugins/)

Extensibility system for custom transformations and downloaders.

flowchart TD
    PR["PluginRegistry\n← Global singleton"]
    PR -->|registers| P["Plugin\n{manifest, transforms, downloaders}"]
    P --> TPLG["TransformationPlugin"]
    P --> DPLG["DownloaderPlugin"]
ComponentDescription
PluginRegistryManages plugin lifecycle: load, init, register transformations, cleanup.
PluginDefines a manifest (name, version, author) + optional transformations and downloaders.
PluginTransformationWrapperWraps a TransformationPlugin function as a standard Transformation class.

Utilities (src/utils/)

Shared, reusable components used across all modules.

UtilityDescription
RuleUtilsRule classification: isComment(), isAdblockRule(), isHostsRule(), parseAdblockRule(), parseHostsRule().
StringUtilsString manipulation: trimming, splitting, normalization.
TldUtilsTLD validation and extraction.
WildcardGlob-style pattern matching (*, ?) compiled to regex.
CircuitBreakerThree-state circuit breaker (Closed → Open → Half-Open) for fault tolerance.
AsyncRetryRetry with exponential backoff and jitter.
ErrorUtilsTyped error hierarchy: BaseError, CompilationError, NetworkError, SourceError, ValidationError, ConfigurationError, FileSystemError.
CompilerEventEmitterType-safe event emission for compilation lifecycle.
BenchmarkCollectorPerformance timing and phase tracking.
BooleanExpressionParserParses !#if condition expressions.
AGTreeParserWraps @adguard/agtree for rule AST parsing.
ErrorReporterMulti-target error reporting (console, Cloudflare, Sentry, composite).
Logger / StructuredLoggerLeveled logging with module-specific overrides and JSON output.
checksumFilter list checksum computation.
PathUtilsSafe path resolution to prevent directory traversal.

CLI (src/cli/)

Command-line interface for local compilation.

ComponentDescription
CliAppMain CLI application; parses args, builds/overlays config, runs FilterCompiler, writes output (file, stdout, append).
ArgumentParserParses all CLI flags — transformation control, filtering, output modes, networking, and queue options. Validates via CliArgumentsSchema.
ConfigurationLoaderLoads and parses JSON configuration files.
OutputWriterWrites compiled rules to the file system.

See the CLI Reference for the full flag list and examples.

Deployment (src/deployment/)

ComponentDescription
version.tsTracks deployment history with records (version, build number, git commit, status) stored in D1.

Cloudflare Worker (worker/)

The edge deployment target that exposes the compiler as an HTTP/WebSocket API.

flowchart TD
    REQ["Incoming Request"]
    REQ --> W["worker.ts\n← Entry point (fetch, queue, scheduled)"]
    W --> R["router.ts\n(HTTP API)"]
    W --> WS["websocket.ts (WS)"]
    W --> QH["queue handler\n(async jobs)"]
    R --> HC["handlers/compile.ts"]
    R --> HM["handlers/metrics.ts"]
    R --> HQ["handlers/queue"]
    R --> HA["handlers/admin"]

API Endpoints

MethodPathHandlerDescription
POST/api/compilehandleCompileJsonSynchronous JSON compilation
POST/api/compile/streamhandleCompileStreamSSE streaming compilation
POST/api/compile/asynchandleCompileAsyncQueue-based async compilation
POST/api/compile/batchhandleCompileBatchBatch sync compilation
POST/api/compile/batch/asynchandleCompileBatchAsyncBatch async compilation
POST/api/ast/parsehandleASTParseRequestRule AST parsing
GET/api/versioninlineVersion info
GET/api/healthinlineHealth check
GET/api/metricshandleMetricsAggregated metrics
GET/api/queue/statshandleQueueStatsQueue statistics
GET/api/queue/results/:idhandleQueueResultsAsync job results
GET/wshandleWebSocketUpgradeWebSocket compilation

Admin Endpoints (require X-Admin-Key)

MethodPathHandler
GET/api/admin/storage/statsD1 storage statistics
POST/api/admin/storage/queryRaw SQL query
POST/api/admin/storage/clear-cacheClear cached data
POST/api/admin/storage/clear-expiredClean expired entries
GET/api/admin/storage/exportExport all data
POST/api/admin/storage/vacuumOptimize database
GET/api/admin/storage/tablesList D1 tables

Middleware Stack

flowchart LR
    REQ["Request"] --> RL["Rate Limit"]
    RL --> TS["Turnstile"]
    TS --> BS["Body Size"]
    BS --> AUTH["Auth"]
    AUTH --> H["Handler"]
    H --> RESP["Response"]
MiddlewareDescription
checkRateLimitKV-backed sliding window rate limiter (10 req/60s default)
verifyTurnstileTokenCloudflare Turnstile CAPTCHA verification
validateRequestSizePrevents DoS via oversized payloads (1MB default)
verifyAdminAuthAPI key authentication for admin endpoints

Durable Workflows

Long-running, crash-resistant compilation pipelines using Cloudflare Workflows:

WorkflowDescription
CompilationWorkflowFull compilation with step-by-step checkpointing: validate → fetch → transform → header → cache.
BatchCompilationWorkflowProcesses multiple compilations with progress tracking.
CacheWarmingWorkflowPre-compiles popular configurations to warm the cache.
HealthMonitoringWorkflowPeriodically checks source availability and health.

Environment Bindings

BindingTypePurpose
COMPILATION_CACHEKVCompiled rule caching
RATE_LIMITKVPer-IP rate limit tracking
METRICSKVEndpoint metrics aggregation
ADBLOCK_COMPILER_QUEUEQueueStandard priority async jobs
ADBLOCK_COMPILER_QUEUE_HIGH_PRIORITYQueueHigh priority async jobs
DBD1SQLite storage (admin, metadata)
ANALYTICS_ENGINEAnalytics EngineMetrics & analytics
ASSETSFetcherStatic web UI assets

Web UI (public/)

Static HTML/JS/CSS frontend served from Cloudflare Workers or Pages.

FileDescription
index.htmlMain landing page with documentation
compiler.htmlInteractive compilation UI with SSE streaming
admin-storage.htmlD1 storage administration dashboard
test.htmlAPI testing interface
validation-demo.htmlConfiguration validation demo
websocket-test.htmlWebSocket compilation testing
e2e-tests.htmlEnd-to-end test runner
js/theme.tsDark/light theme toggle (ESM module)
js/chart.tsChart.js configuration for metrics visualization

Cross-Cutting Concerns

Error Handling

flowchart TD
    BE["BaseError (abstract)"]
    BE --> CE["CompilationError\n— Compilation pipeline failures"]
    BE --> NE["NetworkError\n— HTTP/connection failures"]
    BE --> SE["SourceError\n— Source download/parse failures"]
    BE --> VE["ValidationError\n— Configuration/rule validation failures"]
    BE --> CFE["ConfigurationError\n— Invalid configuration"]
    BE --> FSE["FileSystemError\n— File system operation failures"]

Each error carries: code (ErrorCode enum), cause (original error), timestamp (ISO string).

Event System

The ICompilerEvents interface provides lifecycle hooks:

flowchart TD
    CS["Compilation Start"]
    CS --> OSS["onSourceStart\n(per source)"]
    CS --> OSC["onSourceComplete\n(per source, with rule count & duration)"]
    CS --> OSE["onSourceError\n(per source, with error)"]
    CS --> OTS["onTransformationStart\n(per transformation)"]
    CS --> OTC["onTransformationComplete\n(per transformation, with counts)"]
    CS --> OP["onProgress\n(phase, current/total, message)"]
    CS --> OCC["onCompilationComplete\n(total rules, duration, counts)"]

Logging

Two logger implementations:

LoggerUse Case
LoggerConsole-based, leveled (trace → error), with optional prefix
StructuredLoggerJSON output for log aggregation (CloudWatch, Datadog, Splunk)

Both implement ILogger (extends IDetailedLogger): info(), warn(), error(), debug(), trace().

Resilience Patterns

PatternImplementationUsed By
Circuit BreakerCircuitBreaker.ts (Closed → Open → Half-Open)FilterDownloader
Retry with BackoffAsyncRetry.ts (exponential + jitter)FilterDownloader
Rate LimitingKV-backed sliding windowWorker middleware
Request DeduplicationIn-memory Map<key, Promise>Worker compile handler

Data Flow Diagrams

CLI Compilation Flow

flowchart LR
    CFG["config.json"] --> CL["ConfigurationLoader"]
    FS["Filter Sources\n(HTTP/FS)"] --> FC
    CL --> FC["FilterCompiler"]
    FC --> SC["SourceCompiler\n(per src)"]
    FC --> TP["TransformationPipeline"]
    FC --> OUT["output.txt"]

Worker API Flow (SSE Streaming)

sequenceDiagram
    participant Client
    participant Worker
    participant Sources

    Client->>Worker: POST /api/compile/stream
    Worker->>Sources: Pre-fetch content
    Sources-->>Worker: content
    Note over Worker: WorkerCompiler.compile()
    Worker-->>Client: SSE: event: log
    Worker-->>Client: SSE: event: source-start
    Worker-->>Client: SSE: event: source-complete
    Worker-->>Client: SSE: event: progress
    Note over Worker: Cache result in KV
    Worker-->>Client: SSE: event: complete

Async Queue Flow

sequenceDiagram
    participant Client
    participant Worker
    participant Queue
    participant Consumer

    Client->>Worker: POST /compile/async
    Worker->>Queue: enqueue message
    Worker-->>Client: 202 {requestId}
    Queue->>Consumer: dequeue
    Consumer->>Consumer: compile
    Consumer->>Queue: store result
    Client->>Worker: GET /queue/results/:id
    Worker->>Queue: fetch result
    Worker-->>Client: 200 {rules}

Deployment Architecture

graph TD
    subgraph CFN["Cloudflare Edge Network"]
        subgraph CW["Cloudflare Worker (worker.ts)"]
            HAPI["HTTP API Router"]
            WSH["WebSocket Handler"]
            QC["Queue Consumer\n(async compile)"]
            DWF["Durable Workflows"]
            TW["Tail Worker"]
            SA["Static Assets\n(Pages/ASSETS)"]
        end
        KV["KV Store\n- Cache\n- Rates\n- Metrics"]
        D1["D1 (SQL)\n- Storage\n- Deploy\n- History"]
        QQ["Queues\n- Std\n- High"]
        AE["Analytics Engine"]
    end

    CLIENTS["Clients\n(Browser, CI/CD, CLI)"] -->|HTTP/SSE/WS| HAPI
    HAPI -->|HTTP fetch sources| FLS["Filter List Sources\n(EasyList, etc.)"]

Technology Stack

LayerTechnology
RuntimeDeno 2.6.7+
LanguageTypeScript (strict mode)
Package RegistryJSR (@jk-com/adblock-compiler)
Edge RuntimeCloudflare Workers
ValidationZod
Rule Parsing@adguard/agtree
ORMPrisma (optional, for local storage)
DatabaseSQLite (local), Cloudflare D1 (edge)
CachingCloudflare KV
QueueCloudflare Queues
AnalyticsCloudflare Analytics Engine
ObservabilityOpenTelemetry (optional), DiagnosticsCollector
UIStatic HTML + Tailwind CSS + Chart.js
CI/CDGitHub Actions
ContainerizationDocker + Docker Compose
FormattingDeno built-in formatter
TestingDeno built-in test framework + @std/assert