Skip to content

feat: add regExpToRoute() to convert PCRE regex back to route pattern - #188

Merged
pi0 merged 5 commits into
mainfrom
feat/pcre-to-route
Jul 2, 2026
Merged

pi0 merged 5 commits into
mainfrom
feat/pcre-to-route

Conversation

@pi0x

@pi0x pi0x commented Jul 2, 2026 •

Copy link
Copy Markdown
Contributor

Summary

Adds regExpToRoute() β€” the inverse of the existing routeToRegExp(). It parses an anchored, PCRE-compatible RegExp (or its source string) back into a rou3 route pattern.

regExpToRoute(/^\/users\/(?<id>\d+)\/?$/);     // "/users/:id(\\d+)"
regExpToRoute(/^\/path\/(?<param>[^/]+)\/?$/); // "/path/:param"
regExpToRoute(/^\/base\/?(?<path>.+)\/?$/);    // "/base/**:path"
  • Exported from rou3; tree-shakeable β€” zero impact on the core bundle (only pulled in when imported).
  • Targets the dialect routeToRegExp() emits; hand-written regexes following the same conventions convert too. Constructs outside the dialect throw a clear rou3: error rather than returning corrupt output.

Mapping

Regex Route
(?<param>[^/]+) :param
(?<id>\d+) :id(\d+)
(?<_0>[^/]*) *
(?<_0>\d+) (\d+)
\/?(?<_>.*) / \/?(?<name>.+) ** / **:name
(?:\/(?<id>[^/]+))? :id?
(?:\/(?<rest>.*))? :rest*
\/(?<rest>.+) :rest+
(?<id>\d+(?:\/\d+)*) :id(\d+)+
(?:s)? / (?:\/bar)? {s}? / {/bar}?

Round-trip guarantee

