Skip to content

Programmatic API Reference

Programmatic API Reference

Back to API docs

This document covers the advanced programmatic API surface exported from @jk-com/bloqr-compiler. All of the features below are available when the package is used as a library; they are separate from the CLI. Import them directly from @jk-com/bloqr-compiler in any Deno or Node.js project.

For CLI usage, see CLI.md. For configuration file options, see CONFIGURATION.md.


Output Formatters

Convert compiled rule arrays into different output formats.

Functions

createFormatter(format, options?)

import { createFormatter, OutputFormat } from '@jk-com/bloqr-compiler';
const formatter = createFormatter(OutputFormat.Hosts);
const result = formatter.format(rules);
console.log(result.content);

formatOutput(rules, format, options?)

Convenience wrapper that creates a formatter and formats in one call.

import { formatOutput, OutputFormat } from '@jk-com/bloqr-compiler';
const result = formatOutput(rules, OutputFormat.Dnsmasq);
console.log(result.content);

Available Formats

OutputFormat valueFormatter classDescription
adblockAdblockFormatterAdGuard / uBlock Origin adblock syntax
hostsHostsFormatter/etc/hosts-style format
dnsmasqDnsmasqFormatterdnsmasq address= directives
dohDoHFormatterDNS-over-HTTPS blocklist format
jsonJsonFormatterJSON array of rule strings
piholePiHoleFormatterPi-hole compatible blocklist
unboundUnboundFormatterUnbound DNS resolver local-zone format

Diff Reports

Compare two compiled filter lists and generate a human-readable diff report.

Functions

generateDiff(oldRules, newRules, options?)

import { generateDiff } from '@jk-com/bloqr-compiler';
const report = generateDiff(previousRules, currentRules);
console.log(`Added: ${report.added.length}, Removed: ${report.removed.length}`);

generateDiffMarkdown(report)

Renders a DiffReport as a Markdown string suitable for PR comments or changelogs.

import { generateDiff, generateDiffMarkdown } from '@jk-com/bloqr-compiler';
const report = generateDiff(oldRules, newRules);
const markdown = generateDiffMarkdown(report);

DiffGenerator class

For more control, use the DiffGenerator class directly:

import { DiffGenerator } from '@jk-com/bloqr-compiler';
const generator = new DiffGenerator();
const report = generator.generate(oldRules, newRules, { includeUnchanged: false });

Plugin System

Extend the compiler with custom transformations and downloaders via the plugin API.

Core API

ExportDescription
PluginRegistryRegistry class that manages loaded plugins
globalRegistrySingleton PluginRegistry instance
loadPlugin(plugin)Load a plugin into the global registry
createSimplePlugin(name, fn)Create a lightweight plugin from a transformation function
PluginTransformationWrapperWraps a plugin into a Transformation-compatible object

Interfaces

InterfaceDescription
PluginBase plugin interface (name, version, description)
TransformationPluginPlugin that provides a custom transformation
DownloaderPluginPlugin that provides a custom content fetcher

Example

import { createSimplePlugin, loadPlugin } from '@jk-com/bloqr-compiler';
const myPlugin = createSimplePlugin('strip-trackers', (rules) =>
rules.filter((r) => !r.includes('tracker'))
);
loadPlugin(myPlugin);

Incremental Compilation

Compile only changed sources by caching previous results, dramatically reducing build time for large lists.

IncrementalCompiler

import { IncrementalCompiler, MemoryCacheStorage } from '@jk-com/bloqr-compiler';
const cache = new MemoryCacheStorage();
const compiler = new IncrementalCompiler({ cache });
// First run — compiles everything
const result1 = await compiler.compile(config);
// Subsequent runs — only recompiles changed sources
const result2 = await compiler.compile(config);

IncrementalCompilerOptions

OptionTypeDescription
cacheICacheStorageCache storage implementation (required)
loggerILoggerOptional logger

MemoryCacheStorage

In-memory implementation of ICacheStorage. Suitable for single-process use or testing. For persistent caching across restarts, implement your own ICacheStorage.


