Skip to content

feat(routes): type page navigation query from the loader schema - #898

Open
0froq wants to merge 5 commits into
voidzero-dev:mainfrom
0froq:typed-page-query
Open

0froq wants to merge 5 commits into
voidzero-dev:mainfrom
0froq:typed-page-query

Conversation

@0froq

@0froq 0froq commented Nov 22, 2026

Copy link
Copy Markdown
Collaborator

This description was drafted by an agent from the diff and the commands it ran. froQ has reviewed it.

Related to #883

Description

A page loader that validates its query with defineHandler.withValidator({ query }) now types navigation. routeUrl() and router.visit() reject a key outside that schema, a value outside it, and a missing required key. The page reads the same schema's output through a new useQuery() hook.

PageQueryMap keeps the input and output sides apart, because what a link may pass and what the page reads stop being the same type once defaults or coercions are involved.

The query option types sit outside route-url.ts for a reason. A page server reaches that file through void, so reading a loader's inferred type from it makes the loader refer to itself, and TypeScript falls back to any for the whole handler.

Pages without a query schema behave as before. Any RouteQuery still compiles, and useQuery() returns the raw request values. A .dev / .prod pair unions its two schemas, the way page action bodies already merge.

Links that pass a key the page does not declare now fail type checking. as RouteQuery opts out.

Still open

The issue also asks to "Support a functional update against the previous query so changing a filter can preserve the other filters and reset pagination". With useQuery() that edit is { ...query, status: 'paid', page: 1 }. A callback form needs a decision on what "previous" means when the destination is a different page, which is easier to settle on its own.

Test

New cases cover the type checks in both directions, the required key error, the no-schema fallback, and the page payload carrying validated values.

Generated route types, type-checked with tsrs in a temporary project. The first call is accepted, the next three are the errors:

routeUrl('/admin/payments', { query: { status: 'paid' } });
routeUrl('/admin/payments', { query: { statsu: 'paid' } });
routeUrl('/admin/payments', { query: { status: 'impossible' } });
routeUrl('/admin/payments');
check.ts(3,31): error TS2322: Type '{ statsu: string; }' is not assignable to type 'RouteQuery & { status: "paid" | "pending"; page?: number | undefined; }'.
  Property 'status' is missing in type '{ statsu: string; }' but required in type '{ status: "paid" | "pending"; page?: number | undefined; }'.
check.ts(4,40): error TS2322: Type '"impossible"' is not assignable to type '"paid" | "pending"'.
check.ts(5,1): error TS2554: Expected 2 arguments, but got 1.

One runtime case: a loader that coerces page to a number serves /users?page=2&q=ada, and the page payload carries { page: 2, q: 'ada' }. Without a query schema the payload carries { tag: ['a', 'b'], q: 'ada' } for ?tag=a&tag=b&q=ada.

useQuery() adds no test of its own. It returns the router's page query, and the pages-client case asserts that value.

A page whose loader validates `query` with `defineHandler.withValidator({ query })`
now types both directions. `routeUrl()` and `router.visit()` check the keys, the
values, and required keys against that schema, and the page reads the parsed
values with `useQuery()`, so defaults and coercions match what the loader saw.

`PageQueryMap` keeps the schema's input and output apart: what a link may pass
differs from what the page reads. The query option types stay outside
route-url.ts on purpose. A page server reaches that module through `void`, so
reading a loader's inferred type back into it makes every loader reference itself
and infer as `any`.
@0froq

0froq commented Nov 22, 2026

Copy link
Copy Markdown
Collaborator Author

👁️‍🗨️ Review this pull request with grouped, summarized diffs at:
👉 https://pulls.review/gh/voidzero-dev/void/898?from=0froq

raw result

💭 analyzed by openai-compatible/opencode-go/deepseek-v4.1-flash
🕰️ 2026-11-22 03:44 UTC
🔗 head 74fd40c
🤖 automated by pulls.review