routeToRegExp(regExpToRoute(regex)).source === regex.source holds for every non-fallback fixture in test/_regexp-cases.ts. The non-reversible alternation-fallback forms (PCRE2_DUPLICATE_NAME_ROUTES, e.g. /media/*{.webp}?) throw.

Review fixes included

An independent review surfaced two correctness bugs, both fixed here with regression tests:

  • Literal regex metacharacters (? + | ^ $ [ ]) sharing a segment with a param were emitted raw and reinterpreted as operators β€” now re-escaped.
  • Inline constraints containing / (and unnamed [^/]+) are unrepresentable as routes β€” now throw instead of returning corrupt output.

Tests

test/regexp-to-route.test.ts: round-trips all reversible fixtures + core constructs, literal-metachar round-trips, and the throw paths. Full suite green, types + lint clean.

πŸ€– Generated with Claude Code

Summary by CodeRabbit

  • New Features

    • Added a new utility to convert supported regular expressions back into route patterns.
    • Expanded public API support so the utility can be used from the main package entry point.
  • Documentation

    • Updated the README with examples and guidance for the new regular expression conversion feature.
  • Tests

    • Added coverage for round-trip behavior, supported pattern forms, and invalid inputs.

pi0 and others added 3 commits July 2, 2026 21:41
Inverse of routeToRegExp(). Tree-shakeable (zero core-bundle impact);
round-trips every non-fallback regexp fixture. Alternation-fallback
forms are not reversible and throw.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
# Conflicts:
#	test/bench/bundle.test.ts
…table constraints

Address two correctness bugs found in independent review:
- ROUTE_SPECIAL omitted `? + | ^ $ [ ]`, so a literal metachar sharing a
  segment with a param was emitted raw and routeToRegExp reinterpreted it
  as an operator (e.g. `/a\+:id` round-tripped to a `+` quantifier).
- Inline param constraints containing `/` (and unnamed `[^/]+`) produced
  routes rou3 cannot express; now throw instead of returning corrupt output.

Adds regression tests and lets automd document the new export.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
@pi0x
pi0x requested a review from pi0 as a code owner July 2, 2026 21:55
@coderabbitai

coderabbitai Bot commented Jul 2, 2026 •

Copy link
Copy Markdown

Review Change Stack

πŸ“ Walkthrough

Walkthrough

Adds a new regExpToRoute(regexp) function that parses an anchored, PCRE-compatible RegExp (or its source string) back into a rou3 route pattern, exports it from the package entry point, documents it in AGENTS.md and README.md, and adds a dedicated test suite.

Changes

regExpToRoute utility

Layer / File(s) Summary
Entry point and source normalization
src/regexp-to-route.ts
Adds module header, ROUTE_SPECIAL set, and the exported regExpToRoute function that validates regex flags, strips anchors/trailing-slash artifacts, and loops through segments.
Segment and optional-group reversal
src/regexp-to-route.ts
reverseSegment converts a single segment into rou3 syntax; applyOptional/mergeGroup handle (?:...)? optional units, merging bodies into preceding segments.
Token classification and support helpers
src/regexp-to-route.ts
paramToken/optionalParam classify captured group bodies into *, :name, :name(<pat>) forms; matchRepeat, constraint, and escapeLiteral support repeat detection, constraint wrapping, and literal escaping.
Group/segment boundary scanning
src/regexp-to-route.ts
matchNamedGroup, readGroup, and segmentEnd implement bracket/paren-aware scanning to locate named groups, matching parentheses, and segment boundaries.
Public export, docs, and tests
src/index.ts, AGENTS.md, README.md, test/bench/bundle.test.ts, test/regexp-to-route.test.ts
Re-exports regExpToRoute, documents it in the project structure, public API, and README (with usage examples and round-trip guarantee), notes bundle tree-shakeability, and adds a comprehensive test suite covering conversions, round-trips, escaping, and thrown errors.

Estimated code review effort: 4 (Complex) | ~50 minutes

Poem

A regex hopped in, tangled and tight,
I nibbled its anchors and set the route right.
Named groups, wild stars, optional bendsβ€”
Round-trip complete, where the parsing ends.
πŸ‡βœ¨ Hop, throw, or bloomβ€”rou3 knows the way!

πŸš₯ Pre-merge checks | βœ… 5
βœ… Passed checks (5 passed)
Check name Status Explanation
Description Check βœ… Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check βœ… Passed The title clearly describes the new regExpToRoute feature and matches the main change in the pull request.
Docstring Coverage βœ… Passed No functions found in the changed files to evaluate docstring coverage. Skipping docstring coverage check.
Linked Issues check βœ… Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check βœ… Passed Check skipped because no linked issues were found for this pull request.
✨ Finishing Touches
πŸ“ Generate docstrings
  • Create stacked PR
  • Commit on current branch
πŸ§ͺ Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch feat/pcre-to-route

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❀️ Share

Comment @coderabbitai help to get the list of available commands.

@codecov

codecov Bot commented Jul 2, 2026 •

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 96.83544% with 5 lines in your changes missing coverage. Please review.

Files with missing lines Patch % Lines
src/regexp-to-route.ts 96.83% 5 Missing ⚠️

πŸ“’ Thoughts on this report? Let us know!

pi0 and others added 2 commits July 2, 2026 22:00
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
reverseSegment() literalized any token it didn't recognize, so several
common PCRE constructs silently produced a wrong route (or crashed with
an internal TypeError), contradicting the "throws a clear rou3: error"
guarantee. Make it a whitelist parser: only named/bare groups,
escaped-punctuation literals and plain literal chars are accepted.

Now rejected with a rou3: error:
- structural look-arounds ((?= (?! (?<= (?<!) and other (?...) constructs
- backreferences / metaclass escapes outside a constraint (\k<x>, \1, \d,
  \w, \b)
- bare unescaped regex operators at segment level (. ^ $ * + ? | [ ] { })
- match-affecting flags (i/m/s); g/y/u/v/d stay ignored

Also extend support: bare (unnamed) capturing groups now map like their
(?<_N>...) equivalents ((\d+) -> (\d+), ([^/]*) -> *). Constraint bodies
stay opaque and round-trip verbatim.

Adds regression tests (proven to fail first) and documents the
reject-by-default contract in AGENTS.md.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🧹 Nitpick comments (1)
src/regexp-to-route.ts (1)

1-309: πŸ“ Maintainability & Code Quality | πŸ”΅ Trivial | βš–οΈ Poor tradeoff

Module exceeds the 200-line single-file limit.

This module is ~309 lines. Consider extracting the scanning helpers (matchNamedGroup, readGroup, segmentEnd) and/or the token classifiers (paramToken, optionalParam, matchRepeat, constraint, escapeLiteral) into a sibling module, keeping the exported regExpToRoute and its immediate segment loop here. Low priority given the parser's cohesion.

As per coding guidelines: "Split logic across files and avoid long single-file modules (over 200 lines)."

πŸ€– Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@src/regexp-to-route.ts` around lines 1 - 309, The module is over the
single-file size limit, so split the parsing helpers out of regExpToRoute into a
sibling module to reduce this file below the threshold. Move the scanning
utilities like matchNamedGroup, readGroup, and segmentEnd, and optionally the
token classifiers such as paramToken, optionalParam, matchRepeat, constraint,
and escapeLiteral, while keeping regExpToRoute and its main loop here. Preserve
the current behavior by importing the extracted helpers back into this module.

Source: Coding guidelines

πŸ€– Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Nitpick comments:
In `@src/regexp-to-route.ts`:
- Around line 1-309: The module is over the single-file size limit, so split the
parsing helpers out of regExpToRoute into a sibling module to reduce this file
below the threshold. Move the scanning utilities like matchNamedGroup,
readGroup, and segmentEnd, and optionally the token classifiers such as
paramToken, optionalParam, matchRepeat, constraint, and escapeLiteral, while
keeping regExpToRoute and its main loop here. Preserve the current behavior by
importing the extracted helpers back into this module.

ℹ️ Review info
βš™οΈ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

Run ID: 38245c9f-b103-407d-8186-6cf8cec74625

πŸ“₯ Commits

Reviewing files that changed from the base of the PR and between e8d816e and ffb62fe.

πŸ“’ Files selected for processing (6)
  • AGENTS.md
  • README.md
  • src/index.ts
  • src/regexp-to-route.ts
  • test/bench/bundle.test.ts
  • test/regexp-to-route.test.ts

@pi0
pi0 merged commit e57e131 into main Jul 2, 2026
5 of 6 checks passed
@pi0
pi0 deleted the feat/pcre-to-route branch July 2, 2026 22:17
@pi0x pi0x mentioned this pull request Aug 21, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants