Press n or j to go to the next uncovered block, b, p or k for the previous block.
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 | 151x 151x 151x 151x 151x 151x 151x 151x 151x 151x 151x 151x 151x 151x 151x 151x 151x 151x 151x 151x 151x 151x 151x 151x 151x 151x 151x 151x 151x 50x 50x 77x 77x 77x 50x 23x 23x 23x 23x 2x 23x 23x 23x 4x 23x 6x 6x 23x 5x 23x 5x 23x 1x 23x 1x 23x 23x 5x 5x 9x 23x 23x 23x 4x 23x 23x 5x 23x 5x 23x 23x 5x 23x 5x 23x 4x 1x 3x 3x 3x 1x 3x 1x 3x 3x 23x 23x 23x 138x 138x 113x 113x 33x 33x 33x 33x 80x 80x 79x 79x 79x 79x 23x 10x 10x 10x 10x | import type { AbstractMaskingInstruction } from "./masker/MaskingInstruction.js";
import { MaskingInstruction as MaskingInstructionClass } from "./masker/MaskingInstruction.js";
import type { TemplatePatternStrategy } from "./core/TemplatePatternStrategy.js";
import {
AffixPreservingStrategy,
ExactMatchStrategy,
FullTokenParameterizationStrategy,
RegexParameterizationStrategy,
TemplatePatternStrategyChain,
} from "./core/TemplatePatternStrategy.js";
import type { TokenNormalizer } from "./core/TokenNormalizer.js";
/**
* Configuration object for TemplateMiner.
*
* Maps 1:1 to Python `TemplateMinerConfig` class (drain3/template_miner.py)
* and the drain3.ini file's [DRAIN], [MASKING], and [SNAPSHOT] sections.
*
* All properties have sensible defaults matching Drain3 v0.9.11.
* Use `TemplateMinerConfig.from({...})` to override selectively.
*
* @example
* ```typescript
* const config = TemplateMinerConfig.from({
* simTh: 0.5,
* depth: 5,
* maskingInstructions: DEFAULT_MASKING_INSTRUCTIONS,
* });
* ```
*/
export class TemplateMinerConfig {
// ===================== [DRAIN] section =====================
/**
* Drain algorithm variant.
* - `"Drain"`: Standard fixed-depth prefix tree with position-wise similarity.
* - `"JaccardDrain"`: First-token-based tree with Jaccard set similarity.
*
* Default: "Drain" (matches Drain3 default).
*/
engine: "Drain" | "JaccardDrain" = "Drain";
/** Similarity threshold for creating new clusters. Default: 0.4 */
simTh: number = 0.4;
/** Max depth of parse tree (minimum: 3). Default: 4 */
depth: number = 4;
/** Max child nodes per tree level. Default: 100 */
maxChildren: number = 100;
/**
* Max clusters before LRU eviction begins.
* `null` means unlimited. Default: null
*/
maxClusters: number | null = null;
/** Additional tokenization delimiters (beyond whitespace). */
drainExtraDelimiters: readonly string[] = [];
/** Whether tokens containing digits are treated as parameters. Default: true */
parametrizeNumericTokens: boolean = true;
/**
* Enable param_count as second dimension in prefix tree binning (AEL-inspired).
*
* When enabled, the root-level tree key is "{token_count}#{param_count}"
* instead of just "{token_count}". Messages with the same number of
* parameters are grouped together, improving clustering for datasets
* with variable parameter patterns.
*
* Default: false (Drain3-compatible behavior)
*/
enableParamBinning: boolean = false;
/**
* Immediately generalize masked tokens to paramStr in templates.
*
* @see DrainOptions.enableMaskParamGeneralization
*/
enableMaskParamGeneralization: boolean = false;
/**
* Enable AEL-style diff-ratio similarity for clustering.
*
* @see DrainOptions.enableAELSimilarity
*/
enableAELSimilarity: boolean = false;
/**
* Maximum diff ratio for AEL-style similarity.
*
* @see DrainOptions.maxDiffRatio
*/
maxDiffRatio: number = 0.3;
/**
* Enable post-training cluster merge (AEL reconcile).
*
* When true, the ClusterMergePipeline is applied after all
* messages are processed. This merges clusters that represent
* the same underlying template but were split during training.
*
* Default: false
*/
enableClusterMerge: boolean = false;
/**
* Merge percent threshold for PositionDiffMergeStrategy.
*
* Default: 0.4
*/
clusterMergePercent: number = 0.4;
// ===================== Template Pattern Strategies =====================
/**
* Enable affix-preserving parameterization (e.g., "bytes<*>sent").
*
* When true, tokens with common prefixes/suffixes are parameterized
* in the middle rather than replaced entirely.
*
* Default: false (Drain3-compatible behavior)
*/
enableAffixPreserving: boolean = false;
/**
* Minimum prefix/suffix length to trigger affix-preserving parameterization.
*
* Only used when enableAffixPreserving is true.
* Default: 2
*/
minAffixLength: number = 2;
/**
* Custom regex patterns for parameterization.
*
* Each pattern defines a regex and its corresponding template.
* Use ${paramStr} as placeholder in templates.
*
* Example:
* ```typescript
* customRegexPatterns: [
* { regex: /^(\d{4})-(\d{2})-(\d{2})$/, template: "${paramStr}-${paramStr}-${paramStr}" }
* ]
* ```
*/
customRegexPatterns: ReadonlyArray<{
readonly regex: RegExp;
readonly template: string;
readonly confidence?: number;
}> = [];
/**
* Advanced: Custom template pattern strategies.
*
* If provided, overrides the default strategy chain construction.
* Use this for full control over template generation behavior.
*
* @see TemplatePatternStrategy
*/
templatePatternStrategies?: readonly TemplatePatternStrategy[];
// ===================== Token Normalization =====================
/**
* Pre-clustering token normalizers.
*
* Applied BEFORE Drain clustering to normalize token sequences.
* This addresses tokenization mismatches between parser output
* and ground truth expectations (e.g., variable token counts,
* compound token structures like "bytes<*>sent").
*
* Built-in normalizers:
* - AdjacentConstantFusion: auto-detects and fuses constant adjacent tokens
*
* Default: [] (no normalization — Drain3-compatible behavior)
*
* @see TokenNormalizer
* @see AdjacentConstantFusion
*/
tokenNormalizers: readonly TokenNormalizer[] = [];
/**
* Whether to enable AdjacentConstantFusion auto-detection.
*
* Convenience flag. When true, automatically adds an
* AdjacentConstantFusion normalizer to the pipeline.
*
* Default: false
*/
enableAdjacentFusion: boolean = false;
/**
* Minimum token length for AdjacentConstantFusion content word detection.
*
* Default: 2
*/
minFusionTokenLength: number = 2;
/**
* Regex collapse patterns for pre-fusion token normalization.
*
* Applied BEFORE AdjacentConstantFusion. Each pattern matches in the
* space-joined token string and replaces matches with the given string.
* Use "" to remove matches.
*
* Default: [] (no collapse)
*/
regexCollapsePatterns: ReadonlyArray<{
readonly regex: RegExp;
readonly replacement: string;
}> = [];
/**
* AEL-style regex substitution patterns.
*
* Applied to INDIVIDUAL tokens BEFORE regex collapse and fusion.
* Unlike masking, this replaces matched content within each token
* with ${paramStr}. This normalizes parameter tokens across all
* masking strategies.
*
* Default: [] (no substitution)
*/
aelRegexSubstitution: ReadonlyArray<{
readonly regex: RegExp;
readonly replacement: string;
}> = [];
// ===================== [MASKING] section =====================
/** Masking instruction list. Empty by default — users opt in. */
maskingInstructions: readonly AbstractMaskingInstruction[] = [];
/** Left wrapper for masked parameters. Default: "<" */
maskPrefix: string = "<";
/** Right wrapper for masked parameters. Default: ">" */
maskSuffix: string = ">";
/** Capacity of the parameter extraction regex cache. Default: 100 */
parameterExtractionCacheCapacity: number = 100;
// ===================== [SNAPSHOT] section =====================
/** Minutes between periodic snapshots. Default: 1 */
snapshotIntervalMinutes: number = 1;
/** Whether to gzip-compress snapshot state. Default: false */
snapshotCompressState: boolean = false;
// ===================== Profiling =====================
/** Enable time profiling. Default: false */
profilingEnabled: boolean = false;
/** Profiling report interval in seconds. Default: 60 */
profilingReportSec: number = 60;
/**
* Optional callback invoked when persistence errors occur (async save/load failures).
* If omitted, errors are logged to `console.error`.
*
* @example
* ```typescript
* const config = TemplateMinerConfig.from({
* onError: (context, err) => metrics.increment("drain.persistence.error", { context }),
* });
* ```
*/
onError?: (context: string, error: Error) => void;
// ===================== Preprocessing =====================
/**
* Optional preprocessor function applied to every log message BEFORE
* masking and Drain clustering.
*
* Use this for dataset-specific normalization: strip timestamps,
* normalize paths, handle embedded punctuation, etc.
*
* The preprocessor receives the raw log message and MUST return
* the (possibly modified) log message. If omitted, the message
* is passed through unchanged.
*
* @example
* ```typescript
* // Fix Proxifier-style embedded commas in log content
* const config = TemplateMinerConfig.from({
* preprocessor: (msg) => msg.replace(/,\s+/g, " "),
* });
* ```
*/
preprocessor?: (content: string) => string;
// ===================== Factory =====================
/**
* Creates a config from a partial override object.
*
* This is the idiomatic way to configure TemplateMiner in TypeScript,
* replacing Python's configparser.ini file approach.
*
* @param partial - Subset of properties to override.
* @returns A new TemplateMinerConfig with defaults applied.
*/
static from(partial: Partial<TemplateMinerConfig>): TemplateMinerConfig {
const config = new TemplateMinerConfig();
// Only assign own properties to avoid prototype pollution
for (const key of Object.keys(partial) as (keyof TemplateMinerConfig)[]) {
const value = partial[key];
Eif (value !== undefined) {
(config as unknown as Record<string, unknown>)[key] = value;
}
}
return config;
}
// ===================== INI file support =====================
/**
* Loads configuration from a Drain3-compatible ini file.
*
* Parses the standard [DRAIN], [MASKING], [SNAPSHOT], and [PROFILING]
* sections with the same key names and value formats as Drain3's
* configparser-based ini loader.
*
* @param content - Raw ini file content (UTF-8).
* @returns A new TemplateMinerConfig with ini values applied.
*
* @example
* ```typescript
* import { readFileSync } from "node:fs";
* const ini = readFileSync("drain3.ini", "utf-8");
* const config = TemplateMinerConfig.fromIni(ini);
* ```
*/
static fromIni(content: string): TemplateMinerConfig {
const config = new TemplateMinerConfig();
const sections = parseIni(content);
// [DRAIN]
const drain = sections["DRAIN"] ?? sections["drain"] ?? {};
if (drain["engine"] !== undefined) {
config.engine = drain["engine"] as "Drain" | "JaccardDrain";
}
if (drain["sim_th"] !== undefined) config.simTh = Number(drain["sim_th"]);
if (drain["depth"] !== undefined) config.depth = Number(drain["depth"]);
if (drain["max_children"] !== undefined)
config.maxChildren = Number(drain["max_children"]);
if (drain["max_clusters"] !== undefined) {
const v = Number(drain["max_clusters"]);
config.maxClusters = Number.isNaN(v) ? null : v;
}
if (drain["extra_delimiters"] !== undefined) {
config.drainExtraDelimiters = parseJsonArray(drain["extra_delimiters"]) as string[];
}
if (drain["parametrize_numeric_tokens"] !== undefined) {
config.parametrizeNumericTokens =
drain["parametrize_numeric_tokens"] === "True" ||
drain["parametrize_numeric_tokens"] === "true";
}
if (drain["enable_affix_preserving"] !== undefined) {
config.enableAffixPreserving =
drain["enable_affix_preserving"] === "True" ||
drain["enable_affix_preserving"] === "true";
}
if (drain["min_affix_length"] !== undefined) {
config.minAffixLength = Number(drain["min_affix_length"]);
}
// [MASKING]
const masking = sections["MASKING"] ?? sections["masking"] ?? {};
if (masking["masking"] !== undefined) {
const instructions = parseJsonArray(masking["masking"]);
config.maskingInstructions = (instructions as Array<{ regex_pattern: string; mask_with: string }>).map(
(mi) => new MaskingInstructionClass(mi.regex_pattern, mi.mask_with),
);
}
if (masking["mask_prefix"] !== undefined) config.maskPrefix = masking["mask_prefix"];
if (masking["mask_suffix"] !== undefined) config.maskSuffix = masking["mask_suffix"];
if (masking["parameter_extraction_cache_capacity"] !== undefined) {
config.parameterExtractionCacheCapacity = Number(
masking["parameter_extraction_cache_capacity"],
);
}
// [SNAPSHOT]
const snap = sections["SNAPSHOT"] ?? sections["snapshot"] ?? {};
if (snap["snapshot_interval_minutes"] !== undefined) {
config.snapshotIntervalMinutes = Number(snap["snapshot_interval_minutes"]);
}
if (snap["compress_state"] !== undefined) {
config.snapshotCompressState =
snap["compress_state"] === "True" || snap["compress_state"] === "true";
}
// [PROFILING]
const prof = sections["PROFILING"] ?? sections["profiling"] ?? {};
if (prof["enabled"] !== undefined) {
config.profilingEnabled =
prof["enabled"] === "True" || prof["enabled"] === "true";
}
if (prof["report_sec"] !== undefined) {
config.profilingReportSec = Number(prof["report_sec"]);
}
return config;
}
// ===================== Strategy Chain Builder =====================
/**
* Builds the template pattern strategy chain based on configuration.
*
* Priority order:
* 1. Custom strategies (if provided) — use as-is
* 2. Built from options: Exact → [Regex] → [AffixPreserving] → FullToken
*
* @returns Configured strategy chain
*/
buildStrategyChain(): TemplatePatternStrategyChain {
// If custom strategies provided, use them directly
if (this.templatePatternStrategies) {
return new TemplatePatternStrategyChain().registerAll(
this.templatePatternStrategies,
);
}
// Build from configuration options
const chain = new TemplatePatternStrategyChain();
// Always register exact match (highest priority)
chain.register(new ExactMatchStrategy());
// Register regex patterns if provided
if (this.customRegexPatterns.length > 0) {
chain.register(
new RegexParameterizationStrategy(this.customRegexPatterns),
);
}
// Register affix-preserving if enabled
if (this.enableAffixPreserving) {
chain.register(new AffixPreservingStrategy(this.minAffixLength));
}
// Always register full-token fallback (lowest priority)
chain.register(new FullTokenParameterizationStrategy());
return chain;
}
}
// ============================================================
// INI parser helpers
// ============================================================
/**
* Parses INI content into a map of section → key-value pairs.
*
* Handles:
* - [Section] headers (case-insensitive)
* - key = value assignments
* - # and ; comment lines
* - Multi-line values (continuation via indentation)
* - Empty lines
*/
function parseIni(content: string): Record<string, Record<string, string>> {
const sections: Record<string, Record<string, string>> = {};
let currentSection: string | null = null;
for (const rawLine of content.split(/\r?\n/)) {
const line = rawLine.trim();
// Skip empty lines and comments
if (!line || line.startsWith("#") || line.startsWith(";")) continue;
// Section header
const sectionMatch = line.match(/^\[(.+)\]$/);
if (sectionMatch) {
currentSection = sectionMatch[1]!.trim();
Eif (!sections[currentSection]) {
sections[currentSection] = {};
}
continue;
}
// Key = value
const eqIdx = line.indexOf("=");
if (eqIdx > 0 && currentSection) {
const key = line.slice(0, eqIdx).trim();
let value = line.slice(eqIdx + 1).trim();
// Handle JSON array continuation (multi-line masking value)
Iif (value.startsWith("[") && !value.endsWith("]")) {
// Placeholder: single-line JSON arrays are supported.
// Multi-line JSON arrays (split across lines) are a TODO.
}
sections[currentSection]![key] = value;
}
}
return sections;
}
/**
* Parses a JSON array value from an INI entry.
*
* Drain3's ini format uses Python list/JSON literals for array values
* like `masking = [{"regex_pattern": "...", "mask_with": "IP"}]` and
* `extra_delimiters = ["_", ":"]`.
*/
function parseJsonArray(raw: string): unknown[] {
try {
// Replace Python-style True/False/None with JSON equivalents
const jsonSafe = raw
.replace(/\bTrue\b/g, "true")
.replace(/\bFalse\b/g, "false")
.replace(/\bNone\b/g, "null");
const parsed = JSON.parse(jsonSafe);
return Array.isArray(parsed) ? parsed : [parsed];
} catch {
// If parsing fails, return as single-element string array
return [raw];
}
}
|