{
  "headSha": "74fd40c0442ae51a2844033c3035c9680da65379",
  "result": {
    "overallSummary": "Pages whose loader validates its query with `defineHandler.withValidator({ query })` now type navigation: `routeUrl()` and `router.visit()` reject unknown keys, wrong values and a missing required key, and a new `useQuery()` hook exposes the loader's validated (coerced/defaulted) query to the page.\n\nThe change is split into a type-generation half (`PageQueryMap`, kept in a separate module to avoid a loader/`route-url.ts` type cycle), a runtime half (the validated query is carried on the page payload so pages can read it), and per-framework `useQuery()` plumbing. Pages without a query schema keep accepting any `RouteQuery`.",
    "groups": [
      {
        "key": "typed-navigation",
        "label": "Typed query for links and navigation",
        "summary": "Adds `PageQueryMap` (input/output per page, generated from each loader's validators) plus `PageQueryInput`/`PageQuery`, and threads it into `routeUrl()` options and the router's destination type. `RouteUrlArgs` becomes conditional so a page with a required query key forces the options argument, and `routeUrl`/`visit` now read the destination page's schema.",
        "category": "core",
        "filePaths": [
          "packages/void/src/codegen/route-types.ts",
          "packages/void/src/routes-stub.ts",
          "packages/void/src/runtime/routing/route-navigation.ts",
          "packages/void/src/runtime/routing/route-url.ts"
        ],
        "fileNotes": [
          {
            "path": "packages/void/src/runtime/routing/route-navigation.ts",
            "text": "`RouteQueryOptions` here re-implements the same conditional the generator emits into `.void/routes.d.ts` for `routeUrl()`. Two copies now have to stay in sync; only the placement (client-only module, to keep loaders out of a type cycle) justifies the duplication."
          }
        ],
        "lineNotes": [
          {
            "path": "packages/void/src/codegen/route-types.ts",
            "side": "additions",
            "line": 262,
            "text": "`RouteUrlArgs` is now pushed twice into the same generated module: the schema-aware version near the top (`RouteOptions & RouteQueryOptions`) and this plain `RouteOptions` one. Duplicate type-alias declarations are a compile error, which `skipLibCheck: true` in the typecheck test can hide — check which declaration the generated file actually ends up using.",
            "critical": true
          }
        ]
      },
      {
        "key": "page-payload-query",
        "label": "Validated query on the page payload",
        "summary": "Adds `query` to `PageObject`: the loader reads back `__voidValidatedInput` (stashed by `withValidator`) so the page payload carries the schema's output, falling back to raw request query values. The client router keeps that query as route state and exposes it through `_pageQuery`, including on SSR proxies and page-level facades.",
        "category": "api",
        "filePaths": [
          "packages/void/src/pages/protocol.ts",
          "packages/void/src/runtime/handler/index.ts",
          "packages/void/src/pages/client.ts"
        ],
        "fileNotes": [
          {
            "path": "packages/void/src/pages/protocol.ts",
            "text": "`query` is a required field on `PageObject`, so any renderer outside this repo (custom adapters, the platform server updated here) must supply it; a payload that omits it degrades to `{}` at runtime via `?? {}` rather than failing loudly.",
            "critical": true
          },
          {
            "path": "packages/void/src/pages/client.ts",
            "text": "`_pageQuery` follows the rendered page, not the address bar: it is set from `pageData.query` on commit and restored from the committed page when a commit fails, matching how params already behave."
          }
        ],
        "lineNotes": [
          {
            "path": "packages/void/src/pages/protocol.ts",
            "side": "additions",
            "line": 349,
            "text": "A schema whose output is not a plain object (array, Date, transformed scalar) silently falls through to the raw request values, so `useQuery()`'s declared type and its runtime value can disagree in that case."
          },
          {
            "path": "packages/void/src/runtime/handler/index.ts",
            "side": "additions",
            "line": 360,
            "text": "`__voidValidatedInput` is stored for every validated handler, not just page loaders, so it also becomes readable from later middleware/handlers on the same request."
          }
        ]
      },
      {
        "key": "use-query-hooks",
        "label": "useQuery() across frameworks",
        "summary": "One identical `useQuery()` hook per framework, reading the router's `_pageQuery`, plus the wiring each integration needs: `createSsrRouter()` takes the page query, and the reactive routers keep a per-page query store updated on commit so the hook re-renders. The platform admin server now supplies the payload's new `query` field.",
        "category": "ui",
        "filePaths": [
          "packages/react/src/runtime/use-query.ts",
          "packages/react/src/runtime/index.ts",
          "packages/react/src/runtime/pages-client.ts",
          "packages/vue/src/runtime/use-query.ts",
          "packages/vue/src/runtime/index.ts",
          "packages/vue/src/plugin-pages.ts",
          "packages/svelte/src/runtime/use-query.ts",
          "packages/svelte/src/runtime/index.ts",
          "packages/svelte/src/plugin-pages.ts",
          "packages/solid/src/runtime/use-query.ts",
          "packages/solid/src/runtime/index.ts",
          "packages/solid/src/plugin-pages.ts",
          "platform/packages/api/src/admin/react/server.ts"
        ],
        "fileNotes": [
          {
            "path": "packages/react/src/runtime/pages-client.ts",
            "text": "The page-level facade overrides `_pageQuery` with this resource's `pageData.query`, so `useQuery()` reads the page being rendered rather than the committed one; `routeQuery` is in the memo deps, which is what makes the value refresh."
          }
        ],
        "lineNotes": [
          {
            "path": "platform/packages/api/src/admin/react/server.ts",
            "side": "additions",
            "line": 25,
            "text": "Built from `URLSearchParams` directly, so repeated keys collapse to the last value — different from `requestQuery()`'s array fallback for the same URL shape."
          }
        ]
      },
      {
        "key": "void-tests",
        "label": "Type and runtime tests",
        "summary": "Covers the new types in both directions (accepted links, unknown key, wrong value, missing required key, no-schema fallback), the generated `PageQueryMap` including the `.dev`/`.prod` union, and the runtime path from a coercing loader to the page payload.",
        "category": "tests",
        "filePaths": [
          "packages/void/test/integration/page-query-types-typecheck.test.ts",
          "packages/void/test/unit/page-query-types.typecheck.ts",
          "packages/void/test/unit/route-types.test.ts",
          "packages/void/test/unit/pages-protocol.test.ts",
          "packages/void/test/unit/pages-client.test.ts",
          "packages/void/test/unit/action-result.test.ts"
        ],
        "fileNotes": [
          {
            "path": "packages/void/test/integration/page-query-types-typecheck.test.ts",
            "text": "Runs `tsrs` over generated types in a temp project with `skipLibCheck: true`, so it proves inference from the loader but would not catch duplicate or conflicting declarations inside the generated `.d.ts` itself."
          }
        ]
      },
      {
        "key": "adapter-test-fixtures",
        "label": "Adapter test fixtures",
        "summary": "Mechanical updates to existing tests for the widened `VoidRouter` (`_pageQuery` stub) and the required `PageObject.query` field. No behaviour change.",
        "category": "tests",
        "filePaths": [
          "packages/react/test/unit/link-prefetch.test.ts",
          "packages/react/test/unit/use-form.test.ts",
          "packages/react/test/unit/pages-server.test.ts",
          "platform/packages/api/test/unit/admin-navigation-fallback.test.ts"
        ],
        "fileNotes": [
          {
            "path": "packages/react/test/unit/pages-server.test.ts",
            "text": "Each `pageObj` fixture gains `query: {}` because the payload field is required; the assertions are unchanged."
          }
        ]
      },
      {
        "key": "docs",
        "label": "Docs",
        "summary": "Documents the page query flow: the schema on the loader, what `routeUrl()`/`visit()` now reject, `useQuery()` with its fallback for pages without a schema, and the new `PageQueryMap`/`PageQueryInput`/`PageQuery` types — including the note that HTTP-handler routes are not checked.",
        "category": "docs",
        "filePaths": [
          "docs/guide/type-safety.md",
          "docs/reference/api/pages.md",
          "docs/reference/api/types.md"
        ]
      }
    ],
    "schemaVersion": 1,
    "source": "llm",
    "generatedAt": "2026-11-22T03:44:58.489Z",
    "model": "openai-compatible/opencode-go/deepseek-v4.1-flash",
    "locale": "en"
  }
}

