1. 23 Sep, 2026 40 commits
    • next-js-bot[bot]'s avatar
      v16.4.0-canary.41 · c9a2a711
      next-js-bot[bot] authored
      c9a2a711
    • Tobias Koppers's avatar
      Add experimental custom webpack support (#98862) · b12b46b6
      Tobias Koppers authored
      ### What?
      
      Add the experimental `customWebpack` configuration option so
      webpack-mode applications can use a project-installed webpack version
      instead of the version bundled with Next.js. Webpack is now an optional
      `^5.98.0` peer dependency, and the new option is documented with
      end-to-end coverage for webpack 5.98.0 and 5.111.0.
      
      ### Why?
      
      Next.js currently redirects webpack imports to its bundled
      implementation. This prevents applications from opting into newer
      compatible webpack releases or validating upgrades independently. The
      new option provides an explicit escape hatch while preserving the
      bundled implementation as the default.
      
      ### How?
      
      After configuration is resolved, webpack-mode startup redirects the
      existing webpack require-hook aliases to the package resolved from the
      application. The selection is propagated to webpack build workers
      through the existing local-webpack runtime switch. If the optional peer
      cannot be resolved, Next.js restores its bundled aliases and reports an
      actionable installation error.
      
      The implementation only activates for webpack, leaving Turbopack and
      Rspack unchanged. It also handles the resolver stack API exposed by
      external webpack versions. The test matrix verifies the selected
      compiler version, rendering in development and production, the
      build-worker path, missing-peer diagnostics, and bundled fallback
      behavior when the option is disabled.
      
      ### Verification
      
      - `pnpm test-dev-webpack
      test/e2e/app-dir/custom-webpack/custom-webpack.test.ts`
      - `pnpm test-start-webpack
      test/e2e/app-dir/custom-webpack/custom-webpack.test.ts`
      - `pnpm --filter=next types`
      
      <!-- NEXT_JS_LLM -->
      
      
      <!-- fleet 19431696-5f4c-400d-a3be-700bfe86abda -->
      
      ---------
      Co-authored-by: 's avatarvercel-fleet-prod[bot] <318278635+vercel-fleet-prod[bot]@users.noreply.github.com>
      Co-authored-by: 's avatarTobias Koppers <1365881+sokra@users.noreply.github.com>
      b12b46b6
    • Jiwon Choi's avatar
      Default agentic upgrades to a separate worktree (#99111) · ccbd0cb5
      Jiwon Choi authored
      ### Why?
      
      The agent nudge offers a background upgrade without specifying a
      separate checkout, so upgrade edits can land alongside the current
      task’s changes.
      
      ### How?
      
      Make both the nudge and upgrade handoff instruct the agent to use a
      separate Git worktree unless the user explicitly requests otherwise. The
      handoff directs upgrade commands to the app’s corresponding directory in
      that worktree. Update the existing prompt assertions and snapshots to
      match.
      
      <!-- NEXT_JS_LLM -->
      ccbd0cb5
    • Jiwon Choi's avatar
      Improve agent upgrade failure message for missing app (#99117) · ae91b476
      Jiwon Choi authored
      ### Why?
      
      The missing-app error tells users to pass an app path without showing
      where it belongs in the command.
      
      ### How?
      
      Add `next upgrade [directory] --ai=<supplied value>` to the error,
      preserving the supplied AI upgrade type or bare `--ai` so users can
      retry with an explicit directory.
      
      <!-- NEXT_JS_LLM -->
      ae91b476
    • Hendrik Liebau's avatar
      Preserve error boundaries in on-demand partial prerenders (#99051) · f4a68604
      Hendrik Liebau authored
      An on-demand prerender failure still throws when its recovery output
      requires a resume. This hides the route's error boundary behind a
      generic error response, even when healthy parts of the page could
      continue rendering.
      
      Failures now retain their original error and serialized postponed state.
      Self-hosted servers append a separate continuation for each document
      request. Adapter deployments use the existing platform transport to
      resume with the actual request.
      
      In `next start`, a failed partial prerender follows the same prerender
      and resume flow as a successful PPR cache miss. Failed preludes are not
      persisted, so later independent requests retry prerendering before
      resuming. Concurrent requests can share the pending prerender, and each
      document request owns its resume.
      
      The response retains status 500 and non-cacheable headers. Failed output
      is not persisted as a successful ISR entry. Build failures and recovery
      without a usable Flight result continue to throw.
      
      The tests cover errors inside and outside Suspense, request-specific
      dynamic content, navigation after failed prefetches, same-URL recovery,
      successful-page retention, and original-error reporting.
      f4a68604
    • Hendrik Liebau's avatar
      Preserve error boundaries during on-demand prerendering (#99037) · c54cc098
      Hendrik Liebau authored
      In production, an error while generating an App Router page on demand
      can return a generic 500 response or a Pages Router 500 page instead of
      the route's `error.tsx` or `global-error.tsx`. This affects dynamic
      routes using `generateStaticParams`, even though their error boundaries
      work in development.
      
      A completed prerender failure now carries its error and recovery output
      through the renderer and response cache as an explicit result. The
      response cache retains completed failures within each platform
      invocation, without changing existing in-flight batching. Failed output
      is not persisted as a successful ISR entry. The server sends recovered
      documents with status 500 and non-cacheable headers. Failed RSC
      responses have empty bodies; navigation falls back to loading the
      document. Build failures and incomplete recovery continue to throw.
      Asynchronous error reporting runs in the background and uses the
      platform's `waitUntil` when available.
      
      Recovery that requires resuming a partially prerendered page is out of
      scope for this PR and continues to throw. A follow-up PR will preserve
      and resume that partial recovery output.
      
      The fix applies to self-hosted production servers and adapter-based
      Vercel deployments. The legacy Vercel deployment path retains its
      existing behavior of replacing the response with a generic error page.
      
      The tests cover both Cache Components settings, batched invocation
      failures, pending I/O inside Suspense, same-URL recovery,
      successful-page retention, and original-error reporting.
      
      Fixes #62046
      c54cc098
    • Tobias Koppers's avatar
      docs: clarify Turbopack ModulePart export examples (#99104) · f8ae35c2
      Tobias Koppers authored
      ## Summary
      
      Clarify the examples for `ModulePart::Export` and `ModulePart::Exports`
      so they illustrate the export declarations those parts represent, rather
      than the importing site or a single-export case.
      
      This follows two late review suggestions on the already-merged #96396:
      [named
      export](https://github.com/vercel/next.js/pull/96396#discussion_r4082789388)
      and [export
      declarations](https://github.com/vercel/next.js/pull/96396#discussion_r4082794496).
      No behavior changes.
      
      ## Verification
      
      - `cargo fmt --all -- --check` (from `turbopack/`)
      - `git diff --check`
      - Confirmed the diff changes only two Rust doc-comment lines.
      
      <!-- NEXT_JS_LLM -->
      
      
      <!-- fleet 993ef5d6-cc80-4082-8e14-ff9ac871ce33 -->
      Co-authored-by: 's avatarvercel-fleet-prod[bot] <318278635+vercel-fleet-prod[bot]@users.noreply.github.com>
      Co-authored-by: 's avatarTobias Koppers <1365881+sokra@users.noreply.github.com>
      Co-authored-by: 's avatarLuke Sandberg <210140+lukesandberg@users.noreply.github.com>
      f8ae35c2
    • Luke Sandberg's avatar
      Add some more verification and safety rules around custom `distDir` (#98997) · 8fab0b4b
      Luke Sandberg authored
      ### What?
      next will delete some or all of the contents of `distDir` on start
      depending on mode. This is normally fine for the default `.next/` dir
      but for a user specified one it can be dangerous if it is misconfigured.
      
      Add some safety checks that the directory is in a valid location
      
      I explored enforcing that the specified directory was either empty,
      missing or filled only with files from a prior build/dev session, but
      this is very ambiguous and would add a speed bump to upgrade paths.
      
      re-compatibility: This PR is enforcing a constraint that wasn't
      previously enforced. In the error case we are addressing (setting dist
      dir to be the workspace root or appliction root), this is not considered
      breaking because all such uses would be catastrophic (application files
      deleted). The other enforcement is that the dist-dir is fully
      _contained_, this was always strictly enforced for turbopack but for
      webpack it would only fail later during dev-serving or SSG. So this is
      just making an obscure error more eager and consistent.
      
      Fixes #98958
      
      ---------
      Co-authored-by: 's avatarClaude Opus 5 (1M context) <noreply@anthropic.com>
      Co-authored-by: 's avatarvercel-fleet-prod[bot] <318278635+vercel-fleet-prod[bot]@users.noreply.github.com>
      Co-authored-by: 's avatarLuke Sandberg <210140+lukesandberg@users.noreply.github.com>
      Co-authored-by: 's avatarTobias Koppers <1365881+sokra@users.noreply.github.com>
      8fab0b4b
    • Josh Story's avatar
      Preserve closed-route admission across cache misses (#98964) · 851b6cb0
      Josh Story authored
      ## Summary
      
      Keep route admission independent of ISR cache contents. With Cache
      Components disabled, a route using `dynamicParams = false` and
      `generateStaticParams()` can currently return 200 for a build-generated
      URL, then incorrectly return 404 after `revalidatePath` expires its
      cache entry. An empty external cache causes the same failure on the
      first request.
      
      For example, if the build generated `/products/known`, that URL remains
      allowed after invalidation; `/products/unlisted` remains disallowed
      regardless of cache state. If a later build removes `/products/known`,
      it must immediately stop matching, even if an external cache still holds
      that URL's old response.
      
      The request handler now rejects unlisted closed URLs before looking up
      their ISR entries. This prevents both serving an old cache hit and
      generating a new response for a URL the current build does not admit. An
      admitted build path whose matched fallback is `false` regenerates using
      a blocking render when necessary.
      
      The two decisions stay separate: the manifest determines whether the URL
      may match, while the response generator chooses how to produce an
      admitted response. We do not share mutable fallback-mode state between
      those stages.
      
      ### Preserved exceptions and adapter behavior
      
      - **Server Actions:** forwarding can invoke a worker at
      `/products/[slug]`, not a concrete page URL. Action calls retain their
      existing exemption from page admission checks. A retained action must
      still work after the user navigates away from its closed route.
      - **Draft mode:** an unpublished URL can be previewed without admitting
      it publicly or replacing its public cache entry.
      - **Minimal mode:** the platform router remains responsible for
      admission before invoking the renderer.
      - **Adapters:** rendering a routing 404 now happens outside the response
      cache. The previous placement could successfully send a 404 and then
      throw `cache entry required but not generated` because it returned no
      cache entry for a non-null cache key. The new adapter fixture reproduces
      this on the parent runtime.
      
      This uses the existing prerender manifest and does not change its format
      or the adapter contract. The most specific matched dynamic route
      continues to determine the policy for open URLs, so specialized matchers
      can admit an open suffix without admitting an unknown closed prefix.
      
      ## Regression coverage
      
      Real fixtures cover:
      
      - Repeated invalidation, ordinary and optional catch-all paths,
      time-based ISR, concurrent regeneration, and serving a stale response
      while regenerating in the background.
      - Empty external caches and an external cache retained across two real
      builds. The latter verifies that the removed path's old entry still
      exists but is never consulted.
      - Document, HEAD, navigation, prefetch, bot, rewritten, and
      overlapping-route requests.
      - Direct and forwarded Server Actions, draft previews, and direct
      minimal-mode renderer invocations.
      - Adapter-specific 404 handling and regeneration of admitted paths.
      - The distinction between routing rejection and content that calls
      `notFound()`: an admitted URL can transition from 200 to 404 and back,
      including when its build render returned 404.
      
      These legacy `dynamicParams` fixtures are excluded from the Cache
      Components matrix because that configuration does not support the API.
      
      ## Stack
      
      This is an unflagged correctness fix, placed after #98950 and before the
      parameter-matching API in #97393. It can land without committing to that
      API. The API's mixed-prefix and dynamic-tail lifecycle coverage belongs
      in the API layer.
      
      ## Verification
      
      - Before the original fix, the two initial regression fixtures failed 11
      checks while the open-route and time-based controls passed.
      - Against the parent runtime, the new adapter fixture reproduces the
      cache-entry invariant on document, navigation, prefetch, and bot
      requests, plus the invalidation regression.
      - The retained Server Action regression passes on the parent runtime,
      fails on the earlier PR revision without the exemption, and passes with
      the explicit action exemption. It also passes in development with the
      exemption.
      - Local production runs before replaying the follow-up onto the rebased
      stack: all 49 tests across seven suites pass in both Webpack and
      fresh-native Turbopack, including the existing closed-parameter
      navigation suite. The follow-up patch applied unchanged; CI will verify
      the rebased head.
      - Development Turbopack request-mode coverage: 10 passed; the
      public-cache reuse assertion is production-only.
      - Repository TypeScript, Next.js declaration generation, changed-file
      formatting/ESLint, and `git diff --check` pass.
      
      No live deployment verification. A separate `revalidate-if-generated`
      hang with an always-empty custom cache reproduces on both this PR and
      its parent; its diagnostic is retained for a separate follow-up, not
      included or silently skipped here.
      
      <!-- NEXT_JS_LLM -->
      851b6cb0
    • Jimmy Miller's avatar
      Move suspension into operation guard (#99053) · 82dd6d6d
      Jimmy Miller authored
      So in some testing I found a rare error where a child task could take
      the suspend point, causing it to decrement the counter even though it
      hadn't incremented it. Move this operation to the guard makes this not
      impossible (you can still just grab the coordinator) but at least in
      this code path makes it unlikely you do this. It fixes the bug I found.
      Discussed this with Luke. We agreed trying to recreate the case in a
      unit test would probably be a bit overkill.
      82dd6d6d
    • Aurora Scharff's avatar
      [agent-feedback] Shorten managed agent instructions (#99065) · 0c129d01
      Aurora Scharff authored
      ## Summary
      
      - reduce the managed agent-feedback block from 199 to 160 words while
      restoring four scannable issue-category bullets
      - explicitly authorize the feedback pass without coupling it to
      `agentRules`
      - explain that `next dev` restores the managed block and that committing
      `AGENTS.md` keeps the tree clean
      - preserve the network-sandbox retry and tell agents to read the command
      output once without piping or truncating it
      - clarify that prepared reports remain in a browser URL fragment until
      the user submits them
      - keep the AI agents guide, API reference, focused integration coverage,
      and eval fixtures in sync
      - restore the `CLAUDE.md` compatibility import inside eval sandboxes
      only, without generating it for users
      - replace subjective feedback transcript judges with deterministic
      source and report-payload checks
      
      The existing `agentRules` managed block is unchanged.
      
      ## Eval results
      
      | Eval | Existing instructions | Shortened instructions |
      | --- | --- | --- |
      | Routine debugging | 10/10 passed in #98887 | Earlier runs produced no
      reports; a post-harness-fix rerun is pending |
      | Anonymization | 2/2 reporting checks passed in #98887 | The
      post-harness-fix rerun reached AI Gateway timeouts; deterministic schema
      and redaction checks are in place |
      | Distinct issues | 1/1 passed in #98887 | The post-harness-fix run
      produced two distinct valid reports; both deterministic report checks
      passed |
      
      The historical results come from #98887. The shortened-instruction runs
      use the same private `agent-feedback` treatment and are not published to
      nextjs.org/evals. The fixtures explicitly enable
      `experimental.agentFeedback`, matching the production opt-in.
      
      The previous transcript judges mixed feature behavior with subjective
      judgments about browser-opening attempts. The fixtures now check the
      actual product outcomes directly: routine work produces no report, a
      qualifying issue produces one valid anonymized report, and distinct
      issues produce separate valid reports.
      
      ## Verification
      
      - `pnpm testonly
      packages/next/src/server/lib/generate-agent-files.test.ts` (10/10
      passed)
      - `NEXT_SKIP_ISOLATE=1 HEADLESS=true pnpm test-dev-turbo
      test/development/app-dir/agent-rules-auto-generate/agent-rules-auto-generate.test.ts`
      (12/12 passed)
      - eval fixture dry-runs for `agent-057-agent-feedback-anonymization` and
      `agent-058-agent-feedback-distinct-issues`
      - targeted Prettier and ESLint through the pre-commit hook
      
      <!-- NEXT_JS_LLM -->
      0c129d01
    • Aurora Scharff's avatar
      docs: clarify Cache Components build output (#98274) · 12f85871
      Aurora Scharff authored
      ## Summary
      
      - Clarify that Cache Components uses PPR for every App Router page,
      including pages whose build-time HTML is empty.
      - Explain that the current tree-view symbols describe output rather than
      a different rendering model: an empty PPR HTML output can show `ƒ` at a
      fixed pathname or `◐` on a dynamic-path fallback row.
      - Clarify that Cache Components pages do not use `●`; generated paths
      from `generateStaticParams` show `○` or `◐` based on their HTML output.
      - Clarify that `instant = false` opts out of instant-navigation
      validation and, when it is the highest config, static-shell validation
      without changing the PPR rendering model.
      - Keep the guide's existing structure and examples while correcting
      factual wording about TypeScript checking, `generateStaticParams`,
      Partial Prefetching, cache lifetime output, and build debugging.
      - Remove signposting, filler, and unverified claims in the sections
      being corrected.
      
      ## Verification
      
      - `pnpm prettier --with-node-modules --ignore-path .prettierignore
      --check docs/01-app/02-guides/building.mdx`
      - `npx eslint --config eslint.config.mjs
      docs/01-app/02-guides/building.mdx`
      - `git diff --check`
      - Verified with `cacheComponents: true` that a fixed page covered by
      `instant = false` prints `ƒ`, writes 0-byte HTML, and remains
      `PARTIALLY_STATIC` in the prerender manifest. Removing the opt-out
      produces the expected prerender-blocking error.
      - Verified that a Cache Components route using `generateStaticParams`
      prints an unmarked route group, a `◐` fallback, and a `○` generated
      pathname without any `●` row.
      - Verified `instant = false` with synchronous runtime values and
      `--debug-prerender` source frames against a minimal Cache Components app
      using the local Next.js package and webpack.
      - Not run: `pnpm lint` (docs-only change; focused formatting, ESLint,
      and runtime checks passed).
      
      <!-- NEXT_JS_LLM -->
      12f85871
    • Tobias Koppers's avatar
      Update Rust namespace re-export snapshots (#99106) · 8ff7f2bd
      Tobias Koppers authored
      ### What?
      
      Update the generated JavaScript and source-map snapshots for the
      Turbopack namespace-value re-export named-import fixture.
      
      ### Why?
      
      Canary's Rust unit job fails because the checked-in fixture expects an
      obsolete export-registration sequence. The current generated output
      omits that redundant sequence, shifting the source-map mapping for the
      entry point.
      
      ### How?
      
      Regenerate both outputs together so the source map describes the
      JavaScript Turbopack actually emits. The fixture continues to exercise
      the named namespace imports and their referenced members; no runtime or
      generator behavior changes.
      
      ### Verification
      
      - Focused `turbopack-tests::snapshot` test passed twice in the default
      profile and once with CI's `release-with-assertions` profile.
      - Full Rust unit suite not run locally; PR CI will run it.
      
      <!-- NEXT_JS_LLM -->
      
      
      <!-- fleet 141f2d4f-ccec-4c7c-a4ac-fd0bb00bdc73 -->
      Co-authored-by: 's avatarvercel-fleet-prod[bot] <318278635+vercel-fleet-prod[bot]@users.noreply.github.com>
      Co-authored-by: 's avatarTobias Koppers <1365881+sokra@users.noreply.github.com>
      8ff7f2bd
    • next-js-bot[bot]'s avatar
      v16.4.0-canary.40 · c9b90452
      next-js-bot[bot] authored
      c9b90452
    • Josh Story's avatar
      Keep cached root parameters out of generic fallback shells (#98950) · 2d895935
      Josh Story authored
      ## Summary
      
      Replace #98892 with a fix for both ways root-dependent content can enter
      a generic fallback shell: reusing an existing Resume Data Cache entry
      and executing a fresh cache fill.
      
      For example, cached English content produced for `/en/items/one` remains
      reusable in `/en/items/[slug]`, but must be absent from
      `/[lang]/items/[slug]`. When reusing that concrete prerender as a seed,
      clone its cache map and replace entries whose recorded
      `readRootParamNames` intersect the unknown roots with omission markers.
      The original seed is unchanged.
      
      Keep those markers in the cache map itself, not a separate collection
      that must stay synchronized. They carry the reason for a hole between
      prerender passes and are never serialized into the persisted RDC.
      Preserve canary's distinction between URL data and session data when
      computing shell and prefetch hints.
      
      For fresh fills, an unknown root read suspends the entire cache
      invocation, including cached components with an internal Suspense
      boundary. Affected nested caches use independently cancellable
      prerenders. Dependencies propagate through consumers without cancelling
      independent sibling fills or saving aborted partial results.
      
      A top-level caller joining a nested cache fill must also record the
      omission marker: the nested leader has no RDC of its own. Otherwise the
      final prerender sees an unexplained miss and loses the fallback's
      prefetch hint. This applies to intra-request joins as well as
      cross-request joins.
      
      This is prerequisite work for configurable root fallbacks in #97393.
      Without the new API, ordinary misses for root parameters still block.
      The prerequisite fixture inspects ordinary build artifacts and document
      requests; the API fixtures exercise fresh fills through real fallback
      requests and tag invalidation. Neither uses forced rendering or
      shell-debugging hooks.
      
      ## Verification
      
      - Prerequisite root-cache fixture: five production tests pass with both
      Webpack and freshly built Turbopack.
      - API root-cache isolation and root-parameter fixtures: eleven
      production tests pass with each bundler. Fourteen closed-route
      revalidation tests also pass with Webpack after restacking.
      - The new nested-leader/top-level-join regression fails without the
      marker write with the reported unexpected-cache-miss warning, and passes
      with the write. Data-service barriers determine the ordering; no timing
      sleeps or framework test hooks are used.
      - Existing runtime prerender cache-warming coverage: eight Webpack tests
      pass, including cached pages that await params/searchParams.
      - The three focused unit suites pass together: 114 tests on this
      prerequisite and 128 on the API layer, with four snapshots each. The
      postponed-state assertion no longer snapshots Node's incidental
      async-hooks fields on promises.
      - Full workspace/native builds and package/repository type checks pass.
      - Deployment tests were not run locally for this update.
      
      <!-- NEXT_JS_LLM -->
      2d895935
    • Hendrik Liebau's avatar
      Fix missing content in Cached Navigations (#98767) · ec0abf41
      Hendrik Liebau authored
      React can render outlined elements in later `setImmediate` callbacks
      after an asynchronous cache read resolves. `cacheReady()` can resolve
      before those elements start their cached reads. The embedded prerender
      for Cached Navigations then reports unexpected cache misses and omits
      cacheable content.
      
      This change tracks pending native immediates in an `AsyncLocalStorage`
      scope around each Cache Components render. `CacheSignal` waits for that
      work before accepting a zero read count. If more native immediates
      appear before the readiness timer runs, it waits and checks again.
      Tracking does not make native immediates fast or change the existing
      explicit, task-local fast-immediate behavior.
      
      The e2e regression uses a delayed cache handler and a large outlined
      tree. It verifies that Cached Navigations reuse outlined content while
      content behind dynamic I/O remains uncached. Each test invocation uses a
      fresh cache key through `searchParams`, so cases and retries cannot
      reuse previously warmed entries.
      
      Unit tests in the existing immediates suite cover scope isolation,
      nested scheduling, cancellation, native scheduling semantics, and error
      recovery.
      
      Fixes #98543
      ec0abf41
    • Sam Poder's avatar
      [turbopack] Track members across namespace re-exports (#96396) · b1c15da6
      Sam Poder authored
      ## What?
      
      This PR closes a missed tree-shaking opportunity for libraries that
      expose a module namespace as a named export. One real-world example is
      Zod, whose public API has a structure similar to the following (and this
      pattern also appears in v0's codebase):
      
      ```js
      // user.js
      import { z } from './lib.js'
      
      console.log(z.object(), z.string(), z.defaultLocale)
      ```
      
      ```js
      // lib.js — mirrors zod/index.js
      import * as z from './external.js'
      
      export * from './external.js'
      export { z }
      export default z
      
      // external.js — mirrors zod/v4/classic/external.js
      import en from './locales/en.js'
      
      export * as locales from './locales/index.js'
      
      export const object = () => 'object'
      export const string = () => 'string'
      export const defaultLocale = en
      ```
      
      The analyzer can now preserve the information that only `object`,
      `string`, and `defaultLocale` are read from `z`, and use it after
      resolving that named export to the namespace of `external.js`.
      
      This PR is now standalone on `canary`. Its two former prerequisites have
      landed: #98680 introduced the independently reviewed
      `EsmAssetReferenceOptions` constructor refactor, and #96282 integrated
      CommonJS and ESM whole-namespace forwarding with canary's generic
      `ExportUsage::Passthrough` fixed point.
      
      ## Why?
      
      Previously, Turbopack knew that the named export `z` was used, but lost
      the static member information from expressions such as `z.object()`.
      Once `z` resolved to a namespace object, the optimizer therefore kept
      every export of `external.js` — including `locales` and all of
      `./locales/index.js` in this example.
      
      The optimization must remain conservative in several cases:
      
      - a computed property whose name cannot be determined statically, such
      as `z[key]`;
      - a namespace binding that escapes to unknown code, such as passing `z`
      to another function;
      - static and opaque uses of the same binding, where the opaque use must
      dominate narrowing;
      - live exports and method calls, whose binding and receiver semantics
      must not change.
      
      It must also avoid changing ordinary named-import behavior. A property
      read on an imported value is not proof that the value is a module
      namespace; narrowing and namespace provenance are valid only after
      re-export resolution proves that fact.
      
      ## How?
      
      ### Represent namespace-member requests explicitly
      
      The module-part model now has explicit states for this operation:
      
      - `ExportedNamespaceMember { export, member }` represents a static
      member read on a named export before re-export resolution;
      - `RenamedNamespaceMember { export, member }` represents the case after
      that export resolves to a module namespace.
      
      This avoids overloading an ordinary `Export` or an optional `member`
      field with two meanings. It also keeps existing `Export` and
      `RenamedNamespace` identities unchanged; the new variants have distinct
      hashes only for the new states.
      
      Multiple static reads and multiple aliases are tracked as independently
      keyed references, so `z.object`, `z.string`, and `z.defaultLocale` all
      survive rather than overwriting one another.
      
      ### Narrow only after proving the export is a namespace
      
      The analyzer records a statically known member on an imported binding
      while leaving the emitted member expression intact. Re-export following
      first resolves the outer named export:
      
      1. If it resolves to a namespace object, Turbopack synthesizes a
      namespace-member reference to the resolved module and contributes
      `PartialNamespaceObject({ member })` there.
      2. If it resolves to an ordinary named export, it continues to behave
      like a normal named read of the outer module. It does not mark the
      module as namespace-observable or unnecessarily disable export-name
      mangling.
      
      Dynamic property access and escaping bindings do not produce a narrowed
      member part, so they continue to retain the full namespace. When static
      and opaque uses are joined, the full-namespace use wins.
      
      The explicit module-part variants are threaded through both fragment and
      non-fragment infrastructure so they remain valid graph identities. The
      new `ExportedNamespaceMember` rewrite itself currently runs only when
      module fragments are disabled. A dedicated `moduleFragmentsEnabled:
      true` fixture verifies the supported existing split behavior without
      claiming that this new rewrite is active there.
      
      While rebasing, canary moved follow-reexport canonicalization into
      `turbopack-ecmascript` so lazy dynamic imports can carry the same
      canonicalization policy. Namespace-member handling now lives in that
      canonicalization helper as well, preserving both the new
      lazy-compilation path and this PR's namespace rewrite.
      
      ## Testing
      
      Enabled coverage includes:
      
      - the Zod-shaped snapshot showing only `object`, `string`, and
      `defaultLocale` retained while the unused locale namespace is removed;
      - multiple static members on one namespace-valued export;
      - dynamic access, escaping use, and mixed static/opaque use retaining
      the full namespace;
      - direct `export * as`, including an enabled used/unused precision
      assertion;
      - computed-string, parenthesized, optional, and missing-property reads;
      - `this`-sensitive method calls;
      - default-exported and renamed namespace values;
      - live bindings read and mutated through multiple aliases, with single
      evaluation;
      - nested namespace runtime behavior and top-level-await targets;
      - scope-hoisted, non-scope-hoisted, and module-fragment configurations;
      - export-name mangling safety and non-pessimization across #96282's
      forwarding edges.
      
      Development coverage updates both a value behind the CommonJS forwarding
      edge and a statically read namespace member, verifying HMR observes each
      new value without stale exports or runtime errors.
      
      One optimization-only limitation is documented under
      `__skipped__/namespace-value-reexport-nested`: member narrowing
      currently stops after the first namespace level for a read such as
      `z.locales.en`. The full nested runtime behavior is covered by the
      enabled `namespace-value-reexport` fixture.
      
      Local verification on the standalone canary rebase passes affected-crate
      and `next-core` checks, 14 focused execution/snapshot tests, the merged
      passthrough/annotation unit tests, 60 analyzer graph tests, `build-all`,
      and the development/HMR test. A throwaway ordinary object-valued
      named-import fixture also verified that the pre-resolution path
      preserves property values and `this` for getters and methods; it was
      removed after review.
      
      <!-- NEXT_JS_LLM -->
      
      
      <!-- fleet 993ef5d6-cc80-4082-8e14-ff9ac871ce33 -->
      Co-authored-by: 's avatarvercel-fleet-prod[bot] <318278635+vercel-fleet-prod[bot]@users.noreply.github.com>
      Co-authored-by: 's avatarTobias Koppers <1365881+sokra@users.noreply.github.com>
      Co-authored-by: 's avatarLuke Sandberg <210140+lukesandberg@users.noreply.github.com>
      b1c15da6
    • Janka Uryga's avatar
      [PPF] Implement `unstable_ensureStatic = "shell" | "prefetch"` (#98191) · 1edced6f
      Janka Uryga authored
      Builds on #98129, where we made it possible for shells to be static
      while the prefetches depending on where runtime data is accessed:
      - `ensureStatic = "shell"` simply defers all runtime tracking until the
      prefetch (semantically, it's as if it was gated by `await prefetch()`).
      this means that the shell will always be considered static (although the
      prefetch can still be runtime)
      - `ensureStatic = "prefetch"` is analogous, but means that the prefetch
      should be static (semantically, it's as if it was gated by `await
      navigation()`). this effectively skips the tracking altogether, and
      *both* the shell and the prefetch will be static.
      - notably, in this mode, accessing fallback params in an ISR fallback no
      longer sets `needsRuntimeRequest` either, because the config disallows
      runtime prefetches, even if it'd let us skip waiting for the ISR
      prerender to finish.
      
      note that "static" here means "statically prerendered", as opposed to
      "rendered on demand via runtime prerender". both options still allow the
      prerender to have dynamic holes. disallowing dynamic holes altogether
      will be handled by `ensureStatic = "navigation"` in a follow up.
      
      ### Implementation notes
      
      i've also renamed `walkNeedsRuntimeCompleteness` to
      `walkCanUseRuntimeRequests` -- in practice, the function checks "is this
      a PPF route", but being PPF no longer means that runtime completeness is
      required, because `ensureStatic` deliberately gets rid of it.
      `walkCanUseRuntimeRequests` is a bit more accurate, because it tells us
      whether runtime requests are possible at all. This change (and the
      associated changes in comments) are in a separate commit for ease of
      review.
      1edced6f
    • Janka Uryga's avatar
      [PPF] Validate `unstable_ensureStatic` nesting (#98357) · 690f1ad8
      Janka Uryga authored
      `ensureStatic` forms a hierarchy: `"auto" < "shell" < "prefetch" <
      "navigation"`, with each value being more contrained than its
      predecessor.
      
      1. A child segment cannot relax constraints set by a parent segment, it
      can only tighten them
      - so `shell` in a layout and `prefetch` in a page is fine, but the
      opposite is not
      - note that setting `"auto"` in the child *is* allowed, because it means
      "unconstrained" and is compatible with all the other configs
      2. We can't have two conflicting levels set by two parallel slots (but
      `auto` is compatible with any other constraint, so it's allowed, same as
      above)
      3. If a segment sets `ensureStatic = false`, then no other segments on
      that route are allowed to constrain the route by setting anything higher
      than `auto` (this is meant as a signal for e.g. "this segment
      DELIBERATELY uses a runtime shell and should not be overridden to be
      static")
      
      Also adds exhaustive tests for all of these scenarios.
      690f1ad8
    • Sebastian "Sebbie" Silbermann's avatar
      Replace lerna task-runner usage with pnpm (#99040) · e09ac7d2
      Sebastian "Sebbie" Silbermann authored
      pnpm solves all the remaining usages of Lerna so we're switching to pnpm
      instead. The goal is to get rid of Lerna.
      e09ac7d2
    • Sebastian "Sebbie" Silbermann's avatar
      [cd] Fix release branch gate and drop dead lerna publish config (#99039) · 2884eb21
      Sebastian "Sebbie" Silbermann authored
      Mostly just updating obsolete/stale information.
      2884eb21
    • Niklas Mischkulnig's avatar
      Turbopack: fix "ModuleId not found for ident" regression (#99090) · 593cec11
      Niklas Mischkulnig authored
      Regression from #98617
      
      Closes #99082
      593cec11
    • Hendrik Liebau's avatar
      Fix private-cache segment reuse across root params (#98810) · 9806642f
      Hendrik Liebau authored
      Private caches only tracked root-param reads in development. Production
      runtime prefetches omitted these dependencies from their vary params
      metadata, allowing the client to reuse content across different
      root-param values.
      
      This extends #98674 to `"use cache: private"`. Private caches now
      collect root-param reads in production and inherit dependencies from
      nested public and private caches. The existing response-level
      propagation can then record those dependencies when it consumes the
      cache entry.
      
      Regression tests cover direct reads, public caches inside private
      caches, and private caches inside private caches. Each case prefetches
      English and German content, then verifies that navigation uses the
      German result without another request.
      9806642f
    • Niklas Mischkulnig's avatar
      Turbopack: fix `Unknown module type` error for imports in webpack loaders (#99088) · 3e4af55d
      Niklas Mischkulnig authored
      Fixes an error like
      ```
      ./node_modules/.pnpm/@esbuild+linux-x64@0.28.1/node_modules/@esbuild/linux-x64/README.md
      Error: Unknown module type
      This module doesn't have an associated type. Use a known file extension, or register a loader for it.
      ```
      
      Regression from https://github.com/vercel/next.js/pull/95732
      3e4af55d
    • Jiwon Choi's avatar
      Nudge humans to adopt Future Defaults (#98874) · 7f79552e
      Jiwon Choi authored
      Stacked on #98873.
      
      Counter part of agent nudge for auto upgrade. Prompt user when runs
      `next dev` or `next build` based on `experimental.agenticAutoUpgrade`
      value. This PR covers `future`.
      7f79552e
    • Jiwon Choi's avatar
      Nudge latest version upgrades for manual `next dev|build` (#98873) · 59a5fae3
      Jiwon Choi authored
      Stacked on #98872.
      
      Counter part of agent nudge for auto upgrade. Prompt user when runs
      `next dev` or `next build` based on `experimental.agenticAutoUpgrade`
      value. This PR covers `latest`.
      59a5fae3
    • Jiwon Choi's avatar
      Nudge security upgrades for manual `next dev|build` (#98872) · 447e018f
      Jiwon Choi authored
      Counter part of agent nudge. Prompt user when runs `next dev` or `next
      build` based on `experimental.agenticAutoUpgrade` value. This PR covers
      `security`.
      447e018f
    • next-js-bot[bot]'s avatar
    • Tobias Koppers's avatar
      refactor(turbo-rcstr): drop unsupported 16-byte pointer width (#98355) · cde6fad2
      Tobias Koppers authored
      ## What?
      
      Removes turbo-rcstr's 16-byte/128-bit pointer representation and the
      unused `atom_size_64` feature plumbing. Unsupported pointer widths now
      fail with an error that names the supported 32-bit and 64-bit widths.
      
      ## Why?
      
      This follows up on review feedback from #97577. The previous negative
      cfg made unknown pointer widths fall through to the 64-bit
      representation, while the 16-bit implementation and `atom_size_64`
      features had no users. Making both supported widths explicit keeps
      representation assumptions visible and produces a useful failure for
      unsupported targets.
      
      ## How?
      
      The narrow tagged-value layout is now specific to 32-bit targets, and
      the pointer-sized layout is specific to 64-bit targets. `atom_size_128`
      remains unchanged. The dead feature declarations are removed from
      turbo-rcstr and its proc-macro crate.
      
      ## Verification
      
      - `cargo test -p turbo-rcstr --lib`
      - `cargo test -p turbo-rcstr --lib --target wasm32-wasip1-threads`
      - `cargo check -p next-napi-bindings`
      - `cargo check -p next-napi-bindings --target wasm32-wasip1-threads`
      - `cargo clippy -p turbo-rcstr -p turbo-rcstr-macros -- -D warnings`
      - `cargo clippy -p turbo-rcstr -p turbo-rcstr-macros --target
      wasm32-wasip1-threads -- -D warnings`
      - `cargo fmt --all -- --check`
      
      <!-- NEXT_JS_LLM -->
      
      <!-- fleet 7cfc7d6e-efc8-4ef3-b81c-b90f71291bb0 -->
      Co-authored-by: 's avatarvercel-fleet-prod[bot] <318278635+vercel-fleet-prod[bot]@users.noreply.github.com>
      Co-authored-by: 's avatarLuke Sandberg <210140+lukesandberg@users.noreply.github.com>
      cde6fad2
    • Tobias Koppers's avatar
      test(turbo-tasks-backend): run the db_versioning tests on wasm (#97901) · d940cd30
      Tobias Koppers authored
      ### What?
      
      Makes `turbo-tasks-backend`'s `db_versioning` tests run on
      `wasm32-wasip1-threads` instead of being
      skipped, by routing temporary-directory creation in tests through a
      small helper that does not depend
      on `std::env::temp_dir()`.
      
      Twelve test instances that were previously skipped now execute on wasm.
      Three related
      `kv_backing_storage` instances remain skipped, but for a different — and
      verified — reason (see below).
      Native behaviour is unchanged: the same tests run exactly as before, and
      nothing is newly skipped there.
      
      The wider WASI suite also exposed an unrelated intermittent stall in
      `test_unbounded_busy_queue_does_not_churn_workers`: passing isolated
      runs finish in about 0.25 seconds,
      while repeated runs can stop making progress indefinitely. That stress
      test is now ignored only on
      WASI, with the observed reason recorded; native coverage remains enabled
      while the underlying
      multi-threaded runtime stall is investigated separately.
      
      ### Why?
      
      These tests were skipped with the reason `no temp directory on WASI`,
      which turned out to be only half
      true. WASI genuinely has no notion of a system temp directory —
      `std::env::temp_dir()` is hard-coded to
      `unsupported()` in `std/sys/paths/wasi.rs`, so it panics regardless of
      `TMPDIR` — but the *filesystem
      itself works fine*. A WASI guest can use any directory the host preopens
      for it.
      
      So the blocker was in how the tests asked for a directory, not in the
      platform. Asking WASI where "temp"
      is fails; creating a directory inside a path the host already granted
      succeeds.
      
      This matters beyond tidiness: skip reasons are the primary record of
      what does and does not work on
      wasm, and an inaccurate one is worse than no reason at all, because it
      makes a fixable problem look like
      a platform limit and quietly discourages anyone from trying.
      
      Fixing it also uncovered the *real* limitation underneath. With temp
      directories working, the three
      `kv_backing_storage` tests get further and hit a genuine platform gap:
      `memmap2` ships `unix.rs`,
      `windows.rs` and a stub for every other target, so `turbo-persistence`
      cannot open a database on WASI
      at all (`Failed to mmap: platform not supported`). Those three are still
      skipped, now with that cause
      recorded instead of the temp-directory one. That is a real, separate
      piece of work — persistent caching
      cannot function on wasm until `turbo-persistence` grows a non-mmap read
      path — and it is now visible
      rather than hidden behind a misleading reason.
      
      ### How?
      
      A single test-only helper owns the platform difference, so the ~11 call
      sites stay identical in shape
      and no test carries its own `cfg`. On native it delegates to
      `tempfile::tempdir()`, preserving today's
      behaviour byte for byte, including having `TempDir` own cleanup. On wasm
      it creates the directory inside
      a preopened path instead of consulting the environment. The helper is
      crate-private and compiled only
      for tests, so it adds nothing to the shipped crate, and it returns
      `tempfile`'s own error type rather
      than erasing it.
      
      Two deliberate choices are worth calling out for review:
      
      - **Every remaining skip is justified by an observed failure**, not by
      inference. Each of the three
      `kv_backing_storage` tests was run individually and traced to
      `memmap2`'s stub before being skipped
      again; the twelve `db_versioning` ones were confirmed to pass. Nothing
      is skipped speculatively.
      - **Skips use `ignore` with a reason rather than `cfg`**, so they appear
      in test output as
      `ignored, <reason>` instead of silently vanishing from the run. That is
      what keeps the count of
      what-doesn't-work-on-wasm honest and reviewable, and it is asserted that
      the native run still has
        zero ignored tests.
      
      The wasm coupling is documented at the helper: it relies on the host
      preopening a directory, which the
      repository's Node wasi test host does. A different runner must provide
      the same, or update the helper.
      
      <!-- NEXT_JS_LLM -->
      
      
      <!-- fleet b6d0486f-97c7-42a7-bdaf-3490774cdec3 -->
      Co-authored-by: 's avatarvercel-fleet-prod[bot] <318278635+vercel-fleet-prod[bot]@users.noreply.github.com>
      Co-authored-by: 's avatarTobias Koppers <1365881+sokra@users.noreply.github.com>
      Co-authored-by: 's avatarLuke Sandberg <210140+lukesandberg@users.noreply.github.com>
      d940cd30
    • Tobias Koppers's avatar
      fix(turbo-tasks): let parking_lot block on wasm instead of panicking (#97860) · a70cf087
      Tobias Koppers authored
      ### What?
      
      Makes `parking_lot` locks actually block on wasm instead of panicking,
      and removes 33 of the 35
      `ignore`s that panic had forced onto the wasm test suites.
      
      ### Why?
      
      `parking_lot_core` picks its thread parker in `thread_parker/mod.rs`.
      The working wasm parker
      (`wasm_atomic.rs`, built on `memory_atomic_wait32` /
      `memory_atomic_notify`) is selected only under
      
      ```
      all(feature = "nightly", target_family = "wasm", target_feature = "atomics")
      ```
      
      Otherwise it falls back to `wasm.rs`, whose `park()` is
      `panic!("Parking not supported on this platform")`.
      `wasm32-wasip1-threads` **does** report
      `target_feature = "atomics"`, so the only missing piece was the feature
      — every contended lock
      panicked, which is why so many tests were ignored on wasm.
      
      ### How?
      
      Two changes, and **neither alone is sufficient**:
      
      - bump `parking_lot_core` 0.9.8 → 0.9.12, because 0.9.8's atomic parker
      needs `feature(stdsimd)`,
        removed from Rust long ago;
      - enable `parking_lot`'s `nightly` feature **for wasm targets only** (it
      forwards to
      `parking_lot_core/nightly`). 0.9.12 *still* gates the atomic parker
      behind it, so a bump on its own
        keeps selecting the panicking stub silently.
      
      Verified on the resolved feature graph rather than the manifest —
      `nightly` is present for
      `wasm32-wasip1-threads` and absent for the host.
      
      ### Testing
      
      `contended_mutex_blocks_and_hands_over` is built so it cannot pass
      vacuously: a barrier guarantees the
      waiter actually contends, the waiter must block for a measurable
      interval, and it must observe the
      holder's write. **Negative control**: with the feature removed it fails
      at
      `parking_lot_core-0.9.12/src/thread_parker/wasm.rs:26` with *"Parking
      not supported on this platform"*.
      
      ```
      turbo-tasks          54 pass / 28 ignored  ->  72 pass / 11 ignored
      turbo-tasks-backend  66 pass / 32 ignored  ->  82 pass / 15 ignored
      native                     0 ignored, unchanged
      ```
      
      Two of the old ignores remain, under a different and verified cause:
      their work completes in ~500 ms
      of an 800 ms serial sum, so the parallelism is real, but dropping a
      multi-thread tokio runtime while
      their blocking helpers are still alive deadlocks on wasm. That was
      previously hidden because
      `panic = abort` killed the process at the failing assertion before
      teardown ran. It is fixed in the
      follow-up runtime layer.
      
      Also fixes a latent bug unrelated to wasm:
      `test_parallel_try_for_each_mut` asserted every element was
      incremented, which only holds when the chunk size is 1. Chunking comes
      from
      `available_parallelism() * 4` and each chunk stops at its first error,
      so with parallelism 1 the chunk
      size is 2 and every second item is skipped — it would fail on any
      single-core machine. It now asserts
      the parallelism-independent contract.
      
      
      <!-- fleet b6d0486f-97c7-42a7-bdaf-3490774cdec3 -->
      Co-authored-by: 's avatarvercel-fleet-prod[bot] <318278635+vercel-fleet-prod[bot]@users.noreply.github.com>
      a70cf087
    • Tobias Koppers's avatar
      test(turbo-tasks): run the wasm tests with a Node wasi host (#97789) · 4811e49e
      Tobias Koppers authored
      ### What?
      
      Adds a Node host so `wasm32-wasip1-threads` test binaries can run, and
      wires the `turbo-rcstr`, `turbo-tasks`, and `turbo-tasks-backend`
      library tests into the WASI CI job.
      
      It also provides the WASI allocation symbols expected by the `lz4-sys`
      dependency introduced by the base PR, allowing those test binaries to
      link.
      
      ### Why?
      
      The Rust test binaries require host functionality that stock WASI
      runners do not provide. Turbopack stores its link-time task registries
      in WebAssembly custom sections and imports a host callback to read them.
      Its multithreaded runtime also requires shared memory and thread
      spawning through Node Workers.
      
      The base PR replaces `lzzzz` with `lz4`. `lz4-sys 1.11.1` compiles its C
      sources against custom allocation shims on `wasm32-wasi*`, but excludes
      the Rust implementations when the target OS is WASI. Without equivalent
      symbols supplied by the consuming crate, test links fail on unresolved
      malloc, calloc, and free shims.
      
      Running these suites in CI gives the remaining WASI layers direct
      regression coverage instead of relying on native-only tests.
      
      ### How?
      
      The Node cargo target runner provides WASI preview1, imported shared
      memory, and the complete two-phase [`link-section` custom-section
      protocol](https://github.com/mmastrac/linktime/blob/ae29e51d94a955df2442ed6418b8a712c1f2bfb3/link-section/docs/PREAMBLE.md#wasm).
      
      
      [`@emnapi/wasi-threads`](https://github.com/toyobayashi/emnapi/tree/main/packages/wasi-threads)
      supplies Worker lifecycle, compiled-module transfer, load/start
      ordering, and cleanup for the
      [`wasi.thread-spawn`](https://github.com/WebAssembly/wasi-threads)
      import that Node's WASI runtime does not provide. The module is compiled
      once, then the structured-cloneable `WebAssembly.Module` and shared
      memory are sent to Workers. A small adapter around the package's
      lower-level `ThreadManager` and `ThreadMessageHandler` APIs preserves
      Rust's original one-argument ABI: the high-level `WASIThreads` wrapper
      requires guest `malloc`/`free` exports for that ABI, and Rust test
      binaries do not export them. Worker identifiers come from a shared
      atomic counter because Tokio Workers can spawn additional Workers while
      the main WebAssembly thread is parked.
      
      On WASI, `turbo-persistence` supplies the three allocation symbols
      required by liblz4 and forwards them to WASI libc, keeping allocation
      and deallocation within the same allocator. Native builds do not compile
      these wrappers.
      
      Tests that depend on unavailable platform behavior remain visible as
      WASI-only ignored tests with explicit reasons. Native runs keep the full
      test set enabled. A following stacked PR replaces the unsupported
      `parking_lot` parker and re-enables the corresponding contention tests.
      
      The workflow installs and builds the workspace before running the host
      because both the package dependency and compiled production support used
      by a later stack layer must be available.
      
      ### Verification
      
      - Node 20 host unit tests: 9/9
      - Exact combined WASI CI command: `turbo-rcstr` 12 passed / 1 ignored;
      `turbo-tasks` 68 / 44; `turbo-tasks-backend` 65 / 35
      - Full 111-test `turbo-tasks` binary through the package-managed host:
      95 passed / 16 ignored
      - No Worker-side `WebAssembly.compile`; the compiled module is
      transferred by `ThreadManager`
      - `pnpm install --lockfile-only --offline` with a frozen lockfile
      
      <!-- NEXT_JS_LLM -->
      
      <!-- fleet b6d0486f-97c7-42a7-bdaf-3490774cdec3 -->
      Co-authored-by: 's avatarvercel-fleet-prod[bot] <318278635+vercel-fleet-prod[bot]@users.noreply.github.com>
      Co-authored-by: 's avatarLuke Sandberg <210140+lukesandberg@users.noreply.github.com>
      Co-authored-by: 's avatarTobias Koppers <1365881+sokra@users.noreply.github.com>
      4811e49e
    • Sebastian "Sebbie" Silbermann's avatar
    • Hendrik Liebau's avatar
      [test] Add fallback param deployment regression coverage (#98883) · 3874b55d
      Hendrik Liebau authored
      Add permanent end-to-end regression coverage for omitted optional
      catch-all route parameters with the Vercel adapter. The fix in
      nextjs/adapter-vercel#126 is now released in the Vercel CLI; these tests
      keep the behavior covered in Next.js.
      
      The fixtures exercise `/[locale]/[[...filterSlugs]]` at `/en` during bot
      and draft-mode prerender bypasses and a fetch action. They also check
      optional route parameters alongside query parameters, draft-mode Cached
      Navigations, and locale data requests. This PR adds tests and fixtures
      without changing Next.js runtime behavior.
      3874b55d
    • Tobias Koppers's avatar
      Turbopack: mangle exports behind an escaping namespace via the facade (#97770) · 8b067039
      Tobias Koppers authored
      ### What?
      
      Allows Turbopack to keep mangling a module's internal export keys when
      its namespace object escapes. A facade preserves the original public
      names while forwarding each one to the mangled key in the locals module,
      matching webpack's materialized-namespace behavior.
      
      This PR is stacked on #98617. That lower PR now owns the generic
      synthetic-facade compact registration, including empty evaluation
      groups, descriptor reuse, scope-hoisted factories, pruned references,
      and cycle/async fallbacks. This PR creates those facades for escaping
      namespaces, so the generic path is exercised at scale here.
      
      ### Why?
      
      A namespace import or dynamic import whose reads cannot be enumerated
      currently disables mangling for the entire target module. That makes one
      broad consumer lose the size benefit for every otherwise-static consumer
      of the module.
      
      Materializing the original namespace surface keeps ESM semantics intact
      — including live values and `Object.keys()` — while allowing internal
      consumers to use shorter names.
      
      ### How?
      
      The facade's synthesized per-export references participate in the module
      graph, so named usage propagates to the locals module. Its structural
      locals edge carries evaluation usage only, while each forwarded name
      carries its own export usage. Part-reference code generation also honors
      references pruned by the graph, matching ordinary ESM references.
      
      Modules with no exports are not split, async modules retain the existing
      path, and real export-cycle circuit breakers avoid compact registration
      because they require their getters to be visible before imports run.
      Namespace grouping includes the SWC syntax context so scope-hoisted
      modules cannot accidentally share the wrong generated binding.
      
      ### Testing
      
      - `cargo test -p turbopack-ecmascript -p turbopack-tests` — **590 unit,
      303 execution, 3 auxiliary, and 131 snapshot tests passed** on the
      current stack
      - `cargo clippy -p turbopack-ecmascript -p turbopack-core -- -D
      warnings`
      - `cargo fmt --all -- --check`
      - `pnpm test-dev-experimental-turbo
      test/development/app-dir/lazy-dynamic-imports/lazy-dynamic-imports.test.ts`
      — 9/9 passed
      - `pnpm test-dev
      test/e2e/app-dir/instant-validation/suspense-boundaries.test.ts` — 38/38
      passed
      - `pnpm test-start-turbo
      test/production/app-dir/barrel-optimization/mui/index.test.ts` — 1/1
      passed
      - `pnpm test-start-turbo
      test/e2e/app-dir/cache-components-allow-otel-spans/cache-components-allow-otel-spans.test.ts`
      — 4/4 passed
      - `pnpm test-start-turbo
      test/e2e/404-page-custom-error/404-page-custom-error.test.ts
      test/e2e/app-dir/app-esm-js/index.test.ts
      test/e2e/app-dir/app-esm-js/standalone.test.ts` — 9/9 passed
      - Existing materialized-namespace fixtures verify namespace values, key
      enumeration, dynamic imports, CommonJS consumers, and liveness through
      the locals module
      - A callable CommonJS namespace fixture regression-tests the compact
      registration path after facade materialization
      - The full execution suite specifically caught and now covers pruned
      locals references and merged evaluation-only locals references in the
      generic #98617 implementation
      
      ### Bundle-size measurements
      
      Incremental effect of enabling `turbopackMangleExportNames` on this
      stack. Both sides use the same native binary and retain #98617's compact
      re-export registration; only mangling is toggled. Client reports raw and
      deterministic gzip (`gzip -9 -n`, sorted files); server reports raw only
      because Node.js consumes server code uncompressed. JavaScript files
      only; source maps, CSS, and license sidecars are excluded.
      
      #### Scope hoisting disabled
      
      | benchmark | client raw | client gzip | server raw |
      | --- | ---: | ---: | ---: |
      | `basic-app` | −17,380 B | −1,131 B | −61,155 B |
      | `heavy-npm-deps` *(three-dependency variant: lodash + Mantine +
      Mermaid)* | −47,537 B | −6,720 B | −82,326 B |
      | `module-cost` | −223,816 B | −2,113 B | −596,419 B |
      
      #### Scope hoisting enabled
      
      | benchmark | client raw | client gzip | server raw |
      | --- | ---: | ---: | ---: |
      | `basic-app` | −22,658 B | −7,634 B | −32,805 B |
      | `heavy-npm-deps` *(three-dependency variant: lodash + Mantine +
      Mermaid)* | −14,118 B | +1,291 B | −20,956 B |
      | `module-cost` | +30 B | −785 B | −7,265 B |
      
      The `heavy-npm-deps` rows use a modified benchmark fixture with Mantine
      and Mermaid enabled alongside lodash; the committed fixture enables
      lodash only. Positive/near-zero configurations were repeated and
      reproduced byte-for-byte for every reported metric.
      
      <!-- NEXT_JS_LLM -->
      
      <!-- fleet ecdfa248-cd54-41ac-b4a2-c9d49e2a67ee -->
      
      ---------
      Co-authored-by: 's avatarvercel-fleet-prod[bot] <318278635+vercel-fleet-prod[bot]@users.noreply.github.com>
      Co-authored-by: 's avatarTobias Koppers <1365881+sokra@users.noreply.github.com>
      Co-authored-by: 's avatarLuke Sandberg <210140+lukesandberg@users.noreply.github.com>
      8b067039
    • Tobias Koppers's avatar
      test(dev): add dedicated compiler polling coverage (#97673) · e2e19c48
      Tobias Koppers authored
      ### What?
      
      Adds a dedicated development integration test for compiler file watching
      in polling mode under both webpack and Turbopack.
      
      It also removes obsolete `CHOKIDAR_USEPOLLING` / `CHOKIDAR_INTERVAL`
      variables from the unrelated `read-only-source-hmr` suite, which remains
      focused on read-only source semantics and normal watcher behavior.
      
      Stack: **5/5** · Previous: #98737
      
      ### Why?
      
      Next.js did not have an e2e/development test dedicated to
      `watchOptions.pollIntervalMs`. Existing Rust coverage checks watcher
      modes, while the filesystem-watcher fuzzer is manual rather than part of
      the normal development-test matrix.
      
      The test also regresses notify-rs/notify#981. Older PollWatcher versions
      stored ordinary-file mtimes at whole-second precision, so a second edit
      in the same second compared equal and was permanently dropped. The
      preceding stack layer upgrades to `notify 9.0.0-rc.5`, which preserves
      nanosecond precision for regular files without content hashing.
      
      ### How?
      
      The dedicated pages-directory fixture configures only
      `watchOptions.pollIntervalMs`:
      
      - webpack maps it to compiler `watchOptions.poll`;
      - Turbopack passes it to notify and selects PollWatcher.
      
      It intentionally does not set `WATCHPACK_POLLING`, create/delete routes,
      or test the dev-server route watcher, keeping the test focused on
      compiler-level polling.
      
      The test writes two versions of an already-loaded page with controlled
      mtimes at +100 ms and +200 ms inside the same future whole second. It
      waits for the first HMR update before making the second write, requiring
      two distinct watcher events rather than allowing changes to coalesce.
      
      A negative control with the older npm-provided native binary observes
      the first update but permanently misses the second. A fresh local native
      build from the full stack passes both updates. The dedicated test and
      `read-only-source-hmr` pass under both Turbopack and webpack; Prettier
      and ESLint also pass.
      
      <!-- NEXT_JS_LLM -->
      
      
      <!-- fleet 6488265d-2685-49d3-b632-6511b4b47690 -->
      Co-authored-by: 's avatarvercel-fleet-prod[bot] <318278635+vercel-fleet-prod[bot]@users.noreply.github.com>
      Co-authored-by: 's avatarTobias Koppers <1365881+sokra@users.noreply.github.com>
      Co-authored-by: 's avatarBenjamin Woodruff ‮ <180404+bgw@users.noreply.github.com>
      e2e19c48
    • Tobias Koppers's avatar
      build(turbopack): upgrade notify to 9.0.0-rc.5 (#98737) · 57ea96fa
      Tobias Koppers authored
      ### What?
      
      Upgrades the Turbopack filesystem-watcher dependency from `notify 8.1.0`
      to the published `9.0.0-rc.5` release candidate.
      
      Stack: **4/5** · Previous: #98863 · Next: #97673
      
      ### Why?
      
      notify-rs/notify#981 fixes PollWatcher dropping multiple edits to the
      same regular file within one second. The old implementation stored file
      mtimes at whole-second precision; with content hashing disabled, a
      second write in the same second compared equal and produced no event.
      This is the root cause behind #96982.
      
      rc.5 keeps nanosecond mtime precision for ordinary files without
      enabling content hashing. It remains a pre-release, so the pin should be
      revisited when notify 9.0 stable is available.
      
      ### How?
      
      The workspace dependency is pinned to exactly `9.0.0-rc.5`, and Cargo
      regenerates the lockfile. No Rust source compatibility changes are
      required: `turbo-tasks-fs` uses a narrow notify API surface and does not
      rely on removed APIs.
      
      The lockfile update includes notify's current backend dependencies
      across Linux, macOS, and Windows; cross-platform CI remains important
      because local runtime verification is Linux-only.
      
      ### Filesystem-watcher fuzzer impact
      
      The preceding stack layer adds `--poll-interval-ms` to `turbo-tasks-fuzz
      fs-watcher`, which provides a direct before/after control for this
      dependency update. Using a 100 ms polling interval, a 1,000 ms
      observation window, and no directory recreation:
      
      | Fuzzer mode | notify 8.1.0 | notify 9.0.0-rc.5 |
      | --- | --- | --- |
      | `--track-read-writes` | **230/288 iterations had mismatches** over
      five minutes | **0/291 iterations had mismatches** over five minutes |
      | ordinary reads | same-second changes can be missed depending on timing
      | **0 missing invalidations across 295 iterations** over five minutes |
      
      The read/write mode is the strongest comparison: it repeatedly produces
      an external edit after a read-derived write in the same-second window,
      so notify 8 fails consistently while rc.5 remains clean.
      
      Two findings are intentionally unchanged by this PR:
      
      - polling symlink mutations can still be missed within one second
      because rc.5 retains whole-second mtime precision for non-files; the
      fuzzer documents this limitation;
      - directory recreation can produce recoverable `PathNotFound`
      diagnostics while PollWatcher scans deleted subtrees. A 60-second
      resilience run completed 500 iterations with no panic or terminal error.
      
      A fresh native SWC/Turbopack build also passes the upper integration
      suite's rapid subsecond HMR case without timestamp workarounds.
      
      Fixes #96982
      
      <!-- NEXT_JS_LLM -->
      
      
      <!-- fleet 6488265d-2685-49d3-b632-6511b4b47690 -->
      Co-authored-by: 's avatarvercel-fleet-prod[bot] <318278635+vercel-fleet-prod[bot]@users.noreply.github.com>
      Co-authored-by: 's avatarTobias Koppers <1365881+sokra@users.noreply.github.com>
      Co-authored-by: 's avatarBenjamin Woodruff ‮ <180404+bgw@users.noreply.github.com>
      57ea96fa
    • Tobias Koppers's avatar
      test(turbopack): add polling to filesystem watcher fuzzer (#98863) · 946d560a
      Tobias Koppers authored
      ### What?
      
      Adds an opt-in polling mode to the manual `turbo-tasks-fuzz fs-watcher`
      stress harness through `--poll-interval-ms`.
      
      Stack: **3/5** · Previous: #98983 · Next: #98737
      
      ### Why?
      
      The fuzzer previously exercised only native filesystem events. A
      configurable polling mode enables sustained stress testing of
      PollWatcher invalidation behavior and provides a direct before/after
      control for the notify upgrade in the next stack layer.
      
      ### How?
      
      A positive, nonzero interval is mapped to
      `DiskWatcherConfig.poll_interval`; omitting it preserves the
      native-watcher defaults. The fuzzer passes an empty `DiskFileSystemMap`,
      matching the default `DiskFileSystem::new` behavior while using the
      extended constructor needed for watcher configuration.
      
      Manual runs cover ordinary reads, tracked read-derived writes,
      recursive/nonrecursive modes, directory recreation, and native omission.
      CLI help also documents that notify's PollWatcher retains whole-second
      mtime precision for non-files, so multiple symlink changes within one
      second can be missed; this upstream limitation is reported rather than
      hidden with timing workarounds.
      
      <!-- NEXT_JS_LLM -->
      
      
      <!-- fleet 6488265d-2685-49d3-b632-6511b4b47690 -->
      Co-authored-by: 's avatarvercel-fleet-prod[bot] <318278635+vercel-fleet-prod[bot]@users.noreply.github.com>
      Co-authored-by: 's avatarTobias Koppers <1365881+sokra@users.noreply.github.com>
      Co-authored-by: 's avatarBenjamin Woodruff ‮ <180404+bgw@users.noreply.github.com>
      946d560a
    • Tobias Koppers's avatar
      test(turbopack): fix filesystem watcher symlink expectations (#98983) · 4ed2f4f3
      Tobias Koppers authored
      ### What?
      
      Makes the filesystem-watcher fuzzer's expected symlink invalidations
      reflect net target changes over each iteration.
      
      Stack: **2/5** · Previous: #98982 · Next: #98863
      
      ### Why?
      
      Symlink indices are sampled with replacement, so one link may be changed
      multiple times before the dependent task re-reads it. A later mutation
      can restore the iteration-start target. The old expectation retained
      that path after the first intermediate mutation and incorrectly reported
      a missing invalidation even though the task observed no net value
      change.
      
      ### How?
      
      The fuzzer snapshots symlink targets at the iteration boundary and
      removes expected paths whose final target matches the snapshot. All
      unlink/recreate operations and watcher timing remain unchanged; only the
      expected observable result is reconciled.
      
      Behavioural tests cover untouched links, restored targets, repeated
      mutations, and genuine net changes. Five-minute recursive and
      nonrecursive directory-symlink runs complete without missing
      invalidations.
      
      <!-- NEXT_JS_LLM -->
      
      
      <!-- fleet 6488265d-2685-49d3-b632-6511b4b47690 -->
      Co-authored-by: 's avatarvercel-fleet-prod[bot] <318278635+vercel-fleet-prod[bot]@users.noreply.github.com>
      Co-authored-by: 's avatarTobias Koppers <1365881+sokra@users.noreply.github.com>
      Co-authored-by: 's avatarBenjamin Woodruff ‮ <180404+bgw@users.noreply.github.com>
      4ed2f4f3
    • Tobias Koppers's avatar
      test(turbopack): fix filesystem watcher read-write tracking (#98982) · ab6e1f62
      Tobias Koppers authored
      ### What?
      
      Replaces the filesystem-watcher fuzzer's obsolete pure-write tracking
      mode with a tracked read-derived write mode.
      
      Stack: **1/5** · Next: #98983
      
      ### Why?
      
      Pure write effects are no longer watcher dependencies after #92300
      removed write-invalidation tracking and added effect-value
      deduplication. The old fuzzer mode therefore expected behavior the
      runtime intentionally does not provide and reported mismatches on every
      iteration.
      
      ### How?
      
      The new mode reads each regular-file path to establish a real watcher
      dependency, then writes an idempotent value derived from the observed
      external content. An external edit changes the derived effect value, so
      the task reruns without restoring removed product semantics or entering
      a write/invalidation loop. Symlinks remain read-tracked.
      
      The content transformation has focused behavioural tests, and
      recursive/nonrecursive stress runs complete without mismatches.
      
      <!-- NEXT_JS_LLM -->
      
      
      <!-- fleet 6488265d-2685-49d3-b632-6511b4b47690 -->
      Co-authored-by: 's avatarvercel-fleet-prod[bot] <318278635+vercel-fleet-prod[bot]@users.noreply.github.com>
      Co-authored-by: 's avatarTobias Koppers <1365881+sokra@users.noreply.github.com>
      Co-authored-by: 's avatarBenjamin Woodruff ‮ <180404+bgw@users.noreply.github.com>
      ab6e1f62