Skip to content

feat: add url rewrites - #125

Merged
Brooooooklyn merged 75 commits into
mainfrom
feat/rewrites
Apr 29, 2026
Merged

Brooooooklyn merged 75 commits into
mainfrom
feat/rewrites

Conversation

@TheAlexLichter

@TheAlexLichter TheAlexLichter commented Apr 14, 2026 •

Copy link
Copy Markdown
Member

Adds support for URL rewrites (serving content from a different internal path without changing the browser URL).

Static via void.json or status 200 in _redirects:

{ "routing": { "rewrites": { "/docs/*": "/en/docs/:splat" } } }

Programmatic via rewrite() for more dynamic cases like i18n or feature flags.

import { defineMiddleware, rewrite } from "void";

export default defineMiddleware(async (c, next) => {
  if (!hasLocalePrefix(c.req.path)) return rewrite(c, `/en${c.req.path}`);
  return next();
 });      

Requires https://github.com/voidzero-dev/void-platform/pull/87

Design decisions

  • Augment hono ctx to add c.rewrite instead of import { rewrite } from 'void'. Better DX, smaller surface area for users to learn, and more consistent with c.redirect.
    • Tradeoffs
      • Future Hono collision if Hono ever ships a built-in c.rewrite
      • Possible Hono Ecosystem collisions (other middleware augmenting Context with rewrite)
  • Different redirect behavior when defined via _redirects. Aligns with other platforms, e.g. Netlify.

Possible Todos for the future

  • Client nav ↔ server rewrite parity: Link adapters are not rewrite rule aware yet.
  • Production X-Void-Routing header as opt-in (dev only right now)
  • c.fallback() middleware hook: Gives symmetry with c.rewrite()
  • Destination validation at build: RewriteDestination's (string & {}) escape hatch lets typos through.
  • ISR opt-out for rewrites revalidate(path, { rewritten: true }) or similar, so /docs/foo can invalidate /en/docs/foo caches
  • Docs: Explain when to use void.json vs _redirects vs c.rewrite().
  • Side-effect-safe middleware re-run — auto-detect or annotate middleware that shouldn't re-fire on rewrite redispatch, rather than relying on users checking X-Void-Rewritten.
  • Features
    • Proxy rewrite support
    • Domain based redirects

@cpojer

cpojer commented Apr 15, 2026

Copy link
Copy Markdown
Member

Looks good based on docs!

@codex[agent] review

@chatgpt-codex-connector chatgpt-codex-connector 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.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 096b312d74

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

Comment thread packages/void/src/router/compile.ts Resolved
Comment thread packages/void/src/router/compile.ts Resolved
@Brooooooklyn

Copy link
Copy Markdown
Member

@codex review

@chatgpt-codex-connector chatgpt-codex-connector 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.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 361686ddea

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

Comment thread packages/void/src/router/compile.ts Resolved
Comment thread packages/void/src/router/compile.ts Resolved

@chatgpt-codex-connector chatgpt-codex-connector 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.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: e8c7eb6314

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

Comment thread packages/void/src/cli/headers.ts Resolved
@TheAlexLichter
TheAlexLichter marked this pull request as draft April 20, 2026 15:25
@TheAlexLichter

Copy link
Copy Markdown
Member Author

Back to draft until I added most of the new changes.

@TheAlexLichter
TheAlexLichter marked this pull request as ready for review April 20, 2026 18:25
@TheAlexLichter
TheAlexLichter marked this pull request as draft April 21, 2026 13:24
TheAlexLichter and others added 16 commits April 22, 2026 15:35
Add support for URL rewrites — serving content from a different
internal path without changing the browser URL.

Static rewrites via void.json config:

  { "routing": { "rewrites": { "/docs/*": "/en/docs/:splat" } } }

