mirror of
https://github.com/cloudflare/vinext.git
synced 2026-09-14 19:04:59 +08:00
vinext@0.1.3
976 Commits
| Author | SHA1 | Message | Date | |
|---|---|---|---|---|
|
|
62db98056c |
fix(image): allow any quality 1-100 when images.qualities is unset (#2023)
* fix(image): allow any quality 1-100 when images.qualities is unset
The image optimization endpoint returned 400 for any quality other than
75 (e.g. `<Image quality={90}>`) because vinext defaulted the allowed
quality list to `[75]` whenever `images.qualities` was not configured.
Next.js only enforces a quality allowlist when `images.qualities` is set;
when unset it permits any integer quality from 1-100. This aligns vinext
with that behaviour: `parseImageParams`/`resolveDevImageRedirect` now take
an optional allowlist and only restrict quality when one is provided, and
the build/runtime plumbing emits `null` (not `[75]`) when unset so the
"allow all" semantics survive into the deploy worker.
Repro: GET /_next/image?url=%2Fshop%2Ftablet.png&w=750&q=90 -> 400.
Fixes the app-router-playground image optimization failure.
* test(image): update App Router blur-exception tests for quality parity
With `images.qualities` unset, any quality 1-100 is now permitted (Next.js
parity), so q=70 is a normal quality rather than a rejected one. Pin the
blur-quality-exception tests to `qualities: [75]` so they still exercise the
dev-only exception, and add a case asserting q=70 is allowed in production
when qualities is unset.
|
||
|
|
a3d2f92152 |
fix(router): honor hybrid pages route priority (#1997)
* fix(router): honor hybrid pages route priority * fix(router): share hybrid owner decision with client navigation PR #1997 fixed the server-side route ownership for direct document loads, but the same invariant broke for client-side soft navigations and the matching prefetch path: - navigateClientSide() always delegated to the App runtime's RSC fetch, even when the Pages route had higher priority. renderPagesFallback() short-circuits RSC requests with null, so the App catch-all won. - prefetchUrl() prefetched an RSC stream for any URL that matched an App route, again ignoring Pages ownership. - The Pages entry was loaded on every hybrid request, even when a static App route had already matched (Pages can never win in that case). Expose the Pages route manifest on the client via a new __VINEXT_PAGES_LINK_PREFETCH_ROUTES__ window global emitted by both the App and Pages browser entries. The link shim consults a shared resolveHybridClientRouteOwner helper that mirrors the server-side pagesRouteHasPriorityOverAppRoute comparison. When Pages owns the URL, the click handler issues a window.location navigation and the prefetch path returns early. Gate the renderPagesFallback call behind a static-App-route check in handleAppRscRequest: when a static App route matches, the bridge cannot win, so skip the eager Pages entry load. Centralise the comparison in a new resolveHybridRouteOwner helper so server and client reach the same answer for the same (URL, route pair). Adds the missing client-navigation coverage to the use-params e2e fixture (Link from /app/ to /pages-dir/foobar) and unit tests for the shared owner decision. * fix(router): mirror server hybrid owner decision on the client PR review flagged two split-brain bugs in the previous hybrid ownership fix: a hand-copied client comparator and a Link-only ownership gate that left programmatic App Router navigations on the wrong path. The hand-copied routePrecedence in hybrid-client-route-owner.ts omitted the static-prefix reduction that lives in routing/utils.ts#routePrecedence, and used a strict-less-than comparison that returned App for identical dynamic patterns. The server returns Pages for both cases (Pages providers sort ahead of App providers, and routePrecedence subtracts 50 per static prefix segment). The split produced a real ownership disagreement on overlapping patterns like /_sites/:slug* (Pages) vs /:slug* (App). Add a shared compareHybridRoutePatterns to routing/utils.ts as the single source of truth: the static/dynamic short-circuits plus a sortRoutes call (which carries the static-prefix reduction and the Pages-first equal-pattern tiebreak). The server pagesRouteHasPriorityOverAppRoute and the client resolveHybridClientRouteOwner both delegate to it, so they cannot diverge. Drop the hand-copied routePrecedence entirely. Wire the ownership check at the App navigation runtime boundary so useRouter().push, useRouter().replace, gesturePush, and form submits all get the same hard-nav contract as the Link click handler. Specifically: - navigateClientSide: after same-origin normalization, if Pages owns the URL, hard-navigate via window.location and return (matching the existing external-URL branch). - _appRouter.prefetch: short-circuit RSC URL construction for Pages-owned targets so we do not warm an unusable cache entry. Centralise the existing two inline hard-nav branches in navigateClientSide into a hardNavigateTo helper for clarity. Tests: - Direct unit tests for compareHybridRoutePatterns covering identical-dynamic tiebreak, static-prefix dynamic overlap, static-prefix catch-all overlap, and infix-static bonus. - Direct unit tests for resolveHybridClientRouteOwner mirroring the server assertions plus a basePath-stripping test. - e2e: useRouter().push('/pages-dir/foobar') from an App page resolves to the Pages document. - e2e: useRouter().prefetch('/pages-dir/foobar') issues zero RSC requests for the target URL. * docs(router): fix stale score in static-prefix catch-all test comment The hand-copied comparator note quoted the dynamic-segment scores (51 / 1000) for the optional-catch-all example (/_sites/:slug* vs /:slug*). The current optional-catch-all scoring actually produces 1951 vs 2000. The test assertion was correct; only the comment was stale. * test(use-params): fix direct-load single dynamic param to use /a instead of /a/b * fix(router): compare hybrid routes structurally * fix(router): reject hybrid route conflicts * fix(router): refresh hybrid route ownership * fix(router): preserve hybrid routing lifecycle * fix(router): recheck pages routes after rewrites * fix(router): preserve rewritten pages queries * fix(router): preserve rewritten route ownership * fix(router): resolve client rewrites sequentially * fix(router): apply rewrite phases sequentially * fix(router): preserve rewrite params and endpoints * fix(router): hand off endpoint navigations * fix(router): preserve rewrite fragment params * test(e2e): avoid hybrid fixture route conflicts * test(pages): await async config validation * test(hybrid): avoid duplicate page fixtures * chore(router): clarify hybrid priority semantics * refactor(router): remove duplicate app route matcher * docs(router): clarify client hybrid comparator --------- Co-authored-by: James <james@eli.cx> |
||
|
|
10b5086f4d |
fix(app-router): align router autoscroll with Next (#2004)
* fix(app-router): align router autoscroll with Next App Router navigation could diverge from Next.js router autoscroll semantics around hydration timing, loading-shell same-page search navigations, and routes whose first committed node is React-hoisted into head. That broke the upstream router-autoscroll deploy-suite because the client marked hydration too early, static loading-shell templates were not usable for navigation, and the fallback scroll path masked the old-handler hoisted-head behavior. The fix moves the Next-compatible hydration marker into a passive effect, wires production hydrateRoot error callbacks to match Next's implicit root-boundary and recoverable-error handling, lets authoritative loading-shell templates drive static route optimistic payloads, and skips fallback document scrolling when the committed document only exposes a React-hoisted head resource. The ported tests cover the upstream router-autoscroll behavior plus focused unit boundaries for prefetch mode, optimistic routing, head-resource detection, and hydrateRoot callbacks. * fix(app-router): hoisted-head scroll fallback is per-intent, not global head scan * test(app-router): add full-chain scroll intent integration test * fix(app-router): match legacy scroll focus parity * fix(app-router): preserve latest scroll navigation intent * fix(app-router): scope scroll and error recovery * fix(app-router): gate navigation failure recovery * fix(app-router): match navigation failure handling * fix(app-router): align scroll completion parity * fix(app-router): retain latest failure target * fix(app-router): preserve route error boundaries * fix(app-router): clear discarded failure targets * fix(app-router): align failure recovery boundaries * fix(app-router): disarm refused recovery targets * fix(app-router): preserve failure target ownership * fix(app-router): match boundary recovery parity --------- Co-authored-by: James <james@eli.cx> |
||
|
|
2b67523e9e |
fix(server): strip HTTP/2 pseudo-headers before building Headers (#2021)
## Summary - Drop RFC 7540 §8.1.2.1 pseudo-headers (`:method`, `:authority`, `:path`, `:scheme`) before constructing WHATWG `Headers` from Node's `req.headers`. - Fixed at every `Headers`-from-`req.headers` site: the Pages Router middleware snapshot (index.ts), the edge API request builder (api-handler.ts), and the shared `appendWebHeader` helper used by `nodeToWebRequest` (prod-server.ts). - Also excluded pseudo-headers from the `reportRequestError` header metadata in both api-handler.ts and dev-server.ts so error reports reflect real request headers only. - Added a regression unit test driving `nodeToWebRequest` with a fake HTTP/2 request. ## Root Cause Over HTTP/2, Node's `http2` server exposes the request pseudo-headers as `:`-prefixed keys on `req.headers`. The WHATWG `Headers` constructor/`append`/`set` reject any header name containing `:` (`TypeError: Headers.set: ":method" is an invalid header name`), so building a `Headers` object directly from `req.headers` threw and returned a 500 on every HTTP/2 request. Per RFC 7540 §8.1.2.1, pseudo-headers must not be treated as regular header fields, so they are stripped at each construction site. ## References - Issue: cloudflare/vinext#2013 - RFC 7540 §8.1.2.1 (HTTP/2 pseudo-header fields) - Node `http2` request `:`-prefixed headers; WHATWG Fetch `Headers` name validation ## Verification - `node -e "new Headers({':method':'GET'})"` → throws (repro). - `CI=true pnpm test tests/http2-pseudo-headers.test.ts` → red before fix, green after. - `CI=true npx vp check` on all changed files → pass (format + lint + types). Co-authored-by: Claude Opus 4.8 (1M context) <noreply@anthropic.com> |
||
|
|
1b3a35606e |
refactor(navigation): drop V0 suffix from planner types (#2008)
The navigation planner's public and internal types were suffixed `V0` (RouteSnapshotV0, NavigationDecisionV0, FlightResultV0, and 19 others). The suffix implied a versioning scheme that never materialized — there is no V1, and the schema-version concerns it hinted at are carried explicitly elsewhere (NAVIGATION_TRACE_SCHEMA_VERSION, CACHE_PROOF_MODEL_SCHEMA_VERSION). The bare suffix was pure noise at every call site. Rename all 22 `…V0` planner types to their unsuffixed names across the planner, the browser state/entry/action modules, and the planner test suite. Pure mechanical rename: no behavior change, all 295 planner and browser-entry tests pass unchanged. |
||
|
|
201f4a64dc |
fix(shims): guard AsyncLocalStorage construction for browser bundles (#2020)
## Summary - Guard `getOrCreateAls` so it no longer calls `new AsyncLocalStorage()` unconditionally; when the runtime does not expose a usable constructor it falls back to a no-op store instead of throwing. - Add a `NoopAsyncLocalStorage` whose `getStore()` returns `undefined`, mirroring Next.js' `FakeAsyncLocalStorage` and this repo's `async-hooks-stub.ts`. - Preserve the cross-bundle singleton behavior (`Symbol.for` + `??=`). ## Root Cause In browser/client bundles `node:async_hooks` can resolve to a stub without a usable `AsyncLocalStorage` constructor (e.g. Vite's `__vite-browser-external`). `getOrCreateAls` ran `new AsyncLocalStorage()` at module-eval time, throwing `TypeError: AsyncLocalStorage is not a constructor`. Because many client-reachable shims (request-context, headers, cache, …) call this helper on import, the whole client bundle died and hydration crashed. Checking `typeof AsyncLocalStorage === "function"` before constructing, with a no-op fallback, matches Next.js' availability guard. Co-authored-by: Claude Opus 4.8 (1M context) <noreply@anthropic.com> |
||
|
|
37e839e2f1 |
fix(prerender): surface thrown generateStaticParams/getStaticPaths errors (#2017)
The build-time prerender proxies that fetch the static-params (App Router) and pages-static-paths (Pages Router) endpoints treated every non-ok response identically: they logged a misleading "stale or missing prerender secret" warning and returned the no-params sentinel, discarding the response body. But the endpoint returns 404 for the genuine disabled/secret case and 500 (with the real error in its JSON body) when the user's generateStaticParams/getStaticPaths throws. Swallowing the 500 silently dropped the route from prerendering and let the default-mode build "succeed" while shipping an app missing pre-rendered pages, blaming a non-existent secret problem. Branch on status: a 500 throws the real error (parsed from the body). App Router's existing per-route collector turns it into a "Failed to call generateStaticParams(): ..." error; the Pages Router getStaticPaths call is now wrapped to produce the same per-route error instead of crashing. Non-500 responses keep the warn-and-skip path, so the legitimate secret/disabled case is unchanged. This matches Next.js, which fails the build with the real error. Fixes #1982 Co-authored-by: Claude Opus 4.8 (1M context) <noreply@anthropic.com> |
||
|
|
47b38a91f3 |
fix(app-router): recover SSR shell render errors via __next_error__ document (#1908)
* fix(plugin): resolve vinext/shims/* package subpaths to local shim files Runtime helper modules embedded into generated entries import vinext's own shims by package subpath (e.g. `vinext/shims/headers`), while source checkouts alias userland `next/*` imports to the local shim files. The two specifiers resolved to different module instances, so request-scoped singleton state (navigation context, headers) split between the source shim copy and the package export copy. The violated invariant is that every shim module must be a per-request singleton regardless of import specifier. Resolve `vinext/shims/*` through the same plugin path as the `next/*` aliases so both forms land on the local shim files. Exercised by the SSR shell-error recovery browser spec, whose fixture imports vinext from the source checkout and depends on shared navigation state across both import forms. * fix(app-router): recover SSR shell render errors via __next_error__ document When the HTML (Fizz) render rejects during SSR, vinext re-rendered a server-side global-error page whose flight payload encodes the error tree. For an app without a custom global-error.tsx that meant the default error card with no path back to the real page: an SSR-phase-only throw (e.g. a client component using the "throw to opt out of server rendering" pattern) left the browser stuck on the card even though the client render would succeed. The violated expectation is Next.js's shell-error semantics: a failed HTML shell is served as the default `__next_error__` error document carrying the ORIGINAL flight payload and the bootstrap module, and the browser re-renders the real tree from that payload with createRoot instead of hydrating. Local error.tsx boundaries still win — they ship inside the flight payload and catch the re-thrown error client-side. handleSsr now resolves to that recovery document instead of rejecting, but only when both hold: - the error did not originate in the RSC render (no string `digest`), so flight errors, redirect()/notFound(), and server-component throws keep driving the existing rejection-based boundary machinery, and - the app has no custom global-error.tsx (the generated entry knows at build time and threads hasCustomGlobalError through dispatch/render options); apps with one keep the server-rendered boundary re-render. The browser entry switches from hydrateRoot to createRoot when the document root carries id="__next_error__", dropping the error-shell styles first. Covered by the new ssr-error-shell-recovery browser spec (recovery to real content, local error.tsx for SSR-only and unconditional client throws) and the existing tests/nextjs-compat/global-error.test.ts boundary-semantics suite. * refactor(review): address PR 1908 non-blocking notes - Add static prerender no-boundary recovery regression test to ssr-error-shell-recovery.browser.spec.ts - Document broad __next_error__ browser marker in app-browser-entry.ts - Extract stripJsExtension to utils/path.ts and wire into all shim resolution sites (vinext/shims/* + react-server shims) Non-functional: targeted regression coverage + code documentation + minor resolver hardening per reviewer feedback. * refactor(review): clarify shell recovery assumptions * fix(ssr): cancel abandoned prerender streams * refactor(ssr): clarify error shell root options * fix(isr): recover shell errors during regeneration * fix(ssr): scope client recovery to marked shells * fix(plugin): explicitly filter vinext shim subpaths * fix(plugin): retain null-prefixed shim resolution * test(nextjs-compat): cover no-boundary shell recovery fallback An unconditional client throw during SSR shell recovery without a local error boundary must still land on the default global-error card. Without a regression test, a future change could tear down the recovery shell and leave a blank document.\n\nAdd a production browser case that exercises the no-boundary route and asserts the default error UI after the client re-render throws again. * fix(app-router): preserve shell recovery error semantics * test(app-router): harden shell recovery cache semantics * fix(app-router): mark global error responses uncacheable * test(app-router): align error response status expectations * fix(build): preserve null-prefixed og resolution * fix(cache): delegate cache header cleanup to adapters --------- Co-authored-by: James <james@eli.cx> |
||
|
|
b7ef466742 |
fix(pages): preserve app props for GSSP requests (#1996)
* fix(pages): preserve app props for gssp requests
* docs(pages): update _next/data comment to reflect full props envelope
* fix(pages-router): preserve _app.getInitialProps during stale ISR regeneration
Stale ISR background regeneration called getStaticProps directly and rendered
HTML and __NEXT_DATA__ with only the page's pageProps, dropping app-level
props from _app.getInitialProps. The foreground path already loads
_app.getInitialProps first and merges its props, but the background
regeneration path skipped that step.
Extract a shared loadPagesAppInitialRenderProps helper from the production
foreground path and reuse it during background regeneration in both
pages-page-data.ts and dev-server.ts. This ensures regenerated pages carry the
same full props envelope as the original render.
Add a regression test in tests/pages-page-data.test.ts.
* fix(pages-router): skip _app.getInitialProps on ISR cache hits
The foreground render path ran _app.getInitialProps before consulting the
ISR cache, so fresh and stale cache hits executed userland App data code
even though the cached HTML was returned verbatim. That wasted work on the
hot path and ran side-effecting App code whose result the cached response
never reflected.
The eager App initial-props load happened up front, ahead of the HIT and
STALE short-circuits. Defer it until the request will actually render:
load it lazily inside the getServerSideProps / getStaticProps /
getInitialProps branches, after the cache short-circuits return.
Stale-while-revalidate already re-runs it inside the regeneration closure,
so regenerated HTML still carries app-level props. The dev SSR handler and
the production page-data resolver are updated in lockstep to preserve
dev/prod parity.
Tests cover the fresh-HIT skip and the stale foreground-skip vs
regeneration-run split at the page-data resolver boundary.
* refactor(pages-router): extract dev App getInitialProps loader into a tested helper
The dev SSR handler ran _app.getInitialProps inside an inline closure that
mutated captured pageProps/renderProps and read res directly, so its lazy
load-only-on-render behavior could only be covered by a heavyweight
integration test that vi.doMock'd the isr-cache and file-matcher modules —
a mock cascade with little signal.
Move the decision into loadDevAppInitialProps in pages-get-initial-props.ts.
It takes the App component, req/res, and an injected AppTree builder (keeping
React out of the module) and returns a discriminated result —
skip / response-sent / render — that the caller applies. The dev-server
closure is now thin glue: build the React tree, delegate, apply the result.
Adds focused unit tests that drive the helper through its real boundary
(genuine getInitialProps functions, plain req/res inputs) — no module mocks:
the skip path, App/page prop merging, pageProps normalization, the
response-sent short-circuit, and the router/ctx wiring passed to userland.
* fix(pages): preserve app props across data requests
* fix(pages): preserve fallback cache expiry
* fix(pages): preserve dev app context during ISR
* fix(pages): hydrate middleware rewrite fallbacks
* fix(pages): retarget middleware data rewrites
* fix(pages): preserve rewrite query on navigation
* fix(pages): finalize rewrite navigation state
* fix(pages): resolve rewrite data targets consistently
* fix(pages): await static props during regeneration
* fix(pages): preserve original query in resolved url
* Revert "fix(pages): await static props during regeneration"
This reverts commit
|
||
|
|
4821d247b0 | fix(pages): preserve module identity with deployment ids (#2012) | ||
|
|
5e37596183 |
fix(routing): re-encode trailing-slash Location for non-Latin-1 paths (#2011)
normalizeTrailingSlash built the redirect Location from the already percent-decoded pathname. A character above U+00FF (e.g. a CJK slug or emoji under trailingSlash:true) made the Headers constructor throw 'Cannot convert argument to a ByteString', caught by the outer handler and surfaced as a 500 instead of a 308. Latin-1 characters such as spaces did not throw but produced a malformed, un-percent-encoded Location. Percent-encode the redirect target before building the response, encoding every character that is invalid raw in an RFC 3986 path while preserving existing %xx escapes and / delimiters so already-encoded delimiters like %23 are not double-encoded. Fixes #1979 Co-authored-by: Claude Opus 4.8 (1M context) <noreply@anthropic.com> |
||
|
|
e1958ae3fa | fix(router): share Pages Router context across chunks (#2010) | ||
|
|
de9d03a846 | test(shims): normalize expected og shim path for Windows (#2006) | ||
|
|
930e03c449 |
fix(ppr): gate fallback shells until request-time resume is supported (#1716)
* fix(app-router): prerender cacheComponents root-param fallback shells PR 1 of 4: core model + build integration. Model: app-ppr-fallback-shell, pregenerated-concrete-paths, prerender-manifest Build: prerender/run-prerender fallback shell artifact generation Tests: createAppPprFallbackShells, pregenerated-concrete-paths core * feat(ppr): add fallback shell payload identity * feat(ppr): safely serve fallback shell cache entries * refactor(ppr): extract fallback shell render pipeline and dedupe getViteMajorVersion * fix(ppr): restore safe-serving CI checks The safe-serving branch failed CI because a client-side server-only guard rejected valid 'use server' action modules, a fallback-shell dependency cast no longer matched its helper type, apps/web lost the Cloudflare cache adapter source path during typecheck, and Knip could not resolve the documented Cloudflare cache adapter subpaths. The server-only guard now reads the directive prologue and skips top-level 'use server' modules, fallback-shell regeneration passes an explicit typed dependency object, apps/web gets the workspace Cloudflare cache path, the Cloudflare package exports explicit adapter subpaths, Knip uses a relative source import in the dispatch unit test, and the readiness test awaits the actual cache-ready promise. * fix(ppr): guard fallback shell reads for queries * fix(ppr): normalize pregenerated concrete paths * fix(ppr): address review comments on fallback shell serving and react runtime check * fix(ci): restore knip ignores for unlisted binaries and prune dependencies * fix(ppr): restrict bracket check in fallback detection to legacy manifests * fix(ppr): prefer stable ESM react-dom/static.edge before CJS fallback The loadStaticPrerender dev-mode path hard-codes react-dom's internal CJS file layout (cjs/react-dom-server.edge.development.js). A React upgrade could silently break fallback-shell rendering in dev without affecting production because the function never tried the stable ESM entry in development. Change the order so that react-dom/static.edge is attempted first in all environments. Only fall back to the CJS path when the ESM entry does not export prerender() and we are in a development runtime. This lets future React dev builds that expose prerender() from the ESM entry work automatically, and it surfaces the CJS-path failure only when the stable path is genuinely unavailable. Also handle the CJS default-export interop shape that Node.js ESM produces when dynamically importing a CommonJS module. * refactor(ppr): address four review cleanup items 1. Remove redundant double-normalization in seed-cache.ts addPregeneratedConcretePath already normalizes internally, so the call-site normalizePregeneratedPathname() was redundant. Dropping it gives a single source of truth for pathname normalization. 2. Lazily construct FallbackShellRenderDeps in tryServePprFallbackShell Extract the large FallbackShellRenderDeps object into a top-level buildFallbackShellRenderDeps helper. The closure in the probe loop now just delegates, so the heavy object is only created when a STALE entry actually triggers regeneration, not on every HIT probe. 3. Add dev-only warning for legacy bracket heuristic When isFallbackShellArtifactPath falls back to the bracket substring scan (route.fallback === undefined), emit a console.warn in dev so developers know a legacy manifest is being used and concrete URLs with literal brackets may be misclassified. 4. Update pregenerated-concrete-paths.test.ts to colon notation The production manifest writer uses colon notation (/:slug) for the route field, but the test fixtures used bracket notation (/[slug]). Update the fixtures so the test format matches production, exercising the real key format that the safe-serving guard depends on. * test(ppr): compact fallback shell dispatch fixtures * refactor(ppr): name fallback shell render phases * refactor(app-router): deduplicate PPR fallback shell and app page cache render paths * fix(ppr): avoid serving incomplete fallback shells * chore: drop redundant cloudflare cache aliases * fix(ppr): track fallback navigation hooks * test(ppr): render navigation hook probes * test(ppr): type navigation hook probes * refactor(ppr): remove unused shell regeneration path * refactor(ppr): remove unused shell result type * fix(ppr): safely gate fallback shell prerendering * fix(ppr): keep fallback shell gate internal * fix(ppr): mark generated dynamic fallback shells * test(ppr): align fallback fixture and search params --------- Co-authored-by: James <james@eli.cx> |
||
|
|
b5619c19f9 |
refactor(navigation): route prefetch reuse through planner (#1962)
* refactor(navigation): route prefetch reuse through planner Navigation cache reuse decisions were still split across the browser executor, which made visited-response reuse, prefetch consumption, and optimistic shell attempts hard to verify at the control-plane boundary. Move the reuse decision table into navigationPlanner with typed candidate facts, keep cache reads and React effects in the executor, and preserve silent stale-prefetch eviction for navigation probes. * refactor(navigation): exercise visited cache miss planning Visited response cache misses were represented in the planner API, but the browser executor still returned before invoking that classifier when the entry was absent or intentionally bypassed. That made the missing-candidate branch planner-owned in tests but executor-local in production. The executor now builds candidate facts for both present and missing states, asks the planner for the decision, and keeps cache mutation in the executor as the effect boundary. * fix(navigation): avoid prefetch probes on visited cache hits Visited-response reuse should stay on the soft-navigation fast path without touching the prefetch cache. The planner extraction accidentally computed prefetch availability before deciding to reuse a visited response, so stale prefetch entries could be silently evicted on a path that previously left them untouched. Add a planner prefetch-probe decision and have the browser executor consult it before reading the prefetch cache. This keeps cache mutation in the executor while making the no-probe condition explicit and tested. * fix(navigation): preserve prefetch fallback behavior * fix(navigation): keep slot mismatch probe behavior --------- Co-authored-by: James <james@eli.cx> |
||
|
|
4baf85ad5e |
fix(router): restore pages scroll traversal state (#1999)
* fix(router): restore pages scroll traversal state * fix(router): preserve pages component identity across HTML fallback Pages Router HTML fallback could import the module URL from fetched __NEXT_DATA__ even when the generated page loader already existed. In Vite chunk graphs that can evaluate a duplicate page or router module, same-route param navigations remounted the page and lost listener state before routeChangeComplete. Store the router wrapper component types on the shared browser runtime singleton, prefer registered page loaders on the HTML fallback path, and resolve navigation at the root commit boundary that Next.js awaits instead of waiting for passive effects. Non-DOM document mocks still resolve immediately so unit harnesses do not masquerade as real browser commits. Validated with the upstream reload-scroll-backforward-restoration deploy suite and the local router-events and scroll-restoration regressions. * test(router): simulate pages router commits in shims tests * fix(router): move Pages Router readiness into shared runtime state Move the pagesRouterReady bit into PagesRouterRuntimeState so duplicated next/router module instances (client entry + page chunks) observe the same readiness value. The initial value is still computed from shouldDeferInitialPagesRouterReady() once per document. Also tighten the scroll-restoration e2e fixture so routeChangeComplete assertions cannot pass from stale page state, and add a regression test that simulates two evaluated router instances on a deferred-ready page. * fix(router): early-exit scroll restoration when target unreachable, document useRouter fallback Addresses ask-bonk review feedback on PR #1999: - restorePagesRouterScrollPosition now breaks early when window.scrollY stops changing across frames, avoiding the full 60-frame budget when the saved scroll position exceeds the rendered page height. - useRouter() fallback path now has an explanatory comment documenting the non-reactive singleton return is intentional for split-chunk compat. * fix(router): harden scroll restoration settling --------- Co-authored-by: James <james@eli.cx> |
||
|
|
d1a80cd668 |
fix(app-router): preserve front redirects through fallback route handlers (#2000)
* fix(app-router): preserve front redirects through fallback route handlers * test(e2e): assert single bootstrap hydration in front-redirect test * chore: remove dead stripDeploymentIdQuery export * fix(app-router): handle cancelled bootstrap streams * docs(app-router): clarify bootstrap recovery * test(e2e): tolerate dangling fixture symlink * test(e2e): run front redirect regression in CI * fix(app-router): always hide internal RSC queries * fix(app-router): preserve visible hydration URL * test(e2e): scope visible URL regression * refactor(app-router): trim front redirect residue * test(e2e): group fixture setup command * test(e2e): tighten front redirect assertions * fix(app-router): preserve ordinary route handler URLs * fix(app-router): normalize edge route handler URLs * docs(app-router): explain route URL parity * fix(app-router): preserve Node RSC request URLs * fix(app-router): normalize route handler RSC paths * fix(app-router): forward RSC tokens through rewrites --------- Co-authored-by: James <james@eli.cx> |
||
|
|
3253aafd77 |
fix(pages-router): pass rewrite URL to edge API requests (#1998)
* fix(pages-router): pass rewrite URL to edge API requests * fix(pages-router): preserve edge API request URL parity * fix(pages-router): configure edge API NextRequest * fix(pages-router): preserve edge API locale config * fix(pages-router): preserve edge request metadata * fix(pages-router): align edge API URL formatting * fix(pages-router): match API locale casing * fix(pages-router): match domain locales by locale * docs(pages-router): clarify edge API basePath parity * test(deploy): expect metadata-preserving URL clone * docs(pages-router): note basePath rewrite parity --------- Co-authored-by: James <james@eli.cx> |
||
|
|
dabcb55e63 |
fix(app-router): expose active source page on window.next (#1995)
* fix(app-router): expose active source page on window.next App Router pages did not update window.next.__internal_src_page, so Next.js-compatible tooling and deploy tests could not observe the active source page on initial render or client transitions. The payload only exposed URL route IDs, which drop route groups and bracketed dynamic segment names. The fix carries a source-page metadata field from the app route's filesystem segments, reads it from committed browser router state, and mirrors it onto window.next like Next.js does. Adds regression coverage for route-group and dynamic source-page encoding plus the window.next writer contract ported from the upstream app-dir test. * fix(app-router): preserve source page across boundary renders * fix(app-router): tolerate malformed source page metadata * fix(app-router): preserve intercepted fallback source page * fix(app-router): omit unknown boundary source page --------- Co-authored-by: James <james@eli.cx> |
||
|
|
5ace0db7ac | fix(deploy): preserve app module identity with deployment ids (#2005) | ||
|
|
3d9639510e |
fix(build): honour experimental.lightningCssFeatures include/exclude (#1498) (#1664)
vinext silently ignored `experimental.lightningCssFeatures` because the options were never plumbed into Vite's CSS pipeline. `light-dark()` and other modern CSS features were still lowered to polyfills even when the user explicitly listed them under `exclude`. Resolve `experimental.useLightningcss` and convert the dash-case feature names from `experimental.lightningCssFeatures` into the numeric bitmask expected by lightningcss (mirroring Next.js's `featureNamesToMask` in `packages/next/src/build/webpack/loaders/lightningcss-loader/src/loader.ts` and `crates/next-core/src/next_config.rs`). When `useLightningcss` is on, forward `transformer: 'lightningcss'` plus the resolved `include`/`exclude` masks to Vite's `css.lightningcss` bridge. Adds a regression test that builds a fixture with `exclude: ['light-dark']` and asserts the function survives untouched in the emitted CSS, plus an inverse `include: ['light-dark']` case and unit coverage for the feature-name → bitmask helper. Ported from Next.js: test/e2e/app-dir/experimental-lightningcss-features/experimental-lightningcss-features.test.ts |
||
|
|
eef22e07a8 |
fix(pages-router): block fallback shell for crawler UAs on prerender (#1543) (#1663)
* fix(pages-router): block fallback shell for crawler UAs on prerender (#1543) When `getStaticPaths` returns `fallback: true` and an unlisted path is hit by a known bot/crawler, vinext was serving the `Loading...` shell so the crawler indexed the fallback HTML instead of the real page. Mirror Next.js `pages-handler.ts` and flip `isFallback` to false for bot User-Agents so the request renders synchronously with real props. - Add `isBotUserAgent` helper (DOM + HTML bot regex) in `utils/html-limited-bots.ts`, matching Next.js `shared/lib/router/utils/is-bot.ts`. - Plumb `userAgent` + `htmlLimitedBots` into `resolvePagesPageData` and flip the fallback bit when the UA matches. - Apply the same flip in the dev `createSSRHandler` for parity. - Targeted unit + integration regression tests covering Googlebot, Bingbot, DuckDuckBot, YandexBot, facebookexternalhit, and a normal Chrome UA control. Ported from `.nextjs-ref/test/e2e/prerender-crawler.test.ts`. Refs #1543. * fix(pages-router): preserve array user-agent bot detection |
||
|
|
6ad04e246d |
perf: skip unnecessary import parsing (#1991)
* perf(optimize-imports): skip unnecessary import parsing * fix(optimize-imports): keep parsing edge static imports * Update packages/vinext/src/plugins/optimize-imports.ts Co-authored-by: ask-bonk[bot] <249159057+ask-bonk[bot]@users.noreply.github.com> --------- Co-authored-by: ask-bonk[bot] <249159057+ask-bonk[bot]@users.noreply.github.com> |
||
|
|
ca34394865 |
fix(app-router): fold typeof window before resolution (#1956)
* fix(app-router): fold typeof window before resolution * fix(build): respect window bindings during folding * fix(build): handle typeof window environment edge cases |
||
|
|
bf41ee49dd |
fix(image): prevent optimizer cache-key amplification (#1944)
* fix(image): validate optimizer parameters * fix(image): close optimizer amplification aliases * fix(image): validate pure app dev requests * fix(image): address optimizer review findings |
||
|
|
24d3dfcf00 |
fix(pages): harden cookie parsing (#1947)
* fix(pages): harden cookie parsing * fix(pages): preserve cookie object compatibility * fix(shims): distinguish edge cookie parser * refactor(cookies): dedupe header parsing |
||
|
|
c023fc3810 | fix(actions): bound Flight payload graph validation (#1942) | ||
|
|
04db457691 |
fix(deploy): prevent Windows shell injection (#1946)
* fix(deploy): avoid Windows shell invocation * fix(deploy): preserve long Wrangler env names |
||
|
|
70ee909adf |
fix(app-router): support extensionless variable imports (#1958)
* fix(app-router): support extensionless variable imports * fix(build): harden extensionless dynamic imports * fix(build): align variable import resolution * fix(build): cover dynamic import contexts * fix(build): scope variable import contexts * fix(build): avoid comment parser backtracking |
||
|
|
b50af3e39d |
fix(link): preserve basePath hash navigation (#1952)
* fix(link): preserve relative hash navigation with basePath * fix(link): remove stale relative href resolution |
||
|
|
b3d407a6fd |
fix(headers): prioritize config cache headers for metadata assets (#1953)
* fix(headers): prioritize config cache headers for metadata assets * test(headers): guard metadata header precedence * style: format metadata header fix |
||
|
|
a84a038fe6 |
fix(config): share CommonJS module fallback (#1990)
* fix(config): share CommonJS module fallback * fix(config): harden CommonJS retry detection |
||
|
|
a155fdf997 |
fix(deploy): improve deployment id parity (#1949)
* fix(deploy): improve deployment id parity * test(router): isolate deployment prefetch globals * fix(deploy): restrict asset tokens to managed files |
||
|
|
5e19a2dd38 |
fix(config): honor resolve extensions and improve webpack config processing (#1959)
* fix(config): honor resolve extensions * fix(config): preserve resolve extension semantics * fix(config): preserve resolve extensions fallback * fix(config): preserve resolver environment semantics * fix(config): treat Vite preview as production |
||
|
|
3ba2528c14 | fix(app-router): preserve page notFound precedence during metadata failure (#1957) | ||
|
|
075919357e |
fix(router): hard navigate Pages links to App routes (#1960)
* fix(router): hard navigate pages links to app routes * fix(router): normalize localized app route detection |
||
|
|
222f18b0d9 |
fix(css): load local CommonJS PostCSS plugins (#1961)
* fix(css): load local CommonJS PostCSS plugins * fix(css): avoid temporary PostCSS plugin copies |
||
|
|
9e3cf90583 | test(e2e): disable hash fixture query prefetch (#1948) | ||
|
|
da26f42d7a |
refactor(router): classify server-action results and RSC navigation errors in planner (#1901)
* feat(router): classify server-action results and RSC navigation errors in planner The navigation executor in app-browser-entry.ts performed ad-hoc compatibility checks for server action responses using two separate helpers: resolveServerActionRedirectCompatibilityHardNavigationTarget and resolveRscCompatibilityNavigationDecision. These checks were scattered in the executor and mixed decision logic with side effects (clearClientNavigationCaches, performHardNavigation). This change introduces two pure classifiers in the navigation planner: - classifyServerActionResult: decides whether a server action response should hard-navigate (due to build skew) or proceed. For redirect responses, it returns the redirect href with appropriate history mode (assign for push, replace for replace). For non-redirect RSC responses, it reloads currentHref. A null clientCompatibilityId is treated as always compatible. - classifyRscNavigationError: always hard-navigates to currentHref on any RSC navigation error, providing a NavigationTrace for observability. Both classifiers produce typed DecisionV0 shapes with NavigationTrace entries, making the planner the single semantic authority for all navigation outcomes. The executor is updated to call these classifiers instead of the ad-hoc helpers, and the now-unused imports are removed. Test coverage: 9 new tests for classifyServerActionResult covering all 7 branches, and 1 test for classifyRscNavigationError. * refactor(router): address review concerns on classifyServerActionResult planner Three non-blocking concerns raised in code review: 1. compatibilityDecision.hardNavigationTarget was silently discarded in classifyServerActionResult without explanation. The helper computes a URL from responseUrl (the RSC action endpoint), which is wrong for user-visible navigation — the authoritative targets are actionRedirectHref and currentHref. Add a comment explaining the intentional discard. 2. The server action callback in app-browser-entry.ts computed the response content-type twice via separate raw string operations. Hoist the check into fetchResponseIsRsc so both consumers (classifyServerActionResult input and the non-RSC redirect guard) share one derived value. 3. The planner's decision dispatch was inlined in the executor, making it untestable without browser globals. Extract applyServerActionResultDecision into app-browser-action-result.ts and add an executor-level regression test that drives it with vi.fn() mocks — covering redirect push/replace, no-redirect reload, and proceed paths against the live classifyServerActionResult output. * refactor(router): move applyServerActionResultDecision to dedicated navigation module * refactor(router): remove old server-action redirect compatibility helper Remove resolveServerActionRedirectCompatibilityHardNavigationTarget from app-browser-action-result.ts and its tests. The planner's classifyServerActionResult is now the single semantic authority for server-action navigation decisions. Add a wiring regression test that exercises the real browser-entry seam: a synthetic Response has its facts extracted (content-type, redirect headers, compatibility ID, response URL) and passed to the planner, pinning the extraction boundary that app-browser-entry.ts performs at runtime. * refactor(router): extract server-action fact collector and remove stale helper Extract as the single pure boundary between raw browser response data and the narrow facts expected by the navigation planner. This removes the duplication where the wiring test had to hand-copy the same extraction logic. - Add to . - Use it in so the inline normalisation disappears. - Delete ; its logic is now folded into the helper's field. - Update tests to target the helper directly and assert the end-to-end wiring through the planner. * fix(router): address server action planner review --------- Co-authored-by: James <james@eli.cx> |
||
|
|
ba6ea6f6f8 |
fix(shims): add useUntrackedPathname hook for error boundary parity (#1933)
* feat(shims): add useUntrackedPathname hook for error boundary parity Next.js upstream provides a useUntrackedPathname() hook (packages/next/src/client/components/navigation-untracked.ts) that is used by the unstable_catchError error boundary. Unlike usePathname(), useUntrackedPathname(): - Returns null during the missing-params shell prerender (instead of "/") - Does not register the pathname as a tracked render dependency, avoiding unnecessary re-renders of the error boundary This commit: 1. Adds useUntrackedPathname() to packages/vinext/src/shims/navigation.ts 2. Switches packages/vinext/src/shims/error.tsx to use it 3. Adds unit tests covering server, client snapshot, and Pages Router paths Refs: - Next.js source: https://github.com/vercel/next.js/blob/v16.2.6/packages/next/src/client/components/navigation-untracked.ts - Issue: https://github.com/cloudflare/vinext/issues/1920 * refactor(shims): move useUntrackedPathname to internal module Address code review feedback on PR 1933: - Move useUntrackedPathname from public next/navigation API to internal/navigation-untracked.ts to prevent public surface leak. - Change server no-context fallback from null to '/' to match usePathname() semantics. Document that null is reserved for future missing-params shell detection. - Update error.tsx to import from the internal module. - Update shims tests to import from internal module and expect '/' for no-context SSR. - Add integration test for unstable_catchError boundary contract: getDerivedStateFromProps clears errors on pathname changes and retains them when pathname stays the same. * fix(shims): gate untracked pathname render snapshot with active count Address second round of code review feedback on PR 1933: - Gate client render snapshot with navigationSnapshotActiveCount > 0 so the hook returns the pending URL only during active transitions. After commit, falls back to cached pathname so user pushState/ replaceState calls are immediately reflected. - Import getNavigationContext() from navigation.ts instead of duplicating the global accessor / hydration context logic. - Add inverse test: provider snapshot present but inactive (navigationSnapshotActiveCount === 0) returns committed pathname, not stale provider value. * test(shims): type-safe unstable_catchError boundary contract test Export _CatchError, _CatchErrorInternalState, _CatchErrorProps, _CatchErrorState, and _UserProps from error.tsx with @internal annotations so tests can reference them without as-unknown-as assertions. Rewrite the getDerivedStateFromProps integration test to use imported types instead of inline type assertions. * chore: format with vp fmt * fix(shims): keep _CatchError and underscore types local in error.tsx Address review feedback: exporting _CatchError and underscore types from next/error widened the public shim surface. Revert them to local types and use structural typing in tests instead. - Make _CatchError, _UserProps, _CatchErrorState, _CatchErrorProps, and _CatchErrorInternalState local again (non-exported). - Update the getDerivedStateFromProps integration test to use structural as-unknown-as assertions instead of importing internal types. * refactor(shims): extract shared Pages Router accessor to internal helper Create packages/vinext/src/shims/internal/pages-router-accessor.ts with getPagesNavigationContext() and PagesNavigationContext type. Import from it in both navigation.ts and navigation-untracked.ts instead of duplicating the Symbol lookup and error handling. This prevents the string key and the accessor shape from drifting across modules if a third consumer is added later. router.ts still writes the global accessor directly using Symbol.for as before. * fix(shims): move pages-router-accessor import to top of navigation.ts Move the import from the middle of the file to the top import block and remove the unused PagesNavigationContext type import. Fixes eslint no-unused-vars and import/first errors. * ci: trigger rebuild * refactor(shims): reuse navigation render snapshot hook --------- Co-authored-by: James <james@eli.cx> |
||
|
|
cd921ab709 |
perf: cache fs probes and precompute route sort keys in scan/deploy paths (#1930)
* perf(routing): precompute route precedence before sorting
`compareRoutes` re-parsed every pattern on each comparison, so a sort
called `routePrecedence` ~2·log n times per route instead of once. Replace
it with `sortRoutes`, which scores each pattern once into a Map and sorts
by (score, pattern.localeCompare). The localeCompare tiebreaker already
guarantees a total order, so ordering is byte-identical; this just removes
the redundant re-parsing on every route scan (dev re-scans on file change,
plus the pages/api and app-graph builds).
* perf(app-router): cache convention-file probes per route-graph scan
`buildAppRouteGraph` walks the appDir→leaf chain separately for every
route (layouts, templates, errors, boundaries, slots), each step probing
up to 4 extensions per convention file via `existsSync`. Shared ancestor
directories — the `app/` root above all — were re-stat'd once per
descendant route, so a scan cost roughly routes × depth × conventions ×
extensions syscalls.
Memoize `findFile` through a `WeakMap<ValidFileMatcher, Map>` keyed by a
per-scan matcher clone created in `buildAppRouteGraph`. Results are
immutable within one scan, so no invalidation is needed: the cache lives
exactly as long as the scan and is GC'd afterward. The fresh per-scan key
also keeps overlapping scans isolated, and the `null` not-found outcome is
cached too. Probe results are identical to the previous direct `existsSync`
calls.
* perf(deploy): single tree walk for detection and reuse parsed package.json
`analyzeProject` walked the app/ tree twice — once in `detectISR` and again
in `detectMDX` — and `detectNativeModules` re-read and re-parsed
package.json that `detectProject` had already parsed into `allDeps`.
Merge the two walkers into one `scanTreeForDetection(dir, { isr, mdx })`
that evaluates both predicates per entry with each flag short-circuiting
independently, extract the next.config MDX check into `detectMDXFromConfig`,
and add `resolveProjectDir` for the shared root/`src` precedence. Pass the
already-merged `allDeps` into `detectNativeModules`. Detection semantics are
unchanged: same files visited, same patterns tested, same booleans out.
|
||
|
|
ae5c72ec13 |
fix(shims): match next/error RSC diagnostic (#1939)
* fix(shims): match next error RSC diagnostic * test(app-router): run catch-error e2e in CI * revert: avoid dedicated catch-error CI job |
||
|
|
5ac620c2d0 |
fix(cache): honor fetch opt-outs and force-dynamic revalidate parity (#1907)
* fix(cache): honor fetch opt-outs in app page output
App Router fetches that explicitly opt out of caching could still leave the rendered page eligible for static output, while dynamic = "force-dynamic" was lowered to fetchCache = "force-no-store" and overrode explicit per-fetch cache/revalidate options.
The cache decision was conflating route-level dynamic rendering with a hard segment fetchCache mode. Next.js treats force-dynamic as a default no-store mode only for fetches without explicit cache or revalidate config, and marks explicit uncached fetches as dynamic for the surrounding render.
Mark explicit uncached fetch decisions through the existing dynamic usage signal, keep force-dynamic as a separate per-request fetch default, and preserve Response.url when reconstructing cached fetch responses.
* fix(cache): correct revalidate:false and Response.url semantics
- Split revalidate: false out of the no-store path; it now caches
indefinitely (INFINITE_CACHE) matching upstream patch-fetch.ts.
- Store actual response.url (freshResp.url / response.url) in cached
fetch entries instead of the input request URL.
- Remove markUncachedFetchForPageOutput() from the auth-header fallback
so it matches upstream's autoNoCache path and does not mark pages
dynamic.
- Update tests to reflect correct revalidate: false caching behavior
and add a test for redirect-style response URLs.
* fix(app-router): resolve target route dynamic config during intercepts and revalidation
Prevents the outer route's force-dynamic default from leaking into
interception source routes and ISR revalidation targets.
- app-rsc-entry.ts: expose __resolveRouteDynamicConfig
- app-page-dispatch.ts: pass resolveRouteDynamicConfig to dispatch,
sync currentForceDynamicFetchDefault when the render target changes
- app-page-dispatch.test.ts: 4 tests covering intercept + revalidation
paths for both lost and leaked defaults
* fix(app-router): sync fetchCache and force-dynamic default during action redirects/re-renders
* fix(cache): treat revalidate:false as non-explicit for force-dynamic parity
Upstream patch-fetch.ts computes noFetchConfigAndForceDynamic using
!currentFetchRevalidate (truthiness), so revalidate: false is treated
as 'no fetch revalidate config' and force-dynamic wins. vinext's
hasExplicitRevalidateValue() previously returned true for false,
blocking the force-dynamic no-store default and causing the fetch to
cache for 1 year instead.
Update hasExplicitRevalidateValue to exclude false (and 0) from the
explicit set, aligning with upstream's truthiness check. Add a parity
test covering force-dynamic + next.revalidate: false.
* fix(cache): split revalidate predicates for force-dynamic vs segment defaults
The previous fix to hasExplicitRevalidateValue() treated false and 0 as
non-explicit, which matched upstream's force-dynamic truthiness check
but broke segment cache defaults: default-cache would override
revalidate: 0 to force-cache, and default-no-store would override
revalidate: false to no-store.
Split into two helpers:
- hasExplicitRevalidateValue(): any defined value is explicit (for
segment defaults where 0 and false are explicit opt-outs)
- isFalsyRevalidate(): false and 0 are falsy (for force-dynamic's
noFetchConfigAndForceDynamic parity check)
Add parity tests for default-cache + revalidate: 0 and
default-no-store + revalidate: false.
* refactor(cache): extract ONE_YEAR_SECONDS and cover only-no-store revalidate:false
* fix(cache): keep dynamic fetch observations for auth bypass and cache-key fallback
Restore recordDynamicFetchObservation in the auth-header safety bypass so
auth-keyed fetches still downgrade the page output to fresh render, and
revert the cache-key-generation fallback to a plain observation so an
internal limitation (oversized/unserializable body) does not mark the
whole page dynamic. Lock in force-dynamic vs explicit segment fetchCache
precedence with a test.
* docs(cache): note deliberate no-cache dynamic-marking divergence from upstream
* fix(route-handler): apply segment fetchCache and force-dynamic fetch default to route handler dispatch
Route handlers never called setCurrentFetchCacheMode /
setCurrentForceDynamicFetchDefault, so a force-dynamic route handler did
not get the per-request no-store fetch default that page dispatch applies,
and an explicit fetchCache export on a route handler module was ignored.
Upstream's app-route module copies userland.fetchCache into the work store
and sets workStore.forceDynamic for dynamic = "force-dynamic", which
patch-fetch turns into a no-store default for fetches without explicit
cache config — for route handlers as well as pages. Mirror that in
dispatchAppRouteHandler and re-apply the state inside the background
regeneration request context.
* fix(fetch-cache): tolerate cached entries missing url and document revalidate:false cacheability
* fix(fetch-cache): fall back to the request URL for cached entries missing url
Reconstructing Response.url from the fetch input preserves the
pre-existing guarantee for legacy/foreign cache entries instead of
degrading to "". Also document why the intercept dispatch deliberately
does not save/restore fetch defaults around buildPageElement.
* docs(fetch-cache): note cached responses now join body-stream cleanup
* docs(fetch-cache): note explicit segment fetchCache beats force-dynamic default
* test(fetch-cache): pin tags-only fetch to no-store under force-dynamic
* docs(fetch-cache): document auth-bypass precedence and test no-store + auth
- Note at the auth-safety bypass that explicit no-store/no-cache/revalidate: 0
takes the stronger branch first and fully marks the page dynamic; the bypass
only covers implicitly-cacheable auth-keyed fetches.
- Add a test locking in that explicit no-store with auth headers routes through
markUncachedFetchForPageOutput rather than the softer auth bypass.
- Clarify in dispatchAppRouteHandler that the fetch-cache setters are new
wiring for route handlers, not a mirror of a pre-existing pattern.
* test(route-handler): lock no-store fetch bailing ISR for revalidating handlers
A route handler with revalidate = 60 that performs
fetch(url, { cache: "no-store" }) must skip its ISR cache write and be
marked known-dynamic, now that the patched fetch's explicit no-store
branch calls markDynamicUsage() (upstream patch-fetch parity). Exercises
the real fetch-cache shim and the real headers-shim dynamic-usage pair,
matching the app-route-handler-dispatch wiring.
---------
Co-authored-by: James <james@eli.cx>
|
||
|
|
e9b0f68658 | feat(web): expose latest compatibility failures (#1941) | ||
|
|
e018a08708 |
fix(pages-router): restore scroll across reload history traversal (#1905)
* fix(pages-router): restore scroll across reload history traversal
Pages Router pages with experimental.scrollRestoration currently expose window.next.router before the popstate runtime is installed and only keep Vinext scroll coordinates in the in-memory history state. After a reload, a back or forward traversal can run before the runtime is ready and has no durable scroll snapshot for the target history entry.
The violated invariant is that the Pages Router owns browser scroll restoration whenever the Next.js scroll restoration flag is enabled, with one stable history key per entry and routeChangeComplete emitted after the new page commits.
Resolve the Next.js config flag into process.env.__NEXT_SCROLL_RESTORATION, install the Pages Router runtime during next/router evaluation, persist Next-style sessionStorage scroll snapshots per history key, and render navigations through a stable commit boundary before emitting routeChangeComplete.
Regression coverage ports Next.js reload-scroll-backforward-restoration and verifies manual restoration plus exact scroll positions across reload, back, and forward traversal.
* fix(pages-router): sequence routeChangeComplete after scroll restoration and settle on render failures
* fix(router): guard against missing window.history in stampInitialHistoryState
* fix(router): defer hash scroll until after routeChangeComplete
Move hash scrolling out of renderPagesRouterElement's commit callback
and into the post-routeChangeComplete path, matching Next.js ordering:
x/y restoration happens during render commit, hash scrolling happens
after the completion event.
Also fix E2E test expectRouteChangeComplete to use one-shot event
listeners instead of checking for stale text, and add listener cleanup
to the fixture to prevent accumulation.
* fix(test): remove post-push deadlock and throw on missing events in E2E helper
expectRouteChangeComplete() now throws if window.next.router.events is
absent instead of silently resolving. Remove the redundant
expectRouteChangeComplete call after pushWithPagesRouter in the third
test — the awaited router.push already resolves after routeChangeComplete,
so registering a listener after it would deadlock.
* fix(test): replace as any casts with type-safe window.next narrowing in E2E scroll tests
* fix(router): narrow renderPagesRouterElement scroll param, drop dead hash branch
* fix(router): reset x/y scroll on hash routes before routeChangeComplete and cancel pending render on supersede
- Pass {x:0, y:0} through commit boundary for all scrollable
navigations, not just hash-less ones (hash scroll deferred to after
routeChangeComplete as before).
- Cancel pending render-commit Promise when a newer navigation starts,
preventing hang when the first root.render() commit is dropped by
React re-reconciliation.
- Add regression tests for both edge cases.
* fix(router): use SSR-safe layout effect in commit boundary and pin shallow scroll ordering
Address bonk review on #1905:
- swap the commit boundary's raw useLayoutEffect for the SSR-safe
useNonWarningLayoutEffect pattern from shims/image.tsx so Pages Router
SSR renders no longer log React's useLayoutEffect warning
- document that the default-noop commit boundary intentionally also wraps
SSR and initial hydration
- document the intentional shallow-scroll-before-routeChangeComplete
ordering and add a unit test pinning it
* fix(router): keep history-state scroll restore on popstate when scrollRestoration flag is off
Without experimental.scrollRestoration, popstate must still honour the
__vinext_scrollX/Y saved into history state on push, since a soft popstate
re-renders content the browser's native restoration can't position. Also
document why the popstate-time sessionStorage snapshot depends on
history.scrollRestoration = "manual".
* fix(router): guard render-commit canceller against late commits from superseded trees
* fix(router): defer current-history-key commit until beforePopState allows navigation
When beforePopState cancels a popstate the app stays on the previous
history entry, but _currentHistoryKey had already been updated to the
target key, skewing subsequent scroll-position bookkeeping. Move the
key commit below the beforePopState early-return, matching the
deliberate deferral of _lastPathnameAndSearch.
* chore(router): note intentional eager scroll snapshot; fix fixture link increment
- Document that the outgoing-entry scroll snapshot is deliberately written
before the beforePopState gate: on cancellation the app stays on
currentKey, so the saved value remains that entry's live scroll.
- Coerce id to a number in the pages-scroll-restoration fixture Link so
the href increments numerically instead of string-concatenating.
* fix(router): keep manual scroll restoration opt-in Pages-Router-only
Gate installManualScrollRestoration on the document not being an App
Router one (window.next.appDir === true): with the now-global
__NEXT_SCROLL_RESTORATION define, an App Router app that value-imports
next/router for compat would otherwise have its native browser scroll
restoration disabled at module eval. Upstream only flips
history.scrollRestoration inside the Pages Router constructor, which
never runs on App Router documents.
Also document the hash-only popstate path discarding the per-entry
__next_scroll_<key> snapshot as intentional upstream parity (change()'s
onlyAHashChange branch passes null to this.set and only scrollToHash
runs), and add unit coverage for both behaviors.
* ci: run pages-scroll-restoration E2E project in the CI matrix
Add the missing E2E matrix entry so the ported Next.js regression spec
(reload-scroll-backforward-restoration.spec.ts) actually executes in CI,
matching the shape of the sibling single-shard Pages Router entries.
Also document why the soft-popstate scroll fallback differs between
manual restoration on ({ x: 0, y: 0 }) and off (null -> native auto
restoration handles unstamped entries), per review.
* refactor(router): fold App Router gate into manualScrollRestoration constant
The popstate handler's sessionStorage save/read branches gated on the
module-level constant, which lacked the window.next?.appDir check that
installManualScrollRestoration used, leaving those branches relying
solely on the __N state filter to stay inert on App Router documents.
Fold the appDir check into the constant so every consumer is
Pages-Router-only by the same gate; the App Router bootstrap stamps
window.next.appDir before any client module evaluates, so the
module-eval-time check is reliable.
* test(pages-scroll-restoration): default getServerSideProps id to string "0"
Route params always arrive as strings, so the numeric 0 fallback was
inconsistent with the string values the component relies on
(Number(id) + 1 href, id === "error" check). Default to "0" for type
consistency.
* test(pages-scroll-restoration): align fixture deps and vinext import with pages-basic
Import vinext via the workspace package name instead of reaching into
dist by relative path, and declare the same react/react-dom/vinext
dependencies as the other fixtures so the fixture is self-describing
and the pnpm-lock.yaml importer entry is populated.
* fix(router): snapshot outgoing scroll on hash-only pushes
Upstream Next.js snapshots the outgoing entry's scroll into
__next_scroll_<key> inside Router.push() itself, before change()'s
onlyAHashChange short-circuit, so hash-only pushes still capture the
departed entry's position. Our hash-only push branch returned before
saveScrollPosition() ran, so a later back-popstate to that entry
restored {x: 0, y: 0} instead of the position the user had reached.
Save the outgoing scroll before updateHistory mints the new key,
matching the full-navigation push path and upstream ordering.
* docs(router): clarify manual scroll-target fallback chain precedence
* test(shims): tag scrollRestoration App Router test as eval-order guard
* docs(router): note missing-snapshot fallback intent at forcedScroll default
---------
Co-authored-by: James <james@eli.cx>
|
||
|
|
fd1023321b |
fix(router): support experimental gesture push (#1909)
* fix(router): support experimental gesture push Vinext did not expose useRouter().experimental_gesturePush when Next.js apps enabled experimental.gestureTransition. Upstream gesture-transition fixtures call the method inside a held async transition, so the target route never became visible before the canonical router.push completed. The fix resolves the config flag into the same __NEXT_GESTURE_TRANSITION define used by Next.js, exposes the optional router method only under that flag, and lets gesture navigation use the existing RSC navigation pipeline with an immediate approved visible commit. The ported e2e fixture preserves the upstream held-transition flow and target/static/dynamic assertions. * test(router): update navigate mock assertions to expect default transition commit mode * fix(router): address ask-bonk review comments on gesture push - track scheduled app router navigation in experimental_gesturePush for parity with push/replace, so a refresh() issued in the same task skips its redundant re-fetch - document the synchronous visible-commit mode's null pendingRouterState invariant in the browser navigation controller - add a unit test asserting experimental_gesturePush is only attached when the __NEXT_GESTURE_TRANSITION define is set * style(tests): fix formatting in shims.test.ts * docs(router): clarify gesture push normalization and flushSync commit paths * test(router): fix unbound-method lint in shims test and document gesture spec coverage * docs(router): clarify gesture define boolean form and spec held-state rationale * docs(test): note gestureTransition is fixture-wide for the gesture spec only * fix(router): no-op experimental_gesturePush before the navigation runtime is ready Upstream gesturePush early-returns when getCurrentAppRouterState() is null, so a gesture dispatched before hydration is a no-op. Previously vinext fell through navigateClientSide's non-runtime branch and performed a real history push. Guard on the runtime's navigate function (the same readiness check navigateClientSide uses) and document that the un-awaited void navigateClientSide(...) deliberately matches push/replace's fire-and-forget rejection shape. * docs(router): note gesturePush guard/dispatch runtime reads have no TOCTOU window * docs(test): document gesture fixture's double-navigation divergence from upstream --------- Co-authored-by: James <james@eli.cx> |
||
|
|
d3bbc4d558 |
test(e2e): close page before temp prod server in remaining specs (#1928)
Same latent race fixed for inline-css.browser.spec.ts in #1927: the temp production server was closed during teardown while the page was still open, so idle-scheduled requests (e.g. Link prefetches via requestIdleCallback) could hit the closed port and log ERR_CONNECTION_REFUSED — which the consoleErrors fixture turns into a flaky failure. Close the page first in hash-rsc-requests and client-reference-runtime-map too. |
||
|
|
2737a38d46 |
fix(pages-router): support stream proxying in API routes (#1902)
* fix(pages-router): support stream proxying in API routes
* fix(pages-router): address review feedback on stream proxying PR
- Narrow auto-end condition to only skip ending when handler returns res
(the destination of req.pipe(...).pipe(res)), preventing hangs from
non-stream return values.
- Replace full-body buffering with a PassThrough-backed PagesResponseStream
that resolves on first write, enabling real streaming responses.
- Add error handling to reject responsePromise when the response stream
errors, preventing silent request hangs.
- Add regression tests: non-stream return auto-end, multi-chunk write,
and response stream error handling.
* fix(pages-router): avoid hanging responses and PassThrough unhandled errors
- Narrow auto-end condition to to prevent non-stream
return values from hanging requests.
- Replace PassThrough + Readable.toWeb() with a direct ReadableStream controller
in PagesResponseStream to eliminate Controller is already closed unhandled
errors during stream proxying.
- Add destroy() override to error/close the stream body when the Node Writable
is destroyed after streaming starts.
- Add rejectResponse callback to PagesResponseStream constructor for proper
error propagation.
- Add regression tests for auto-end, multi-chunk streaming, and destroy error
handling.
* fix(pages-router): destroy Node side when Fetch body is cancelled
- Reject writes in _write() when streamEnded or destroyed to prevent
buffering chunks after cancellation.
- In the ReadableStream cancel handler, clear bufferedChunks and destroy
the Node-compatible PagesResponseStream so upstream writers receive
an error instead of silently accumulating data.
- Add regression test proving writes after body cancellation fail with
an error and do not accumulate in the bridge.
- Rename multi-chunk test to be more accurate about what it verifies.
* fix(pages-router): settle response when res.destroy() is called without error
- In destroy(), if the response has not been resolved yet, resolve the
response promise (with a closed stream) when no error is provided, or
reject it when an error is provided. This prevents the request from
hanging forever when a handler calls res.destroy() before any body
write and returns the res object.
- Add regression test proving res.destroy() without error resolves to an
empty 200 response instead of hanging.
* chore: trigger CI run for flaky E2E test validation
* fix(pages-router): track pipe event and fix request body cancellation
- Add `res.once("pipe", ...)` listener to detect when a handler pipes into the response without returning the writable. Skipping auto-end by return-value only missed the real-world pattern:
(req, res) => { req.pipe(upstream).pipe(res); } // returns undefined
Next.js uses the pipe event signal, not the handler return value.
- Fix request body cancellation: the async generator finally block now calls `reader.cancel()` before `releaseLock()`, restoring the pre-PR behavior where early return from `for await (chunk of req)` cancelled the underlying stream instead of just releasing the lock.
- Add regression tests for both pipe-without-return and pipe-with-return.
* fix(pages-router): drop handlerResult === res auto-end signal, rely on pipe event only
The `handlerResult === res` check was too broad — chainable helpers like
`return res.status(202)` return `this` without implying streaming, and would
cause a hang by skipping auto-end. Now that `res.once("pipe", ...)` provides
the real stream signal, the return-value check is redundant and harmful.
Removes:
- handlerResult variable and === res comparison
- comment about returning the writable
Adds:
- regression test for `return res.status(202)` not hanging
* fix(pages-router): address stream response review
* fix(pages-router): close IncomingMessage parity gaps in API route streams
- Yield Buffer chunks (zero-copy views) from the request readable and opt
out of objectMode so req matches IncomingMessage byte-stream semantics:
per-chunk chunk.toString("utf8") decodes instead of comma-joining byte
values, and setEncoding()/read(n) behave byte-wise.
- Honour config.api.externalResolver: Next.js never auto-ends a response,
and externalResolver: true is the documented contract for handlers that
respond after the handler promise settles (e.g. proxy middleware that
attaches its pipe asynchronously). Skip the auto-end safety net for such
routes so they are not truncated to an empty response.
---------
Co-authored-by: James <james@eli.cx>
|
||
|
|
56393aedad |
test(e2e): close page before prod server in inline-css fixture teardown (#1927)
The inlineCssApp fixture closed its temp production server while the page was still open. Link prefetches are scheduled via requestIdleCallback and could fire after the test body finished, hitting the closed port and logging ERR_CONNECTION_REFUSED, which the consoleErrors fixture then turned into a flaky failure at teardown. Close the page first so no late request can target the dead port. |
||
|
|
dea4472c2f |
fix(app-router): include parallel slot params in useParams (#1904)
* fix(app-router): include parallel slot params in useParams App Router navigation state previously used only the primary route match params when setting request navigation context, RSC param headers, render observations, and optimistic navigation payloads. That lost catch-all params from active parallel slot branches, so useParams() diverged from the slot page's params prop after SSR and client navigations. Next.js derives params from the selected router tree across parallel route branches. Resolve active slot params from route metadata, merge them into the navigation params boundary, and feed that selected param set through server render and optimistic navigation payloads. Port the upstream parallel-route-navigations fixture and cover the route graph, selected params helper, and optimistic payload boundary. * fix(app-router): preserve canonical pathname in navigation context after middleware rewrite * fix(app-router): resolve parallel slot params for static, revalidation, and action paths * chore: retrigger CI * fix(app-router): address ask-bonk review comments on parallel slot params - Remove unused parameter from - Add clarifying comment on routeParams fallback being deliberate no-op - Use (full matched params) instead of narrowed as base for slot param merge, preserving interception-specific extras on ISR regeneration path * fix(app-router): use full navigationParams in server-action re-render path The server-action re-render path was passing narrowed actionRerenderTarget.params to resolveAppPageNavigationParams, dropping interception-specific extras from source-route intercepts. Use actionRerenderTarget.navigationParams (full matched params) instead, matching the pattern used in the dispatch ISR path at app-page-dispatch.ts:602. Adds unit tests for the intercepted-slot and mixed intercepted + non-intercepted slot branches of resolveAppPageNavigationParams. * docs(router): clarify decode invariant and type cast rationale in parallel-slot params - app-optimistic-routing.ts: add comment explaining the pre-existing double-decode asymmetry between route params and slot params, noting TODO to converge decode passes - app-server-action-execution.ts: expand the comment on the interceptOpts cast to document why it's safe and what a follow-up would look like * fix(app-router): merge slot params for fresh intercepts --------- Co-authored-by: James <james@eli.cx> |