whatwg/urlpattern

Reintroduce toRegExp

jacobrask opened this issue · 3 comments

I can see that the design document mentions toRegExp, but that it's not in the shipped versions or specification drafts.

To use URLPattern as the source of truth for routing in a complex application or organisation, it needs to be able to work with a number of different tools on different platforms. Most existing tools that handle paths accept regular expressions. On the web platform, regular expressions are also useful for features such as

input.title = 'Enter a valid route';
input.pattern = urlPattern.toRegExp().toString();

If different regular expressions are needed for the different parts of a pattern, you could introduce a static method on URLPattern to convert a pattern to a regexp.

const pattern = new URLPattern(...);
const re = URLPattern.toRegExp(pattern.pathname);

One of the difficulties I ran into with exposing toRegExp was that the path-to-regexp algorithm does not use named regexp groups. It wants to maintain compatibility with older regexp engines that don't support that feature. But I got feedback that if we wanted to exposed toRegexp() we should probably standardize on using named regexp groups. That would mean diverging from path-to-regexp which would have some downsides; e.g. more difficult to maintain the polyfill, divergence with tooling built on path-to-regexp, etc.

For that reason I decided to wait on exposing toRegExp(). We can consider trying to resolve this issue, though, and exposing this in the future.

I see. Not exposing the method at all is also divergence from path-to-regexp tooling though. I guess an option on toRegExp for whether or not to used named groups is not considered nice API design?

My imagined use case is being able to maintain a list of routes in a URLPattern compatible format, and through a web interface allow things like testing if a path matches a pattern, and copying the regexp for a pattern for usage in other tools.

For tooling that runs outside of the browser I was imagining folks would use the polyfill or path-to-regexp directly in some kind of build automation.