And via _redirects file with status 200:

  /docs/* /en/docs/:splat 200

Programmatic rewrites via middleware:

  import { defineMiddleware, rewrite } from "void";
  export default defineMiddleware(async (c, next) => {
    return rewrite(c, "/en" + c.req.path);
  });

Implementation:
- routing.rewrites in void.json (Record<string, string>)
- _redirects parser now accepts status 200
- Deploy pipeline merges rewrite rules into redirectRules array
- Node target: combined routing rules middleware handles both
  redirects (3xx) and rewrites (200) via app.fetch() re-dispatch
- rewrite() runtime utility with __rewrite context injection
- New docs/guide/edge/rewrites.md with use cases, examples,
  middleware rewrite() API, and X-Void-Original-URL docs
- Add routing.rewrites section to config reference
- Update redirects guide to mention _redirects 200 support
- Add Rewrites entry to docs sidebar
Pass c.executionCtx as the third argument to app.fetch() in the
__rewrite utility so that rewritten requests retain access to
waitUntil() and other execution context APIs on Cloudflare targets.
Replace the X-Void-Rewritten header check with an in-memory WeakSet to
guard against rewrite loops. The header is user-controlled on incoming
requests, so a client could set it to skip all configured redirects and
rewrites. The WeakSet tracks only internally re-dispatched requests,
making the guard unspoofable. The header is still set for observability.
Extend the pattern matcher with named captures (:name, :name*) in
addition to the existing * / :splat syntax, so rules can re-slot
multiple segments (e.g. /blog/:author/:slug -> /articles/:author/:slug).
Legacy * remains captured as :splat.

The compiled redirect middleware now also merges the request's query
string into the Location header (UTMs, auth state, pagination were
previously dropped). Destination query wins on per-key conflict.
The existing routing.rewrites fires before static/route resolution and
overrides them, which makes it unsuitable for the common "rewrite only
when nothing else matched" pattern (SPA shells, default-locale catch-all,
migration fallbacks).

routing.fallbacks is a distinct config key with the same shape as
rewrites. It's merged into the deploy manifest alongside redirectRules
so the dispatch worker can evaluate it when the static asset resolver
returns null. Scope is static/SPA deployments only in v1; worker
projects own their own 404 handling, and node-target self-hosted
builds already register their own app.notFound handlers.
Proxy-style 200 rules (e.g. `/api/* https://upstream/:splat 200`) were
being parsed into the manifest and turned into invalid local pathname
rewrites at runtime. External rewrite destinations are declined by
design (see platform design doc 0062) and already rejected for
`routing.rewrites` in `void.json`; bring `_redirects` in line by
skipping non-internal destinations with a warning.
Move the middleware rewrite utility from a free `rewrite(c, path)` import
to `c.rewrite(path)` so it mirrors Hono's built-in `c.redirect()`. Added
via module augmentation of Hono's Context; compiled routes attach the
dispatcher directly on the context instead of stashing it under a
`__rewrite` variable.

Also document `routing.fallbacks` in the config reference and guide —
it shipped on the config side but wasn't described anywhere.
- c.redirect() now merges the incoming query string into internal
  destinations via __mergeQueryIntoLocation, matching static redirect
  behavior. External URLs pass through untouched; destination query
  wins on conflict.
- c.rewrite() sets X-Void-Original-URL on the re-dispatched request,
  preserving the earliest pre-rewrite URL across multi-hop rewrites.
  This restores symmetry with static rewrites (which already carry
  the header from the platform layer).
The previous phrasing ("your middleware is responsible for its own
loop prevention") contradicted the runtime, which already tracks
the re-dispatched Request object and skips static rules on the
second pass. Lead with the automatic guard, then describe what it
doesn't catch (multi-hop cycles across middleware) and add a
performance caveat about deep chains.
_redirects status 200 entries now follow Netlify / Cloudflare Pages
conventions:

- Plain `/foo /bar 200` = asset-miss fallback (force=false), equivalent
  to routing.fallbacks in void.json. Fires only when the static asset
  resolver would have returned 404.
- `/foo /bar 200!` = always-rewrite (force=true), equivalent to
  routing.rewrites. Fires regardless of whether an asset exists.

Migrating Cloudflare Pages or Netlify users now get the same semantics
they had before. The force flag threads through RedirectRule, the
_redirects parser, and convertRewritesConfig / convertFallbacksConfig.
`301!` and similar are rejected with a clear warning — the suffix only
has meaning on 200.
For the spa app type, routing.fallbacks is now additive rather than
an override. User fallbacks are evaluated first; if none match, the
implicit /* → /index.html SPA fallback still fires.

Implemented at the manifest layer, not the worker: when a SPA deploy
has user fallbacks, not_found_handling is flipped from
'single-page-application' to 'none' and a synthetic /* → /index.html
fallback rule is appended. The dispatch worker already evaluates
fallbacks with last-match-wins, so user rules win when they match
and the synthetic rule catches everything else. SPA deploys without
routing.fallbacks keep the platform-level SPA switch — zero overhead
for the common case.

Emits a warning when user fallbacks include a literal /* → /index.html
on a SPA app, noting the rule duplicates the default.
Route codegen now emits `RouteName = keyof RouteMap` and
`RewriteDestination = RouteName | (string & {})` into the
void/routes module. The `string & {}` intersection keeps autocomplete
for known routes while still accepting dynamic strings (like
`/users/${id}`) — losing the literal branch would collapse both to
plain `string` and drop IDE completions.

Threads the type through c.rewrite's signature and the rewrites /
fallbacks value types in RoutingConfig. Runtime validation stays at
`string`; only the TS surface narrows to RewriteDestination.

On a fresh checkout (before codegen has run), RouteMap is empty so
`keyof RouteMap` is never — RewriteDestination degenerates to
`string & {}` which any string satisfies. No build-order footgun.
Adds a dev-only trace header so users can see which rule resolved a
request without reaching for curl. Format:

- redirect[/old] → /new 301 (_redirects:12)
- rewrite[/api/*] → /backend/:splat (void.json#routing.rewrites)
- fallback[/docs/*] → /docs.html (void.json#routing.fallbacks)
- c.rewrite → /new-path (middleware)
- pass-through  (no rule matched)

Rules now carry an optional `origin` tag (_redirects line number or
void.json#<field>) so the trace points back to source. Origins are
stripped from production manifests and the compiled worker gates all
trace emission on a compile-time __VOID_DEV_ROUTING boolean, which
minifies away cleanly. The header never ships in prod.
The middleware `c.rewrite()` wrapper used `new Request(url, c.req.raw)` to
clone the incoming request, which copies every header — including any
forged `X-Void-Original-URL` sent by the client. The subsequent
`!headers.has("X-Void-Original-URL")` guard, intended to preserve the
earliest origin across multi-hop rewrites, would then preserve the
client-supplied value instead of overwriting it. Handlers and middleware
that read `X-Void-Original-URL` (as the docs recommend for canonical
links, locale detection, etc.) would trust the spoofed value.

Fix at the entry point: in the middleware that installs `c.rewrite`,
strip `X-Void-Original-URL` from `c.req.raw.headers` whenever the
incoming request is not an internal re-dispatch (tracked via the
existing `__rewrittenReqs` WeakSet). Internal hops — where we set the
header ourselves on the previous pass — flow through untouched, so
multi-hop rewrites still preserve the earliest origin URL.

Defense-in-depth: snapshot the internal-redispatch bit and, inside
`c.rewrite`, explicitly `delete` the header on the cloned `rewriteReq`
when the current hop is external. This closes the gap on runtimes where
incoming request headers are immutable and the entry-point `delete`
silently fails — the cloned Request always has mutable headers, so the
spoofed value is guaranteed to be dropped before re-dispatch.

The static-rewrite path (`compileRoutingRulesMiddleware`, node-only) is
unchanged: it runs after the entry-point strip, and on CF the platform
dispatch worker owns this header entirely.
@TheAlexLichter
TheAlexLichter marked this pull request as ready for review April 22, 2026 18:42
@Brooooooklyn

Copy link
Copy Markdown
Member

@codex review

@chatgpt-codex-connector chatgpt-codex-connector 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.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 04fe394c6e

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

Comment thread packages/void/src/router/compile.ts Resolved
Comment thread packages/void/src/plugin-routing.ts Resolved
…tions

`c.rewrite('/en' + c.req.path)` was clobbering the incoming `?page=2`,
OAuth callbacks, etc. by setting `rewriteUrl.search` to an empty string
when the destination had no `?`. Guard the assignment on a truthy
search — mirrors the static-rewrite codegen below and Netlify 200
semantics (destinations can't declare `?`, incoming query carries).
When a user set Vite's `publicDir: false`, `reloadFileRules` early-
returned and left whatever rules were merged during the pre-resolve
preload from the default `<root>/public` in place. Configured
`routing.redirects`/`rewrites`/`headers`/`fallbacks` were also never
picked up. Drop the early return and let `mergeRoutingRules` handle
`dir: null` by skipping file reads while still merging config rules.
Comment thread packages/void/src/router/compile.ts Resolved
…y merge

The c.redirect wrapper merged the incoming request query into any location
starting with "/". Protocol-relative URLs ("//host/x") satisfy that check
but the browser resolves them cross-origin, so the merge leaked request
query params (incl. attacker-controlled values or victim session tokens)
off-origin. Mirrors the guard already in c.rewrite and the static-redirect
schema validation.
TheAlexLichter and others added 5 commits April 28, 2026 17:12
The fallback guard inside `notFound` short-circuited on
`__voidOriginalUrls.has(c.req.raw)`, but that WeakMap is populated by
three different sources: the dispatch-handoff header migration,
the static-rewrite middleware, and user `c.rewrite`. Treating all three
as "fallbacks already considered" was wrong for `c.rewrite` and
static-rewrite — the rewrite target was never evaluated against
fallbackRules, so a middleware `c.rewrite("/missing")` whose target
is a fallback source silently 404'd instead of resolving.

Split the cycle guard onto a separate `__voidFallbackHandled` WeakSet
that is populated only by fallback re-dispatches. `__voidOriginalUrls`
still drives `c.originalUrl()` / `c.isRewritten()` and the routing-
rules middleware loop guard. The fallback guard now reads the new
WeakSet, so static-rewrite + fallback chains and `c.rewrite` +
fallback chains both fire correctly while fallback->fallback cycles
are still blocked (single-hop semantics, parity with dispatch's
single `applyRoutingRules(fallbackRules, ...)` call).

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

@chatgpt-codex-connector chatgpt-codex-connector 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.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 4c66875b24

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

Comment thread packages/void/src/router/compile.ts Resolved
Bundle of small follow-ups from the feat/rewrites branch review.

* Multi-`*` patterns no longer crash on emit (F3): `__compilePattern`
  now tracks `legacySplatCaptured` so the second bare `*` becomes
  non-capturing `(?:.*)`, mirroring dispatch. `__matchPattern` wraps
  the regex compile in try/catch with one-time `console.warn` per
  pattern. Validators for `routing.headers` and
  `routing.revalidateQueryAllowlist` now call `assertSingleSplat`
  so misconfigurations fail loudly at config-read time.

* Validator no longer over-rejects valid patterns (F5): `countSplats`
  skips `*` that's part of a `:name*` named-multi-segment capture.
  Patterns like `/users/:id*/files/*` (one named, one anonymous —
  distinct group names, valid regex) are now accepted. Same fix
  applies to the `_redirects` parser via the shared helper.

* `c.rewrite()` strips fragment from destination (F20): the helper
  already computed `__firstDelim` for the asset-extension guard,
  but `__pathOnly` only split on `?`. Setting `URL.pathname` to a
  string containing `#` percent-encoded it into the path. Reuse
  `__firstDelim` so the fragment is dropped consistently.

* `X-Void-Original-URL` trust boundary verified behaviorally (F10):
  the previous test was a substring assertion against the generated
  source. Replaced with a behavioral test that compiles + evaluates
  the artifact for cfDev/cfProd/nodeDev/nodeProd, sends a Request
  with a spoofed header, and asserts only cfProd trusts it.

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

@chatgpt-codex-connector chatgpt-codex-connector 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.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 63867e9880

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

Comment thread packages/void/src/router/compile.ts Outdated
): void {
lines.push(`${indent}let matched;`);
lines.push(`${indent}for (const rule of ${rulesVar}) {`);
lines.push(`${indent} const { regex } = __compilePattern(rule.source);`);

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P1 Badge Guard routing-rule pattern compilation errors

The generated redirect/rewrite/fallback middleware compiles each rule.source via __compilePattern(rule.source) without any error handling, so a rule with duplicate capture names (for example /:id/:id or /*/:splat) throws SyntaxError: Duplicate capture group name at request time and aborts the whole request before handlers run. This commit already added a resilient __matchPattern path for headers, but emitApplyRoutingRules bypasses it and can still 500 traffic from a single malformed routing rule; these compile errors should be caught (or validated out) so one bad rule is skipped instead of taking down matching requests.

