$ show le0pard/re2js
re2js is a pure JavaScript port of Google's RE2 regular expression engine, providing linear-time O(n) matching and protection against ReDoS attacks. It implements a full compilation pipeline: parsing RE2 syntax into an AST, simplifying the expression, compiling into a bytecode instruction set (Prog), and executing via multiple engines (DFA, NFA, OnePass, Backtracker, Prefilter). The library exposes a Java-style Matcher API with find, matches, replaceAll, and supports named capture groups, lookbehinds (linear-time), and both JS and Java replacement string dialects. It is distributed as an npm package supporting ESM, CJS, and UMD, with TypeScript declarations, and is tested across Node.js, Bun, Deno, and browsers. The architecture follows Russ Cox's regexp articles and uses sparse sets for efficient NFA simulation. Unicode tables for categories, scripts, and case folding are generated from @unicode/unicode-17.0.0 and decoded lazily.
The LLM identified 3 files worth highlighting for reuse:
Performs simplification passes on the parsed Regexp AST (e.g., removing empty captures, flattening nested alternations) before compilation. This pass is self-contained (imports only Regexp and constants) and could be extracted as a standalone regex optimizer for other regex engines or tools.
Provides a uniform interface over different input types (UTF-16 strings, UTF-8 Uint8Array, generic arrays) for the regex execution engines. It supports one-character lookahead and bounded input for lookbehinds. The abstraction is clean, generic, and reusable for any pattern-matching system that needs to operate on multiple data representations.
Contains generated Unicode range tables (categories, scripts, binary properties, case folding) encoded using a base64-VLQ scheme and decoded lazily via a LazyMap. This pattern of deferring expensive table construction is reusable for any project needing large precomputed lookup tables without increasing startup time or bundle size.