Rebasely Beta: data may be purged

justintypescript-ultra-strict Public

TypeScript · 43 lines · 1.9 KiB · at f30ac63

// Bug: unguarded decodeURIComponent (URIError crashes) and specificity by static-segment count only.export type RouteMatch = { route: string; params: Record<string, string> };export class RouteError extends Error {  readonly kind = "invalid_route" as const;  constructor(public readonly route: string) {    super(`invalid_route: ${route}`);  }}export function matchRoute(routes: string[], path: string): RouteMatch | undefined {  for (const r of routes) {    const segs = r === "/" ? [] : r.slice(1).split("/");    const names = segs.filter((s) => s[0] === ":" || s[0] === "*").map((s) => s.slice(1));    if (!r.startsWith("/") || segs.some((s) => !s) || names.some((n) => !n) || new Set(names).size !== names.length) throw new RouteError(r);    if (segs.some((s, i) => s[0] === "*" && i !== segs.length - 1)) throw new RouteError(r);  }  const clean = path.split("?")[0].replace(/(.)\/$/, "$1");  const parts = clean === "/" ? [] : clean.slice(1).split("/");  const sorted = [...routes].sort(    (a, b) => b.split("/").filter((s) => s && !":*".includes(s[0])).length - a.split("/").filter((s) => s && !":*".includes(s[0])).length,  );  for (const route of sorted) {    const segs = route === "/" ? [] : route.slice(1).split("/");    const params: Record<string, string> = {};    let ok = true;    for (let i = 0; i < segs.length && ok; i++) {      const s = segs[i];      if (s[0] === "*") {        params[s.slice(1)] = decodeURIComponent(parts.slice(i).join("/"));        break;      }      if (i >= parts.length) ok = false;      else if (s[0] === ":") {        if (!parts[i]) ok = false;        else params[s.slice(1)] = decodeURIComponent(parts[i]);      } else if (s !== parts[i]) ok = false;    }    const splat = segs.length > 0 && segs[segs.length - 1][0] === "*";    if (ok && (splat || segs.length === parts.length)) return { route, params };  }  return undefined;}