Useful? React with 👍 / 👎.

emitApplyRoutingRules called __compilePattern(rule.source) directly to
get the regex for capture-group extraction, bypassing the try/catch in
__matchPattern. A single rule whose source compiles to a duplicate
named-capture group (e.g. /:id/:id, /:splat/*, or /:rest*/:rest*)
threw SyntaxError synchronously, escaped the routing-rules middleware,
and 500'd every request hitting it on CF dev.

Two-part fix mirroring the dispatch worker's applyRoutingRules:

1. Runtime guard in emitApplyRoutingRules — wrap the per-rule
   compilation in try/catch + continue, sharing __matchPatternWarned
   so the warn fires once per pattern across both header and routing
   middleware paths.

2. Build-time validator assertUniqueCaptureNames — wired into
   redirects/rewrites/fallbacks. Detects duplicate :name tokens
   (with or without trailing *) and the :splat / bare * collision
   that the legacySplatCaptured flag does not cover.

assertSingleSplat continues to handle multi-anonymous-* clashes;
this validator complements it for named-group collisions.

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

@chatgpt-codex-connector chatgpt-codex-connector 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.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: fc089f88e7

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

const hasRedirectsFile = redirectDirs.some((dir) => Boolean(parseRedirectsFile(dir)));
const hasRedirectsFile = redirectDirs.some((dir) => {
const parsed = parseRedirectsFile(dir);
return parsed != null && parsed.rules.length > 0;

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P1 Badge Disable static page-data fast path when config rewrites exist

resolveStaticPageDataBuildOptions() only treats routing.redirects as a config-level fast-path blocker, so static builds that define routing.rewrites/routing.fallbacks in void.json can still ship with fastPath: true. In that mode the client loads /_void-pages/<requested-path>.json directly before hitting the server pipeline, which bypasses rewrite/fallback resolution and can render the wrong page data (or stale data) for rewritten URLs during navigation/prefetch. This commit added config rewrites/fallbacks but did not include them in the fast-path guard.

Useful? React with 👍 / 👎.

Comment thread packages/void/src/router/compile.ts Outdated
// worker, not inside it). `.html` is deliberately excluded: it's ambiguous
// with legit route handlers at `.html` paths.
lines.push(
'const __voidAssetRewriteExtRE = /\\.(png|jpg|jpeg|gif|webp|avif|svg|ico|css|js|mjs|cjs|woff|woff2|ttf|otf|eot|mp4|webm|mp3|wav|pdf|txt|xml|json|wasm|map)$/i;',

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P2 Badge Allow c.rewrite to target extension-suffixed routes

The runtime rewrite guard rejects any destination ending in extensions like .json, .xml, or .txt by throwing VoidAssetRewriteError, but Void routes can legitimately use dotted path segments (e.g. /feed.xml or /api/openapi.json). With this regex, middleware c.rewrite() cannot dispatch to those valid handlers even when they exist, creating false positives and behavior divergence from static rewrite rules.

Useful? React with 👍 / 👎.

Two follow-ups from review:

* Disable static page-data fast path when routing.rewrites or
  routing.fallbacks is configured (P1). The fast path fetches
  /_void/pages/<requested>.json directly using the original pathname,
  so the dispatch worker's edge rewrite phase never matches the user-
  facing source — clients commit unrewritten page data on <Link>
  navigation while SSR/hard-refresh still serves the rewritten target.
  Result: same URL renders different content depending on entry point.
  resolveStaticPageDataBuildOptions previously gated only on
  routing.redirects + _redirects file; now also gates on rewrites and
  fallbacks. Headers don't change body shape so they still don't gate.

* c.rewrite asset-extension blocklist now respects route patterns (P2).
  Void routes can legitimately use dotted-extension paths (feed.xml.ts
  → /feed.xml, api/openapi.json.ts → /api/openapi.json), but the runtime
  rewrite guard rejected any destination ending in .json/.xml/.txt/etc
  by throwing VoidAssetRewriteError, even when the destination is a
  real route handler. This diverged from routing.rewrites, which routes
  the same destination correctly. The fix walks scan.routes (and
  scan.pages.pages) at compile time, finds extensions used by registered
  routes, and removes those from the blocklist regex. Genuine asset
  paths (png, css, woff, etc.) still throw the helpful error.

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

@chatgpt-codex-connector chatgpt-codex-connector 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.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: abca2ef5c2

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

Comment thread packages/void/src/router/compile.ts Resolved
@Brooooooklyn
Brooooooklyn merged commit 9eb1be5 into main Apr 29, 2026
9 checks passed
@Brooooooklyn
Brooooooklyn deleted the feat/rewrites branch April 29, 2026 06:25
cpojer pushed a commit that referenced this pull request Sep 11, 2026
* feat(dispatch): handle URL rewrites at the edge

Extend the dispatch worker to support rewrite rules (status 200)
alongside existing redirect rules (3xx).

- Refactor applyRedirectRules into applyRoutingRules returning a
  discriminated union: redirect (Response) or rewrite (destination)
- Rewrites modify the request pathname and continue through the
  normal pipeline (ISR, static assets, worker dispatch)
- Set X-Void-Original-URL header on rewritten requests so the
  worker can access the original URL
- Add tests for rewrite matching, splat substitution, and
  mixed redirect/rewrite last-match-wins ordering

* docs: add rewrites design doc and update READMEs

- New design doc 0062-rewrites covering motivation, design
  decisions, static and middleware rewrites, X-Void-Original-URL
- Update dispatch README to mention rewrites
- Update root README "Where Code for X Lives" table

* test(dispatch): add rewrite integration tests

Test the full dispatch flow for rewrites:
- Rewrite forwards to worker with rewritten pathname
- Splat substitution in rewritten paths
- X-Void-Original-URL header set on rewritten requests
- Query string preserved through rewrite
- Non-matching paths pass through unchanged
- Last-match-wins when redirect and rewrite rules overlap

* feat(dispatch): named path params and query preservation on redirects

Swap the glob-only matcher for a shared compiler in headers.ts that
supports named captures (:name for one segment, :name* for zero-or-more).
Legacy * keeps working as an anonymous :splat catch-all. Destinations
are substituted via :name tokens; redirects.ts uses this for both
redirect and rewrite paths.

applyRoutingRules now returns a discriminated { destination, status }
instead of a pre-built Response, which lets the caller merge the
request's query string into the Location header. Previously we dropped
?utm, auth state, pagination etc. on 3xx responses. Destination query
wins on per-key conflict.

No change to rewrite behavior (it only mutates pathname).

* feat(dispatch,api): fallback rewrites for static deployments

Add a post-lookup rewrite phase that fires only when the static asset
resolver returns null. Source is routing.fallbacks in void.json,
surfaced through the deploy manifest as fallbackRules.

Scope is static/SPA deployments. Worker projects own their own 404
handling and are not intercepted, which avoids per-request re-dispatch
cost and keeps the worker's routing model unambiguous.

Evaluation is single-pass: one fallback match re-resolves the asset
path and serves it (or 404s if the rewritten path also misses).
Redirects in fallbackRules still short-circuit with query preservation.

* docs: rewrites v1.1 revisions and considered-and-rejected

Document the three DX additions landed on this branch (named params,
fallback rewrites, query preservation on redirects) and capture the
two generalizations that were evaluated and declined so they're not
re-litigated later: external rewrite destinations (SSRF surface, egress
accounting, open-proxy posture) and conditional matching on
cookies/headers/query (middleware already covers this, and adding it
to static rules would contaminate the edge cache key).

* fix(dispatch): guard consumed body before rewrite request clone

A disturbed stream makes the Request constructor throw, so POST/PUT
requests whose body was already read failed at the rewrite branch
before reaching the downstream bodyUsed fallback.

* fix(dispatch): forward rewritten URL through ISR worker fetches

ISR miss render and background revalidation were dispatching the
original request, so a /docs → /en/docs rewrite rendered /docs content
but cached it under the /en/docs key (and kept refreshing from /docs).
Hoist the rewritten-request builder so hashed-asset, ISR, and final
dispatch all share it.

* feat(dispatch,api): accept force field and fallbackRules from new framework manifest

Framework's feat/rewrites branch introduces `routing.fallbacks` / rewrites,
emitting richer manifest entries:

- `redirectRules` / `fallbackRules` entries may carry `force?: boolean`.
  Dispatch doesn't branch on it — the list identity (pre-asset vs post-asset
  phase) already encodes the semantic — but it must be accepted so manifests
  parse. Mirrored on `DeployManifest` in @voidcloud/api.
- Add integration coverage for the SPA + user-fallbacks shape the CLI now
  emits: synthetic `/*` → `/index.html` catch-all prepended, user rules
  appended. Last-match-wins in dispatch lets the more-specific user rule
  (e.g. `/docs/*` → `/docs.html`) win when it matches, and the synthetic
  catches everything else. Covers static-only fallbackRules, `_redirects`
  200-entries via fallbackRules, and `force: true` redirectRules.

* fix(dispatch): address PR review findings for rewrites

- Strip any client-supplied X-Void-Original-URL on ingress so dispatch
  is authoritative on CF. Previously the header was only set on the
  rewrite path and passed through verbatim otherwise, letting clients
  spoof the original URL seen by non-Void user workers.
- Preserve the pre-rewrite pathname for the fallback edge-cache key
  when routing.version is absent. Under the previous code the key was
  built from the rewritten pathname, so repeat hits to the original
  URL never found the cache entry.
- Document why the force field is carried through on redirect/fallback
  rules but not branched on — the list identity encodes the phase.

* docs: refresh rewrites design doc for v1.1 implementation

Update Files changed to include the shared pattern compiler in
packages/dispatch/src/headers.ts, the discriminated applyRoutingRules
and mergeQueryIntoLocation helper in redirects.ts, fallbackRules
propagation in packages/api/src/routing.ts, and force-field plumbing
in types.ts. Add an Interaction with header rules subsection — rules
match the post-rewrite pathname. Bump revised date.

* docs(rewrites): consolidate design doc into single coherent spec

Fold v1.1/v1.2 revision sections into the main Design section (this is
all one PR, no shipped v1.0 to revise) and document the newly added
c.rewrite / c.originalUrl / c.isRewritten context helpers alongside
CloudEnv-scoped typing.

* test(dispatch): unit tests for pattern compiler and param substitution

Add direct coverage for compilePattern, matchPatternCaptures, and
substituteParams — previously exercised only transitively via redirect
integration tests. Pins down named captures, middle-splat behavior,
legacy * handling, cache identity, and missing-param substitution.

* refactor(dispatch,api): drop force field from rewrite manifest wire shape

The `force?: boolean` was accepted on `redirectRules` and `fallbackRules`
manifest entries for forward-compat, but dispatch never branched on it —
list identity alone (pre-asset `redirectRules` vs post-asset `fallbackRules`)
determines phase. The framework is dropping `force` from the shipped
manifest in a sibling change, so drop it from the wire type here too.

Updated tests: stripped `force` from fixtures, renamed the
`redirectRules with force: true` describe block to reflect that the phase
is what's under test, and removed the now-obsolete "tolerates force" case.

* docs(rewrites): correct design doc for two-phase manifest and edge/node loop distinction

The Design intro claimed a single `redirectRules` array contains both redirects
and rewrites; in reality the manifest splits into `redirectRules` (pre-asset)
and `fallbackRules` (post-asset, static deployments only). Rewrite the intro
to describe the two-phase model accurately.

Also clarify that the `X-Void-Rewritten` header guard is a framework-runtime
concern for Node/Bun/Deno targets that re-dispatch via `app.fetch` — dispatch
at the edge is single-pass and doesn't need loop prevention. Update the
"files changed" bullets to reflect that `force` is a framework-internal flag
and not a wire field.

* fix(dispatch): skip rewrites whose destination is not path-absolute

Framework validates at build time that rewrite destinations start with `/`,
but a malformed or tampered manifest could still reach the edge. Guard both
rewrite sites (pre-asset `redirectRules` and post-asset `fallbackRules`)
with a defensive `startsWith('/')` check: log and skip the rule on violation
so the request falls through to normal resolution rather than crashing on
`url.pathname = 'https://...'` or producing a bogus URL.

Adds coverage in `fallback-rules.test.ts` for both phases.

* fix(api): harden manifest validation for rewrite wire shape

- Accept status 200 in redirectRules (framework ships force rewrites
  from routing.rewrites and _redirects 200! with status: 200).
- Validate fallbackRules symmetric to redirectRules, with status locked
  to 200 since fallbacks are rewrites only.
- Reject `?` in rewrite/fallback destinations in both rule branches —
  request query is merged separately at dispatch time via
  mergeQueryIntoLocation, so an embedded query in the destination
  silently breaks merging. Framework already rejects this at build time.

Adds five integration regression tests covering the status-200 accept
path and each new rejection.

* docs(dispatch): list fallback-rules.test.ts in README source layout

The file was added alongside the rewrites feature but wasn't
registered in the README's source-layout block or test list.

* docs(rewrites): align design doc with X-Void-Original-URL signal and CF-dev gap

c.isRewritten() in the framework now reads X-Void-Original-URL instead
of a separate X-Void-Rewritten header, which fixes the CF-prod path
where dispatch rewrites the pathname and sets the former but not the
latter. The framework loop guard is a WeakSet on the in-memory Request
object, not header-based. Update the doc to describe both accurately
and drop the (now removed) X-Void-Rewritten references.

Also note the CF-dev asymmetry: static routing rules are applied by
dispatch in prod, but dispatch doesn't run under `vite dev`, so those
rules are inert locally on the CF target. Parity holds on
node/bun/deno where the rules are compiled into the worker middleware.

* feat(isr,api,dispatch): scope cache keys to rewrite variants + review fixes

ISR variant keying

- Include the `X-Void-Original-URL` value in the ISR cache key so
  direct and rewritten requests to the same pathname cache
  independently — necessary whenever a user handler branches on
  `c.isRewritten()` or `c.originalUrl()`.
- New `encodeIsrVariantToken` / `splitIsrCacheKey` /
  `isrCacheVariantPrefix` helpers in `isr-shared`; dispatch + API
  revalidation thread the original URL through every cache call
  site.
- Path revalidation scans the `<path>#rw=` variant subspace and
  purges each variant (KV entry + reconstructed edge URL), so a
  single `revalidate({ paths: [destination] })` invalidates all
  rewrite sources under that destination.

Review findings

- API validator rejects non-path-absolute destinations on
  status-200 `redirectRules` and on every `fallbackRules` entry.
- Dispatch wraps `compilePattern` in a per-rule try/catch so a
  malformed manifest pattern (e.g. duplicate `splat`) skips with
  a warning instead of 500ing the request.
- Headers compile-cache LRU eviction uses an explicit `done`
  check instead of a non-null assertion.

Design doc `0062-rewrites.md` updated for two-phase traversal,
cross-system loop guard, and ISR variant keying. Dispatch README
source layout reflects the shared pattern compiler in `headers.ts`.

* docs(rewrites): drop stale standalone rewrite() mentions

The framework ships only c.rewrite(path); the standalone rewrite(c, path)
export referenced in this doc does not exist. Align the spec with the
shipped API.

* chore(dispatch): clarify rewrite guard intent + add log context

- Comment the path-absolute guard as defense-in-depth: the API rejects
  non-absolute destinations at manifest ingress (packages/api/src/routes/
  deploy.ts); this guard covers KV mutation / manifest-version skew.
- Include the matched request path in the malformed-rewrite console.warn
  calls so production logs are triageable. Rule source isn't in scope at
  the log site, so path= is used as the best available locator.

* fix(api): allow '?' in 3xx redirect destinations + 303 test + ISR design-doc note

- deploy.ts no longer rejects '?' in redirectRules destinations when status
  is a 3xx; mergeQueryIntoLocation handles the merge. 200 force-rewrites
  and fallbackRules still reject '?'.
- Add a 303 redirect case to dispatch redirect tests to lock the contract
  end-to-end now that framework + platform both accept 303.
- Clarify in the rewrites design doc that middleware c.rewrite() reuses the
  dispatch-assigned ISR slot; only dispatch-phase rewrites contribute to
  variant cache keys.

* docs(rewrites): isr-shared README, design doc refinements, dispatch/api README updates

- packages/isr-shared/README.md (new): documents the byte-identical
  contract between api (purge) and dispatch (read/write), enumerates
  every export, explains key format (#rw= variant suffix, base64url
  token), and spells out the rule that any key/URL shape lives here
  (not duplicated) and format changes require an
  ISR_CACHE_KEY_VERSION bump.
- packages/dispatch/README: split Request Flow into explicit pre-asset
  redirectRules (step 4) and post-asset fallbackRules (step 7).
- packages/api/README: point Deploy Flow at manifest wire-shape
  validation (deploy.ts:468-532).
- meta/design-docs/0062-rewrites: enumerate status allowlists
  (redirectRules [200,301,302,303,307,308], fallbackRules [200]);
  correct the middleware X-Void-Original-URL passage (middleware does
  set the header; ISR cache isolation is a timing concern, not
  header-participation); add CF-dev gap note — no dispatch locally, so
  c.originalUrl() returns null for dispatch-side rewrites, while
  middleware c.rewrite() still sets the header.

* test(dispatch): X-Void-Original-URL surface, body-consumed rewrite, fallback+ISR pin

- redirectRules rewrite forwards full pre-rewrite URL (including query)
  in X-Void-Original-URL on workerRequest.
- body-consumed POST rewrite path: asserts the forwarded request has no
  body, content-length/transfer-encoding stripped, X-Void-Original-URL
  still set, no throw.
- fallbackRules rewrite (static deployments): pins the current reality
  that no worker dispatch happens (asset serve only), so there is no
  workerRequest to inspect and ISR is not invoked. Includes an
  isrCacheKey pure-function contract test so the #rw= variant shape
  stays locked in, with a TODO for the day fallback+ISR actually share
  a code path.

* docs(rewrites): ISR variant keying, isr-shared consumers, body-rebuild rationale, 200! example

Credits X-Void-Original-URL as the variant-token source in dispatch README
and links to isr-shared. Marks isr-shared as an internal platform package
with dispatch and api as the only intended consumers. Explains why
content-length is dropped on the body-consumed rebuild paths. Expands the
_redirects example in the design doc to show 200! vs plain 200 so the
two-phase encoding is concrete.

* fix(rewrites): reject // destinations + pin framework wire shape + bump framework

- api/deploy.ts + dispatch/index.ts: reject protocol-relative
  destinations (`//host/x`) in redirectRules (status 200) and
  fallbackRules. startsWith("/") alone let them through even though
  they parse as cross-origin URLs, defeating the defense-in-depth
  story dispatch already claims against a malformed manifest. 3xx
  redirects still accept external URLs.
- dispatch/test/framework-contract.test.ts: compile-time pin on the
  framework wire shape `{source, destination, status}` — re-adding
  a `force` field (or otherwise drifting) breaks typecheck on the
  platform side.
- meta/design-docs/0062-rewrites.md: new "Framework pin" section
  naming the pinned SHA and the cli/types.ts contract boundary.
- isr-shared/README.md: expand the v2 bullet so a future maintainer
  doesn't drop the prefix as dead weight — it's what lets pre- and
  post-rewrite entries coexist during rollout.
- framework submodule: 1586e50 → 8ba805a (picks up the stale-warning
  drop, c.rewrite `//` guard, same-source ordering pin, and the
  vestigial-test cleanup).

* refactor(dispatch): drop rewrite-destination re-validation

The framework rejects non-path-absolute / protocol-relative / query-in-
destination rewrites at build time (`packages/void/src/config.ts`), and
the API re-checks them on manifest ingest before writing to KV. Dispatch
used to re-check a third time and `console.warn + fallthrough` on
failure, which is a worse failure mode than surfacing the bad manifest
loudly (silent drop on a corrupted KV entry → weird 404s no one can
trace). Trust the two ingress gates; drop the edge-level guard and the
four defensive tests that pinned it.

* docs(rewrites): flag static-fallback worker-skip and lead with isr-shared rationale

- dispatch/README.md: note that on static deployments a matched
  `fallbackRules` entry serves the resolved asset directly without
  worker dispatch — so `X-Void-Original-URL` is not set, `c.originalUrl`
  is unavailable, and the response is not ISR-cached. This gap is
  already pinned by `test/unit/fallback-rules.test.ts`; surface it in
  the README so readers see it up front.
- isr-shared/README.md: lead the Purpose section with *why* the
  variant-key suffix exists — user code that branches on
  `c.isRewritten()` / `c.originalUrl()` needs cache splits per
  pre-rewrite URL. The original "producer/consumer drift prevention"
  paragraph follows unchanged.

* style: conform rewrite code to Array<T> generics

Matches main's `chore: Change array notation to generics` rule which
landed on platform after feat/rewrites forked. Auto-fixed by oxlint;
affects dispatch + api test helpers and one internal type in dispatch.

* refactor(rewrites): platform review cleanups + bump framework

- dispatch/src/index.ts: extract rebuildRequest(request, url, mutateHeaders)
  for the three near-identical header/body rebuilds (ingress X-Void-Original-URL
  strip, rewrite URL swap, post-ISR re-dispatch). Drop the unreachable
  fallback.type === 'redirect' branch (fallbackRules are API-validated
  status-200-only) with a one-line unreachability comment.
- api/src/types.ts: introduce named RedirectRule and HeaderRule interfaces
  replacing the two inline object types on DeployManifest; export
  MANIFEST_REDIRECT_RULE_STATUSES as a shared const consumed by the ingest
  validator.
- api/src/routes/deploy.ts: use the shared status const in place of the
  inline allowed-status literal.
- isr-shared: trim public surface from 11 to 6 helpers. normalizeIsrPath,
  canonicalIsrPathname, encodeIsrVariantToken, decodeIsrVariantToken,
  isrCacheVersionPrefix, and ISR_CACHE_KEY_VERSION are package-internal now;
  README updated.
- dispatch/test/unit/framework-contract.test.ts: import RedirectRule from
  the framework submodule source (via relative path) and from api, with
  structural round-trip + keyof pins on each side. The test is now
  load-bearing against framework-side and api-side drift.
- dispatch/test/unit/fallback-rules.test.ts: drop the 80-line ISR-propagation
  "negative contract" describe (test-as-doc for an acknowledged gap; the
  pure-function half duplicated isr.test.ts).
- dispatch/test/unit/index.test.ts: merge duplicate body-consumed rewrite
  tests; add a new rewrite test that exercises the custom-domain KV key
  path (domain:<hostname>) by building ROUTING by hand so the slug-vs-domain
  branch in dispatch is actually covered.
- meta/design-docs/0062-rewrites.md: reconcile with shipped code. WeakMap
  (not WeakSet), CF-dev parity inverted (rules fire locally), client-header
  stripping at dispatch ingress, framework-side CF-prod-only header read,
  rollback-unsafety for status-200 rules, v2 ISR key-prefix rationale.
  Rename Framework pin -> Framework wire contract; drop the stale SHA pin.
- Bump framework submodule to 540d214 (matching framework-side rewrite
  cleanups).

* fix(dispatch): type workerFetch param so mock.calls indexing typechecks

CI caught that the custom-domain rewrite test's workerFetch was inferred
with no-arg signature, making tuple-index access through mock.calls fail
tsgo's narrowing. Declaring the param as Request gives the mock the
typed call-tuple the extraction needs.

* refactor: better rror msg

* rename and refactor

* test(deploy): align manifest-shape assertions with source-annotated messages

* refactor(dispatch): rename redirects.ts to routing-rules.ts

The module's exported function is `applyRoutingRules` — the file name
should match. Updates imports, the framework-contract test reference,
the API-side doc comment, the rewrites design doc, and the README.

* refactor(dispatch): extract path-pattern helpers into pattern.ts

`headers.ts` was housing the pattern compiler and captures/substitute
helpers that routing-rules and ISR path matching both reuse. Pulls
`compilePattern`, `matchPattern`, `matchPatternCaptures`,
`substituteParams`, and `CompiledPattern` into a dedicated
`pattern.ts`, leaving `headers.ts` focused on header-rule application.

Splits the tests along the same seam and updates the README source map.

* refactor(api): use Set for MANIFEST_REDIRECT_RULE_STATUSES

Membership-test constant is naturally a Set. Drops the
`ReadonlyArray<number>` cast at the call site in favor of `.has()`, and
documents why the source string is passed through `JSON.stringify`
(safe quoting/escaping of user-supplied content in the error message).

* refactor(api): drop isr-cache re-exports of shared pure helpers

`isr-cache.ts` was re-exporting pure key/URL helpers from
`@voidcloud/isr-shared` as a transitional convenience. Callers now
import those directly, leaving `isr-cache.ts` focused on the API-only
pieces that touch `KVNamespace`.

* fix(dispatch): don't 500 header rules on malformed patterns

matchPattern / matchPatternCaptures now return false / null when the
pattern fails to compile (e.g. duplicate `splat` capture from multiple
legacy `*`). applyRoutingRules already caught and skipped these, but
applyHeaderRules called matchPattern unguarded, so a hand-crafted
manifest reaching the edge could turn normal traffic into 500s.

* fix(dispatch): preserve fragment when merging query into redirect location

mergeQueryIntoLocation now splits off `#fragment` before merging and
re-appends it afterwards. Previously `/new#faq` + `?utm=x` produced
`/new#faq?utm=x`, which browsers treat as fragment text — the query
was effectively lost. Correct form is `/new?utm=x#faq`.

* fix(isr): hash variant token instead of base64-encoding the URL

KV is operator-readable and the prior `btoa(originalUrl)` token let any
operator with list access recover the original URLs — including
sensitive query strings like `?token=…`/`?email=…`. Switch to a
fixed-length FNV-1a 64-bit hex hash so the token is opaque and
length-bounded regardless of input.

splitIsrCacheKey now returns `{ normalizedPath, variantToken }`; the
purger uses `isrEdgeCacheUrlForToken` to rebuild the matching edge
cache URL since the original URL is no longer recoverable.

* fix(api): cap routing rule lists at deploy-ingest validation

Each rule compiles a regex per request in dispatch, so a manifest with
100k entries exhausts CPU on every project request. Cap redirectRules
and fallbackRules at 2000 entries (per list, well above what real
frameworks emit) and reject oversized lists at deploy ingest so dispatch
never sees them.

* fix(isr): cap rewrite-variant entries per (project, deployment, pathname)

Even with the queryAllowlist defaulting to drop every param, a path with
an allowlisted param can still be probed by varying the param value.
The cap is the second line of defense: once the KV slot for a pathname
holds 200 variants, new variants stop being written. The worker still
renders fresh content; we simply refuse to persist it, so KV growth and
revalidation cost stay bounded. Existing variants continue to update so
ISR refresh keeps working.

* fix(dispatch): preserve request.cf when rebuilding the worker request

Plain `new Request(url, { method, headers, body })` drops `cf` (country,
colo, botManagement, tlsClientAuth, …) on the floor. User workers that
read `request.cf` for geolocation, bot scoring, or mTLS info silently
saw an empty object whenever dispatch rebuilt the request (X-Void-Original-URL
strip, post-rewrite re-dispatch, post-ISR fallback). Thread `cf` through
init.cf explicitly. See remix-run/remix#3640 for the same pattern.

* fix(dispatch): key hashed-asset cache on the post-rewrite URL

Hashed assets are cached `immutable` for a year. The cache key must
track the post-rewrite (hash-bearing) URL, not the request URL — a
redirect rule that maps `/logo` to `/assets/logo-<hash>.png` would
otherwise cache content under `/logo`, and a future deploy pointing
`/logo` at a different hash would keep serving the stale entry under
its 1-year immutable Cache-Control.

* fix(isr): default-strip query from rewrite-variant cache key

The variant key on a rewrite was derived from the full original request
URL (with query). Varying any param (`?utm`, `?cb`, `?fbclid`, …) fanned
out cache slots and forced repeated SSR — Brook's DoS scenario in the
PR thread.

Default-strip every query param from the variant URL. Per-pathname
allowlist (manifest field `revalidateQueryAllowlist`, persisted to the
ROUTING entry as `queryAllowlist`) opts specific params back in for
paths where query genuinely affects rendered output (search pages,
paginated lists, etc).

Also splits the rewrite-time `originalUrl` into two values: the
ISR variant key (normalized, security-relevant) and the
X-Void-Original-URL header (full request URL — what user code expects
to see via `c.originalUrl()`).

* fix(dispatch): apply routing.fallbackRules in WfP/framework branch

For static deployments, fallbackRules fire post-asset-miss (line ~533).
For WfP/framework projects (SvelteKit/Nuxt/Astro), the user worker is
the path resolver — its 404 is the analogue of a static-asset miss.
Without this branch, framework users author `routing.fallbacks` (e.g.
SPA shell `/*` → `/index.html`), see it work in vite dev, and watch
it silently 404 in production.

Single-pass: the rewrite target's response is returned as-is, no
further fallbacks even if it also 404s.

* fix(dispatch): apply fallback rules on ISR misses

* fix dispatch fallback ISR cache writes

* fix dispatch legacy multi-splat patterns

* fix: handle fallback rewrite cache variants

* fix: gate void fallback dispatch

* fix(rewrites): address routing review follow-ups

* fix(rewrites): post-review hardening (bump framework)

* Preserve request.cf during ISR background revalidation (F7).
  revalidateInBackground was building the re-render request via
  `new Request(url, { method, headers })`, dropping the edge-populated
  `cf` bag (country, colo, botManagement, tlsClientAuth). The user
  worker re-rendered with `cf === undefined` and wrote wrong-geo or
  wrong-bot HTML into the ISR cache for the next TTL window. Replaced
  with the existing `rebuildRequest` helper which threads `cf` through
  every branch, mirroring all other re-dispatch paths in dispatch.

* Flush ISR purge per cursor page in `body.all` revalidation (F11).
  runRevalidate previously accumulated all pathnames + variant tuples
  across every deployment id and every KV list page, then expanded into
  a flat URL array sized
  `|hostnames| × |ids| × (2·|paths| + 2·|variants|)`. For high-cardinality
  projects (~20k paths × ~50 variants) this exceeded the 128 MB Worker
  cap and OOM'd mid-purge, leaving KV partially deleted. Now flushes
  `purgeEdgeCache` per cursor page; CF tolerates duplicate purge URLs
  so cross-page dedup loss is fine. Aggregate `purged` count preserved
  via a project-wide pathname set (bounded ~MBs even at high cardinality).

* Keep literal `:` semantics for non-rewrite pattern matchers (F8).
  The new shared `compilePattern` in `dispatch/src/pattern.ts` treats
  `:name` as a single-segment named capture. That's intentional for
  redirect/rewrite/fallback rules per design-doc 0064, but three other
  consumers — `routing.headers`, `routing.revalidate`, and
  `routing.revalidateQueryAllowlist` — silently inherited the new
  semantics through the shared `matchPattern`. Existing tenant configs
  using `:` as a literal URL character (e.g. `/api/v1:health`,
  `:batchGet`-style) would silently begin matching unrelated paths.
  Added `matchLiteralPattern` (escape regex specials, expand `*` only,
  defensive try/catch) and switched the three non-rewrite consumers to
  it. The capture-aware compiler stays for routing rules. Renamed the
  inline matcher in `api/src/routes/deploy.ts` to match and added a
  sync-comment cross-referencing the dispatch version.

Bump framework submodule to 63867e9 — pattern hardening + validator
fixes, c.rewrite fragment strip, behavioral X-Void-Original-URL test.

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

* chore: bump framework — guard routing-rule compile errors

Picks up fc089f8: emitApplyRoutingRules now wraps per-rule pattern
compilation in try/catch so a single malformed routing rule (duplicate
named-capture groups) cannot 500 every CF dev request hitting the
middleware. Build-time validator assertUniqueCaptureNames catches the
misconfiguration at config-read for redirects/rewrites/fallbacks.

Mirrors dispatch's existing applyRoutingRules behavior — CF prod was
already safe because dispatch had this try/catch from the start.

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

* fix(dispatch): preserve request body across worker fallback re-dispatch

When a worker-backed fallbackRule fires on a non-GET request, the inner
re-dispatch lost the body silently. The first `worker.fetch(dispatchReq)`
consumed the body stream; `applyWorkerFallbackRules` then called
`rebuildRequest(dispatchReq, ...)`, which takes the `bodyUsed` branch and
returns a new Request with method/headers but no body and the framing
headers stripped. Any user fallback covering a POST/PUT endpoint
(e.g. `/api/*: /api/handler` BFF pattern) saw an empty payload at the
fallback handler — the request looked syntactically valid, just empty.

Clone `dispatchReq` before the first worker.fetch when both:
  - method has a body (not GET/HEAD), and
  - routing.fallbackRules has at least one entry.
Pass the clone to applyWorkerFallbackRules so the inner re-dispatch can
re-stream the body. `Request.clone()` tees the underlying stream on CF
Workers — the standard mechanism for replay. Skipped on the common case
(GET, or no fallback rules) so zero overhead.

Regression test: POST + JSON body, fallbackRule covering the URL,
asserts the handler receives the original body verbatim. Test fails
without the fix (handler returns 'not found').

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

* chore: bump framework — fast path & c.rewrite blocklist follow-ups

Picks up abca2ef:

* resolveStaticPageDataBuildOptions now disables the page-data fast
  path when routing.rewrites or routing.fallbacks is set, not just
  routing.redirects. Without this, static-output projects with
  in-config rewrites silently render unrewritten page data on
  client-side <Link> navigation.

* c.rewrite asset-extension blocklist filters to extensions NOT used
  by registered routes/pages, so c.rewrite('/feed.xml') to a real
  feed.xml.ts handler stops falsely throwing VoidAssetRewriteError.
  Genuine asset paths (.png, .css, etc.) still produce the helpful
  error when no route shadows that extension.

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

* chore: bump framework to main — feat/rewrites merged

PR #125 (feat: add url rewrites) landed on framework main as squash
9eb1be5, replacing the per-fix snapshot pointer with the merged
single-commit head. All routing-rules / rewrites / fallbacks /
c.rewrite / static-page-data / pattern-compiler work from this
branch is now part of the framework's main history.

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

---------

Co-authored-by: LongYinan <lynweklm@gmail.com>
Co-authored-by: Claude Opus 4.7 <noreply@anthropic.com>
cpojer pushed a commit that referenced this pull request Sep 11, 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.

4 participants