Diagnostics & OpenTelemetry Tracing

Collect and export fine-grained performance and diagnostic data.

DiagnosticsCollector

import { DiagnosticsCollector } from '@jk-com/bloqr-compiler';
const collector = new DiagnosticsCollector();
// Pass to FilterCompiler options to automatically collect metrics

OpenTelemetryExporter

Implements IDiagnosticsCollector and exports events as OpenTelemetry spans. Construct it with options and pass it wherever a IDiagnosticsCollector is accepted.

import { OpenTelemetryExporter } from '@jk-com/bloqr-compiler';
const otelExporter = new OpenTelemetryExporter({
serviceName: 'my-blocklist-builder',
serviceVersion: '1.0.0',
enableConsoleLogging: true,
});
// Pass as the diagnostics collector in FilterCompiler options
const compiler = new FilterCompiler({ diagnostics: otelExporter });

Tracing helpers

ExportDescription
traceAsync(ctx, name, fn)Wrap an async function in a named trace span
traceSync(ctx, name, fn)Wrap a sync function in a named trace span
createTracingContext(name)Create a root tracing context
createChildContext(parent, name)Create a child span context
TraceCategoryEnum of built-in span categories
TraceSeverityEnum of span severity levels

Transformation Hooks

Attach before/after/error hooks to any transformation in the pipeline for logging, metrics, or side-effects.

TransformationHookManager

import {
TransformationHookManager,
createLoggingHook,
TransformationType,
} from '@jk-com/bloqr-compiler';
const hookManager = new TransformationHookManager();
hookManager.addBeforeHook(TransformationType.Deduplicate, createLoggingHook());

Built-in hook factories

FactoryDescription
createLoggingHook()Logs transformation start/end/error events
createMetricsHook()Collects rule-count metrics for each transformation
createEventBridgeHook(emitter)Bridges hook events into the compiler event emitter

Hook interfaces

InterfaceDescription
BeforeTransformHookCalled before a transformation runs
AfterTransformHookCalled after a transformation completes successfully
TransformErrorHookCalled when a transformation throws an error

Conflict Detection

Detect and optionally auto-resolve conflicting block/allow rules for the same domain.

detectConflicts(rules, options?)

import { detectConflicts } from '@jk-com/bloqr-compiler';
const result = detectConflicts(rules, { autoResolve: true });
console.log(result.conflicts);
console.log(result.resolvedRules);

ConflictDetectionTransformation

Use as part of a custom pipeline via --transformation ConflictDetection or programmatically:

import {
ConflictDetectionTransformation,
TransformationPipeline,
} from '@jk-com/bloqr-compiler';
const transformation = new ConflictDetectionTransformation(logger, { autoResolve: true });
const pipeline = new TransformationPipeline([transformation]);
const result = pipeline.execute(rules);

ConflictDetectionOptions

OptionTypeDescription
autoResolvebooleanAutomatically remove conflicting rules (default: false)
preferAllowbooleanWhen resolving, prefer allow rules over block rules (default: false)

Rule Optimizer

Optimize rules for smaller file size and better matching performance.

optimizeRules(rules, options?)

import { optimizeRules } from '@jk-com/bloqr-compiler';
const { rules: optimized, stats } = optimizeRules(inputRules);
console.log(`Optimized ${stats.rulesOptimized} rules, removed ${stats.redundantRemoved} redundant entries`);

RuleOptimizerTransformation

Use as part of a custom pipeline via --transformation RuleOptimizer or programmatically:

import {
RuleOptimizerTransformation,
TransformationPipeline,
} from '@jk-com/bloqr-compiler';
const transformation = new RuleOptimizerTransformation(logger);
const pipeline = new TransformationPipeline([transformation]);
const result = pipeline.execute(rules);

OptimizationStats

FieldTypeDescription
rulesOptimizednumberNumber of rules that were modified
redundantRemovednumberNumber of redundant rules removed
rulesMergednumberNumber of rules merged into combined patterns
modifiersSimplifiednumberNumber of rules with simplified modifiers
originalCountnumberRule count before optimization