@0froq 0froq closed this Nov 22, 2026
@0froq
0froq deleted the typed-page-query branch November 22, 2026 03:52
@0froq
0froq restored the typed-page-query branch November 22, 2026 03:55
@0froq 0froq reopened this Nov 22, 2026

@yangshun yangshun left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

I had Claude do a pass on the PR.

Comment thread packages/void/src/pages/client.ts Resolved
Comment thread docs/reference/api/types.md Resolved
The generated map pointed at each page's `loader`, so a loader that built a
link to its own page referenced itself: TS7022 for the loader, and under
`noImplicitAny: false` the loader, its props and its map entry silently became
`any`. The generator now reads the page's exported `query` value instead. A
schema has no dependency on the handler, so the loop is gone.

`RouteOptions` carries the schema again, which keeps `routeUrl()`,
`router.visit()` and `c.redirect()` in agreement. Its `query` no longer
intersects `RouteQuery`, whose index signature had been turning excess-property
checks off for schemas where every key is optional. An input that a query string
cannot carry, such as `Date`, is typed as its string form. A `.dev` + `.prod`
pair keeps the untyped fallback for the side that exports no schema, instead of
narrowing the shared key to the other side's schema.
React SSR never passed the page's query to its router, so `usePageQuery()`
returned `{}` on the server and disagreed with the client after hydration.

Svelte built its context router without the query argument and returned a plain
object, so a template never re-read it and a page kept mounted across two URLs
kept the first one's values. Solid passed a signal read, which freezes at setup.
Both now keep a mutable query next to `params` and return it, so reading a key
in a template or JSX subscribes to it.

`useQuery` becomes `usePageQuery`, since `useQuery` already means a data-fetching
hook in TanStack Query, Apollo and urql.
Every `withValidator` call wrote the same context slot, so a mutation re-render
could hand the page the action's validated query when the page loader did not
validate one itself. The slot is cleared before the page loader runs, so only
that loader's own result reaches the page.

A mutation re-render also dropped the action key from the page URL but kept it
in the page query, so `{ ...query, page: 3 }` navigated to `?delete=&page=3`.
The fallback is built from the same action-key-free search the URL uses.

The platform admin page object grouped repeated query keys by keeping the last
one. It now keeps them as an array, like every other page.
Every page payload carried the query its loader validated. A schema can
transform a value into something the loader never returned, such as a looked-up
row or a class instance, so the browser started receiving data the loader did
not choose to send, and devalue threw on values it cannot serialize.

Publishing is now opt-in. A page sets `export const exposeQuery = true` and gets
its validated values on the client. Every other page sends the request's raw
query strings, which are already in the URL. A page that opts in and returns a
value that cannot be serialized fails in dev with that reason instead of a 500
from page serialization.

A prerendered page has no request behind its static data, so it carries no query
and the browser reads the address bar instead.

This branch has not been deployed

No deployments
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.

2 participants