1. 14 Mar, 2026 14 commits
    • nextjs-bot's avatar
      v16.2.0-canary.99 · 0f599731
      nextjs-bot authored
      0f599731
    • Matt Mastracci's avatar
      [turbopack] const-ify most of the registration code (#90868) · 95e92c73
      Matt Mastracci authored
      # What
      
      Make a significant chunk of the remaining turbotask registration code
      (Values, Traits and Value/Trait impls) `const`. The vtable lookup for
      trait methods is constructed at compile time, allowing us to look up a
      trait's implementation in near-constant time.
      
      Introduces a new, common RegistryType we use for Values, Traits and
      Functions to reduce duplication. We still have a Lazy guard on each
      registry, but that will probably be removed if we migrate to distributed
      slices.
      
      NOTE: This removes a number of Lazy guards, but not all of them to avoid
      making the PR too large. The next pass of PR will remove the remaining
      Lazy guards, where possible.
      
      # Why
      
      By making this code `const`, we reduce the overall init time of the
      executable, make LTO a little more powerful (when we end up using that),
      reduce startup allocations, and reduce the amount of time we spend
      checking Lazy atomics.
      
      In hyperfine tests of the benchmark-apps folder, we see a 1% to 3%
      speedup for compilation.
      95e92c73
    • Matt Mastracci's avatar
      Enable thin LTO for release builds (#91343) · 2b4bde2e
      Matt Mastracci authored
      # What
      
      Add `lto = "thin"` to the workspace-level `[profile.release]` in
      `Cargo.toml`.
      
      # Why
      
      Thin LTO enables cross-crate optimization at link time, improving
      runtime
      performance of the final artifacts (next-napi-bindings native module,
      turbopack-cli binary, and benchmarks) without the full build time cost
      of
      fat LTO.
      
      # How
      
      Added `lto = "thin"` to the workspace root `[profile.release]` section.
      This applies to all release-profile link targets in the workspace,
      including
      binaries, cdylibs, and benchmarks. The `release-with-assertions` and
      `release-with-debug` profiles inherit from `release`, so they also
      benefit.
      2b4bde2e
    • Tobias Koppers's avatar
      Turbopack: use keyed cell access for AsyncModulesInfo (#91305) · 4cd8a989
      Tobias Koppers authored
      ### What?
      
      Switch `AsyncModulesInfo` to use `cell = "keyed"` and per-key access
      (`is_async()`) instead of reading the full `FxHashSet` via `.await?`.
      
      ### Why?
      
      `AsyncModulesInfo` is a large set that gets read from many call sites.
      With the default cell, any change to any module's async status
      invalidates all readers. The `cell = "keyed"` annotation enables
      turbo-tasks to track reads at the key level, so a change to one module's
      async status only invalidates tasks that queried that specific module.
      
      This reduces unnecessary recomputation during incremental rebuilds where
      only a small subset of modules change their async status.
      
      ### How?
      
      **Core change** (`async_module_info.rs`):
      - Added `cell = "keyed"` to the `#[turbo_tasks::value]` annotation on
      `AsyncModulesInfo`
      - Added `is_async()` method that uses `contains_key()` for keyed reads
      instead of full-set reads
      
      **Call site migration** (5 files):
      - All call sites changed from `.async_module_info().await?` (reads full
      set) → `.async_module_info()` (returns `Vc`, defers reads)
      - `attach_async_info_to_chunkable_module` and
      `from_chunkable_module_or_batch` now take `Vc<AsyncModulesInfo>` instead
      of `&ReadRef<AsyncModulesInfo>`
      - Each call site uses `async_module_info.is_async(module).await?` for
      per-key reads
      
      **`referenced_async_modules`** (`mod.rs`):
      - Collects neighbor candidates first, then filters via `is_async()` with
      `try_flat_join` for concurrent keyed reads
      - Simplified: uses in-place `.reverse()` instead of `.rev().collect()`
      double allocation
      
      **`compute_merged_modules`** (`merged_modules.rs`):
      - Pre-fetches async status for all mergeable modules into a local
      `FxHashSet` before the synchronous fixed-point traversal (which cannot
      do async reads)
      - Added tracing span `"pre-fetch async module status"` for observability
      
      **Cleanup:**
      - Consistent variable naming (`async_module_info`) across all call sites
      - Doc comment on `attach_async_info_to_chunkable_module` explaining the
      keyed access pattern
      
      ---------
      Co-authored-by: 's avatarTobias Koppers <sokra@users.noreply.github.com>
      Co-authored-by: 's avatarClaude <noreply@anthropic.com>
      4cd8a989
    • Andrew Clark's avatar
      Simplify scroll restoration with shared ScrollRef on CacheNode (#91348) · 83e47acd
      Andrew Clark authored
      Replaces the segment-path-matching scroll system with a simpler model
      based on a shared mutable ScrollRef on CacheNode.
      
      The old system accumulated segment paths during navigation and matched
      them in layout-router to decide which segments should scroll. This was
      necessary when CacheNodes were created lazily during render. Now that we
      construct the entire CacheNode tree immediately upon navigation, we can
      assign a shared ScrollRef directly to each new leaf node. When any
      segment scrolls, it flips the ref to false, preventing other segments
      from also scrolling. This removes all the segment path accumulation and
      matching logic.
      
      Fixes a regression where calling `refresh()` from a server action
      scrolled the page to the top. The old system had a semantic gap between
      `null` (no segments) and `[]` (scroll everything) — a server action
      refresh with no new segments fell through to a path that scrolled
      unconditionally. The new model avoids this: refresh creates no new
      CacheNodes, so no ScrollRef is assigned, and nothing scrolls.
      
      Repro: https://github.com/stipsan/nextjs-refresh-regression-repro
      
      There is extensive existing test coverage for scroll restoration
      behavior. This adds one additional test for the server action refresh
      bug.
      83e47acd
    • Niklas Mischkulnig's avatar
      Turbopack: `require(/* turbopackChunkingType: parallel */` (#91278) · 855f0a3f
      Niklas Mischkulnig authored
      1. Add the CJS version of `import ... with {"turbopack-chunking-type: "parallel"`
      2. Allow `shared` as a chunking type
      3. Improve error message for invalid values:
      
      <img width="718" height="455" alt="Bildschirmfoto 2026-03-13 um 15 07 06" src="https://github.com/user-attachments/assets/bc1efb43-4cc1-4885-b253-49c1e58b3add" />
      855f0a3f
    • Niklas Mischkulnig's avatar
      Turboopack: put import attributes behind a pointer, 23% faster analyze (#91347) · baad064f
      Niklas Mischkulnig authored
      The JS analyze microbenchmark got 23% faster:
      
      Only a tiny fraction of imports have annotations, be it `import ... with {...}` or `require(/*webpackIgnore: true*/...)`, so a `Option<Pointer<Struct>>` mkes sense here.
      ```
      canary:
      references/jsonwebtoken.js/full
                              time:   [63.250 ms 63.918 ms 64.752 ms]
                              change: [-5.2380% -3.0074% -0.8753%] (p = 0.01 < 0.05)
                              Change within noise threshold.
      Found 12 outliers among 100 measurements (12.00%)
        5 (5.00%) high mild
        7 (7.00%) high severe
      
      
      now:
      references/jsonwebtoken.js/full
                              time:   [49.070 ms 49.166 ms 49.273 ms]
                              change: [-24.097% -23.079% -22.237%] (p = 0.00 < 0.05)
                              Performance has improved.
      Found 6 outliers among 100 measurements (6.00%)
        3 (3.00%) high mild
        3 (3.00%) high severe
      ````
      
      This came up in https://github.com/vercel/next.js/pull/91278#issuecomment-4058275943, which added another (tiny) field to ImportAttributes. But it caused a 6% regression in the microbenchmark anyway.
      baad064f
    • Zack Tanner's avatar
      disable sub shell generation test outside of adapter (#91353) · cd49df2d
      Zack Tanner authored
      These tests have started failing in deploy mode in environments outside
      of the new Vercel adapter. Shell related behavior is changing as part of
      the new `partialFallbacks` flag and will not be backported to the old
      CLI, so this gates the test to ensure it runs in the right deployment
      environment.
      cd49df2d
    • Jude Gao's avatar
      Add eval and docs for unstable_instant (#91334) · 0e3b35ec
      Jude Gao authored
      0e3b35ec
    • nextjs-bot's avatar
      v16.2.0-canary.98 · 792522d2
      nextjs-bot authored
      792522d2
    • Zack Tanner's avatar
      partial fallbacks: complete generic shells into more specific shells (#91231) · ae3f9f51
      Zack Tanner authored
      In #91158, I wired up the plumbing to indicate whether a partial
      fallback shell is upgradeable. The previous heuristic was too coarse.
      This wires up the handling in `next start`.
      
      This PR teaches the runtime to complete a fallback shell only as far as
      prerendering allows. Instead of promoting a generic shell like
      `/[one]/[two]` directly to `/c/foo`, it promotes it to the most specific
      prerendered shell for that branch, `/c/[two]`, where `[one]` has
      `generateStaticParams`. That means later requests can reuse the more
      complete shell, while fully dynamic params continue to stream as dynamic
      content.
      
      With this change:
      
      - the first request still serves the generic fallback shell immediately
      - the background revalidate writes a more specific shell, not a fully
      concrete route
      - later requests for the same prerendered branch reuse that shell
      - upgrading stops once only fully dynamic params remain
      
      This keeps the runtime behavior aligned with the build-time
      `remainingPrerenderableParams` contract from the downstack PR.
      ae3f9f51
    • Kahfi Elhady's avatar
      docs: remove incorrect _document.tsx font example (#91346) · 914df17a
      Kahfi Elhady authored
      saw the issue about the _document.tsx example not working. next/font
      cant be used in _document.tsx, it throws an error. removed that section
      from the docs since _app.tsx already has the correct example.
      
      fixes #88832
      Co-authored-by: 's avatarKahfi Elhady <kahfie@gmail.com>
      Co-authored-by: 's avatarJoseph <joseph.chamochumbi@vercel.com>
      914df17a
    • Zack Tanner's avatar
      partial fallbacks: only upgrade shells with remaining prerenderable params (#91158) · cf4d3ae8
      Zack Tanner authored
      Partial fallback upgrading is currently too broad. Any PPR fallback shell can be treated as upgradeable, including routes with no `generateStaticParams` and shells that are already as specific as prerendering can make them.
      
      In practice, that means we preserve `allowQuery` and enable background promotion for shells that should remain as partial fallbacks. That broadens the feature beyond the medium-cardinality case it was meant for and makes the build output imply per-param upgradeability when there are no prerenderable params left to fill.
      
      This PR teaches static-path generation to compute `remainingPrerenderableParams` for each fallback shell: the unresolved pathname params that can still be filled by `generateStaticParams` in that branch. We then use that signal to gate partial fallback behavior.
      
      With this change:
      
      - `partialFallback` is only emitted for shells that still have prerenderable params remaining
      - `allowQuery` with params is only preserved for those shells
      
      Effectively, this limits partial fallback upgrading to shells that can still be made more specific by prerendering.
      cf4d3ae8
    • Benjamin Woodruff's avatar
      Turbopack: Remove old macos-compress script (#90967) · 68dade46
      Benjamin Woodruff authored
      @wbinnssmith added these scripts a long time ago at my suggestion/urging, but I think they ended up bad for a couple reasons that were hard to foresee at the time:
      
      - afsctool operates in-place and doesn't atomically write the compressed file, so if the process gets interrupted, your `target` directory is corrupted. https://github.com/Dr-Emann/applesauce is better for this reason.
      - This doesn't acquire the cargo lock, and modifying files while cargo is running is a good way to get corruption of the `target` directory.
      
      https://github.com/bgw/cargo-apfs-compress is my latest attempt at solving this, though I don't have a `LaunchAgents` config for it.  
        
      Regarding `node_modules`: pnpm creates reflinks from a shared global store on apfs. Trying to compress these reflinked files is just going to hurt you because it'll break the data deduplication that would've otherwise happened.
      68dade46
  2. 13 Mar, 2026 26 commits
    • nextjs-bot's avatar
      v16.2.0-canary.97 · 2769b555
      nextjs-bot authored
      2769b555
    • Will Binns-Smith's avatar
      [Turbopack] write route bundle stats to .next/diagnostics/route-bundle-stats.json (#90949) · 5394d39a
      Will Binns-Smith authored
      After a successful, Turbopack production build, this writes
      `.next/diagnostics/route-bundle-stats.json`
      containing First Load JS stats for every route. 
      
      ## Why?
      
      We used to have route bundle size statistics print after every build. It
      was not very high-signal and could be misleading, often using heuristics
      to give a best-effort estimate of what sizes may be at runtime. **These
      kinds of metrics for route bundle sizes can be misleading, as pages can
      be slow to visual/interactive completeness even if they have small first
      load bytes.**
      
      However, a minimal gauge of how much JavaScript a route ships during
      initial page load can be a useful signal so long as users have
      additional context and awareness of their app structure. Let's provide
      just this number for now for those that could benefit.
      
      Additionally, this does so in the form of writing a json document to the
      build directory, rather than writing a table to stdout, where users have
      needed to write extra tools to parse.
      
      ## Format
      
      An array of route entries sorted descending by
      `firstLoadUncompressedJsBytes`:
      
      ```json
      [
        {
          "route": "/blog/[slug]",
          "firstLoadUncompressedJsBytes": 124928,
          "firstLoadChunkPaths": [
            ".next/static/chunks/framework.js",
            ".next/static/chunks/main.js",
            ".next/static/chunks/pages/blog/[slug].js"
          ]
        }
      ]
      ```
      
      `firstLoadUncompressedJsBytes`: sum of uncompressed sizes of all JS
      chunks loaded on first navigation to the route (shared chunks included),
      for both Pages Router and App Router
      `firstLoadChunkPaths`: paths to those chunks relative to the project
      root
      
      ## Test Plan
      Added an integration test. Built with a create-next-app and verified the
      json document is written and the numbers align with what Chrome reports
      during initial load of a page.
      5394d39a
    • Vercel Release Bot's avatar
      Update Rspack development test manifest (#91300) · 3b9344d7
      Vercel Release Bot authored
      This auto-generated PR updates the development integration test manifest used when testing Rspack.
      3b9344d7
    • Vercel Release Bot's avatar
      Update Rspack production test manifest (#91301) · ad63ba04
      Vercel Release Bot authored
      This auto-generated PR updates the production integration test manifest used when testing Rspack.
      ad63ba04
    • Hendrik Liebau's avatar
      [test] Current behavior for request APIs in `generateStaticParams` (#91188) · 69e2b9df
      Hendrik Liebau authored
      Adds a dedicated test suite that asserts on the errors thrown when `cookies`, `headers`, `connection`, `draftMode`, and `next/root-params` are called inside `generateStaticParams`. Currently, these all fail because `generateStaticParams` runs without a work unit store.
      
      Each route is built individually using `--debug-build-paths` so we can capture and assert on the error for each API independently.
      69e2b9df
    • Niklas Mischkulnig's avatar
      Turbopack: don't emit polyfill chunk for API routes (#91331) · 202db657
      Niklas Mischkulnig authored
      1. This is misldeading in the bundle analyzer view
      2. If you have a Nextjs app consisting of only API routes, then there is
      no need to ever write out any polyfill chunk.
      202db657
    • Tobias Koppers's avatar
      Turbopack: switch chunk/asset hashes from hex to base40 encoding (#91137) · e22988e5
      Tobias Koppers authored
      ### What?
      
      Switch Turbopack's hash encoding for chunk and asset output filenames
      from hexadecimal (base16) to base40, using the alphabet \`0-9 a-z _ - ~
      .\`. Version hashes (used for HMR update comparison, not filenames) use
      base64 instead.
      
      ### Why?
      
      Base40 encodes the same number of bits in fewer characters than hex,
      producing shorter output filenames. All 40 characters are RFC 3986
      unreserved (URL-safe) and safe on case-insensitive filesystems (macOS
      HFS+/APFS, Windows NTFS).
      
      Hash truncation lengths are reduced proportionally to maintain
      equivalent collision resistance:
      
      | Context | Before (hex) | After (base40) | Entropy |
      |---|---|---|---|
      | Content hash in chunk filenames | 16 chars | 13 chars | ~69 bits |
      | Content hash in asset filenames | 8 chars | 13 chars | ~69 bits |
      | Ident disambiguator hash | 8 chars | 7 chars | ~37 bits |
      | Long-path prefix hash | 5 chars | 4 chars | ~21 bits |
      
      ### How?
      
      **New encoding module** (\`turbo-tasks-hash/src/base40.rs\`):
      - Defines the base40 alphabet and length constants (\`BASE40_LEN_64 =
      13\`, \`BASE40_LEN_128 = 25\`)
      - Implements a generic \`encode_base40_fixed<N>\` helper to avoid
      duplication
      - Public API: \`encode_base40(u64) -> String\` and
      \`encode_base40_128(u128) -> String\`
      
      **New base64 encoding** (\`turbo-tasks-hash/src/base64.rs\`):
      - \`encode_base64(u64) -> String\` — 11-char base64 (no padding) for
      version hashes
      - Version hashes don't appear in URLs or filenames, so base64 is safe
      and shorter
      
      **New \`HashAlgorithm\` variants** (\`turbo-tasks-hash/src/lib.rs\`):
      - \`Xxh3Hash64Base40\` and \`Xxh3Hash128Base40\` added alongside
      existing hex variants
      - Existing hex variants kept for internal manifests and identifiers
      
      **\`ContentHashing\` moved to \`turbopack-core\`**:
      - Moved from \`turbopack-browser\` to
      \`turbopack-core/src/chunk/mod.rs\` so both \`BrowserChunkingContext\`
      and \`NodeJsChunkingContext\` can use it
      
      **Separate chunk vs asset content hashing**:
      - \`BrowserChunkingContext\`: \`content_hashing\` renamed to
      \`chunk_content_hashing\` (optional), new \`asset_content_hashing:
      ContentHashing\` field (non-optional, defaults to 13 chars)
      - \`NodeJsChunkingContext\`: new \`asset_content_hashing:
      ContentHashing\` field (non-optional, defaults to 13 chars)
      - Builder methods: \`use_content_hashing()\` renamed to
      \`chunk_content_hashing()\`, new \`asset_content_hashing()\`
      
      **Version hashes switched to base64**:
      - \`turbopack-nodejs/src/ecmascript/node/version.rs\`
      - \`turbopack-dev-server/src/html.rs\`
      - \`turbopack-browser/src/ecmascript/version.rs\`,
      \`merged/version.rs\`, \`list/version.rs\`
      
      **Other callers updated** (15 files across turbopack and next-core):
      - All chunk/asset content hashing switched from \`Xxh3Hash128Hex\` →
      \`Xxh3Hash128Base40\`
      - \`ContentHashing::Direct { length }\` reduced from 16 → 13
      - Asset path truncations use full 13-char base40 hash (matching chunk
      filenames)
      
      **Exception — \`wasm_edge_var_name\`** (\`turbopack-wasm/src/lib.rs\`):
      - Kept as \`Xxh3Hash128Hex\` because the hash is used as part of a
      JavaScript variable name (\`wasm_{hash}\`), and base40 characters \`-\`,
      \`~\`, \`.\` are not valid JS identifier characters.
      
      **Scope — NOT changed:**
      - Webpack configuration (unchanged)
      - Internal manifests (\`routes_hashes_manifest\`,
      \`project_asset_hashes_manifest\`)
      - Internal identifiers (font naming, external module hashing, data URI
      sources, debug IDs)
      - SRI hashes (SHA-based Base64, different purpose)
      
      ---------
      Co-authored-by: 's avatarVercel <vercel[bot]@users.noreply.github.com>
      Co-authored-by: 's avatarClaude <noreply@anthropic.com>
      e22988e5
    • Delba de Oliveira's avatar
      Docs skills: guide and api-reference (#90992) · fb0686d8
      Delba de Oliveira authored
      Writing skills for guides and API reference for more consistent
      formatting.
      
      - `write-guide` - this skill helps create guides with progressive
      disclosure and a consistent format (intro, summary, step-by-step
      instructions, next steps). Works best when you give agents a demo.
      - `write-api-reference`  - this skill looks at the API type (component,
      function, file, etc) and helps draft references following a consistent
      format. Works best when you give agents context. e.g. source code, PR
      descriptions, RFCs. Also explores repo context (e.g. e2e tests)
      
      
      Note:
      
      - While skills help you write a first draft, they’re 80%. Humans still
      need to check for accuracy, test APIs, and take it to 110%.
      - If no technical writing guidance is provided, skills work best when
      you give it references of past work.
      
      Closes:
      
      - https://linear.app/vercel/issue/DOC-6245/create-guide-skill
      - https://linear.app/vercel/issue/DOC-6246/create-api-reference-skill
      
      ---------
      Co-authored-by: 's avatarvercel[bot] <35613825+vercel[bot]@users.noreply.github.com>
      fb0686d8
    • Sebastian "Sebbie" Silbermann's avatar
    • Luke Sandberg's avatar
      [turbopack] Remove `turbo_tasks::function` from ModuleReference getters (#91229) · 236a76dd
      Luke Sandberg authored
      ### What?
      
      Refactors the `ModuleReference` trait to make `chunking_type()` and `binding_usage()` methods return direct values instead of `Vc<T>` wrapped values, removing the need for async task functions.
      
      Also removes the `get_referenced_asset` task from `EsmAssetReference`, inlining its logic into the callers.
      
      ### Why?
      
      This change simplifies the API by eliminating unnecessary async overhead for methods that typically return simple, computed values. The previous implementation required `#[turbo_tasks::function]` annotations and `Vc<T>` wrappers even when the methods didn't need to perform async operations or benefit from caching.
      
      ### Impact
      
      | Metric | Base | Change | Delta |
      |--------|------|--------|-------|
      | Hits | 35,678,143 | 35,845,124 | **+166,981** |
      | Misses | 9,418,378 | 7,910,986 | **-1,507,392** |
      | Total | 45,096,521 | 43,756,110 | **-1,340,411** |
      | Task types | 1,306 | 1,277 | **-29** |
      
      29 task types were removed, eliminating **2.6M total task invocations** (1.1M hits + 1.5M misses):
      
      - **`chunking_type`** — 21 task types removed across all `ModuleReference` implementors (~952k invocations)
      - **`binding_usage`** — 6 task types removed (~527k invocations)
      - **`BindingUsage::all`** — helper task removed (~36k invocations)
      - **`EsmAssetReference::get_referenced_asset`** — removed and inlined (~1.08M invocations: 628k hits + 451k misses)
      
      The removed `get_referenced_asset` hits reappear as +628k hits on `EsmAssetReference::resolve_reference` and `ReferencedAsset::from_resolve_result` (with zero increase in misses), confirming the work is now served from cache through the existing callers.
      
      No tasks had increased misses — the removal is clean with no cache invalidation spillover.
      
      I also ran some builds to measure latency
      
      ```
      # This branch
      $ hyperfine -p 'rm -rf .next' -w 2 -r 10  'pnpm next build --turbopack --experimental-build-mode=compile'
      Benchmark 1: pnpm next build --turbopack --experimental-build-mode=compile
        Time (mean ± σ):     52.752 s ±  0.658 s    [User: 376.575 s, System: 106.375 s]
        Range (min … max):   51.913 s … 54.161 s    10 runs
      
      # on canary
      $ hyperfine -p 'rm -rf .next' -w 2 -r 10  'pnpm next build --turbopack --experimental-build-mode=compile'
      Benchmark 1: pnpm next build --turbopack --experimental-build-mode=compile
        Time (mean ± σ):     54.675 s ±  1.394 s    [User: 389.273 s, System: 114.642 s]
        Range (min … max):   53.434 s … 58.189 s    10 runs
      ```
      
      so a solid win of almost 2 seconds
      
      MaxRSS also went from 16,474,324,992 bytes to 16,359,309,312 bytes (from one measurement) so a savings of ~100M of max heap size.
      
      
      ### How?
      
      - Changed `chunking_type()` method signature from `Vc<ChunkingTypeOption>` to `Option<ChunkingType>`
      - Changed `binding_usage()` method signature from `Vc<BindingUsage>` to `BindingUsage`
      - Removed `ChunkingTypeOption` type alias as it's no longer needed
      - Updated all implementations across the codebase to return direct values instead of wrapped ones
      - Removed `#[turbo_tasks::function]` annotations from these methods
      - Updated call sites to use `into_trait_ref().await?` pattern when accessing these methods from `Vc<dyn ModuleReference>`
      - Removed `EsmAssetReference::get_referenced_asset`, inlining its logic into callers
      - Added validation for `turbopack-chunking-type` annotation values in import analysis
      - Fixed cache effectiveness analysis script
      236a76dd
    • Tobias Koppers's avatar
      Use keyed cells for used_exports and export_circuit_breakers in BindingUsageInfo (#91306) · 00067f40
      Tobias Koppers authored
      ## What?
      
      Apply the `cell = "keyed"` pattern to `used_exports` (`FxHashMap`) and
      `export_circuit_breakers` (`FxHashSet`) in `BindingUsageInfo`, matching
      the existing pattern already used for `unused_references`.
      
      ## Why?
      
      Previously, `used_exports` and `export_circuit_breakers` were stored as
      plain inline collections within `BindingUsageInfo`. Any change to any
      module's export usage would invalidate **all** callers of
      `used_exports()`, even those querying unrelated modules. This causes
      unnecessary recomputation during incremental rebuilds.
      
      With keyed cells, lookups like `self.used_exports.get(&module)` and
      `self.export_circuit_breakers.contains_key(&module)` only invalidate
      callers that queried the specific module whose export usage changed,
      providing per-module invalidation granularity.
      
      ## How?
      
      1. **New keyed transparent value types** — `UsedExportsMap` and
      `ExportCircuitBreakers` wrappers with `#[turbo_tasks::value(transparent,
      cell = "keyed")]`.
      
      2. **Fields changed to `ResolvedVc`** — `used_exports` and
      `export_circuit_breakers` fields are now `ResolvedVc<UsedExportsMap>`
      and `ResolvedVc<ExportCircuitBreakers>` instead of inline
      `FxHashMap`/`FxHashSet`.
      
      3. **`used_exports()` becomes a `#[turbo_tasks::function]`** — Moved
      into a `#[turbo_tasks::value_impl]` block so it's a tracked task
      function. Callers (`BrowserChunkingContext`, `NodeJsChunkingContext`) no
      longer need `.await?` — they call it directly and get a
      `Vc<ModuleExportUsage>`.
      
      4. **Per-key lookups** — `contains_key(&module).await?` and
      `get(&module).await?` leverage the keyed cell pattern for fine-grained
      invalidation.
      
      ### Files changed
      
      -
      `turbopack/crates/turbopack-core/src/module_graph/binding_usage_info.rs`
      — Core changes: new keyed types, field type changes, `used_exports()` as
      tracked function
      - `turbopack/crates/turbopack-browser/src/chunking_context.rs` —
      Simplified call site (no `.await?`)
      - `turbopack/crates/turbopack-nodejs/src/chunking_context.rs` —
      Simplified call site (no `.await?`)
      
      ---------
      Co-authored-by: 's avatarTobias Koppers <sokra@users.noreply.github.com>
      Co-authored-by: 's avatarClaude <noreply@anthropic.com>
      00067f40
    • JJ Kasper's avatar
      Expose edge runtime fields in build-complete (#91239) · 07189c52
      JJ Kasper authored
      ### What?
      
      - Add canonical edge entrypoint metadata to edge function definitions in
      the middleware manifest.
      - Surface that canonical entrypoint through `build-complete` as
      `edgeRuntime` metadata in adapter outputs.
      - Update middleware and adapter tests to assert the new metadata instead
      of relying on bundler-specific emitted file names.
      
      ### Why?
      
      Adapter consumers need a stable way to load and invoke edge outputs
      without depending on `next-server`'s sandbox handling or guessing which
      emitted file is the executable entrypoint. The existing checks were also
      brittle across webpack and Turbopack because the emitted file lists can
      differ.
      
      ### How?
      
      - Add an optional `entrypoint` field to `EdgeFunctionDefinition` and
      populate it in both the webpack middleware manifest generator and the
      Turbopack manifest emitters for app, pages, and middleware edge
      functions.
      - In `packages/next/src/build/adapter/build-complete.ts`, use that
      canonical entrypoint for `filePath` and expose `edgeRuntime.modulePath`,
      `edgeRuntime.entryKey`, and `edgeRuntime.handlerExport` for edge
      outputs.
      - Adjust the middleware manifest tests to validate cross-bundler
      invariants and add adapter-config coverage for the new `edgeRuntime`
      fields.
      07189c52
    • Zack Tanner's avatar
      re-enable RDC deployment tests (#91327) · afe3993e
      Zack Tanner authored
      Flag has been re-enabled and is attached to the test team.
      afe3993e
    • nextjs-bot's avatar
      v16.2.0-canary.96 · 80385f53
      nextjs-bot authored
      80385f53
    • Benjamin Woodruff's avatar
      Turbopack: Remove the IntoTraitRef trait, make it an inherent method on Vc (#91223) · d7de6f10
      Benjamin Woodruff authored
      This is basically one-shot from Opus 4.6, with a minor tweak to the doc comment by hand.
      
      Discussed this with @lukesandberg, and we realized that there's only one implementation of this trait, so it doesn't make a ton of sense as a trait.
      d7de6f10
    • Sebastian "Sebbie" Silbermann's avatar
    • JJ Kasper's avatar
      Wire cache handlers in edge paths and add e2e regression coverage (#91236) · a6b36200
      JJ Kasper authored
      ### What?
      
      This PR wires custom `cacheHandler` / `cacheHandlers` through the
      remaining edge entrypoints so edge app pages, edge app routes, edge
      pages SSR, middleware, and edge API routes can all see the configured
      handlers.
      
      It also adds an e2e regression suite covering:
      - pages-router ISR revalidation with a custom incremental cache handler
      - app-router cache handlers with cache components enabled
      - edge app page + edge app route wiring when cache components are
      disabled
      
      ### Why?
      
      We already support custom cache handlers in non-edge paths, but several
      edge code paths were not forwarding that configuration into the
      generated entrypoints/runtime wrappers. That meant custom cache handlers
      could be skipped in edge rendering and edge route execution, and we did
      not have regression coverage around those cases.
      
      ### How?
      
      - pass `cacheHandler` / `cacheHandlers` through the JS build entry
      plumbing for edge server entries
      - inject cache handler imports/registration into the webpack edge
      templates and loaders
      - mirror the same wiring in the Turbopack/Rust entry generation for edge
      app pages, app routes, pages SSR, and middleware
      - update the edge route wrapper to initialize and register cache
      handlers before invoking the route module
      - extend `next-taskless` template expansion with raw injection support
      so the generated edge templates can add imports and registration code
      - add `test/e2e/cache-handlers-upstream-wiring` fixtures to cover
      pages/app, edge/non-edge, and revalidation behavior
      a6b36200
    • Tobias Koppers's avatar
      Delete blob files during compaction when entries are superseded (#91314) · 11266613
      Tobias Koppers authored
      ### What?
      
      During compaction in `turbo-persistence`, when entries are dropped
      (superseded by newer values or pruned by tombstones), blob files
      referenced by those entries are now marked for deletion.
      
      ### Why?
      
      Previously, compaction would merge SST files and correctly drop stale
      entries, but blob files referenced by those dropped entries were leaked
      on disk (marked with a TODO at the time). Over time this would cause
      unbounded disk usage growth for databases that overwrite or delete
      blob-sized values.
      
      ### How?
      
      When the compaction merge loop skips an entry (because
      `skip_remaining_for_this_key` is `true`), it now checks if the dropped
      entry is a `LookupValue::Blob` and, if so, pushes its sequence number to
      `blob_seq_numbers_to_delete`. The existing `commit()` infrastructure
      already handles the rest — writing `.del` files and removing the actual
      `.blob` files after the CURRENT pointer is updated.
      
      The change is minimal (4 lines of logic in `db.rs`):
      - Made `blob_seq_numbers_to_delete` mutable
      - Added an `else` branch to collect blob sequence numbers from dropped
      entries
      
      This covers both cases:
      - **SingleValue**: After the first (newest) entry for a key is written,
      all older entries are skipped. Blob references in those older entries
      are marked for deletion.
      - **MultiValue**: After a tombstone is encountered, all older entries
      for that key are skipped. Blob references in those older entries are
      marked for deletion.
      
      ### Tests
      
      Added 4 new tests:
      - `compaction_deletes_superseded_blob` — blob overwritten by smaller
      value → blob deleted after compaction
      - `compaction_deletes_blob_on_tombstone` — blob deleted via tombstone →
      blob deleted after compaction
      - `compaction_deletes_blob_multi_value_tombstone` — MultiValue:
      tombstone prunes blob → blob deleted
      - `compaction_preserves_active_blob` — blob still referenced → blob
      preserved after compaction
      
      All existing compaction tests (23) and full turbo-persistence test suite
      (60) continue to pass.
      Co-authored-by: 's avatarTobias Koppers <sokra@users.noreply.github.com>
      Co-authored-by: 's avatarClaude <noreply@anthropic.com>
      11266613
    • JJ Kasper's avatar
      Expose resolved invocation targets in next-routing (#91242) · d5e88639
      JJ Kasper authored
      ### What?
      
      This PR extends `@next/routing` so `resolveRoutes()` returns the
      concrete route resolution data callers need after rewrites and dynamic
      matches:
      
      - rename `matchedPathname` to `resolvedPathname`
      - add `resolvedQuery`
      - add `invocationTarget` for the concrete pathname/query that should be
      invoked
      - export the new query/invocation target types from the package
      entrypoint
      
      It also removes the leftover `query` alias so the result shape
      consistently uses `resolvedQuery`.
      
      ### Why?
      
      `matchedPathname` only described part of the result, and it was
      ambiguous for dynamic routes because the resolved route template and the
      concrete invocation target are not always the same thing.
      
      For example, a dynamic route can resolve to `/blog/[slug]` while the
      actual invocation target is `/blog/post-1`, and rewrites can merge query
      params that callers need to preserve. Exposing these values directly
      makes the package easier to consume from adapters without each caller
      reconstructing them manually.
      
      ### How?
      
      - thread resolved query construction through the route resolution paths
      - build `invocationTarget` alongside `resolvedPathname` wherever
      rewrites, static matches, and dynamic matches resolve successfully
      - preserve merged rewrite query params in `resolvedQuery`
      - update the public types, README example, and existing tests to use
      `resolvedPathname`
      - add coverage for resolved query + invocation target behavior on
      rewrite and dynamic route matches
      
      Verified with:
      - `pnpm --filter @next/routing test -- --runInBand`
      - `pnpm --filter @next/routing build`
      d5e88639
    • Sebastian "Sebbie" Silbermann's avatar
    • Andrew Clark's avatar
      [Prefetch Inlining] Generate size-based hints on server (#90891) · 0e6ab3f5
      Andrew Clark authored
      Part 1 of 2. This commit adds the server-side infrastructure for
      size-based segment bundling but does not change any observable behavior.
      The client-side changes that actually consume bundled responses are in
      the next commit.
      
      At build time, a measurement pass renders each segment's prefetch
      response, measures its gzip size, and decides which segments should be
      bundled together vs fetched separately. The decisions are persisted to a
      manifest and embedded into the route tree prefetch response so the
      client can act on them.
      
      The decisions are computed once at build and remain fixed for the
      lifetime of the deployment. They are not recomputed during
      ISR/revalidation — if they could change, the client would need to
      re-fetch the route tree after every revalidation, defeating the purpose
      of caching it independently.
      
      Refer to the next commit for a full description of the design and
      motivation.
      
      ## Config
      
      experimental.prefetchInlining accepts either a boolean or an object with
      threshold overrides (maxSize, maxBundleSize). When true, the default
      thresholds are used (2KB per-segment, 10KB total budget). The auto
      behavior will eventually become the default. The config will remain
      available for overriding thresholds.
      0e6ab3f5
    • Hendrik Liebau's avatar
      Respect `generateStaticParams` in instant navigation shell (#91316) · 834c41ef
      Hendrik Liebau authored
      When the instant navigation testing cookie is set, the debug static
      shell path previously called `getFallbackRouteParams()` which treats all
      dynamic segments as fallback params regardless of
      `generateStaticParams`. This caused two issues:
      
      - Root params (via `next/root-params`) errored with a
      `NEXT_STATIC_GEN_BAILOUT` 500 response because the root layout's param
      access returned a hanging promise, which was treated as uncached data
      accessed outside of `<Suspense>`.
      - Params defined in `generateStaticParams` were incorrectly excluded
      from the instant shell, shown behind Suspense fallbacks instead of
      resolving.
      
      The fix uses `prerenderInfo?.fallbackRouteParams` from the prerender
      manifest instead, which correctly distinguishes between statically known
      params (defined in `generateStaticParams`) and unknown params. For
      prerendered URLs, the outer guard (`!isPrerendered`) prevents the
      fallback path from being entered, so no fallback params are set and all
      params resolve normally.
      
      To make this work in dev mode, the dev server now populates
      `fallbackRouteParams` in the prerender manifest's dynamic route entries,
      which were previously left as `undefined`.
      
      Additionally, the `fallbackParams` request metadata is now overridden
      when rendering a debug static shell. Without this override, the staged
      rendering would use the smallest set of fallback params across all
      prerendered routes (set by `base-server.ts` for dev validation), which
      may omit fallback params for the current URL when a different value for
      the same param is defined in `generateStaticParams`. The override
      ensures the route-specific fallback params are used instead.
      834c41ef
    • Niklas Mischkulnig's avatar
    • Hendrik Liebau's avatar
      Skip dimming when `--inspect` is used (#91271) · 25447831
      Hendrik Liebau authored
      When the Node.js inspector is active (e.g. via `next dev --inspect`),
      dimming wraps console arguments in a format string which defeats
      inspector affordances such as collapsible objects and
      clickable/linkified stack traces.
      
      This adds an early return in `convertToDimmedArgs` that skips dimming
      entirely when `inspector.url()` is defined. Terminal output without
      `--inspect` is unchanged.
      
      Ideally we would only skip dimming when a debugger frontend is actually
      attached, but Node.js does not expose a synchronous API for that —
      detecting it would require async polling of the `/json/list` HTTP
      endpoint.
      
      Test plan:
      - Unit tests in `console-dim.external.test.ts`
      - Manual: dimming almost never triggers now since we switched to in-band
      validation (no separate render pass). To reproduce manually, use a
      client component that calls `console.error(new Error(...))` during SSR,
      e.g.:
      1. `__NEXT_CACHE_COMPONENTS=true pnpm next dev
      test/e2e/app-dir/server-source-maps/fixtures/default --inspect`
        2. Open `http://localhost:3000/` in Chrome
        3. Click the Node.js DevTools button
        4. Load `http://localhost:3000/ssr-error-log`
      5. Verify the first error in DevTools has source-mapped, expandable
      stack frames
      
      Before:
      
      <img width="1496" height="848" alt="before"
      src="https://github.com/user-attachments/assets/8b4358e1-06ec-4078-b6cc-269986e295e7"
      />
      
      After:
      
      <img width="1496" height="842" alt="after"
      src="https://github.com/user-attachments/assets/42f33c6f-f025-410f-b44c-2ccd88fe0cfe"
      />
      25447831
    • Webdesign29's avatar
      perf: use Buffer.from for base64 encoding of binary Flight data (#91221) · 5903c030
      Webdesign29 authored
      ## Summary
      
      Replace `btoa(String.fromCodePoint(...chunk))` with
      `Buffer.from().toString('base64')` for encoding binary Flight data
      chunks in `writeFlightDataInstruction`.
      
      The spread operator `...chunk` converts the entire Uint8Array into
      individual arguments on the call stack. For a 64KB binary chunk, this
      creates 65,536 arguments — causing:
      - Significant call stack pressure (V8's argument limit is ~65K)
      - Temporary JS string allocation from `String.fromCodePoint`
      - The entire chunk must be converted to a JS string before base64
      encoding
      
      `Buffer.from().toString('base64')` performs base64 encoding natively in
      C++ without any intermediate string allocation or argument spreading.
      
      **Edge runtime compatibility**: Falls back to the original `btoa` path
      where `Buffer` is unavailable.
      
      ## Test plan
      
      - [x] TypeScript compilation passes
      - [x] Prettier and ESLint pass (pre-commit hooks)
      - [x] Produces identical base64 output
      - [x] Edge runtime falls back to original path (no `Buffer` available)
      - [x] Node.js runtime uses `Buffer.from` for native encoding
      
      
      🤖 Generated with [Claude Code](https://claude.com/claude-code)
      5903c030
    • Delba de Oliveira's avatar