ReviewOS

stacks/stx

Dev server: catch-all [...all] shadows ALL specific dynamic routes (glob-order dependent) — every detail route 404s

#1837
Closed glennmichael123 opened this 22 days ago · 0 comments
22 days ago

Summary

The dev server's dynamic-route matcher (getRoute, "Strategy 6") iterates discovered files in discoverFiles order (Bun glob order) and returns the first regex match. There's no specificity ordering, so the catch-all [...all].stx — whose regex is ^(.+)$ and which Bun's glob frequently returns first — matches before any specific dynamic route. Net effect: every /segment/:id detail route 404s whenever a catch-all view exists (which is the normal way to define a 404 page).

Repro

Project with:

resources/views/[...all].stx        (the 404 catch-all)
resources/views/foo/[id].stx

Request /foo/15 → serves [...all].stx (404), not foo/[id].stx.

Proof (Bun glob order + the matcher's first-match)

const all = [...new Bun.Glob('**/*.stx').scanSync({ cwd: 'resources/views' })].filter(f => f.includes('['))
// all[0] === '[...all].stx'   ← catch-all first

// buildDynamicRouteRegexes('[...all]') → /^(.+)$/  matches 'foo/15'
// the loop returns the FIRST match → [...all].stx  → 404

Observed live: /article/15, /review/15, /judges/15, /court-houses/15, /user/15, /blog/15 all resolved to the catch-all and rendered the 404 page.

Why it's nasty

The bug is glob-order dependent, so it appears/disappears across filesystems, Bun versions, and directory layouts — a heisenbug. A project can work for months, then a single new view or a version bump reorders the glob and every detail route silently 404s.

Fix

Order dynamic candidates most-specific-first before the first-match loop: catch-all ([...x]) always last, static segments outrank dynamic [param] segments. Sketch:

const routeSpecificity = (fp) => {
  let score = 0
  for (const s of fp.replace(/\.(stx|md|html)$/, '').split('/')) {
    if (/\[\.\.\./.test(s)) score -= 10000      // catch-all: always last
    else if (s.includes('[')) score += 1        // dynamic param
    else score += 100                            // static segment
  }
  return score
}
const dynamicFiles = files.filter(f => f.includes('[')).sort((a, b) => routeSpecificity(b) - routeSpecificity(a))
for (const filePath of dynamicFiles) { /* first regex match wins */ }

Since it only reorders candidates (first match still wins), it's strictly more correct — a more-specific route can no longer be shadowed by a broader one.

Location

packages/bun-plugin/src/serve.ts — getRoute "Strategy 6" dynamic loop (for (const filePath of files)), fed by discoverFiles (returns unsorted glob order).

Sign in to comment on this issue.