Rebasely Beta: data may be purged

justintypescript-ultra-strict Public

Markdown · 1.7 KiB · at 355e324

Write matchRoute(routes, path), which finds the route pattern that best matches a URL path and extracts its parameters.

Route patterns: "/" (no segments), or "/"-separated non-empty segments after a leading "/", e.g. "/users/:id/files/*rest". Each segment is one of:

  • static text, which matches a path segment exactly (case-sensitive, compared before decoding);
  • :name, a param, which matches exactly one non-empty path segment;
  • *name, a splat, allowed only as the last segment, which matches all remaining path segments (zero or more), joined with "/".

A pattern is invalid if it does not start with "/", has an empty segment (including a trailing "/", except the pattern "/" itself), has a param or splat with an empty name, has a splat that is not last, or uses the same name twice. All patterns are validated before any matching; the first invalid one in list order fails with { kind: "invalid_route", route }.

The path always starts with "/". Before matching, drop everything from the first "?" on, then drop one trailing "/" unless the path is just "/". Param and splat values are percent-decoded with decodeURIComponent rules (the splat after joining). If a value cannot be decoded, that route does not match.

When several routes match, pick the most specific: compare their segments left to right, and at the first position where they differ in kind, static beats param, param beats splat, and a route that has no segment at that position beats a splat. If no position differs, the route earlier in the list wins.

Return { route, params } for the winning route, where route is the pattern string and params is a plain object with one own property per param or splat name. If no route matches, the result is absent.